@kaeawc/auto-mobile 0.0.93 → 0.0.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/dist/build-info.json +12 -12
  2. package/dist/src/ble-peripheral.py +153 -0
  3. package/dist/src/{chunk-r6z1eztj.js → chunk-026y62r9.js} +11 -11
  4. package/dist/src/chunk-0jyfg947.js +4 -0
  5. package/dist/src/{chunk-8g1922rp.js → chunk-0zfpp1wh.js} +4 -4
  6. package/dist/src/{chunk-qf6nynk6.js → chunk-13qxf7ym.js} +5 -5
  7. package/dist/src/chunk-1scenrk7.js +4 -0
  8. package/dist/src/chunk-1vb5ph1k.js +4 -0
  9. package/dist/src/{chunk-710rxz9y.js → chunk-20g565q7.js} +3 -3
  10. package/dist/src/chunk-21h6dhdm.js +5 -0
  11. package/dist/src/chunk-25mfpthk.js +78 -0
  12. package/dist/src/{chunk-rbpdk7m0.js → chunk-2b39zyxc.js} +3 -3
  13. package/dist/src/chunk-2gzd6wbd.js +4 -0
  14. package/dist/src/{chunk-xgan0qqp.js → chunk-3dntffy9.js} +1 -1
  15. package/dist/src/chunk-3gfczcsn.js +4 -0
  16. package/dist/src/{chunk-dgrbdpb7.js → chunk-3h5jz1vb.js} +6 -6
  17. package/dist/src/{chunk-t6c8akcm.js → chunk-41zcy6b3.js} +3 -3
  18. package/dist/src/chunk-47n9m2de.js +4 -0
  19. package/dist/src/chunk-4vxeq0vd.js +58 -0
  20. package/dist/src/chunk-59dx6qaf.js +4 -0
  21. package/dist/src/chunk-5sdf9y92.js +4 -0
  22. package/dist/src/{chunk-58wzr3mt.js → chunk-5wk1t46v.js} +3 -3
  23. package/dist/src/{chunk-vy3bwm1d.js → chunk-661c50hh.js} +5 -5
  24. package/dist/src/chunk-68n6bjjd.js +21 -0
  25. package/dist/src/{chunk-v6pya0dm.js → chunk-69pmjdf2.js} +3 -3
  26. package/dist/src/{chunk-e98dqnc9.js → chunk-6hrj3jt6.js} +20 -20
  27. package/dist/src/{chunk-wbh8spm5.js → chunk-6myr26wx.js} +8 -8
  28. package/dist/src/chunk-6n96k09n.js +4 -0
  29. package/dist/src/chunk-6vwrbkre.js +4 -0
  30. package/dist/src/chunk-6wk0yrab.js +4 -0
  31. package/dist/src/chunk-6yhm9een.js +4 -0
  32. package/dist/src/{chunk-mjrps0ac.js → chunk-7k7gjg2t.js} +5 -5
  33. package/dist/src/chunk-7n5fz68h.js +4 -0
  34. package/dist/src/chunk-8cvnpnbp.js +4 -0
  35. package/dist/src/chunk-8kzv7rk7.js +4 -0
  36. package/dist/src/chunk-8nj68t1v.js +167 -0
  37. package/dist/src/{chunk-g7tmjbkt.js → chunk-96r3bpg7.js} +3 -3
  38. package/dist/src/chunk-97x887te.js +4 -0
  39. package/dist/src/{chunk-8ph29g99.js → chunk-99a6tbvd.js} +1 -1
  40. package/dist/src/chunk-9p5d2994.js +5 -0
  41. package/dist/src/{chunk-aabchzxk.js → chunk-9q265er0.js} +4 -4
  42. package/dist/src/{chunk-jh6vhqzx.js → chunk-9xgnrv5w.js} +3 -3
  43. package/dist/src/chunk-9xgsmshb.js +5 -0
  44. package/dist/src/chunk-a02d1wgv.js +4 -0
  45. package/dist/src/{chunk-ndt1ccxm.js → chunk-a9ps00a1.js} +10 -10
  46. package/dist/src/{chunk-5d2hft6c.js → chunk-aewdveet.js} +3 -3
  47. package/dist/src/{chunk-ycaj2sgf.js → chunk-b3tdtq7r.js} +6 -6
  48. package/dist/src/chunk-bn7jx7a2.js +4 -0
  49. package/dist/src/{chunk-3y6eykz9.js → chunk-bnyw27ja.js} +2 -2
  50. package/dist/src/{chunk-rqc9ap3x.js → chunk-bpwsg76p.js} +2 -2
  51. package/dist/src/chunk-bvranw3g.js +4 -0
  52. package/dist/src/chunk-c25a84zb.js +4 -0
  53. package/dist/src/chunk-c27yv1dx.js +5 -0
  54. package/dist/src/chunk-c3ewxm4x.js +5 -0
  55. package/dist/src/{chunk-rvvy1bte.js → chunk-cb1ga9rd.js} +5 -5
  56. package/dist/src/chunk-cn7fwy7k.js +4 -0
  57. package/dist/src/chunk-cnvy4a64.js +4 -0
  58. package/dist/src/{chunk-7rz9898k.js → chunk-cqhw4yr6.js} +3 -3
  59. package/dist/src/{chunk-g04bwyj3.js → chunk-ctmfshjc.js} +2 -2
  60. package/dist/src/chunk-ctwmhz13.js +4 -0
  61. package/dist/src/{chunk-waqwcjyn.js → chunk-d3jx9bz5.js} +2 -2
  62. package/dist/src/{chunk-ayp07wbb.js → chunk-d6rb08ga.js} +1 -1
  63. package/dist/src/chunk-ddqhj4eg.js +5 -0
  64. package/dist/src/{chunk-r7bpkgff.js → chunk-ddrhs1c3.js} +2 -2
  65. package/dist/src/chunk-dnjnh9p6.js +4 -0
  66. package/dist/src/{chunk-wyrkw6hw.js → chunk-dw5rwgya.js} +3 -3
  67. package/dist/src/{chunk-3xkpk44w.js → chunk-e0870khr.js} +3 -3
  68. package/dist/src/chunk-ea3k10kj.js +4 -0
  69. package/dist/src/chunk-emv82m1w.js +7 -0
  70. package/dist/src/chunk-f3m6pdnx.js +4 -0
  71. package/dist/src/chunk-f84z32cb.js +4 -0
  72. package/dist/src/chunk-fpczgf0z.js +4 -0
  73. package/dist/src/{chunk-2tqzq5qh.js → chunk-g2js4c2v.js} +18 -18
  74. package/dist/src/chunk-g3af2qbk.js +5 -0
  75. package/dist/src/{chunk-3qwrzxh0.js → chunk-gadtna7s.js} +6 -6
  76. package/dist/src/{chunk-ybbtagbt.js → chunk-gcyx407v.js} +3 -3
  77. package/dist/src/{chunk-bfw6125s.js → chunk-gfpntwc1.js} +3 -3
  78. package/dist/src/chunk-gmnm5e3e.js +4 -0
  79. package/dist/src/chunk-gp6vb5gf.js +4 -0
  80. package/dist/src/chunk-gppgy7pa.js +4 -0
  81. package/dist/src/chunk-hegfz0ae.js +5 -0
  82. package/dist/src/chunk-hpzxdp1k.js +17 -0
  83. package/dist/src/{chunk-qcxzr2my.js → chunk-j69g8b50.js} +3 -3
  84. package/dist/src/chunk-jvstjnqm.js +19 -0
  85. package/dist/src/chunk-jzqrv78s.js +4 -0
  86. package/dist/src/chunk-k2948b8d.js +4 -0
  87. package/dist/src/chunk-k4ftd40d.js +4 -0
  88. package/dist/src/{chunk-bxmsax22.js → chunk-kd9vfaxh.js} +3 -3
  89. package/dist/src/{chunk-s3jc6cwp.js → chunk-kdczmgwk.js} +3 -3
  90. package/dist/src/{chunk-t6bfvfkg.js → chunk-ke3wn14v.js} +1 -1
  91. package/dist/src/chunk-kh5n7m6w.js +4 -0
  92. package/dist/src/{chunk-6wt9rgjf.js → chunk-khejfph4.js} +3 -3
  93. package/dist/src/chunk-kny2xemh.js +4 -0
  94. package/dist/src/chunk-knyzw9md.js +4 -0
  95. package/dist/src/chunk-mbzpt2hp.js +4 -0
  96. package/dist/src/chunk-mm8rcxad.js +4 -0
  97. package/dist/src/chunk-nc4516tx.js +4 -0
  98. package/dist/src/{chunk-6bznss4t.js → chunk-ntfrqrqn.js} +5 -5
  99. package/dist/src/chunk-nz5h2j52.js +4 -0
  100. package/dist/src/chunk-p22s97qy.js +4 -0
  101. package/dist/src/chunk-p9kt1sgr.js +6 -0
  102. package/dist/src/{chunk-yb97j25b.js → chunk-pf282r5g.js} +4 -4
  103. package/dist/src/chunk-pnd4mrxy.js +4 -0
  104. package/dist/src/chunk-pqqteyj6.js +4 -0
  105. package/dist/src/{chunk-6xmss8er.js → chunk-qj1tbnv2.js} +6 -6
  106. package/dist/src/chunk-qnh9egwr.js +4 -0
  107. package/dist/src/chunk-qy3khhf8.js +8 -0
  108. package/dist/src/{chunk-z637nqg8.js → chunk-r0vp315h.js} +6 -6
  109. package/dist/src/chunk-r4j43b9s.js +237 -0
  110. package/dist/src/{chunk-1p7xf5kb.js → chunk-r54cxxze.js} +3 -3
  111. package/dist/src/{chunk-yf7ympyz.js → chunk-r6pvhj33.js} +92 -92
  112. package/dist/src/chunk-rb7aa5gr.js +54 -0
  113. package/dist/src/chunk-rdj50kb4.js +4 -0
  114. package/dist/src/chunk-rnd4vcas.js +4 -0
  115. package/dist/src/{chunk-w5b2jwk3.js → chunk-s3y3zfcx.js} +8 -8
  116. package/dist/src/chunk-s4g43k75.js +5 -0
  117. package/dist/src/chunk-sfqe223f.js +311 -0
  118. package/dist/src/{chunk-284ptqa4.js → chunk-sqdrxjw5.js} +5 -5
  119. package/dist/src/{chunk-zgja5f3p.js → chunk-t54k47em.js} +4 -4
  120. package/dist/src/{chunk-3sy6ahhz.js → chunk-tek4pnvv.js} +10 -10
  121. package/dist/src/chunk-tn74y7af.js +4 -0
  122. package/dist/src/{chunk-thbh3jew.js → chunk-tvq0nzam.js} +3 -3
  123. package/dist/src/{chunk-0jrrsnc9.js → chunk-tx4f0h9c.js} +4 -4
  124. package/dist/src/chunk-vdqag3fj.js +5 -0
  125. package/dist/src/chunk-vz5zzs57.js +4 -0
  126. package/dist/src/chunk-w4s2vfpj.js +4 -0
  127. package/dist/src/{chunk-4hw3665t.js → chunk-w5yypt53.js} +11 -11
  128. package/dist/src/{chunk-8037tzzj.js → chunk-w68v64vh.js} +3 -3
  129. package/dist/src/chunk-whwj0pdk.js +5 -0
  130. package/dist/src/chunk-wnmqt1dc.js +4 -0
  131. package/dist/src/{chunk-cyy71ggq.js → chunk-wpe46vsa.js} +3 -3
  132. package/dist/src/{chunk-w3vs79ex.js → chunk-wxdjeb4k.js} +19 -19
  133. package/dist/src/chunk-xcqzwf9j.js +247 -0
  134. package/dist/src/chunk-xezekwwn.js +5 -0
  135. package/dist/src/chunk-xf19m15s.js +4 -0
  136. package/dist/src/chunk-xghbxha4.js +4 -0
  137. package/dist/src/{chunk-00167wan.js → chunk-xn9m3xc2.js} +5 -5
  138. package/dist/src/{chunk-26k317v5.js → chunk-yqfz4vts.js} +3 -3
  139. package/dist/src/chunk-z8tvs8nk.js +5 -0
  140. package/dist/src/chunk-zm2rehqb.js +5 -0
  141. package/dist/src/chunk-zs6dqm35.js +4 -0
  142. package/dist/src/daemon/processEntry.js +2 -2
  143. package/dist/src/index.js +4 -4
  144. package/dist/src/runtime/bunRuntimeGuard.js +2 -2
  145. package/dist/src/utils/workers/iosBundleExtractWorker.js +2 -2
  146. package/package.json +2 -2
  147. package/dist/src/chunk-0n6swkwg.js +0 -5
  148. package/dist/src/chunk-0qsy1qsx.js +0 -57
  149. package/dist/src/chunk-11m8wj8j.js +0 -237
  150. package/dist/src/chunk-23p5f095.js +0 -4
  151. package/dist/src/chunk-28re4xrg.js +0 -4
  152. package/dist/src/chunk-2f9rkmhx.js +0 -5
  153. package/dist/src/chunk-2fxdh48t.js +0 -4
  154. package/dist/src/chunk-2tbdrbt6.js +0 -4
  155. package/dist/src/chunk-32gvv9b4.js +0 -21
  156. package/dist/src/chunk-3f3t1x97.js +0 -8
  157. package/dist/src/chunk-3fspkbc7.js +0 -4
  158. package/dist/src/chunk-3vg455e6.js +0 -4
  159. package/dist/src/chunk-49bsqdx3.js +0 -4
  160. package/dist/src/chunk-5snsn9cf.js +0 -4
  161. package/dist/src/chunk-5tm9mn47.js +0 -54
  162. package/dist/src/chunk-5zc77a5t.js +0 -4
  163. package/dist/src/chunk-64j0majr.js +0 -19
  164. package/dist/src/chunk-65y8v4td.js +0 -17
  165. package/dist/src/chunk-6awz7vhq.js +0 -5
  166. package/dist/src/chunk-6ep7f5ge.js +0 -4
  167. package/dist/src/chunk-7cs2da62.js +0 -5
  168. package/dist/src/chunk-7g103b54.js +0 -4
  169. package/dist/src/chunk-7j5vj4pa.js +0 -4
  170. package/dist/src/chunk-7tw8x05v.js +0 -4
  171. package/dist/src/chunk-7zy586cb.js +0 -4
  172. package/dist/src/chunk-84nanf8s.js +0 -5
  173. package/dist/src/chunk-8gvwcv2p.js +0 -4
  174. package/dist/src/chunk-8thrmfat.js +0 -4
  175. package/dist/src/chunk-8zgzzs7k.js +0 -78
  176. package/dist/src/chunk-97b1zmaq.js +0 -4
  177. package/dist/src/chunk-9fth9ayh.js +0 -4
  178. package/dist/src/chunk-9j6anhjr.js +0 -4
  179. package/dist/src/chunk-bfjwqk8q.js +0 -4
  180. package/dist/src/chunk-bnhscm2n.js +0 -4
  181. package/dist/src/chunk-c1vs4g1n.js +0 -4
  182. package/dist/src/chunk-ct3e7yng.js +0 -4
  183. package/dist/src/chunk-ddzkz92z.js +0 -4
  184. package/dist/src/chunk-drdz8hee.js +0 -5
  185. package/dist/src/chunk-eersndy7.js +0 -5
  186. package/dist/src/chunk-eggq53ks.js +0 -4
  187. package/dist/src/chunk-f2dya7cs.js +0 -4
  188. package/dist/src/chunk-fbakd6cw.js +0 -4
  189. package/dist/src/chunk-fgb98zjj.js +0 -5
  190. package/dist/src/chunk-fmpad823.js +0 -5
  191. package/dist/src/chunk-g0xr8zw0.js +0 -4
  192. package/dist/src/chunk-g3rjs80x.js +0 -4
  193. package/dist/src/chunk-g78rtrfv.js +0 -4
  194. package/dist/src/chunk-gabgv3y5.js +0 -4
  195. package/dist/src/chunk-gmr45m8f.js +0 -4
  196. package/dist/src/chunk-gsyfebqj.js +0 -4
  197. package/dist/src/chunk-h5rpn9wr.js +0 -247
  198. package/dist/src/chunk-hb1x7v55.js +0 -4
  199. package/dist/src/chunk-hrfytkxh.js +0 -168
  200. package/dist/src/chunk-j4yjzbak.js +0 -4
  201. package/dist/src/chunk-jd6a5v6p.js +0 -5
  202. package/dist/src/chunk-kn5spq15.js +0 -4
  203. package/dist/src/chunk-m94qs0f0.js +0 -4
  204. package/dist/src/chunk-n03dmn5q.js +0 -5
  205. package/dist/src/chunk-n72qhwd9.js +0 -4
  206. package/dist/src/chunk-nr6y0n4y.js +0 -5
  207. package/dist/src/chunk-pcsen2vs.js +0 -4
  208. package/dist/src/chunk-ppfr0b8h.js +0 -4
  209. package/dist/src/chunk-q10bdnat.js +0 -4
  210. package/dist/src/chunk-q9xmq595.js +0 -4
  211. package/dist/src/chunk-qyqypn28.js +0 -5
  212. package/dist/src/chunk-r2epb56s.js +0 -4
  213. package/dist/src/chunk-r5bxavdx.js +0 -311
  214. package/dist/src/chunk-r8jf3d92.js +0 -4
  215. package/dist/src/chunk-rc0dbypm.js +0 -4
  216. package/dist/src/chunk-rhcty4ms.js +0 -4
  217. package/dist/src/chunk-rpvckv3p.js +0 -4
  218. package/dist/src/chunk-ry0mz41y.js +0 -4
  219. package/dist/src/chunk-sfv61xjb.js +0 -6
  220. package/dist/src/chunk-t7w8rctc.js +0 -4
  221. package/dist/src/chunk-v2wd4n3e.js +0 -5
  222. package/dist/src/chunk-w4zga19f.js +0 -4
  223. package/dist/src/chunk-w7hkv422.js +0 -5
  224. package/dist/src/chunk-xa73x2cx.js +0 -5
  225. package/dist/src/chunk-y2vs6jwg.js +0 -4
  226. package/dist/src/chunk-yattm52s.js +0 -4
  227. package/dist/src/chunk-yjawdzk8.js +0 -4
  228. package/dist/src/chunk-zs1sghs9.js +0 -4
@@ -0,0 +1,21 @@
1
+ // @bun
2
+ import{w,Hs,me,v,z,L,b,vt,je,Gi,Qe,Xr,CR,Ai,Ze,k,lo,Qo,Sb,UY,Ab,LR,KD,BR,wj,Rj,VY,WY,zY,jY,KY,kie,ba,jR,b2,PP,FO,S2,w2,LO,Doe,R2,H9,q9,Ooe,W9,z9,Moe,cU,E}from"./chunk-sfqe223f.js";import{n,a,m,Me,S,s,Ne,p,Yp,W,c,X,Ff,hU,Od,Gb,_P,xP,GO,Xp,gy,Yb,Jb,CP,Lf,Zp,Et,gse,EE,wse,A8,kK,XO,Ase,Tse,Wl,ZO,Qse,Yu,Nd,_8,Xb,xK,x8,wU,tc,wy,C8,LP,uae,DK,AU,Qp,$P,Te,Zb,$ae,OK,ka}from"./chunk-w5yypt53.js";import{i,Je,l,e}from"./chunk-r0vp315h.js";import"./chunk-5wk1t46v.js";import{cJ,TG,YE,l1,MJ,NM,_G,FM,u1,xG,LM,CG,NJ,DG,FJ,p1,f1,h1,g1,LJ,rp,BJ,BM,eI,MG,y1,NG,ky,v1,UJ,HJ,qJ,VJ,b1,WJ,zJ,$M,jJ,FG,LG,S1,KJ,tI,GJ,YJ,JJ,w1,R1,XJ,ZJ,QJ,eX,tX,rX,nX,iX,lS,oX,sX,aX,$G,UM,UG,HG,P1,zG,HM,qM,N1,dX,Jf,VM}from"./chunk-r4j43b9s.js";import{B,Ul,_e}from"./chunk-r6pvhj33.js";import"./chunk-aewdveet.js";import"./chunk-9xgnrv5w.js";import{Fe,ig,Pn,_t,nB,ai,ma}from"./chunk-4vxeq0vd.js";import"./chunk-9q265er0.js";import{HE,oJ}from"./chunk-whwj0pdk.js";import{aJ}from"./chunk-ntfrqrqn.js";import"./chunk-6hrj3jt6.js";import"./chunk-e0870khr.js";import{R,bu,dL,_C,ote,ste}from"./chunk-7k7gjg2t.js";import"./chunk-tvq0nzam.js";import{H0,tV,xQ,CQ,DQ}from"./chunk-8nj68t1v.js";import{QS,vv,gV,as,yV,G0,E_}from"./chunk-xezekwwn.js";import"./chunk-cqhw4yr6.js";import"./chunk-69pmjdf2.js";import{r,t,u}from"./chunk-2b39zyxc.js";var ro=new WeakMap;function ae(o){let d=ro.get(o);if(d===void 0)d={onPrototypeEvent:(y)=>o.onEvent(y)},ro.set(o,d);return d}function Xe(o){return{requestPutPrototypeAsset:(d,y)=>o.putAsset(d,y)}}var Kr=s({id:n().min(1),persistent:m(),state:HG,data:UG.optional(),pages:Ne(n(),a().int().nonnegative()).default({}),stacks:Me().optional().transform(BR),lastSequence:a().int().nonnegative(),hiddenReason:p(["app_layer_window_hidden","device_blocked"]).optional().catch(void 0).describe("Android: the prototype exists but is not visible, and why; absent when visible, when suspended, or with an older CtrlProxy"),suspended:m().optional(),orientation:p(["portrait","landscape","unlocked"]).optional().catch(void 0),statusBar:p(["unsupported"]).optional().catch(void 0),appearance:Me().optional().transform(LO),storage:Me().optional().transform(xK),timers:Me().optional(),feedbackLog:Me().optional().transform($G),shaderFailures:Ne(n(),n()).optional().catch(void 0),degradedEffects:Me().optional().transform(b2)});function Qr(o){return(o??[]).flatMap((d)=>{let y=Kr.safeParse(d);if(!y.success)return e.warn("[prototype] Ignoring malformed prototype in inspect reply",y.error),[];return[y.data]})}function Zr(o){let d=new Map;for(let y of o)d.set(y.id,[...d.get(y.id)??[],y]);return d}function en(o,d,y,f){for(let h of o.shownIds(y.deviceId))if(!f.has(h))d.dismiss(y.deviceId,h),o.dismissed(y,h)}function io(o,d,y,{scope:f,report:h}){let{prototypes:P,replayed:g,timersSupported:T}=h,A=Qr(P),C=new Set(A.map((O)=>O.id)),I=Zr(g);for(let[O,_]of I)if(C.has(O)||_.some((x)=>x.kind==="dismissed")){let x=A.find((F)=>F.id===O);d.adopt(f,O,y,{replayed:_,lastSequence:x?.lastSequence??0})}en(o,d,f,C);for(let O of A){if(!I.has(O.id))d.adopt(f,O.id,y,{replayed:[],lastSequence:O.lastSequence});if(!d.isDismissed(f,O.id))o.adopt(f,{...O,storage:xK(O.storage),timers:T?O.timers===void 0?[]:$ae(O.timers):void 0})}}async function tn(o,d,y,{timeoutMs:f,signal:h}={}){let{store:P,events:g}=o,T=d.android;if(!T){if(d.ios)return rn({store:P,events:g},d,d.ios,y);throw new t("inspect needs an Android device or an iOS simulator agent.")}let A=[],C=T.onEvent((O)=>A.push(O)),I;try{let O=await T.supportsCommand(Xp);if(h?.throwIfAborted(),!O)return{success:!1,error:new t(KY()).message};I=await T.inspect(f)}catch(O){return h?.throwIfAborted(),e.warn("[prototype] Inspect request failed",O),{success:!1,error:u(O,"Prototype inspect failed").message}}finally{C()}if(!I.success)return{success:!1,error:I.error??"Prototype inspect failed"};return io(P,g,ae(d.transport),{scope:y,report:{prototypes:I.prototypes,replayed:A,timersSupported:await T.supportsCommand(Od)}}),{success:!0,...Ee(P,g,y,{deviceDark:"fresh"}),deviceDroppedEvents:I.droppedEvents??0}}function ao(o){return o==="inspect"||o==="clearStorage"||o==="simulate"}async function po(o,d,y,{target:f,scope:h,signal:P}){if(o.action==="simulate")return FJ(f,o);if(o.action==="clearStorage")return aX(f,o,d.store,y.deviceId);return tn(d,f,h,{timeoutMs:o.timeoutMs,signal:P})}var on=s({shown:m(),id:n().min(1).nullable(),pages:Ne(n(),a().int().nonnegative()).default({}),stacks:Me().optional().transform(BR),state:HG,data:UG.optional(),lastSequence:a().int().nonnegative(),appearance:Me().optional().transform(LO),storage:Me().optional().transform(xK),timers:Me().optional(),feedbackLog:Me().optional().transform($G),degradedEffects:Me().optional().transform(b2)});async function rn(o,d,y,f){let{store:h,events:P}=o;if(!y.supportsCapability(W9))return{success:!1,error:new t(`inspect: the connected prototype agent does not advertise ${W9}; relaunch the app with launchApp prototype: true to load the agent built for this AutoMobile version.`).message};let g;try{g=await y.status()}catch(U){return e.warn("[prototype] iOS inspect request failed",U),{success:!1,error:u(U,"Prototype inspect failed").message}}if(!g.success)return{success:!1,error:g.error??"Prototype inspect failed"};let T=on.safeParse(g.status);if(!T.success)return e.warn("[prototype] Malformed iOS agent status in inspect reply",T.error),{success:!1,error:"Prototype inspect failed: the agent returned a malformed status."};let{shown:A,id:C,pages:I,stacks:O,state:_,data:x,lastSequence:F,appearance:q,storage:D,timers:M,feedbackLog:j,degradedEffects:G}=T.data,Q=A&&C!==null?[{id:C,persistent:!1,state:_,data:x,pages:I,stacks:O,lastSequence:F,appearance:q,storage:D,timers:M,feedbackLog:j,degradedEffects:G}]:[];return io(h,P,ae(d.transport),{scope:f,report:{prototypes:Q,replayed:[],timersSupported:y.supportsCapability(Od)}}),{success:!0,...Ee(h,P,f,{deviceDark:"fresh"})}}function Ee(o,d,y,f){let h=o.status(y);return{...h,prototypes:h.prototypes.map((P)=>{let g=f.deviceDark==="fresh"?P:q9(P),T={...g,...FO(g.degradedEffects)},A=T.id?d.counts(y,T.id):void 0;return A?.lastSequence===void 0?T:{...T,...A}}),...h.lastResult?{lastResult:q9(h.lastResult)}:{}}}function co(o,d,y,f){return o.status(d).prototypes.some((P)=>P.id===y&&P.suspended===!0)&&f.timedOut?{warning:kie}:{}}function no(o,d){if(!o)return;Promise.resolve().then(()=>o(d?1:0,1,d?"Prototype event wait finished":"Waiting for a prototype event")).catch((y)=>{e.warn("[prototype] Wait progress notification failed",y)})}async function uo(o,d,y,{query:f,context:h}){let P=o.awaitEvent(d,f.id,y,{eventName:f.eventName,kind:f.kind,afterSequence:f.afterSequence,timeoutMs:f.timeoutMs,signal:me(h.signal)});no(h.progress,!1);try{return await P}finally{no(h.progress,!0)}}var nn=s({stack:n().nullable(),screen:n().nullable(),x:a().finite(),y:a().finite()}).strict(),yo=s({changes:S(s({key:n(),valueLength:a().optional(),valueType:n().optional(),valid:m().optional()})).optional(),keys:S(n()).optional(),path:n().nullable().optional(),op:n().optional(),stack:n().nullable().optional(),screen:n().nullable().optional(),depth:a().optional(),pager:n().nullable().optional(),page:a().optional(),reason:n().optional(),x:a().optional(),y:a().optional()});function et(o){let d=Object.entries(o??{}).filter(([,y])=>y.path.length>0).sort(([y,f],[h,P])=>P.path.length-f.path.length||(y<h?-1:y>h?1:0))[0];return d?`${d[0]}/${d[1].path.at(-1)}`:"(root)"}function Ae(o){return o!==null&&typeof o==="object"&&!Array.isArray(o)?o:{}}function sn(o,d){let y=Ae(o.payload),f=typeof y.key==="string"?[y.key]:Array.isArray(y.keys)?y.keys.filter((g)=>typeof g==="string"):[],h=Ae(y.values),P=f.filter((g)=>!d.has("*")&&!d.has(g)).map((g)=>{let T=typeof y.key==="string"?y.value:h[g];return{key:g,...typeof T==="string"?{valueLength:T.length}:{valueType:typeof T},...typeof o.validity?.[g]==="boolean"?{valid:o.validity[g]}:{}}});return P.length?{changes:P}:void 0}function an(o,d){if(o.name==="change")return sn(o,d);if(o.name==="prototype_dead_tap"){let y=nn.safeParse(o.payload);return y.success?y.data:void 0}return{}}function pn(o){let d=Ae(o.payload);return{stack:o.name,...typeof d.screen==="string"?{screen:d.screen}:{},...typeof d.depth==="number"?{depth:d.depth}:{}}}function dn(o,d){return{keys:(o.keys??[]).filter((y)=>!d.has("*")&&!d.has(y))}}function cn(o,d){let y=Ae(o.payload);switch(o.kind){case"appearance_changed":case"unknown":return;case"emit":return an(o,d);case"change":return{path:o.name,...typeof y.op==="string"?{op:y.op}:{}};case"validation_failed":return dn(o,d);case"screen_changed":return pn(o);case"page_changed":return{pager:o.name,...typeof o.payload==="number"?{page:o.payload}:{}};case"dismissed":return typeof y.reason==="string"?{reason:y.reason}:{};default:return}}function fo(o,d){let y=cn(o,d);return y===void 0?void 0:{event_sequence:o.sequence,at_ms:o.timestamp,kind:o.kind,name:o.name,screen:et(o.stacks),detail_json:JSON.stringify(y)}}var un="No text values are recorded. Secure fields are excluded; other fields retain only keys, lengths/types and validity.";function ln(o){return yo.parse(JSON.parse(o.detail_json))}function yn(o,d,y){if(y.x===void 0||y.y===void 0)return;let f=o.get(d)??{screen:d,count:0,points:[],grid:[]};if(o.set(d,f),f.count++,f.points.length<200)f.points.push({x:y.x,y:y.y});let h=Math.floor(y.x/48),P=Math.floor(y.y/48),g=f.grid.find((T)=>T.col===h&&T.row===P);if(g)g.count++;else f.grid.push({col:h,row:P,count:1})}function fn(o,d,y){let f=ln(o);if(o.kind==="emit"&&o.name==="prototype_dead_tap")d.deadTaps++,yn(y.taps,d.screen,f);if(o.kind==="validation_failed"){d.validationFailures++;for(let h of f.keys??[])y.fields.set(h,(y.fields.get(h)??0)+1)}if(o.kind==="page_changed"&&o.name!==null)y.pagers.set(o.name,(y.pagers.get(o.name)??0)+1)}function mo(o,d){let y=o.get(d)??{screen:d,reached:0,left:0,abandoned:0,totalMs:0,averageMs:0,deadTaps:0,validationFailures:0};return o.set(d,y),y.reached++,y}function ho(o,d,y){let f=new Map,h={taps:new Map,fields:new Map,pagers:new Map},P=mo(f,o.start_screen),g=o.started_at_ms,T=o.goal===null?null:o.goal===P.screen,A=Math.max(o.started_at_ms,o.ended_at_ms??y);for(let O of d){let _=Math.min(A,Math.max(g,O.at_ms));if(P.totalMs+=_-g,g=_,O.screen!==P.screen)P.left++,P=mo(f,O.screen);if(o.goal===P.screen)T=!0;fn(O,P,h)}P.totalMs+=A-g;let C=o.status==="ended"&&o.ended_reason!=="released"&&T!==!0;if(C)P.abandoned=1;let I=[...f.values()].map((O)=>({...O,averageMs:O.totalMs/O.reached}));return{id:o.test_session_id,prototypeId:o.prototype_id,deviceId:o.device_id,sessionUuid:o.session_uuid,cohort:o.cohort,goal:o.goal,startedAt:o.started_at_ms,endedAt:o.ended_at_ms,durationMs:A-o.started_at_ms,status:o.status,endedReason:o.ended_reason,eventCount:d.length,droppedCount:o.dropped_count,truncated:o.dropped_count>0,privacy:un,funnel:I,completed:T,lastScreenBeforeAbandonment:C?P.screen:null,timePerScreen:I.map(({screen:O,totalMs:_,averageMs:x})=>({screen:O,totalMs:_,averageMs:x})).sort((O,_)=>_.totalMs-O.totalMs),deadTaps:[...h.taps.values()],validationFailures:[...h.fields].map(([O,_])=>({key:O,count:_})),pageChanges:[...h.pagers].map(([O,_])=>({pager:O,count:_}))}}var ee=(o)=>o.replaceAll("|","\\|").replaceAll(`
3
+ `," ").replaceAll("\r"," ");function Po(o){return[`# Prototype test session ${ee(o.id)}`,`Prototype: ${ee(o.prototypeId)} \xB7 Device: ${ee(o.deviceId)} \xB7 Status: ${o.status}`,`Cohort: ${ee(o.cohort??"\u2014")} \xB7 Goal: ${ee(o.goal??"\u2014")}`,`Completed: ${o.completed===null?"no goal set":o.completed} \xB7 Duration: ${o.durationMs} ms`,`Last screen before abandonment: ${ee(o.lastScreenBeforeAbandonment??"\u2014")}`,`Events: ${o.eventCount} \xB7 Dropped: ${o.droppedCount} \xB7 Truncated: ${o.truncated}`,"",o.privacy,"","| Screen | Reached | Left | Abandoned | Total ms | Average ms | Dead taps | Validation failures |","| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",...o.funnel.map((d)=>`| ${ee(d.screen)} | ${d.reached} | ${d.left} | ${d.abandoned} | ${d.totalMs} | ${d.averageMs} | ${d.deadTaps} | ${d.validationFailures} |`),"","Dead taps use window-local dp (points on iOS), with a 48-unit grid. No screenshot overlay is available yet.",...o.validationFailures.map(({key:d,count:y})=>`Validation failures: ${ee(d)} = ${y}`),...o.pageChanges.map(({pager:d,count:y})=>`Page changes: ${ee(d)} = ${y}`)].join(`
4
+ `)}class tt{deps;recording=new Map;key(o,d){return JSON.stringify([o.sessionUuid??null,o.deviceId,d])}chain=Promise.resolve();constructor(o){this.deps=o}enqueue(o){let d=this.chain.then(o);return this.chain=d.then(()=>{},(y)=>{e.warn("Prototype test session persistence failed",y)}),d}flush(){return this.chain}begin(o,d,y={}){let f=this.deps.timer.now(),h=this.deps.startScreen(o,d),P=this.deps.deadTapsEnabled(o,d)?"enabled":"off",g=this.deps.ids.next(),T=this.key(o,d),A=[...this.recording.values()].some((C)=>C.scope.deviceId===o.deviceId&&C.id===d);if(!A)this.recording.set(T,{scope:{...o},id:d,testSessionId:g});return this.enqueue(async()=>{let C=await this.deps.store.findActive(o,d);if(C&&A)throw new t("A test session is already active for this device and prototype. End it with testSessionEnd before beginning another.");if(C)await this.deps.store.endSession(C.test_session_id,Math.max(C.started_at_ms,f),"released");let I={test_session_id:g,prototype_id:d,device_id:o.deviceId,session_uuid:o.sessionUuid??null,cohort:y.cohort??null,goal:y.goal??null,start_screen:h,status:"active",started_at_ms:f,ended_at_ms:null,ended_reason:null,dropped_count:0};return await this.deps.store.insertSession(I),this.recording.set(this.key(o,d),{scope:{...o},id:d,testSessionId:I.test_session_id}),{session:I,eventCount:0,deadTaps:P,...P==="off"?{warning:"Add window.deadTaps: true via show to record dead taps (requires prototype_dead_tap_v1)."}:{}}}).catch((C)=>{if(this.recording.get(T)?.testSessionId===g)this.recording.delete(T);throw u(C,"Failed to begin prototype test session")})}recordEvent(o,d){let y=this.recording.get(this.key(o,d.id));if(!y)return;let f=this.deps.timer.now(),h=fo(d,this.deps.secureKeys(o,d.id)),P=h&&{...h,at_ms:f},g=d.kind==="dismissed";this.enqueue(async()=>{let T=await this.deps.store.findById(y.testSessionId);if(T?.status!=="active")return;if(P)try{await this.deps.store.appendEvents(T.test_session_id,[P])}catch(A){e.warn("Prototype test event append failed",A)}if(g)await this.finish(T,f,"dismissed"),await this.deps.store.pruneEnded()}).catch((T)=>{e.warn("Prototype test event was not persisted",T)})}async active(o,d){let y=await this.deps.store.findActive(o,d);return y?.session_uuid===(o.sessionUuid??null)?y:void 0}async finish(o,d,y){await this.deps.store.endSession(o.test_session_id,Math.max(o.started_at_ms,d),y),this.recording.delete(this.key({deviceId:o.device_id,sessionUuid:o.session_uuid??void 0},o.prototype_id))}endForDismiss(o,d,y){let f=this.recording.get(this.key(o,d));if(!f)return;let h=this.deps.timer.now();this.enqueue(async()=>{let P=await this.deps.store.findById(f.testSessionId);if(P?.status==="active")await this.finish(P,h,y),await this.deps.store.pruneEnded()}).catch((P)=>{e.warn("Prototype test session cleanup failed",P)})}endSessionRecordings(o){for(let{scope:d,id:y}of this.recording.values())if(d.sessionUuid===o)this.endForDismiss(d,y,"released")}endDeviceRecordings(o){for(let{scope:d,id:y}of this.recording.values())if(d.deviceId===o)this.endForDismiss(d,y,"released")}end(o,d){let y=this.deps.timer.now();return this.enqueue(async()=>{let f=await this.active(o,d);if(!f)throw new t("No active test session for this scope and prototype. Use testSessionBegin first, or testSessionReport for a stored session.");await this.finish(f,y,"end");let h=await this.result({...f,status:"ended",ended_at_ms:Math.max(f.started_at_ms,y),ended_reason:"end"},o);return await this.deps.store.pruneEnded(),h})}report(o,d){return this.enqueue(async()=>{let y=d.testSessionId?await this.deps.store.findById(d.testSessionId):await this.deps.store.findLatest(o,d.id);if(!y||d.id!==void 0&&d.id!==y.prototype_id)throw new t("No stored test session for this id. Check testSessionId or begin a test session for this prototype.");return this.result(y,{deviceId:y.device_id,sessionUuid:y.session_uuid??void 0})})}async result(o,d){let y=await this.deps.store.listEvents(o.test_session_id),f=ho(o,y,this.deps.timer.now());return{session:o,eventCount:y.length,deadTaps:this.deps.deadTapsEnabled(d,o.prototype_id)?"enabled":"off",report:f,markdown:Po(f)}}}function go(o){let d=new Set,y=(f)=>{if(Array.isArray(f)){f.forEach(y);return}if(f===null||typeof f!=="object")return;let h=f;if((h.type==="textField"||h.type==="searchBar")&&typeof h.stateKey==="string"&&h.secure!==!1)d.add(h.stateKey.includes("{")?"*":h.stateKey);Object.values(h).forEach(y)};return y(o),d}var mn=5000;class ot{db;constructor({db:o}={}){this.db=o}getDb(){return this.db??_e()}async insertSession(o){await this.getDb().insertInto("prototype_test_sessions").values(o).execute()}findActive(o,d){return this.getDb().selectFrom("prototype_test_sessions").selectAll().where("device_id","=",o.deviceId).where("prototype_id","=",d).where("status","=","active").executeTakeFirst()}findById(o){return this.getDb().selectFrom("prototype_test_sessions").selectAll().where("test_session_id","=",o).executeTakeFirst()}findLatest(o,d){return this.getDb().selectFrom("prototype_test_sessions").selectAll().where("device_id","=",o.deviceId).where("prototype_id","=",d).where("session_uuid",o.sessionUuid===void 0?"is":"=",o.sessionUuid??null).orderBy("started_at_ms","desc").orderBy("test_session_id","desc").executeTakeFirst()}async appendEvents(o,d){await this.getDb().transaction().execute(async(y)=>{if((await y.selectFrom("prototype_test_sessions").select("status").where("test_session_id","=",o).executeTakeFirstOrThrow()).status!=="active")return;let h=await y.selectFrom("prototype_test_session_steps").select((g)=>g.fn.countAll().as("count")).where("test_session_id","=",o).executeTakeFirstOrThrow(),P=d.slice(0,Math.max(0,mn-Number(h.count)));for(let g=0;g<P.length;g+=100)await y.insertInto("prototype_test_session_steps").values(P.slice(g,g+100).map((T,A)=>({...T,test_session_id:o,seq:Number(h.count)+g+A+1}))).execute();if(P.length<d.length)await y.updateTable("prototype_test_sessions").set((g)=>({dropped_count:g("dropped_count","+",d.length-P.length)})).where("test_session_id","=",o).execute()})}async endSession(o,d,y){await this.getDb().updateTable("prototype_test_sessions").set({status:"ended",ended_at_ms:d,ended_reason:y}).where("test_session_id","=",o).where("status","=","active").execute()}listEvents(o){return this.getDb().selectFrom("prototype_test_session_steps").selectAll().where("test_session_id","=",o).orderBy("seq").execute()}async pruneEnded(o=50){await this.getDb().transaction().execute(async(d)=>{let y=await d.selectFrom("prototype_test_sessions").selectAll().where("status","=","ended").orderBy("ended_at_ms","desc").orderBy("test_session_id","desc").execute(),f=new Map;for(let h of y){let P=JSON.stringify([h.device_id,h.prototype_id]),g=(f.get(P)??0)+1;if(f.set(P,g),g>Math.max(0,o))await d.deleteFrom("prototype_test_session_steps").where("test_session_id","=",h.test_session_id).execute(),await d.deleteFrom("prototype_test_sessions").where("test_session_id","=",h.test_session_id).execute()}})}}var hn=Yp();function vo(o,d){let y=(f,h)=>d.shownSpecs.read(f.deviceId,h);return new tt({store:o.testSessionStore??new ot,timer:o.clock??o.timer??i,ids:o.idGenerator??B,secureKeys:(f,h)=>{let P=y(f,h);return P.kind==="known"?go(P.spec):new Set(["*"])},startScreen:(f,h)=>et(d.status(f).prototypes.find((P)=>P.id===h)?.stacks),deadTapsEnabled:(f,h)=>{let P=y(f,h);if(P.kind!=="known")return!1;let g=P.spec.window;return g!==null&&typeof g==="object"&&"deadTaps"in g&&g.deadTaps===!0}})}var gn=(o)=>["testSessionBegin","testSessionEnd","testSessionReport"].includes(o);async function vn(o,d,y){try{let f=y.action==="testSessionBegin"?await o.begin(d,y.id,y):y.action==="testSessionEnd"?await o.end(d,y.id):await o.report(d,y),h=f.session;return{success:!0,testSession:{id:h.test_session_id,prototypeId:h.prototype_id,deviceId:h.device_id,status:h.status,...h.cohort===null?{}:{cohort:h.cohort},...h.goal===null?{}:{goal:h.goal},startedAt:h.started_at_ms,...h.ended_at_ms===null?{}:{endedAt:h.ended_at_ms},eventCount:f.eventCount,droppedCount:h.dropped_count,deadTaps:f.deadTaps},..."report"in f?{report:hn.parse(f.report),markdown:f.markdown}:{},..."warning"in f?{warning:f.warning}:{}}}catch(f){return e.warn("Prototype test session action failed",f),{success:!1,error:u(f,"Prototype test session failed").message}}}function wo(o){return o==="status"||gn(o)}function So(o,d,y){if(y.action!=="status")return vn(o.recorder,d,y);let f=o.preview?.().info();return{success:!0,...Ee(o.store,o.events,d,{deviceDark:"cached"}),...f?{previewServer:f}:{}}}import{join as pe}from"path";async function Ce(o,d,y,{signal:f,timeoutGuidance:h="It may still have saved the prototype: check ProtoViewer before retrying, and unlock the device if it is locked."}={}){let P=d.now()+y;do{f?.throwIfAborted();let g=(await o()).trim();if(g.length>0)return wn(g);await d.sleep(Math.min(yV,Math.max(0,P-d.now())))}while(d.now()<P);throw new t(`ProtoViewer did not answer within ${y} ms. ${h}`)}function wn(o){let d;try{d=JSON.parse(o)}catch(f){throw new t(`ProtoViewer wrote an unreadable result: ${r(f)}`,{cause:f})}let y=QJ.safeParse(d);if(!y.success)throw new t(`ProtoViewer wrote an unexpected result: ${y.error.message}`);return y.data}var Sn=1000;class rt{deps;constructor(o){this.deps=o}async installed(o){return z(this.deps)==="simulator"&&await this.deps.simctl.installed(this.deps.deviceId,o)}async capabilities(){return}importBundle(o,d,y,f){return this.exchange(y,f,{bytes:o,label:d})}open(o,d,y){return this.exchange(d,y,{libraryId:o})}async exchange(o,d,y){d?.throwIfAborted();let f=this.deps.timer.now(),h=`mcp-${this.deps.ids.next().replace(/[^A-Za-z0-9_-]/g,"")}`.slice(0,64);if(!$M.test(h))throw new t("Generated an unusable ProtoViewer request id.");let P=await this.deps.simctl.dataContainer(this.deps.deviceId,d);if(!P.trim())throw new as("Could not resolve ProtoViewer's data container.");let g=pe(P,eX),T=pe(g,tX),A=pe(g,rX),C=pe(T,`${h}.automobile-proto`),I=`${C}.tmp`,O=pe(A,`${h}.json`),_=pe(T,`${h}.request`),x=`${_}.tmp`;try{await this.prepare({inboxDir:T,resultsDir:A,temporary:I,inbox:C},y,d),d?.throwIfAborted(),await this.foreground(o,d),await this.requireFileDelivery(g,Math.max(0,o-(this.deps.timer.now()-f)),d),await this.deliverRequest(x,_,y,d);let F=Math.max(o-(this.deps.timer.now()-f),Math.min(o,Sn)),q=await Ce(()=>this.deps.files.read(O),this.deps.timer,F,{signal:d,timeoutGuidance:"Retrying the same spec is safe: imports are idempotent. Open ProtoViewer and unlock the simulator if it is locked."});if(q.request!==h)throw new t(`ProtoViewer answered request ${q.request}, not ${h}; retry the call.`);if(q.status==="prepared")throw new t("ProtoViewer answered a request with a prepare result; retry.");if(q.status==="rejected"&&q.path==="inbox")throw new as(`ProtoViewer cannot read the prototype pushed into its inbox: ${q.reason}.`);return q}finally{await this.cleanup([_,x,O,C,I])}}async prepare({inboxDir:o,resultsDir:d,temporary:y,inbox:f},h,P){try{if(await this.deps.files.mkdir(o),await this.deps.files.mkdir(d),"bytes"in h)await this.deps.files.write(y,h.bytes),await this.deps.files.rename(y,f)}catch(g){if(P?.aborted)throw g;throw new as(`Could not prepare ProtoViewer's inbox: ${r(g)}`,{cause:g})}}async deliverRequest(o,d,y,f){let h="bytes"in y?{action:"import",...y.label===void 0?{}:{label:y.label}}:{action:"open",libraryId:y.libraryId};try{f?.throwIfAborted(),await this.deps.files.write(o,new TextEncoder().encode(JSON.stringify(h))),await this.deps.files.rename(o,d)}catch(P){if(f?.aborted)throw P;throw new as(`Could not publish ProtoViewer's request: ${r(P)}`,{cause:P})}}async foreground(o,d){try{await this.deps.simctl.launch(this.deps.deviceId,o,d)}catch(y){if(d?.aborted)throw y;throw new gV({cause:y})}}async requireFileDelivery(o,d,y){let f=this.deps.timer.now()+d;do{if(y?.throwIfAborted(),(await this.deps.files.read(pe(o,"delivery"))).trim()===nX)return;await this.deps.timer.sleep(Math.min(yV,Math.max(0,f-this.deps.timer.now())))}while(this.deps.timer.now()<f);throw new E_}async cleanup(o){for(let d of o)try{await l(()=>this.deps.files.remove(d),{timer:this.deps.timer,timeoutMs:G0,label:"ProtoViewer cleanup"})}catch(y){e.warn(`[protoviewer] cleanup failed: ${r(y)}`)}}}class nt{client;bundleIdCandidates;bundleIds=new Map;constructor(o,d){this.client=o;this.bundleIdCandidates=d}async installed(o,d){let y=await this.client.listAppsOrThrow(o,{signal:d}),f=v1((h)=>y.some((P)=>P.bundleId===h),this.bundleIdCandidates);if(f===void 0)return this.bundleIds.delete(o),!1;return this.bundleIds.set(o,f),!0}async dataContainer(o,d){try{return await Qo({deviceId:o,bundleId:this.bundleId(o),run:(y)=>this.client.executeCommandArgs(y,void 0,d)})}catch(y){if(y instanceof lo)return e.debug("ProtoViewer data container unresolved"),"";throw y}}async launch(o,d,y){await this.client.executeCommandArgs(["launch",o,this.bundleId(o)],d,y)}bundleId(o){return this.bundleIds.get(o)??ky}}import{mkdir as bn,writeFile as Rn,rename as kn,readFile as En,rm as Tn}from"fs/promises";class st{async mkdir(o){await bn(o,{recursive:!0})}async write(o,d){await Rn(o,d)}async rename(o,d){await kn(o,d)}async read(o){try{return await En(o,"utf8")}catch(d){if(d instanceof Error&&"code"in d&&d.code==="ENOENT")return e.debug("ProtoViewer result pending"),"";throw d}}async remove(o){await Tn(o,{force:!0})}}var Oe=".mock.automobile.invalid";function Ie(o){let d;try{d=new URL(o)}catch(h){e.debug("[PrototypeMock] URL parse failed.");return}let y=d.hostname.toLowerCase();if(d.protocol!=="https:"&&d.protocol!=="http:"||!y.endsWith(Oe))return;return{backendId:y.slice(0,-Oe.length),path:d.pathname,query:Object.fromEntries(d.searchParams)}}var it=(o)=>`https://${o}${Oe}`;function bo(o,d){let y=d.backendId;try{if(d.action==="clearBackend")return{success:!0,backend:{id:y,origin:it(y),cleared:o.clear(y)}};if(d.action==="backendLog"||d.action==="publish"){let P=o.get(y);if(P===void 0)return{success:!1,error:`No mock backend "${y}" is defined.`};if(d.action==="backendLog")return{success:!0,backendLog:P.requestLog(d.since)};return{success:!0,backend:{id:y,origin:it(y),delivered:P.publish(d.room,d.frame)}}}o.define(y,d.backend);let f=o.get(y),h=Object.fromEntries(Object.entries(f.snapshot()).map(([P,g])=>[P,g.length]));return{success:!0,backend:{id:y,origin:it(y),collections:h,routes:f.routeCount,faults:f.faultCount,rooms:f.roomCount,actors:f.actorCount}}}catch(f){return e.warn("Prototype mock backend action failed",f),{success:!1,error:u(f,"Mock backend action failed").message}}}class at{state;constructor(o=1){this.state=Ro(o)}reseed(o){this.state=Ro(o)}next(){this.state=this.state+1831565813>>>0;let o=this.state;return o=Math.imul(o^o>>>15,o|1),o^=o+Math.imul(o^o>>>7,o|61),((o^o>>>14)>>>0)/4294967296}pick(o){if(o.length===0)throw Error("Random.pick cannot pick from an empty array");return o[Math.floor(this.next()*o.length)]}}var Ro=(o)=>Math.floor(o)>>>0||1;var{MAX_PROTOTYPE_UPLOAD_BYTES:Qd,MAX_PROTOTYPE_UPLOAD_PARTS:Zd,DEFAULT_PROTOTYPE_REQUEST_TIMEOUT_MS:te,MAX_PROTOTYPE_REQUEST_TIMEOUT_MS:xe,MAX_PROTOTYPE_RESPONSE_BYTES:de,MAX_PROTOTYPE_REQUESTS_IN_FLIGHT:ko}=W.limits;var Eo=String.raw`params\.[A-Za-z][A-Za-z0-9_]*|query\.[^{}\s]+|body:\/[^{}\s]*`,An=[Eo,String.raw`${Eo}|item(?::\/[^{}\s]*)?`].map((o)=>({placeholder:new RegExp(String.raw`\{(${o})\}`,"g"),exact:new RegExp(String.raw`^\{(${o})\}$`)}));function To(o,d){if(o.startsWith("params."))return Ao(d.params,o.slice(7));if(o.startsWith("query."))return Ao(d.query,o.slice(6));if(o==="item")return d.item;if(o.startsWith("item:"))return Et(d.item,o.slice(5));return Et(d.body,o.slice(5))}function Ao(o,d){return Object.hasOwn(o,d)?o[d]:void 0}function Cn(o){if(o===void 0||o===null)return"";return typeof o==="string"?o:JSON.stringify(o)}class De extends Error{}function oe(o,d,y=de){let{placeholder:f,exact:h}=An["item"in d?1:0],P=y,g=(I)=>{if(P-=I,P<0)throw new De(`Response body exceeds ${y} bytes.`)},T=new Map,A=(I,O)=>{let _=T.get(I);if(_===void 0)_=JSON.stringify(O).length,T.set(I,_);return _},C=(I)=>{if(typeof I==="string"){let O=h.exec(I);if(O){let _=To(O[1],d)??null;return g(A(O[1],_)),_}return g(I.replace(f,"").length),I.replace(f,(_,x)=>{let F=Cn(To(x,d));return g(F.length),F})}if(Array.isArray(I))return g(2+Math.max(0,I.length-1)),I.map(C);if(typeof I==="object"&&I!==null)return g(2+Math.max(0,Object.keys(I).length-1)),Object.fromEntries(Object.entries(I).map(([O,_])=>(g(O.length+3),[O,C(_)])));return g(JSON.stringify(I).length),I};return C(o)}function ce(o,d){let y=o.split("/"),f=d.split("/");if(y.length!==f.length)return;let h={};for(let[P,g]of y.entries()){let T=f[P];if(g.startsWith(":"))h[g.slice(1)]=Le(T);else if(g!==T)return}return h}function Le(o){try{return decodeURIComponent(o)}catch(d){return e.debug("[PrototypeMock] path segment is not valid percent-encoding."),o}}var Co=256,On={params:{},query:{},body:void 0};class pt{actors;timer;apply;pending=new Set;disposed=!1;constructor(o,d,y){this.actors=o;this.timer=d;this.apply=y}start(){for(let o of this.actors)if(o.every!==void 0)this.tick(o,1,(o.afterMs??0)+o.every)}onRequest(o,d,y,f){if(y>=400)return;for(let h of this.actors){let[P,g]=h.on?.route.split(" ")??[],T=P===o&&g!==void 0?ce(g,d):void 0;if(T!==void 0)this.run(h.do,0,h.afterMs??0,{...f,params:T})}}dispose(){this.disposed=!0;for(let o of this.pending)this.timer.clearTimeout(o);this.pending.clear(),this.steps=0}get pendingCount(){return this.pending.size}tick(o,d,y){this.schedule(y,()=>{if(d<o.maxRuns)this.tick(o,d+1,o.every);this.run(o.do,0,0,On)},!1)}run(o,d,y,f){let h=o[d];if(h===void 0||this.disposed)return;let P=y+(h.afterMs??0),g=()=>{this.applyStep(h,f),this.run(o,d+1,0,f)};if(P===0)g();else this.schedule(P,g)}steps=0;schedule(o,d,y=!0){if(this.disposed)return;if(y&&this.steps>=Co){e.warn(`[PrototypeMock] actor step dropped: ${Co} steps already scheduled.`);return}let f=this.timer.setTimeout(()=>{if(this.pending.delete(f),y)this.steps--;if(!this.disposed)d()},o);if(this.pending.add(f),y)this.steps++}applyStep(o,d){let y=In(o,d);if(y===void 0)return;let f=this.apply(y);if(f>=400)e.warn(`[PrototypeMock] actor ${y.method} ${y.collection}${y.id===void 0?"":`/${y.id}`} answered ${f}.`)}}function In(o,d){try{let y=o.value===void 0?void 0:oe(o.value,d),f=o.id===void 0?void 0:oe(o.id,d),h=f===void 0||f===null?void 0:String(f);if(o.append!==void 0)return{method:"POST",collection:o.append,body:y};if(o.update!==void 0)return{method:"PATCH",collection:o.update,id:h,body:y};if(o.remove!==void 0)return{method:"DELETE",collection:o.remove,id:h};return}catch(y){e.warn(`[PrototypeMock] actor step skipped: ${r(y)}`,y);return}}var Oo=10,Io=100,_n=new Set(["q","_sort","_page","_limit","after","size"]),_o=W.limits.MAX_PROTOTYPE_DATA_ARRAY_ITEMS,ne=(o,d,y={})=>({status:o,headers:y,body:d}),V=(o,d)=>ne(o,{error:d});function Mn(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)}function xn(o,d){if(typeof o==="number"&&typeof d==="number")return o-d;let y=String(o??""),f=String(d??"");return y<f?-1:y>f?1:0}function Dn(o,d){if(d===void 0||d==="")return o;let y=d.startsWith("-"),f=y?d.slice(1):d;return[...o].sort((h,P)=>(y?-1:1)*xn(h[f],P[f]))}function Ln(o,d){let y=Object.entries(d).filter(([h])=>!_n.has(h)),f=d.q?.toLowerCase();return o.filter((h)=>y.every(([P,g])=>String(h[P])===g)&&(f===void 0||Object.values(h).some((P)=>(typeof P==="string"||typeof P==="number")&&String(P).toLowerCase().includes(f))))}function dt(o,d,y){if(o===void 0)return d;return/^[1-9][0-9]*$/.test(o)&&Number(o)<=y?Number(o):void 0}function qn(o,d){let y=Dn(Ln(o,d),d._sort);if(d.after!==void 0||d.size!==void 0)return Fn(y,d);if(d._page===void 0&&d._limit===void 0)return ne(200,y);let f=dt(d._limit,Oo,Io),h=dt(d._page,1,_o);if(f===void 0||h===void 0)return V(400,"_page and _limit must be positive integers (_limit at most 100)");return ne(200,y.slice((h-1)*f,h*f),{"x-total-count":String(y.length)})}function Fn(o,d){let y=dt(d.size,Oo,Io);if(y===void 0)return V(400,"size must be a positive integer of at most 100");let f=0;if(d.after!==void 0&&d.after!==""){let g=o.findIndex((T)=>String(T.id)===d.after);if(g===-1)return V(400,"after names no item in this result");f=g+1}let h=o.slice(f,f+y),P=f+y<o.length;return ne(200,{items:h,next:P?h[h.length-1]?.id??null:null})}function Mo(o){return Mn(o)?o:void 0}function xo(o,d){return o.length<=_o&&d.fits(o)}function ct(o,d,y){let[f,...h]=d.rest;if(h.length>0)return V(404,"No such route");if(f===void 0)return Nn(o,d,y);let P=o.findIndex((g)=>String(g.id)===f);switch(d.method){case"GET":return P===-1?V(404,"Not found"):ne(200,o[P]);case"PATCH":case"PUT":return Hn(o,P,d,y);case"DELETE":return $n(o,P);default:return V(405,`${d.method} is not allowed here`)}}function Nn(o,d,y){if(d.method==="GET")return qn(o,d.query);if(d.method!=="POST")return V(405,`${d.method} is not allowed here`);let f=Mo(d.body);if(f===void 0)return V(400,"Expected a JSON object body");if(f.id!==void 0&&!CG(f.id))return V(400,"id must be a number or a non-empty string other than . and ..");let h=f.id===void 0?{...f,id:y.ids.next()}:f;if(o.some((g)=>String(g.id)===String(h.id)))return V(409,"An item with that id already exists");let P=[...o,h];if(!xo(P,y))return V(413,"The collection is full");return o.push(h),ne(201,h)}function Hn(o,d,y,f){let h=Mo(y.body);if(h===void 0)return V(400,"Expected a JSON object body");if(d===-1)return V(404,"Not found");let P=o[d];if(h.id!==void 0&&String(h.id)!==String(P.id))return V(400,"The id of an item cannot change");let g=y.method==="PATCH"?{...P,...h,id:P.id}:{...h,id:P.id},T=o.map((A,C)=>C===d?g:A);if(!xo(T,f))return V(413,"The collection is full");return o[d]=g,ne(200,g)}function $n(o,d){if(d===-1)return V(404,"Not found");return o.splice(d,1),ne(200,{})}function Do(o){return typeof o==="string"?o:JSON.stringify(o)}function ut(o){let d=new URL("https://room.invalid");return d.pathname=o,d.pathname}var lt=(o)=>Buffer.byteLength(o)<=Wl;class yt{rooms;deps;members=new Set;constructor(o,d){this.rooms=o;this.deps=d}memberCount(o){return this.membersOf(o===void 0?void 0:ut(o)).length}join(o,d,y){let f=ut(o),h=this.match(f);if(h===void 0)return{ok:!1,status:404,message:`No mock room matches ${f}.`};if(this.membersOf(f).length>=xG)return{ok:!1,status:503,message:`Mock room ${f} already has ${xG} connections.`};let P={room:h.room,path:f,target:y,timers:[],left:!1};this.members.add(P);let g={params:h.params,query:d,body:void 0};for(let T of h.room.onConnect??[])this.deliverBound(P,T,g);for(let T of h.room.timeline??[])P.timers.push(this.deps.timer.setTimeout(()=>this.deliverBound(P,T.frame,g),T.afterMs));return{ok:!0,connection:{send:(T)=>this.send(P,T),leave:()=>this.leave(P)}}}publish(o,d,y){let f=ut(o),h=Do(d);if(!lt(h))return e.warn(`[PrototypeMock] dropped a ${y} frame to ${f}: over ${Wl} bytes`),0;this.deps.record(f,y,h);let P=this.membersOf(f);return P.forEach((g)=>g.target.deliver(h)),P.length}closeAll(o){for(let d of[...this.members])this.leave(d),d.target.close(1001,o)}send(o,d){if(o.left)return{ok:!1,reason:"not_open"};if(!lt(d))return{ok:!1,reason:"too_large"};if(this.deps.record(o.path,"client",d),o.room.echo===!0)o.target.deliver(d);if(o.room.relay===!0)this.membersOf(o.path).filter((y)=>y!==o).forEach((y)=>y.target.deliver(d));return{ok:!0}}leave(o){if(o.left)return;o.left=!0,o.timers.forEach((d)=>this.deps.timer.clearTimeout(d)),this.members.delete(o)}deliverBound(o,d,y){if(o.left)return;let f;try{f=Do(oe(d,y,Wl))}catch(h){e.warn(`[PrototypeMock] dropped a scripted frame to ${o.path}: ${r(h)}`);return}if(lt(f))o.target.deliver(f);else e.warn(`[PrototypeMock] dropped a scripted frame to ${o.path}: too large`)}match(o){for(let d of this.rooms){let y=ce(d.path,o);if(y!==void 0)return{room:d,params:y}}return}membersOf(o){return[...this.members].filter((d)=>o===void 0||d.path===o)}}var Vn=200;class ft{definition;deps;collections=new Map;faultHits=new Map;log=[];rooms;seq=0;actors;constructor(o,d){this.definition=o;this.deps=d;for(let[y,f]of Object.entries(o.collections??{}))this.collections.set(y,structuredClone(f));this.rooms=new yt(o.rooms??[],{timer:d.timer,record:(y,f,h)=>this.append({seq:0,room:y,from:f,data:h})}),this.actors=new pt(o.actors??[],d.timer,(y)=>this.applyActorWrite(y)),this.actors.start()}get actorCount(){return this.definition.actors?.length??0}get roomCount(){return this.definition.rooms?.length??0}join(o,d,y){return this.rooms.join(o,d,y)}publish(o,d){return this.rooms.publish(o,d,"publish")}dispose(o="Mock backend was disposed."){this.actors.dispose(),this.rooms.closeAll(o)}get routeCount(){return this.definition.routes?.length??0}get faultCount(){return this.definition.faults?.length??0}requestLog(o=0){return this.log.filter((d)=>d.seq>o)}snapshot(){return Object.fromEntries([...this.collections].map(([o,d])=>[o,structuredClone(d)]))}async answer(o,d){let y=o.method.toUpperCase();await this.waitLatency(),d?.throwIfAborted();let f=this.faultFor(y,o.path)??await this.cannedRoute(y,o,d),h=f===void 0?this.collectionResponse(y,o):void 0,P=f??h??{status:404,headers:{},body:{error:"No such route"}};if(this.record(y,o,P),h!==void 0)this.broadcastWrite(y,o,h);return this.actors.onRequest(y,o.path,P.status,{query:o.query,body:o.body}),P}applyActorWrite(o){let d=this.collections.get(o.collection);if(d===void 0)return 404;return ct(d,{method:o.method,rest:o.id===void 0?[]:[o.id],query:{},body:o.body},{ids:this.deps.ids,fits:(y)=>this.fitsWith(d,y)}).status}broadcastWrite(o,d,y){let f=Le(d.path.split("/")[1]??""),h=this.broadcastFor(f,o,y.status);if(h===void 0)return;let P={params:{},query:d.query,body:d.body,item:y.body??null};try{let g=oe(h.room,P);if(typeof g!=="string"||!g.startsWith("/")){e.warn(`[PrototypeMock] broadcast for ${f} dropped: room is not a path`);return}let T=oe(h.frame,P,Wl);this.rooms.publish(g,T,"broadcast")}catch(g){e.warn(`[PrototypeMock] broadcast for ${f} dropped: ${r(g)}`)}}broadcastFor(o,d,y){let f=this.definition.broadcasts??{};if(y<200||y>299||!this.collections.has(o)||!Object.hasOwn(f,o))return;let h=f[o];return(h.on??["POST"]).some((P)=>P===d)?h:void 0}async waitLatency(){let o=this.definition.latencyMs;if(o===void 0)return;let d=o.min+Math.floor(this.deps.random.next()*(o.max-o.min+1));if(d>0)await this.deps.timer.sleep(d)}faultFor(o,d){for(let y of this.definition.faults??[]){if(y.method!==void 0&&y.method!==o||!ce(y.path,d))continue;let f=(this.faultHits.get(y)??0)+1;if(this.faultHits.set(y,f),y.every!==void 0?f%y.every===0:this.deps.random.next()<y.rate)return{status:y.status,headers:{},body:{error:"mock fault"}}}return}async cannedRoute(o,d,y){for(let f of this.definition.routes??[]){let h=f.method===o?ce(f.path,d.path):void 0;if(h!==void 0)return this.routeResponse(f,{params:h,query:d.query,body:d.body},y)}return}async routeResponse(o,d,y){if(o.delayMs!==void 0&&o.delayMs>0)await this.deps.timer.sleep(o.delayMs),y?.throwIfAborted();return{status:o.status??200,headers:o.headers??{},body:o.body===void 0?null:oe(o.body,d)}}collectionResponse(o,d){let[,y,...f]=d.path.split("/").map(Le),h=y===void 0?void 0:this.collections.get(y);if(h===void 0)return;return ct(h,{method:o,rest:f,query:d.query,body:d.body},{ids:this.deps.ids,fits:(P)=>this.fitsWith(h,P)})}fitsWith(o,d){let y=Object.fromEntries([...this.collections].map(([f,h])=>[f,h===o?d:h]));return DG(this.definition,y)<=FM}record(o,d,y){this.append({seq:0,method:o,path:d.path,query:d.query,status:y.status,...d.body===void 0?{}:{body:d.body}})}append(o){if(o.seq=++this.seq,this.log.push(o),this.log.length>Vn)this.log.shift()}}var Un=(o)=>o===void 0?Ul:new at(o);class mt{deps;backends=new Map;constructor(o){this.deps=o}define(o,d){this.defineAll({[o]:d})}defineAll(o){let d=Object.entries(o).map(([h,P])=>{if(!LM.test(h))throw new t(`Mock backend id "${h}" must match ${LM.source}.`);let g=NJ.safeParse(P);if(!g.success){let T=g.error.issues[0],A=[h,...T?.path??[]].join(".");throw new t(`Invalid mock backend definition at ${A}: ${T?.message??"invalid"}`)}return[h,g.data]}),y=d.filter(([h])=>!this.backends.has(h)).length;if(this.backends.size+y>_G)throw new t(`At most ${_G} mock backends may be defined; clear one first.`);let f=this.deps.createRandom??Un;for(let[h,P]of d)this.backends.get(h)?.dispose(`Mock backend "${h}" was replaced.`),this.backends.set(h,new ft(P,{random:f(P.seed),ids:this.deps.ids,timer:this.deps.timer}))}get(o){return this.backends.get(o)}clear(o){return this.backends.get(o)?.dispose(`Mock backend "${o}" was cleared.`),this.backends.delete(o)}clearAll(){for(let o of this.ids())this.clear(o)}ids(){return[...this.backends.keys()]}}class ht{states=new Map;begin(o,d){let y=JSON.stringify([o,d]),f=this.states.get(y)??{issued:0,settledValid:0,latestValid:0,inFlight:new Map};return f.issued+=1,f.latestValid=f.issued,f.inFlight.set(f.issued,!1),this.states.set(y,f),f.issued}isLatest(o,d,y){let f=this.states.get(JSON.stringify([o,d]));if(!f)return!0;return f.inFlight.get(y)===!0?y===f.issued:y===f.latestValid}withdraw(o,d,y){let f=this.states.get(JSON.stringify([o,d]));if(!f||f.inFlight.get(y)!==!1)return;if(f.inFlight.set(y,!0),f.latestValid===y)f.latestValid=this.newestValidBelow(f,y)}settle(o,d,y){let f=JSON.stringify([o,d]),h=this.states.get(f);if(!h)return;if(h.inFlight.get(y)===!1)h.settledValid=Math.max(h.settledValid,y);if(h.inFlight.delete(y),h.inFlight.size===0)this.states.delete(f)}trackedIds(){return this.states.size}newestValidBelow(o,d){let y=o.settledValid;for(let[f,h]of o.inFlight)if(!h&&f<d&&f>y)y=f;return y}}var Bn=64;function Wn(o){return o.kind!==hU}class Pt{events=[];lastSequence;droppedCount=0;push(o){if(this.lastSequence!==void 0&&o.sequence<=this.lastSequence)return!1;if(this.lastSequence=o.sequence,!Wn(o))return!1;if(this.events.push(structuredClone(o)),this.events.length>Bn)this.events.shift(),this.droppedCount++;return!0}advanceTo(o){if(this.lastSequence===void 0||o>this.lastSequence)this.lastSequence=o}take(o){let d=this.events.findIndex((y)=>y.sequence>(o.afterSequence??-1)&&(o.eventName===void 0||y.name===o.eventName)&&(o.kind===void 0||y.kind===o.kind));return d<0?void 0:this.events.splice(d,1)[0]}status(){return{pendingCount:this.events.length,...this.lastSequence===void 0?{}:{lastSequence:this.lastSequence},droppedCount:this.droppedCount}}startEpoch(){this.events=[],this.lastSequence=void 0}clear(){this.events=[]}}var K=(o,d)=>JSON.stringify([o.sessionUuid??null,o.deviceId,d]);class gt{timer;store;entries=new Map;sources=new Map;telemetry;requests;recorder;constructor(o,d,{telemetry:y,requests:f,recorder:h}={}){this.timer=o;this.store=d;this.telemetry=y,this.requests=f,this.recorder=h}show(o,d,y){for(let h of this.entries.values())if(h.scope.deviceId===o.deviceId&&h.id===d&&K(h.scope,d)!==K(o,d))this.remove(h);let f=this.watch(o,d,y);this.store.startShow(o,d),f.buffer.startEpoch(),f.shown=!0,f.terminal=!1,this.subscribe(o.deviceId,y)}adopt(o,d,y,{replayed:f,lastSequence:h}){let P=this.entries.get(K(o,d)),g=P?.terminal===!0&&P.buffer.status().pendingCount>0;if(P?.shown&&!P.terminal||g)this.watch(o,d,y);else this.show(o,d,y);for(let T of f)this.receive(o.deviceId,T);this.entries.get(K(o,d))?.buffer.advanceTo(h)}isDismissed(o,d){return this.entries.get(K(o,d))?.terminal??!1}counts(o,d){return this.entries.get(K(o,d))?.buffer.status()}async awaitEvent(o,d,y,f){f.signal?.throwIfAborted();let h=this.watch(o,d,y),P=this.take(h,f);if(P)return this.dropConsumedTerminal(h),this.pruneSources(),P;return this.wait(h,f)}replaceShown(o,d){for(let y of this.entries.values())if(y.scope.deviceId===o&&y.id!==d&&y.shown)this.remove(y);this.pruneSources()}dismiss(o,d){for(let y of this.entries.values())if(y.scope.deviceId===o&&(d===void 0||y.id===d))this.remove(y);this.pruneSources()}releaseSession(o){this.recorder?.endSessionRecordings?.(o);let d=new Set(this.store.clearSession(o));for(let y of d)this.recorder?.endDeviceRecordings?.(y);for(let y of this.entries.values())if(y.scope.sessionUuid===o||d.has(y.scope.deviceId))this.remove(y,"released");this.pruneSources()}releaseDevice(o){this.recorder?.endDeviceRecordings?.(o),this.store.clearDevice(o);for(let d of this.entries.values())if(d.scope.deviceId===o)this.remove(d,"released");this.pruneSources()}dispose(){for(let o of this.entries.values())this.remove(o,"released");this.pruneSources()}watch(o,d,y){let f=K(o,d),h=this.entries.get(f);if(!h){if(Array.from(this.entries.values()).some((g)=>g.scope.deviceId===o.deviceId&&g.id===d))throw new t("Prototype events belong to another session; show this id in the current session first.");h={scope:{...o},id:d,buffer:new Pt,shown:!1,terminal:!1,waiters:new Set},this.entries.set(f,h)}if(!h.terminal)this.subscribe(o.deviceId,y);return h}subscribe(o,d){let y=this.sources.get(o);if(y?.client===d)return;y?.unsubscribe(),this.sources.set(o,{client:d,unsubscribe:d.onPrototypeEvent((f)=>this.receive(o,f))})}receive(o,d){let y=Array.from(this.entries.values()).find((f)=>f.scope.deviceId===o&&f.id===d.id);if(!y||y.terminal||!y.buffer.push(d))return;try{this.recorder?.recordEvent(y.scope,d)}catch(f){e.warn("Prototype test event recording failed",f)}if(this.store.recordEvent(y.scope,d),d.kind==="dismissed")y.shown=!1,y.terminal=!0,this.requests?.cancelPrototype(y.scope.deviceId,y.id),this.store.dismissed(y.scope,y.id);for(let f of[...y.waiters])f();this.pruneSources();try{this.telemetry?.recordPrototypeEvent(y.scope,d)}catch(f){e.warn(`[PrototypeEventCoordinator] Telemetry recording failed: ${r(f)}`)}}take(o,d){let y=o.buffer.take(d);if(!y)return o.terminal?{...o.buffer.status(),reason:"dismissed"}:void 0;if(y.kind==="dismissed")o.buffer.clear();return{event:{id:y.id,sequence:y.sequence,kind:y.kind,name:y.name,payload:y.payload,...y.context===void 0?{}:{context:y.context},...y.contextTruncated===!0?{contextTruncated:!0}:{},state:y.state,pages:y.pages,...y.stacks?{stacks:structuredClone(y.stacks)}:{},timestamp:y.timestamp,...y.validity===void 0?{}:{validity:y.validity},...y.keys===void 0?{}:{keys:y.keys}},...o.buffer.status()}}async wait(o,d){let y=()=>{},f=new Promise((g)=>{y=()=>{if(d.signal?.aborted)return;let T=this.take(o,d);if(T)o.waiters.delete(y),g(T)},o.waiters.add(y)}),h,P=new Promise((g)=>{h=this.timer.setTimeout(()=>{o.waiters.delete(y),g({...o.buffer.status(),timedOut:!0})},d.timeoutMs??QS)});try{return await l([f,P],{timer:this.timer,signal:d.signal,label:"Await prototype event"})}finally{if(h!==void 0)this.timer.clearTimeout(h);if(o.waiters.delete(y),this.dropConsumedTerminal(o),!o.shown&&!o.terminal&&o.buffer.status().lastSequence===void 0&&o.waiters.size===0)this.entries.delete(K(o.scope,o.id));this.pruneSources()}}dropConsumedTerminal(o){if(o.terminal&&o.waiters.size===0&&o.buffer.status().pendingCount===0&&this.entries.get(K(o.scope,o.id))===o)this.entries.delete(K(o.scope,o.id))}remove(o,d="dismissed"){try{this.recorder?.endForDismiss(o.scope,o.id,d)}catch(y){e.warn("Prototype test session cleanup failed",y)}o.buffer.clear(),o.shown=!1,o.terminal=!0,this.requests?.cancelPrototype(o.scope.deviceId,o.id);for(let y of[...o.waiters])y();this.entries.delete(K(o.scope,o.id))}pruneSources(){for(let[o,d]of this.sources)if(!Array.from(this.entries.values()).some((f)=>f.scope.deviceId===o&&!f.terminal))d.unsubscribe(),this.sources.delete(o)}}var jn=64;function Lo(o){return o==="/data"?[]:Zp(o.slice(5))}function Yn(o,d){let y=Lo(o),f=Lo(d),h=Math.min(y.length,f.length);return y.slice(0,h).every((P,g)=>P===f[g])}class wt{revisions;sequence=0;devices=new Map;constructor(o){this.revisions=o}beginShow(o,d,y=!0,f){let h=this.devices.get(o)??{entries:new Map,dataWrites:new Map,epoch:0,issued:0,open:new Map,poisonedThrough:0};h.platform=f??h.platform;let P=++this.sequence;h.issued=P;for(let g of h.open.values())if(y||g.replaceOthers||g.id===d)g.superseded=!0;return h.open.set(P,{id:d,replaceOthers:y,superseded:!1}),h.epoch=++this.sequence,this.devices.set(o,h),P}endShow(o,d,y,f){let h=this.devices.get(o),P=h?.open.get(d);if(!h||!P)return;if(h.open.delete(d),h.epoch=++this.sequence,P.superseded)return;if(f){if(f==="indeterminate"&&P.id!==void 0)h.entries.delete(P.id),h.dataWrites.delete(P.id);return}if(y&&d>h.poisonedThrough)this.storeShown(h,y);else h.entries.clear(),h.dataWrites.clear()}storeShown(o,d){if(d.replaceOthers!==!1)o.entries.clear(),o.dataWrites.clear();if(d.spec)o.entries.set(d.id,structuredClone(d.spec)),this.revisions?.recordShow(d.id,{spec:d.spec,platform:o.platform,variant:d.variant,mcpSessionId:d.mcpSessionId});else o.entries.delete(d.id);o.dataWrites.delete(d.id)}read(o,d){let y=this.devices.get(o);if(y&&y.open.size>0)return{kind:"busy"};let f=y?.entries.get(d);return f&&y?{kind:"known",spec:f,version:y.epoch}:{kind:"unknown"}}platformOf(o){return this.devices.get(o)?.platform}devicesShowing(o){return[...this.devices.entries()].filter(([,d])=>d.entries.has(o)).map(([d])=>d).sort()}showStartedSince(o,d){return(this.devices.get(o)?.issued??0)>d}commitPatch(o,d,y,f){let h=this.devices.get(o);if(!h)return!1;let P=h.open.size===0&&h.epoch===y&&h.entries.has(d);if(P)h.entries.set(d,structuredClone(f.spec)),h.epoch=++this.sequence,this.revisions?.recordPatch(d,{spec:f.spec,platform:h.platform,deviceRevision:f.deviceRevision,mcpSessionId:f.mcpSessionId});else this.abandon(o);return P}recordDeviceDataWrite(o,d,y){let f=this.devices.get(o);if(!f)return{kind:"untracked"};if(f.open.size>0)return this.abandon(o),{kind:"dropped"};let h=f.entries.get(d);if(!h)return{kind:"untracked"};let P=y.op==="remove"?$P(h.data,{op:"remove",path:y.path}):y.value===void 0?void 0:y.op==="extend"||y.op==="prepend"?$P(h.data,{...y,value:y.value}):$P(h.data,{...y,value:y.value});if(!P?.success)return this.forget(o,d),{kind:"dropped"};f.entries.set(d,{...h,data:P.data}),f.epoch=++this.sequence;let g=f.dataWrites.get(d)??{floor:0,writes:[]};g.writes.push({path:y.path,revision:y.revision});while(g.writes.length>jn)g.floor=Math.max(g.floor,g.writes.shift().revision);return f.dataWrites.set(d,g),{kind:"mirrored",data:P.data}}dataPatchGuard(o,d,y,f){let h=this.devices.get(o)?.dataWrites.get(d);if(!h||y.length===0)return{kind:"ok"};if(f===void 0)return{kind:"baseRevisionRequired"};let P=f<h.floor,g=h.writes.filter((T)=>T.revision>f&&y.some((A)=>Yn(A,T.path)));if(!P&&g.length===0)return{kind:"ok"};return{kind:"conflict",revision:Math.max(f,h.floor,...h.writes.map((T)=>T.revision)),paths:P?[...y]:[...new Set(g.map((T)=>T.path))]}}abandon(o){let d=this.devices.get(o);if(!d)return;d.entries.clear(),d.dataWrites.clear(),d.poisonedThrough=d.issued,d.epoch=++this.sequence}forget(o,d){let y=this.devices.get(o);if(y&&(d===void 0||y.entries.has(d))){if(d===void 0)y.entries.clear(),y.dataWrites.clear();else y.entries.delete(d),y.dataWrites.delete(d);y.epoch=++this.sequence}}retainOnly(o,d){let y=this.devices.get(o);for(let f of y?.entries.keys()??[])if(f!==d)this.forget(o,f)}clearDevice(o){this.devices.delete(o)}}var Jn=["battery","power","audio"];function zn(o){return Jn.find((d)=>d===o)}function Gn(o,d){switch(d.kind){case"number":return Zb(o,d);case"boolean":return typeof o==="boolean";case"enum":return(d.values??[]).some((y)=>y===o);default:return!1}}function Kn(o){let d=o?.event.indexOf(".")??-1;return o&&!o.truncated&&o.event.slice(d+1)==="changed"?zn(o.event.slice(0,d)):void 0}function Xn(o,d){return Object.entries(o).every(([y,f])=>Object.hasOwn(d,y)&&Gn(f,d[y].value))}function qo(o){let d=Rj(o),y=Kn(d),f=Te(d?.data),h=y?Yu[y]?.state:void 0;if(!y||!f||!h||!Xn(f,h))return;return{module:y,values:{...f},...d?.simulated?{simulated:!0}:{}}}function Qn(o){return o.feedbackLog?{feedbackLog:structuredClone(o.feedbackLog)}:{}}function Zn(o){return{...o.orientation?{orientation:o.orientation}:{},...o.statusBar?{statusBar:o.statusBar}:{}}}function es(o,d){if(d===void 0)delete o.data;else o.data=structuredClone(d)}function Fo(o,d){return d===void 0||(o.revision??-1)>d?{}:{revision:d}}function No(o,d,y){return o==="show"&&d.success?{...y===void 0?{}:{data:structuredClone(y)},...d.stacks?{stacks:structuredClone(d.stacks)}:{}}:{}}var ts=128;function os(o){return{pages:{...o.pages},...o.stacks?{stacks:structuredClone(o.stacks)}:{},state:{...o.state},...o.context===void 0?{}:{context:structuredClone(o.context)},...o.contextTruncated===!0?{contextTruncated:!0}:{},lastKnown:!0}}function rs(o){if(!o)return{};return{pages:{...o.pages},...o.stacks?{stacks:structuredClone(o.stacks)}:{},state:{...o.state},...o.context===void 0?{}:{context:structuredClone(o.context)},...o.contextTruncated===!0?{contextTruncated:!0}:{},lastKnown:!0}}function ns(o,d){let{stacks:y,...f}=o;return{...f,...!d&&y?{stacks:structuredClone(y)}:{},...o.data===void 0?{}:{data:structuredClone(o.data)},...rs(d)}}class St{clock;maxScopes;scopes=new Map;showDispatches=new Map;shownSpecs;constructor(o=i,d=ts,y=new qM(o)){this.clock=o;this.maxScopes=d;this.shownSpecs=new wt(y)}status(o){let d=this.scopes.get(JSON.stringify([o.sessionUuid??null,o.deviceId]));return{prototypes:Array.from(d?.shown.values()??[],(y)=>ns(y,y.id?d?.snapshots?.get(y.id):void 0)),...d?.lastResult?{lastResult:{...d.lastResult}}:{},...d?.platformStatus?{platformStatus:structuredClone(d.platformStatus)}:{}}}shownOnDevice(o,d){for(let y of this.scopes.values()){let f=y.deviceId===o?y.shown.get(d):void 0;if(f)return structuredClone(f)}return}startShow(o,d){let y=this.scopes.get(JSON.stringify([o.sessionUuid??null,o.deviceId]));if(y)if(d===void 0)y.pendingSnapshots?.clear();else y.pendingSnapshots?.delete(d)}beginShowDispatch(o,d){let y=this.showDispatches.get(o)??new Map;y.set(d,!1),this.showDispatches.set(o,y)}adopt(o,d){let y=JSON.stringify([o.sessionUuid??null,o.deviceId]),f=this.scopes.get(y)??{...o,shown:new Map},h=this.patchedFields(o.deviceId,d.id);this.clearShown(o.deviceId,d.id);let P={id:d.id,lastAction:"show",adopted:!0,...d.persistent===void 0?{}:{persistent:d.persistent},...d.suspended===!0?{suspended:!0}:{},...d.hiddenReason?{hiddenReason:d.hiddenReason}:{},...Zn(d),...d.appearance?{appearance:{...d.appearance}}:{},...d.storage?{storage:structuredClone(d.storage)}:{},...PP(d.degradedEffects),...d.timers?{timers:structuredClone(d.timers)}:{},...Qn(d),shaderFailures:structuredClone(d.shaderFailures),success:!0,timestamp:this.clock.now()};f.lastResult=P,f.shown.set(d.id,{...P,...h,...No("show",{success:!0},d.data)}),f.pendingSnapshots?.delete(d.id),f.snapshots??=new Map,f.snapshots.set(d.id,{pages:{...d.pages},...d.stacks?{stacks:structuredClone(d.stacks)}:{},state:{...d.state},lastKnown:!0}),this.remember(y,f)}recordEvent(o,d){this.applyDeviceDataWrite(o.deviceId,d);let y=this.showDispatches.get(o.deviceId);if(y?.has(d.id)&&d.kind==="appearance_changed"&&H9(void 0,d.payload))y.set(d.id,!0);let f=JSON.stringify([o.sessionUuid??null,o.deviceId]),h=this.scopes.get(f)??{...o,shown:new Map};this.recordDeviceStatus(h,d),h.pendingSnapshots??=new Map;let P=os(d);h.pendingSnapshots.set(d.id,P);let g=h.shown.get(d.id);if(g){if(h.snapshots??=new Map,h.snapshots.set(d.id,P),d.kind==="appearance_changed")this.recordAppearanceChange(h,g,d)}this.remember(f,h)}recordDeviceStatus(o,d){let y=qo(d),f=y?o.platformStatus?.[y.module]:void 0;if(y&&!(f&&f.timestamp>d.timestamp))o.platformStatus={...o.platformStatus,[y.module]:{values:y.values,timestamp:d.timestamp,receivedAt:this.clock.now(),...y.simulated?{simulated:!0}:{}}}}recordAppearanceChange(o,d,y){let f=H9(d.appearance,y.payload);if(f)o.shown.set(y.id,{...d,appearance:f})}record(o,d,y,{result:f,details:h={}}){let{displayId:P}=h,g=JSON.stringify([o.sessionUuid??null,o.deviceId]),T=this.scopes.get(g),A=d!=="show"&&y.id!==void 0?T?.shown.get(y.id)?.displayId:void 0,C=this.createResult(d,y,f,{displayId:P??A,chrome:h.chrome}),I=this.consumeShowDispatch(o.deviceId,C);if(!T&&!f.success)return structuredClone(C);let O=T??{...o,shown:new Map,lastResult:C};return O.lastResult=C,this.updatePresence(O,{...I,...No(d,f,h.data)},h.replaceOthers),this.remember(g,O),structuredClone(C)}applyDeviceDataWrite(o,d){let y=wj(d);if(!y)return;this.shownSpecs.recordDeviceDataWrite(o,d.id,y);for(let f of this.scopes.values()){let h=f.deviceId===o?f.shown.get(d.id):void 0;if(!h)continue;let P=y.op==="remove"?$P(h.data,{op:"remove",path:y.path}):y.value===void 0?void 0:y.op==="extend"||y.op==="prepend"?$P(h.data,{...y,value:y.value}):$P(h.data,{...y,value:y.value}),g={...h,...Fo(h,y.revision)};if(P?.success)g.data=P.data;else delete g.data;f.shown.set(d.id,g)}}recordPatch(o,d,y){let{data:f,revision:h}=y;for(let P of this.scopes.values()){let g=P.deviceId===o?P.shown.get(d):void 0;if(g){let T={...g,lastAction:"patch",...Fo(g,h)};if(Object.hasOwn(y,"data"))es(T,f);P.shown.set(d,T)}}}forgetStorage(o,d){for(let y of this.scopes.values()){if(y.deviceId!==o)continue;let f=y.shown.get(d);if(f?.storage)y.shown.set(d,{...f,storage:void 0});if(y.lastResult?.id===d&&y.lastResult.storage)y.lastResult={...y.lastResult,storage:void 0}}}consumeShowDispatch(o,d){if(d.lastAction!=="show"||!d.success||!d.id)return d;let y=this.showDispatches.get(o),f=y?.get(d.id);if(y?.delete(d.id),y?.size===0)this.showDispatches.delete(o);if(!f)return d;let h={...d};return delete h.appearance,h}remember(o,d){this.scopes.delete(o),this.scopes.set(o,d);for(let y of this.scopes.keys()){if(this.scopes.size<=this.maxScopes)break;this.scopes.delete(y)}}updatePresence(o,d,y){if(d.lastAction==="show"&&d.success&&d.id)this.showPresence(o,d,y);else if(d.lastAction==="dismiss"&&d.success){if(this.shownSpecs.forget(o.deviceId,d.all?void 0:d.id),d.all)this.clearShown(o.deviceId);else if(d.id)this.clearShown(o.deviceId,d.id)}}showPresence(o,d,y){if(!d.id)return;let f=o.pendingSnapshots?.get(d.id);if(this.clearShown(o.deviceId,y===!1?d.id:void 0),o.snapshots??=new Map,f)o.snapshots.set(d.id,f);o.shown.set(d.id,d)}clearDevice(o){this.shownSpecs.clearDevice(o),this.showDispatches.delete(o);for(let[d,y]of this.scopes)if(y.deviceId===o)this.scopes.delete(d)}clearSession(o){let d=new Set(Array.from(this.scopes.values()).filter((y)=>y.sessionUuid===o&&y.lastResult!==void 0).map((y)=>y.deviceId));for(let y of d)this.clearDevice(y);for(let[y,f]of this.scopes)if(f.sessionUuid===o)this.scopes.delete(y);return Array.from(d)}dismissed(o,d){this.shownSpecs.forget(o.deviceId,d),this.clearShown(o.deviceId,d)}patchedFields(o,d){for(let y of this.scopes.values()){let f=y.deviceId===o?y.shown.get(d):void 0;if(f?.lastAction==="patch"||f?.revision!==void 0)return{...f.lastAction==="patch"?{lastAction:"patch"}:{},...f.revision===void 0?{}:{revision:f.revision}}}return{}}shownIds(o){let d=new Set;for(let y of this.scopes.values())if(y.deviceId===o)for(let f of y.shown.keys())d.add(f);return Array.from(d)}createResult(o,d,y,{displayId:f,chrome:h}={}){return{...d,lastAction:o,...f===void 0?{}:{displayId:f},...o==="show"&&y.success&&h!==void 0?{chrome:h}:{},...R2(o,y),...OK(o,y),success:y.success,...y.error?{error:y.error}:{},...y.totalTimeMs===void 0?{}:{totalTimeMs:y.totalTimeMs},timestamp:this.clock.now()}}clearShown(o,d){for(let y of this.scopes.values()){if(y.deviceId!==o)continue;if(d===void 0)y.pendingSnapshots?.clear(),y.snapshots?.clear();else y.pendingSnapshots?.delete(d),y.snapshots?.delete(d);if(d===void 0)y.shown.clear();else y.shown.delete(d)}}}class bt{client;constructor(o){this.client=o}async show(o,d={}){return Doe(await this.client.requestShowPrototype(o,d.timeoutMs,void 0,{displayId:d.displayId,reset:d.reset,appearance:d.appearance,replaceOthers:d.replaceOthers,locale:o.strings?d.locale:void 0}))}patch(o,d){return this.client.requestPatchPrototype(o,d)}inspect(o){return this.client.requestInspectPrototypes(o)}save(o,d){return this.client.requestSavePrototype(o,d)}listSaved(o){return this.client.requestListSavedPrototypes(o)}pinSaved(o,d,y){return this.client.requestPinSavedPrototype(o,d,y)}deleteSaved(o,d){return this.client.requestDeleteSavedPrototype(o,d)}dismiss(o,d){return this.client.requestDismissPrototype(o,d)}advanceClock(o,d,y){if(!this.client.requestAdvancePrototypeClock)throw new t("Update the connected CtrlProxy to simulate prototype timers");return this.client.requestAdvancePrototypeClock(o,d,y)}clearStorage(o,d){if(!this.client.requestClearPrototypeStorage)throw new t(Xb("android"));return this.client.requestClearPrototypeStorage(o,d)}putAsset(o,d){return this.client.requestPutPrototypeAsset(o,d)}removeAsset(o,d){return this.client.requestRemovePrototypeAsset(o,d)}async status(){return{success:!1,error:"CtrlProxy has no prototype status request; use the host-local status action."}}onEvent(o){return this.client.onPrototypeEvent(o)}supportsCommand(o){return this.client.supportsCommand(o)}}import{Agent as ss,request as is}from"http";import{Agent as ps,request as ds}from"https";import{isIP as cs}from"net";import{checkServerIdentity as us}from"tls";import{createBrotliDecompress as ls,createGunzip as ys,createInflate as fs}from"zlib";class se extends Error{}function ms(o){let d=o.headers["content-encoding"]?.toLowerCase(),y=d==="gzip"?ys():d==="deflate"?fs():d==="br"?ls():void 0;if(!y)return o;return o.once("error",(f)=>y.destroy(f)),y.once("close",()=>o.destroy()),o.pipe(y)}function hs(o,d,y){let f=new Headers;for(let C=0;C<o.rawHeaders.length;C+=2)f.append(o.rawHeaders[C],o.rawHeaders[C+1]);let h=o.statusCode??502;if(d==="HEAD"||[204,205,304].includes(h))return o.destroy(),new Response(null,{status:h,headers:f});let P=ms(o);if(P!==o)f.delete("content-encoding"),f.delete("content-length");let g=P[Symbol.asyncIterator](),T=0,A=new ReadableStream({async pull(C){let{done:I,value:O}=await g.next();if(I)C.close();else if(O instanceof Uint8Array)if(T+=O.byteLength,T>y)P.destroy(),o.destroy(),C.error(new se);else C.enqueue(O);else C.error(Error("Unexpected response chunk type.")),P.destroy(),o.destroy()},async cancel(){o.destroy(),P.destroy(),await g.return?.()}});return new Response(A,{status:h,headers:f})}function Ps(o=(f,h)=>(f.protocol==="https:"?ds:is)(f,h),d=process.env,y=process.versions.bun?"bun":"node"){return(f,h,P,g)=>{if(h.signal?.throwIfAborted(),y==="bun"&&(["HTTP_PROXY","http_proxy","HTTPS_PROXY","https_proxy","ALL_PROXY","all_proxy"].some((I)=>Boolean(d[I]))||Object.entries(d).some(([I,O])=>/^(http|https|all)_proxy$/i.test(I)&&Boolean(O))))return Promise.reject(Error("Pinned transport requires a direct connection."));let T=new URL(f),A=T.hostname.replace(/^\[|\]$/g,""),C=new Headers(h.headers);if(C.set("Host",T.host),!C.has("accept-encoding"))C.set("Accept-Encoding","gzip, deflate, br");return new Promise((I,O)=>{let _=T.protocol==="https:"?new ps({proxyEnv:{}}):new ss({proxyEnv:{}}),x,F=()=>{h.signal?.removeEventListener("abort",D),_.destroy()},q=o({protocol:T.protocol,host:P.address,family:P.family,port:T.port||(T.protocol==="https:"?443:80),path:T.pathname+T.search,method:h.method,headers:Object.fromEntries(C),servername:cs(A)?void 0:A,checkServerIdentity:(M,j)=>us(A,j),agent:_},(M)=>{if(x=M,M.once("close",F),M.statusCode===void 0||M.statusCode<200||M.statusCode>599){M.destroy(),O(Error("Invalid HTTP response status."));return}I(hs(M,h.method,g))}),D=()=>{let M=Error("Request cancelled.");F(),x?.destroy(M),q.destroy(M),O(M)};if(h.signal?.addEventListener("abort",D,{once:!0}),q.on("error",(M)=>{F(),O(M)}),q.on("upgrade",(M,j)=>{j.destroy(),F(),O(Error("Protocol upgrades are not supported."))}),h.signal?.aborted)D();else q.end(h.body)})}}var qe=Ps();import{lookup as gs}from"dns/promises";import{isIP as Rt}from"net";var fe=(o)=>gs(o,{all:!0,verbatim:!0});async function he(o,d,y){if(o.username||o.password)return{code:"invalid_request",message:"URL credentials are not permitted."};let f=wse(o,d.policy);if(f!==void 0)return{code:"blocked_destination",message:f};let h=o.hostname.replace(/^\[|\]$/g,""),P=Rt(h),g=P?[{address:h,family:P}]:await l(()=>d.resolver(h),{timer:d.timer,signal:y,label:"Prototype destination resolution"});if(y.throwIfAborted(),g.length===0)return{code:"network",message:"The destination did not resolve to an address."};if(g.some(({address:T,family:A})=>!Rt(T)||Rt(T)!==A||!d.policy.permitsAddress(T,A8(o))))return{code:"blocked_destination",message:"The destination is not permitted."};return g[0]}var vs=new Set([301,302,303,307,308]),ws=5,$o=new Set(["GET","HEAD"]),Ss=new Set(["content-type","content-encoding","content-language","content-location"]);function At(o){if(Array.isArray(o))return`[${o.map(At).join(",")}]`;if(typeof o==="object"&&o!==null)return`{${Object.keys(o).sort().map((y)=>`${JSON.stringify(y)}:${At(o[y])}`).join(",")}}`;return JSON.stringify(o)}function bs(o,d){return Object.keys(o).some((y)=>y.toLowerCase()===d)}function Rs(o){let d=o,y=d?.code??d?.cause?.code;return y==="ECONNREFUSED"||y==="ConnectionRefused"}var kt=Symbol("too_large"),Vo=Symbol("literal_null");function Ct(o){if(typeof o==="number")return!Number.isFinite(o);if(Array.isArray(o))return o.some(Ct);return typeof o==="object"&&o!==null&&Object.values(o).some(Ct)}function ks(o){if(o.length===0)return null;try{let d=JSON.parse(o);if(Ct(d))return o;return d===null?Vo:d}catch(d){return e.debug("[PrototypeHttpExecutor] body is not JSON."),o}}var Es=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ts=/[\0\r\n]/;function Ot(o){if(kK(o)!==void 0)return"A request header is not permitted.";for(let[d,y]of Object.entries(o??{})){if(!Es.test(d))return"Header name is not an HTTP token.";if(Ts.test(y))return"A header value contains a CR, LF or NUL character."}return}function Ho(o){let d=As(o.url);if(d!==void 0)return{code:"invalid_url",message:d};let y=Ot(o.headers);return y===void 0?void 0:{code:"invalid_request",message:y}}function As(o){try{let d=new URL(o);return d.protocol==="http:"||d.protocol==="https:"?void 0:`Only http and https URLs are supported, got ${d.protocol}`}catch(d){return e.debug("[PrototypeHttpExecutor] URL parse failed."),"Not an absolute HTTP URL."}}function Cs(o,d,y,f){let h={...o,headers:y.origin===f.origin?o.headers:void 0};if(!((d===301||d===302)&&o.method==="POST"||d===303&&!$o.has(o.method)))return h;let g=h.headers===void 0?void 0:Object.fromEntries(Object.entries(h.headers).filter(([T])=>!Ss.has(T.toLowerCase())));return{...h,method:"GET",body:void 0,headers:g}}function Os(o,d){try{return new URL(o,d)}catch(y){e.debug("[PrototypeHttpExecutor] redirect URL parse failed.");return}}function Tt(o,d,y){return{ok:!1,error:{code:o,message:d},durationMs:y}}function Is(o,d){let y=new Uint8Array(d),f=0;for(let h of o)y.set(h,f),f+=h.byteLength;return y}class It{options;fetchImpl;maxBytes;policy;resolver;constructor(o){this.options=o;this.fetchImpl=o.fetch??qe,this.maxBytes=o.maxResponseBytes??de,this.policy=o.policy??new EE(HE),this.resolver=o.resolver??fe}async execute(o,d){let{timer:y}=this.options,f=y.now(),h=(O,_)=>({ok:!1,error:{code:O,message:_},durationMs:y.now()-f}),P=Ho(o);if(P!==void 0)return h(P.code,P.message);if(d.aborted)return h("cancelled","Request was cancelled before it started.");let g=Math.min(o.timeoutMs??te,xe),T=new AbortController,A=!1,C=y.setTimeout(()=>{A=!0,T.abort()},g),I=AbortSignal.any([d,T.signal]);try{let O=await this.fetchResponse(o,I,f);if(!("response"in O))return O;return await this.outcomeOf(O.response,O.method,I,f)}catch(O){let _=Rs(O);if(e.warn("[PrototypeHttpExecutor] request could not complete.",{connectionRefused:_,aborted:I.aborted,timedOut:A}),I.aborted)return A?h("timeout",`Request timed out after ${g}ms.`):h("cancelled","Request was cancelled.");if(_)return h("connection_refused","Connection refused.");if(O instanceof se)return h("too_large",`Response body exceeds ${this.maxBytes} bytes.`);return h("network","The request could not complete.")}finally{y.clearTimeout(C)}}async fetchResponse(o,d,y){let f=o,h=new URL(f.url),P=(g,T)=>Tt(g,T,this.options.timer.now()-y);for(let g=0;;g++){d.throwIfAborted();let T=Ho({...f,url:h.href});if(T!==void 0)return P(T.code,T.message);let A=await this.pinDestination(h,d);if("code"in A)return P(A.code,A.message);d.throwIfAborted();let C=await this.fetchImpl(h.href,this.requestInit(f,d),A,this.maxBytes);if(!vs.has(C.status))return{response:C,method:f.method};if(await C.body?.cancel(),g===ws)return P("network","Too many redirects.");let I=C.headers.get("location");if(!I)return P("invalid_response","Redirect response has no Location header.");let O=Os(I,h);if(O===void 0)return P("invalid_response","Redirect Location is not a valid URL.");if(h.protocol==="https:"&&O.protocol==="http:")return P("blocked_destination","The destination is not permitted: scheme downgrade.");f=Cs(f,C.status,h,O),h=O}}pinDestination(o,d){return he(o,{policy:this.policy,resolver:this.resolver,timer:this.options.timer},d)}async outcomeOf(o,d,y,f){let h=()=>this.options.timer.now()-f,P=Object.fromEntries(o.headers.entries());if(o.status<200||o.status>299)return await o.body?.cancel(),{ok:!0,status:o.status,headers:P,body:null,durationMs:h()};let g=await this.readBody(o,d,y);if(g===kt)return Tt("too_large",`Response body exceeds ${this.maxBytes} bytes.`,h());if(g===Vo)return Tt("invalid_response","A response body of JSON null cannot be stored in /data.",h());return{ok:!0,status:o.status,headers:P,body:g,durationMs:h()}}requestInit(o,d){let y={...o.headers},f;if(o.body!==void 0&&!$o.has(o.method)){if(typeof o.body==="string")f=o.body;else if(f=At(o.body),!bs(y,"content-type"))y["Content-Type"]="application/json"}return{method:o.method,headers:y,body:f,signal:d,redirect:"manual"}}async readBody(o,d,y){let f=Number(o.headers.get("content-length"));if(Number.isFinite(f)&&f>this.maxBytes)return await o.body?.cancel(),kt;if(d==="HEAD"||o.body===null)return null;let h=o.body.getReader(),P=[],g=0;for(;;){y.throwIfAborted();let{done:T,value:A}=await l(()=>h.read(),{timer:this.options.timer,signal:y,label:"Prototype response body"});if(T)break;if(g+=A.byteLength,g>this.maxBytes)return await h.cancel(),kt;P.push(A)}return ks(new TextDecoder().decode(Is(P,g)))}}function _s(o){if(typeof o!=="string")return o;try{return JSON.parse(o)}catch(d){return e.debug("[PrototypeMock] request body is not JSON."),o}}var Uo=Symbol("mock request timed out");class Mt{inner;registry;timer;constructor(o,d,y){this.inner=o;this.registry=d;this.timer=y}async execute(o,d){let y=Ie(o.url);if(y===void 0)return this.inner.execute(o,d);let f=this.timer.now(),h=()=>this.timer.now()-f,P=this.registry.get(y.backendId);if(P===void 0)return{ok:!1,error:{code:"network",message:`No mock backend "${y.backendId}" is defined.`},durationMs:h()};if(d.aborted)return{ok:!1,error:{code:"cancelled",message:"Request was cancelled before it started."},durationMs:h()};let g=Math.min(o.timeoutMs??te,xe),T=new AbortController,A=AbortSignal.any([d,T.signal]),C;try{C=await l(()=>P.answer({method:o.method,path:y.path,query:y.query,body:_s(o.body)},A),{timer:this.timer,timeoutMs:g,signal:d,label:"Mock request",timeoutError:()=>Uo,onTimeout:()=>T.abort()})}catch(I){return this.failure(I,d,g,h())}if(Buffer.byteLength(JSON.stringify(C.body))>de)return{ok:!1,error:{code:"too_large",message:`Response body exceeds ${de} bytes.`},durationMs:h()};return{ok:!0,status:C.status,headers:C.headers,body:o.method==="HEAD"?null:C.body,durationMs:h()}}failure(o,d,y,f){if(o instanceof De)return{ok:!1,error:{code:"too_large",message:o.message},durationMs:f};if(o===Uo)return{ok:!1,error:{code:"timeout",message:`Request timed out after ${y}ms.`},durationMs:f};if(d.aborted)return{ok:!1,error:{code:"cancelled",message:"Request was cancelled."},durationMs:f};return e.warn(`[PrototypeMock] backend failed: ${r(o)}`,o),{ok:!1,error:{code:"network",message:"The mock backend failed."},durationMs:f}}}class xt{executor;maxInFlight;inFlight=new Set;constructor(o,d=ko){this.executor=o;this.maxInFlight=d}inFlightCount(o){return[...this.inFlight].filter((d)=>o===void 0||d.deviceId===o).length}async run(o,d){if(this.inFlightCount(o.deviceId)>=this.maxInFlight)return{ok:!1,error:{code:"too_many_in_flight",message:`At most ${this.maxInFlight} requests may be in flight per device.`},durationMs:0};let y={...o,controller:new AbortController};this.inFlight.add(y);try{return await this.executor.execute(d,y.controller.signal)}finally{this.inFlight.delete(y)}}cancelPrototype(o,d){this.cancelWhere((y)=>y.deviceId===o&&y.prototypeId===d)}cancelDevice(o){this.cancelWhere((d)=>d.deviceId===o)}cancelRequest(o,d){let y=(h)=>h.connection===o&&h.requestId===d,f=[...this.inFlight].some(y);return this.cancelWhere(y),f}cancelConnection(o){this.cancelWhere((d)=>d.connection===o)}cancelWhere(o){for(let d of[...this.inFlight].filter(o))e.debug(`[PrototypeRequest] cancelling ${d.deviceId}/${d.prototypeId}`),this.inFlight.delete(d),d.controller.abort()}}function Bo(o,d){return new xt(new Mt(new It({timer:o}),d,o))}function Wo(o,d,y){if(y!==void 0)o.attachRequestHost?.(WY(d,y))}function jo(o,d,y){if(y!==void 0)o.attachPrototypeRequestHost?.(WY(d,y))}var xs=/^(sec-websocket-|last-event-id$)/i,Yo={websocket:["ws:","wss:"],sse:["http:","https:"]};function Pe(o){let d;try{d=new URL(o.url)}catch(f){return e.debug("[PrototypeChannel] URL parse failed."),{code:"invalid_url",message:"Not an absolute URL."}}if(!Yo[o.kind].includes(d.protocol))return{code:"invalid_url",message:`A ${o.kind} channel needs a ${Yo[o.kind].join(" or ")} URL, got ${d.protocol}`};let y=Ot(o.headers);if(y!==void 0)return{code:"invalid_request",message:y};if(Object.keys(o.headers??{}).some((f)=>xs.test(f)))return{code:"invalid_request",message:"A request header is not permitted."};return}class Dt{webSocket;sse;constructor(o,d){this.webSocket=o;this.sse=d}open(o,d,y){return(o.kind==="websocket"?this.webSocket:this.sse).open(o,d,y)}}function ge(o){let d=!1;return{isClosed:()=>d,silence:()=>{d=!0},sink:{opened:(y)=>{if(!d)o.opened(y)},frame:(y)=>{if(!d)o.frame(y)},closed:(y)=>{if(!d)d=!0,o.closed(y)}}}}var He={send:()=>({ok:!1,reason:"not_open"}),close:()=>{}};class Lt{inner;registry;constructor(o,d){this.inner=o;this.registry=d}open(o,d,y){if(y.aborted)return He;let f=Ds(o.url);if(f===void 0)return this.inner.open(o,d,y);let h=Pe(o);if(h!==void 0)return d.closed({error:h}),He;let P=this.registry.get(f.backendId);if(P===void 0)return d.closed({error:{code:"network",message:`No mock backend "${f.backendId}" is defined.`}}),He;return Ls({backend:P,request:o,target:f},d,y)}}function Ds(o){let d=URL.canParse(o)?new URL(o):void 0;if(d?.protocol==="ws:"||d?.protocol==="wss:")d.protocol=d.protocol==="ws:"?"http:":"https:";return Ie(d?.href??o)}function Ls({backend:o,request:d,target:y},f,h){let{sink:P,silence:g}=ge(f),T=[],A=o.join(y.path,y.query,{deliver:(O)=>T===void 0?P.frame({data:O}):T.push(O),close:(O,_)=>P.closed(d.kind==="websocket"?{code:O,reason:_}:{})});if(!A.ok)return P.closed({error:{code:"handshake_failed",message:A.message,status:A.status}}),He;let{connection:C}=A;P.opened(d.kind==="websocket"?d.protocols?.[0]:void 0);let I=T;return T=void 0,I.forEach((O)=>P.frame({data:O})),h.addEventListener("abort",()=>{C.leave(),g()},{once:!0}),{send:(O)=>{if(d.kind!=="websocket")return{ok:!1,reason:"unsupported"};if(Buffer.byteLength(O)>ZO)return{ok:!1,reason:"too_large"};return C.send(O)},close:(O,_)=>{C.leave(),P.closed({code:O??1000,..._===void 0?{}:{reason:_}})}}}class qt{executor;maxOpen;open_=new Set;constructor(o,d=Qse){this.executor=o;this.maxOpen=d}openCount(o){return[...this.open_].filter((d)=>o===void 0||d.deviceId===o).length}open(o,d,y){if(this.find(o.connection,o.connectionId)!==void 0)return{ok:!1,error:{code:"invalid_request",message:"That connection id is already open."}};if(this.openCount(o.deviceId)>=this.maxOpen)return{ok:!1,error:{code:"too_many_in_flight",message:`At most ${this.maxOpen} channels may be open per device.`}};let f=new AbortController,h={...o,controller:f};return this.open_.add(h),h.handle=this.executor.open(d,{opened:(P)=>y.opened(P),frame:(P)=>y.frame(P),closed:(P)=>{this.open_.delete(h),y.closed(P)}},f.signal),{ok:!0}}send(o,d,y){return this.find(o,d)?.handle.send(y)}close(o,d,y,f){let h=this.find(o,d);return h?.handle.close(y,f),h!==void 0}cancelPrototype(o,d){this.cancelWhere((y)=>y.deviceId===o&&y.prototypeId===d)}cancelDevice(o){this.cancelWhere((d)=>d.deviceId===o)}cancelConnection(o){this.cancelWhere((d)=>d.connection===o)}find(o,d){return[...this.open_].find((y)=>y.connection===o&&y.connectionId===d)}cancelWhere(o){for(let d of[...this.open_].filter(o))e.debug(`[PrototypeChannel] cancelling ${d.deviceId}/${d.prototypeId}`),this.open_.delete(d),d.controller.abort()}}class Ft{handlers;buffer="";pendingCr=!1;atStart=!0;eventName="";dataLines=[];hasData=!1;lastEventId="";constructor(o){this.handlers=o}get pendingChars(){let o=this.dataLines.reduce((d,y)=>d+y.length,0);return this.buffer.length+o+Math.max(0,this.dataLines.length-1)+this.eventName.length+this.lastEventId.length}seedLastEventId(o){this.lastEventId=o}push(o){let d=o;if(this.atStart&&d.length>0)this.atStart=!1,d=d.startsWith("\uFEFF")?d.slice(1):d;for(let y of d){if(this.pendingCr){if(this.pendingCr=!1,y===`
5
+ `)continue}if(y==="\r")this.pendingCr=!0,this.endLine();else if(y===`
6
+ `)this.endLine();else this.buffer+=y}}endLine(){let o=this.buffer;if(this.buffer="",o===""){this.dispatch();return}if(o.startsWith(":"))return;let d=o.indexOf(":"),y=d===-1?o:o.slice(0,d),f=d===-1?"":o.slice(d+1);if(f.startsWith(" "))f=f.slice(1);this.applyField(y,f)}applyField(o,d){if(o==="event")this.eventName=d;else if(o==="data")this.dataLines.push(d),this.hasData=!0;else if(o==="id"){if(!d.includes("\x00"))this.lastEventId=d}else if(o==="retry"&&/^[0-9]+$/.test(d))this.handlers.onRetry?.(Number(d))}dispatch(){let o=this.eventName,d=this.hasData,y=this.dataLines.join(`
7
+ `);if(this.eventName="",this.dataLines=[],this.hasData=!1,!d)return;this.handlers.onEvent({...o===""?{}:{event:o},data:y,...this.lastEventId===""?{}:{id:this.lastEventId}})}}var qs=new Set([301,302,303,307,308]),Fs=5,Ns=Number.MAX_SAFE_INTEGER,$s=6;class Nt{options;pinning;fetchImpl;constructor(o){this.options=o;this.fetchImpl=o.fetch??qe,this.pinning={policy:o.policy??new EE(HE),resolver:o.resolver??fe,timer:o.timer}}open(o,d,y){let f=ge(d),h=new AbortController,P=AbortSignal.any([y,h.signal]);return y.addEventListener("abort",()=>f.silence(),{once:!0}),this.run(o,f.sink,P,h),{send:()=>({ok:!1,reason:"unsupported"}),close:(g,T)=>{f.sink.closed({...g===void 0?{}:{code:g},...T===void 0?{}:{reason:T}}),h.abort()}}}async run(o,d,y,f){let h=Pe(o);if(h!==void 0){d.closed({error:h});return}let P=!1,g=this.options.timer.setTimeout(()=>{P=!0,f.abort()},te);try{let T=await this.connect(o,y);if(this.options.timer.clearTimeout(g),"code"in T){d.closed({error:T});return}d.opened(),await this.pump(T,o,d,y),d.closed({})}catch(T){if(this.options.timer.clearTimeout(g),y.aborted&&!P)return;d.closed({error:this.failureOf(T,P)})}}failureOf(o,d){if(d)return{code:"timeout",message:"The event stream handshake timed out."};if(o instanceof se)return{code:"too_large",message:`An event exceeded ${Wl} bytes.`};e.warn(`[PrototypeChannel] event stream failed: ${r(o)}`);let y=o;return(y?.code??y?.cause?.code)==="ECONNREFUSED"?{code:"connection_refused",message:"Connection refused."}:{code:"network",message:"The event stream failed."}}async connect(o,d){let y=new URL(o.url),f=this.requestHeaders(o,o.headers);for(let h=0;;h++){d.throwIfAborted();let P=await he(y,this.pinning,d);if("code"in P)return P;let g=await this.fetchImpl(y.href,{method:"GET",headers:f,signal:d,redirect:"manual"},P,Ns);if(!qs.has(g.status))return this.acceptStream(g);await g.body?.cancel();let T=Vs(g,y);if(h===Fs||T===void 0)return{code:"network",message:"Too many redirects or an invalid redirect."};if(y.protocol==="https:"&&T.protocol==="http:")return{code:"blocked_destination",message:"The destination is not permitted: scheme downgrade."};if(y.origin!==T.origin)f=this.requestHeaders(o,void 0);y=T}}requestHeaders(o,d){return{...d,Accept:"text/event-stream","Cache-Control":"no-cache",...o.lastEventId===void 0?{}:{"Last-Event-ID":o.lastEventId}}}async acceptStream(o){let d=o.headers.get("content-type")??"";if(o.status===200&&d.toLowerCase().startsWith("text/event-stream"))return o;return await o.body?.cancel(),{code:"handshake_failed",message:o.status===200?"The server did not answer with text/event-stream.":`The server answered the event stream with HTTP ${o.status}.`,status:o.status}}async pump(o,d,y,f){if(o.body===null)return;let h=new Ft({onEvent:(A)=>{if(Buffer.byteLength(A.data)+Buffer.byteLength(A.event??"")+Buffer.byteLength(A.id??"")>Wl)throw new se;y.frame(A)}});if(d.lastEventId!==void 0)h.seedLastEventId(d.lastEventId);let P=new TextDecoder,g=o.body.getReader(),T=()=>void g.cancel().catch(()=>{return});f.addEventListener("abort",T,{once:!0});try{for(;;){f.throwIfAborted();let{done:A,value:C}=await g.read();if(A)return;if(h.push(P.decode(C,{stream:!0})),h.pendingChars>Wl+$s)throw new se}}finally{f.removeEventListener("abort",T),await g.cancel().catch((A)=>{e.debug(`[PrototypeChannel] event stream cancel failed: ${r(A)}`)})}}}function Vs(o,d){let y=o.headers.get("location");if(!y)return;try{return new URL(y,d)}catch(f){e.debug("[PrototypeChannel] redirect URL parse failed.");return}}import Us from"ws";var Bs=25000,Ws=1000,js=1001,Jo=(o,d)=>{let y=new Us(o.url,o.protocols,{headers:o.headers,followRedirects:!1,handshakeTimeout:o.handshakeTimeoutMs,maxPayload:o.maxPayload,lookup:(f,h,P)=>{let g={address:o.pinned.address,family:o.pinned.family};if(h.all)P(null,[g]);else P(null,g.address,g.family)}});return y.on("open",()=>d.open(y.protocol)),y.on("message",(f,h)=>{if(!h)d.message(f.toString())}),y.on("pong",()=>d.pong()),y.on("close",(f,h)=>d.close(f,h.toString())),y.on("unexpected-response",(f,h)=>{h.resume(),d.unexpectedResponse(h.statusCode??0)}),y.on("error",(f)=>{if(f.code==="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")d.tooLarge();else d.error(f)}),y};class Ht{request;guarded;signal;socket;isOpen=!1;awaitingPong=!1;handshakeTimer;deadline=new AbortController;pingTimer;sink;timer;socketFactory;pinning;constructor(o,d,y,{timer:f,socketFactory:h,pinning:P}){this.request=o;this.guarded=d;this.signal=y;this.timer=f,this.socketFactory=h,this.pinning=P,this.sink=d.sink,y.addEventListener("abort",()=>this.abort(),{once:!0})}async start(){let o=Pe(this.request);if(o!==void 0){this.fail(o);return}this.handshakeTimer=this.timer.setTimeout(()=>{this.deadline.abort(),this.fail({code:"timeout",message:"The WebSocket handshake timed out."})},te);try{let d=await he(new URL(this.request.url),this.pinning,AbortSignal.any([this.signal,this.deadline.signal]));if(this.signal.aborted||this.guarded.isClosed())return;if("code"in d){this.fail(d);return}this.connect(d)}catch(d){if(!this.signal.aborted&&!this.deadline.signal.aborted)e.warn(`[PrototypeChannel] websocket could not start: ${r(d)}`,d),this.fail({code:"network",message:"The connection could not be started."})}}send(o){if(!this.isOpen||this.socket===void 0)return{ok:!1,reason:"not_open"};if(Buffer.byteLength(o)>ZO)return{ok:!1,reason:"too_large"};return this.socket.send(o),{ok:!0}}close(o=Ws,d){if(this.socket===void 0){this.deadline.abort(),this.cleanup(),this.sink.closed({code:o,...d===void 0?{}:{reason:d}});return}this.socket.close(o,d)}connect(o){this.socket=this.socketFactory({url:this.request.url,protocols:this.request.protocols??[],headers:this.request.headers??{},pinned:o,handshakeTimeoutMs:te,maxPayload:Wl},this.events())}events(){return{open:(o)=>{this.clearHandshakeTimer(),this.isOpen=!0,this.pingTimer=this.timer.setInterval(()=>this.ping(),Bs),this.sink.opened(o===""?void 0:o)},message:(o)=>{if(Buffer.byteLength(o)>Wl)this.tooLarge();else this.sink.frame({data:o})},pong:()=>{this.awaitingPong=!1},close:(o,d)=>{this.cleanup(),this.sink.closed({code:o,...d===""?{}:{reason:d}})},tooLarge:()=>this.tooLarge(),unexpectedResponse:(o)=>this.fail({code:"handshake_failed",message:`The server answered the WebSocket upgrade with HTTP ${o}.`,status:o}),error:(o)=>{e.warn("[PrototypeChannel] websocket error.",{name:o.name}),this.fail(o.code==="ECONNREFUSED"?{code:"connection_refused",message:"Connection refused."}:{code:"network",message:"The connection failed."})}}}ping(){if(this.awaitingPong){this.fail({code:"network",message:"The server stopped answering pings."});return}this.awaitingPong=!0,this.socket?.ping()}tooLarge(){this.fail({code:"too_large",message:`A frame exceeded ${Wl} bytes.`})}abort(){this.guarded.silence(),this.cleanup(),this.socket?.close(js,"Cancelled"),this.socket?.terminate()}fail(o){this.cleanup(),this.sink.closed({error:o}),this.socket?.terminate()}clearHandshakeTimer(){if(this.handshakeTimer!==void 0)this.timer.clearTimeout(this.handshakeTimer),this.handshakeTimer=void 0}cleanup(){if(this.clearHandshakeTimer(),this.pingTimer!==void 0)this.timer.clearInterval(this.pingTimer),this.pingTimer=void 0;this.isOpen=!1}}class $t{options;policy;resolver;socketFactory;constructor(o){this.options=o;this.policy=o.policy??new EE(HE),this.resolver=o.resolver??fe,this.socketFactory=o.socketFactory??Jo}open(o,d,y){let f=new Ht(o,ge(d),y,{timer:this.options.timer,socketFactory:this.socketFactory,pinning:{policy:this.policy,resolver:this.resolver,timer:this.options.timer}});return f.start(),f}}function zo(o,d,y=new Dt(new $t({timer:o}),new Nt({timer:o}))){return new qt(new Lt(y,d))}function Go(...o){return{cancelPrototype:(d,y)=>o.forEach((f)=>f.cancelPrototype(d,y)),cancelDevice:(d)=>o.forEach((y)=>y.cancelDevice(d))}}function Ko(o,d,y){if(y!==void 0)o.attachChannelHost?.(VY(d,y))}function Xo(o,d,y){if(y!==void 0)o.attachPrototypeChannelHost?.(VY(d,y))}import{mkdir as Js,writeFile as zs}from"fs/promises";import{dirname as Gs}from"path";class Vt{outputDir(){return Je("prototype-shares")}async write(o,d){await Js(Gs(o),{recursive:!0,mode:448}),await zs(o,d,{mode:420})}}function ue(o){return{appLayer:o.window.layer==="app",devicePersistence:o.window.persistence==="device"}}function Zo(o){let d=[...o.appLayer?['window.layer "app"']:[],...o.devicePersistence?['window.persistence "device"']:[]].join(" and ");return`The connected CtrlProxy does not advertise ${_P}, so it would ignore ${d} and show a session-scoped system-layer prototype; update the connected CtrlProxy or omit ${d}.`}var Ks=`shell appops set ${vt} SYSTEM_ALERT_WINDOW allow`;async function er(o,d){try{let y=await o.executeCommand(Ks,{noRetry:!0,signal:d});if(je(y.stdout,y.stderr??""))e.warn(`[prototype] SYSTEM_ALERT_WINDOW appop grant reported a failure: ${`${y.stdout}
8
+ ${y.stderr??""}`.trim()}`)}catch(y){if(d?.aborted)throw y;e.warn(`[prototype] SYSTEM_ALERT_WINDOW appop grant failed: ${r(y)}`,y)}}var Xs=new Set(["app","notifications"]);function $e(o,d){if(d==="android")return;for(let y of Nd(o)){if(y.kind!=="call"||y.action.call!=="settings.open")continue;let f=c(c(y.action.args)?.page)?.value;if(typeof f==="string"&&!Xs.has(f))return{path:y.path,message:`settings.open page "${f}" is Android only; on iOS use "app" or "notifications"`}}return}var Qs=8000,Zs=1000;class Ut{deps;target;constructor(o){this.deps=o}async installed(o){let{userId:d}=await new _t(this.deps.adb).resolve({currentUser:!0,signal:o}),y=await this.deps.adb.executeCommand(`shell pm list packages --user ${d}`,{noRetry:!0,signal:o}),f=v1((h)=>Gi(y.stdout,h),this.deps.appIds);return this.target=f===void 0?void 0:{userId:d,appId:f},this.target!==void 0}async capabilities({timeoutMs:o,refresh:d,signal:y}){let f=await this.requireTarget(y);if(f.userId!==0)return;await this.ensureStorage(f,o,y);let h=await this.installedVersionCode(f,y),P=await this.readCapabilities(f,y),g=P!==void 0&&h!==void 0&&P.versionCode!==h;if(d||g)await this.prepare(f,o,y),P=await this.readCapabilities(f,y);if(P===void 0||h!==void 0&&P.versionCode!==h)return;return{...P.versionName?{version:P.versionName}:{},capabilities:new Set(P.capabilities),updateUrl:JJ}}async installedVersionCode(o,d){let y=await jR(this.deps.adb,o.appId,{signal:d,optional:!0}),f=y?.buildNumber?Number(y.buildNumber):Number.NaN;return Number.isSafeInteger(f)?f:void 0}async readCapabilities(o,d){let y=b(GJ(o.userId,o.appId)),f=(await this.shell(`if [ -f ${y} ]; then cat ${y}; fi`,d)).trim();if(f==="")return;let h;try{h=YJ.safeParse(JSON.parse(f))}catch(P){e.warn(`[protoviewer] unreadable capabilities report: ${r(P)}`);return}if(!h.success){e.warn(`[protoviewer] capabilities report has an unexpected shape: ${h.error.message}`);return}return h.data}async importBundle(o,d,y,f){let h=await this.requireTarget(f),P=this.deps.timer.now(),g=this.requestId(),T=h.userId===0?XJ(h.userId,h.appId,g):FG(h.appId,"inbox",g);if(h.userId===0)await this.ensureStorage(h,y,f);let A=await this.deps.tempFiles.write(o);try{let _=h.userId===0?T:LG(g),x=await this.push(A.path,_,f);if(je(x.stdout,x.stderr??""))throw new as(`Could not copy the prototype into ProtoViewer's inbox (${T}): ${ei(x)}.`);if(h.userId!==0)await this.providerShell(KJ(h.userId,T,_),f)}catch(_){if(h.userId!==0)await this.removeStagingQuietly(LG(g));throw _}finally{await A.dispose()}let C=[`--es ${b1} ${g}`];if(d!==void 0)C.push(`--es ${WJ} ${b(d)}`);let I=Math.max(y-(this.deps.timer.now()-P),Math.min(y,Zs)),O=await this.work(h,g,HJ,{extras:C,timeoutMs:I,signal:f,cleanup:[T]});if(O.status==="rejected"&&O.path===jJ)throw new as(`ProtoViewer cannot read the prototype pushed into its inbox: ${O.reason}.`);return O}async open(o,d,y){let f=await this.requireTarget(y),h=this.requestId(),P=[`--es ${b1} ${h}`,`--es ${zJ} ${b(o)}`];return await this.work(f,h,qJ,{extras:P,timeoutMs:d,signal:y,cleanup:[]})}async requireTarget(o){if(this.target===void 0&&!await this.installed(o))throw new t("ProtoViewer is not installed for the current Android user.");return this.target}async push(o,d,y){try{return await this.deps.adb.execute(["push",o,d],{noRetry:!0,signal:y})}catch(f){if(y?.aborted)throw f;throw new as(`Could not copy the prototype into ProtoViewer's inbox (${d}): ${r(f)}.`,{cause:f})}}async ensureStorage(o,d,y){if(await this.storageReady(o,y))return;if(await this.removeShellOwnedFolders(o,y),await this.prepare(o,d,y),!await this.storageReady(o,y))throw new as("ProtoViewer reported its inbox ready, but the folders are not there.")}async prepare(o,d,y){let f=this.requestId();try{let h=await this.exchange(o,f,VJ,{extras:[`--es ${b1} ${f}`],timeoutMs:Math.min(d,Qs),signal:y,cleanup:[]});if(h.status!=="prepared")throw new t(`ProtoViewer answered a prepare request with ${h.status}.`)}catch(h){if(y?.aborted||h instanceof vv)throw h;throw new as(`ProtoViewer could not prepare its inbox (${r(h)}).`,{cause:h})}}async storageReady(o,d){let y=b(tI(o.userId,o.appId)),f=b(w1(o.userId,o.appId)),h=b(R1(o.userId,o.appId));return(await this.shell(`if [ -d ${f} ] && [ -d ${h} ] && [ ! -O ${y} ] && [ ! -O ${f} ] && [ ! -O ${h} ]; then echo ready; fi`,d)).includes("ready")}async removeShellOwnedFolders(o,d){let y=[tI(o.userId,o.appId),w1(o.userId,o.appId),R1(o.userId,o.appId)].map(b);await this.shell(`for d in ${y.join(" ")}; do if [ -O "$d" ]; then rm -rf "$d"; fi; done`,d)}async work(o,d,y,f){let h=await this.exchange(o,d,y,f);if(h.status==="prepared")throw new t("ProtoViewer answered a request with a prepare result; retry.");return h}requestId(){let o=`mcp-${this.deps.ids.next().replace(/[^A-Za-z0-9_-]/g,"")}`.slice(0,64);if(!$M.test(o))throw new t(`Generated an unusable ProtoViewer request id: ${o}`);return o}async exchange(o,d,y,{extras:f,...h}){let P=o.userId===0?ZJ(o.userId,o.appId,d):FG(o.appId,"results",d);try{let g=await this.shell(`am start -W --activity-multiple-task --user ${o.userId} -n ${UJ(o.appId)} -a ${y} ${f.join(" ")}`,h.signal);ti(g);let T=await Ce(()=>o.userId===0?this.shell(`if [ -f ${b(P)} ]; then cat ${b(P)}; fi`,h.signal):this.providerShell(S1("read",o.userId,P),h.signal),this.deps.timer,h.timeoutMs,{signal:h.signal});if(T.request!==d)throw new t(`ProtoViewer answered request ${T.request}, not ${d}; retry the call.`);return T}finally{await this.removeQuietly(o,[P,...h.cleanup])}}async removeQuietly(o,d){try{let y=o.userId===0?`rm -f ${d.map(b).join(" ")}`:d.map((f)=>S1("delete",o.userId,f)).join("; ");await this.shell(y,void 0,{timeoutMs:G0})}catch(y){e.warn(`[protoviewer] cleanup of ${d.join(", ")} failed: ${r(y)}`)}}async removeStagingQuietly(o){try{await this.shell(`rm -f ${b(o)}`,void 0,{timeoutMs:G0})}catch(d){e.warn(`[protoviewer] cleanup of ${o} failed: ${r(d)}`)}}async providerShell(o,d){try{let y=await this.shell(o,d);if(!y.trimStart().startsWith("{")&&je(y,""))throw new as(`Could not access ProtoViewer's MCP storage: ${y.trim()}.`);return y}catch(y){if(d?.aborted||y instanceof as)throw y;throw new as(`Could not access ProtoViewer's MCP storage: ${r(y)}.`,{cause:y})}}async shell(o,d,y={}){let f=await this.deps.adb.executeCommand(`shell ${o}`,{noRetry:!0,signal:d,...y});return`${f.stdout}${f.stderr?`
9
+ ${f.stderr}`:""}`}}function ei(o){return`${o.stdout}
10
+ ${o.stderr??""}`.trim()}function ti(o){if(/does not exist|Unable to resolve Intent/.test(o))throw new vv;if(/(^|\n)\s*Error( type \d+)?:|Exception|Permission Denial|Activity not started/.test(o))throw new t(`Could not start ProtoViewer: ${o.trim()}`)}import{mkdtemp as oi,rm as ri,writeFile as ni}from"fs/promises";import{tmpdir as si}from"os";import{join as tr}from"path";class Bt{async write(o){let d=await oi(tr(si(),"automobile-protoviewer-")),y=tr(d,"bundle.automobile-proto");return await ni(y,o,{mode:420}),{path:y,dispose:()=>ri(d,{recursive:!0,force:!0})}}}function or(o,d){let y=(A)=>d.releaseDevice(A),f=[o.subscribeSessionRelease((A,C)=>{if(d.releaseSession(A),C)y(C)}),o.subscribeDeviceRemoval(y)],h={},P,g=!1,T=()=>{if(g)return;let A=o.deviceUnboundSource?o.deviceUnboundSource():h;if(P!==void 0&&P.source===A)return;if(P?.unsubscribe(),P=void 0,A===void 0)return;let C=o.subscribeDeviceUnbound(y);if(C)P={source:A,unsubscribe:C}};return T(),{ensureSubscribed:T,unsubscribe:()=>{g=!0,P?.unsubscribe(),P=void 0;for(let A of f)A()}}}function rr(){let o=new Map;return{run(d,y){let f=(o.get(d)??Promise.resolve()).then(y),h=f.then(()=>{},()=>{});return o.set(d,h),h.then(()=>{if(o.get(d)===h)o.delete(d)}),f}}}var J=(o)=>({success:!1,error:o});function ii(o,d){try{let y=XO(o,d,{stateTests:"skip"});if(!y.success)return J(`Invalid patch at ${y.error.path}: ${y.error.message}`);let f=Qp(y.spec);return f.success?{spec:y.spec,validated:f.data}:J(`Invalid patch result at spec.${f.error.path}: ${f.error.message}`)}catch(y){if(e.warn("[prototype] Patch application failed",y),!(y instanceof RangeError))throw y;return J("Invalid patch at ops: Patch is nested too deeply")}}async function pi(o,d){try{return await o.transport.patch({id:d.id,...d.baseRevision===void 0?{}:{baseRevision:d.baseRevision},ops:d.ops},d.timeoutMs)}catch(y){return e.warn("[prototype] Patch request failed",y),{success:!1,delivery:"indeterminate",error:u(y,"Prototype patch failed").message}}}async function di(o,d,y,f){let h=o.store.shownSpecs.read(d,y.id);if(h.kind==="busy")return J(`Prototype ${y.id} was not patched: a show is in flight on this device. Patch after it returns.`);if(h.kind==="unknown")return J(`Prototype ${y.id} was not patched: this host is not tracking its spec on this device (it was not shown by this host, or a dismiss, a failed show or an overlapping show ended the tracking). Show it, then patch.`);let P=ui(o,d,y,h.spec);if(!("spec"in P))return P;let g=$e(P.spec,o.platform);if(g)return J(`Invalid patch result at spec.${g.path}: ${g.message}`);let T=await o.specRefusal?.(P.spec);if(T!==void 0)return J(T);f?.throwIfAborted();let A=await pi(o,y);return ci(o,d,y,{read:h,applied:P,result:A})}async function ci(o,d,y,f){let{read:h,applied:P,result:g}=f;if(g.delivery==="indeterminate")return o.store.shownSpecs.abandon(d),J(`${g.error??"Prototype patch failed"} The device may or may not have applied the patch: show the prototype again before the next patch.`);let T=LR(g);if(!g.success)return{success:!1,error:g.error??"The device refused the patch.",...T};let A=o.store.shownSpecs.commitPatch(d,y.id,h.version,{spec:P.spec,deviceRevision:T.revision,...o.mcpSessionId===void 0?{}:{mcpSessionId:o.mcpSessionId}});if(A)o.store.recordPatch(d,y.id,{data:P.validated.data,revision:T.revision});else if(!o.store.shownSpecs.showStartedSince(d,h.version))o.store.recordPatch(d,y.id,{revision:T.revision});o.retire(g);let C=yi(T.revision,A,y.id),I=FO(g.degradedEffects),O=[C.warning,I.warning,...DK(P.spec)].filter(Boolean).join(" ");return{...C,...I,...O?{warning:O}:{},...f1(P.spec),...h1(P.spec)}}function ui(o,d,y,f){let h=ii(f,y.ops);return"spec"in h?li(o,d,y)??h:h}function li(o,d,y){let f=o.store.shownSpecs.dataPatchGuard(d,y.id,Tse(y.ops),y.baseRevision);if(f.kind==="baseRevisionRequired")return J("Invalid patch at baseRevision: required for /data ops once the device has written this prototype's data (setData, appendData, prependData, removeData); use the revision from the latest change event or patch result");return f.kind==="conflict"?{success:!1,error:`The patch was refused: the device wrote ${f.paths.join(", ")} after revision ${y.baseRevision}. Re-read the prototype's data and patch again from revision ${f.revision}.`,conflict:{revision:f.revision,state:{},data:f.paths}}:void 0}function yi(o,d,y){return{success:!0,...o===void 0?{}:{revision:o},...d?{}:{warning:`A show on this device overlapped this patch, so the host no longer tracks prototype ${y}'s spec: show it again before the next patch.`}}}async function nr(o,d,y,f){let h=await o.supportsPatch();if(f?.throwIfAborted(),!h)return J(new t(KD(o.platform)).message);if(y.baseRevision===void 0&&Ase(y.ops))return J("Invalid patch at baseRevision: required when a patch has /state ops");try{if(Buffer.byteLength(JSON.stringify({id:y.id,baseRevision:y.baseRevision,ops:y.ops}),"utf8")>ka)return J("Invalid patch at ops: Patch byte limit exceeded")}catch(P){if(e.warn("[prototype] Patch serialization failed",P),!(P instanceof RangeError))throw P;return J("Invalid patch at ops: Patch is nested too deeply")}return o.queue.run(d,()=>di(o,d,y,f))}function sr(o){return o.map((d)=>`'${d}'`).join(", ")}function ir(o){let d=o.missing.filter((h)=>!o.supplied.has(h)),y=o.missing.filter((h)=>o.supplied.has(h)),f=[];if(d.length>0)f.push(`The device has no copy of prototype asset(s) ${sr(d)}, so those images show placeholders. Upload them with assets: [{id, path}] on a show.`);if(y.length>0){let h=o.repair?.kind==="retry-failed"?`the automatic re-upload did not complete: ${o.repair.reason}`:"they were re-uploaded and the prototype re-sent once, and the device still reports them missing";f.push(`Asset(s) ${sr(y)} were supplied on this call but the device reports them missing; ${h}. Repeat the call to try again.`)}return f.join(" ")}var ar=new WeakSet;function pr(o){return ar.add(o),o}function fi(o){return ar.has(o)}function dr(o){if(o.action!=="show")return{};if(o.result.errorCode==="render_failed")return{refusal:"typed"};if(o.success&&o.id){let d=_8(o.spec)?.keys.some((y)=>y.startsWith("data:"));return{shown:{id:o.id,spec:d?void 0:o.spec,replaceOthers:o.replaceOthers,...o.variant?{variant:o.variant}:{}}}}if(o.replaceOthers===!1&&!o.success)return{refusal:fi(o.result)?"indeterminate":"typed"};return{}}async function mi(o,d,y){if(d.action==="show")return o.transport.show(d.spec,{timeoutMs:d.timeoutMs,displayId:y,reset:d.reset,...d.spec?.strings&&d.locale!==void 0?{locale:d.locale}:{},replaceOthers:d.replaceOthers,appearance:S2(d.appearance)});let f=d.all?{all:!0}:{id:d.id};return o.transport.dismiss(f,d.timeoutMs)}async function Ve(o,d,y,{signal:f,cached:h}={}){let P=wy(d.spec,y.env);if(P)return{uploaded:[],prepared:[],failure:{success:!1,error:P}};if(d.assets===void 0){let C=h?await LP(d.spec,h.serial,h.cache):void 0;return{uploaded:[],prepared:[],...C?{failure:{success:!1,error:C}}:{}}}let g=await eI(d.assets,y.assetFileReader,y.observationScreenshotReader,y.env);if("error"in g)return{uploaded:[],prepared:[],failure:{success:!1,error:g.error}};let T=h?await LP(d.spec,h.serial,h.cache,g.assets):C8(d.spec,g.assets);if(T)return{uploaded:[],prepared:[],failure:{success:!1,error:T}};let A=await MG(Xe(o.transport),g.assets,{signal:f,action:d.action==="save"?"save":"show",env:y.env});return{uploaded:A.uploaded,prepared:g.assets,...A.success?{}:{failure:{success:!1,error:A.error}}}}async function cr(o,d,y){try{return await mi(o,d,y)}catch(f){return e.warn("[prototype] Request failed",f),pr({success:!1,error:u(f,"Prototype request failed").message})}}async function hi(o,d,y,f){try{return await MG(Xe(o.transport),d,{signal:y,action:"resend",env:f})}catch(h){return e.warn("[prototype] Asset re-upload failed after the show was sent",h),{success:!1,uploaded:[],error:y?.aborted?"the request was cancelled":r(h)}}}async function Pi(o,d,y,{first:f,signal:h,displayId:P,env:g}){let T=new Set(f.missingAssets),A=y.prepared.filter((_)=>T.has(_.id));if(A.length===0)return;let C=(_)=>({result:f,repair:{kind:"retry-failed",reason:_}});if(h?.aborted)return C("the request was cancelled");let I=await hi(o,A,h,g);if(!I.success)return C(I.error??"upload failed");if(h?.aborted)return C("the request was cancelled before the prototype was re-sent");let O=await cr(o,d,P);return O.success?{result:O,repair:{kind:"still-missing"}}:C(O.error??"re-sending the prototype failed")}function gi(o){return{success:!1,error:`Prototype ${o.spec?.id??""} was not sent: a newer show of the same id on this device started first and is the one on screen.`}}function vi(o,d){return o.success&&(o.missingAssets?.length??0)>0&&!d()}async function ur(o,d,y,f){let h=f.superseded??(()=>!1),{signal:P,displayId:g,beforeSend:T}=f;if(y.failure)return{result:y.failure};if(h())return{result:gi(d)};await T?.();let A=await cr(o,d,g);if(!vi(A,h))return{result:A};let C=await Pi(o,d,y,{first:A,signal:P,displayId:g,env:f.env}),I=C?.result??A;if(!I.missingAssets?.length)return{result:I};return{result:I,warning:ir({missing:I.missingAssets,supplied:new Set(y.prepared.map((O)=>O.id)),repair:C?.repair})}}import{createServer as wi}from"http";function Si(o){return{writeHead:(d,y)=>{o.writeHead(d,y),o.flushHeaders()},write:(d)=>{o.write(d)},end:(d)=>{o.end(d)},onClose:(d)=>{o.once("close",d)}}}function bi(o){return new Promise((d)=>{o.close(()=>d()),o.closeAllConnections()})}var lr={listen:(o,d)=>new Promise((y,f)=>{let h=wi((P,g)=>d({method:P.method??"GET",url:P.url??"/",host:P.headers.host},Si(g)));h.once("error",f),h.listen(o.port,o.host,()=>{h.off("error",f),h.on("error",(g)=>{e.warn(`[prototype] preview server socket error: ${r(g)}`,g)});let P=h.address();y({port:typeof P==="object"&&P!==null?P.port:o.port,close:()=>bi(h)})})})};import{createHash as Ri}from"crypto";var ki=/^\/p\/([^/]+)(\/page|\/events)?\/?$/;function Ei(o){try{let d=decodeURIComponent(o);return d.length>0?d:void 0}catch(d){e.debug(`[prototype] preview path segment not decodable: ${r(d)}`);return}}function yr(o,d){let y=d.get("variant")||void 0,f=d.get("frame")||void 0;return{id:o,...y?{variant:y}:{},...f?{frame:f}:{}}}var Ti=/^\/p\/?$/;function Ci(o){let d=o.get("id"),y=o.get("view")??"shell";if(!d)return{kind:"notFound"};if(y==="events")return{kind:"events",id:d};return y==="shell"||y==="page"?{kind:y,...yr(d,o)}:{kind:"notFound"}}function fr(o){let d;try{d=new URL(o,"http://preview.invalid")}catch(h){return e.debug(`[prototype] preview request target not parseable: ${r(h)}`),{kind:"notFound"}}if(d.pathname==="/")return{kind:"index"};if(Ti.test(d.pathname))return Ci(d.searchParams);let y=ki.exec(d.pathname),f=y?.[1]===void 0?void 0:Ei(y[1]);if(f===void 0)return{kind:"notFound"};if(y?.[2]==="/events")return{kind:"events",id:f};return{kind:y?.[2]==="/page"?"page":"shell",...yr(f,d.searchParams)}}function Se(o,d="shell",y={}){if(o==="."||o==="..")return`/p?${new URLSearchParams({id:o,...d==="shell"?{}:{view:d},...y}).toString()}`;let f=new URLSearchParams(y).toString(),h=d==="shell"?"":`/${d}`;return`/p/${Qe(o)}${h}${f?`?${f}`:""}`}var mr=["(() => {",'const frame = document.querySelector("iframe[data-preview]");','const status = document.querySelector("[data-preview-status]");',"const events = new EventSource(document.body.dataset.events);","let generation;","let loaded = false;","const reload = () => {","if (!loaded) {","loaded = true;","frame.src = frame.dataset.page;","return;","}",'const picked = frame.contentDocument?.querySelector("[data-control=variant]")?.value;','const next = new URL(frame.getAttribute("src"), location.href);','if (picked) next.searchParams.set("variant", picked);','next.searchParams.set("generation", String(generation));',"frame.src = next.pathname + next.search;","};",'events.addEventListener("ready", (event) => {',"const seen = JSON.parse(event.data).generation;","const missed = !loaded || seen !== generation;","generation = seen;",'status.textContent = "Live";',"if (missed) reload();","});",'events.addEventListener("reload", (event) => {',"generation = JSON.parse(event.data).generation;","reload();","});","events.onerror = () => {",'status.textContent = "Reconnecting";',"if (!loaded) reload();","};","})();"].join(`
11
+ `),Oi=Ri("sha256").update(mr).digest("base64"),Wt={"cache-control":"no-store","x-content-type-options":"nosniff","referrer-policy":"no-referrer"},Ii=["default-src 'none'",`script-src 'sha256-${Oi}'`,"style-src 'unsafe-inline'","img-src data:","connect-src 'self'","frame-src 'self'","frame-ancestors 'none'"].join("; "),_i="default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'self'",Mi="html,body{margin:0;height:100%;font:14px system-ui,-apple-system,Roboto,sans-serif}body{display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:6px 12px;border-bottom:1px solid #ccc}iframe{flex:1;border:0;width:100%}main{padding:16px}";function jt(o,d,y={}){let f=`<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="data:,"><title>${bu(o)}</title><style>${Mi}</style></head>`,h=bu(R("body",{attrs:y},d));return`<!doctype html><html lang="en">${f}${h}</html>
12
+ `}function Ue(o,d,y=_i){return{status:o,headers:{...Wt,"content-type":"text/html; charset=utf-8","content-security-policy":y},body:d}}function be(o,d){return{status:o,headers:{...Wt,"content-type":"text/plain; charset=utf-8"},body:d}}function xi(o){let d=o.ids(),y=d.length===0?R("p",{},["No prototype shown yet. Show one and open its link here."]):R("ul",{},d.map((f)=>R("li",{},[R("a",{attrs:{href:Se(f)}},[f])])));return Ue(200,jt("AutoMobile prototypes",[R("main",{},[R("h1",{},["Prototypes"]),y])]))}function Di(o){let d={...o.variant?{variant:o.variant}:{},...o.frame?{frame:o.frame}:{}},y=R("header",{},[R("a",{attrs:{href:"/"}},["All prototypes"]),R("strong",{},[o.id]),R("span",{attrs:{"data-preview-status":""}},["Connecting"])]),f=R("iframe",{attrs:{"data-preview":"",title:o.id,"data-page":Se(o.id,"page",d)}}),P=jt(`${o.id} preview`,[y,f],{"data-events":Se(o.id,"events")}).replace("</body>",`<script>${mr}</script></body>`);return Ue(200,P,Ii)}function Li(o){let d=`Prototype "${o}" has no web output yet. Show it and this page reloads.`;return Ue(404,jt(o,[R("main",{},[R("p",{},[d])])]))}function qi(o,d){if(d.variant===void 0||o.related(d.id).includes(d.variant))return d;return{id:d.id,...d.frame?{frame:d.frame}:{}}}async function Fi(o,d){if(!o.has(d.id))return Li(d.id);try{return Ue(200,await o.page(qi(o,d)),"frame-ancestors 'self'")}catch(y){if(y instanceof t)return be(400,y.message);return e.warn(`[prototype] preview page for ${d.id} failed: ${r(y)}`,y),be(500,"The prototype page could not be rendered; see the daemon log.")}}async function hr(o,d){switch(o.kind){case"index":return xi(d);case"shell":return Di(o);case"page":return Fi(d,o);case"notFound":return be(404,"Not found")}}var Yt={method:()=>be(405,"Only GET is served"),host:()=>be(421,"This preview server answers its loopback address only")},Jt={...Wt,"content-type":"text/event-stream; charset=utf-8",connection:"keep-alive","x-accel-buffering":"no"};var Ni=15000,Be="127.0.0.1",Hi="0.0.0.0";function $i(o){return typeof o==="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"}function Pr(o,d){return`event: ${o}
13
+ data: ${JSON.stringify(d)}
14
+
15
+ `}class zt{dependencies;running;streams=new Set;idleHandle;generation=0;stoppedReason;served=!1;queue=Promise.resolve();constructor(o){this.dependencies=o}serve(o){return this.serialized(()=>this.serveNow(o))}stop(o="stop"){return this.serialized(async()=>(await this.stopNow(o),this.info()??{running:!1}))}info(){let o=this.running;if(o===void 0){if(!this.served)return;return{running:!1,...this.stoppedReason?{stoppedReason:this.stoppedReason}:{}}}let d=o.listener.port;return{running:!0,url:`http://${Be}:${d}/`,host:o.host,port:d,remote:o.remote,idleTimeoutMs:o.idleTimeoutMs}}pageUrl(o){let d=this.running;return d&&`http://${Be}:${d.listener.port}${Se(o)}`}serialized(o){let d=this.queue.then(o,o);return this.queue=d.catch((y)=>{e.debug(`[prototype] preview server operation failed: ${r(y)}`)}),d}async serveNow(o){let d=o.remote===!0,y=o.port??0,f=o.idleTimeoutMs??p1,h=this.running,P=y===0||y===h?.requestedPort||y===h?.listener.port;if(h&&h.remote===d&&P)return h.idleTimeoutMs=f,this.touch(),this.info();await this.stopNow("stop");let g=d?Hi:Be,T=await this.bind(g,y);return this.generation+=1,this.served=!0,this.stoppedReason=void 0,this.running={listener:T,host:g,remote:d,requestedPort:y,idleTimeoutMs:f,unsubscribe:this.dependencies.source.onChange((A)=>this.changed(A)),keepalive:this.dependencies.timer.setInterval(()=>this.broadcastKeepalive(),Ni)},this.touch(),this.info()}async bind(o,d){try{return await this.dependencies.http.listen({host:o,port:d},(y,f)=>this.handle(y,f))}catch(y){if($i(y))throw new t(`Port ${d} is already in use on ${o}: pass another port, or omit port for a free one.`);throw u(y,"Failed to start the prototype preview server")}}async stopNow(o){let d=this.running;if(d===void 0)return;this.running=void 0,this.stoppedReason=o,this.clearIdle(),d.unsubscribe(),this.dependencies.timer.clearInterval(d.keepalive),[...this.streams].forEach((y)=>y.response.end()),this.streams.clear(),await d.listener.close(),e.info(`[prototype] preview server on port ${d.listener.port} stopped (${o})`)}clearIdle(){if(this.idleHandle!==void 0)this.dependencies.timer.clearTimeout(this.idleHandle),this.idleHandle=void 0}touch(){this.clearIdle();let o=this.running;if(o===void 0||this.streams.size>0)return;this.idleHandle=this.dependencies.timer.setTimeout(()=>{this.idleHandle=void 0,this.stop("idle").catch((d)=>{e.warn(`[prototype] preview server idle stop failed: ${r(d)}`,d)})},o.idleTimeoutMs)}handle(o,d){let y=this.running;if(y===void 0){d.writeHead(503,{"content-type":"text/plain; charset=utf-8"}),d.end("The preview server is stopping");return}this.touch();let f=this.refusal(o,y);if(f){d.writeHead(f.status,f.headers),d.end(f.body);return}let h=fr(o.url);if(h.kind==="events"&&o.method==="HEAD"){d.writeHead(200,Jt),d.end();return}if(h.kind==="events"){this.openStream(h.id,d);return}this.respond(h,d)}refusal(o,d){if(o.method!=="GET"&&o.method!=="HEAD")return Yt.method();let y=d.listener.port,f=[`${Be}:${y}`,`localhost:${y}`,`[::1]:${y}`],h=o.host?.toLowerCase();if(!d.remote&&h!==void 0&&!f.includes(h))return Yt.host();return}async respond(o,d){try{let y=await hr(o,this.dependencies.source);d.writeHead(y.status,y.headers),d.end(y.body)}catch(y){e.warn(`[prototype] preview request failed: ${r(y)}`,y),d.writeHead(500,{"content-type":"text/plain; charset=utf-8"}),d.end("The preview request failed; see the daemon log.")}}openStream(o,d){let y={id:o,response:d,watched:new Set(this.related(o))};this.streams.add(y),this.clearIdle(),d.onClose(()=>{if(this.streams.delete(y))this.touch()}),d.writeHead(200,Jt),d.write(`retry: 1000
16
+
17
+ ${Pr("ready",{generation:this.generation})}`)}related(o){try{return this.dependencies.source.related(o)}catch(d){return e.debug(`[prototype] preview related ids of ${o} unavailable: ${r(d)}`),[o]}}changed(o){this.generation+=1,this.touch();let d=Pr("reload",{id:o,generation:this.generation});this.streams.forEach((y)=>{let f=this.related(y.id),h=y.id===o||y.watched.has(o)||f.includes(o);if(h)y.response.write(d);y.watched=h?new Set(f):new Set([...y.watched,...f])})}broadcastKeepalive(){this.streams.forEach((o)=>o.response.write(`: keepalive
18
+
19
+ `))}}function gr(o,d){let y=(f)=>o.ids().includes(f);return{ids:()=>o.ids(),has:y,related:(f)=>y(f)?Jf(o,f):[f],page:d,onChange:(f)=>o.onRevision((h)=>f(h.id))}}function Vi(o){return gr(o.revisions,async(d)=>(await dL(o.revisions,d,o.rendererVersion(),o.images)).html)}var Gt;function vr(){if(Gt===void 0){let o=Vi(VM()),d=new zt({source:o,http:lr,timer:i});oJ(d),Gt={server:d,source:o}}return Gt}async function wr(o,d){try{if(d.action==="stop")return{success:!0,previewServer:await o.server.stop()};let y=await o.server.serve({port:d.port,remote:d.remote,idleTimeoutMs:d.idleTimeoutMs}),f=d.id===void 0?void 0:o.server.pageUrl(d.id),h=d.id!==void 0&&!o.source.has(d.id);return{success:!0,previewServer:{...y,...f?{pageUrl:f}:{}},...h?{warning:`Prototype "${d.id}" has no web output yet; its page loads once it is shown.`}:{}}}catch(y){return e.warn(`Prototype ${d.action} failed`,y),{success:!1,error:u(y,`Prototype ${d.action} failed`).message}}}var Sr=new Set(W.stringFields),Ui=new Set(W.stringOpaqueFields),br=0.4,Rr="~",Bi={a:"\xE1",b:"\u0180",c:"\xE7",d:"\u010F",e:"\xE9",f:"\u0192",g:"\u011F",h:"\u0125",i:"\xED",j:"\u0135",k:"\u0137",l:"\u013C",m:"\u0271",n:"\xF1",o:"\xF3",p:"\xFE",q:"\u01A3",r:"\u0155",s:"\u0161",t:"\u0165",u:"\xFA",v:"\u1E7D",w:"\u0175",x:"\u1E8B",y:"\xFD",z:"\u017E",A:"\xC1",B:"\u0181",C:"\xC7",D:"\u010E",E:"\xC9",F:"\u0191",G:"\u011E",H:"\u0124",I:"\xCD",J:"\u0134",K:"\u0136",L:"\u013B",M:"\u1E40",N:"\xD1",O:"\xD3",P:"\xDE",Q:"\u01EA",R:"\u0154",S:"\u0160",T:"\u0164",U:"\xDA",V:"\u1E7C",W:"\u0174",X:"\u1E8A",Y:"\xDD",Z:"\u017D"},Wi=/\{[^{}]*\}/g;function kr(o){let d=[...gse(o),...[...o.matchAll(/\{t:[^{}]*(?:\{data:[^{}]*\}[^{}]*)?\}/g)].map((f)=>({start:f.index,end:f.index+f[0].length}))],y=[...o.matchAll(Wi)].map((f)=>({start:f.index,end:f.index+f[0].length})).filter((f)=>d.every((h)=>f.end<=h.start||f.start>=h.end));return[...d,...y].sort((f,h)=>f.start-h.start).reduce((f,h)=>{let P=f.at(-1);if(P&&h.start<P.end)P.end=Math.max(P.end,h.end);else f.push({...h});return f},[])}function Kt(o){let d=(h)=>[...h].map((P)=>Bi[P]??P).join(""),y=[],f=0;for(let{start:h,end:P}of kr(o))y.push(d(o.slice(f,h)),o.slice(h,P)),f=P;return y.join("")+d(o.slice(f))}function Xt(o){if(o.trim()===""||/^\{t:[^{}]*(?:\{data:[^{}]*\}[^{}]*)?\}$/.test(o))return o;let d=Rr.repeat(Math.ceil([...o].length*br));return`[${Kt(o)}${d}]`}var ji=new Set(["mention","hashtag","url"]),Yi=new Set(["screens","components"]);function Ji(o,d){let y=kr(o);return AU(o,d).filter((f)=>y.every(({start:h,end:P})=>f.start<=h||f.start>=P)).map((f)=>{let h=y.find(({start:P,end:g})=>f.end>P&&f.end<g);return h?{...f,end:h.end,text:o.slice(f.start,h.end)}:f})}function zi(o,d){if(o.trim()===""||/^\{t:[^{}]*(?:\{data:[^{}]*\}[^{}]*)?\}$/.test(o))return o;let y=Ji(o,d),f=y.flatMap((g,T)=>[Kt(o.slice(T===0?0:y[T-1].end,g.start)),g.text]),h=o.slice(y.at(-1)?.end??0),P=Rr.repeat(Math.ceil([...o].length*br));return`${f.join("")}${Kt(h)} ${P}`}function Ki(o){let d=c(o.linkify)?.kinds;return Array.isArray(d)&&d.every((y)=>ji.has(y))?d:void 0}function Xi(o,d,y,f){if(Ui.has(d))return[d,y];if(Yi.has(d)&&c(y)){let h=Object.entries(c(y)).map(([P,g])=>[P,We(g)]);return[d,Object.fromEntries(h)]}if((Sr.has(d)||Sr.has(`${f}.${d}`))&&typeof y==="string"){let h=d==="text"?Ki(o):void 0;return[d,h?zi(y,h):Xt(y)]}return[d,We(y,d)]}function We(o,d=""){if(Array.isArray(o))return o.map((f)=>We(f,d));let y=c(o);if(!y)return o;return Object.fromEntries(Object.entries(y).map(([f,h])=>Xi(y,f,h,d)))}function Er(o){let d=We(o),y=c(d),f=c(c(o)?.strings);if(y&&f)y.strings=Object.fromEntries(Object.entries(f).map(([h,P])=>[h,Object.fromEntries(Object.entries(c(P)??{}).map(([g,T])=>[g,typeof T==="string"?Xt(T):Object.fromEntries(Object.entries(c(T)??{}).map(([A,C])=>[A,typeof C==="string"?Xt(C):C]))]))]));return d}var Tr=3,Qi=250,Zi=1000;async function ea(o,d,y,{signal:f,hiddenReason:h}={}){try{for(let P=0;P<Tr;P++){f?.throwIfAborted();let g=await o.capture({freshness:"fresh",displayId:y,timeoutMs:Zi,signal:f});if(f?.throwIfAborted(),ba(g.hierarchy))return;if(P<Tr-1){await d.sleep(Qi);continue}return ta(g.hierarchy,h)}}catch(P){if(f?.aborted){e.debug("App-layer visibility confirmation cancelled; the dispatched show is retained");return}e.warn("Could not confirm Android app-layer prototype visibility",P);return}return}function ta(o,d){if(!o.prototypeHiddenReason&&oa(o))return;let y=o.prototypeHiddenReason??d;if(y)return{visible:!1,notVisibleReason:y,warning:UY(y,o.packageName)};return ra(o)}function oa(o){return o.prototypeSuspended===!0||!o.windows?.length||o.ctrlProxyIncomplete===!0||o.hierarchy.error!==void 0}function ra(o){return{visible:!1,notVisibleReason:"no_prototype_window_on_screen",warning:`The prototype was shown with window.layer "app" but no prototype window is on screen. The app in front${o.packageName?` (${o.packageName})`:""} most likely hides app-layer windows drawn over it (system apps such as Settings do); a locked device hides it too. Until it is visible, layer "prototype" calls will report that no prototype is showing. Show it again without window.layer (the default layer draws over every app) or over a different app, or dismiss it.`}}async function Ar(o){if(!o.android||o.action!=="show"||!o.success||o.superseded())return{};if(o.hiddenReason==="device_blocked")return{visible:!1,notVisibleReason:"device_blocked",warning:UY("device_blocked")};if(!ue(o.spec).appLayer)return{};let d=await ea(o.capture(),o.timer??i,o.displayId,{signal:o.signal,hiddenReason:o.hiddenReason});return o.superseded()?{}:d??{}}function Cr(o){return`The connected ${o==="android"?"CtrlProxy":"iOS prototype agent"} does not advertise prototype_dead_tap_v1, so it would ignore window.deadTaps and report no dead taps. Nothing was shown. ${o==="android"?"Update the connected CtrlProxy":"Update the iOS prototype agent by relaunching the app with launchApp prototype: true"}, or omit window.deadTaps.`}var Qt={prototype_platform_namespace_v1:17,prototype_icon_effects_v1:17,prototype_glass_v1:26,prototype_keyframes_v1:17,prototype_motion_tokens_v1:17,prototype_zoom_transition_v1:18};function Or(o,d=Qt){let y=d[o];return y===void 0?"":` It needs iOS ${y} or later.`}function na(o){return`The ${o==="ios"?"connected iOS prototype agent":"connected CtrlProxy"} does not advertise ${xP}, so it would ignore window.chrome "none" and keep the host dismiss bar. Nothing was shown. ${o==="ios"?"Relaunch the app with launchApp prototype: true to load the agent built for this AutoMobile version":"Update the connected CtrlProxy"}, or omit window.chrome (the bar is then kept and reported).`}function Ir(o,{supported:d,platform:y}){let f=o.window.chrome,h=f===void 0?{}:{requested:f};if(o.window.placement.type!=="fullscreen")return{...h,...f===void 0?{}:{refusal:"window.chrome applies to a fullscreen placement only; omit it for a sheet or floating window. Nothing was shown."}};if(!d&&f==="none")return{...h,refusal:na(y)};return{...h,effective:d?f??(o.window.persistence==="device"?"bar":"none"):"bar"}}async function sa(o,d,y,{dependencies:f,signal:h}){if(y.action!=="show"||y.display===void 0||!o.android)return;let P=await YE(d,y.display,{adb:(f.adbFactory??v).create(d),lastRenderedObservation:f.lastRenderedObservation});if(h?.throwIfAborted(),!P)return;let g=await o.android.supportsCommand(Gb);if(h?.throwIfAborted(),!g)throw new t(zY(P));return P}async function ia(o,d,y){if(d.action!=="show"||d.spec===void 0)return;let f=_r(d)?await aa(o,d,y):void 0;if(f)return f;let h=ue(d.spec);if(!h.appLayer&&!h.devicePersistence)return;if(!o.android)return;let P=await o.android.supportsCommand(_P);if(y?.throwIfAborted(),!P)return{success:!1,error:new t(Zo(h)).message};return}function _r(o){return o.action==="show"&&o.spec?.window.deadTaps===!0}async function aa(o,d,y){if(!_r(d))return;let f=o.android?await o.android.supportsCommand(GO):o.ios?.supportsCapability(GO)===!0;return y?.throwIfAborted(),f?void 0:{success:!1,error:new t(Cr(o.android?"android":"ios")).message}}function Mr(o,d,y,{dependencies:f,signal:h}){if(y.action!=="show"||y.spec===void 0||!o.android)return;if(!ue(y.spec).appLayer)return;return async()=>{await er((f.adbFactory??v).create(d),h),h?.throwIfAborted()}}function pa(o,d,y){if(!o.android&&tc(d).length)return{success:!1,error:x8};let f=wy(d,y);return f?{success:!1,error:f}:void 0}async function Zt(o,d,y,{iosMinimumOs:f=Qt,env:h}={}){let P=pa(o,d,h);if(P)return P;for(let g of NG(d,o.android?"android":"ios")){let T=o.android?await o.android.supportsCommand(g.capability):o.ios?.supportsCapability(g.capability)===!0;if(y?.throwIfAborted(),!T){let A=o.android?"android":"ios",C=A==="ios"?Or(g.capability,f):"",I=g.unsupportedMessage(g.fields,A)+C;return{success:!1,error:new t(I).message}}}return}async function da(o,d,y){let f=d.action==="show"?S2(d.appearance):void 0;if(f===void 0)return;let h=o.android?await o.android.supportsCommand(CP):o.ios?.supportsCapability(CP)===!0;if(y?.throwIfAborted(),h)return;let P=w2(f,o.android?"android":"ios");return{success:!1,error:new t(P).message}}async function ca(o,d,y){if(d.action!=="show"||d.replaceOthers!==!1)return;let f=o.android?await o.android.supportsCommand(Yb):!1;if(y?.throwIfAborted(),f)return;let h=o.android?jY():z9;return{success:!1,error:new t(h).message}}async function ua(o,d,y){if(d.action!=="show"||!d.spec)return{};let f=d.spec,P=f.window.placement.type==="fullscreen"?o.android?await o.android.supportsCommand(xP):o.ios?.supportsCapability(xP)===!0:!1;y?.throwIfAborted();let g=Ir(f,{supported:P,platform:o.android?"android":"ios"});if(g.refusal)return{failure:{success:!1,error:new t(g.refusal).message}};return g.effective===void 0?{}:{chrome:g.effective}}var la=`The connected iOS prototype agent does not advertise ${gy}, so it does not support reset: it would keep the pager pages instead of starting fresh. Nothing was shown. Relaunch the app with launchApp prototype: true to load the agent built for this AutoMobile version, or omit reset.`;function ya(o,d){if(d.action!=="show"||d.reset!==!0||!o.ios||o.ios.supportsCapability(gy))return;return{success:!1,error:new t(la).message}}var fa=`The connected CtrlProxy does not advertise ${Jb}, so it would ignore anchor and draw the node at its normal position. Nothing was shown. Update the connected CtrlProxy, or remove anchor.`,ha=`The connected iOS prototype agent does not advertise ${Jb}, so it would ignore anchor and draw the node at its normal position. Nothing was shown. Relaunch the app with launchApp prototype: true to load the agent built for this AutoMobile version, or remove anchor.`,Pa="Element anchors resolve against the default display's app hierarchy, so they cannot be shown on another display. Nothing was shown. Omit display, or use a bounds anchor in dp.";async function ga(o){if(o.android){if(!await o.android.supportsCommand(Jb))throw new t(fa);return}if(!o.ios?.supportsCapability(Jb))throw new t(ha)}async function va(o,d,y,f){await ga(o),f?.throwIfAborted();let h=LJ(d);if(h)throw new t(h);if(y&&rp(d))throw new t(Pa)}async function wa(o,d,y,f){if(!rp(d))return{};let P=await(f.anchorHierarchyCaptureFactory??Pn)(o).capture({freshness:"fresh",...y}),g=BJ(d,{...P,boundsUnit:o.platform==="ios"?"points":"px"});return{spec:g.spec,anchors:g.anchors,...g.hierarchyUpdatedAt===void 0?{}:{hierarchyUpdatedAt:g.hierarchyUpdatedAt}}}async function Sa(o,d,y,{context:f,dependencies:h}){let{displayId:P,signal:g}=f,T=y.action==="show"?y.spec:void 0;if(!T||!g1(T))return{};try{return await va(o,T,P,g),await wa(d,T,{timeoutMs:y.timeoutMs,signal:g},h)}catch(A){return g?.throwIfAborted(),e.warn(`[prototype] anchor resolution refused the show: ${r(A)}`),{failure:{success:!1,error:u(A,"Prototype anchor failed").message}}}}async function Ra(o,d,y,{dependencies:f,signal:h}){try{return{displayId:await sa(o,d,y,{dependencies:f,signal:h})}}catch(P){return h?.throwIfAborted(),e.warn("[prototype] Request failed",P),{failure:{success:!1,error:u(P,"Prototype request failed").message}}}}async function xr(o,d,y,{args:f,dependencies:h}){let{signal:P}=o,g=await ca(d,f,P);if(g)return{failure:g};let T=await ua(d,f,P);if(T.failure)return{failure:T.failure};let A=await Ea(o,d,y,{args:f,dependencies:h});if(A.failure)return A;let C=ya(d,f)??(f.action==="show"&&f.spec!==void 0?await Zt(d,f.spec,P,{env:h.env}):void 0)??await da(d,f,P)??await ia(d,f,P);if(C)return{displayId:A.displayId,failure:C};let I=o.inPlace?o.shownDisplayId:A.displayId,O=await Sa(d,y,f,{context:{displayId:I,signal:P},dependencies:h});return{...A,...O,...T}}async function Ea({inPlace:o,signal:d},y,f,{args:h,dependencies:P}){return o?{}:Ra(y,f,h,{dependencies:P,signal:d})}async function Dr(o,d){let{action:y,success:f,device:h,deviceScreenRound:P,signal:g}=o;if(y!=="show"||!f||h.platform!=="android")return{};if(h.formFactor!=="watch")return{};if(typeof P==="boolean")return{screenRound:P};let A=await(d.screenRoundFactory?.(h)??new nB((d.adbFactory??v).create(h))).isScreenRound(g);return A===void 0?{}:{screenRound:A}}function Lr(o){let{action:d,success:y,device:f}=o;return d==="show"&&y&&f.platform==="android"&&f.formFactor==="automotive"?{formFactor:"automotive"}:{}}function Ta(o,d,y,{action:f,success:h,clearFailedShow:P}){if(f==="dismiss"&&h||f==="show"&&!h&&P)o.dismiss(d.deviceId,y.id)}function Aa(o,d,y,f){if(f.args.action==="show"&&!f.inPlace)o.show(d,f.target.id,y)}function Ca(o,d,y,f){if(f.inPlace&&f.success)o.show(d,f.target.id,y)}function Oa(o){if(o.all)return{all:!0};return{id:o.action==="show"?o.spec.id:o.id}}function Ia(o,d,y){return y.id?o.shownOnDevice(d.deviceId,y.id):void 0}async function _a(o,d,y,{device:f,signal:h}){return o?{uploaded:[],prepared:[],failure:o}:Ve(y.target,d,y.assetReaders,{signal:h,cached:Ga(y,f.deviceId)})}async function Fr(o,d,y,{scope:f,queue:h,signal:P,mcpSessionId:g}){if(y.action==="patch"){let{store:T,target:A,cacheInvalidator:C}=o;return nr({store:T,transport:A.transport,supportsPatch:async()=>A.android?A.android.supportsCommand(Ff):A.ios?.supportsCapability(Ff)===!0,specRefusal:async(I)=>(await Zt(A,I,P,{env:o.env}))?.error??await LP(I,d.deviceId,o.shaderAssetCache??CR()),platform:d.platform==="android"?"android":"ios",queue:h,retire:(I)=>Nr(C,d,I),mcpSessionId:g},d.deviceId,{id:y.id,ops:y.ops,baseRevision:y.baseRevision,timeoutMs:y.timeoutMs},P)}return Ma(o,d,{...y,action:y.action},{scope:f,signal:P,mcpSessionId:g})}async function Ma(o,d,y,{scope:f,signal:h,mcpSessionId:P}){let{store:g,events:T,target:A,commits:C}=o,I=Oa(y),O=ae(A.transport),_=Ia(g,f,I),x=y.action==="show"&&_!==void 0&&y.reset!==!0,F=await Na(A,I,x,h),q=Va(C,f,y.action,I),D={commits:C,scope:f,target:I,generation:q,sent:!1,startedFreshEvents:!1,mcpSessionId:P};try{let M=await $a(D,()=>xr({inPlace:x,shownDisplayId:_?.displayId,signal:h},A,d,{args:y,dependencies:o})),j=M.spec?{...y,spec:M.spec}:y,G=xa(j),Q=await ze(D,h,Ua(M,x,d,{args:y,dependencies:o})),U=x?_?.displayId:M.displayId,Z=await ze(D,h,_a(M.failure,G,o,{device:d,signal:h}));if(Z.failure)eo(D);let{result:Y,warning:we,mutationReply:N}=await ze(D,void 0,ur(A,G,Z,{signal:h,displayId:U,env:o.env,superseded:()=>Ye(C,f,I,q),beforeSend:async()=>{if(h?.throwIfAborted(),await Mr(A,d,y,{dependencies:o,signal:h})?.(),Aa(T,f,O,{target:I,args:y,inPlace:x}),D.startedFreshEvents=y.action==="show"&&!x,y.action==="show"&&I.id)o.store.beginShowDispatch(f.deviceId,I.id);if(D.sent=!0,y.action==="show")D.specTicket=g.shownSpecs.beginShow(f.deviceId,I.id,y.replaceOthers,d.platform==="android"?"android":"ios")}})).then(Da);qr(g,D,{action:y.action,success:Y.success,id:I.id,spec:j.spec,replaceOthers:y.replaceOthers,variant:y.variant,result:Y}),Nr(o.cacheInvalidator,d,Y),TG(d.deviceId,G.action,G.spec,{accepted:Y.success&&!Ye(C,f,I,q),sent:D.sent,id:G.id,all:G.all});let le={...Ya(y,_,Q,Y.success),chrome:M.chrome},ie=Ye(C,f,I,q)?Wa(o,{args:y,target:I,result:Y,placed:le}):Ba(o,f,O,{args:y,target:I,result:Y,placed:le,inPlace:x,previouslyShown:_!==void 0,startedFreshEvents:D.startedFreshEvents}),{warning:re,...ye}=await Ar({android:A.android!==void 0,action:y.action,success:Y.success,hiddenReason:Sb(Y.hiddenReason),spec:G.spec,superseded:()=>Ye(C,f,I,q),capture:()=>(o.anchorHierarchyCaptureFactory??Pn)(d),timer:o.timer,displayId:U,signal:h}),Ke=j.spec;return{...N,lastResult:ie,...Z.uploaded.length>0?{uploadedAssets:Z.uploaded}:{},...Ja(M),...await La(j,d,o,{result:Y,signal:h}),...ye,...za(Y,[we,le.warning,re],F,Ke)}}catch(M){throw TG(d.deviceId,y.action,void 0,{accepted:!1,sent:D.sent}),M}finally{qr(g,D),Ha(D)}}function xa(o){return o.action==="show"&&o.pseudoLocale===!0&&o.spec?{...o,spec:Er(o.spec)}:o}function Da(o){let d=o.result.errorCode==="render_failed"?lS(o.result):void 0;return{...o,result:d?{...o.result,success:!1,error:d.error}:o.result,mutationReply:d??{success:o.result.success,error:o.result.error??void 0}}}async function La(o,d,y,{result:f,signal:h}){let{success:P,screenRound:g}=f;return{...await Fa(o,d,y.target,P),...o.action==="show"&&P?f1(o.spec):{},...o.action==="show"&&P?h1(o.spec):{},...await Dr({action:o.action,success:P,device:d,deviceScreenRound:g,signal:h},y),...Lr({action:o.action,success:P,device:d})}}function qa(o){return Number.parseInt(o.iosVersion??o.osVersion??"",10)||void 0}async function Fa(o,d,y,f){if(o.action!=="show"||!f)return{};let h=_C.fields(o.spec).length>0?await y.android?.supportsCommand(_C.capability):!1,P=ote(o.spec,d.platform==="ios"?"ios":"android",(T)=>d.platform==="android"?T===_C.capability&&h===!0:y.ios?.supportsCapability(T)===!0,qa(d));P.push(...ste(o.spec,o.locale));let g=d.platform==="ios"?y1(o.spec):[];if(g.length>0)P.push({platform:"ios",construct:"node.gestures",effect:"substituted",paths:g.slice(0,20),...g.length>20?{total:g.length}:{},detail:[...g.some((T)=>T.endsWith(".onLongPress"))?["Long-press uses the platform default threshold (about 0.5 s on iOS versus the Android long-press timeout, about 0.4 s)."]:[],...g.some((T)=>T.endsWith(".onDoubleTap"))?["The double-tap window is the system's. With onDoubleTap, onTap fires only after that window elapses."]:[]].join(" ")});return P.length>0?{platformNotes:P}:{}}async function Na(o,d,y,f){if(!y||!o.android)return;let h=await o.android.supportsCommand(gy);if(f?.throwIfAborted(),h)return;return`the connected CtrlProxy does not advertise ${gy}, so prototype ${d.id} was re-shown fresh on its display: pager pages restarted. Update the connected CtrlProxy to keep pages.`}function Nr(o,d,y){if(y.success)o.invalidate(d,!0)}function eo(o){let{commits:d,scope:y,target:f,generation:h,sent:P}=o;if(!P&&h!==void 0&&f.id!==void 0)d.withdraw(y.deviceId,f.id,h)}function qr(o,d,y){if(d.specTicket!==void 0){let{shown:f,refusal:h}=y?dr(y):{},{mcpSessionId:P}=d,g=f&&P!==void 0?{...f,mcpSessionId:P}:f;o.shownSpecs.endShow(d.scope.deviceId,d.specTicket,g,h)}}function Ha(o){let{commits:d,scope:y,target:f,generation:h}=o;if(h!==void 0&&f.id!==void 0)d.settle(y.deviceId,f.id,h)}async function ze(o,d,y){try{let f=await y;return d?.throwIfAborted(),f}catch(f){throw eo(o),f}}async function $a(o,d){let y=await ze(o,void 0,d());if(y.failure)eo(o);return y}function Va(o,d,y,f){return y==="show"&&f.id?o.begin(d.deviceId,f.id):void 0}function Ye(o,d,y,f){return f!==void 0&&y.id!==void 0&&!o.isLatest(d.deviceId,y.id,f)}async function Ua(o,d,y,{args:f,dependencies:h}){return o.failure?void 0:ja(d,o.displayId,y,{args:f,dependencies:h})}function Ba(o,d,y,f){let{store:h,events:P}=o,{args:g,target:T,result:A,placed:C,inPlace:I,previouslyShown:O}=f;if(Ca(P,d,y,{target:T,inPlace:I,success:A.success}),Ta(P,d,T,{action:g.action,success:A.success,clearFailedShow:f.startedFreshEvents&&!O}),g.action==="show"&&A.success&&T.id&&g.replaceOthers!==!1)P.replaceShown(d.deviceId,T.id);let _=h.record(d,g.action,T,{result:A,details:{displayId:C.displayId,data:g.action==="show"?g.spec?.data:void 0,chrome:C.chrome,replaceOthers:g.replaceOthers}});if(T.id&&P.isDismissed(d,T.id))h.dismissed(d,T.id);return _}function Wa(o,d){let{args:y,target:f,result:h,placed:P}=d;return{...f,lastAction:y.action,...P.displayId===void 0?{}:{displayId:P.displayId},...y.action==="show"&&h.success&&P.chrome!==void 0?{chrome:P.chrome}:{},...R2(y.action,h),...OK(y.action,h),success:h.success,...h.error?{error:h.error}:{},...h.totalTimeMs===void 0?{}:{totalTimeMs:h.totalTimeMs},timestamp:o.now()}}async function ja(o,d,y,{args:f,dependencies:h}){if(!o)return d;if(f.display===void 0)return;try{return await YE(y,f.display,{adb:(h.adbFactory??v).create(y),lastRenderedObservation:h.lastRenderedObservation})||void 0}catch(P){return e.debug(`[prototype] ignored display selector did not resolve: ${r(P)}`),null}}function Ya(o,d,y,f){if(o.action!=="show"||d?.id===void 0)return{displayId:y??void 0};if(!f)return{displayId:d.displayId};if(o.reset===!0)return{displayId:y??void 0};if(o.display===void 0||y===d.displayId)return{displayId:d.displayId};let h=d.displayId===void 0?"the default display":`logical display ${d.displayId}`;return{displayId:d.displayId,warning:`display was ignored: prototype ${d.id} is already shown on ${h}, and a show with the same id replaces it in place there. Pass reset: true to show it fresh on the requested display.`}}function Ja(o){return o.anchors?.length?{anchors:o.anchors,...o.hierarchyUpdatedAt===void 0?{}:{hierarchyUpdatedAt:o.hierarchyUpdatedAt}}:{}}function za(o,d,y,f){let h=o.success?FO(o.degradedEffects):{},P=[...d,h.warning,o.success?y:void 0,...o.success?DK(f):[],...o.success?uae(f):[]].filter((g)=>g!==void 0).join(" ");return{...o.success&&o.missingAssets?.length?{missingAssets:o.missingAssets}:{},...h,...P?{warning:P}:{}}}function Ga(o,d){return{serial:d,cache:o.shaderAssetCache??CR()}}var Ge={success:!1,error:"The headless virtual device has no saved prototypes."};function Ka(o){let d=o.ops.flatMap((y)=>y.op!=="replaceNode"&&y.path.startsWith("/state/")?[Zp(y.path.slice(6))[0]]:[]);return[...new Set(d)].filter((y)=>y!==void 0)}function Hr(o,d,y,f){let h=[...new Set([...Object.keys(d),...Object.keys(y)])].filter((P)=>d[P]!==y[P]);for(let P of h)o.set(P,f);return h}function Xa(o,d){let y=Ka(d);if(y.length===0)return;let{baseRevision:f}=d;if(f===void 0||f>o.ledger.revision)return{success:!1,delivery:"answered",revision:o.ledger.revision,error:f===void 0?"baseRevision is required when a patch has /state ops":`baseRevision ${f} is newer than the device revision ${o.ledger.revision}`};let h=y.filter((g)=>(o.stateRevisions.get(g)??0)>f);if(h.length===0)return;let P=Object.fromEntries(h.filter((g)=>(g in o.state)).map((g)=>[g,o.state[g]]));return{success:!1,delivery:"answered",error:"conflict",revision:o.ledger.revision,conflict:{revision:o.ledger.revision,state:P}}}function $r(o,d,y){let f={};return X({root:o.root},(h)=>{if(h.type!=="pager"||typeof h.id!=="string")return;let P=Math.max(0,(Array.isArray(h.children)?h.children.length:0)-1),g=typeof h.stateKey==="string"?d[h.stateKey]:void 0,T=Object.hasOwn(y,h.id)?y[h.id]:void 0,A=typeof g==="number"?Math.trunc(g):T??0;f[h.id]=Math.min(Math.max(A,0),P)}),f}function Vr(o,d={}){let y={};return X({root:o.root},(f)=>{if(f.type!=="stack"||typeof f.id!=="string"||typeof f.start!=="string")return;let h=Object.hasOwn(d,f.id)?d[f.id]:void 0,P=h===void 0?void 0:Qa(f,h);if(P){y[f.id]=P;return}let g=c(Wr(f,f.start));y[f.id]={path:[f.start],depth:1,...g?.params===void 0?{}:{params:[{}]}}}),y}function Qa(o,d){let y=d.path.map((h,P)=>({screen:h,params:d.params?.[P]??{}})).filter(({screen:h,params:P})=>Za(o,h,P)).slice(0,W.limits.MAX_PROTOTYPE_STACK_DEPTH);if(y.length===0)return;let f=y.map((h)=>structuredClone(h.params));return{path:y.map((h)=>h.screen),depth:y.length,...f.some((h)=>Object.keys(h).length>0)?{params:f}:{}}}function Wr(o,d){let y=c(o.routes);return y&&Object.hasOwn(y,d)?y[d]:void 0}function Za(o,d,y){let f=c(o.screens);if(!f||!Object.hasOwn(f,d))return!1;let h=c(c(Wr(o,d))?.params)??{},P=Object.keys(y);return P.length===Object.keys(h).length&&P.every((g)=>Object.hasOwn(h,g)&&h[g]===ep(y[g]))}function ep(o){if(typeof o==="string")return"string";if(typeof o==="boolean")return"boolean";return typeof o==="number"&&Number.isFinite(o)?"number":void 0}function Ur(o,d){let y={...d};return X({root:o.root},(f)=>{if(f.type!=="pager"||typeof f.stateKey!=="string")return;let h=y[f.stateKey];if(typeof h!=="number"||!Number.isInteger(h))return;let P=Math.max(0,(Array.isArray(f.children)?f.children.length:0)-1);y[f.stateKey]=Math.min(Math.max(h,0),P)}),y}var Br=(o)=>o&&typeof o==="object"&&!Array.isArray(o)?structuredClone(o):{};class to{clock;shown=new Map;ledgers=new Map;assets=new Set;listeners=new Set;capabilities;constructor(o,d=xQ){this.clock=o;this.capabilities=new Set(d)}async supportsCommand(o){return this.capabilities.has(o)}async requestShowPrototype(o,d,y,f={}){let h=this.shown.get(o.id);if(f.replaceOthers!==!1)[...this.shown.keys()].filter((O)=>O!==o.id).forEach((O)=>this.shown.delete(O));let P=h!==void 0&&f.reset!==!0,g={...structuredClone(o)},T=Ur(g,Br(g.state));g.state=T;let A=this.ledgers.get(o.id)??{revision:0,lastSequence:0},C=++A.revision;this.ledgers.set(o.id,A),this.shown.set(o.id,{spec:g,state:T,pages:$r(g,T,P?h.pages:{}),ledger:A,stacks:Vr(g,P?h.stacks:{}),stateRevisions:new Map(Object.keys(T).map((O)=>[O,C]))});let I=this.missingAssets(g);return{success:!0,totalTimeMs:0,timestamp:this.clock.now(),...I.length>0?{missingAssets:I}:{}}}async requestDismissPrototype(o){if(o.all)this.shown.clear();else if(o.id!==void 0)this.shown.delete(o.id);return{success:!0,totalTimeMs:0,timestamp:this.clock.now()}}async requestPatchPrototype(o){let d=this.shown.get(o.id);if(!d)return{success:!1,delivery:"answered",error:`No prototype with id ${o.id} is shown on the virtual device.`};let y=Xa(d,o);if(y)return y;let f={...d.spec,state:d.state},h=XO(f,o.ops);if(!h.success)return{success:!1,delivery:"answered",error:`Invalid patch at ${h.error.path}: ${h.error.message}`};let P=Ur(h.spec,Br(h.spec.state));d.ledger.revision+=1;let g=Hr(d.stateRevisions,d.state,P,d.ledger.revision).filter((T)=>(T in P));if(d.spec={...h.spec,state:P},d.state=P,d.pages=$r(d.spec,P,d.pages),d.stacks=Vr(d.spec,d.stacks),g.length>0)this.dispatch({id:o.id,kind:"emit",name:"change",payload:g.length===1?{key:g[0],value:P[g[0]]}:{keys:g,values:Object.fromEntries(g.map((T)=>[T,P[T]]))}});return{success:!0,delivery:"answered",revision:d.ledger.revision,totalTimeMs:0}}async requestInspectPrototypes(){let o=[...this.shown.entries()].map(([y,f])=>({id:y,persistent:!1,state:{...f.state},pages:{...f.pages},...Object.keys(f.stacks).length?{stacks:structuredClone(f.stacks)}:{},lastSequence:f.ledger.lastSequence,...f.spec.data===void 0?{}:{data:structuredClone(f.spec.data)}})),d=Object.assign({},...o.map((y)=>y.stacks??{}));return{success:!0,prototypes:o,droppedEvents:0,timestamp:this.clock.now(),...Object.keys(d).length?{stacks:d}:{}}}async requestPutPrototypeAsset(o,d){return d?.abortSignal?.throwIfAborted(),d?.onDispatch?.(),this.assets.add(o.id),{success:!0,dispatched:!0,acknowledged:!0}}async requestRemovePrototypeAsset(o,d){return d?.abortSignal?.throwIfAborted(),d?.onDispatch?.(),this.assets.delete(o),{success:!0,dispatched:!0,acknowledged:!0}}async requestSavePrototype(){return Ge}async requestListSavedPrototypes(){return Ge}async requestPinSavedPrototype(){return Ge}async requestDeleteSavedPrototype(){return Ge}onPrototypeEvent(o){return this.listeners.add(o),()=>{this.listeners.delete(o)}}dispatch(o){let d=this.shown.get(o.id);if(!d)return!1;if(o.state!==void 0){let f={...d.state,...o.state};d.ledger.revision+=1,Hr(d.stateRevisions,d.state,f,d.ledger.revision),d.state=f}if(o.pages!==void 0)d.pages={...d.pages,...o.pages};d.ledger.lastSequence+=1;let y={type:"prototype_event",timestamp:this.clock.now(),id:o.id,sequence:d.ledger.lastSequence,kind:o.kind,name:o.name,payload:o.payload??null,state:{...d.state},pages:{...d.pages},...Object.keys(d.stacks).length?{stacks:structuredClone(d.stacks)}:{}};return[...this.listeners].forEach((f)=>f(y)),!0}shownIds(){return[...this.shown.keys()]}missingAssets(o){let{images:d,fonts:y,shaders:f}=Ab(o);return[...d,...y,...f].filter((h)=>!this.assets.has(h)).sort()}}function tp(o,d){let y=Fe();return{sessionUuid:d.sessionUuid??y?.routingSessionUuid??y?.toolSelectionProfileUuid,deviceId:o.deviceId}}function Jr(){let o=ig();return o&&o.trim().length>0?o:void 0}function op(o,d,y=Jr()){return(d==="show"||d==="patch")&&o.success&&y?{...o,mcpSessionId:y}:o}function np(o,d,y){return{scope:o,queue:d,signal:me(y),mcpSessionId:Jr()}}var jr=(o)=>Ze(k(o),o.success);function sp(o,d,y){let f=typeof d==="object"&&d!==null&&"action"in d?d.action:void 0,h=typeof f==="string"&&HM(f)&&!H0(y);return tV(o)&&!h?(P)=>jr({...P,virtualDevice:DQ()}):jr}function ip(){return w.sessionManager()}function ap(o){let d=w.sessionManager();if(!d)return;return d.onDeviceOwnershipChange((y,f)=>{if(f==="full"||d.getSessionForDevice(y)===null)o(y)})}function pp(o,d){if(o.platform==="android")return;if(o.platform!=="ios")return new t("Prototypes need an Android device or an iOS simulator. Target one with deviceId or sessionUuid.");let y=wU(d.spec,d.assets);if(y)return new t(y);if(d.display!==void 0)return new t("display is Android only; omit display on iOS.");if(d.spec!==void 0){if(ue(d.spec).devicePersistence)return new t('window.persistence "device" is Android only; omit it on iOS.');let h=d.action==="show"||d.action==="save"?$e(d.spec,"ios"):void 0;if(h)return new t(`Invalid prototype at spec.${h.path}: ${h.message}. Nothing was shown.`)}return}function dp(o){return o.spec===void 0?o:{...o,spec:Lf(o.spec)}}function cp(o){return(d)=>d.platform==="ios"?new rt({deviceId:d.deviceId,simctl:new nt(new L),files:new st,timer:o.timer??i,ids:B}):new Ut({adb:(o.adbFactory??v).create(d),timer:o.timer??i,ids:B,tempFiles:new Bt})}function up(){return{subscribeSessionRelease:(o)=>Ai.subscribe((d,y,f,h)=>o(d,h?.upgradeOnly?void 0:f?.deviceId)),subscribeDeviceRemoval:(o)=>ma().onDeviceRemoved(o),subscribeDeviceUnbound:ap,deviceUnboundSource:ip}}function lp(o,d,y){return{androidTarget:(P)=>{let g=o(P),T=y.android.get(g);if(T===void 0)T=new bt(g),y.android.set(g,T),jo(g,P.deviceId,y.requests),Xo(g,P.deviceId,y.channels);return{transport:T,android:T}},iosTarget:(P)=>{let g=d.get(P.deviceId);if(g===void 0)return;let T=y.ios.get(g);if(T===void 0)T=new cU(g),y.ios.set(g,T),Wo(g,P.deviceId,y.requests),Ko(g,P.deviceId,y.channels);return{transport:T,ios:T}}}}function oo(o){return o.clock??o.timer??i}function Yr(o,d){let y=o.store??new St(oo(o),void 0,d),f=o.timer??i,h=new mt({ids:o.idGenerator??B,timer:f}),P=Bo(f,h),g=zo(f,h,o.channelExecutor),T=vo(o,y),A=new gt(f,y,{telemetry:Xr.getInstance(),requests:Go(P,g),recorder:T}),C=or(o.lifecycle??up(),A),I=!1;return{store:y,events:A,recorder:T,commits:new ht,patchQueue:rr(),transports:{android:new WeakMap,ios:new WeakMap,requests:P,channels:g},mocks:h,virtualDevice:o.virtualDevice??new to(oo(o)),ensureLifecycle:C.ensureSubscribed,dispose:()=>{if(!I)I=!0,C.unsubscribe(),A.dispose(),h.clearAll()}}}var Re,ve;function yp(o){let{store:d,clock:y,timer:f,lifecycle:h}=o;if(d||y||f||h||o.testSessionStore||o.idGenerator||o.channelExecutor||o.virtualDevice)return Yr(o);return Re??=Yr(o,N1()),Re}function fp(){return Re?.store.shownSpecs}dX(fp);function mp(o){let d=()=>{let y=ve?.dispose===d;if(y)ve=void 0;if(o!==Re)o.dispose();else if(y)o.dispose(),Re=void 0};return d}function hp(o){let d=o&&typeof o==="object"&&!Array.isArray(o)?{...o}:{};return Hs(d),P1.safeParse(d)}async function Pp(o,d,y){let f=await gp(o,d,y);return"error"in f?f:vp(f.args,d,y)}async function gp(o,d,y){if(o.specPath===void 0||!zr(o.action))return{args:o};let{specPath:f,...h}=o,P=await NM(f,d);if(y?.throwIfAborted(),"error"in P)return P;let g=UM(P.json);if(g)return{error:`specPath ${f}: ${g.path}: ${g.text}`};return{args:{...h,spec:P.json}}}var zr=(o)=>o==="show"||o==="screenMap"||o==="share";async function vp(o,d,y){if(o.mockPath===void 0)return{args:o};let{mockPath:f,...h}=o,P=await NM(f,d,{label:"mockPath",maxBytes:u1});if(y?.throwIfAborted(),"error"in P)return P;let g=P.json;if(typeof g!=="object"||g===null||Array.isArray(g))return{error:`mockPath ${f}: expected an object of {backendId: definition}`};return{args:{...h,mock:{...g}}}}function wp(o,d,y,f){if("error"in o)return o;let h=tV(d)?CQ(o.args):void 0;if(h)return{error:h};let P=dp(o.args),g=d.platform==="ios"?void 0:wy(P.spec,y);return g?{error:g}:Sp(P,f)}function Sp(o,d){if(o.mock===void 0)return{args:o};try{d.defineAll(o.mock)}catch(y){return e.warn("Prototype show mock definition failed",y),{error:u(y,"Mock backend definition failed").message}}return{args:o}}function bp(o){return zr(o.action)&&o.specPath!==void 0||o.action==="show"&&o.mockPath!==void 0}async function Rp(o,d,y,f){if(d.action==="share")return await kp(d,y,f);if(zG(d.action))return await wr(o.preview(),d);return d.action==="screenMap"?Ep(d.spec):bo(o.mocks,d)}async function kp(o,d,y=new Vt){return await aJ({spec:o.spec,assets:o.assets,url:o.url},{assetFileReader:d.assetFileReader,observationScreenshotReader:d.observationScreenshotReader,files:y})}function Ep(o){let d=l1(o);return{success:!0,screenMap:d,mermaid:MJ(d)}}function Uh(o={}){let d=yp(o);if(ve&&ve.host!==d)ve.dispose();d.ensureLifecycle();let{store:y,events:f,commits:h}=d,P=o.clientFactory??((M)=>E.getInstance(M)),g=(M)=>tV(M)?d.virtualDevice:P(M),T=o.agentConnections??Ooe,{androidTarget:A,iosTarget:C}=lp(g,T,d.transports),I=o.cacheInvalidator??new ai,O=oo(o),_={env:o.env,assetFileReader:o.assetFileReader??BM,observationScreenshotReader:o.observationScreenshotReader??cJ},x=oX({..._,installer:o.iosSavedPrototypeInstaller,protoViewer:o.protoViewerFactory??cp(o)}),F=()=>o.preview??vr(),q=async(M,j,G,Q)=>{d.ensureLifecycle();let U=sp(M,j,o.env),Z=hp(j);if(!Z.success)return U({success:!1,error:`Invalid prototype input: ${Z.error.message}`});let Y=bp(Z.data)?await Pp(Z.data,_.assetFileReader,Q):{args:Z.data},we=wp(Y,M,o.env,d.mocks);if("error"in we)return U({success:!1,error:we.error});let N=we.args,le=x(M,{...N,spec:N.spec},me(Q),()=>pp(M,N));if(le){let H=await le;if(H)return U(H)}if(HM(N.action)){let H=o.protoViewerShareFiles,ke={mocks:d.mocks,preview:F};return U(await Rp(ke,N,_,H))}let ie=tp(M,N);if(wo(N.action)){let H={recorder:d.recorder,store:y,events:f,preview:()=>F().server};return U(await So(H,ie,N))}let re=M.platform==="android"?A(M):C(M);if(!re){let H=new t(Moe(M.deviceId));return U({success:!1,error:H.message})}let{action:ye}=N;if(ao(ye))return U(await po(N,{store:y,events:f},M,{target:re,scope:ie,signal:Q}));if(ye==="awaitEvent"){let H=ae(re.transport),ke=await uo(f,ie,H,{query:N,context:{progress:G,signal:Q}});return U({success:!0,...ke,...co(y,ie,N.id,ke)})}let Ke={store:y,events:f,target:re,assetReaders:_,commits:h,cacheInvalidator:I,now:()=>O.now(),timer:o.timer,adbFactory:o.adbFactory,lastRenderedObservation:o.lastRenderedObservation,anchorHierarchyCaptureFactory:o.anchorHierarchyCaptureFactory,screenRoundFactory:o.screenRoundFactory,shaderAssetCache:o.shaderAssetCache,env:o.env},Gr=await sX({...N,action:ye,spec:N.spec},()=>{let H=me(Q);return{client:re.android,...iX(M,o),signal:H,stageAssets:()=>Ve(re,N,_,{signal:H})}},(H)=>Fr(Ke,M,{...N,action:H},np(ie,d.patchQueue,Q)));return U(op(Gr,ye))},D=mp(d);return ve={host:d,dispose:D},{handler:q,dispose:D}}export{op as attributeRevision,Uh as createPrototypeToolRuntime,fp as daemonPrototypeShownSpecs};
20
+
21
+ //# debugId=E82C09B14559701464756E2164756E21
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Y,I}from"./chunk-58wzr3mt.js";import{Bl}from"./chunk-qcxzr2my.js";import*as c from"fs";import*as l from"os";import*as n from"path";function D3(o={}){let t={env:o.env??process.env,platform:o.platform??process.platform,homedir:o.homedir??l.homedir,directoryExists:o.directoryExists??b};f(t),m(t)}function f(o){let{env:t,directoryExists:e}=o,r=n.delimiter,i=t.PATH??"",s=new Set(i.split(r).filter(Boolean)),u=h(o),a=[];for(let d of u)if(!s.has(d)&&e(d))a.push(d),s.add(d);if(a.length===0)return;t.PATH=i.length>0?`${i}${r}${a.join(r)}`:a.join(r)}function m(o){let{env:t,directoryExists:e}=o;if(t.ANDROID_HOME||t.ANDROID_SDK_ROOT)return;for(let r of A(o))if(e(r)){t.ANDROID_HOME=r;return}}function h({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin","/opt/homebrew/bin","/opt/homebrew/sbin",n.join(r,"Library/Android/sdk/platform-tools"),n.join(r,"Library/Android/sdk/emulator"),n.join(r,"Library/Android/sdk/cmdline-tools/latest/bin")];if(t==="linux")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin",n.join(r,"Android/Sdk/platform-tools"),n.join(r,"Android/Sdk/emulator"),n.join(r,"Android/Sdk/cmdline-tools/latest/bin")];if(t==="win32"){let i=I(Y.LOCALAPPDATA,o),s=i?n.join(i,"Android","Sdk"):"";return[...s?[n.join(s,"platform-tools"),n.join(s,"emulator"),n.join(s,"cmdline-tools","latest","bin")]:[]]}return[]}function A({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return[n.join(r,"Library/Android/sdk")];if(t==="linux")return[n.join(r,"Android/Sdk")];if(t==="win32"){let i=I(Y.LOCALAPPDATA,o);return i?[n.join(i,"Android","Sdk")]:[]}return[]}function b(o){return Bl(()=>c.statSync(o).isDirectory(),()=>!1)}var p=async()=>{};function Jte(o){let t=p;return p=o,()=>{p=t}}function jL(o){return p(o)}
3
- export{D3,Jte,jL};
2
+ import{Y,I}from"./chunk-5wk1t46v.js";import{Kl}from"./chunk-j69g8b50.js";import*as c from"fs";import*as l from"os";import*as n from"path";function eY(o={}){let t={env:o.env??process.env,platform:o.platform??process.platform,homedir:o.homedir??l.homedir,directoryExists:o.directoryExists??b};f(t),m(t)}function f(o){let{env:t,directoryExists:e}=o,r=n.delimiter,i=t.PATH??"",s=new Set(i.split(r).filter(Boolean)),u=h(o),a=[];for(let d of u)if(!s.has(d)&&e(d))a.push(d),s.add(d);if(a.length===0)return;t.PATH=i.length>0?`${i}${r}${a.join(r)}`:a.join(r)}function m(o){let{env:t,directoryExists:e}=o;if(t.ANDROID_HOME||t.ANDROID_SDK_ROOT)return;for(let r of A(o))if(e(r)){t.ANDROID_HOME=r;return}}function h({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin","/opt/homebrew/bin","/opt/homebrew/sbin",n.join(r,"Library/Android/sdk/platform-tools"),n.join(r,"Library/Android/sdk/emulator"),n.join(r,"Library/Android/sdk/cmdline-tools/latest/bin")];if(t==="linux")return["/usr/bin","/bin","/usr/sbin","/sbin","/usr/local/bin","/usr/local/sbin",n.join(r,"Android/Sdk/platform-tools"),n.join(r,"Android/Sdk/emulator"),n.join(r,"Android/Sdk/cmdline-tools/latest/bin")];if(t==="win32"){let i=I(Y.LOCALAPPDATA,o),s=i?n.join(i,"Android","Sdk"):"";return[...s?[n.join(s,"platform-tools"),n.join(s,"emulator"),n.join(s,"cmdline-tools","latest","bin")]:[]]}return[]}function A({env:o,platform:t,homedir:e}){let r=e();if(t==="darwin")return[n.join(r,"Library/Android/sdk")];if(t==="linux")return[n.join(r,"Android/Sdk")];if(t==="win32"){let i=I(Y.LOCALAPPDATA,o);return i?[n.join(i,"Android","Sdk")]:[]}return[]}function b(o){return Kl(()=>c.statSync(o).isDirectory(),()=>!1)}var p=async()=>{};function _re(o){let t=p;return p=o,()=>{p=t}}function lB(o){return p(o)}
3
+ export{eY,_re,lB};
4
4
 
5
- //# debugId=C5674C7F5ACEBD7A64756E2164756E21
5
+ //# debugId=42AAFF28E791661564756E2164756E21