@shumai-one/shumai 0.6.2 → 0.6.4

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 (192) hide show
  1. package/bin/{chunk-mcj1xpcc.js → chunk-01vx2chc.js} +2 -2
  2. package/bin/chunk-0epkrexd.js +2 -0
  3. package/bin/chunk-0h5239kt.js +2 -0
  4. package/bin/{chunk-jt0ykktx.js → chunk-0jnstdgf.js} +1 -1
  5. package/bin/{chunk-x03jwaga.js → chunk-0njsjy6x.js} +4 -4
  6. package/bin/{chunk-7naa7tpn.js → chunk-13rq2gtr.js} +2 -2
  7. package/bin/chunk-1aqs9sdh.js +3 -0
  8. package/bin/{chunk-m0q2cgfg.js → chunk-22jbsrka.js} +1 -1
  9. package/bin/chunk-2qknebmd.js +1 -0
  10. package/bin/{chunk-a411xhmm.js → chunk-2qzmh3ae.js} +4 -4
  11. package/bin/{chunk-2nhgdqdg.js → chunk-2tt0b8ym.js} +2 -2
  12. package/bin/{chunk-p3f5aevs.js → chunk-2zm7czk6.js} +1 -1
  13. package/bin/{chunk-p4s95471.js → chunk-396tfwdx.js} +1 -1
  14. package/bin/chunk-3mx4trvh.js +10 -0
  15. package/bin/{chunk-b5rhvzv9.js → chunk-45pb3kzz.js} +2 -2
  16. package/bin/{chunk-q83h0hkx.js → chunk-47fmhzwv.js} +2 -2
  17. package/bin/chunk-4awk4xhq.js +2 -0
  18. package/bin/{chunk-2cdxm1cp.js → chunk-4b2x2qba.js} +23 -23
  19. package/bin/{chunk-knj2s8mg.js → chunk-4rjy7ybr.js} +8 -8
  20. package/bin/{chunk-q8w4mbw4.js → chunk-598x693h.js} +2 -2
  21. package/bin/chunk-5c7ztqs7.js +1 -0
  22. package/bin/{chunk-2jj4j8cn.js → chunk-65dh7x4c.js} +2 -2
  23. package/bin/{chunk-hnkcgvcj.js → chunk-66e2vrky.js} +1 -1
  24. package/bin/{chunk-g22wmpk1.js → chunk-6j3beg6n.js} +2 -2
  25. package/bin/{chunk-cgmebxx6.js → chunk-6ke13k69.js} +1 -1
  26. package/bin/{chunk-7sgrtxbt.js → chunk-6rqakmg0.js} +2 -2
  27. package/bin/{chunk-4mws03es.js → chunk-6ty4tfmf.js} +3 -3
  28. package/bin/chunk-7e9ws6dh.js +129 -0
  29. package/bin/chunk-7mdddkfc.js +1 -0
  30. package/bin/{chunk-q2bew2vc.js → chunk-7q4mgd5x.js} +2 -2
  31. package/bin/chunk-7yv7shad.js +1 -0
  32. package/bin/{chunk-qwpkcp8d.js → chunk-81b8rfv7.js} +2 -2
  33. package/bin/{chunk-atfz7g7e.js → chunk-8a7ymmd4.js} +2 -2
  34. package/bin/chunk-8ac9at5y.js +2 -0
  35. package/bin/{chunk-gxepkvt2.js → chunk-8zcfgz9c.js} +1 -1
  36. package/bin/{chunk-mcw198kg.js → chunk-955kf5kc.js} +8 -8
  37. package/bin/{chunk-jzgbxqdg.js → chunk-978rm9a9.js} +2 -2
  38. package/bin/{chunk-jt02kpfc.js → chunk-9qzbrp4d.js} +2 -2
  39. package/bin/{chunk-tekwpkjf.js → chunk-a283dh05.js} +2 -2
  40. package/bin/chunk-aa2a06cc.js +1 -0
  41. package/bin/{chunk-8cjet7pp.js → chunk-ajr1w3vq.js} +6 -6
  42. package/bin/chunk-akafypge.js +218 -0
  43. package/bin/chunk-amk373q2.js +2 -0
  44. package/bin/chunk-apq2gvvp.js +4 -0
  45. package/bin/chunk-av2w1sez.js +2 -0
  46. package/bin/{chunk-5wapd171.js → chunk-b6kmj34z.js} +12 -12
  47. package/bin/chunk-bkzaw9p8.js +1 -0
  48. package/bin/{chunk-zezje74z.js → chunk-bssb9tar.js} +3 -3
  49. package/bin/chunk-bwvj1aqc.js +1 -0
  50. package/bin/chunk-by9esjn7.js +3 -0
  51. package/bin/chunk-bywk8mbc.js +2 -0
  52. package/bin/{chunk-9xhjy897.js → chunk-c61g9hfa.js} +4 -4
  53. package/bin/{chunk-zrszykjf.js → chunk-cdcgjh8k.js} +1 -1
  54. package/bin/{chunk-yk12hydf.js → chunk-d277evce.js} +4 -4
  55. package/bin/{chunk-55h9ze53.js → chunk-d3brvxh7.js} +2 -2
  56. package/bin/{chunk-9t3p4xp6.js → chunk-dcb1nzf1.js} +1 -1
  57. package/bin/{chunk-mzsw9var.js → chunk-dfbzatq9.js} +2 -2
  58. package/bin/chunk-e0bckx12.js +2 -0
  59. package/bin/{chunk-3ckkwdjx.js → chunk-e2p4s2pj.js} +3 -3
  60. package/bin/chunk-e8zzg57c.js +2 -0
  61. package/bin/{chunk-vp3czaeh.js → chunk-edfaqwaq.js} +2 -2
  62. package/bin/chunk-ehgrp0f9.js +1 -0
  63. package/bin/chunk-evs2aaav.js +12 -0
  64. package/bin/{chunk-s9ksftq2.js → chunk-f5bhcjhw.js} +1 -1
  65. package/bin/{chunk-ns33grgx.js → chunk-fb9dedm2.js} +2 -2
  66. package/bin/{chunk-srxp5jav.js → chunk-ff0mh9p3.js} +32 -32
  67. package/bin/chunk-fpfby5tz.js +1 -0
  68. package/bin/{chunk-eyjfhdp9.js → chunk-gd3b5akr.js} +2 -2
  69. package/bin/{chunk-1wfg56z3.js → chunk-gm1fy3hm.js} +5 -5
  70. package/bin/{chunk-9n1w5dw1.js → chunk-gqkjx7rz.js} +3 -3
  71. package/bin/{chunk-1nvd90g2.js → chunk-h7f5370s.js} +1 -1
  72. package/bin/chunk-hcyhsn8e.js +2 -0
  73. package/bin/{chunk-vcrmjtcz.js → chunk-jxm0gzmf.js} +2 -2
  74. package/bin/{chunk-b7bnp021.js → chunk-k3ggy3xk.js} +2 -2
  75. package/bin/{chunk-257dcd2f.js → chunk-k9vjs21p.js} +2 -2
  76. package/bin/chunk-ka40gv72.js +1 -0
  77. package/bin/chunk-km70p970.js +2 -0
  78. package/bin/{chunk-e4yscwen.js → chunk-m6v8rb39.js} +8 -8
  79. package/bin/chunk-m8spagwp.js +4 -0
  80. package/bin/{chunk-y241cxff.js → chunk-mfh7mg5b.js} +1 -1
  81. package/bin/chunk-n0cn0218.js +2 -0
  82. package/bin/chunk-n54ftsdx.js +2 -0
  83. package/bin/{chunk-02fvcrej.js → chunk-n7cvj15k.js} +7 -7
  84. package/bin/chunk-na5fh7er.js +2 -0
  85. package/bin/chunk-neazdbxy.js +1 -0
  86. package/bin/chunk-nk24qw3m.js +1 -0
  87. package/bin/{chunk-73yncv54.js → chunk-nsbbseff.js} +2 -2
  88. package/bin/chunk-nseef85h.js +1 -0
  89. package/bin/chunk-p35ztj2z.js +3 -0
  90. package/bin/chunk-pcjc9ygv.js +2 -0
  91. package/bin/{chunk-167z646e.js → chunk-pemmtd8q.js} +1 -1
  92. package/bin/{chunk-82tps5n1.js → chunk-pzrqnnpg.js} +1 -1
  93. package/bin/{chunk-a74g6h8a.js → chunk-q43m934j.js} +2 -2
  94. package/bin/{chunk-r1xer8gn.js → chunk-q57m34h0.js} +3 -3
  95. package/bin/chunk-q5k72jz9.js +3 -0
  96. package/bin/chunk-q9fsxakd.js +2 -0
  97. package/bin/chunk-qadpe0ct.js +2 -0
  98. package/bin/chunk-qeypjv4f.css +1 -0
  99. package/bin/chunk-qw92z3wf.js +2 -0
  100. package/bin/chunk-r0byfq1t.js +1 -0
  101. package/bin/chunk-r0q88qw3.js +2 -0
  102. package/bin/chunk-rjhczkh3.js +2 -0
  103. package/bin/{chunk-mwktrwtx.js → chunk-s0wxbybf.js} +1 -1
  104. package/bin/{chunk-q5vkxee3.js → chunk-s4hkcw24.js} +2 -2
  105. package/bin/chunk-szta50g1.js +1 -0
  106. package/bin/chunk-t6cb99gp.js +2 -0
  107. package/bin/chunk-tcr080b9.js +1 -0
  108. package/bin/{chunk-yq32evnn.js → chunk-v4nqx084.js} +5 -5
  109. package/bin/{chunk-ympbfzz4.js → chunk-v7jzc3ye.js} +1 -1
  110. package/bin/{chunk-9zsv6d2f.js → chunk-vbe8wred.js} +1 -1
  111. package/bin/{chunk-hpbn0k9n.js → chunk-vf9s8b5t.js} +2 -2
  112. package/bin/{chunk-m9adtgzk.js → chunk-vk3eqr65.js} +1 -1
  113. package/bin/{chunk-hpwv4am3.js → chunk-vm9bbk97.js} +4 -4
  114. package/bin/{chunk-v05rrxp5.js → chunk-w4gqg27w.js} +2 -2
  115. package/bin/{chunk-x8mjh387.js → chunk-w6ym7tsd.js} +4 -4
  116. package/bin/{chunk-hzkjgcre.js → chunk-ways29d1.js} +1 -1
  117. package/bin/chunk-wesg7tg9.js +1 -0
  118. package/bin/chunk-wmrrapwv.js +2 -0
  119. package/bin/chunk-wnwsjgj8.js +2 -0
  120. package/bin/{chunk-hw6czrya.js → chunk-wrb4xq9v.js} +1 -1
  121. package/bin/{chunk-v5cn90cf.js → chunk-wzrzc07t.js} +2 -2
  122. package/bin/chunk-xd1axsdv.js +2 -0
  123. package/bin/{chunk-cwat1jwx.js → chunk-xk0jmx4s.js} +2 -2
  124. package/bin/{chunk-g6sdezec.js → chunk-y545vfn0.js} +1 -1
  125. package/bin/{chunk-fatmqnp1.js → chunk-y6h885fs.js} +1 -1
  126. package/bin/{chunk-cz13a82m.js → chunk-yncmfr39.js} +2 -2
  127. package/bin/{chunk-01052ssf.js → chunk-yxnz4ypt.js} +11 -11
  128. package/bin/chunk-zc1asygg.js +2 -0
  129. package/bin/{chunk-m82tkhaa.js → chunk-zc7wzcvh.js} +7 -7
  130. package/bin/chunk-zdvhh8mk.js +2 -0
  131. package/bin/{chunk-kvhf12b4.js → chunk-zg0b902x.js} +2 -2
  132. package/bin/{chunk-7v7mypc6.js → chunk-zhq7a7hs.js} +2 -2
  133. package/bin/{chunk-f25fe9th.js → chunk-zmnvskn7.js} +11 -11
  134. package/bin/shumai-app.html +1 -1
  135. package/bin/shumai-app.js +470 -389
  136. package/package.json +7 -7
  137. package/prisma/migrations/20261102032402_add_archive_storage/migration.sql +25 -0
  138. package/prisma/schema.prisma +12 -6
  139. package/bin/chunk-0bj887zm.js +0 -2
  140. package/bin/chunk-1ktk6764.js +0 -10
  141. package/bin/chunk-26qn7fek.js +0 -2
  142. package/bin/chunk-2ne2b54t.js +0 -2
  143. package/bin/chunk-2vbeqczj.js +0 -1
  144. package/bin/chunk-37p6bcx2.js +0 -1
  145. package/bin/chunk-3knfx6dm.js +0 -1
  146. package/bin/chunk-3z85zxkn.js +0 -1
  147. package/bin/chunk-54tbfvya.js +0 -2
  148. package/bin/chunk-56kh5fxc.js +0 -1
  149. package/bin/chunk-576nj64j.js +0 -2
  150. package/bin/chunk-6cnqjngz.js +0 -1
  151. package/bin/chunk-7g46e1wy.js +0 -3
  152. package/bin/chunk-84x8p7v5.js +0 -1
  153. package/bin/chunk-88jg9dq5.js +0 -2
  154. package/bin/chunk-8fyg9dy4.js +0 -2
  155. package/bin/chunk-8gtfgkrn.js +0 -2
  156. package/bin/chunk-8mqbztj8.js +0 -2
  157. package/bin/chunk-8qdtvfx3.css +0 -1
  158. package/bin/chunk-8xb6yz11.js +0 -2
  159. package/bin/chunk-8yjsmr7g.js +0 -2
  160. package/bin/chunk-91rb0jpb.js +0 -2
  161. package/bin/chunk-96qpjght.js +0 -2
  162. package/bin/chunk-9f1xk1nt.js +0 -1
  163. package/bin/chunk-9mk9cvbk.js +0 -1
  164. package/bin/chunk-9nw5w8vh.js +0 -1
  165. package/bin/chunk-ah8fjb6f.js +0 -2
  166. package/bin/chunk-cf5axr8c.js +0 -1
  167. package/bin/chunk-dk42gf7v.js +0 -2
  168. package/bin/chunk-e4f56spj.js +0 -4
  169. package/bin/chunk-eb7mzbfm.js +0 -1
  170. package/bin/chunk-er14d498.js +0 -3
  171. package/bin/chunk-f6avg5qe.js +0 -129
  172. package/bin/chunk-fvx9k1dc.js +0 -2
  173. package/bin/chunk-gtf19jc1.js +0 -2
  174. package/bin/chunk-h1n7jqnw.js +0 -1
  175. package/bin/chunk-hfm82066.js +0 -2
  176. package/bin/chunk-j2s311yc.js +0 -3
  177. package/bin/chunk-kj6h5j5a.js +0 -4
  178. package/bin/chunk-km4gn6b6.js +0 -1
  179. package/bin/chunk-ny1kbmxt.js +0 -2
  180. package/bin/chunk-p3j6ydk1.js +0 -1
  181. package/bin/chunk-pk406dgy.js +0 -2
  182. package/bin/chunk-s1e4qy3q.js +0 -14
  183. package/bin/chunk-swtwaaqe.js +0 -1
  184. package/bin/chunk-tagdrg7p.js +0 -1
  185. package/bin/chunk-twtxnzbv.js +0 -2
  186. package/bin/chunk-v5mcjwxy.js +0 -2
  187. package/bin/chunk-vkzasgxw.js +0 -2
  188. package/bin/chunk-x342vzdx.js +0 -2
  189. package/bin/chunk-xc54vhfz.js +0 -2
  190. package/bin/chunk-xvkwbczx.js +0 -3
  191. package/bin/chunk-z1p13dnc.js +0 -2
  192. package/bin/chunk-zarz3sqn.js +0 -211
@@ -1,129 +0,0 @@
1
- import{xi,Qa,Rt,ne,J,Tl,Q,Zt,S,Ff,bn,nt,G,M,w,Ci,Z,Y,a,g,ie,ee,Js,Oo,Va,Oc,Si,Pc,Dc,Nc,$f,Ii,Fc,Hf,en,R,z,K,$t,yo,qe,Be,Mn,jt,cr,Bt,ki,ps,Re,rr,Ge,B,F,$e,He,Qe,De,Ne,Fe,de,En,ur,ri,np,bA,ap,md,tw,rw,hd,nw,ow,sw,Gm,gd,iw,aw,Ke,bw,Qw,Km,Ww,Uc,up,Dr,JE,YE,sh,jc,ah,ch,uh,Ll,fh,bC,wC,Ap,wd,DS,Ah,gI,J_,Y_,QI,GI,Ep,JI,p0,Ph,Sp,Zl,XT,d1,Lh,F0,Vc,wo,Gk,Y0,rR,tg,rM,WM,UO,_g,yg,Se,Oy,xe,ke,Ce,Ot,re,Os,an,Yn,Eo,j,Dt,ze,ql,el,Hp,eu,Nr,Od,Pd,rn,Kr,Lo,Gl,pt,mt,ht,fe,Ve,Yp,ii,An,ar,hs}from"./chunk-zarz3sqn.js";import{_s}from"./chunk-ns33grgx.js";import{os,Lr}from"./chunk-q2bew2vc.js";import{ss,fi,ro,Ia,Vd,Kd,un}from"./chunk-55h9ze53.js";import{Uo}from"./chunk-atfz7g7e.js";import{_r}from"./chunk-ny1kbmxt.js";import{jn}from"./chunk-fvx9k1dc.js";import{qn}from"./chunk-qwpkcp8d.js";import{Zr}from"./chunk-v5cn90cf.js";import{se,L,Ye}from"./chunk-2jj4j8cn.js";var y8=L(function(wU,Wh){Z();Hf();Wh.exports=function(e){function t(f,u,y,x){return new Uk(f,u,y,x)}function n(){}function s(f){var u="https://react.dev/errors/"+f;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var y=2;y<arguments.length;y++)u+="&args[]="+encodeURIComponent(arguments[y])}return"Minified React error #"+f+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(f){var u=f,y=f;if(f.alternate)for(;u.return;)u=u.return;else{f=u;do u=f,(u.flags&4098)!==0&&(y=u.return),f=u.return;while(f)}return u.tag===3?y:null}function r(f){if(i(f)!==f)throw Error(s(188))}function o(f){var u=f.alternate;if(!u){if(u=i(f),u===null)throw Error(s(188));return u!==f?null:f}for(var y=f,x=u;;){var C=y.return;if(C===null)break;var D=C.alternate;if(D===null){if(x=C.return,x!==null){y=x;continue}break}if(C.child===D.child){for(D=C.child;D;){if(D===y)return r(C),f;if(D===x)return r(C),u;D=D.sibling}throw Error(s(188))}if(y.return!==x.return)y=C,x=D;else{for(var X=!1,pe=C.child;pe;){if(pe===y){X=!0,y=C,x=D;break}if(pe===x){X=!0,x=C,y=D;break}pe=pe.sibling}if(!X){for(pe=D.child;pe;){if(pe===y){X=!0,y=D,x=C;break}if(pe===x){X=!0,x=D,y=C;break}pe=pe.sibling}if(!X)throw Error(s(189))}}if(y.alternate!==x)throw Error(s(190))}if(y.tag!==3)throw Error(s(188));return y.stateNode.current===y?f:u}function l(f){var u=f.tag;if(u===5||u===26||u===27||u===6)return f;for(f=f.child;f!==null;){if(u=l(f),u!==null)return u;f=f.sibling}return null}function c(f){var u=f.tag;if(u===5||u===26||u===27||u===6)return f;for(f=f.child;f!==null;){if(f.tag!==4&&(u=c(f),u!==null))return u;f=f.sibling}return null}function h(f){if(f===null||typeof f!=="object")return null;return f=By&&f[By]||f["@@iterator"],typeof f==="function"?f:null}function d(f){if(f==null)return null;if(typeof f==="function")return f.$$typeof===Xk?null:f.displayName||f.name||null;if(typeof f==="string")return f;switch(f){case uc:return"Fragment";case qp:return"Profiler";case Py:return"StrictMode";case Fp:return"Suspense";case Lp:return"SuspenseList";case Pp:return"Activity"}if(typeof f==="object")switch(f.$$typeof){case hc:return"Portal";case Mo:return f.displayName||"Context";case Ny:return(f._context.displayName||"Context")+".Consumer";case Mp:var u=f.render;return f=f.displayName,f||(f=u.displayName||u.name||"",f=f!==""?"ForwardRef("+f+")":"ForwardRef"),f;case Op:return u=f.displayName||null,u!==null?u:d(f.type)||"Memo";case Fo:u=f._payload,f=f._init;try{return d(f(u))}catch(y){}}return null}function m(f){return{current:f}}function p(f){0>pc||(f.current=Vp[pc],Vp[pc]=null,pc--)}function b(f,u){pc++,Vp[pc]=f.current,f.current=u}function v(f){return f>>>=0,f===0?32:31-(kA(f)/xA|0)|0}function k(f){var u=f&42;if(u!==0)return u;switch(f&-f){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return f&261888;case 262144:case 524288:case 1048576:case 2097152:return f&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return f&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return f}}function A(f,u,y){var x=f.pendingLanes;if(x===0)return 0;var C=0,D=f.suspendedLanes,X=f.pingedLanes;f=f.warmLanes;var pe=x&134217727;return pe!==0?(x=pe&~D,x!==0?C=k(x):(X&=pe,X!==0?C=k(X):y||(y=pe&~f,y!==0&&(C=k(y))))):(pe=x&~D,pe!==0?C=k(pe):X!==0?C=k(X):y||(y=x&~f,y!==0&&(C=k(y)))),C===0?0:u!==0&&u!==C&&(u&D)===0&&(D=C&-C,y=u&-u,D>=y||D===32&&(y&4194048)!==0)?u:C}function T(f,u){return(f.pendingLanes&~(f.suspendedLanes&~f.pingedLanes)&u)===0}function E(f,u){switch(f){case 1:case 2:case 4:case 8:case 64:return u+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return u+5000;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function I(){var f=Gu;return Gu<<=1,(Gu&62914560)===0&&(Gu=4194304),f}function _(f){for(var u=[],y=0;31>y;y++)u.push(f);return u}function q(f,u){f.pendingLanes|=u,u!==268435456&&(f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0)}function P(f,u,y,x,C,D){var X=f.pendingLanes;f.pendingLanes=y,f.suspendedLanes=0,f.pingedLanes=0,f.warmLanes=0,f.expiredLanes&=y,f.entangledLanes&=y,f.errorRecoveryDisabledLanes&=y,f.shellSuspendCounter=0;var{entanglements:pe,expirationTimes:Ie,hiddenUpdates:et}=f;for(y=X&~y;0<y;){var gt=31-fr(y),rt=1<<gt;pe[gt]=0,Ie[gt]=-1;var Tt=et[gt];if(Tt!==null)for(et[gt]=null,gt=0;gt<Tt.length;gt++){var ln=Tt[gt];ln!==null&&(ln.lane&=-536870913)}y&=~rt}x!==0&&N(f,x,0),D!==0&&C===0&&f.tag!==0&&(f.suspendedLanes|=D&~(X&~u))}function N(f,u,y){f.pendingLanes|=u,f.suspendedLanes&=~u;var x=31-fr(u);f.entangledLanes|=u,f.entanglements[x]=f.entanglements[x]|1073741824|y&261930}function H(f,u){var y=f.entangledLanes|=u;for(f=f.entanglements;y;){var x=31-fr(y),C=1<<x;C&u|f[x]&u&&(f[x]|=u),y&=~C}}function V(f,u){var y=u&-u;return y=(y&42)!==0?1:U(y),(y&(f.suspendedLanes|u))!==0?0:y}function U(f){switch(f){case 2:f=1;break;case 8:f=4;break;case 32:f=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:f=128;break;case 268435456:f=134217728;break;default:f=0}return f}function W(f){return f&=-f,2<f?8<f?(f&134217727)!==0?32:268435456:8:2}function ce(f){if(typeof jA==="function"&&_A(f),hr&&typeof hr.setStrictMode==="function")try{hr.setStrictMode(Pf,f)}catch(u){}}function ue(f,u){return f===u&&(f!==0||1/f===1/u)||f!==f&&u!==u}function oe(f){if(Wp===void 0)try{throw Error()}catch(y){var u=y.stack.trim().match(/\n( *(at )?)/);Wp=u&&u[1]||"",u5=-1<y.stack.indexOf(`
2
- at`)?" (<anonymous>)":-1<y.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+Wp+f+u5}function ae(f,u){if(!f||Kp)return"";Kp=!0;var y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var x={DetermineComponentFrameRoot:function(){try{if(u){var rt=function(){throw Error()};if(Object.defineProperty(rt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==="object"&&Reflect.construct){try{Reflect.construct(rt,[])}catch(ln){var Tt=ln}Reflect.construct(f,[],rt)}else{try{rt.call()}catch(ln){Tt=ln}f.call(rt.prototype)}}else{try{throw Error()}catch(ln){Tt=ln}(rt=f())&&typeof rt.catch==="function"&&rt.catch(function(){})}}catch(ln){if(ln&&Tt&&typeof ln.stack==="string")return[ln.stack,Tt.stack]}return[null,null]}};x.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var C=Object.getOwnPropertyDescriptor(x.DetermineComponentFrameRoot,"name");C&&C.configurable&&Object.defineProperty(x.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=x.DetermineComponentFrameRoot(),X=D[0],pe=D[1];if(X&&pe){var Ie=X.split(`
4
- `),et=pe.split(`
5
- `);for(C=x=0;x<Ie.length&&!Ie[x].includes("DetermineComponentFrameRoot");)x++;for(;C<et.length&&!et[C].includes("DetermineComponentFrameRoot");)C++;if(x===Ie.length||C===et.length)for(x=Ie.length-1,C=et.length-1;1<=x&&0<=C&&Ie[x]!==et[C];)C--;for(;1<=x&&0<=C;x--,C--)if(Ie[x]!==et[C]){if(x!==1||C!==1)do if(x--,C--,0>C||Ie[x]!==et[C]){var gt=`
6
- `+Ie[x].replace(" at new "," at ");return f.displayName&&gt.includes("<anonymous>")&&(gt=gt.replace("<anonymous>",f.displayName)),gt}while(1<=x&&0<=C);break}}}finally{Kp=!1,Error.prepareStackTrace=y}return(y=f?f.displayName||f.name:"")?oe(y):""}function te(f,u){switch(f.tag){case 26:case 27:case 5:return oe(f.type);case 16:return oe("Lazy");case 13:return f.child!==u&&u!==null?oe("Suspense Fallback"):oe("Suspense");case 19:return oe("SuspenseList");case 0:case 15:return ae(f.type,!1);case 11:return ae(f.type.render,!1);case 1:return ae(f.type,!0);case 31:return oe("Activity");default:return""}}function me(f){try{var u="",y=null;do u+=te(f,y),y=f,f=f.return;while(f);return u}catch(x){return`
7
- Error generating stack: `+x.message+`
8
- `+x.stack}}function he(f,u){if(typeof f==="object"&&f!==null){var y=d5.get(f);if(y!==void 0)return y;return u={value:f,source:u,stack:me(u)},d5.set(f,u),u}return{value:f,source:u,stack:me(u)}}function we(f,u){bc[wc++]=Nf,bc[wc++]=$u,$u=f,Nf=u}function be(f,u,y){Ar[Tr++]=ba,Ar[Tr++]=wa,Ar[Tr++]=Po,Po=f;var x=ba;f=wa;var C=32-fr(x)-1;x&=~(1<<C),y+=1;var D=32-fr(u)+C;if(30<D){var X=C-C%5;D=(x&(1<<X)-1).toString(32),x>>=X,C-=X,ba=1<<32-fr(u)+C|y<<C|x,wa=D+f}else ba=1<<D|y<<C|x,wa=f}function ye(f){f.return!==null&&(we(f,1),be(f,1,0))}function Te(f){for(;f===$u;)$u=bc[--wc],bc[wc]=null,Nf=bc[--wc],bc[wc]=null;for(;f===Po;)Po=Ar[--Tr],Ar[Tr]=null,wa=Ar[--Tr],Ar[Tr]=null,ba=Ar[--Tr],Ar[Tr]=null}function Oe(f,u){Ar[Tr++]=ba,Ar[Tr++]=wa,Ar[Tr++]=Po,ba=u.id,wa=u.overflow,Po=f}function st(f,u){b(No,u),b(Bf,f),b(vi,null),f=Yk(u),p(vi),b(vi,f)}function We(){p(vi),p(Bf),p(No)}function wt(f){f.memoizedState!==null&&b(Xu,f);var u=vi.current,y=Qk(u,f.type);u!==y&&(b(Bf,f),b(vi,y))}function xt(f){Bf.current===f&&(p(vi),p(Bf)),Xu.current===f&&(p(Xu),eo?Sl._currentValue=dc:Sl._currentValue2=dc)}function ft(f){var u=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Kn(he(u,f)),Qp}function It(f,u){if(!Li)throw Error(s(175));Qx(f.stateNode,f.type,f.memoizedProps,u,f)||ft(f,!0)}function Wt(f){for(Ai=f.return;Ai;)switch(Ai.tag){case 5:case 31:case 13:Er=!1;return;case 27:case 3:Er=!0;return;default:Ai=Ai.return}}function hn(f){if(!Li||f!==Ai)return!1;if(!Cn)return Wt(f),Cn=!0,!1;var u=f.tag;if(ei?u!==3&&u!==27&&(u!==5||Zy(f.type)&&!Hu(f.type,f.memoizedProps))&&Ts&&ft(f):u!==3&&(u!==5||Zy(f.type)&&!Hu(f.type,f.memoizedProps))&&Ts&&ft(f),Wt(f),u===13){if(!Li)throw Error(s(316));if(f=f.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(s(317));Ts=nA(f)}else if(u===31){if(f=f.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(s(317));Ts=tA(f)}else Ts=ei&&u===27?Hx(f.type,Ts):Ai?Jy(f.stateNode):null;return!0}function zt(){Li&&(Ts=Ai=null,Cn=!1)}function tn(){var f=Bo;return f!==null&&(Ki===null?Ki=f:Ki.push.apply(Ki,f),Bo=null),f}function Kn(f){Bo===null?Bo=[f]:Bo.push(f)}function Le(f,u,y){eo?(b(Wu,u._currentValue),u._currentValue=y):(b(Wu,u._currentValue2),u._currentValue2=y)}function Je(f){var u=Wu.current;eo?f._currentValue=u:f._currentValue2=u,p(Wu)}function bt(f,u,y){for(;f!==null;){var x=f.alternate;if((f.childLanes&u)!==u?(f.childLanes|=u,x!==null&&(x.childLanes|=u)):x!==null&&(x.childLanes&u)!==u&&(x.childLanes|=u),f===y)break;f=f.return}}function ut(f,u,y,x){var C=f.child;C!==null&&(C.return=f);for(;C!==null;){var D=C.dependencies;if(D!==null){var X=C.child;D=D.firstContext;e:for(;D!==null;){var pe=D;D=C;for(var Ie=0;Ie<u.length;Ie++)if(pe.context===u[Ie]){D.lanes|=y,pe=D.alternate,pe!==null&&(pe.lanes|=y),bt(D.return,y,f),x||(X=null);break e}D=pe.next}}else if(C.tag===18){if(X=C.return,X===null)throw Error(s(341));X.lanes|=y,D=X.alternate,D!==null&&(D.lanes|=y),bt(X,y,f),X=null}else X=C.child;if(X!==null)X.return=C;else for(X=C;X!==null;){if(X===f){X=null;break}if(C=X.sibling,C!==null){C.return=X.return,X=C;break}X=X.return}C=X}}function Ft(f,u,y,x){f=null;for(var C=u,D=!1;C!==null;){if(!D){if((C.flags&524288)!==0)D=!0;else if((C.flags&262144)!==0)break}if(C.tag===10){var X=C.alternate;if(X===null)throw Error(s(387));if(X=X.memoizedProps,X!==null){var pe=C.type;dr(C.pendingProps.value,X.value)||(f!==null?f.push(pe):f=[pe])}}else if(C===Xu.current){if(X=C.alternate,X===null)throw Error(s(387));X.memoizedState.memoizedState!==C.memoizedState.memoizedState&&(f!==null?f.push(Sl):f=[Sl])}C=C.return}f!==null&&ut(u,f,y,x),u.flags|=262144}function nn(f){for(f=f.firstContext;f!==null;){var u=f.context;if(!dr(eo?u._currentValue:u._currentValue2,f.memoizedValue))return!0;f=f.next}return!1}function mn(f){kl=f,no=null,f=f.dependencies,f!==null&&(f.firstContext=null)}function Vt(f){return ns(kl,f)}function Fn(f,u){return kl===null&&mn(f),ns(f,u)}function ns(f,u){var y=eo?u._currentValue:u._currentValue2;if(u={context:u,memoizedValue:y,next:null},no===null){if(f===null)throw Error(s(308));no=u,f.dependencies={lanes:0,firstContext:u},f.flags|=524288}else no=no.next=u;return y}function St(){return{controller:new RA,data:new Map,refCount:0}}function it(f){f.refCount--,f.refCount===0&&DA(qA,function(){f.controller.abort()})}function sn(){}function Lt(f){f!==yc&&f.next===null&&(yc===null?Ku=yc=f:yc=yc.next=f),Yu=!0,Jp||(Jp=!0,nr())}function Ln(f,u){if(!Zp&&Yu){Zp=!0;do{var y=!1;for(var x=Ku;x!==null;){if(!u)if(f!==0){var C=x.pendingLanes;if(C===0)var D=0;else{var X=x.suspendedLanes,pe=x.pingedLanes;D=(1<<31-fr(42|f)+1)-1,D&=C&~(X&~pe),D=D&201326741?D&201326741|1:D?D|2:0}D!==0&&(y=!0,Pi(x,D))}else D=xn,D=A(x,x===as?D:0,x.cancelPendingCommit!==null||x.timeoutHandle!==vl),(D&3)===0||T(x,D)||(y=!0,Pi(x,D));x=x.next}}while(y);Zp=!1}}function is(){xs()}function xs(){Yu=Jp=!1;var f=0;xl!==0&&ax()&&(f=xl);for(var u=Xi(),y=null,x=Ku;x!==null;){var C=x.next,D=Ls(x,u);if(D===0)x.next=null,y===null?Ku=C:y.next=C,C===null&&(yc=y);else if(y=x,f!==0||(D&3)!==0)Yu=!0;x=C}ti!==0&&ti!==5||Ln(f,!1),xl!==0&&(xl=0)}function Ls(f,u){for(var{suspendedLanes:y,pingedLanes:x,expirationTimes:C}=f,D=f.pendingLanes&-62914561;0<D;){var X=31-fr(D),pe=1<<X,Ie=C[X];if(Ie===-1){if((pe&y)===0||(pe&x)!==0)C[X]=E(pe,u)}else Ie<=u&&(f.expiredLanes|=pe);D&=~pe}if(u=as,y=xn,y=A(f,f===u?y:0,f.cancelPendingCommit!==null||f.timeoutHandle!==vl),x=f.callbackNode,y===0||f===u&&($n===2||$n===9)||f.cancelPendingCommit!==null)return x!==null&&x!==null&&$p(x),f.callbackNode=null,f.callbackPriority=0;if((y&3)===0||T(f,y)){if(u=y&-y,u===f.callbackPriority)return u;switch(x!==null&&$p(x),W(y)){case 2:case 8:y=EA;break;case 32:y=Xp;break;case 268435456:y=CA;break;default:y=Xp}return x=ha.bind(null,f),y=Vu(y,x),f.callbackPriority=u,f.callbackNode=y,u}return x!==null&&x!==null&&$p(x),f.callbackPriority=2,f.callbackNode=null,2}function ha(f,u){if(ti!==0&&ti!==5)return f.callbackNode=null,f.callbackPriority=0,null;var y=f.callbackNode;if(qf()&&f.callbackNode!==y)return null;var x=xn;if(x=A(f,f===as?x:0,f.cancelPendingCommit!==null||f.timeoutHandle!==vl),x===0)return null;return uy(f,x,u),Ls(f,Xi()),f.callbackNode!=null&&f.callbackNode===y?ha.bind(null,f):null}function Pi(f,u){if(qf())return null;uy(f,u,!0)}function nr(){dx?mx(function(){(vn&6)!==0?Vu(f5,is):xs()}):Vu(f5,is)}function To(){if(xl===0){var f=vc;f===0&&(f=Uu,Uu<<=1,(Uu&261888)===0&&(Uu=256)),xl=f}return xl}function pl(f,u){if(Uf===null){var y=Uf=[];eg=0,vc=To(),Sc={status:"pending",value:void 0,then:function(x){y.push(x)}}}return eg++,u.then(sr,sr),u}function sr(){if(--eg===0&&Uf!==null){Sc!==null&&(Sc.status="fulfilled");var f=Uf;Uf=null,vc=0,Sc=null;for(var u=0;u<f.length;u++)(0,f[u])()}}function $a(f,u){var y=[],x={status:"pending",value:null,reason:null,then:function(C){y.push(C)}};return f.then(function(){x.status="fulfilled",x.value=u;for(var C=0;C<y.length;C++)(0,y[C])(u)},function(C){x.status="rejected",x.reason=C;for(C=0;C<y.length;C++)(0,y[C])(void 0)}),x}function ua(){var f=Al.current;return f!==null?f:as.pooledCache}function Xa(f,u){u===null?b(Al,Al.current):b(Al,u.pool)}function da(){var f=ua();return f===null?null:{parent:eo?Es._currentValue:Es._currentValue2,pool:f}}function Co(f,u){if(dr(f,u))return!0;if(typeof f!=="object"||f===null||typeof u!=="object"||u===null)return!1;var y=Object.keys(f),x=Object.keys(u);if(y.length!==x.length)return!1;for(x=0;x<y.length;x++){var C=y[x];if(!IA.call(u,C)||!dr(f[C],u[C]))return!1}return!0}function ma(f){return f=f.status,f==="fulfilled"||f==="rejected"}function jo(f,u,y){switch(y=f[y],y===void 0?f.push(u):y!==u&&(u.then(sn,sn),u=y),u.status){case"fulfilled":return u.value;case"rejected":throw f=u.reason,Ze(f),f;default:if(typeof u.status==="string")u.then(sn,sn);else{if(f=as,f!==null&&100<f.shellSuspendCounter)throw Error(s(482));f=u,f.status="pending",f.then(function(x){if(u.status==="pending"){var C=u;C.status="fulfilled",C.value=x}},function(x){if(u.status==="pending"){var C=u;C.status="rejected",C.reason=x}})}switch(u.status){case"fulfilled":return u.value;case"rejected":throw f=u.reason,Ze(f),f}throw El=u,kc}}function ir(f){try{var u=f._init;return u(f._payload)}catch(y){if(y!==null&&typeof y==="object"&&typeof y.then==="function")throw El=y,kc;throw y}}function _o(){if(El===null)throw Error(s(459));var f=El;return El=null,f}function Ze(f){if(f===kc||f===Qu)throw Error(s(483))}function pn(f){var u=zf;return zf+=1,xc===null&&(xc=[]),jo(xc,f,u)}function Xt(f,u){u=u.props.ref,f.ref=u!==void 0?u:null}function us(f,u){if(u.$$typeof===Vk)throw Error(s(525));throw f=Object.prototype.toString.call(u),Error(s(31,f==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":f))}function Zs(f){function u(Ee,Ae){if(f){var _e=Ee.deletions;_e===null?(Ee.deletions=[Ae],Ee.flags|=16):_e.push(Ae)}}function y(Ee,Ae){if(!f)return null;for(;Ae!==null;)u(Ee,Ae),Ae=Ae.sibling;return null}function x(Ee){for(var Ae=new Map;Ee!==null;)Ee.key!==null?Ae.set(Ee.key,Ee):Ae.set(Ee.index,Ee),Ee=Ee.sibling;return Ae}function C(Ee,Ae){return Ee=Za(Ee,Ae),Ee.index=0,Ee.sibling=null,Ee}function D(Ee,Ae,_e){if(Ee.index=_e,!f)return Ee.flags|=1048576,Ae;if(_e=Ee.alternate,_e!==null)return _e=_e.index,_e<Ae?(Ee.flags|=67108866,Ae):_e;return Ee.flags|=67108866,Ae}function X(Ee){return f&&Ee.alternate===null&&(Ee.flags|=67108866),Ee}function pe(Ee,Ae,_e,at){if(Ae===null||Ae.tag!==6)return Ae=_p(_e,Ee.mode,at),Ae.return=Ee,Ae;return Ae=C(Ae,_e),Ae.return=Ee,Ae}function Ie(Ee,Ae,_e,at){var Ht=_e.type;if(Ht===uc)return gt(Ee,Ae,_e.props.children,at,_e.key);if(Ae!==null&&(Ae.elementType===Ht||typeof Ht==="object"&&Ht!==null&&Ht.$$typeof===Fo&&ir(Ht)===Ae.type))return Ae=C(Ae,_e.props),Xt(Ae,_e),Ae.return=Ee,Ae;return Ae=Pu(_e.type,_e.key,_e.props,null,Ee.mode,at),Xt(Ae,_e),Ae.return=Ee,Ae}function et(Ee,Ae,_e,at){if(Ae===null||Ae.tag!==4||Ae.stateNode.containerInfo!==_e.containerInfo||Ae.stateNode.implementation!==_e.implementation)return Ae=Ip(_e,Ee.mode,at),Ae.return=Ee,Ae;return Ae=C(Ae,_e.children||[]),Ae.return=Ee,Ae}function gt(Ee,Ae,_e,at,Ht){if(Ae===null||Ae.tag!==7)return Ae=yl(_e,Ee.mode,at,Ht),Ae.return=Ee,Ae;return Ae=C(Ae,_e),Ae.return=Ee,Ae}function rt(Ee,Ae,_e){if(typeof Ae==="string"&&Ae!==""||typeof Ae==="number"||typeof Ae==="bigint")return Ae=_p(""+Ae,Ee.mode,_e),Ae.return=Ee,Ae;if(typeof Ae==="object"&&Ae!==null){switch(Ae.$$typeof){case Nu:return _e=Pu(Ae.type,Ae.key,Ae.props,null,Ee.mode,_e),Xt(_e,Ae),_e.return=Ee,_e;case hc:return Ae=Ip(Ae,Ee.mode,_e),Ae.return=Ee,Ae;case Fo:return Ae=ir(Ae),rt(Ee,Ae,_e)}if(Bu(Ae)||h(Ae))return Ae=yl(Ae,Ee.mode,_e,null),Ae.return=Ee,Ae;if(typeof Ae.then==="function")return rt(Ee,pn(Ae),_e);if(Ae.$$typeof===Mo)return rt(Ee,Fn(Ee,Ae),_e);us(Ee,Ae)}return null}function Tt(Ee,Ae,_e,at){var Ht=Ae!==null?Ae.key:null;if(typeof _e==="string"&&_e!==""||typeof _e==="number"||typeof _e==="bigint")return Ht!==null?null:pe(Ee,Ae,""+_e,at);if(typeof _e==="object"&&_e!==null){switch(_e.$$typeof){case Nu:return _e.key===Ht?Ie(Ee,Ae,_e,at):null;case hc:return _e.key===Ht?et(Ee,Ae,_e,at):null;case Fo:return _e=ir(_e),Tt(Ee,Ae,_e,at)}if(Bu(_e)||h(_e))return Ht!==null?null:gt(Ee,Ae,_e,at,null);if(typeof _e.then==="function")return Tt(Ee,Ae,pn(_e),at);if(_e.$$typeof===Mo)return Tt(Ee,Ae,Fn(Ee,_e),at);us(Ee,_e)}return null}function ln(Ee,Ae,_e,at,Ht){if(typeof at==="string"&&at!==""||typeof at==="number"||typeof at==="bigint")return Ee=Ee.get(_e)||null,pe(Ae,Ee,""+at,Ht);if(typeof at==="object"&&at!==null){switch(at.$$typeof){case Nu:return Ee=Ee.get(at.key===null?_e:at.key)||null,Ie(Ae,Ee,at,Ht);case hc:return Ee=Ee.get(at.key===null?_e:at.key)||null,et(Ae,Ee,at,Ht);case Fo:return at=ir(at),ln(Ee,Ae,_e,at,Ht)}if(Bu(at)||h(at))return Ee=Ee.get(_e)||null,gt(Ae,Ee,at,Ht,null);if(typeof at.then==="function")return ln(Ee,Ae,_e,pn(at),Ht);if(at.$$typeof===Mo)return ln(Ee,Ae,_e,Fn(Ae,at),Ht);us(Ae,at)}return null}function Ti(Ee,Ae,_e,at){for(var Ht=null,Cs=null,Gt=Ae,Pn=Ae=0,mi=null;Gt!==null&&Pn<_e.length;Pn++){Gt.index>Pn?(mi=Gt,Gt=null):mi=Gt.sibling;var Nn=Tt(Ee,Gt,_e[Pn],at);if(Nn===null){Gt===null&&(Gt=mi);break}f&&Gt&&Nn.alternate===null&&u(Ee,Gt),Ae=D(Nn,Ae,Pn),Cs===null?Ht=Nn:Cs.sibling=Nn,Cs=Nn,Gt=mi}if(Pn===_e.length)return y(Ee,Gt),Cn&&we(Ee,Pn),Ht;if(Gt===null){for(;Pn<_e.length;Pn++)Gt=rt(Ee,_e[Pn],at),Gt!==null&&(Ae=D(Gt,Ae,Pn),Cs===null?Ht=Gt:Cs.sibling=Gt,Cs=Gt);return Cn&&we(Ee,Pn),Ht}for(Gt=x(Gt);Pn<_e.length;Pn++)mi=ln(Gt,Ee,Pn,_e[Pn],at),mi!==null&&(f&&mi.alternate!==null&&Gt.delete(mi.key===null?Pn:mi.key),Ae=D(mi,Ae,Pn),Cs===null?Ht=mi:Cs.sibling=mi,Cs=mi);return f&&Gt.forEach(function(Xo){return u(Ee,Xo)}),Cn&&we(Ee,Pn),Ht}function Qf(Ee,Ae,_e,at){if(_e==null)throw Error(s(151));for(var Ht=null,Cs=null,Gt=Ae,Pn=Ae=0,mi=null,Nn=_e.next();Gt!==null&&!Nn.done;Pn++,Nn=_e.next()){Gt.index>Pn?(mi=Gt,Gt=null):mi=Gt.sibling;var Xo=Tt(Ee,Gt,Nn.value,at);if(Xo===null){Gt===null&&(Gt=mi);break}f&&Gt&&Xo.alternate===null&&u(Ee,Gt),Ae=D(Xo,Ae,Pn),Cs===null?Ht=Xo:Cs.sibling=Xo,Cs=Xo,Gt=mi}if(Nn.done)return y(Ee,Gt),Cn&&we(Ee,Pn),Ht;if(Gt===null){for(;!Nn.done;Pn++,Nn=_e.next())Nn=rt(Ee,Nn.value,at),Nn!==null&&(Ae=D(Nn,Ae,Pn),Cs===null?Ht=Nn:Cs.sibling=Nn,Cs=Nn);return Cn&&we(Ee,Pn),Ht}for(Gt=x(Gt);!Nn.done;Pn++,Nn=_e.next())Nn=ln(Gt,Ee,Pn,Nn.value,at),Nn!==null&&(f&&Nn.alternate!==null&&Gt.delete(Nn.key===null?Pn:Nn.key),Ae=D(Nn,Ae,Pn),Cs===null?Ht=Nn:Cs.sibling=Nn,Cs=Nn);return f&&Gt.forEach(function(OA){return u(Ee,OA)}),Cn&&we(Ee,Pn),Ht}function Il(Ee,Ae,_e,at){if(typeof _e==="object"&&_e!==null&&_e.type===uc&&_e.key===null&&(_e=_e.props.children),typeof _e==="object"&&_e!==null){switch(_e.$$typeof){case Nu:e:{for(var Ht=_e.key;Ae!==null;){if(Ae.key===Ht){if(Ht=_e.type,Ht===uc){if(Ae.tag===7){y(Ee,Ae.sibling),at=C(Ae,_e.props.children),at.return=Ee,Ee=at;break e}}else if(Ae.elementType===Ht||typeof Ht==="object"&&Ht!==null&&Ht.$$typeof===Fo&&ir(Ht)===Ae.type){y(Ee,Ae.sibling),at=C(Ae,_e.props),Xt(at,_e),at.return=Ee,Ee=at;break e}y(Ee,Ae);break}else u(Ee,Ae);Ae=Ae.sibling}_e.type===uc?(at=yl(_e.props.children,Ee.mode,at,_e.key),at.return=Ee,Ee=at):(at=Pu(_e.type,_e.key,_e.props,null,Ee.mode,at),Xt(at,_e),at.return=Ee,Ee=at)}return X(Ee);case hc:e:{for(Ht=_e.key;Ae!==null;){if(Ae.key===Ht)if(Ae.tag===4&&Ae.stateNode.containerInfo===_e.containerInfo&&Ae.stateNode.implementation===_e.implementation){y(Ee,Ae.sibling),at=C(Ae,_e.children||[]),at.return=Ee,Ee=at;break e}else{y(Ee,Ae);break}else u(Ee,Ae);Ae=Ae.sibling}at=Ip(_e,Ee.mode,at),at.return=Ee,Ee=at}return X(Ee);case Fo:return _e=ir(_e),Il(Ee,Ae,_e,at)}if(Bu(_e))return Ti(Ee,Ae,_e,at);if(h(_e)){if(Ht=h(_e),typeof Ht!=="function")throw Error(s(150));return _e=Ht.call(_e),Qf(Ee,Ae,_e,at)}if(typeof _e.then==="function")return Il(Ee,Ae,pn(_e),at);if(_e.$$typeof===Mo)return Il(Ee,Ae,Fn(Ee,_e),at);us(Ee,_e)}return typeof _e==="string"&&_e!==""||typeof _e==="number"||typeof _e==="bigint"?(_e=""+_e,Ae!==null&&Ae.tag===6?(y(Ee,Ae.sibling),at=C(Ae,_e),at.return=Ee,Ee=at):(y(Ee,Ae),at=_p(_e,Ee.mode,at),at.return=Ee,Ee=at),X(Ee)):y(Ee,Ae)}return function(Ee,Ae,_e,at){try{zf=0;var Ht=Il(Ee,Ae,_e,at);return xc=null,Ht}catch(Gt){if(Gt===kc||Gt===Qu)throw Gt;var Cs=t(29,Gt,null,Ee.mode);return Cs.lanes=at,Cs.return=Ee,Cs}finally{}}}function Gr(){for(var f=Ac,u=sg=Ac=0;u<f;){var y=Cr[u];Cr[u++]=null;var x=Cr[u];Cr[u++]=null;var C=Cr[u];Cr[u++]=null;var D=Cr[u];if(Cr[u++]=null,x!==null&&C!==null){var X=x.pending;X===null?C.next=C:(C.next=X.next,X.next=C),x.pending=C}D!==0&&Yt(y,C,D)}}function je(f,u,y,x){Cr[Ac++]=f,Cr[Ac++]=u,Cr[Ac++]=y,Cr[Ac++]=x,sg|=x,f.lanes|=x,f=f.alternate,f!==null&&(f.lanes|=x)}function ot(f,u,y,x){return je(f,u,y,x),_n(f)}function At(f,u){return je(f,null,null,u),_n(f)}function Yt(f,u,y){f.lanes|=y;var x=f.alternate;x!==null&&(x.lanes|=y);for(var C=!1,D=f.return;D!==null;)D.childLanes|=y,x=D.alternate,x!==null&&(x.childLanes|=y),D.tag===22&&(f=D.stateNode,f===null||f._visibility&1||(C=!0)),f=D,D=D.return;return f.tag===3?(D=f.stateNode,C&&u!==null&&(C=31-fr(y),f=D.hiddenUpdates,x=f[C],x===null?f[C]=[u]:x.push(u),u.lane=y|536870912),D):null}function _n(f){if(50<Yf)throw Yf=0,pg=null,Error(s(185));for(var u=f.return;u!==null;)f=u,u=f.return;return f.tag===3?f.stateNode:null}function gn(f){f.updateQueue={baseState:f.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ws(f,u){f=f.updateQueue,u.updateQueue===f&&(u.updateQueue={baseState:f.baseState,firstBaseUpdate:f.firstBaseUpdate,lastBaseUpdate:f.lastBaseUpdate,shared:f.shared,callbacks:null})}function Hn(f){return{lane:f,tag:0,payload:null,callback:null,next:null}}function Vn(f,u,y){var x=f.updateQueue;if(x===null)return null;if(x=x.shared,(vn&2)!==0){var C=x.pending;return C===null?u.next=u:(u.next=C.next,C.next=u),x.pending=u,u=_n(f),Yt(f,null,y),u}return je(f,x,u,y),_n(f)}function Qn(f,u,y){if(u=u.updateQueue,u!==null&&(u=u.shared,(y&4194048)!==0)){var x=u.lanes;x&=f.pendingLanes,y|=x,u.lanes=y,H(f,y)}}function Bs(f,u){var y=f.updateQueue,x=f.alternate;if(x!==null&&(x=x.updateQueue,y===x)){var C=null,D=null;if(y=y.firstBaseUpdate,y!==null){do{var X={lane:y.lane,tag:y.tag,payload:y.payload,callback:null,next:null};D===null?C=D=X:D=D.next=X,y=y.next}while(y!==null);D===null?C=D=u:D=D.next=u}else C=D=u;y={baseState:x.baseState,firstBaseUpdate:C,lastBaseUpdate:D,shared:x.shared,callbacks:x.callbacks},f.updateQueue=y;return}f=y.lastBaseUpdate,f===null?y.firstBaseUpdate=u:f.next=u,y.lastBaseUpdate=u}function rs(){if(ig){var f=Sc;if(f!==null)throw f}}function Ni(f,u,y,x){ig=!1;var C=f.updateQueue;Ho=!1;var{firstBaseUpdate:D,lastBaseUpdate:X}=C,pe=C.shared.pending;if(pe!==null){C.shared.pending=null;var Ie=pe,et=Ie.next;Ie.next=null,X===null?D=et:X.next=et,X=Ie;var gt=f.alternate;gt!==null&&(gt=gt.updateQueue,pe=gt.lastBaseUpdate,pe!==X&&(pe===null?gt.firstBaseUpdate=et:pe.next=et,gt.lastBaseUpdate=Ie))}if(D!==null){var rt=C.baseState;X=0,gt=et=Ie=null,pe=D;do{var Tt=pe.lane&-536870913,ln=Tt!==pe.lane;if(ln?(xn&Tt)===Tt:(x&Tt)===Tt){Tt!==0&&Tt===vc&&(ig=!0),gt!==null&&(gt=gt.next={lane:0,tag:pe.tag,payload:pe.payload,callback:null,next:null});e:{var Ti=f,Qf=pe;Tt=u;var Il=y;switch(Qf.tag){case 1:if(Ti=Qf.payload,typeof Ti==="function"){rt=Ti.call(Il,rt,Tt);break e}rt=Ti;break e;case 3:Ti.flags=Ti.flags&-65537|128;case 0:if(Ti=Qf.payload,Tt=typeof Ti==="function"?Ti.call(Il,rt,Tt):Ti,Tt===null||Tt===void 0)break e;rt=Dp({},rt,Tt);break e;case 2:Ho=!0}}Tt=pe.callback,Tt!==null&&(f.flags|=64,ln&&(f.flags|=8192),ln=C.callbacks,ln===null?C.callbacks=[Tt]:ln.push(Tt))}else ln={lane:Tt,tag:pe.tag,payload:pe.payload,callback:pe.callback,next:null},gt===null?(et=gt=ln,Ie=rt):gt=gt.next=ln,X|=Tt;if(pe=pe.next,pe===null)if(pe=C.shared.pending,pe===null)break;else ln=pe,pe=ln.next,ln.next=null,C.lastBaseUpdate=ln,C.shared.pending=null}while(1);gt===null&&(Ie=rt),C.baseState=Ie,C.firstBaseUpdate=et,C.lastBaseUpdate=gt,D===null&&(C.shared.lanes=0),Go|=X,f.lanes=X,f.memoizedState=rt}}function Vr(f,u){if(typeof f!=="function")throw Error(s(191,f));f.call(u)}function xf(f,u){var y=f.callbacks;if(y!==null)for(f.callbacks=null,f=0;f<y.length;f++)Vr(y[f],u)}function Af(f,u){f=ao,b(Zu,f),b(Tc,u),ao=f|u.baseLanes}function Hs(){b(Zu,ao),b(Tc,Tc.current)}function Bi(){ao=Zu.current,p(Tc),p(Zu)}function ys(f){var u=f.alternate;b(zs,zs.current&1),b(mr,f),jr===null&&(u===null||Tc.current!==null?jr=f:u.memoizedState!==null&&(jr=f))}function ac(f){b(zs,zs.current),b(mr,f),jr===null&&(jr=f)}function Io(f){f.tag===22?(b(zs,zs.current),b(mr,f),jr===null&&(jr=f)):Ro(f)}function Ro(){b(zs,zs.current),b(mr,mr.current)}function or(f){p(mr),jr===f&&(jr=null),p(zs)}function yu(f){for(var u=f;u!==null;){if(u.tag===13){var y=u.memoizedState;if(y!==null&&(y=y.dehydrated,y===null||Up(y)||zp(y)))return u}else if(u.tag===19&&(u.memoizedProps.revealOrder==="forwards"||u.memoizedProps.revealOrder==="backwards"||u.memoizedProps.revealOrder==="unstable_legacy-backwards"||u.memoizedProps.revealOrder==="together")){if((u.flags&128)!==0)return u}else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===f)break;for(;u.sibling===null;){if(u.return===null||u.return===f)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}function qs(){throw Error(s(321))}function Mm(f,u){if(u===null)return!1;for(var y=0;y<u.length&&y<f.length;y++)if(!dr(f[y],u[y]))return!1;return!0}function Fm(f,u,y,x,C,D){return so=D,dn=u,u.memoizedState=null,u.updateQueue=null,u.lanes=0,Nt.H=f===null||f.memoizedState===null?g5:rg,jl=!1,D=y(x,C),jl=!1,Ec&&(D=M2(u,y,x,C)),q2(f),D}function q2(f){Nt.H=Vf;var u=Jn!==null&&Jn.next!==null;if(so=0,Vs=Jn=dn=null,ed=!1,Gf=0,Cc=null,u)throw Error(s(300));f===null||$s||(f=f.dependencies,f!==null&&nn(f)&&($s=!0))}function M2(f,u,y,x){dn=f;var C=0;do{if(Ec&&(Cc=null),Gf=0,Ec=!1,25<=C)throw Error(s(301));if(C+=1,Vs=Jn=null,f.updateQueue!=null){var D=f.updateQueue;D.lastEffect=null,D.events=null,D.stores=null,D.memoCache!=null&&(D.memoCache.index=0)}Nt.H=b5,D=u(y,x)}while(Ec);return D}function Sk(){var f=Nt.H,u=f.useState()[0];return u=typeof u.then==="function"?Tf(u):u,f=f.useState()[0],(Jn!==null?Jn.memoizedState:null)!==f&&(dn.flags|=1024),u}function Lm(){var f=td!==0;return td=0,f}function Om(f,u,y){u.updateQueue=f.updateQueue,u.flags&=-2053,f.lanes&=~y}function Pm(f){if(ed){for(f=f.memoizedState;f!==null;){var u=f.queue;u!==null&&(u.pending=null),f=f.next}ed=!1}so=0,Vs=Jn=dn=null,Ec=!1,Gf=td=0,Cc=null}function Hi(){var f={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Vs===null?dn.memoizedState=Vs=f:Vs=Vs.next=f,Vs}function Us(){if(Jn===null){var f=dn.alternate;f=f!==null?f.memoizedState:null}else f=Jn.next;var u=Vs===null?dn.memoizedState:Vs.next;if(u!==null)Vs=u,Jn=f;else{if(f===null){if(dn.alternate===null)throw Error(s(467));throw Error(s(310))}Jn=f,f={memoizedState:Jn.memoizedState,baseState:Jn.baseState,baseQueue:Jn.baseQueue,queue:Jn.queue,next:null},Vs===null?dn.memoizedState=Vs=f:Vs=Vs.next=f}return Vs}function vu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Tf(f){var u=Gf;return Gf+=1,Cc===null&&(Cc=[]),f=jo(Cc,f,u),u=dn,(Vs===null?u.memoizedState:Vs.next)===null&&(u=u.alternate,Nt.H=u===null||u.memoizedState===null?g5:rg),f}function Su(f){if(f!==null&&typeof f==="object"){if(typeof f.then==="function")return Tf(f);if(f.$$typeof===Mo)return Vt(f)}throw Error(s(438,String(f)))}function Nm(f){var u=null,y=dn.updateQueue;if(y!==null&&(u=y.memoCache),u==null){var x=dn.alternate;x!==null&&(x=x.updateQueue,x!==null&&(x=x.memoCache,x!=null&&(u={data:x.data.map(function(C){return C.slice()}),index:0})))}if(u==null&&(u={data:[],index:0}),y===null&&(y=vu(),dn.updateQueue=y),y.memoCache=u,y=u.data[u.index],y===void 0)for(y=u.data[u.index]=Array(f),x=0;x<f;x++)y[x]=$k;return u.index++,y}function Wa(f,u){return typeof u==="function"?u(f):u}function ku(f){var u=Us();return Bm(u,Jn,f)}function Bm(f,u,y){var x=f.queue;if(x===null)throw Error(s(311));x.lastRenderedReducer=y;var C=f.baseQueue,D=x.pending;if(D!==null){if(C!==null){var X=C.next;C.next=D.next,D.next=X}u.baseQueue=C=D,x.pending=null}if(D=f.baseState,C===null)f.memoizedState=D;else{u=C.next;var pe=X=null,Ie=null,et=u,gt=!1;do{var rt=et.lane&-536870913;if(rt!==et.lane?(xn&rt)===rt:(so&rt)===rt){var Tt=et.revertLane;if(Tt===0)Ie!==null&&(Ie=Ie.next={lane:0,revertLane:0,gesture:null,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null}),rt===vc&&(gt=!0);else if((so&Tt)===Tt){et=et.next,Tt===vc&&(gt=!0);continue}else rt={lane:0,revertLane:et.revertLane,gesture:null,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null},Ie===null?(pe=Ie=rt,X=D):Ie=Ie.next=rt,dn.lanes|=Tt,Go|=Tt;rt=et.action,jl&&y(D,rt),D=et.hasEagerState?et.eagerState:y(D,rt)}else Tt={lane:rt,revertLane:et.revertLane,gesture:et.gesture,action:et.action,hasEagerState:et.hasEagerState,eagerState:et.eagerState,next:null},Ie===null?(pe=Ie=Tt,X=D):Ie=Ie.next=Tt,dn.lanes|=rt,Go|=rt;et=et.next}while(et!==null&&et!==u);if(Ie===null?X=D:Ie.next=pe,!dr(D,f.memoizedState)&&($s=!0,gt&&(y=Sc,y!==null)))throw y;f.memoizedState=D,f.baseState=X,f.baseQueue=Ie,x.lastRenderedState=D}return C===null&&(x.lanes=0),[f.memoizedState,x.dispatch]}function Hm(f){var u=Us(),y=u.queue;if(y===null)throw Error(s(311));y.lastRenderedReducer=f;var{dispatch:x,pending:C}=y,D=u.memoizedState;if(C!==null){y.pending=null;var X=C=C.next;do D=f(D,X.action),X=X.next;while(X!==C);dr(D,u.memoizedState)||($s=!0),u.memoizedState=D,u.baseQueue===null&&(u.baseState=D),y.lastRenderedState=D}return[D,x]}function F2(f,u,y){var x=dn,C=Us(),D=Cn;if(D){if(y===void 0)throw Error(s(407));y=y()}else y=u();var X=!dr((Jn||C).memoizedState,y);if(X&&(C.memoizedState=y,$s=!0),C=C.queue,Vm(P2.bind(null,x,C,f),[f]),C.getSnapshot!==u||X||Vs!==null&&Vs.memoizedState.tag&1){if(x.flags|=2048,oc(9,{destroy:void 0},O2.bind(null,x,C,y,u),null),as===null)throw Error(s(349));D||(so&127)!==0||L2(x,u,y)}return y}function L2(f,u,y){f.flags|=16384,f={getSnapshot:u,value:y},u=dn.updateQueue,u===null?(u=vu(),dn.updateQueue=u,u.stores=[f]):(y=u.stores,y===null?u.stores=[f]:y.push(f))}function O2(f,u,y,x){u.value=y,u.getSnapshot=x,N2(u)&&B2(f)}function P2(f,u,y){return y(function(){N2(u)&&B2(f)})}function N2(f){var u=f.getSnapshot;f=f.value;try{var y=u();return!dr(f,y)}catch(x){return!0}}function B2(f){var u=At(f,2);u!==null&&$i(u,f,2)}function Um(f){var u=Hi();if(typeof f==="function"){var y=f;if(f=y(),jl){ce(!0);try{y()}finally{ce(!1)}}}return u.memoizedState=u.baseState=f,u.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wa,lastRenderedState:f},u}function H2(f,u,y,x){return f.baseState=y,Bm(f,Jn,typeof x==="function"?x:Wa)}function kk(f,u,y,x,C){if(Eu(f))throw Error(s(485));if(f=u.action,f!==null){var D={payload:C,action:f,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(X){D.listeners.push(X)}};Nt.T!==null?y(!0):D.isTransition=!1,x(D),y=u.pending,y===null?(D.next=u.pending=D,U2(u,D)):(D.next=y.next,u.pending=y.next=D)}}function U2(f,u){var{action:y,payload:x}=u,C=f.state;if(u.isTransition){var D=Nt.T,X={};Nt.T=X;try{var pe=y(C,x),Ie=Nt.S;Ie!==null&&Ie(X,pe),z2(f,u,pe)}catch(et){zm(f,u,et)}finally{D!==null&&X.types!==null&&(D.types=X.types),Nt.T=D}}else try{D=y(C,x),z2(f,u,D)}catch(et){zm(f,u,et)}}function z2(f,u,y){y!==null&&typeof y==="object"&&typeof y.then==="function"?y.then(function(x){G2(f,u,x)},function(x){return zm(f,u,x)}):G2(f,u,y)}function G2(f,u,y){u.status="fulfilled",u.value=y,V2(u),f.state=y,u=f.pending,u!==null&&(y=u.next,y===u?f.pending=null:(y=y.next,u.next=y,U2(f,y)))}function zm(f,u,y){var x=f.pending;if(f.pending=null,x!==null){x=x.next;do u.status="rejected",u.reason=y,V2(u),u=u.next;while(u!==x)}f.action=null}function V2(f){f=f.listeners;for(var u=0;u<f.length;u++)(0,f[u])()}function $2(f,u){return u}function X2(f,u){if(Cn){var y=as.formState;if(y!==null){e:{var x=dn;if(Cn){if(Ts){var C=Nx(Ts,Er);if(C){Ts=Jy(C),x=Bx(C);break e}}ft(x)}x=!1}x&&(u=y[0])}}y=Hi(),y.memoizedState=y.baseState=u,x={pending:null,lanes:0,dispatch:null,lastRenderedReducer:$2,lastRenderedState:u},y.queue=x,y=yw.bind(null,dn,x),x.dispatch=y,x=Um(!1);var D=Ym.bind(null,dn,!1,x.queue);return x=Hi(),C={state:u,dispatch:null,action:f,pending:null},x.queue=C,y=kk.bind(null,dn,C,D,y),C.dispatch=y,x.memoizedState=f,[u,y,!1]}function W2(f){var u=Us();return K2(u,Jn,f)}function K2(f,u,y){if(u=Bm(f,u,$2)[0],f=ku(Wa)[0],typeof u==="object"&&u!==null&&typeof u.then==="function")try{var x=Tf(u)}catch(X){if(X===kc)throw Qu;throw X}else x=u;u=Us();var C=u.queue,D=C.dispatch;return y!==u.memoizedState&&(dn.flags|=2048,oc(9,{destroy:void 0},xk.bind(null,C,y),null)),[x,D,f]}function xk(f,u){f.action=u}function Y2(f){var u=Us(),y=Jn;if(y!==null)return K2(u,y,f);Us(),u=u.memoizedState,y=Us();var x=y.queue.dispatch;return y.memoizedState=f,[u,x,!1]}function oc(f,u,y,x){return f={tag:f,create:y,deps:x,inst:u,next:null},u=dn.updateQueue,u===null&&(u=vu(),dn.updateQueue=u),y=u.lastEffect,y===null?u.lastEffect=f.next=f:(x=y.next,y.next=f,f.next=x,u.lastEffect=f),f}function Q2(){return Us().memoizedState}function xu(f,u,y,x){var C=Hi();dn.flags|=f,C.memoizedState=oc(1|u,{destroy:void 0},y,x===void 0?null:x)}function Tu(f,u,y,x){var C=Us();x=x===void 0?null:x;var D=C.memoizedState.inst;Jn!==null&&x!==null&&Mm(x,Jn.memoizedState.deps)?C.memoizedState=oc(u,D,y,x):(dn.flags|=f,C.memoizedState=oc(1|u,D,y,x))}function J2(f,u){xu(8390656,8,f,u)}function Vm(f,u){Tu(2048,8,f,u)}function Ak(f){dn.flags|=4;var u=dn.updateQueue;if(u===null)u=vu(),dn.updateQueue=u,u.events=[f];else{var y=u.events;y===null?u.events=[f]:y.push(f)}}function Z2(f){var u=Us().memoizedState;return Ak({ref:u,nextImpl:f}),function(){if((vn&2)!==0)throw Error(s(440));return u.impl.apply(void 0,arguments)}}function ew(f,u){return Tu(4,2,f,u)}function lw(f,u){return Tu(4,4,f,u)}function cw(f,u){if(typeof u==="function"){f=f();var y=u(f);return function(){typeof y==="function"?y():u(null)}}if(u!==null&&u!==void 0)return f=f(),u.current=f,function(){u.current=null}}function fw(f,u,y){y=y!==null&&y!==void 0?y.concat([f]):null,Tu(4,4,cw.bind(null,u,f),y)}function $m(){}function hw(f,u){var y=Us();u=u===void 0?null:u;var x=y.memoizedState;if(u!==null&&Mm(u,x[1]))return x[0];return y.memoizedState=[f,u],f}function uw(f,u){var y=Us();u=u===void 0?null:u;var x=y.memoizedState;if(u!==null&&Mm(u,x[1]))return x[0];if(x=f(),jl){ce(!0);try{f()}finally{ce(!1)}}return y.memoizedState=[x,u],x}function Xm(f,u,y){if(y===void 0||(so&1073741824)!==0&&(xn&261930)===0)return f.memoizedState=u;return f.memoizedState=y,f=hy(),dn.lanes|=f,Go|=f,y}function dw(f,u,y,x){if(dr(y,u))return y;if(Tc.current!==null)return f=Xm(f,y,x),dr(f,u)||($s=!0),f;if((so&42)===0||(so&1073741824)!==0&&(xn&261930)===0)return $s=!0,f.memoizedState=y;return f=hy(),dn.lanes|=f,Go|=f,u}function mw(f,u,y,x,C){var D=to();oi(D!==0&&8>D?D:8);var X=Nt.T,pe={};Nt.T=pe,Ym(f,!1,u,y);try{var Ie=C(),et=Nt.S;if(et!==null&&et(pe,Ie),Ie!==null&&typeof Ie==="object"&&typeof Ie.then==="function"){var gt=$a(Ie,x);Ef(f,u,gt,lr(f))}else Ef(f,u,x,lr(f))}catch(rt){Ef(f,u,{then:function(){},status:"rejected",reason:rt},lr())}finally{oi(D),X!==null&&pe.types!==null&&(X.types=pe.types),Nt.T=X}}function pw(f){var u=f.memoizedState;if(u!==null)return u;u={memoizedState:dc,baseState:dc,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wa,lastRenderedState:dc},next:null};var y={};return u.next={memoizedState:y,baseState:y,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Wa,lastRenderedState:y},next:null},f.memoizedState=u,f=f.alternate,f!==null&&(f.memoizedState=u),u}function Wm(){return Vt(Sl)}function gw(){return Us().memoizedState}function ww(){return Us().memoizedState}function Tk(f){for(var u=f.return;u!==null;){switch(u.tag){case 24:case 3:var y=lr();f=Hn(y);var x=Vn(u,f,y);x!==null&&($i(x,u,y),Qn(x,u,y)),u={cache:St()},f.payload=u;return}u=u.return}}function Ek(f,u,y){var x=lr();y={lane:x,revertLane:0,gesture:null,action:y,hasEagerState:!1,eagerState:null,next:null},Eu(f)?vw(u,y):(y=ot(f,u,y,x),y!==null&&($i(y,f,x),Sw(y,u,x)))}function yw(f,u,y){var x=lr();Ef(f,u,y,x)}function Ef(f,u,y,x){var C={lane:x,revertLane:0,gesture:null,action:y,hasEagerState:!1,eagerState:null,next:null};if(Eu(f))vw(u,C);else{var D=f.alternate;if(f.lanes===0&&(D===null||D.lanes===0)&&(D=u.lastRenderedReducer,D!==null))try{var X=u.lastRenderedState,pe=D(X,y);if(C.hasEagerState=!0,C.eagerState=pe,dr(pe,X))return je(f,u,C,0),as===null&&Gr(),!1}catch(Ie){}finally{}if(y=ot(f,u,C,x),y!==null)return $i(y,f,x),Sw(y,u,x),!0}return!1}function Ym(f,u,y,x){if(x={lane:2,revertLane:To(),gesture:null,action:x,hasEagerState:!1,eagerState:null,next:null},Eu(f)){if(u)throw Error(s(479))}else u=ot(f,y,x,2),u!==null&&$i(u,f,2)}function Eu(f){var u=f.alternate;return f===dn||u!==null&&u===dn}function vw(f,u){Ec=ed=!0;var y=f.pending;y===null?u.next=u:(u.next=y.next,y.next=u),f.pending=u}function Sw(f,u,y){if((y&4194048)!==0){var x=u.lanes;x&=f.pendingLanes,y|=x,u.lanes=y,H(f,y)}}function Qm(f,u,y,x){u=f.memoizedState,y=y(x,u),y=y===null||y===void 0?u:Dp({},u,y),f.memoizedState=y,f.lanes===0&&(f.updateQueue.baseState=y)}function kw(f,u,y,x,C,D,X){return f=f.stateNode,typeof f.shouldComponentUpdate==="function"?f.shouldComponentUpdate(x,D,X):u.prototype&&u.prototype.isPureReactComponent?!Co(y,x)||!Co(C,D):!0}function xw(f,u,y,x){f=u.state,typeof u.componentWillReceiveProps==="function"&&u.componentWillReceiveProps(y,x),typeof u.UNSAFE_componentWillReceiveProps==="function"&&u.UNSAFE_componentWillReceiveProps(y,x),u.state!==f&&ag.enqueueReplaceState(u,u.state,null)}function gl(f,u){var y=u;if("ref"in u){y={};for(var x in u)x!=="ref"&&(y[x]=u[x])}if(f=f.defaultProps){y===u&&(y=Dp({},y));for(var C in f)y[C]===void 0&&(y[C]=f[C])}return y}function Cu(f,u){try{var y=f.onUncaughtError;y(u.value,{componentStack:u.stack})}catch(x){setTimeout(function(){throw x})}}function Aw(f,u,y){try{var x=f.onCaughtError;x(y.value,{componentStack:y.stack,errorBoundary:u.tag===1?u.stateNode:null})}catch(C){setTimeout(function(){throw C})}}function Jm(f,u,y){return y=Hn(y),y.tag=3,y.payload={element:null},y.callback=function(){Cu(f,u)},y}function Tw(f){return f=Hn(f),f.tag=3,f}function Ew(f,u,y,x){var C=y.type.getDerivedStateFromError;if(typeof C==="function"){var D=x.value;f.payload=function(){return C(D)},f.callback=function(){Aw(u,y,x)}}var X=y.stateNode;X!==null&&typeof X.componentDidCatch==="function"&&(f.callback=function(){Aw(u,y,x),typeof C!=="function"&&(Vo===null?Vo=new Set([this]):Vo.add(this));var pe=x.stack;this.componentDidCatch(x.value,{componentStack:pe!==null?pe:""})})}function Ck(f,u,y,x,C){if(y.flags|=32768,x!==null&&typeof x==="object"&&typeof x.then==="function"){if(u=y.alternate,u!==null&&Ft(u,y,C,!0),y=mr.current,y!==null){switch(y.tag){case 31:case 13:return jr===null?Lu():y.alternate===null&&Ms===0&&(Ms=3),y.flags&=-257,y.flags|=65536,y.lanes=C,x===Ju?y.flags|=16384:(u=y.updateQueue,u===null?y.updateQueue=new Set([x]):u.add(x),Cp(f,x,C)),!1;case 22:return y.flags|=65536,x===Ju?y.flags|=16384:(u=y.updateQueue,u===null?(u={transitions:null,markerInstances:null,retryQueue:new Set([x])},y.updateQueue=u):(y=u.retryQueue,y===null?u.retryQueue=new Set([x]):y.add(x)),Cp(f,x,C)),!1}throw Error(s(435,y.tag))}return Cp(f,x,C),Lu(),!1}if(Cn)return u=mr.current,u!==null?((u.flags&65536)===0&&(u.flags|=256),u.flags|=65536,u.lanes=C,x!==Qp&&(f=Error(s(422),{cause:x}),Kn(he(f,y)))):(x!==Qp&&(u=Error(s(423),{cause:x}),Kn(he(u,y))),f=f.current.alternate,f.flags|=65536,C&=-C,f.lanes|=C,x=he(x,y),C=Jm(f.stateNode,x,C),Bs(f,C),Ms!==4&&(Ms=2)),!1;var D=Error(s(520),{cause:x});if(D=he(D,y),Wf===null?Wf=[D]:Wf.push(D),Ms!==4&&(Ms=2),u===null)return!0;x=he(x,y),y=u;do{switch(y.tag){case 3:return y.flags|=65536,f=C&-C,y.lanes|=f,f=Jm(y.stateNode,x,f),Bs(y,f),!1;case 1:if(u=y.type,D=y.stateNode,(y.flags&128)===0&&(typeof u.getDerivedStateFromError==="function"||D!==null&&typeof D.componentDidCatch==="function"&&(Vo===null||!Vo.has(D))))return y.flags|=65536,C&=-C,y.lanes|=C,C=Tw(C),Ew(C,f,y,x),Bs(y,C),!1}y=y.return}while(y!==null);return!1}function yi(f,u,y,x){u.child=f===null?p5(u,null,y,x):Cl(u,f.child,y,x)}function Cw(f,u,y,x,C){y=y.render;var D=u.ref;if("ref"in x){var X={};for(var pe in x)pe!=="ref"&&(X[pe]=x[pe])}else X=x;if(mn(u),x=Fm(f,u,y,X,D,C),pe=Lm(),f!==null&&!$s)return Om(f,u,C),Ka(f,u,C);return Cn&&pe&&ye(u),u.flags|=1,yi(f,u,x,C),u.child}function jw(f,u,y,x,C){if(f===null){var D=y.type;if(typeof D==="function"&&!jp(D)&&D.defaultProps===void 0&&y.compare===null)return u.tag=15,u.type=D,_w(f,u,D,x,C);return f=Pu(y.type,null,x,u,u.mode,C),f.ref=u.ref,f.return=u,u.child=f}if(D=f.child,!op(f,C)){var X=D.memoizedProps;if(y=y.compare,y=y!==null?y:Co,y(X,x)&&f.ref===u.ref)return Ka(f,u,C)}return u.flags|=1,f=Za(D,x),f.ref=u.ref,f.return=u,u.child=f}function _w(f,u,y,x,C){if(f!==null){var D=f.memoizedProps;if(Co(D,x)&&f.ref===u.ref)if($s=!1,u.pendingProps=x=D,op(f,C))(f.flags&131072)!==0&&($s=!0);else return u.lanes=f.lanes,Ka(f,u,C)}return Zm(f,u,y,x,C)}function Iw(f,u,y,x){var C=x.children,D=f!==null?f.memoizedState:null;if(f===null&&u.stateNode===null&&(u.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),x.mode==="hidden"){if((u.flags&128)!==0){if(D=D!==null?D.baseLanes|y:y,f!==null){x=u.child=f.child;for(C=0;x!==null;)C=C|x.lanes|x.childLanes,x=x.sibling;x=C&~D}else x=0,u.child=null;return Rw(f,u,D,y,x)}if((y&536870912)!==0)u.memoizedState={baseLanes:0,cachePool:null},f!==null&&Xa(u,D!==null?D.cachePool:null),D!==null?Af(u,D):Hs(),Io(u);else return x=u.lanes=536870912,Rw(f,u,D!==null?D.baseLanes|y:y,y,x)}else D!==null?(Xa(u,D.cachePool),Af(u,D),Ro(u),u.memoizedState=null):(f!==null&&Xa(u,null),Hs(),Ro(u));return yi(f,u,C,y),u.child}function Cf(f,u){return f!==null&&f.tag===22||u.stateNode!==null||(u.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),u.sibling}function Rw(f,u,y,x,C){var D=ua();return D=D===null?null:{parent:eo?Es._currentValue:Es._currentValue2,pool:D},u.memoizedState={baseLanes:y,cachePool:D},f!==null&&Xa(u,null),Hs(),Io(u),f!==null&&Ft(f,u,x,!0),u.childLanes=C,null}function ju(f,u){return u=Iu({mode:u.mode,children:u.children},f.mode),u.ref=f.ref,f.child=u,u.return=f,u}function Dw(f,u,y){return Cl(u,f.child,null,y),f=ju(u,u.pendingProps),f.flags|=2,or(u),u.memoizedState=null,f}function jk(f,u,y){var x=u.pendingProps,C=(u.flags&128)!==0;if(u.flags&=-129,f===null){if(Cn){if(x.mode==="hidden")return f=ju(u,x),u.lanes=536870912,Cf(null,f);if(ac(u),(f=Ts)?(f=Kx(f,Er),f!==null&&(u.memoizedState={dehydrated:f,treeContext:Po!==null?{id:ba,overflow:wa}:null,retryLane:536870912,hydrationErrors:null},y=Ry(f),y.return=u,u.child=y,Ai=u,Ts=null)):f=null,f===null)throw ft(u);return u.lanes=536870912,null}return ju(u,x)}var D=f.memoizedState;if(D!==null){var X=D.dehydrated;if(ac(u),C)if(u.flags&256)u.flags&=-257,u=Dw(f,u,y);else if(u.memoizedState!==null)u.child=f.child,u.flags|=128,u=null;else throw Error(s(558));else if($s||Ft(f,u,y,!1),C=(y&f.childLanes)!==0,$s||C){if(x=as,x!==null&&(X=V(x,y),X!==0&&X!==D.retryLane))throw D.retryLane=X,At(f,X),$i(x,f,X),og;Lu(),u=Dw(f,u,y)}else f=D.treeContext,Li&&(Ts=Gx(X),Ai=u,Cn=!0,Bo=null,Er=!1,f!==null&&Oe(u,f)),u=ju(u,x),u.flags|=4096;return u}return f=Za(f.child,{mode:x.mode,children:x.children}),f.ref=u.ref,u.child=f,f.return=u,f}function _u(f,u){var y=u.ref;if(y===null)f!==null&&f.ref!==null&&(u.flags|=4194816);else{if(typeof y!=="function"&&typeof y!=="object")throw Error(s(284));if(f===null||f.ref!==y)u.flags|=4194816}}function Zm(f,u,y,x,C){if(mn(u),y=Fm(f,u,y,x,void 0,C),x=Lm(),f!==null&&!$s)return Om(f,u,C),Ka(f,u,C);return Cn&&x&&ye(u),u.flags|=1,yi(f,u,y,C),u.child}function qw(f,u,y,x,C,D){if(mn(u),u.updateQueue=null,y=M2(u,x,y,C),q2(f),x=Lm(),f!==null&&!$s)return Om(f,u,D),Ka(f,u,D);return Cn&&x&&ye(u),u.flags|=1,yi(f,u,y,D),u.child}function Mw(f,u,y,x,C){if(mn(u),u.stateNode===null){var D=gc,X=y.contextType;typeof X==="object"&&X!==null&&(D=Vt(X)),D=new y(x,D),u.memoizedState=D.state!==null&&D.state!==void 0?D.state:null,D.updater=ag,u.stateNode=D,D._reactInternals=u,D=u.stateNode,D.props=x,D.state=u.memoizedState,D.refs={},gn(u),X=y.contextType,D.context=typeof X==="object"&&X!==null?Vt(X):gc,D.state=u.memoizedState,X=y.getDerivedStateFromProps,typeof X==="function"&&(Qm(u,y,X,x),D.state=u.memoizedState),typeof y.getDerivedStateFromProps==="function"||typeof D.getSnapshotBeforeUpdate==="function"||typeof D.UNSAFE_componentWillMount!=="function"&&typeof D.componentWillMount!=="function"||(X=D.state,typeof D.componentWillMount==="function"&&D.componentWillMount(),typeof D.UNSAFE_componentWillMount==="function"&&D.UNSAFE_componentWillMount(),X!==D.state&&ag.enqueueReplaceState(D,D.state,null),Ni(u,x,D,C),rs(),D.state=u.memoizedState),typeof D.componentDidMount==="function"&&(u.flags|=4194308),x=!0}else if(f===null){D=u.stateNode;var pe=u.memoizedProps,Ie=gl(y,pe);D.props=Ie;var et=D.context,gt=y.contextType;X=gc,typeof gt==="object"&&gt!==null&&(X=Vt(gt));var rt=y.getDerivedStateFromProps;gt=typeof rt==="function"||typeof D.getSnapshotBeforeUpdate==="function",pe=u.pendingProps!==pe,gt||typeof D.UNSAFE_componentWillReceiveProps!=="function"&&typeof D.componentWillReceiveProps!=="function"||(pe||et!==X)&&xw(u,D,x,X),Ho=!1;var Tt=u.memoizedState;D.state=Tt,Ni(u,x,D,C),rs(),et=u.memoizedState,pe||Tt!==et||Ho?(typeof rt==="function"&&(Qm(u,y,rt,x),et=u.memoizedState),(Ie=Ho||kw(u,y,Ie,x,Tt,et,X))?(gt||typeof D.UNSAFE_componentWillMount!=="function"&&typeof D.componentWillMount!=="function"||(typeof D.componentWillMount==="function"&&D.componentWillMount(),typeof D.UNSAFE_componentWillMount==="function"&&D.UNSAFE_componentWillMount()),typeof D.componentDidMount==="function"&&(u.flags|=4194308)):(typeof D.componentDidMount==="function"&&(u.flags|=4194308),u.memoizedProps=x,u.memoizedState=et),D.props=x,D.state=et,D.context=X,x=Ie):(typeof D.componentDidMount==="function"&&(u.flags|=4194308),x=!1)}else{D=u.stateNode,ws(f,u),X=u.memoizedProps,gt=gl(y,X),D.props=gt,rt=u.pendingProps,Tt=D.context,et=y.contextType,Ie=gc,typeof et==="object"&&et!==null&&(Ie=Vt(et)),pe=y.getDerivedStateFromProps,(et=typeof pe==="function"||typeof D.getSnapshotBeforeUpdate==="function")||typeof D.UNSAFE_componentWillReceiveProps!=="function"&&typeof D.componentWillReceiveProps!=="function"||(X!==rt||Tt!==Ie)&&xw(u,D,x,Ie),Ho=!1,Tt=u.memoizedState,D.state=Tt,Ni(u,x,D,C),rs();var ln=u.memoizedState;X!==rt||Tt!==ln||Ho||f!==null&&f.dependencies!==null&&nn(f.dependencies)?(typeof pe==="function"&&(Qm(u,y,pe,x),ln=u.memoizedState),(gt=Ho||kw(u,y,gt,x,Tt,ln,Ie)||f!==null&&f.dependencies!==null&&nn(f.dependencies))?(et||typeof D.UNSAFE_componentWillUpdate!=="function"&&typeof D.componentWillUpdate!=="function"||(typeof D.componentWillUpdate==="function"&&D.componentWillUpdate(x,ln,Ie),typeof D.UNSAFE_componentWillUpdate==="function"&&D.UNSAFE_componentWillUpdate(x,ln,Ie)),typeof D.componentDidUpdate==="function"&&(u.flags|=4),typeof D.getSnapshotBeforeUpdate==="function"&&(u.flags|=1024)):(typeof D.componentDidUpdate!=="function"||X===f.memoizedProps&&Tt===f.memoizedState||(u.flags|=4),typeof D.getSnapshotBeforeUpdate!=="function"||X===f.memoizedProps&&Tt===f.memoizedState||(u.flags|=1024),u.memoizedProps=x,u.memoizedState=ln),D.props=x,D.state=ln,D.context=Ie,x=gt):(typeof D.componentDidUpdate!=="function"||X===f.memoizedProps&&Tt===f.memoizedState||(u.flags|=4),typeof D.getSnapshotBeforeUpdate!=="function"||X===f.memoizedProps&&Tt===f.memoizedState||(u.flags|=1024),x=!1)}return D=x,_u(f,u),x=(u.flags&128)!==0,D||x?(D=u.stateNode,y=x&&typeof y.getDerivedStateFromError!=="function"?null:D.render(),u.flags|=1,f!==null&&x?(u.child=Cl(u,f.child,null,C),u.child=Cl(u,null,y,C)):yi(f,u,y,C),u.memoizedState=D.state,f=u.child):f=Ka(f,u,C),f}function Fw(f,u,y,x){return zt(),u.flags|=256,yi(f,u,y,x),u.child}function ep(f){return{baseLanes:f,cachePool:da()}}function tp(f,u,y){return f=f!==null?f.childLanes&~y:0,u&&(f|=gr),f}function Lw(f,u,y){var x=u.pendingProps,C=!1,D=(u.flags&128)!==0,X;if((X=D)||(X=f!==null&&f.memoizedState===null?!1:(zs.current&2)!==0),X&&(C=!0,u.flags&=-129),X=(u.flags&32)!==0,u.flags&=-33,f===null){if(Cn){if(C?ys(u):Ro(u),(f=Ts)?(f=Yx(f,Er),f!==null&&(u.memoizedState={dehydrated:f,treeContext:Po!==null?{id:ba,overflow:wa}:null,retryLane:536870912,hydrationErrors:null},y=Ry(f),y.return=u,u.child=y,Ai=u,Ts=null)):f=null,f===null)throw ft(u);return zp(f)?u.lanes=32:u.lanes=536870912,null}var pe=x.children;if(x=x.fallback,C)return Ro(u),C=u.mode,pe=Iu({mode:"hidden",children:pe},C),x=yl(x,C,y,null),pe.return=u,x.return=u,pe.sibling=x,u.child=pe,x=u.child,x.memoizedState=ep(y),x.childLanes=tp(f,X,y),u.memoizedState=lg,Cf(null,x);return ys(u),sp(u,pe)}var Ie=f.memoizedState;if(Ie!==null&&(pe=Ie.dehydrated,pe!==null)){if(D)u.flags&256?(ys(u),u.flags&=-257,u=ip(f,u,y)):u.memoizedState!==null?(Ro(u),u.child=f.child,u.flags|=128,u=null):(Ro(u),pe=x.fallback,C=u.mode,x=Iu({mode:"visible",children:x.children},C),pe=yl(pe,C,y,null),pe.flags|=2,x.return=u,pe.return=u,x.sibling=pe,u.child=x,Cl(u,f.child,null,y),x=u.child,x.memoizedState=ep(y),x.childLanes=tp(f,X,y),u.memoizedState=lg,u=Cf(null,x));else if(ys(u),zp(pe))X=Ox(pe).digest,x=Error(s(419)),x.stack="",x.digest=X,Kn({value:x,source:null,stack:null}),u=ip(f,u,y);else if($s||Ft(f,u,y,!1),X=(y&f.childLanes)!==0,$s||X){if(X=as,X!==null&&(x=V(X,y),x!==0&&x!==Ie.retryLane))throw Ie.retryLane=x,At(f,x),$i(X,f,x),og;Up(pe)||Lu(),u=ip(f,u,y)}else Up(pe)?(u.flags|=192,u.child=f.child,u=null):(f=Ie.treeContext,Li&&(Ts=Vx(pe),Ai=u,Cn=!0,Bo=null,Er=!1,f!==null&&Oe(u,f)),u=sp(u,x.children),u.flags|=4096);return u}if(C)return Ro(u),pe=x.fallback,C=u.mode,Ie=f.child,D=Ie.sibling,x=Za(Ie,{mode:"hidden",children:x.children}),x.subtreeFlags=Ie.subtreeFlags&65011712,D!==null?pe=Za(D,pe):(pe=yl(pe,C,y,null),pe.flags|=2),pe.return=u,x.return=u,x.sibling=pe,u.child=x,Cf(null,x),x=u.child,pe=f.child.memoizedState,pe===null?pe=ep(y):(C=pe.cachePool,C!==null?(Ie=eo?Es._currentValue:Es._currentValue2,C=C.parent!==Ie?{parent:Ie,pool:Ie}:C):C=da(),pe={baseLanes:pe.baseLanes|y,cachePool:C}),x.memoizedState=pe,x.childLanes=tp(f,X,y),u.memoizedState=lg,Cf(f.child,x);return ys(u),y=f.child,f=y.sibling,y=Za(y,{mode:"visible",children:x.children}),y.return=u,y.sibling=null,f!==null&&(X=u.deletions,X===null?(u.deletions=[f],u.flags|=16):X.push(f)),u.child=y,u.memoizedState=null,y}function sp(f,u){return u=Iu({mode:"visible",children:u},f.mode),u.return=f,f.child=u}function Iu(f,u){return f=t(22,f,null,u),f.lanes=0,f}function ip(f,u,y){return Cl(u,f.child,null,y),f=sp(u,u.pendingProps.children),f.flags|=2,u.memoizedState=null,f}function Ow(f,u,y){f.lanes|=u;var x=f.alternate;x!==null&&(x.lanes|=u),bt(f.return,u,y)}function rp(f,u,y,x,C,D){var X=f.memoizedState;X===null?f.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:x,tail:y,tailMode:C,treeForkCount:D}:(X.isBackwards=u,X.rendering=null,X.renderingStartTime=0,X.last=x,X.tail=y,X.tailMode=C,X.treeForkCount=D)}function Pw(f,u,y){var x=u.pendingProps,C=x.revealOrder,D=x.tail;x=x.children;var X=zs.current,pe=(X&2)!==0;if(pe?(X=X&1|2,u.flags|=128):X&=1,b(zs,X),yi(f,u,x,y),x=Cn?Nf:0,!pe&&f!==null&&(f.flags&128)!==0)e:for(f=u.child;f!==null;){if(f.tag===13)f.memoizedState!==null&&Ow(f,y,u);else if(f.tag===19)Ow(f,y,u);else if(f.child!==null){f.child.return=f,f=f.child;continue}if(f===u)break e;for(;f.sibling===null;){if(f.return===null||f.return===u)break e;f=f.return}f.sibling.return=f.return,f=f.sibling}switch(C){case"forwards":y=u.child;for(C=null;y!==null;)f=y.alternate,f!==null&&yu(f)===null&&(C=y),y=y.sibling;y=C,y===null?(C=u.child,u.child=null):(C=y.sibling,y.sibling=null),rp(u,!1,C,y,D,x);break;case"backwards":case"unstable_legacy-backwards":y=null,C=u.child;for(u.child=null;C!==null;){if(f=C.alternate,f!==null&&yu(f)===null){u.child=C;break}f=C.sibling,C.sibling=y,y=C,C=f}rp(u,!0,y,null,D,x);break;case"together":rp(u,!1,null,null,void 0,x);break;default:u.memoizedState=null}return u.child}function Ka(f,u,y){if(f!==null&&(u.dependencies=f.dependencies),Go|=u.lanes,(y&u.childLanes)===0)if(f!==null){if(Ft(f,u,y,!1),(y&u.childLanes)===0)return null}else return null;if(f!==null&&u.child!==f.child)throw Error(s(153));if(u.child!==null){f=u.child,y=Za(f,f.pendingProps),u.child=y;for(y.return=u;f.sibling!==null;)f=f.sibling,y=y.sibling=Za(f,f.pendingProps),y.return=u;y.sibling=null}return u.child}function op(f,u){if((f.lanes&u)!==0)return!0;return f=f.dependencies,f!==null&&nn(f)?!0:!1}function _k(f,u,y){switch(u.tag){case 3:st(u,u.stateNode.containerInfo),Le(u,Es,f.memoizedState.cache),zt();break;case 27:case 5:wt(u);break;case 4:st(u,u.stateNode.containerInfo);break;case 10:Le(u,u.type,u.memoizedProps.value);break;case 31:if(u.memoizedState!==null)return u.flags|=128,ac(u),null;break;case 13:var x=u.memoizedState;if(x!==null){if(x.dehydrated!==null)return ys(u),u.flags|=128,null;if((y&u.child.childLanes)!==0)return Lw(f,u,y);return ys(u),f=Ka(f,u,y),f!==null?f.sibling:null}ys(u);break;case 19:var C=(f.flags&128)!==0;if(x=(y&u.childLanes)!==0,x||(Ft(f,u,y,!1),x=(y&u.childLanes)!==0),C){if(x)return Pw(f,u,y);u.flags|=128}if(C=u.memoizedState,C!==null&&(C.rendering=null,C.tail=null,C.lastEffect=null),b(zs,zs.current),x)break;else return null;case 22:return u.lanes=0,Iw(f,u,y,u.pendingProps);case 24:Le(u,Es,f.memoizedState.cache)}return Ka(f,u,y)}function Nw(f,u,y){if(f!==null)if(f.memoizedProps!==u.pendingProps)$s=!0;else{if(!op(f,y)&&(u.flags&128)===0)return $s=!1,_k(f,u,y);$s=(f.flags&131072)!==0?!0:!1}else $s=!1,Cn&&(u.flags&1048576)!==0&&be(u,Nf,u.index);switch(u.lanes=0,u.tag){case 16:e:{var x=u.pendingProps;if(f=ir(u.elementType),u.type=f,typeof f==="function")jp(f)?(x=gl(f,x),u.tag=1,u=Mw(null,u,f,x,y)):(u.tag=0,u=Zm(null,u,f,x,y));else{if(f!==void 0&&f!==null){var C=f.$$typeof;if(C===Mp){u.tag=11,u=Cw(null,u,f,x,y);break e}else if(C===Op){u.tag=14,u=jw(null,u,f,x,y);break e}}throw u=d(f)||f,Error(s(306,u,""))}}return u;case 0:return Zm(f,u,u.type,u.pendingProps,y);case 1:return x=u.type,C=gl(x,u.pendingProps),Mw(f,u,x,C,y);case 3:e:{if(st(u,u.stateNode.containerInfo),f===null)throw Error(s(387));var D=u.pendingProps;C=u.memoizedState,x=C.element,ws(f,u),Ni(u,D,null,y);var X=u.memoizedState;if(D=X.cache,Le(u,Es,D),D!==C.cache&&ut(u,[Es],y,!0),rs(),D=X.element,Li&&C.isDehydrated)if(C={element:D,isDehydrated:!1,cache:X.cache},u.updateQueue.baseState=C,u.memoizedState=C,u.flags&256){u=Fw(f,u,D,y);break e}else if(D!==x){x=he(Error(s(424)),u),Kn(x),u=Fw(f,u,D,y);break e}else for(Li&&(Ts=zx(u.stateNode.containerInfo),Ai=u,Cn=!0,Bo=null,Er=!0),y=p5(u,null,D,y),u.child=y;y;)y.flags=y.flags&-3|4096,y=y.sibling;else{if(zt(),D===x){u=Ka(f,u,y);break e}yi(f,u,D,y)}u=u.child}return u;case 26:if(Yr)return _u(f,u),f===null?(y=t5(u.type,null,u.pendingProps,null))?u.memoizedState=y:Cn||(u.stateNode=gA(u.type,u.pendingProps,No.current,u)):u.memoizedState=t5(u.type,f.memoizedProps,u.pendingProps,f.memoizedState),null;case 27:if(ei)return wt(u),f===null&&ei&&Cn&&(x=u.stateNode=o5(u.type,u.pendingProps,No.current,vi.current,!1),Ai=u,Er=!0,Ts=$x(u.type,x,Ts)),yi(f,u,u.pendingProps.children,y),_u(f,u),f===null&&(u.flags|=4194304),u.child;case 5:if(f===null&&Cn){if(dA(u.type,u.pendingProps,vi.current),C=x=Ts)x=Xx(x,u.type,u.pendingProps,Er),x!==null?(u.stateNode=x,Ai=u,Ts=Ux(x),Er=!1,C=!0):C=!1;C||ft(u)}return wt(u),C=u.type,D=u.pendingProps,X=f!==null?f.memoizedProps:null,x=D.children,Hu(C,D)?x=null:X!==null&&Hu(C,X)&&(u.flags|=32),u.memoizedState!==null&&(C=Fm(f,u,Sk,null,null,y),eo?Sl._currentValue=C:Sl._currentValue2=C),_u(f,u),yi(f,u,x,y),u.child;case 6:if(f===null&&Cn){if(mA(u.pendingProps,vi.current),f=y=Ts)y=Wx(y,u.pendingProps,Er),y!==null?(u.stateNode=y,Ai=u,Ts=null,f=!0):f=!1;f||ft(u)}return null;case 13:return Lw(f,u,y);case 4:return st(u,u.stateNode.containerInfo),x=u.pendingProps,f===null?u.child=Cl(u,null,x,y):yi(f,u,x,y),u.child;case 11:return Cw(f,u,u.type,u.pendingProps,y);case 7:return yi(f,u,u.pendingProps,y),u.child;case 8:return yi(f,u,u.pendingProps.children,y),u.child;case 12:return yi(f,u,u.pendingProps.children,y),u.child;case 10:return x=u.pendingProps,Le(u,u.type,x.value),yi(f,u,x.children,y),u.child;case 9:return C=u.type._context,x=u.pendingProps.children,mn(u),C=Vt(C),x=x(C),u.flags|=1,yi(f,u,x,y),u.child;case 14:return jw(f,u,u.type,u.pendingProps,y);case 15:return _w(f,u,u.type,u.pendingProps,y);case 19:return Pw(f,u,y);case 31:return jk(f,u,y);case 22:return Iw(f,u,y,u.pendingProps);case 24:return mn(u),x=Vt(Es),f===null?(C=ua(),C===null&&(C=as,D=St(),C.pooledCache=D,D.refCount++,D!==null&&(C.pooledCacheLanes|=y),C=D),u.memoizedState={parent:x,cache:C},gn(u),Le(u,Es,C)):((f.lanes&y)!==0&&(ws(f,u),Ni(u,null,null,y),rs()),C=f.memoizedState,D=u.memoizedState,C.parent!==x?(C={parent:x,cache:x},u.memoizedState=C,u.lanes===0&&(u.memoizedState=u.updateQueue.baseState=C),Le(u,Es,x)):(x=D.cache,Le(u,Es,x),x!==C.cache&&ut(u,[Es],y,!0))),yi(f,u,u.pendingProps.children,y),u.child;case 29:throw u.pendingProps}throw Error(s(156,u.tag))}function $r(f){f.flags|=4}function Ru(f){ga&&(f.flags|=8)}function Bw(f,u){if(f!==null&&f.child===u.child)return!1;if((u.flags&16)!==0)return!0;for(f=u.child;f!==null;){if((f.flags&8218)!==0||(f.subtreeFlags&8218)!==0)return!0;f=f.sibling}return!1}function lp(f,u,y,x){if(Fi)for(y=u.child;y!==null;){if(y.tag===5||y.tag===6)Np(f,y.stateNode);else if(!(y.tag===4||ei&&y.tag===27)&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===u)break;for(;y.sibling===null;){if(y.return===null||y.return===u)return;y=y.return}y.sibling.return=y.return,y=y.sibling}else if(ga)for(var C=u.child;C!==null;){if(C.tag===5){var D=C.stateNode;y&&x&&(D=Yy(D,C.type,C.memoizedProps)),Np(f,D)}else if(C.tag===6)D=C.stateNode,y&&x&&(D=Qy(D,C.memoizedProps)),Np(f,D);else if(C.tag!==4){if(C.tag===22&&C.memoizedState!==null)D=C.child,D!==null&&(D.return=C),lp(f,C,!0,!0);else if(C.child!==null){C.child.return=C,C=C.child;continue}}if(C===u)break;for(;C.sibling===null;){if(C.return===null||C.return===u)return;C=C.return}C.sibling.return=C.return,C=C.sibling}}function Hw(f,u,y,x){var C=!1;if(ga)for(var D=u.child;D!==null;){if(D.tag===5){var X=D.stateNode;y&&x&&(X=Yy(X,D.type,D.memoizedProps)),Wy(f,X)}else if(D.tag===6)X=D.stateNode,y&&x&&(X=Qy(X,D.memoizedProps)),Wy(f,X);else if(D.tag!==4){if(D.tag===22&&D.memoizedState!==null)C=D.child,C!==null&&(C.return=D),Hw(f,D,!0,!0),C=!0;else if(D.child!==null){D.child.return=D,D=D.child;continue}}if(D===u)break;for(;D.sibling===null;){if(D.return===null||D.return===u)return C;D=D.return}D.sibling.return=D.return,D=D.sibling}return C}function Uw(f,u){if(ga&&Bw(f,u)){f=u.stateNode;var y=f.containerInfo,x=Xy();Hw(x,u,!1,!1),f.pendingChildren=x,$r(u),Lx(y,x)}}function cp(f,u,y,x){if(Fi)f.memoizedProps!==x&&$r(u);else if(ga){var C=f.stateNode,D=f.memoizedProps;if((f=Bw(f,u))||D!==x){var X=vi.current;D=Fx(C,y,D,x,!f,null),D===C?u.stateNode=C:(Ru(u),Uy(D,y,x,X)&&$r(u),u.stateNode=D,f&&lp(D,u,!1,!1))}else u.stateNode=C}}function fp(f,u,y,x,C){if((f.mode&32)!==0&&(y===null?lx(u,x):cx(u,y,x))){if(f.flags|=16777216,(C&335544128)===C||Bp(u,x))if(Gy(f.stateNode,u,x))f.flags|=8192;else if(gy())f.flags|=8192;else throw El=Ju,ng}else f.flags&=-16777217}function zw(f,u){if(yA(u)){if(f.flags|=16777216,!a5(u))if(gy())f.flags|=8192;else throw El=Ju,ng}else f.flags&=-16777217}function Du(f,u){u!==null&&(f.flags|=4),f.flags&16384&&(u=f.tag!==22?I():536870912,f.lanes|=u,Rc|=u)}function jf(f,u){if(!Cn)switch(f.tailMode){case"hidden":u=f.tail;for(var y=null;u!==null;)u.alternate!==null&&(y=u),u=u.sibling;y===null?f.tail=null:y.sibling=null;break;case"collapsed":y=f.tail;for(var x=null;y!==null;)y.alternate!==null&&(x=y),y=y.sibling;x===null?u||f.tail===null?f.tail=null:f.tail.sibling=null:x.sibling=null}}function ms(f){var u=f.alternate!==null&&f.alternate.child===f.child,y=0,x=0;if(u)for(var C=f.child;C!==null;)y|=C.lanes|C.childLanes,x|=C.subtreeFlags&65011712,x|=C.flags&65011712,C.return=f,C=C.sibling;else for(C=f.child;C!==null;)y|=C.lanes|C.childLanes,x|=C.subtreeFlags,x|=C.flags,C.return=f,C=C.sibling;return f.subtreeFlags|=x,f.childLanes=y,u}function Ik(f,u,y){var x=u.pendingProps;switch(Te(u),u.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return ms(u),null;case 1:return ms(u),null;case 3:if(y=u.stateNode,x=null,f!==null&&(x=f.memoizedState.cache),u.memoizedState.cache!==x&&(u.flags|=2048),Je(Es),We(),y.pendingContext&&(y.context=y.pendingContext,y.pendingContext=null),f===null||f.child===null)hn(u)?$r(u):f===null||f.memoizedState.isDehydrated&&(u.flags&256)===0||(u.flags|=1024,tn());return Uw(f,u),ms(u),null;case 26:if(Yr){var{type:C,memoizedState:D}=u;return f===null?($r(u),D!==null?(ms(u),zw(u,D)):(ms(u),fp(u,C,null,x,y))):D?D!==f.memoizedState?($r(u),ms(u),zw(u,D)):(ms(u),u.flags&=-16777217):(D=f.memoizedProps,Fi?D!==x&&$r(u):cp(f,u,C,x),ms(u),fp(u,C,D,x,y)),null}case 27:if(ei){if(xt(u),y=No.current,C=u.type,f!==null&&u.stateNode!=null)Fi?f.memoizedProps!==x&&$r(u):cp(f,u,C,x);else{if(!x){if(u.stateNode===null)throw Error(s(166));return ms(u),null}f=vi.current,hn(u)?It(u,f):(f=o5(C,x,y,f,!0),u.stateNode=f,$r(u))}return ms(u),null}case 5:if(xt(u),C=u.type,f!==null&&u.stateNode!=null)cp(f,u,C,x);else{if(!x){if(u.stateNode===null)throw Error(s(166));return ms(u),null}if(D=vi.current,hn(u))It(u,D),oA(u.stateNode,C,x,D)&&(u.flags|=64);else{var X=ex(C,x,No.current,D,u);Ru(u),lp(X,u,!1,!1),u.stateNode=X,Uy(X,C,x,D)&&$r(u)}}return ms(u),fp(u,u.type,f===null?null:f.memoizedProps,u.pendingProps,y),null;case 6:if(f&&u.stateNode!=null)y=f.memoizedProps,Fi?y!==x&&$r(u):ga&&(y!==x?(f=No.current,y=vi.current,Ru(u),u.stateNode=zy(x,f,y,u)):u.stateNode=f.stateNode);else{if(typeof x!=="string"&&u.stateNode===null)throw Error(s(166));if(f=No.current,y=vi.current,hn(u)){if(!Li)throw Error(s(176));if(f=u.stateNode,y=u.memoizedProps,x=null,C=Ai,C!==null)switch(C.tag){case 27:case 5:x=C.memoizedProps}Jx(f,y,u,x)||ft(u,!0)}else Ru(u),u.stateNode=zy(x,f,y,u)}return ms(u),null;case 31:if(y=u.memoizedState,f===null||f.memoizedState!==null){if(x=hn(u),y!==null){if(f===null){if(!x)throw Error(s(318));if(!Li)throw Error(s(556));if(f=u.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(s(557));Zx(f,u)}else zt(),(u.flags&128)===0&&(u.memoizedState=null),u.flags|=4;ms(u),f=!1}else y=tn(),f!==null&&f.memoizedState!==null&&(f.memoizedState.hydrationErrors=y),f=!0;if(!f){if(u.flags&256)return or(u),u;return or(u),null}if((u.flags&128)!==0)throw Error(s(558))}return ms(u),null;case 13:if(x=u.memoizedState,f===null||f.memoizedState!==null&&f.memoizedState.dehydrated!==null){if(C=hn(u),x!==null&&x.dehydrated!==null){if(f===null){if(!C)throw Error(s(318));if(!Li)throw Error(s(344));if(C=u.memoizedState,C=C!==null?C.dehydrated:null,!C)throw Error(s(317));eA(C,u)}else zt(),(u.flags&128)===0&&(u.memoizedState=null),u.flags|=4;ms(u),C=!1}else C=tn(),f!==null&&f.memoizedState!==null&&(f.memoizedState.hydrationErrors=C),C=!0;if(!C){if(u.flags&256)return or(u),u;return or(u),null}}if(or(u),(u.flags&128)!==0)return u.lanes=y,u;return y=x!==null,f=f!==null&&f.memoizedState!==null,y&&(x=u.child,C=null,x.alternate!==null&&x.alternate.memoizedState!==null&&x.alternate.memoizedState.cachePool!==null&&(C=x.alternate.memoizedState.cachePool.pool),D=null,x.memoizedState!==null&&x.memoizedState.cachePool!==null&&(D=x.memoizedState.cachePool.pool),D!==C&&(x.flags|=2048)),y!==f&&y&&(u.child.flags|=8192),Du(u,u.updateQueue),ms(u),null;case 4:return We(),Uw(f,u),f===null&&ix(u.stateNode.containerInfo),ms(u),null;case 10:return Je(u.type),ms(u),null;case 19:if(p(zs),x=u.memoizedState,x===null)return ms(u),null;if(C=(u.flags&128)!==0,D=x.rendering,D===null)if(C)jf(x,!1);else{if(Ms!==0||f!==null&&(f.flags&128)!==0)for(f=u.child;f!==null;){if(D=yu(f),D!==null){u.flags|=128,jf(x,!1),f=D.updateQueue,u.updateQueue=f,Du(u,f),u.subtreeFlags=0,f=y;for(y=u.child;y!==null;)Iy(y,f),y=y.sibling;return b(zs,zs.current&1|2),Cn&&we(u,x.treeForkCount),u.child}f=f.sibling}x.tail!==null&&Xi()>Kf&&(u.flags|=128,C=!0,jf(x,!1),u.lanes=4194304)}else{if(!C)if(f=yu(D),f!==null){if(u.flags|=128,C=!0,f=f.updateQueue,u.updateQueue=f,Du(u,f),jf(x,!0),x.tail===null&&x.tailMode==="hidden"&&!D.alternate&&!Cn)return ms(u),null}else 2*Xi()-x.renderingStartTime>Kf&&y!==536870912&&(u.flags|=128,C=!0,jf(x,!1),u.lanes=4194304);x.isBackwards?(D.sibling=u.child,u.child=D):(f=x.last,f!==null?f.sibling=D:u.child=D,x.last=D)}if(x.tail!==null)return f=x.tail,x.rendering=f,x.tail=f.sibling,x.renderingStartTime=Xi(),f.sibling=null,y=zs.current,b(zs,C?y&1|2:y&1),Cn&&we(u,x.treeForkCount),f;return ms(u),null;case 22:case 23:return or(u),Bi(),x=u.memoizedState!==null,f!==null?f.memoizedState!==null!==x&&(u.flags|=8192):x&&(u.flags|=8192),x?(y&536870912)!==0&&(u.flags&128)===0&&(ms(u),u.subtreeFlags&6&&(u.flags|=8192)):ms(u),y=u.updateQueue,y!==null&&Du(u,y.retryQueue),y=null,f!==null&&f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(y=f.memoizedState.cachePool.pool),x=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(x=u.memoizedState.cachePool.pool),x!==y&&(u.flags|=2048),f!==null&&p(Al),null;case 24:return y=null,f!==null&&(y=f.memoizedState.cache),u.memoizedState.cache!==y&&(u.flags|=2048),Je(Es),ms(u),null;case 25:return null;case 30:return null}throw Error(s(156,u.tag))}function Rk(f,u){switch(Te(u),u.tag){case 1:return f=u.flags,f&65536?(u.flags=f&-65537|128,u):null;case 3:return Je(Es),We(),f=u.flags,(f&65536)!==0&&(f&128)===0?(u.flags=f&-65537|128,u):null;case 26:case 27:case 5:return xt(u),null;case 31:if(u.memoizedState!==null){if(or(u),u.alternate===null)throw Error(s(340));zt()}return f=u.flags,f&65536?(u.flags=f&-65537|128,u):null;case 13:if(or(u),f=u.memoizedState,f!==null&&f.dehydrated!==null){if(u.alternate===null)throw Error(s(340));zt()}return f=u.flags,f&65536?(u.flags=f&-65537|128,u):null;case 19:return p(zs),null;case 4:return We(),null;case 10:return Je(u.type),null;case 22:case 23:return or(u),Bi(),f!==null&&p(Al),f=u.flags,f&65536?(u.flags=f&-65537|128,u):null;case 24:return Je(Es),null;case 25:return null;default:return null}}function Gw(f,u){switch(Te(u),u.tag){case 3:Je(Es),We();break;case 26:case 27:case 5:xt(u);break;case 4:We();break;case 31:u.memoizedState!==null&&or(u);break;case 13:or(u);break;case 19:p(zs);break;case 10:Je(u.type);break;case 22:case 23:or(u),Bi(),f!==null&&p(Al);break;case 24:Je(Es)}}function _f(f,u){try{var y=u.updateQueue,x=y!==null?y.lastEffect:null;if(x!==null){var C=x.next;y=C;do{if((y.tag&f)===f){x=void 0;var D=y.create,X=y.inst;x=D(),X.destroy=x}y=y.next}while(y!==C)}}catch(pe){On(u,u.return,pe)}}function Do(f,u,y){try{var x=u.updateQueue,C=x!==null?x.lastEffect:null;if(C!==null){var D=C.next;x=D;do{if((x.tag&f)===f){var X=x.inst,pe=X.destroy;if(pe!==void 0){X.destroy=void 0,C=u;var Ie=y,et=pe;try{et()}catch(gt){On(C,Ie,gt)}}}x=x.next}while(x!==D)}}catch(gt){On(u,u.return,gt)}}function Vw(f){var u=f.updateQueue;if(u!==null){var y=f.stateNode;try{xf(u,y)}catch(x){On(f,f.return,x)}}}function $w(f,u,y){y.props=gl(f.type,f.memoizedProps),y.state=f.memoizedState;try{y.componentWillUnmount()}catch(x){On(f,u,x)}}function If(f,u){try{var y=f.ref;if(y!==null){switch(f.tag){case 26:case 27:case 5:var x=Mf(f.stateNode);break;case 30:x=f.stateNode;break;default:x=f.stateNode}typeof y==="function"?f.refCleanup=y(x):y.current=x}}catch(C){On(f,u,C)}}function pa(f,u){var y=f.ref,x=f.refCleanup;if(y!==null)if(typeof x==="function")try{x()}catch(C){On(f,u,C)}finally{f.refCleanup=null,f=f.alternate,f!=null&&(f.refCleanup=null)}else if(typeof y==="function")try{y(null)}catch(C){On(f,u,C)}else y.current=null}function Xw(f){var{type:u,memoizedProps:y,stateNode:x}=f;try{Ax(x,u,y,f)}catch(C){On(f,f.return,C)}}function hp(f,u,y){try{Tx(f.stateNode,f.type,y,u,f)}catch(x){On(f,f.return,x)}}function Kw(f){return f.tag===5||f.tag===3||(Yr?f.tag===26:!1)||(ei?f.tag===27&&mc(f.type):!1)||f.tag===4}function dp(f){e:for(;;){for(;f.sibling===null;){if(f.return===null||Kw(f.return))return null;f=f.return}f.sibling.return=f.return;for(f=f.sibling;f.tag!==5&&f.tag!==6&&f.tag!==18;){if(ei&&f.tag===27&&mc(f.type))continue e;if(f.flags&2)continue e;if(f.child===null||f.tag===4)continue e;else f.child.return=f,f=f.child}if(!(f.flags&2))return f.stateNode}}function mp(f,u,y){var x=f.tag;if(x===5||x===6)f=f.stateNode,u?Cx(y,f,u):kx(y,f);else if(x!==4&&(ei&&x===27&&mc(f.type)&&(y=f.stateNode,u=null),f=f.child,f!==null))for(mp(f,u,y),f=f.sibling;f!==null;)mp(f,u,y),f=f.sibling}function qu(f,u,y){var x=f.tag;if(x===5||x===6)f=f.stateNode,u?Ex(y,f,u):Sx(y,f);else if(x!==4&&(ei&&x===27&&mc(f.type)&&(y=f.stateNode),f=f.child,f!==null))for(qu(f,u,y),f=f.sibling;f!==null;)qu(f,u,y),f=f.sibling}function Yw(f,u,y){f=f.containerInfo;try{Ky(f,y)}catch(x){On(u,u.return,x)}}function Jw(f){var{stateNode:u,memoizedProps:y}=f;try{SA(f.type,y,u,f)}catch(x){On(f,f.return,x)}}function Dk(f,u){Jk(f.containerInfo);for(hi=u;hi!==null;)if(f=hi,u=f.child,(f.subtreeFlags&1028)!==0&&u!==null)u.return=f,hi=u;else for(;hi!==null;){f=hi;var y=f.alternate;switch(u=f.flags,f.tag){case 0:if((u&4)!==0&&(u=f.updateQueue,u=u!==null?u.events:null,u!==null))for(var x=0;x<u.length;x++){var C=u[x];C.ref.impl=C.nextImpl}break;case 11:case 15:break;case 1:if((u&1024)!==0&&y!==null){u=void 0,x=f,C=y.memoizedProps,y=y.memoizedState;var D=x.stateNode;try{var X=gl(x.type,C);u=D.getSnapshotBeforeUpdate(X,y),D.__reactInternalSnapshotBeforeUpdate=u}catch(pe){On(x,x.return,pe)}}break;case 3:(u&1024)!==0&&Fi&&Mx(f.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((u&1024)!==0)throw Error(s(163))}if(u=f.sibling,u!==null){u.return=f.return,hi=u;break}hi=f.return}}function Zw(f,u,y){var x=y.flags;switch(y.tag){case 0:case 11:case 15:Ya(f,y),x&4&&_f(5,y);break;case 1:if(Ya(f,y),x&4)if(f=y.stateNode,u===null)try{f.componentDidMount()}catch(X){On(y,y.return,X)}else{var C=gl(y.type,u.memoizedProps);u=u.memoizedState;try{f.componentDidUpdate(C,u,f.__reactInternalSnapshotBeforeUpdate)}catch(X){On(y,y.return,X)}}x&64&&Vw(y),x&512&&If(y,y.return);break;case 3:if(Ya(f,y),x&64&&(x=y.updateQueue,x!==null)){if(f=null,y.child!==null)switch(y.child.tag){case 27:case 5:f=Mf(y.child.stateNode);break;case 1:f=y.child.stateNode}try{xf(x,f)}catch(X){On(y,y.return,X)}}break;case 27:ei&&u===null&&x&4&&Jw(y);case 26:case 5:if(Ya(f,y),u===null){if(x&4)Xw(y);else if(x&64){f=y.type,u=y.memoizedProps,C=y.stateNode;try{sA(C,f,u,y)}catch(X){On(y,y.return,X)}}}x&512&&If(y,y.return);break;case 12:Ya(f,y);break;case 31:Ya(f,y),x&4&&ty(f,y);break;case 13:Ya(f,y),x&4&&ny(f,y),x&64&&(x=y.memoizedState,x!==null&&(x=x.dehydrated,x!==null&&(y=Nk.bind(null,y),Px(x,y))));break;case 22:if(x=y.memoizedState!==null||io,!x){u=u!==null&&u.memoizedState!==null||Xs,C=io;var D=Xs;io=x,(Xs=u)&&!D?Ja(f,y,(y.subtreeFlags&8772)!==0):Ya(f,y),io=C,Xs=D}break;case 30:break;default:Ya(f,y)}}function ey(f){var u=f.alternate;u!==null&&(f.alternate=null,ey(u)),f.child=null,f.deletions=null,f.sibling=null,f.tag===5&&(u=f.stateNode,u!==null&&ox(u)),f.stateNode=null,f.return=null,f.dependencies=null,f.memoizedProps=null,f.memoizedState=null,f.pendingProps=null,f.stateNode=null,f.updateQueue=null}function Xr(f,u,y){for(y=y.child;y!==null;)pp(f,u,y),y=y.sibling}function pp(f,u,y){if(hr&&typeof hr.onCommitFiberUnmount==="function")try{hr.onCommitFiberUnmount(Pf,y)}catch(D){}switch(y.tag){case 26:if(Yr){Xs||pa(y,u),Xr(f,u,y),y.memoizedState?s5(y.memoizedState):y.stateNode&&r5(y.stateNode);break}case 27:if(ei){Xs||pa(y,u);var x=Ws,C=Wi;mc(y.type)&&(Ws=y.stateNode,Wi=!1),Xr(f,u,y),l5(y.stateNode),Ws=x,Wi=C;break}case 5:Xs||pa(y,u);case 6:if(Fi){if(x=Ws,C=Wi,Ws=null,Xr(f,u,y),Ws=x,Wi=C,Ws!==null)if(Wi)try{_x(Ws,y.stateNode)}catch(D){On(y,u,D)}else try{jx(Ws,y.stateNode)}catch(D){On(y,u,D)}}else Xr(f,u,y);break;case 18:Fi&&Ws!==null&&(Wi?fA(Ws,y.stateNode):cA(Ws,y.stateNode));break;case 4:Fi?(x=Ws,C=Wi,Ws=y.stateNode.containerInfo,Wi=!0,Xr(f,u,y),Ws=x,Wi=C):(ga&&Yw(y.stateNode,y,Xy()),Xr(f,u,y));break;case 0:case 11:case 14:case 15:Do(2,y,u),Xs||Do(4,y,u),Xr(f,u,y);break;case 1:Xs||(pa(y,u),x=y.stateNode,typeof x.componentWillUnmount==="function"&&$w(y,u,x)),Xr(f,u,y);break;case 21:Xr(f,u,y);break;case 22:Xs=(x=Xs)||y.memoizedState!==null,Xr(f,u,y),Xs=x;break;default:Xr(f,u,y)}}function ty(f,u){if(Li&&u.memoizedState===null&&(f=u.alternate,f!==null&&(f=f.memoizedState,f!==null))){f=f.dehydrated;try{rA(f)}catch(y){On(u,u.return,y)}}}function ny(f,u){if(Li&&u.memoizedState===null&&(f=u.alternate,f!==null&&(f=f.memoizedState,f!==null&&(f=f.dehydrated,f!==null))))try{aA(f)}catch(y){On(u,u.return,y)}}function qk(f){switch(f.tag){case 31:case 13:case 19:var u=f.stateNode;return u===null&&(u=f.stateNode=new w5),u;case 22:return f=f.stateNode,u=f._retryCache,u===null&&(u=f._retryCache=new w5),u;default:throw Error(s(435,f.tag))}}function Mu(f,u){var y=qk(f);u.forEach(function(x){if(!y.has(x)){y.add(x);var C=Bk.bind(null,f,x);x.then(C,C)}})}function Mi(f,u){var y=u.deletions;if(y!==null)for(var x=0;x<y.length;x++){var C=y[x],D=f,X=u;if(Fi){var pe=X;e:for(;pe!==null;){switch(pe.tag){case 27:if(ei){if(mc(pe.type)){Ws=pe.stateNode,Wi=!1;break e}break}case 5:Ws=pe.stateNode,Wi=!1;break e;case 3:case 4:Ws=pe.stateNode.containerInfo,Wi=!0;break e}pe=pe.return}if(Ws===null)throw Error(s(160));pp(D,X,C),Ws=null,Wi=!1}else pp(D,X,C);D=C.alternate,D!==null&&(D.return=null),C.return=null}if(u.subtreeFlags&13886)for(u=u.child;u!==null;)sy(u,f),u=u.sibling}function sy(f,u){var y=f.alternate,x=f.flags;switch(f.tag){case 0:case 11:case 14:case 15:Mi(u,f),Ui(f),x&4&&(Do(3,f,f.return),_f(3,f),Do(5,f,f.return));break;case 1:Mi(u,f),Ui(f),x&512&&(Xs||y===null||pa(y,y.return)),x&64&&io&&(f=f.updateQueue,f!==null&&(x=f.callbacks,x!==null&&(y=f.shared.hiddenCallbacks,f.shared.hiddenCallbacks=y===null?x:y.concat(x))));break;case 26:if(Yr){var C=Qr;if(Mi(u,f),Ui(f),x&512&&(Xs||y===null||pa(y,y.return)),x&4){x=y!==null?y.memoizedState:null;var D=f.memoizedState;y===null?D===null?f.stateNode===null?f.stateNode=pA(C,f.type,f.memoizedProps,f):i5(C,f.type,f.stateNode):f.stateNode=n5(C,D,f.memoizedProps):x!==D?(x===null?y.stateNode!==null&&r5(y.stateNode):s5(x),D===null?i5(C,f.type,f.stateNode):n5(C,D,f.memoizedProps)):D===null&&f.stateNode!==null&&hp(f,f.memoizedProps,y.memoizedProps)}break}case 27:if(ei){Mi(u,f),Ui(f),x&512&&(Xs||y===null||pa(y,y.return)),y!==null&&x&4&&hp(f,f.memoizedProps,y.memoizedProps);break}case 5:if(Mi(u,f),Ui(f),x&512&&(Xs||y===null||pa(y,y.return)),Fi){if(f.flags&32){C=f.stateNode;try{$y(C)}catch(rt){On(f,f.return,rt)}}x&4&&f.stateNode!=null&&(C=f.memoizedProps,hp(f,C,y!==null?y.memoizedProps:C)),x&1024&&(cg=!0)}else ga&&f.alternate!==null&&(f.alternate.stateNode=f.stateNode);break;case 6:if(Mi(u,f),Ui(f),x&4&&Fi){if(f.stateNode===null)throw Error(s(162));x=f.memoizedProps,y=y!==null?y.memoizedProps:x,C=f.stateNode;try{xx(C,y,x)}catch(rt){On(f,f.return,rt)}}break;case 3:if(Yr?(wA(),C=Qr,Qr=Gp(u.containerInfo),Mi(u,f),Qr=C):Mi(u,f),Ui(f),x&4){if(Fi&&Li&&y!==null&&y.memoizedState.isDehydrated)try{iA(u.containerInfo)}catch(rt){On(f,f.return,rt)}if(ga){x=u.containerInfo,y=u.pendingChildren;try{Ky(x,y)}catch(rt){On(f,f.return,rt)}}}cg&&(cg=!1,iy(f));break;case 4:Yr?(y=Qr,Qr=Gp(f.stateNode.containerInfo),Mi(u,f),Ui(f),Qr=y):(Mi(u,f),Ui(f)),x&4&&ga&&Yw(f.stateNode,f,f.stateNode.pendingChildren);break;case 12:Mi(u,f),Ui(f);break;case 31:Mi(u,f),Ui(f),x&4&&(x=f.updateQueue,x!==null&&(f.updateQueue=null,Mu(f,x)));break;case 13:Mi(u,f),Ui(f),f.child.flags&8192&&f.memoizedState!==null!==(y!==null&&y.memoizedState!==null)&&(od=Xi()),x&4&&(x=f.updateQueue,x!==null&&(f.updateQueue=null,Mu(f,x)));break;case 22:C=f.memoizedState!==null;var X=y!==null&&y.memoizedState!==null,pe=io,Ie=Xs;if(io=pe||C,Xs=Ie||X,Mi(u,f),Xs=Ie,io=pe,Ui(f),x&8192&&(u=f.stateNode,u._visibility=C?u._visibility&-2:u._visibility|1,C&&(y===null||X||io||Xs||bl(f)),Fi)){e:if(y=null,Fi)for(u=f;;){if(u.tag===5||Yr&&u.tag===26){if(y===null){X=y=u;try{D=X.stateNode,C?Ix(D):Dx(X.stateNode,X.memoizedProps)}catch(rt){On(X,X.return,rt)}}}else if(u.tag===6){if(y===null){X=u;try{var et=X.stateNode;C?Rx(et):qx(et,X.memoizedProps)}catch(rt){On(X,X.return,rt)}}}else if(u.tag===18){if(y===null){X=u;try{var gt=X.stateNode;C?hA(gt):uA(X.stateNode)}catch(rt){On(X,X.return,rt)}}}else if((u.tag!==22&&u.tag!==23||u.memoizedState===null||u===f)&&u.child!==null){u.child.return=u,u=u.child;continue}if(u===f)break e;for(;u.sibling===null;){if(u.return===null||u.return===f)break e;y===u&&(y=null),u=u.return}y===u&&(y=null),u.sibling.return=u.return,u=u.sibling}}x&4&&(x=f.updateQueue,x!==null&&(y=x.retryQueue,y!==null&&(x.retryQueue=null,Mu(f,y))));break;case 19:Mi(u,f),Ui(f),x&4&&(x=f.updateQueue,x!==null&&(f.updateQueue=null,Mu(f,x)));break;case 30:break;case 21:break;default:Mi(u,f),Ui(f)}}function Ui(f){var u=f.flags;if(u&2){try{for(var y,x=f.return;x!==null;){if(Kw(x)){y=x;break}x=x.return}if(Fi){if(y==null)throw Error(s(160));switch(y.tag){case 27:if(ei){var C=y.stateNode,D=dp(f);qu(f,D,C);break}case 5:var X=y.stateNode;y.flags&32&&($y(X),y.flags&=-33);var pe=dp(f);qu(f,pe,X);break;case 3:case 4:var Ie=y.stateNode.containerInfo,et=dp(f);mp(f,et,Ie);break;default:throw Error(s(161))}}}catch(gt){On(f,f.return,gt)}f.flags&=-3}u&4096&&(f.flags&=-4097)}function iy(f){if(f.subtreeFlags&1024)for(f=f.child;f!==null;){var u=f;iy(u),u.tag===5&&u.flags&1024&&ux(u.stateNode),f=f.sibling}}function Ya(f,u){if(u.subtreeFlags&8772)for(u=u.child;u!==null;)Zw(f,u.alternate,u),u=u.sibling}function bl(f){for(f=f.child;f!==null;){var u=f;switch(u.tag){case 0:case 11:case 14:case 15:Do(4,u,u.return),bl(u);break;case 1:pa(u,u.return);var y=u.stateNode;typeof y.componentWillUnmount==="function"&&$w(u,u.return,y),bl(u);break;case 27:ei&&l5(u.stateNode);case 26:case 5:pa(u,u.return),bl(u);break;case 22:u.memoizedState===null&&bl(u);break;case 30:bl(u);break;default:bl(u)}f=f.sibling}}function Ja(f,u,y){y=y&&(u.subtreeFlags&8772)!==0;for(u=u.child;u!==null;){var x=u.alternate,C=f,D=u,X=D.flags;switch(D.tag){case 0:case 11:case 15:Ja(C,D,y),_f(4,D);break;case 1:if(Ja(C,D,y),x=D,C=x.stateNode,typeof C.componentDidMount==="function")try{C.componentDidMount()}catch(et){On(x,x.return,et)}if(x=D,C=x.updateQueue,C!==null){var pe=x.stateNode;try{var Ie=C.shared.hiddenCallbacks;if(Ie!==null)for(C.shared.hiddenCallbacks=null,C=0;C<Ie.length;C++)Vr(Ie[C],pe)}catch(et){On(x,x.return,et)}}y&&X&64&&Vw(D),If(D,D.return);break;case 27:ei&&Jw(D);case 26:case 5:Ja(C,D,y),y&&x===null&&X&4&&Xw(D),If(D,D.return);break;case 12:Ja(C,D,y);break;case 31:Ja(C,D,y),y&&X&4&&ty(C,D);break;case 13:Ja(C,D,y),y&&X&4&&ny(C,D);break;case 22:D.memoizedState===null&&Ja(C,D,y),If(D,D.return);break;case 30:break;default:Ja(C,D,y)}u=u.sibling}}function gp(f,u){var y=null;f!==null&&f.memoizedState!==null&&f.memoizedState.cachePool!==null&&(y=f.memoizedState.cachePool.pool),f=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(f=u.memoizedState.cachePool.pool),f!==y&&(f!=null&&f.refCount++,y!=null&&it(y))}function bp(f,u){f=null,u.alternate!==null&&(f=u.alternate.memoizedState.cache),u=u.memoizedState.cache,u!==f&&(u.refCount++,f!=null&&it(f))}function Wr(f,u,y,x){if(u.subtreeFlags&10256)for(u=u.child;u!==null;)ry(f,u,y,x),u=u.sibling}function ry(f,u,y,x){var C=u.flags;switch(u.tag){case 0:case 11:case 15:Wr(f,u,y,x),C&2048&&_f(9,u);break;case 1:Wr(f,u,y,x);break;case 3:Wr(f,u,y,x),C&2048&&(f=null,u.alternate!==null&&(f=u.alternate.memoizedState.cache),u=u.memoizedState.cache,u!==f&&(u.refCount++,f!=null&&it(f)));break;case 12:if(C&2048){Wr(f,u,y,x),f=u.stateNode;try{var D=u.memoizedProps,X=D.id,pe=D.onPostCommit;typeof pe==="function"&&pe(X,u.alternate===null?"mount":"update",f.passiveEffectDuration,-0)}catch(Ie){On(u,u.return,Ie)}}else Wr(f,u,y,x);break;case 31:Wr(f,u,y,x);break;case 13:Wr(f,u,y,x);break;case 23:break;case 22:D=u.stateNode,X=u.alternate,u.memoizedState!==null?D._visibility&2?Wr(f,u,y,x):Rf(f,u):D._visibility&2?Wr(f,u,y,x):(D._visibility|=2,lc(f,u,y,x,(u.subtreeFlags&10256)!==0||!1)),C&2048&&gp(X,u);break;case 24:Wr(f,u,y,x),C&2048&&bp(u.alternate,u);break;default:Wr(f,u,y,x)}}function lc(f,u,y,x,C){C=C&&((u.subtreeFlags&10256)!==0||!1);for(u=u.child;u!==null;){var D=f,X=u,pe=y,Ie=x,et=X.flags;switch(X.tag){case 0:case 11:case 15:lc(D,X,pe,Ie,C),_f(8,X);break;case 23:break;case 22:var gt=X.stateNode;X.memoizedState!==null?gt._visibility&2?lc(D,X,pe,Ie,C):Rf(D,X):(gt._visibility|=2,lc(D,X,pe,Ie,C)),C&&et&2048&&gp(X.alternate,X);break;case 24:lc(D,X,pe,Ie,C),C&&et&2048&&bp(X.alternate,X);break;default:lc(D,X,pe,Ie,C)}u=u.sibling}}function Rf(f,u){if(u.subtreeFlags&10256)for(u=u.child;u!==null;){var y=f,x=u,C=x.flags;switch(x.tag){case 22:Rf(y,x),C&2048&&gp(x.alternate,x);break;case 24:Rf(y,x),C&2048&&bp(x.alternate,x);break;default:Rf(y,x)}u=u.sibling}}function wl(f,u,y){if(f.subtreeFlags&_c)for(f=f.child;f!==null;)ay(f,u,y),f=f.sibling}function ay(f,u,y){switch(f.tag){case 26:if(wl(f,u,y),f.flags&_c)if(f.memoizedState!==null)vA(y,Qr,f.memoizedState,f.memoizedProps);else{var x=f.stateNode,C=f.type;f=f.memoizedProps,((u&335544128)===u||Bp(C,f))&&Vy(y,x,C,f)}break;case 5:wl(f,u,y),f.flags&_c&&(x=f.stateNode,C=f.type,f=f.memoizedProps,((u&335544128)===u||Bp(C,f))&&Vy(y,x,C,f));break;case 3:case 4:Yr?(x=Qr,Qr=Gp(f.stateNode.containerInfo),wl(f,u,y),Qr=x):wl(f,u,y);break;case 22:f.memoizedState===null&&(x=f.alternate,x!==null&&x.memoizedState!==null?(x=_c,_c=16777216,wl(f,u,y),_c=x):wl(f,u,y));break;default:wl(f,u,y)}}function oy(f){var u=f.alternate;if(u!==null&&(f=u.child,f!==null)){u.child=null;do u=f.sibling,f.sibling=null,f=u;while(f!==null)}}function Df(f){var u=f.deletions;if((f.flags&16)!==0){if(u!==null)for(var y=0;y<u.length;y++){var x=u[y];hi=x,cy(x,f)}oy(f)}if(f.subtreeFlags&10256)for(f=f.child;f!==null;)ly(f),f=f.sibling}function ly(f){switch(f.tag){case 0:case 11:case 15:Df(f),f.flags&2048&&Do(9,f,f.return);break;case 3:Df(f);break;case 12:Df(f);break;case 22:var u=f.stateNode;f.memoizedState!==null&&u._visibility&2&&(f.return===null||f.return.tag!==13)?(u._visibility&=-3,Fu(f)):Df(f);break;default:Df(f)}}function Fu(f){var u=f.deletions;if((f.flags&16)!==0){if(u!==null)for(var y=0;y<u.length;y++){var x=u[y];hi=x,cy(x,f)}oy(f)}for(f=f.child;f!==null;){switch(u=f,u.tag){case 0:case 11:case 15:Do(8,u,u.return),Fu(u);break;case 22:y=u.stateNode,y._visibility&2&&(y._visibility&=-3,Fu(u));break;default:Fu(u)}f=f.sibling}}function cy(f,u){for(;hi!==null;){var y=hi;switch(y.tag){case 0:case 11:case 15:Do(8,y,u);break;case 23:case 22:if(y.memoizedState!==null&&y.memoizedState.cachePool!==null){var x=y.memoizedState.cachePool.pool;x!=null&&x.refCount++}break;case 24:it(y.memoizedState.cache)}if(x=y.child,x!==null)x.return=y,hi=x;else e:for(y=f;hi!==null;){x=hi;var C=x.sibling,D=x.return;if(ey(x),x===y){hi=null;break e}if(C!==null){C.return=D,hi=C;break e}hi=D}}}function wp(f){var u=sx(f);if(u!=null){if(typeof u.memoizedProps["data-testname"]!=="string")throw Error(s(364));return u}if(f=px(f),f===null)throw Error(s(362));return f.stateNode.current}function yp(f,u){var y=f.tag;switch(u.$$typeof){case nd:if(f.type===u.value)return!0;break;case sd:e:{u=u.value,f=[f,0];for(y=0;y<f.length;){var x=f[y++],C=x.tag,D=f[y++],X=u[D];if(C!==5&&C!==26&&C!==27||!Of(x)){for(;X!=null&&yp(x,X);)D++,X=u[D];if(D===u.length){u=!0;break e}else for(x=x.child;x!==null;)f.push(x,D),x=x.sibling}}u=!1}return u;case id:if((y===5||y===26||y===27)&&wx(f.stateNode,u.value))return!0;break;case ad:if(y===5||y===6||y===26||y===27){if(f=bx(f),f!==null&&0<=f.indexOf(u.value))return!0}break;case rd:if(y===5||y===26||y===27){if(f=f.memoizedProps["data-testname"],typeof f==="string"&&f.toLowerCase()===u.value.toLowerCase())return!0}break;default:throw Error(s(365))}return!1}function vp(f){switch(f.$$typeof){case nd:return"<"+(d(f.value)||"Unknown")+">";case sd:return":has("+(vp(f)||"")+")";case id:return'[role="'+f.value+'"]';case ad:return'"'+f.value+'"';case rd:return'[data-testname="'+f.value+'"]';default:throw Error(s(365))}}function fy(f,u){var y=[];f=[f,0];for(var x=0;x<f.length;){var C=f[x++],D=C.tag,X=f[x++],pe=u[X];if(D!==5&&D!==26&&D!==27||!Of(C)){for(;pe!=null&&yp(C,pe);)X++,pe=u[X];if(X===u.length)y.push(C);else for(C=C.child;C!==null;)f.push(C,X),C=C.sibling}}return y}function kp(f,u){if(!Lf)throw Error(s(363));f=wp(f),f=fy(f,u),u=[],f=Array.from(f);for(var y=0;y<f.length;){var x=f[y++],C=x.tag;if(C===5||C===26||C===27)Of(x)||u.push(x.stateNode);else for(x=x.child;x!==null;)f.push(x),x=x.sibling}return u}function lr(){return(vn&2)!==0&&xn!==0?xn&-xn:Nt.T!==null?To():rx()}function hy(){if(gr===0)if((xn&536870912)===0||Cn){var f=zu;zu<<=1,(zu&3932160)===0&&(zu=262144),gr=f}else gr=536870912;return f=mr.current,f!==null&&(f.flags|=32),gr}function $i(f,u,y){if(f===as&&($n===2||$n===9)||f.cancelPendingCommit!==null)cc(f,0),qo(f,xn,gr,!1);if(q(f,y),(vn&2)===0||f!==as)f===as&&((vn&2)===0&&(_l|=y),Ms===4&&qo(f,xn,gr,!1)),Lt(f)}function uy(f,u,y){if((vn&6)!==0)throw Error(s(327));var x=!y&&(u&127)===0&&(u&f.expiredLanes)===0||T(f,u),C=x?Lk(f,u):Tp(f,u,!0),D=x;do{if(C===0){Ic&&!x&&qo(f,u,0,!1);break}else{if(y=f.current.alternate,D&&!Mk(y)){C=Tp(f,u,!1),D=!1;continue}if(C===2){if(D=u,f.errorRecoveryDisabledLanes&D)var X=0;else X=f.pendingLanes&-536870913,X=X!==0?X:X&536870912?536870912:0;if(X!==0){u=X;e:{var pe=f;C=Wf;var Ie=Li&&pe.current.memoizedState.isDehydrated;if(Ie&&(cc(pe,X).flags|=256),X=Tp(pe,X,!1),X!==2){if(fg&&!Ie){pe.errorRecoveryDisabledLanes|=D,_l|=D,C=4;break e}D=Ki,Ki=C,D!==null&&(Ki===null?Ki=D:Ki.push.apply(Ki,D))}C=X}if(D=!1,C!==2)continue}}if(C===1){cc(f,0),qo(f,u,0,!0);break}e:{switch(x=f,D=C,D){case 0:case 1:throw Error(s(345));case 4:if((u&4194048)!==u)break;case 6:qo(x,u,gr,!zo);break e;case 2:Ki=null;break;case 3:case 5:break;default:throw Error(s(329))}if((u&62914560)===u&&(C=od+300-Xi(),10<C)){if(qo(x,u,gr,!zo),A(x,0,!0)!==0)break e;oo=u,x.timeoutHandle=tx(dy.bind(null,x,y,Ki,ld,ug,u,gr,_l,Rc,zo,D,"Throttled",-0,0),C);break e}dy(x,y,Ki,ld,ug,u,gr,_l,Rc,zo,D,null,-0,0)}}break}while(1);Lt(f)}function dy(f,u,y,x,C,D,X,pe,Ie,et,gt,rt,Tt,ln){if(f.timeoutHandle=vl,rt=u.subtreeFlags,rt&8192||(rt&16785408)===16785408){rt=fx(),ay(u,D,rt);var Ti=(D&62914560)===D?od-Xi():(D&4194048)===D?y5-Xi():0;if(Ti=hx(rt,Ti),Ti!==null){oo=D,f.cancelPendingCommit=Ti(ky.bind(null,f,u,D,y,x,C,X,pe,Ie,gt,rt,null,Tt,ln)),qo(f,D,X,!et);return}}ky(f,u,D,y,x,C,X,pe,Ie)}function Mk(f){for(var u=f;;){var y=u.tag;if((y===0||y===11||y===15)&&u.flags&16384&&(y=u.updateQueue,y!==null&&(y=y.stores,y!==null)))for(var x=0;x<y.length;x++){var C=y[x],D=C.getSnapshot;C=C.value;try{if(!dr(D(),C))return!1}catch(X){return!1}}if(y=u.child,u.subtreeFlags&16384&&y!==null)y.return=u,u=y;else{if(u===f)break;for(;u.sibling===null;){if(u.return===null||u.return===f)return!0;u=u.return}u.sibling.return=u.return,u=u.sibling}}return!0}function qo(f,u,y,x){u&=~hg,u&=~_l,f.suspendedLanes|=u,f.pingedLanes&=~u,x&&(f.warmLanes|=u),x=f.expirationTimes;for(var C=u;0<C;){var D=31-fr(C),X=1<<D;x[D]=-1,C&=~X}y!==0&&N(f,y,u)}function my(){return(vn&6)===0?(Ln(0,!1),!1):!0}function xp(){if(Sn!==null){if($n===0)var f=Sn.return;else f=Sn,no=kl=null,Pm(f),xc=null,zf=0,f=Sn;for(;f!==null;)Gw(f.alternate,f),f=f.return;Sn=null}}function cc(f,u){var y=f.timeoutHandle;y!==vl&&(f.timeoutHandle=vl,nx(y)),y=f.cancelPendingCommit,y!==null&&(f.cancelPendingCommit=null,y()),oo=0,xp(),as=f,Sn=y=Za(f.current,null),xn=u,$n=0,pr=null,zo=!1,Ic=T(f,u),fg=!1,Rc=gr=hg=_l=Go=Ms=0,Ki=Wf=null,ug=!1,(u&8)!==0&&(u|=u&32);var x=f.entangledLanes;if(x!==0)for(f=f.entanglements,x&=u;0<x;){var C=31-fr(x),D=1<<C;u|=f[C],x&=~D}return ao=u,Gr(),y}function py(f,u){dn=null,Nt.H=Vf,u===kc||u===Qu?(u=_o(),$n=3):u===ng?(u=_o(),$n=4):$n=u===og?8:u!==null&&typeof u==="object"&&typeof u.then==="function"?6:1,pr=u,Sn===null&&(Ms=1,Cu(f,he(u,f.current)))}function gy(){var f=mr.current;return f===null?!0:(xn&4194048)===xn?jr===null?!0:!1:(xn&62914560)===xn||(xn&536870912)!==0?f===jr:!1}function by(){var f=Nt.H;return Nt.H=Vf,f===null?Vf:f}function wy(){var f=Nt.A;return Nt.A=FA,f}function Lu(){Ms=4,zo||(xn&4194048)!==xn&&mr.current!==null||(Ic=!0),(Go&134217727)===0&&(_l&134217727)===0||as===null||qo(as,xn,gr,!1)}function Tp(f,u,y){var x=vn;vn|=2;var C=by(),D=wy();if(as!==f||xn!==u)ld=null,cc(f,u);u=!1;var X=Ms;e:do try{if($n!==0&&Sn!==null){var pe=Sn,Ie=pr;switch($n){case 8:xp(),X=6;break e;case 3:case 2:case 9:case 6:mr.current===null&&(u=!0);var et=$n;if($n=0,pr=null,fc(f,pe,Ie,et),y&&Ic){X=0;break e}break;default:et=$n,$n=0,pr=null,fc(f,pe,Ie,et)}}Fk(),X=Ms;break}catch(gt){py(f,gt)}while(1);return u&&f.shellSuspendCounter++,no=kl=null,vn=x,Nt.H=C,Nt.A=D,Sn===null&&(as=null,xn=0,Gr()),X}function Fk(){for(;Sn!==null;)yy(Sn)}function Lk(f,u){var y=vn;vn|=2;var x=by(),C=wy();as!==f||xn!==u?(ld=null,Kf=Xi()+500,cc(f,u)):Ic=T(f,u);e:do try{if($n!==0&&Sn!==null){u=Sn;var D=pr;t:switch($n){case 1:$n=0,pr=null,fc(f,u,D,1);break;case 2:case 9:if(ma(D)){$n=0,pr=null,vy(u);break}u=function(){$n!==2&&$n!==9||as!==f||($n=7),Lt(f)},D.then(u,u);break e;case 3:$n=7;break e;case 4:$n=5;break e;case 7:ma(D)?($n=0,pr=null,vy(u)):($n=0,pr=null,fc(f,u,D,7));break;case 5:var X=null;switch(Sn.tag){case 26:X=Sn.memoizedState;case 5:case 27:var pe=Sn,{type:Ie,pendingProps:et}=pe;if(X?a5(X):Gy(pe.stateNode,Ie,et)){$n=0,pr=null;var gt=pe.sibling;if(gt!==null)Sn=gt;else{var rt=pe.return;rt!==null?(Sn=rt,Ou(rt)):Sn=null}break t}}$n=0,pr=null,fc(f,u,D,5);break;case 6:$n=0,pr=null,fc(f,u,D,6);break;case 8:xp(),Ms=6;break e;default:throw Error(s(462))}}Ok();break}catch(Tt){py(f,Tt)}while(1);if(no=kl=null,Nt.H=x,Nt.A=C,vn=y,Sn!==null)return 0;return as=null,xn=0,Gr(),Ms}function Ok(){for(;Sn!==null&&!AA();)yy(Sn)}function yy(f){var u=Nw(f.alternate,f,ao);f.memoizedProps=f.pendingProps,u===null?Ou(f):Sn=u}function vy(f){var u=f,y=u.alternate;switch(u.tag){case 15:case 0:u=qw(y,u,u.pendingProps,u.type,void 0,xn);break;case 11:u=qw(y,u,u.pendingProps,u.type.render,u.ref,xn);break;case 5:Pm(u);default:Gw(y,u),u=Sn=Iy(u,ao),u=Nw(y,u,ao)}f.memoizedProps=f.pendingProps,u===null?Ou(f):Sn=u}function fc(f,u,y,x){no=kl=null,Pm(u),xc=null,zf=0;var C=u.return;try{if(Ck(f,C,u,y,xn)){Ms=1,Cu(f,he(y,f.current)),Sn=null;return}}catch(D){if(C!==null)throw Sn=C,D;Ms=1,Cu(f,he(y,f.current)),Sn=null;return}if(u.flags&32768){if(Cn||x===1)f=!0;else if(Ic||(xn&536870912)!==0)f=!1;else if(zo=f=!0,x===2||x===9||x===3||x===6)x=mr.current,x!==null&&x.tag===13&&(x.flags|=16384);Sy(u,f)}else Ou(u)}function Ou(f){var u=f;do{if((u.flags&32768)!==0){Sy(u,zo);return}f=u.return;var y=Ik(u.alternate,u,ao);if(y!==null){Sn=y;return}if(u=u.sibling,u!==null){Sn=u;return}Sn=u=f}while(u!==null);Ms===0&&(Ms=5)}function Sy(f,u){do{var y=Rk(f.alternate,f);if(y!==null){y.flags&=32767,Sn=y;return}if(y=f.return,y!==null&&(y.flags|=32768,y.subtreeFlags=0,y.deletions=null),!u&&(f=f.sibling,f!==null)){Sn=f;return}Sn=f=y}while(f!==null);Ms=6,Sn=null}function ky(f,u,y,x,C,D,X,pe,Ie){f.cancelPendingCommit=null;do qf();while(ti!==0);if((vn&6)!==0)throw Error(s(327));if(u!==null){if(u===f.current)throw Error(s(177));if(D=u.lanes|u.childLanes,D|=sg,P(f,y,D,X,pe,Ie),f===as&&(Sn=as=null,xn=0),qc=u,$o=f,oo=y,dg=D,mg=C,v5=x,(u.subtreeFlags&10256)!==0||(u.flags&10256)!==0?(f.callbackNode=null,f.callbackPriority=0,Hk(Xp,function(){return Cy(),null})):(f.callbackNode=null,f.callbackPriority=0),x=(u.flags&13878)!==0,(u.subtreeFlags&13878)!==0||x){x=Nt.T,Nt.T=null,C=to(),oi(2),X=vn,vn|=4;try{Dk(f,u,y)}finally{vn=X,oi(C),Nt.T=x}}ti=1,xy(),Ay(),Ty()}}function xy(){if(ti===1){ti=0;var f=$o,u=qc,y=(u.flags&13878)!==0;if((u.subtreeFlags&13878)!==0||y){y=Nt.T,Nt.T=null;var x=to();oi(2);var C=vn;vn|=4;try{sy(u,f),Zk(f.containerInfo)}finally{vn=C,oi(x),Nt.T=y}}f.current=u,ti=2}}function Ay(){if(ti===2){ti=0;var f=$o,u=qc,y=(u.flags&8772)!==0;if((u.subtreeFlags&8772)!==0||y){y=Nt.T,Nt.T=null;var x=to();oi(2);var C=vn;vn|=4;try{Zw(f,u.alternate,u)}finally{vn=C,oi(x),Nt.T=y}}ti=3}}function Ty(){if(ti===4||ti===3){ti=0,TA();var f=$o,u=qc,y=oo,x=v5;(u.subtreeFlags&10256)!==0||(u.flags&10256)!==0?ti=5:(ti=0,qc=$o=null,Ey(f,f.pendingLanes));var C=f.pendingLanes;if(C===0&&(Vo=null),W(y),u=u.stateNode,hr&&typeof hr.onCommitFiberRoot==="function")try{hr.onCommitFiberRoot(Pf,u,void 0,(u.current.flags&128)===128)}catch(Ie){}if(x!==null){u=Nt.T,C=to(),oi(2),Nt.T=null;try{for(var D=f.onRecoverableError,X=0;X<x.length;X++){var pe=x[X];D(pe.value,{componentStack:pe.stack})}}finally{Nt.T=u,oi(C)}}(oo&3)!==0&&qf(),Lt(f),C=f.pendingLanes,(y&261930)!==0&&(C&42)!==0?f===pg?Yf++:(Yf=0,pg=f):Yf=0,Li&&lA(),Ln(0,!1)}}function Ey(f,u){(f.pooledCacheLanes&=u)===0&&(u=f.pooledCache,u!=null&&(f.pooledCache=null,it(u)))}function qf(){return xy(),Ay(),Ty(),Cy()}function Cy(){if(ti!==5)return!1;var f=$o,u=dg;dg=0;var y=W(oo),x=32>y?32:y;y=Nt.T;var C=to();try{oi(x),Nt.T=null,x=mg,mg=null;var D=$o,X=oo;if(ti=0,qc=$o=null,oo=0,(vn&6)!==0)throw Error(s(331));var pe=vn;if(vn|=4,ly(D.current),ry(D,D.current,X,x),vn=pe,Ln(0,!1),hr&&typeof hr.onPostCommitFiberRoot==="function")try{hr.onPostCommitFiberRoot(Pf,D)}catch(Ie){}return!0}finally{oi(C),Nt.T=y,Ey(f,u)}}function jy(f,u,y){u=he(y,u),u=Jm(f.stateNode,u,2),f=Vn(f,u,2),f!==null&&(q(f,2),Lt(f))}function On(f,u,y){if(f.tag===3)jy(f,f,y);else for(;u!==null;){if(u.tag===3){jy(u,f,y);break}else if(u.tag===1){var x=u.stateNode;if(typeof u.type.getDerivedStateFromError==="function"||typeof x.componentDidCatch==="function"&&(Vo===null||!Vo.has(x))){f=he(y,f),y=Tw(2),x=Vn(u,y,2),x!==null&&(Ew(y,x,u,f),q(x,2),Lt(x));break}}u=u.return}}function Cp(f,u,y){var x=f.pingCache;if(x===null){x=f.pingCache=new LA;var C=new Set;x.set(u,C)}else C=x.get(u),C===void 0&&(C=new Set,x.set(u,C));C.has(y)||(fg=!0,C.add(y),f=Pk.bind(null,f,u,y),u.then(f,f))}function Pk(f,u,y){var x=f.pingCache;x!==null&&x.delete(u),f.pingedLanes|=f.suspendedLanes&y,f.warmLanes&=~y,as===f&&(xn&y)===y&&(Ms===4||Ms===3&&(xn&62914560)===xn&&300>Xi()-od?(vn&2)===0&&cc(f,0):hg|=y,Rc===xn&&(Rc=0)),Lt(f)}function _y(f,u){u===0&&(u=I()),f=At(f,u),f!==null&&(q(f,u),Lt(f))}function Nk(f){var u=f.memoizedState,y=0;u!==null&&(y=u.retryLane),_y(f,y)}function Bk(f,u){var y=0;switch(f.tag){case 31:case 13:var{stateNode:x,memoizedState:C}=f;C!==null&&(y=C.retryLane);break;case 19:x=f.stateNode;break;case 22:x=f.stateNode._retryCache;break;default:throw Error(s(314))}x!==null&&x.delete(u),_y(f,y)}function Hk(f,u){return Vu(f,u)}function Uk(f,u,y,x){this.tag=f,this.key=y,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=x,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function jp(f){return f=f.prototype,!(!f||!f.isReactComponent)}function Za(f,u){var y=f.alternate;return y===null?(y=t(f.tag,u,f.key,f.mode),y.elementType=f.elementType,y.type=f.type,y.stateNode=f.stateNode,y.alternate=f,f.alternate=y):(y.pendingProps=u,y.type=f.type,y.flags=0,y.subtreeFlags=0,y.deletions=null),y.flags=f.flags&65011712,y.childLanes=f.childLanes,y.lanes=f.lanes,y.child=f.child,y.memoizedProps=f.memoizedProps,y.memoizedState=f.memoizedState,y.updateQueue=f.updateQueue,u=f.dependencies,y.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},y.sibling=f.sibling,y.index=f.index,y.ref=f.ref,y.refCleanup=f.refCleanup,y}function Iy(f,u){f.flags&=65011714;var y=f.alternate;return y===null?(f.childLanes=0,f.lanes=u,f.child=null,f.subtreeFlags=0,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=y.childLanes,f.lanes=y.lanes,f.child=y.child,f.subtreeFlags=0,f.deletions=null,f.memoizedProps=y.memoizedProps,f.memoizedState=y.memoizedState,f.updateQueue=y.updateQueue,f.type=y.type,u=y.dependencies,f.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext}),f}function Pu(f,u,y,x,C,D){var X=0;if(x=f,typeof f==="function")jp(f)&&(X=1);else if(typeof f==="string")X=Yr&&ei?e5(f,y,vi.current)?26:c5(f)?27:5:Yr?e5(f,y,vi.current)?26:5:ei?c5(f)?27:5:5;else e:switch(f){case Pp:return f=t(31,y,u,C),f.elementType=Pp,f.lanes=D,f;case uc:return yl(y.children,C,D,u);case Py:X=8,C|=24;break;case qp:return f=t(12,y,u,C|2),f.elementType=qp,f.lanes=D,f;case Fp:return f=t(13,y,u,C),f.elementType=Fp,f.lanes=D,f;case Lp:return f=t(19,y,u,C),f.elementType=Lp,f.lanes=D,f;default:if(typeof f==="object"&&f!==null)switch(f.$$typeof){case Mo:X=10;break e;case Ny:X=9;break e;case Mp:X=11;break e;case Op:X=14;break e;case Fo:X=16,x=null;break e}X=29,y=Error(s(130,f===null?"null":typeof f,"")),x=null}return u=t(X,y,u,C),u.elementType=f,u.type=x,u.lanes=D,u}function yl(f,u,y,x){return f=t(7,f,x,u),f.lanes=y,f}function _p(f,u,y){return f=t(6,f,null,u),f.lanes=y,f}function Ry(f){var u=t(18,null,null,0);return u.stateNode=f,u}function Ip(f,u,y){return u=t(4,f.children!==null?f.children:[],f.key,u),u.lanes=y,u.stateNode={containerInfo:f.containerInfo,pendingChildren:null,implementation:f.implementation},u}function zk(f,u,y,x,C,D,X,pe,Ie){this.tag=1,this.containerInfo=f,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=vl,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=_(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=_(0),this.hiddenUpdates=_(null),this.identifierPrefix=x,this.onUncaughtError=C,this.onCaughtError=D,this.onRecoverableError=X,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=Ie,this.incompleteTransitions=new Map}function Dy(f,u,y,x,C,D,X,pe,Ie,et,gt,rt){return f=new zk(f,u,y,X,Ie,et,gt,rt,pe),u=1,D===!0&&(u|=24),D=t(3,null,null,u),f.current=D,D.stateNode=f,u=St(),u.refCount++,f.pooledCache=u,u.refCount++,D.memoizedState={element:x,isDehydrated:y,cache:u},gn(D),f}function qy(f){if(!f)return gc;return f=gc,f}function My(f){var u=f._reactInternals;if(u===void 0){if(typeof f.render==="function")throw Error(s(188));throw f=Object.keys(f).join(","),Error(s(268,f))}return f=o(u),f=f!==null?l(f):null,f===null?null:Mf(f.stateNode)}function Fy(f,u,y,x,C,D){C=qy(C),x.context===null?x.context=C:x.pendingContext=C,x=Hn(u),x.payload={element:y},D=D===void 0?null:D,D!==null&&(x.callback=D),y=Vn(f,x,u),y!==null&&($i(y,f,u),Qn(y,f,u))}function Ly(f,u){if(f=f.memoizedState,f!==null&&f.dehydrated!==null){var y=f.retryLane;f.retryLane=y!==0&&y<u?y:u}}function Rp(f,u){Ly(f,u),(f=f.alternate)&&Ly(f,u)}var yn={},Dp=Object.assign,Vk=Symbol.for("react.element"),Nu=Symbol.for("react.transitional.element"),hc=Symbol.for("react.portal"),uc=Symbol.for("react.fragment"),Py=Symbol.for("react.strict_mode"),qp=Symbol.for("react.profiler"),Ny=Symbol.for("react.consumer"),Mo=Symbol.for("react.context"),Mp=Symbol.for("react.forward_ref"),Fp=Symbol.for("react.suspense"),Lp=Symbol.for("react.suspense_list"),Op=Symbol.for("react.memo"),Fo=Symbol.for("react.lazy"),Pp=Symbol.for("react.activity"),$k=Symbol.for("react.memo_cache_sentinel"),By=Symbol.iterator,Xk=Symbol.for("react.client.reference"),Bu=Array.isArray,Nt=Qa,{rendererVersion:Wk,rendererPackageName:Kk,extraDevToolsConfig:Hy,getPublicInstance:Mf,getRootHostContext:Yk,getChildHostContext:Qk,prepareForCommit:Jk,resetAfterCommit:Zk,createInstance:ex}=e;e.cloneMutableInstance;var{appendInitialChild:Np,finalizeInitialChildren:Uy,shouldSetTextContent:Hu,createTextInstance:zy}=e;e.cloneMutableTextInstance;var{scheduleTimeout:tx,cancelTimeout:nx,noTimeout:vl,isPrimaryRenderer:eo}=e;e.warnsIfNotActing;var{supportsMutation:Fi,supportsPersistence:ga,supportsHydration:Li,getInstanceFromNode:sx}=e;e.beforeActiveInstanceBlur;var ix=e.preparePortalMount;e.prepareScopeUpdate,e.getInstanceFromScope;var{setCurrentUpdatePriority:oi,getCurrentUpdatePriority:to,resolveUpdatePriority:rx}=e;e.trackSchedulerEvent,e.resolveEventType,e.resolveEventTimeStamp;var{shouldAttemptEagerTransition:ax,detachDeletedInstance:ox}=e;e.requestPostPaintCallback;var{maySuspendCommit:lx,maySuspendCommitOnUpdate:cx,maySuspendCommitInSyncRender:Bp,preloadInstance:Gy,startSuspendingCommit:fx,suspendInstance:Vy}=e;e.suspendOnActiveViewTransition;var hx=e.waitForCommitToBeReady;e.getSuspendedCommitReason;var{NotPendingTransition:dc,HostTransitionContext:Sl,resetFormInstance:ux}=e;e.bindToConsole;var{supportsMicrotasks:dx,scheduleMicrotask:mx,supportsTestSelectors:Lf,findFiberRoot:px,getBoundingRect:gx,getTextContent:bx,isHiddenSubtree:Of,matchAccessibilityRole:wx,setFocusIfFocusable:yx,setupIntersectionObserver:vx,appendChild:Sx,appendChildToContainer:kx,commitTextUpdate:xx,commitMount:Ax,commitUpdate:Tx,insertBefore:Ex,insertInContainerBefore:Cx,removeChild:jx,removeChildFromContainer:_x,resetTextContent:$y,hideInstance:Ix,hideTextInstance:Rx,unhideInstance:Dx,unhideTextInstance:qx}=e;e.cancelViewTransitionName,e.cancelRootViewTransitionName,e.restoreRootViewTransitionName,e.cloneRootViewTransitionContainer,e.removeRootViewTransitionClone,e.measureClonedInstance,e.hasInstanceChanged,e.hasInstanceAffectedParent,e.startViewTransition,e.startGestureTransition,e.stopViewTransition,e.getCurrentGestureOffset,e.createViewTransitionInstance;var Mx=e.clearContainer;e.createFragmentInstance,e.updateFragmentInstanceFiber,e.commitNewChildToFragmentInstance,e.deleteChildFromFragmentInstance;var{cloneInstance:Fx,createContainerChildSet:Xy,appendChildToContainerChildSet:Wy,finalizeContainerChildren:Lx,replaceContainerChildren:Ky,cloneHiddenInstance:Yy,cloneHiddenTextInstance:Qy,isSuspenseInstancePending:Up,isSuspenseInstanceFallback:zp,getSuspenseInstanceFallbackErrorDetails:Ox,registerSuspenseInstanceRetry:Px,canHydrateFormStateMarker:Nx,isFormStateMarkerMatching:Bx,getNextHydratableSibling:Jy,getNextHydratableSiblingAfterSingleton:Hx,getFirstHydratableChild:Ux,getFirstHydratableChildWithinContainer:zx,getFirstHydratableChildWithinActivityInstance:Gx,getFirstHydratableChildWithinSuspenseInstance:Vx,getFirstHydratableChildWithinSingleton:$x,canHydrateInstance:Xx,canHydrateTextInstance:Wx,canHydrateActivityInstance:Kx,canHydrateSuspenseInstance:Yx,hydrateInstance:Qx,hydrateTextInstance:Jx,hydrateActivityInstance:Zx,hydrateSuspenseInstance:eA,getNextHydratableInstanceAfterActivityInstance:tA,getNextHydratableInstanceAfterSuspenseInstance:nA,commitHydratedInstance:sA,commitHydratedContainer:iA,commitHydratedActivityInstance:rA,commitHydratedSuspenseInstance:aA,finalizeHydratedChildren:oA,flushHydrationEvents:lA}=e;e.clearActivityBoundary;var cA=e.clearSuspenseBoundary;e.clearActivityBoundaryFromContainer;var{clearSuspenseBoundaryFromContainer:fA,hideDehydratedBoundary:hA,unhideDehydratedBoundary:uA,shouldDeleteUnhydratedTailInstances:Zy}=e;e.diffHydratedPropsForDevWarnings,e.diffHydratedTextForDevWarnings,e.describeHydratableInstanceForDevWarnings;var{validateHydratableInstance:dA,validateHydratableTextInstance:mA,supportsResources:Yr,isHostHoistableType:e5,getHoistableRoot:Gp,getResource:t5,acquireResource:n5,releaseResource:s5,hydrateHoistable:pA,mountHoistable:i5,unmountHoistable:r5,createHoistableInstance:gA,prepareToCommitHoistables:wA,mayResourceSuspendCommit:yA,preloadResource:a5,suspendResource:vA,supportsSingletons:ei,resolveSingletonInstance:o5,acquireSingletonInstance:SA,releaseSingletonInstance:l5,isHostSingletonType:c5,isSingletonScope:mc}=e,Vp=[],pc=-1,gc={},fr=Math.clz32?Math.clz32:v,{log:kA,LN2:xA}=Math,Uu=256,zu=262144,Gu=4194304,Vu=Ii,$p=Dc,AA=Fc,TA=Nc,Xi=Oo,f5=Oc,EA=Pc,Xp=Si,CA=Va,jA=void 0,_A=void 0,Pf=null,hr=null,dr=typeof Object.is==="function"?Object.is:ue,h5=typeof reportError==="function"?reportError:function(f){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var u=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof f==="object"&&f!==null&&typeof f.message==="string"?String(f.message):String(f),error:f});if(!window.dispatchEvent(u))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",f);return}console.error(f)},IA=Object.prototype.hasOwnProperty,Wp,u5,Kp=!1,d5=new WeakMap,bc=[],wc=0,$u=null,Nf=0,Ar=[],Tr=0,Po=null,ba=1,wa="",vi=m(null),Bf=m(null),No=m(null),Xu=m(null),Ai=null,Ts=null,Cn=!1,Bo=null,Er=!1,Qp=Error(s(519)),Wu=m(null),kl=null,no=null,RA=typeof AbortController<"u"?AbortController:function(){var f=[],u=this.signal={aborted:!1,addEventListener:function(y,x){f.push(x)}};this.abort=function(){u.aborted=!0,f.forEach(function(y){return y()})}},DA=Ii,qA=Si,Es={$$typeof:Mo,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},Ku=null,yc=null,Jp=!1,Yu=!1,Zp=!1,xl=0,Uf=null,eg=0,vc=0,Sc=null,m5=Nt.S;Nt.S=function(f,u){y5=Xi(),typeof u==="object"&&u!==null&&typeof u.then==="function"&&pl(f,u),m5!==null&&m5(f,u)};var Al=m(null),kc=Error(s(460)),ng=Error(s(474)),Qu=Error(s(542)),Ju={then:function(){}},El=null,xc=null,zf=0,Cl=Zs(!0),p5=Zs(!1),Cr=[],Ac=0,sg=0,Ho=!1,ig=!1,Tc=m(null),Zu=m(0),mr=m(null),jr=null,zs=m(0),so=0,dn=null,Jn=null,Vs=null,ed=!1,Ec=!1,jl=!1,td=0,Gf=0,Cc=null,MA=0,Vf={readContext:Vt,use:Su,useCallback:qs,useContext:qs,useEffect:qs,useImperativeHandle:qs,useLayoutEffect:qs,useInsertionEffect:qs,useMemo:qs,useReducer:qs,useRef:qs,useState:qs,useDebugValue:qs,useDeferredValue:qs,useTransition:qs,useSyncExternalStore:qs,useId:qs,useHostTransitionStatus:qs,useFormState:qs,useActionState:qs,useOptimistic:qs,useMemoCache:qs,useCacheRefresh:qs};Vf.useEffectEvent=qs;var g5={readContext:Vt,use:Su,useCallback:function(f,u){return Hi().memoizedState=[f,u===void 0?null:u],f},useContext:Vt,useEffect:J2,useImperativeHandle:function(f,u,y){y=y!==null&&y!==void 0?y.concat([f]):null,xu(4194308,4,cw.bind(null,u,f),y)},useLayoutEffect:function(f,u){return xu(4194308,4,f,u)},useInsertionEffect:function(f,u){xu(4,2,f,u)},useMemo:function(f,u){var y=Hi();u=u===void 0?null:u;var x=f();if(jl){ce(!0);try{f()}finally{ce(!1)}}return y.memoizedState=[x,u],x},useReducer:function(f,u,y){var x=Hi();if(y!==void 0){var C=y(u);if(jl){ce(!0);try{y(u)}finally{ce(!1)}}}else C=u;return x.memoizedState=x.baseState=C,f={pending:null,lanes:0,dispatch:null,lastRenderedReducer:f,lastRenderedState:C},x.queue=f,f=f.dispatch=Ek.bind(null,dn,f),[x.memoizedState,f]},useRef:function(f){var u=Hi();return f={current:f},u.memoizedState=f},useState:function(f){f=Um(f);var u=f.queue,y=yw.bind(null,dn,u);return u.dispatch=y,[f.memoizedState,y]},useDebugValue:$m,useDeferredValue:function(f,u){var y=Hi();return Xm(y,f,u)},useTransition:function(){var f=Um(!1);return f=mw.bind(null,dn,f.queue,!0,!1),Hi().memoizedState=f,[!1,f]},useSyncExternalStore:function(f,u,y){var x=dn,C=Hi();if(Cn){if(y===void 0)throw Error(s(407));y=y()}else{if(y=u(),as===null)throw Error(s(349));(xn&127)!==0||L2(x,u,y)}C.memoizedState=y;var D={value:y,getSnapshot:u};return C.queue=D,J2(P2.bind(null,x,D,f),[f]),x.flags|=2048,oc(9,{destroy:void 0},O2.bind(null,x,D,y,u),null),y},useId:function(){var f=Hi(),u=as.identifierPrefix;if(Cn){var y=wa,x=ba;y=(x&~(1<<32-fr(x)-1)).toString(32)+y,u="_"+u+"R_"+y,y=td++,0<y&&(u+="H"+y.toString(32)),u+="_"}else y=MA++,u="_"+u+"r_"+y.toString(32)+"_";return f.memoizedState=u},useHostTransitionStatus:Wm,useFormState:X2,useActionState:X2,useOptimistic:function(f){var u=Hi();u.memoizedState=u.baseState=f;var y={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return u.queue=y,u=Ym.bind(null,dn,!0,y),y.dispatch=u,[f,u]},useMemoCache:Nm,useCacheRefresh:function(){return Hi().memoizedState=Tk.bind(null,dn)},useEffectEvent:function(f){var u=Hi(),y={impl:f};return u.memoizedState=y,function(){if((vn&2)!==0)throw Error(s(440));return y.impl.apply(void 0,arguments)}}},rg={readContext:Vt,use:Su,useCallback:hw,useContext:Vt,useEffect:Vm,useImperativeHandle:fw,useInsertionEffect:ew,useLayoutEffect:lw,useMemo:uw,useReducer:ku,useRef:Q2,useState:function(){return ku(Wa)},useDebugValue:$m,useDeferredValue:function(f,u){var y=Us();return dw(y,Jn.memoizedState,f,u)},useTransition:function(){var f=ku(Wa)[0],u=Us().memoizedState;return[typeof f==="boolean"?f:Tf(f),u]},useSyncExternalStore:F2,useId:gw,useHostTransitionStatus:Wm,useFormState:W2,useActionState:W2,useOptimistic:function(f,u){var y=Us();return H2(y,Jn,f,u)},useMemoCache:Nm,useCacheRefresh:ww};rg.useEffectEvent=Z2;var b5={readContext:Vt,use:Su,useCallback:hw,useContext:Vt,useEffect:Vm,useImperativeHandle:fw,useInsertionEffect:ew,useLayoutEffect:lw,useMemo:uw,useReducer:Hm,useRef:Q2,useState:function(){return Hm(Wa)},useDebugValue:$m,useDeferredValue:function(f,u){var y=Us();return Jn===null?Xm(y,f,u):dw(y,Jn.memoizedState,f,u)},useTransition:function(){var f=Hm(Wa)[0],u=Us().memoizedState;return[typeof f==="boolean"?f:Tf(f),u]},useSyncExternalStore:F2,useId:gw,useHostTransitionStatus:Wm,useFormState:Y2,useActionState:Y2,useOptimistic:function(f,u){var y=Us();if(Jn!==null)return H2(y,Jn,f,u);return y.baseState=f,[f,y.queue.dispatch]},useMemoCache:Nm,useCacheRefresh:ww};b5.useEffectEvent=Z2;var ag={enqueueSetState:function(f,u,y){f=f._reactInternals;var x=lr(),C=Hn(x);C.payload=u,y!==void 0&&y!==null&&(C.callback=y),u=Vn(f,C,x),u!==null&&($i(u,f,x),Qn(u,f,x))},enqueueReplaceState:function(f,u,y){f=f._reactInternals;var x=lr(),C=Hn(x);C.tag=1,C.payload=u,y!==void 0&&y!==null&&(C.callback=y),u=Vn(f,C,x),u!==null&&($i(u,f,x),Qn(u,f,x))},enqueueForceUpdate:function(f,u){f=f._reactInternals;var y=lr(),x=Hn(y);x.tag=2,u!==void 0&&u!==null&&(x.callback=u),u=Vn(f,x,y),u!==null&&($i(u,f,y),Qn(u,f,y))}},og=Error(s(461)),$s=!1,lg={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},io=!1,Xs=!1,cg=!1,w5=typeof WeakSet==="function"?WeakSet:Set,hi=null,Ws=null,Wi=!1,Qr=null,_c=8192,FA={getCacheForType:function(f){var u=Vt(Es),y=u.data.get(f);return y===void 0&&(y=f(),u.data.set(f,y)),y},cacheSignal:function(){return Vt(Es).controller.signal}},nd=0,sd=1,id=2,rd=3,ad=4;if(typeof Symbol==="function"&&Symbol.for){var Xf=Symbol.for;nd=Xf("selector.component"),sd=Xf("selector.has_pseudo_class"),id=Xf("selector.role"),rd=Xf("selector.test_id"),ad=Xf("selector.text")}var LA=typeof WeakMap==="function"?WeakMap:Map,vn=0,as=null,Sn=null,xn=0,$n=0,pr=null,zo=!1,Ic=!1,fg=!1,ao=0,Ms=0,Go=0,_l=0,hg=0,gr=0,Rc=0,Wf=null,Ki=null,ug=!1,od=0,y5=0,Kf=1/0,ld=null,Vo=null,ti=0,$o=null,qc=null,oo=0,dg=0,mg=null,v5=null,Yf=0,pg=null;return yn.attemptContinuousHydration=function(f){if(f.tag===13||f.tag===31){var u=At(f,67108864);u!==null&&$i(u,f,67108864),Rp(f,67108864)}},yn.attemptHydrationAtCurrentPriority=function(f){if(f.tag===13||f.tag===31){var u=lr();u=U(u);var y=At(f,u);y!==null&&$i(y,f,u),Rp(f,u)}},yn.attemptSynchronousHydration=function(f){switch(f.tag){case 3:if(f=f.stateNode,f.current.memoizedState.isDehydrated){var u=k(f.pendingLanes);if(u!==0){f.pendingLanes|=2;for(f.entangledLanes|=2;u;){var y=1<<31-fr(u);f.entanglements[1]|=y,u&=~y}Lt(f),(vn&6)===0&&(Kf=Xi()+500,Ln(0,!1))}}break;case 31:case 13:u=At(f,2),u!==null&&$i(u,f,2),my(),Rp(f,2)}},yn.batchedUpdates=function(f,u){return f(u)},yn.createComponentSelector=function(f){return{$$typeof:nd,value:f}},yn.createContainer=function(f,u,y,x,C,D,X,pe,Ie,et){return Dy(f,u,!1,null,y,x,D,null,X,pe,Ie,et)},yn.createHasPseudoClassSelector=function(f){return{$$typeof:sd,value:f}},yn.createHydrationContainer=function(f,u,y,x,C,D,X,pe,Ie,et,gt,rt,Tt,ln){return f=Dy(y,x,!0,f,C,D,pe,ln,Ie,et,gt,rt),f.context=qy(null),y=f.current,x=lr(),x=U(x),C=Hn(x),C.callback=u!==void 0&&u!==null?u:null,Vn(y,C,x),u=x,f.current.lanes=u,q(f,u),Lt(f),f},yn.createPortal=function(f,u,y){var x=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:hc,key:x==null?null:""+x,children:f,containerInfo:u,implementation:y}},yn.createRoleSelector=function(f){return{$$typeof:id,value:f}},yn.createTestNameSelector=function(f){return{$$typeof:rd,value:f}},yn.createTextSelector=function(f){return{$$typeof:ad,value:f}},yn.defaultOnCaughtError=function(f){console.error(f)},yn.defaultOnRecoverableError=function(f){h5(f)},yn.defaultOnUncaughtError=function(f){h5(f)},yn.deferredUpdates=function(f){var u=Nt.T,y=to();try{return oi(32),Nt.T=null,f()}finally{oi(y),Nt.T=u}},yn.discreteUpdates=function(f,u,y,x,C){var D=Nt.T,X=to();try{return oi(2),Nt.T=null,f(u,y,x,C)}finally{oi(X),Nt.T=D,vn===0&&(Kf=Xi()+500)}},yn.findAllNodes=kp,yn.findBoundingRects=function(f,u){if(!Lf)throw Error(s(363));u=kp(f,u),f=[];for(var y=0;y<u.length;y++)f.push(gx(u[y]));for(u=f.length-1;0<u;u--){y=f[u];for(var x=y.x,C=x+y.width,D=y.y,X=D+y.height,pe=u-1;0<=pe;pe--)if(u!==pe){var Ie=f[pe],et=Ie.x,gt=et+Ie.width,rt=Ie.y,Tt=rt+Ie.height;if(x>=et&&D>=rt&&C<=gt&&X<=Tt){f.splice(u,1);break}else if(!(x!==et||y.width!==Ie.width||Tt<D||rt>X)){rt>D&&(Ie.height+=rt-D,Ie.y=D),Tt<X&&(Ie.height=X-rt),f.splice(u,1);break}else if(!(D!==rt||y.height!==Ie.height||gt<x||et>C)){et>x&&(Ie.width+=et-x,Ie.x=x),gt<C&&(Ie.width=C-et),f.splice(u,1);break}}}return f},yn.findHostInstance=My,yn.findHostInstanceWithNoPortals=function(f){return f=o(f),f=f!==null?c(f):null,f===null?null:Mf(f.stateNode)},yn.findHostInstanceWithWarning=function(f){return My(f)},yn.flushPassiveEffects=qf,yn.flushSyncFromReconciler=function(f){var u=vn;vn|=1;var y=Nt.T,x=to();try{if(oi(2),Nt.T=null,f)return f()}finally{oi(x),Nt.T=y,vn=u,(vn&6)===0&&Ln(0,!1)}},yn.flushSyncWork=my,yn.focusWithin=function(f,u){if(!Lf)throw Error(s(363));f=wp(f),u=fy(f,u),u=Array.from(u);for(f=0;f<u.length;){var y=u[f++],x=y.tag;if(!Of(y)){if((x===5||x===26||x===27)&&yx(y.stateNode))return!0;for(y=y.child;y!==null;)u.push(y),y=y.sibling}}return!1},yn.getFindAllNodesFailureDescription=function(f,u){if(!Lf)throw Error(s(363));var y=0,x=[];f=[wp(f),0];for(var C=0;C<f.length;){var D=f[C++],X=D.tag,pe=f[C++],Ie=u[pe];if(X!==5&&X!==26&&X!==27||!Of(D)){if(yp(D,Ie)&&(x.push(vp(Ie)),pe++,pe>y&&(y=pe)),pe<u.length)for(D=D.child;D!==null;)f.push(D,pe),D=D.sibling}}if(y<u.length){for(f=[];y<u.length;y++)f.push(vp(u[y]));return`findAllNodes was able to match part of the selector:
9
- `+(x.join(" > ")+`
10
-
11
- No matching component was found for:
12
- `)+f.join(" > ")}return null},yn.getPublicRootInstance=function(f){if(f=f.current,!f.child)return null;switch(f.child.tag){case 27:case 5:return Mf(f.child.stateNode);default:return f.child.stateNode}},yn.injectIntoDevTools=function(){var f={bundleType:0,version:Wk,rendererPackageName:Kk,currentDispatcherRef:Nt,reconcilerVersion:"19.2.0"};if(Hy!==null&&(f.rendererConfig=Hy),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")f=!1;else{var u=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(u.isDisabled||!u.supportsFiber)f=!0;else{try{Pf=u.inject(f),hr=u}catch(y){}f=u.checkDCE?!0:!1}}return f},yn.isAlreadyRendering=function(){return(vn&6)!==0},yn.observeVisibleRects=function(f,u,y,x){if(!Lf)throw Error(s(363));f=kp(f,u);var C=vx(f,y,x).disconnect;return{disconnect:function(){C()}}},yn.shouldError=function(){return null},yn.shouldSuspend=function(){return!1},yn.startHostTransition=function(f,u,y,x){if(f.tag!==5)throw Error(s(476));var C=pw(f).queue;mw(f,C,u,dc,y===null?n:function(){var D=pw(f);return D.next===null&&(D=f.alternate.memoizedState),Ef(f,D.next.queue,{},lr()),y(x)})},yn.updateContainer=function(f,u,y,x){var C=u.current,D=lr();return Fy(C,D,f,u,y,x),D},yn.updateContainerSync=function(f,u,y,x){return Fy(u.current,2,f,u,y,x),2},yn};Wh.exports.default=Wh.exports;Object.defineProperty(Wh.exports,"__esModule",{value:!0})});var L8=L(function(BU,F8){Z();F8.exports=function(t,n,s){let i=M("loading"),r=M(),[o,l]=w(0),c=M(),h=M(),d=M();if(c.current!==t||h.current!==n||d.current!==s)i.current="loading",r.current=void 0,c.current=t,h.current=n,d.current=s;return nt(function(){if(!t)return;var m=document.createElement("img");function p(){m.decode().catch(()=>{}).finally(()=>{i.current="loaded",r.current=m,l(Math.random())})}function b(){i.current="failed",r.current=void 0,l(Math.random())}return m.addEventListener("load",p),m.addEventListener("error",b),n&&(m.crossOrigin=n),s&&(m.referrerPolicy=s),m.src=t,function(){m.removeEventListener("load",p),m.removeEventListener("error",b)}},[t,n,s]),[r.current,i.current]}});var Mb={};Ye(Mb,{HostTransitionContext:()=>Iq,NotPendingTransition:()=>_q,afterActiveInstanceBlur:()=>uq,appendChild:()=>YD,appendChildToContainer:()=>QD,appendInitialChild:()=>ED,beforeActiveInstanceBlur:()=>hq,cancelTimeout:()=>BD,clearContainer:()=>lq,commitMount:()=>nq,commitTextUpdate:()=>tq,commitUpdate:()=>sq,createInstance:()=>CD,createTextInstance:()=>jD,detachDeletedInstance:()=>cq,finalizeInitialChildren:()=>_D,getChildHostContext:()=>PD,getCurrentEventPriority:()=>dq,getCurrentUpdatePriority:()=>bq,getInstanceFromNode:()=>fq,getInstanceFromScope:()=>pq,getPublicInstance:()=>ID,getRootHostContext:()=>OD,hideInstance:()=>iq,hideTextInstance:()=>rq,idlePriority:()=>Va,insertBefore:()=>C8,insertInContainerBefore:()=>JD,isPrimaryRenderer:()=>VD,maySuspendCommit:()=>Aq,noTimeout:()=>zD,now:()=>Oo,preloadInstance:()=>Tq,prepareForCommit:()=>RD,preparePortalMount:()=>DD,prepareScopeUpdate:()=>mq,prepareUpdate:()=>qD,removeChild:()=>ZD,removeChildFromContainer:()=>eq,requestPostPaintCallback:()=>xq,resetAfterCommit:()=>MD,resetFormInstance:()=>Rq,resetTextContent:()=>FD,resolveEventTimeStamp:()=>kq,resolveEventType:()=>Sq,resolveUpdatePriority:()=>wq,run:()=>$f,scheduleMicrotask:()=>UD,scheduleTimeout:()=>ND,setCurrentUpdatePriority:()=>gq,shouldAttemptEagerTransition:()=>yq,shouldDeprioritizeSubtree:()=>LD,shouldSetTextContent:()=>GD,startSuspendingCommit:()=>Eq,supportsHydration:()=>KD,supportsMicrotasks:()=>HD,supportsMutation:()=>XD,supportsPersistence:()=>WD,suspendInstance:()=>Cq,trackSchedulerEvent:()=>vq,unhideInstance:()=>aq,unhideTextInstance:()=>oq,waitForCommitToBeReady:()=>jq,warnsIfNotActing:()=>$D});var PA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],gg=z("circle-question-mark",PA);var NA=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],S5=z("text-align-start",NA);var BA=[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]],Ps=z("audio-lines",BA);var HA=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],k5=z("ban",HA);var UA=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],x5=z("hash",UA);var zA=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],ai=z("maximize",zA);var GA=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],li=z("minimize",GA);var VA=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],Mc=z("pause",VA);var $A=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],ya=z("play",$A);var XA=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],cd=z("repeat",XA);var WA=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],xa=z("settings",WA);var KA=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],fd=z("star",KA);var YA=[["path",{d:"M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",key:"16rjxf"}],["path",{d:"M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",key:"178nd4"}],["circle",{cx:"10.5",cy:"6.5",r:".5",fill:"currentColor",key:"12ikhr"}]],A5=z("tags",YA);var QA=[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]],T5=z("toggle-left",QA);var JA=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],ec=z("type",JA);var ZA=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],ud=z("volume-2",ZA);var eT=[["path",{d:"M11 4.702a.7.7 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.7.7 0 0 0 11 19.298z",key:"1p7khw"}],["path",{d:"m16.5 14.5 5-5",key:"cul3yw"}],["path",{d:"m16.5 9.5 5 5",key:"1akey5"}]],dd=z("volume-x",eT);function E5(e,t){let{start:n,end:s}=eu(t?.in,e),i=+n>+s,r=i?+n:+s,o=i?s:n;o.setHours(0,0,0,0);let l=t?.step??1;if(!l)return[];if(l<0)l=-l,i=!i;let c=[];while(+o<=r)c.push(Dt(n,o)),o.setDate(o.getDate()+l),o.setHours(0,0,0,0);return i?c.reverse():c}function pd(e,t){return ze(e,t?.in).getDate()}function C5(e,t){return ze(e,t?.in).getDay()}function bg(e,t){return ze(e,t?.in).getHours()}function wg(e,t){return ze(e,t?.in).getMinutes()}function tT(e,t,n){let s=e.slice();return s.splice(n,0,s.splice(t,1)[0]),s}function qd(e,t,n,s){if(n===s)return e;let i=tT(t,n,s),r=new Set(t.map((l)=>l.id)),o=0;return e.map((l)=>r.has(l.id)?i[o++]:l)}async function tc(e){let t=[],n=[],s=e.items;if(s)for(let o=0;o<s.length;o++){let l=s[o];if(l.kind==="file"){let c=l.webkitGetAsEntry?.();if(c)n.push({entry:c,path:""})}}else return Array.from(e.files);let i=(o)=>new Promise((l)=>{o.readEntries((c)=>l(c),()=>l([]))}),r=(o)=>new Promise((l,c)=>{o.file((h)=>l(h),(h)=>c(h))});while(n.length>0){let o=n.shift();if(!o)continue;let{entry:l,path:c}=o;if(l.isFile)try{let h=await r(l),d=c?`${c}/${h.name}`:h.name;Object.defineProperty(h,"webkitRelativePath",{value:d,writable:!1,configurable:!0}),t.push(h)}catch(h){console.error("Error reading file entry:",h)}else if(l.isDirectory){let h=l.createReader(),d=[],m=await i(h);while(m.length>0)d=d.concat(m),m=await i(h);let p=c?`${c}/${l.name}`:l.name;for(let b of d)n.push({entry:b,path:p})}}return t}var cn=en((e)=>({fields:[],loadedProjectId:null,setFields:(t,n)=>e({fields:t,loadedProjectId:n}),updateFields:(t)=>e({fields:t})}));var Rl;(function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID"})(Rl||(Rl={}));class Lc extends Error{constructor(e,t){super(`${t} (${e})`);this.name="ULIDError",this.code=e}}function nT(e){let t=Math.floor(e()*32)%32;return"0123456789ABCDEFGHJKMNPQRSTVWXYZ".charAt(t)}function sT(e){let t=iT(),n=t&&(t.crypto||t.msCrypto)||null;if(typeof n?.getRandomValues==="function")return()=>{let s=new Uint8Array(1);return n.getRandomValues(s),s[0]/256};else if(typeof n?.randomBytes==="function")return()=>n.randomBytes(1).readUInt8()/256;throw new Lc(Rl.PRNGDetectFailure,"Failed to find a reliable PRNG")}function iT(){if(oT())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function rT(e,t){let n="";for(;e>0;e--)n=nT(t)+n;return n}function aT(e,t=10){if(isNaN(e))throw new Lc(Rl.EncodeTimeValueMalformed,`Time must be a number: ${e}`);else if(e>281474976710655)throw new Lc(Rl.EncodeTimeSizeExceeded,`Cannot encode a time larger than 281474976710655: ${e}`);else if(e<0)throw new Lc(Rl.EncodeTimeNegative,`Time must be positive: ${e}`);else if(Number.isInteger(e)===!1)throw new Lc(Rl.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let n,s="";for(let i=t;i>0;i--)n=e%32,s="0123456789ABCDEFGHJKMNPQRSTVWXYZ".charAt(n)+s,e=(e-n)/32;return s}function oT(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function As(e,t){let n=t||sT(),s=!e||isNaN(e)?Date.now():e;return aT(s,10)+rT(16,n)}Z();var lt=Number.isFinite||function(e){return typeof e==="number"&&isFinite(e)},lT=Number.isSafeInteger||function(e){return typeof e==="number"&&Math.abs(e)<=cT},cT=Number.MAX_SAFE_INTEGER||9007199254740991,Et=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ve=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",e.UNKNOWN="unknown",e}({}),O=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});function fT(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vg={exports:{}},j5;function hT(){if(j5)return vg.exports;return j5=1,function(e,t){(function(n){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(c,h,d){if(d=d||{},c=c.trim(),h=h.trim(),!h){if(!d.alwaysNormalize)return c;var m=l.parseURL(c);if(!m)throw Error("Error trying to parse base URL.");return m.path=l.normalizePath(m.path),l.buildURLFromParts(m)}var p=l.parseURL(h);if(!p)throw Error("Error trying to parse relative URL.");if(p.scheme){if(!d.alwaysNormalize)return h;return p.path=l.normalizePath(p.path),l.buildURLFromParts(p)}var b=l.parseURL(c);if(!b)throw Error("Error trying to parse base URL.");if(!b.netLoc&&b.path&&b.path[0]!=="/"){var v=i.exec(b.path);b.netLoc=v[1],b.path=v[2]}if(b.netLoc&&!b.path)b.path="/";var k={scheme:b.scheme,netLoc:p.netLoc,path:null,params:p.params,query:p.query,fragment:p.fragment};if(!p.netLoc){if(k.netLoc=b.netLoc,p.path[0]!=="/")if(!p.path){if(k.path=b.path,!p.params){if(k.params=b.params,!p.query)k.query=b.query}}else{var A=b.path,T=A.substring(0,A.lastIndexOf("/")+1)+p.path;k.path=l.normalizePath(T)}}if(k.path===null)k.path=d.alwaysNormalize?l.normalizePath(p.path):p.path;return l.buildURLFromParts(k)},parseURL:function(c){var h=s.exec(c);if(!h)return null;return{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}},normalizePath:function(c){c=c.split("").reverse().join("").replace(r,"");while(c.length!==(c=c.replace(o,"")).length);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};e.exports=l})()}(vg),vg.exports}var A1=hT();class c0{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var fn=function(e){return e.MANIFEST="manifest",e.LEVEL="level",e.AUDIO_TRACK="audioTrack",e.SUBTITLE_TRACK="subtitleTrack",e.MEDIA_FRAGMENT="media-fragment",e.KEY="key",e.STEERING_MANIFEST="steering-manifest",e.SERVER_CERTIFICATE="server-certificate",e.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",e}({}),kt=function(e){return e.MAIN="main",e.AUDIO="audio",e.SUBTITLE="subtitle",e}({}),Zn={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class T1{constructor(e){if(this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e==="string")e={url:e};this.base=e,uT(this,"stats")}setByteRange(e,t){let n=e.split("@",2),s;if(n.length===1)s=(t==null?void 0:t.byteRangeEndOffset)||0;else s=parseInt(n[1]);this._byteRange=[s,parseInt(n[0])+s]}get baseurl(){return this.base.url}get byteRange(){if(this._byteRange===null)return[];return this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){if(this._streams===null)this._streams={[Zn.AUDIO]:null,[Zn.VIDEO]:null,[Zn.AUDIOVIDEO]:null};return this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){if(this._stats===null)this._stats=new c0;return this._stats}set stats(e){this._stats=e}get url(){if(!this._url&&this.relurl)this._url=A1.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0});return this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Zn.AUDIO]=null,e[Zn.VIDEO]=null,e[Zn.AUDIOVIDEO]=null,this.url=null}}function js(e){return e.sn!=="initSegment"}function nh(e,t){return e.sn===(t==null?void 0:t.sn)&&e.level===t.level}function Kg(e,t){return e.sn===(t==null?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}class ih extends T1{constructor(e,t){super(t);this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(lt(e)&&lt(t))return t-e}return null}get bitrate(){if(this.byteLength)return this.byteLength*8/this.duration;if(this._bitrate)return this._bitrate;return null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity){if(!this._decryptdata)this._decryptdata=t.identity.getDecryptData(this.sn)}else if(!((e=this._decryptdata)!=null&&e.keyId)){let n=Object.keys(t);if(n.length===1){let s=this._decryptdata=t[n[0]]||null;if(s)this._decryptdata=s.getDecryptData(this.sn,t)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=!lt(this.duration)?0:this.duration;return this.programDateTime+e*1000}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;else if(this.levelkeys){var t;let n=Object.keys(this.levelkeys),s=n.length;if(s>1||s===1&&(t=this.levelkeys[n[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){if(this._programDateTime===null&&this.rawProgramDateTime)this.programDateTime=Date.parse(this.rawProgramDateTime);return this._programDateTime}set programDateTime(e){if(!lt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){if(!js(this))return null;if(!this._ref)this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime};return this._ref}addStart(e){this.setStart(this.start+e)}setStart(e){if(this.start=e,this._ref)this._ref.start=e}setDuration(e){if(this.duration=e,this._ref)this._ref.duration=e}setKeyFormat(e){let t=this.levelkeys;if(t){var n;let s=t[e];if(s&&!((n=this._decryptdata)!=null&&n.keyId))this._decryptdata=s.getDecryptData(this.sn,t)}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,s,i,r=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:n,startDTS:s,endDTS:i,partial:r};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,n),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,i)}}class Z3 extends T1{constructor(e,t,n,s,i){super(n);this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=s;let r=e.enumeratedString("BYTERANGE");if(r)this.setByteRange(r,i);if(i)this.fragOffset=i.fragOffset+i.duration}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===kt.SUBTITLE&&this.stats.loading.end>0)}}function e9(e,t){let n=Object.getPrototypeOf(e);if(n){let s=Object.getOwnPropertyDescriptor(n,t);if(s)return s;return e9(n,t)}}function uT(e,t){let n=e9(e,t);if(n)n.enumerable=!0,Object.defineProperty(e,t,n)}function dT(e,t,n){return(t=gT(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gn(){return Gn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Gn.apply(null,arguments)}function _5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,s)}return n}function Ct(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_5(Object(n),!0).forEach(function(s){dT(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_5(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function f0(e,t){if(e==null)return{};var n,s,i=mT(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(s=0;s<r.length;s++)n=r[s],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function mT(e,t){if(e==null)return{};var n={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.indexOf(s)!==-1)continue;n[s]=e[s]}return n}function pT(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(typeof s!="object")return s;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function gT(e){var t=pT(e,"string");return typeof t=="symbol"?t:t+""}function Gd(e){switch(e.details){case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_TIMEOUT:case ve.LEVEL_LOAD_TIMEOUT:case ve.MANIFEST_LOAD_TIMEOUT:case ve.AUDIO_TRACK_LOAD_TIMEOUT:case ve.SUBTITLE_TRACK_LOAD_TIMEOUT:case ve.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function t9(e){return e.details.startsWith("key")}function n9(e){return t9(e)&&!!e.frag&&!e.frag.decryptdata}function I5(e,t){let n=Gd(t);return e.default[`${n?"timeout":"error"}Retry`]}function E1(e,t){let n=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function R5(e){return Ct(Ct({},e),{errorRetry:null,timeoutRetry:null})}function gh(e,t,n,s){if(!e)return!1;let i=s==null?void 0:s.code,r=t<e.maxNumRetry&&(bT(i)||!!n);return e.shouldRetry?e.shouldRetry(e,t,n,s,r):r}function bT(e){return bh(e)||!!e&&(e<400||e>499)}function bh(e){return e===0&&navigator.onLine===!1}function s9(e,t){return t>0&&e.loadError>0&&e.loadErrorTime!==0&&self.performance.now()-e.loadErrorTime>t}class Ol{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(0.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){let n=Math.pow(this.alpha_,e);this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class i9{constructor(e,t,n,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=0.001,this.minDelayMs_=50,this.slow_=new Ol(e),this.fast_=new Ol(t),this.defaultTTFB_=s,this.ttfb_=new Ol(e)}update(e,t){let{slow_:n,fast_:s,ttfb_:i}=this;if(n.halfLife!==e)this.slow_=new Ol(e,n.getEstimate(),n.getTotalWeight());if(s.halfLife!==t)this.fast_=new Ol(t,s.getEstimate(),s.getTotalWeight());if(i.halfLife!==e)this.ttfb_=new Ol(e,i.getEstimate(),i.getTotalWeight())}sample(e,t){if(t<=0)return;let n=Math.min(this.minDelayMs_,t/1e5),s=8*t,i=Math.max(e,n)/1000,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=e/1000,n=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){if(this.canEstimate())return Math.min(this.fast_.getEstimate(),this.slow_.getEstimate());else return this.defaultEstimate_}getEstimateTTFB(){if(this.ttfb_.getTotalWeight()>=this.minWeight_)return this.ttfb_.getEstimate();else return this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class Ji{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let n=`[${e}]:`;this.trace=Ko,this.debug=t.debug.bind(null,n),this.log=t.log.bind(null,n),this.warn=t.warn.bind(null,n),this.info=t.info.bind(null,n),this.error=t.error.bind(null,n)}}var Ko=function(){},wT={trace:Ko,debug:Ko,log:Ko,warn:Ko,info:Ko,error:Ko};function Yg(){return Gn({},wT)}function yT(e,t){let n=self.console[e];return n?n.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Ko}function D5(e,t,n){return t[e]?t[e].bind(t):yT(e,n)}var Qg=Yg();function vT(e,t,n){let s=Yg();if(typeof console==="object"&&e===!0||typeof e==="object"){let i=["debug","log","info","warn","error"];i.forEach((r)=>{s[r]=D5(r,e,n)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.7.3`)}catch(r){return Yg()}i.forEach((r)=>{Qg[r]=D5(r,e)})}else Gn(Qg,s);return s}var Rn=Qg;function Zo(e=!0){if(typeof self>"u")return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ST(e){return typeof self<"u"&&e===self.ManagedMediaSource}function r9(e,t){let n=Object.keys(e),s=Object.keys(t),i=n.length,r=s.length;return!i||!r||i===r&&!n.some((o)=>s.indexOf(o)===-1)}function kT(e){return btoa(String.fromCharCode(...e))}function h0(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}var xT="utf-16",Sg="utf-16be",q5="utf-16le",Md="utf-8";function AT(e,t={}){let n;if(h0(e))n=new DataView(e);else n=new DataView(e.buffer,e.byteOffset,e.byteLength);let s=0,{encoding:i}=t;if(!i){let h=n.getUint8(0),d=n.getUint8(1);if(h==239&&d==187&&n.getUint8(2)==191)i=Md,s=3;else if(h==254&&d==255)i=Sg,s=2;else if(h==255&&d==254)i=q5,s=2;else i=Md}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(n);let{byteLength:r}=n,o=i!==Sg,l="",c;while(s<r){switch(i){case Md:if(c=n.getUint8(s),c<128)s++;else if(c>=194&&c<=223)if(s+1<r){let h=n.getUint8(s+1);if(h>=128&&h<=191)c=(c&31)<<6|h&63,s+=2;else s++}else s++;else if(c>=224&&c<=239)if(s+2<=r-1){let h=n.getUint8(s+1),d=n.getUint8(s+2);if(h>=128&&h<=191&&d>=128&&d<=191)c=(c&15)<<12|(h&63)<<6|d&63,s+=3;else s++}else s++;else if(c>=240&&c<=244)if(s+3<=r-1){let h=n.getUint8(s+1),d=n.getUint8(s+2),m=n.getUint8(s+3);if(h>=128&&h<=191&&d>=128&&d<=191&&m>=128&&m<=191)c=(c&7)<<18|(h&63)<<12|(d&63)<<6|m&63,s+=4;else s++}else s++;else s++;break;case Sg:case xT:case q5:c=n.getUint16(s,o),s+=2;break}l+=String.fromCodePoint(c)}return l}function TT(e){let t=typeof e==="string"?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}function a9(e,t){if(e<0)return-a9(-e,t);let n=Math.pow(10,t);if(Math.abs(e*n%1-0.5)<Number.EPSILON){let s=Math.floor(e*n);return(s%2===0?s:s+1)/n}else return Math.round(e*n)/n}function ET(e,t){let n;try{n=new URL(e)}catch(l){return e}let s=new URL(t);if(n.origin!==s.origin)return e;let i=n.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),o=Math.min(i.length,r.length);for(let l=0;l<o;l++){if(i[l]!==r[l])break;i.shift(),r.shift()}while(r.length)r.shift(),i.unshift("..");return i.join("/")+n.search+n.hash}function o9(){try{return crypto.randomUUID()}catch(e){try{let t=URL.createObjectURL(new Blob),n=t.toString();return URL.revokeObjectURL(t),n.slice(n.lastIndexOf("/")+1)}catch(t){let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(s)=>{let i=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(s=="x"?i:i&3|8).toString(16)})}}}function C1(e,t){if(t+10<=e.length){if(e[t]===73&&e[t+1]===68&&e[t+2]===51){if(e[t+3]<255&&e[t+4]<255){if(e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128)return!0}}}return!1}function u0(e,t){let n=0;return n=(e[t]&127)<<21,n|=(e[t+1]&127)<<14,n|=(e[t+2]&127)<<7,n|=e[t+3]&127,n}function CT(e,t){return C1(e,t)&&u0(e,t+6)+10<=e.length-t}function l9(e,t){if(t+10<=e.length){if(e[t]===51&&e[t+1]===68&&e[t+2]===73){if(e[t+3]<255&&e[t+4]<255){if(e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128)return!0}}}return!1}function wh(e,t){let n=t,s=0;while(C1(e,t)){s+=10;let i=u0(e,t+6);if(s+=i,l9(e,t+10))s+=10;t+=s}if(s>0)return e.subarray(n,n+s)}function jT(e){if(h0(e))return e;else{if(e.byteOffset==0&&e.byteLength==e.buffer.byteLength)return e.buffer;return new Uint8Array(e).buffer}}function kg(e,t=0,n=1/0){return _T(e,t,n,Uint8Array)}function _T(e,t,n,s){let i=IT(e),r=1;if("BYTES_PER_ELEMENT"in s)r=s.BYTES_PER_ELEMENT;let o=RT(e)?e.byteOffset:0,l=(o+e.byteLength)/r,c=(o+t)/r,h=Math.floor(Math.max(0,Math.min(c,l)));return new s(i,h,Math.floor(Math.min(h+Math.max(n,0),l))-h)}function IT(e){if(h0(e))return e;else return e.buffer}function RT(e){return e&&h0(e.buffer)&&e.byteLength!==void 0&&e.byteOffset!==void 0}function yr(e,t=!1){let n=t?e.indexOf(0):e.length,s=AT(new DataView(e.buffer,e.byteOffset,n),{encoding:Md});return t?s:s.replace(/\0/g,"")}function DT(e){let t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},n=3;if(e.size<2)return;if(e.data[0]!==3){console.log("Ignore frame with unrecognized character encoding");return}let s=e.data.subarray(1).indexOf(0);if(s===-1)return;let i=yr(kg(e.data,1,s)),r=e.data[2+s],o=e.data.subarray(3+s).indexOf(0);if(o===-1)return;let l=yr(kg(e.data,3+s,o)),c;if(i==="-->")c=yr(kg(e.data,4+s+o));else c=jT(e.data.subarray(4+s+o));return t.mimeType=i,t.pictureType=r,t.description=l,t.data=c,t}function qT(e){if(e.size<2)return;let t=yr(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}}function MT(e){if(e.size<2)return;if(e.type==="TXXX"){let n=1,{data:s}=e,i=yr(s.subarray(n),!0);n+=i.length+1;let r=yr(s.subarray(n));return{key:e.type,info:i,data:r}}let t=yr(e.data.subarray(1));return{key:e.type,info:"",data:t}}function FT(e){if(e.type==="WXXX"){if(e.size<2)return;let n=1,s=yr(e.data.subarray(n),!0);n+=s.length+1;let i=yr(e.data.subarray(n));return{key:e.type,info:s,data:i}}let t=yr(e.data);return{key:e.type,info:"",data:t}}function LT(e){if(e.type==="PRIV")return qT(e);else if(e.type[0]==="W")return FT(e);else if(e.type==="APIC")return DT(e);return MT(e)}function OT(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=u0(e,4),s=10;return{type:t,size:n,data:e.subarray(10,10+n)}}var bd=10,PT=10;function c9(e){let t=0,n=[];while(C1(e,t)){let s=u0(e,t+6);if(e[t+5]>>6&1)t+=bd;t+=bd;let i=t+s;while(t+PT<i){let r=OT(e.subarray(t)),o=LT(r);if(o)n.push(o);t+=r.size+bd}if(l9(e,t))t+=bd}return n}function f9(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function NT(e){if(e.data.byteLength===8){let t=new Uint8Array(e.data),n=t[3]&1,s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];if(s/=45,n)s+=47721858.84;return Math.round(s)}}function j1(e){let t=c9(e);for(let n of t)if(f9(n))return NT(n)}function Ys(e){let t="";for(let n=0;n<e.length;n++){let s=e[n].toString(16);if(s.length<2)s="0"+s;t+=s}return t}function h9(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function _1(e){return Uint8Array.from(atob(e),(t)=>t.charCodeAt(0))}function ia(e){return String.fromCharCode.apply(null,e)}var Aa=Math.pow(2,32)-1,Pt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},u9={video:1,audio:2,id3:3,text:4};function d9(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function yt(e,t){let n=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return n<0?4294967296+n:n}function M5(e,t){let n=yt(e,t);return n*=Math.pow(2,32),n+=yt(e,t+4),n}function yd(e,t){let n="";for(let s=t;s<e.length;s++)if(n+=String.fromCharCode(e[s]),e[s]===0)return n;return null}function Jg(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Gs(e,t,n){e[t]=n>>24,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255}function F5(e,t,n){let s=t.byteOffset-e.byteOffset-8,i=8+n,r=t.byteLength+8-i;if(r<8)return;Gs(e,s,i),Gs(e,s+i,r),Gs(e,s+i+4,Pt.free)}function Zg(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function m9(e,t){t.sort((l,c)=>l[0]-c[0]);let n=t.reduce((l,[c,h])=>l+h-c,0),s=new Uint8Array(e.byteLength-n),i=0,r=0;for(let l=0;l<t.length;l++){let[c,h]=t[l];s.set(e.subarray(i,c),r),r+=c-i,i=h}return s.set(e.subarray(i),r),{result:s,dropped:n,droppedBefore:(l)=>t.reduce((c,[h,d])=>d<=l?c+d-h:c,0)}}function BT(e){let t=Ut(e,["moov"]);if(t.length!==1||Ut(e,["moof"]).length)return null;let n=e.byteOffset,s=[],i=[],r=!1,o=Ut(t[0],["trak"]);for(let b=0;b<o.length;b++){let v=o[b],k=Ut(v,["mdia","hdlr"])[0];if((k?ia(k.subarray(8,12)):"")==="vide"){r=!0;continue}let T=Ut(v,["tkhd"])[0];if(!T)return null;let E=T[0];i.push(yt(T,E===0?12:20)),s.push(Zg(v,n))}if(!r||!s.length)return null;let l=Ut(t[0],["mvex"])[0],c=0;if(l){let b=Ut(l,["trex"]);for(let v=0;v<b.length;v++){let k=b[v];if(i.indexOf(yt(k,4))!==-1)s.push(Zg(k,n)),c+=k.byteLength+8}}let{result:h,dropped:d,droppedBefore:m}=m9(e,s),p=t[0].byteOffset-n-8;if(Gs(h,p,t[0].byteLength+8-d),l&&c){let b=l.byteOffset-n-8;Gs(h,b-m(b),l.byteLength+8-c)}return h}function HT(e,t,n,s,i){if(n<1)return null;let r=Ut(e,["moof"]);if(r.length!==1)return null;let o=r[0],l=e.byteOffset,c=[],h=[],d=Ut(o,["traf"]),m=!0;for(let k=0;k<d.length;k++){let A=d[k],T=Ut(A,["tfhd"])[0];if(!T)return null;if(yt(T,4)===t){if(c.push(A),!(yt(T,0)&131072))m=!1}else h.push(Zg(A,l))}if(!c.length)return null;if(h.length&&!m)return null;if(s!==void 0){let k=n;for(let T=0;T<c.length;T++){let E=c[T],I=0,_=Ut(E,["trun"]);for(let N=0;N<_.length;N++){let H=_[N],V=Math.min(k,yt(H,4));if(V){Gs(e,H.byteOffset-l+4,V);let U=yt(H,0)&16777215,W=(U&256?4:0)+(U&512?4:0)+(U&1024?4:0)+(U&2048?4:0);F5(e,H,8+(U&1?4:0)+(U&4?4:0)+V*W)}else Gs(e,H.byteOffset-l-4,Pt.free);k-=V,I+=V}let q=Ut(E,["senc"])[0];if(q)Gs(e,q.byteOffset-l+4,I);let P=Ut(E,["saiz"])[0];if(P){let N=P[1]<<16|P[2]<<8|P[3],H=4;if(N&1)H+=8;let V=P[H];H+=1,Gs(e,P.byteOffset-l+H,I),F5(e,P,H+4+(V===0?I:0))}}let A=Ut(e,["mdat"]);if(A.length===1){let T=A[0].byteOffset-l-8;Gs(e,T,s-T)}}let p=e,b=0,v=()=>0;if(h.length){({result:p,dropped:b,droppedBefore:v}=m9(e,h)),Gs(p,o.byteOffset-l-8,o.byteLength+8-b);for(let k=0;k<c.length;k++){let A=c[k],T=v(A.byteOffset-l),E=Ut(A,["trun"]);for(let I=0;I<E.length;I++){let _=E[I];if(yt(_,0)&1)Gs(p,_.byteOffset-l-T+8,yt(_,8)-b)}if(T){let I=Ut(A,["saio"]);for(let _=0;_<I.length;_++){let q=I[_],P=q[0]===0?4:8,N=yt(q,0)&1?12:4,H=yt(q,N);for(N+=4;H--;N+=P){let V=N+P-4;Gs(p,q.byteOffset-l-T+V,yt(q,V)-T)}}}}}if(i){let{durationOffset:k,value:A}=i;Gs(p,k-v(k),A)}return s!==void 0?p.subarray(0,s-b):p}function UT(e,t){let n=e.byteLength;for(let s=0;s<n;){let i=yt(e,s);if(i>8&&yt(e,s+4)===Pt[t])return!0;s=i>1?s+i:n}return!1}function Ut(e,t){let n=[];if(!t.length)return n;return p9(e,t,0,0,e.byteLength,n),n}function p9(e,t,n,s,i,r){let o=t[n];if((o==null?void 0:o.length)!==4)return;let l=o.charCodeAt(0),c=o.charCodeAt(1),h=o.charCodeAt(2),d=o.charCodeAt(3),m=t.length-1;for(let p=s;p<i;){let b=p+8<=i,v=p+4<=i?e[p]*16777216+(e[p+1]<<16|e[p+2]<<8|e[p+3]):yt(e,p),k=v>1?p+v:i;if(b&&e[p+4]===l&&e[p+5]===c&&e[p+6]===h&&e[p+7]===d){let A=Math.min(k,i);if(n===m)r.push(e.subarray(p+8,A));else p9(e,t,n+1,p+8,A,r)}p=k}}function zT(e){let t=[],n=e[0],s=8,i=yt(e,s);s+=4;let r=0,o=0;if(n===0)r=yt(e,s),o=yt(e,s+4),s+=8;else r=M5(e,s),o=M5(e,s+8),s+=16;s+=2;let l=e.length+o,c=d9(e,s);s+=2;for(let h=0;h<c;h++){let d=s,m=yt(e,d);d+=4;let p=m&2147483647;if((m&2147483648)>>>31===1)return Rn.warn("SIDX has hierarchical references (not supported)"),null;let v=yt(e,d);d+=4,t.push({referenceSize:p,subsegmentDuration:v,info:{duration:v/i,start:l,end:l+p-1}}),l+=p,d+=4,s=d}return{earliestPresentationTime:r,timescale:i,version:n,referencesCount:c,references:t}}function g9(e){let t=[],n=Ut(e,["moov","trak"]);for(let i=0;i<n.length;i++){let r=n[i],o=Ut(r,["tkhd"])[0];if(o){let l=o[0],c=yt(o,l===0?12:20),h=Ut(r,["mdia","mdhd"])[0];if(h){l=h[0];let d=yt(h,l===0?12:20),m=Ut(r,["mdia","hdlr"])[0];if(m){let p=ia(m.subarray(8,12)),b={soun:Zn.AUDIO,vide:Zn.VIDEO}[p],v=Ut(r,["mdia","minf","stbl","stsd"])[0],k=GT(v);if(b)t[c]={timescale:d,type:b,stsd:k},t[b]=Ct({timescale:d,id:c},k);else t[c]={timescale:d,type:p,stsd:k}}}}}return Ut(e,["moov","mvex","trex"]).forEach((i)=>{let r=yt(i,4),o=t[r];if(o)o.default={duration:yt(i,12),sampleSize:yt(i,16),flags:yt(i,20)}}),t}function GT(e){let t=e.subarray(8),n=t.subarray(86),s=ia(t.subarray(4,8)),i=s,r,o=s==="enca"||s==="encv";if(o){let h=Ut(t,[s])[0].subarray(s==="enca"?28:78);Ut(h,["sinf"]).forEach((m)=>{let p=Ut(m,["schm"])[0];if(p){let b=ia(p.subarray(4,8));if(b==="cbcs"||b==="cenc"){let v=Ut(m,["frma"])[0];if(v)i=ia(v)}}})}let l=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{let c=Ut(n,["avcC"])[0];if(c&&c.length>3)i+="."+Sd(c[1])+Sd(c[2])+Sd(c[3]),r=vd(l==="avc1"?"dva1":"dvav",n);break}case"mp4a":{let c=Ut(t,[s])[0],h=Ut(c.subarray(28),["esds"])[0];if(h&&h.length>7){let d=4;if(h[d++]!==3)break;d=xg(h,d),d+=2;let m=h[d++];if(m&128)d+=2;if(m&64)d+=h[d++];if(h[d++]!==4)break;d=xg(h,d);let p=h[d++];if(p===64)i+="."+Sd(p);else break;if(d+=12,h[d++]!==5)break;d=xg(h,d);let b=h[d++],v=(b&248)>>3;if(v===31)v+=1+((b&7)<<3)+((h[d]&224)>>5);i+="."+v}break}case"hvc1":case"hev1":{let c=Ut(n,["hvcC"])[0];if(c&&c.length>12){let h=c[1],d=["","A","B","C"][h>>6],m=h&31,p=yt(c,2),b=(h&32)>>5?"H":"L",v=c[12],k=c.subarray(6,12);i+="."+d+m,i+="."+VT(p).toString(16).toUpperCase(),i+="."+b+v;let A="";for(let T=k.length;T--;){let E=k[T];if(E||A)A="."+E.toString(16).toUpperCase()+A}i+=A}r=vd(l=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=vd(i,n)||i;break}case"vp09":{let c=Ut(n,["vpcC"])[0];if(c&&c.length>6){let h=c[4],d=c[5],m=c[6]>>4&15;i+="."+Ta(h)+"."+Ta(d)+"."+Ta(m)}break}case"av01":{let c=Ut(n,["av1C"])[0];if(c&&c.length>2){let h=c[1]>>>5,d=c[1]&31,m=c[2]>>>7?"H":"M",p=(c[2]&64)>>6,b=(c[2]&32)>>5,v=h===2&&p?b?12:10:p?10:8,k=(c[2]&16)>>4,A=(c[2]&8)>>3,T=(c[2]&4)>>2,E=c[2]&3,I=1,_=1,q=1,P=0;i+="."+h+"."+Ta(d)+m+"."+Ta(v)+"."+k+"."+A+T+E+"."+Ta(1)+"."+Ta(1)+"."+Ta(1)+".0",r=vd("dav1",n)}break}}return{codec:i,encrypted:o,supplemental:r}}function vd(e,t){let n=Ut(t,["dvvC"]),s=n.length?n[0]:Ut(t,["dvcC"])[0];if(s){let i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return e+"."+Ta(i)+"."+Ta(r)}}function VT(e){let t=0;for(let n=0;n<32;n++)t|=(e>>n&1)<<31-n;return t>>>0}function xg(e,t){let n=t+5;while(e[t++]&128&&t<n);return t}function Sd(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Ta(e){return(e<10?"0":"")+e}function $T(e,t){if(!e||!t)return;let n=t.keyId;if((n==null?void 0:n.byteLength)===16&&t.isCommonEncryption)b9(e,(s,i)=>{let r=s.subarray(8,24);if(!r.some((o)=>o!==0))Rn.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ys(r)} -> ${Ys(n)}`),s.set(n,8)})}function WT(e){let t=[];return b9(e,(n)=>t.push(n.subarray(8,24))),t}function b9(e,t){Ut(e,["moov","trak"]).forEach((s)=>{let i=Ut(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),o=Ut(r,["enca"]),l=o.length>0;if(!l)o=Ut(r,["encv"]);o.forEach((c)=>{let h=l?c.subarray(28):c.subarray(78);Ut(h,["sinf"]).forEach((m)=>{let p=w9(m);if(p)t(p,l)})})})}function w9(e){let t=Ut(e,["schm"])[0];if(t){let n=ia(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){let s=Ut(e,["schi","tenc"])[0];if(s)return s}}}var L5;function KT(e){if(typeof TextDecoder>"u")return yr(e);return(L5||(L5=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function YT(e){let t=e.byteLength,n=[];for(let s=0;s<t;){let i=s+8<=t,r=s+4<=t?e[s]*16777216+(e[s+1]<<16|e[s+2]<<8|e[s+3]):yt(e,s),o=r>1?s+r:t;if(i&&e[s+4]===109&&e[s+5]===111&&e[s+6]===111&&e[s+7]===102){let l=Math.min(o,t);for(let c=s+8;c<l;){let h=c+8<=l,d=c+4<=l?e[c]*16777216+(e[c+1]<<16|e[c+2]<<8|e[c+3]):yt(e,c),m=d>1?c+d:l;if(h&&e[c+4]===116&&e[c+5]===114&&e[c+6]===97&&e[c+7]===102){let p=Math.min(m,l),b,v,k=[];for(let A=c+8;A<p;){let T=A+8<=p,E=A+4<=p?e[A]*16777216+(e[A+1]<<16|e[A+2]<<8|e[A+3]):yt(e,A),I=E>1?A+E:p;if(T&&e[A+4]===116){let _=Math.min(I,p);if(e[A+5]===102&&e[A+6]===104&&e[A+7]===100)v||(v=e.subarray(A+8,_));else if(e[A+5]===102&&e[A+6]===100&&e[A+7]===116)b||(b=e.subarray(A+8,_));else if(e[A+5]===114&&e[A+6]===117&&e[A+7]===110)k.push(e.subarray(A+8,_))}A=I}n.push({moofOffset:e.byteOffset+s,tfdt:b,tfhd:v,truns:k})}c=m}}s=o}return n}function QT(e,t,n,s,i=!0){return y9(e,t,s,i)}function JT(e,t,n,s,i=!1){let r=[],o=t.samples,l=y9(o,n,s,i,{isHEVCFlavor:jh(t.codec),samples:r,timeOffset:e,timescale:t.timescale,trackId:t.id});return{samples:r,sampleData:{includeSampleDetails:i,tracks:l}}}function y9(e,t,n,s,i){let r={},o=!1,l=YT(e),c=e.byteLength;for(let m=0;m<l.length;m++){let{moofOffset:p,tfdt:b,tfhd:v,truns:k}=l[m],A=yt(v,4),T=t[A];if(!T)continue;let E=r[A]||(r[A]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:T.timescale,type:T.type}),I;if(b){let me=b[0];if(I=yt(b,4),me===1)if(I===Aa)n.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");else I*=Aa+1,I+=yt(b,8);if(lt(I)&&(!lt(E.start)||I<E.start))E.start=I;if(i&&lt(I))i.timeOffset=I/i.timescale}let _=(i==null?void 0:i.trackId)===A&&T.type===Zn.VIDEO,q=T.default,P=yt(v,0)&16777215,N=(q==null?void 0:q.duration)||0,H,V=(q==null?void 0:q.sampleSize)||0,U=8;if(P&1)U+=8;if(P&2)U+=4;if(P&8)N=yt(v,U),H=v.byteOffset-e.byteOffset+U,U+=4;if(P&16)V=yt(v,U);let W=0,ce=(P&1)!==0,ue=!ce&&(P&131072)!==0;if(ce)W=yt(v,8),W*=Math.pow(2,32),W+=yt(v,12);else if(ue)W=p;let oe=I||0,ae=0,te=N;for(let me=0;me<k.length;me++){let he=k[me],we=yt(he,4),be=E.sampleCount;E.sampleCount+=we;let ye=he[3]&1,Te=0,Oe=he[3]&4,st=he[2]&1,We=he[2]&2,wt=he[2]&4,xt=he[2]&8,ft=8;if(ye)Te=Jg(he,ft),ft+=4;if(Oe){if(!(he[ft+1]&1)&&E.keyFrameIndex===void 0)E.keyFrameIndex=be;ft+=4}let It=W+Te;if(!s&&he[1]===0&&he[2]===6&&he[3]===1){var h,d;let tn=oe,Kn=It,Le=ft,Je=-1,bt=0,ut=0,Ft=(h=i==null?void 0:i.timeOffset)!=null?h:0,nn=N/((d=i==null?void 0:i.timescale)!=null?d:1),mn=(i==null?void 0:i.isHEVCFlavor)===!0,Vt=mn?2:1;for(let ns=0;ns<we;ns++){let St=he[ft]===0?he[ft+1]<<16|he[ft+2]<<8|he[ft+3]:yt(he,ft),it=Je===-1&&E.keyFrameIndex===void 0&&(he[ft+5]&1)===0;ft+=8;let sn=It+St;if(_){if(St>0){let Lt=It;do{let Ln=e[Lt]===0?e[Lt+1]<<16|e[Lt+2]<<8|e[Lt+3]:yt(e,Lt);Lt+=4;let is=e[Lt],xs=mn?is>>1&63:is&31;if(mn?xs===39||xs===40:xs===6)yh(e.subarray(Lt,Lt+Ln),Vt,Ft,i.samples);Lt+=Ln}while(Lt<sn)}Ft+=nn}if(It=sn,it)Je=ns,bt=It}if(It<=c)ut=we;else{let ns=Kn,St=Le;for(let it=0;it<we;it++){let sn=he[St]===0?he[St+1]<<16|he[St+2]<<8|he[St+3]:yt(he,St);if(ns+=sn,ns>c)break;ut=it+1,St+=8}}if(_)i.timeOffset=Ft;if(Je!==-1&&bt<=c&&E.keyFrameIndex===void 0)E.keyFrameIndex=Je,E.keyFrameStart=tn+Je*N;if(ut){if(!lt(E.ptsMin)||tn<E.ptsMin)E.ptsMin=tn;let ns=tn+ut*N;if(!lt(E.ptsMax)||ns>E.ptsMax)E.ptsMax=ns}let Fn=N*we;oe=tn+Fn,ae+=Fn;continue}let Wt,hn;if(s){if(Wt=[],hn={sampleOffset:It,samples:Wt,defaultSampleDurationOffset:H},It<=c)E.trun.push(hn)}let zt;for(let tn=0;tn<we;tn++){let Kn;if(st){if(s)Kn=he.byteOffset-e.byteOffset+ft;te=yt(he,ft),ft+=4}else te=N;if(We)zt=yt(he,ft),ft+=4;else zt=V;let Le,Je;if(wt){if(Je=he[ft+1]&1?1:0,s)Le={isNonSync:Je,dependsOn:(he[ft]&3)===1?1:2};ft+=4}let bt=0;if(xt)bt=he[0]===0?yt(he,ft):Jg(he,ft),ft+=4;if(_){let ut=It,Ft=0;while(Ft<zt){let nn=yt(e,ut);if(ut+=4,v9(i.isHEVCFlavor,e[ut]))yh(e.subarray(ut,ut+nn),i.isHEVCFlavor?2:1,i.timeOffset+bt/i.timescale,i.samples);ut+=nn,Ft+=nn+4}i.timeOffset+=te/i.timescale}if(It+=zt,It<=c){if(hn&&Kn!==void 0)hn.lastSampleDurationOffset=Kn;if(Je===0&&E.keyFrameIndex===void 0)E.keyFrameIndex=tn,E.keyFrameStart=oe;let ut=oe+bt;if(!lt(E.ptsMin)||ut<E.ptsMin)E.ptsMin=ut;if(!lt(E.ptsMax)||ut+te>E.ptsMax)E.ptsMax=ut+te;if(Wt)Wt[tn]={cts:bt,duration:te,flags:Le,size:zt}}oe+=te,ae+=te}if(!ae&&N)ae+=N*we}if(E.duration+=ae,E.duration)o=!0}if(!o){let m=1/0,p=0,b=Ut(e,["sidx"]);for(let v=0;v<b.length;v++){let k=zT(b[v]);if(k!=null&&k.references){m=Math.min(m,k.earliestPresentationTime/k.timescale);let A=k.references.reduce((T,E)=>T+E.info.duration||0,0);p=Math.max(p,A+k.earliestPresentationTime/k.timescale)}}if(p&&lt(p))Object.keys(r).forEach((v)=>{if(!r[v].duration)r[v].duration=p*r[v].timescale-r[v].start})}return r}function ZT(e){let t={valid:null,remainder:null},n=Ut(e,["moof"]);if(n.length<2)return t.remainder=e,t;let s=n[n.length-1];return t.valid=e.slice(0,s.byteOffset-8),t.remainder=e.slice(s.byteOffset-8),t}function Rr(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function eE(e,t){let n=[],{samples:s,timescale:i,id:r}=t,o=!1;return Ut(s,["moof"]).map((c)=>{let h=c.byteOffset-8;Ut(c,["traf"]).map((m)=>{let p=Ut(m,["tfdt"]).map((b)=>{let v=b[0],k=yt(b,4);if(v===1)k*=Math.pow(2,32),k+=yt(b,8);return k/i})[0];if(p!==void 0)e=p;return Ut(m,["tfhd"]).map((b)=>{let v=yt(b,4),k=yt(b,0)&16777215,A=(k&1)!==0,T=0,E=(k&2)!==0,I=(k&8)!==0,_=0,q=(k&16)!==0,P=0,N=(k&32)!==0,H=!A&&(k&131072)!==0,V=8;if(v===r){if(A)T=yt(b,V),V+=4,T*=Math.pow(2,32),T+=yt(b,V),V+=4;else if(H)T=h;if(E)V+=4;if(I)_=yt(b,V),V+=4;if(q)P=yt(b,V),V+=4;if(N)V+=4;if(t.type==="video")o=jh(t.codec);Ut(m,["trun"]).map((U)=>{let W=U[0],ce=yt(U,0)&16777215,ue=(ce&1)!==0,oe=0,ae=(ce&4)!==0,te=(ce&256)!==0,me=0,he=(ce&512)!==0,we=0,be=(ce&1024)!==0,ye=(ce&2048)!==0,Te=0,Oe=yt(U,4),st=8;if(ue)oe=yt(U,st),st+=4;if(ae)st+=4;let We=T+oe;for(let wt=0;wt<Oe;wt++){if(te)me=yt(U,st),st+=4;else me=_;if(he)we=yt(U,st),st+=4;else we=P;if(be)st+=4;if(ye){if(W===0)Te=yt(U,st);else Te=Jg(U,st);st+=4}if(t.type===Zn.VIDEO){let xt=0;while(xt<we){let ft=yt(s,We);if(We+=4,v9(o,s[We])){let It=s.subarray(We,We+ft);yh(It,o?2:1,e+Te/i,n)}We+=ft,xt+=ft+4}}e+=me/i}})}})})}),n}function jh(e){if(!e)return!1;let t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function v9(e,t){if(e){let n=t>>1&63;return n===39||n===40}else return(t&31)===6}function yh(e,t,n,s){let i=S9(e),r=0;r+=t;let o=0,l=0,c=0;while(r<i.length){o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);l=0;do{if(r>=i.length)break;c=i[r++],l+=c}while(c===255);let h=i.length-r,d=r;if(l<h)r+=l;else if(l>h){Rn.error(`Malformed SEI payload. ${l} is too small, only ${h} bytes left to parse.`);break}if(o===4){if(i[d++]===181){let p=d9(i,d);if(d+=2,p===49){let b=yt(i,d);if(d+=4,b===1195456820){let v=i[d++];if(v===3){let k=i[d++],A=31&k,T=64&k,E=T?2+A*3:0,I=new Uint8Array(E);if(T){I[0]=k;for(let _=1;_<E;_++)I[_]=i[d++]}s.push({type:v,payloadType:o,pts:n,bytes:I})}}}}}else if(o===5){if(l>16){let m=[];for(let v=0;v<16;v++){let k=i[d++].toString(16);if(m.push(k.length==1?"0"+k:k),v===3||v===5||v===7||v===9)m.push("-")}let p=l-16,b=new Uint8Array(p);for(let v=0;v<p;v++)b[v]=i[d++];s.push({payloadType:o,pts:n,uuid:m.join(""),userData:KT(b),userDataBytes:b})}}}}function S9(e){let t=e.byteLength,n,s=e.indexOf(3,3);while(s!==-1){if(e[s-1]===0&&e[s-2]===0)(n||(n=[])).push(s);s=e.indexOf(3,s+1)}if(!n)return e;let i=t-n.length,r=new Uint8Array(i),o=0,l=0;for(let c=0;c<i;l++,c++){if(l===n[o])l++,o++;r[c]=e[l]}return r}function tE(e){let t=e[0],n="",s="",i=0,r=0,o,l=0,c=0,h=4;if(t===0){let m=yd(e,h),p=m!==null?yd(e,h+m.length):null;if(m!==null&&p!==null)n=m,s=p,h+=m.length+p.length,i=yt(e,h),h+=4,r=yt(e,h),h+=4,l=yt(e,h),h+=4,c=yt(e,h),h+=4;else Rn.warn(`Unterminated ${m===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=e.length}else if(t===1){i=yt(e,h),h+=4;let m=yt(e,h);h+=4;let p=yt(e,h);if(h+=4,o=4294967296*m+p,!lT(o))o=Number.MAX_SAFE_INTEGER,Rn.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");l=yt(e,h),h+=4,c=yt(e,h),h+=4;let b=yd(e,h),v=b!==null?yd(e,h+b.length):null;if(b!==null)n=b,h+=b.length;if(v!==null)s=v,h+=v.length;else Rn.warn(`Unterminated ${b===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${b===null?"strings and payload":"value and payload"}`),h=e.length}let d=e.subarray(h,e.byteLength);return{schemeIdUri:n,value:s,timeScale:i,presentationTime:o,presentationTimeDelta:r,eventDuration:l,id:c,payload:d}}function nE(e,...t){let n=t.length,s=8,i=n;while(i--)s+=t[i].byteLength;let r=new Uint8Array(s);r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(e,4);for(i=0,s=8;i<n;i++)r.set(t[i],s),s+=t[i].byteLength;return r}function sE(e,t,n){if(e.byteLength!==16)throw RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;if(s>0){if(r=new Uint8Array(4),t.length>0)new DataView(r.buffer).setUint32(0,t.length,!1)}else r=new Uint8Array;let o=new Uint8Array(4);if(n.byteLength>0)new DataView(o.buffer).setUint32(0,n.byteLength,!1);return nE([112,115,115,104],new Uint8Array([s,0,0,0]),e,r,i,o,n)}function k9(e){let t=[];if(e instanceof ArrayBuffer){let n=e.byteLength,s=0;while(s+32<n){let i=new DataView(e,s),r=rE(i);t.push(r),s+=r.size}}return t}function iE(e){let t=[];for(let n=0;n<e.length;){let s=e[n++],i=s&7;if(i===0){while(e[n++]&128);continue}if(i!==2){n+=i===1?8:4;continue}let r=0;for(let o=0,l=128;l&128;o+=7)r|=((l=e[n++])&127)<<o;if(s>>3===2){if(r===32){let o=new Uint8Array(16);for(let l=0;l<16;l++)o[l]=parseInt(String.fromCharCode(e[n+l*2],e[n+l*2+1]),16);t.push(o)}else if(r===16)t.push(e.subarray(n,n+16))}n+=r}return t}function rE(e){let t=e.getUint32(0),{byteOffset:n,byteLength:s}=e;if(s<t)return{offset:n,size:s};if(e.getUint32(4)!==1886614376)return{offset:n,size:t};let r=e.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:n,size:t};let o=e.buffer,l=Ys(new Uint8Array(o,n+12,16)),c=null,h=null,d=0;if(r===0)d=28;else{let p=e.getUint32(28);if(!p||s<32+p*16)return{offset:n,size:t};c=[];for(let b=0;b<p;b++)c.push(new Uint8Array(o,n+32+b*16,16));d=32+p*16}if(!d)return{offset:n,size:t};let m=e.getUint32(d);if(t-32<m)return{offset:n,size:t};if(h=new Uint8Array(o,n+d+4,m),r===0)c=iE(h);return{version:r,systemId:l,kids:c,data:h,offset:n,size:t}}var Zc=x9("userAgent"),aE=x9("vendor"),Ag,Tg,Eg;function x9(e){try{return navigator[e]||""}catch(t){}return""}function oE(){if(Eg===void 0){let e=Zc.match(/Safari\/(\d+)/i);Eg=e?parseInt(e[1]):0}return Eg}function lh(){if(Ag===void 0){let e=Zc.match(/Chrome\/(\d+)/i);Ag=e?parseInt(e[1]):0}return Ag}function lE(){if(Tg===void 0){let e=Zc.match(/Firefox\/(\d+)/i);Tg=e?parseInt(e[1]):0}return Tg}function A9(){return/\(Windows.+Firefox\//i.test(Zc)}function cE(){return aE.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Zc)}function fE(){return/Android/.test(Zc)}var Kc={audio:{a3ds:1,"ac-3":0.95,"ac-4":1,alac:0.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":0.9,enca:1,fLaC:0.9,flac:0.9,FLAC:0.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:0.8,dav1:0.8,drac:1,dva1:1,dvav:1,dvh1:0.7,dvhe:0.7,encv:1,hev1:0.75,hvc1:0.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:0.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function I1(e,t){let n=Kc[t];return!!n&&!!n[e.slice(0,4)]}function vh(e,t,n=!0){return!e.split(",").some((s)=>!R1(s,t,n))}function R1(e,t,n=!0){var s;let i=Zo(n);return(s=i==null?void 0:i.isTypeSupported(Sh(e,t)))!=null?s:!1}function Sh(e,t){return`${t}/mp4;codecs=${e}`}function O5(e){if(e){let t=e.substring(0,4);return Kc.video[t]}return 2}function Xd(e){let t=A9();return e.split(",").reduce((n,s)=>{let r=t&&jh(s)?9:Kc.video[s];if(r)return(r*2+n)/(n?3:2);return(Kc.audio[s]+n)/(n?2:1)},0)}var Cg={};function hE(e,t=!0){if(Cg[e])return Cg[e];let n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let i=0;i<n.length;i++){var s;if(R1(n[i],"audio",t))return Cg[e]=n[i],n[i];else if(n[i]==="mp3"&&(s=Zo(t))!=null&&s.isTypeSupported("audio/mpeg"))return""}return e}var uE=/flac|opus|mp4a\.40\.34/i;function Wd(e,t=!0){return e.replace(uE,(n)=>hE(n.toLowerCase(),t))}function dE(e,t){let n=[];if(e){let s=e.split(",");for(let i=0;i<s.length;i++)if(!I1(s[i],"video"))n.push(s[i])}if(t)n.push(t);return n.join(",")}function Fd(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)){if(P5(e,"audio")||P5(e,"video"))return e}if(t){let n=t.split(",");if(n.length>1){if(e){for(let s=n.length;s--;)if(n[s].substring(0,4)===e.substring(0,4))return n[s]}return n[0]}}return t||e}function P5(e,t){return I1(e,t)&&R1(e,t)}function mE(e){let t=e.split(",");for(let n=0;n<t.length;n++){let s=t[n].split(".");if(s.length>2&&s[0]==="avc1")t[n]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`}return t.join(",")}function pE(e){if(e.startsWith("av01.")){let t=e.split("."),n=["0","111","01","01","01","0"];for(let s=t.length;s>4&&s<10;s++)t[s]=n[s-4];return t.join(".")}return e}function N5(e){let t=Zo(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function e1(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var gE={supported:!0,powerEfficient:!0,smooth:!0},bE={supported:!1,smooth:!1,powerEfficient:!1},T9={supported:!0,configurations:[],decodingInfoResults:[gE]};function E9(e,t){return{supported:!1,configurations:t,decodingInfoResults:[bE],error:e}}function wE(e,t,n,s,i,r){let o=e.videoCodec,l=e.audioCodec?e.audioGroups:null,c=r==null?void 0:r.audioCodec,h=r==null?void 0:r.channels,d=h?parseInt(h):c?1/0:2,m=null;if(l!=null&&l.length)try{if(l.length===1&&l[0])m=t.groups[l[0]].channels;else m=l.reduce((p,b)=>{if(b){let v=t.groups[b];if(!v)throw Error(`Audio track group ${b} not found`);Object.keys(v.channels).forEach((k)=>{p[k]=(p[k]||0)+v.channels[k]})}return p},{2:0})}catch(p){return!0}return o!==void 0&&(o.split(",").some((p)=>jh(p))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(s,30)||e.videoRange!=="SDR"&&e.videoRange!==n||e.bitrate>Math.max(i,8000000))||!!m&&lt(d)&&Object.keys(m).some((p)=>parseInt(p)>d)}function C9(e,t,n,s={}){let i=e.videoCodec;if(!i&&!e.audioCodec||!n)return Promise.resolve(T9);let r=[],o=yE(e),l=o.length,c=vE(e,t,l>0),h=c.length;for(let d=l||1*h||1;d--;){let m={type:"media-source"};if(l)m.video=o[d%l];if(h){m.audio=c[d%h];let p=m.audio.bitrate;if(m.video&&p)m.video.bitrate-=p}r.push(m)}if(i){let d=navigator.userAgent;if(i.split(",").some((m)=>jh(m))&&A9())return Promise.resolve(E9(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),r))}return Promise.all(r.map((d)=>{let m=SE(d);return s[m]||(s[m]=n.decodingInfo(d))})).then((d)=>({supported:!d.some((m)=>!m.supported),configurations:r,decodingInfoResults:d})).catch((d)=>({supported:!1,configurations:r,decodingInfoResults:[],error:d}))}function yE(e){var t;let n=(t=e.videoCodec)==null?void 0:t.split(","),s=_9(e),i=e.width||640,r=e.height||480,o=e.frameRate||30,l=e.videoRange.toLowerCase();return n?n.map((c)=>{let h={contentType:Sh(pE(c),"video"),width:i,height:r,bitrate:s,framerate:o};if(l!=="sdr")h.transferFunction=l;return h}):[]}function vE(e,t,n){var s;let i=(s=e.audioCodec)==null?void 0:s.split(","),r=_9(e);if(i&&e.audioGroups)return e.audioGroups.reduce((o,l)=>{var c;let h=l?(c=t.groups[l])==null?void 0:c.tracks:null;if(h)return h.reduce((d,m)=>{if(m.groupId===l){let p=parseFloat(m.channels||"");i.forEach((b)=>{let v={contentType:Sh(b,"audio"),bitrate:n?j9(b,r):r};if(p)v.channels=""+p;d.push(v)})}return d},o);return o},[]);return[]}function j9(e,t){if(t<=1)return 1;let n=128000;if(e==="ec-3")n=768000;else if(e==="ac-3")n=640000;return Math.min(t/2,n)}function _9(e){return Math.ceil(Math.max(e.bitrate*0.9,e.averageBitrate)/1000)*1000||1}function SE(e){let t="",{audio:n,video:s}=e;if(s){let i=e1(s.contentType);t+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(n){let i=e1(n.contentType);t+=`${s?"_":""}${i}_c${n.channels}`}return t}function Qo(e,t,n){let s=encodeURIComponent(t),i=`${s}=${encodeURIComponent(n)}`,r=!1,o=[];if(e.search.substring(1).split("&").forEach((l)=>{if(l===s||l.startsWith(s+"=")){if(!r)o.push(i),r=!0}else if(l)o.push(l)}),!r)o.push(i);e.search=o.join("&")}var t1=["NONE","TYPE-0","TYPE-1",null];function kE(e){return t1.indexOf(e)>-1}var Yd=["SDR","PQ","HLG"];function xE(e){return!!e&&Yd.indexOf(e)>-1}var Ld={No:"",Yes:"YES",v2:"v2"};function B5(e){let{canSkipUntil:t,canSkipDateRanges:n,age:s}=e,i=s<t/2;if(t&&i){if(n)return Ld.v2;return Ld.Yes}return Ld.No}class n1{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){let t=new self.URL(e);if(this.msn!==void 0)Qo(t,"_HLS_msn",this.msn.toString());if(this.part!==void 0)Qo(t,"_HLS_part",this.part.toString());if(this.skip)Qo(t,"_HLS_skip",this.skip);return t.href}}class Yc{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details)this.details=e.details;if(this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e)this.imageCodec=e.imageCodec;if(this.codecSet=[e.videoCodec,e.audioCodec].filter((n)=>!!n).map((n)=>n.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let n=(t=e.supplemental)==null?void 0:t.videoCodec;if(n&&n!==e.videoCodec)this.codecSet+=`,${n.substring(0,4)}`}if("iframes"in e&&e.iframes)this.iframes=!0;else this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return H5(this._audioGroups,e)}hasSubtitleGroup(e){return H5(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(!t)return;if(e==="audio"){let n=this._audioGroups;if(!n)n=this._audioGroups=[];if(n.indexOf(t)===-1)n.push(t)}else if(e==="text"){let n=this._subtitleGroups;if(!n)n=this._subtitleGroups=[];if(n.indexOf(t)===-1)n.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function H5(e,t){if(!t||!e)return!1;return e.indexOf(t)!==-1}function AE(){if(typeof matchMedia==="function"){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function TE(e,t){let n=!1,s=[];if(e)n=e!=="SDR",s=[e];if(t){s=t.allowedVideoRanges||Yd.slice(0);let i=s.join("")!=="SDR"&&!t.videoCodec;if(n=t.preferHDR!==void 0?t.preferHDR:i&&AE(),!n)s=["SDR"]}return{preferHDR:n,allowedVideoRanges:s}}var EE=(e)=>{let t=new WeakSet;return(n,s)=>{if(e)s=e(n,s);if(typeof s==="object"&&s!==null){if(t.has(s))return;t.add(s)}return s}},ls=(e,t)=>JSON.stringify(e,EE(t));function CE(e,t,n,s,i){let r=Object.keys(e),o=s==null?void 0:s.channels,l=s==null?void 0:s.audioCodec,c=i==null?void 0:i.videoCodec,h=o&&parseInt(o)===2,d=!1,m=!1,p=1/0,b=1/0,v=1/0,k=1/0,A=0,T=[],{preferHDR:E,allowedVideoRanges:I}=TE(t,i);for(let H=r.length;H--;){let V=e[r[H]];if(d||(d=V.channels[2]>0),p=Math.min(p,V.minHeight),b=Math.min(b,V.minFramerate),v=Math.min(v,V.minBitrate),I.filter((W)=>V.videoRanges[W]>0).length>0)m=!0}p=lt(p)?p:0,b=lt(b)?b:0;let _=Math.max(1080,p),q=Math.max(30,b);if(v=lt(v)?v:n,n=Math.max(v,n),!m)t=void 0;let P=r.length>1;return{codecSet:r.reduce((H,V)=>{let U=e[V];if(V===H)return H;if(T=m?I.filter((W)=>U.videoRanges[W]>0):[],P){if(U.minBitrate>n)return va(V,`min bitrate of ${U.minBitrate} > current estimate of ${n}`),H;if(!U.hasDefaultAudio)return va(V,"no renditions with default or auto-select sound found"),H;if(l&&V.indexOf(l.substring(0,4))%5!==0)return va(V,`audio codec preference "${l}" not found`),H;if(o&&!h){if(!U.channels[o])return va(V,`no renditions with ${o} channel sound found (channels options: ${Object.keys(U.channels)})`),H}else if((!l||h)&&d&&U.channels["2"]===0)return va(V,"no renditions with stereo sound found"),H;if(U.minHeight>_)return va(V,`min resolution of ${U.minHeight} > maximum of ${_}`),H;if(U.minFramerate>q)return va(V,`min framerate of ${U.minFramerate} > maximum of ${q}`),H;if(!T.some((W)=>U.videoRanges[W]>0))return va(V,`no variants with VIDEO-RANGE of ${ls(T)} found`),H;if(c&&V.indexOf(c.substring(0,4))%5!==0)return va(V,`video codec preference "${c}" not found`),H;if(U.maxScore<A)return va(V,`max score of ${U.maxScore} < selected max of ${A}`),H}if(H&&(Xd(V)>=Xd(H)||U.fragmentError>e[H].fragmentError))return H;return k=U.minIndex,A=U.maxScore,V},void 0),videoRanges:T,preferHDR:E,minFramerate:b,minBitrate:v,minIndex:k}}function va(e,t){Rn.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function I9(e){return e.reduce((t,n)=>{let s=t.groups[n.groupId];if(!s)s=t.groups[n.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1};s.tracks.push(n);let i=n.channels||"2";if(s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||n.default,s.hasAutoSelect=s.hasAutoSelect||n.autoselect,s.hasDefault)t.hasDefaultAudio=!0;if(s.hasAutoSelect)t.hasAutoSelectAudio=!0;return t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function jE(e,t,n,s){return e.slice(n,s+1).reduce((i,r,o)=>{if(!r.codecSet)return i;let l=r.audioGroups,c=i[r.codecSet];if(!c)i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{"2":0},hasDefaultAudio:!l,fragmentError:0};c.minBitrate=Math.min(c.minBitrate,r.bitrate);let h=Math.min(r.height,r.width);if(c.minHeight=Math.min(c.minHeight,h),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,l)l.forEach((d)=>{if(!d)return;let m=t.groups[d];if(!m)return;c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach((p)=>{c.channels[p]=(c.channels[p]||0)+m.channels[p]})});return i},{})}function U5(e){if(!e)return e;let{lang:t,assocLang:n,characteristics:s,channels:i,audioCodec:r}=e;return{lang:t,assocLang:n,characteristics:s,channels:i,audioCodec:r}}function ja(e,t,n){if("attrs"in e){let s=t.indexOf(e);if(s!==-1)return s}for(let s=0;s<t.length;s++){let i=t[s];if(Nl(e,i,n))return s}return-1}function Nl(e,t,n){let{groupId:s,name:i,lang:r,assocLang:o,default:l}=e,c=e.forced;return(s===void 0||t.groupId===s)&&(i===void 0||t.name===i)&&(r===void 0||_E(r,t.lang))&&(o===void 0||t.assocLang===o)&&(l===void 0||t.default===l)&&(c===void 0||t.forced===c)&&(!("characteristics"in e)||IE(e.characteristics||"",t.characteristics))&&(n===void 0||n(e,t))}function _E(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}function IE(e,t=""){let n=e.split(","),s=t.split(",");return n.length===s.length&&!n.some((i)=>s.indexOf(i)===-1)}function Pl(e,t){let{audioCodec:n,channels:s}=e;return(n===void 0||(t.audioCodec||"").substring(0,4)===n.substring(0,4))&&(s===void 0||s===(t.channels||"2"))}function RE(e,t,n,s,i){let r=t[s],l=t.reduce((p,b,v)=>{let k=b.uri;return(p[k]||(p[k]=[])).push(v),p},{})[r.uri];if(l.length>1)s=Math.max.apply(Math,l);let{videoRange:c,frameRate:h}=r,d=r.codecSet.substring(0,4),m=z5(t,s,(p)=>{if(p.videoRange!==c||p.frameRate!==h||p.codecSet.substring(0,4)!==d)return!1;let b=p.audioGroups,v=n.filter((k)=>kh(k.groupId,b));return ja(e,v,i)>-1});if(m>-1)return m;return z5(t,s,(p)=>{let b=p.audioGroups,v=n.filter((k)=>kh(k.groupId,b));return ja(e,v,i)>-1})}function z5(e,t,n){for(let s=t;s>-1;s--)if(n(e[s]))return s;for(let s=t+1;s<e.length;s++)if(n(e[s]))return s;return-1}function Jd(e,t){var n;return!!e&&e!==((n=t.loadLevelObj)==null?void 0:n.uri)}function kh(e,t){if(!t)return!0;return t.indexOf(e)!==-1}function R9(e,t){if(t||e){let n=Gn({},t);if(e){if(e.videoCodec)n.videoCodec=e.videoCodec;if(e.videoRange)n.allowedVideoRanges=[e.videoRange]}return n}}class D9 extends Ji{constructor(e){super("abr",e.logger);this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=(t)=>{var n;let{fragCurrent:s,partCurrent:i,hls:r}=this;if(!r)return;let{autoLevelEnabled:o,media:l}=r;if(!s||!l)return;let c=performance.now(),h=i?i.stats:s.stats,d=i?i.duration:s.duration,m=c-h.loading.start,p=r.minAutoLevel,b=s.level,v=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||b<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let k=v>-1&&v!==b,A=!!t||k;if(!A&&(l.paused||!l.playbackRate||!l.readyState))return;let T=r.mainForwardBufferInfo;if(!A&&T===null)return;let E=this.bwEstimator.getEstimateTTFB(),I=Math.abs(l.playbackRate);if(m<=Math.max(E,1000*(d/(I*2))))return;let _=T?T.len/I:0,q=h.loading.first?h.loading.first-h.loading.start:-1,P=h.loaded&&q>-1,N=this.getBwEstimate(),H=r.levels,V=H[b],U=Math.max(h.loaded,Math.round(d*(s.bitrate||V.averageBitrate)/8)),W=P?m-q:m;if(W<1&&P)W=Math.min(m,h.loaded*8/N);let ce=P?h.loaded*1000/W:0,ue=E/1000,oe=ce?(U-h.loaded)/ce:U*8/N+ue;if(oe<=_)return;let ae=ce?ce*8:N,te=((n=(t==null?void 0:t.details)||r.latestLevelDetails)==null?void 0:n.live)===!0,me=r.config.abrBandWidthUpFactor,he=Number.POSITIVE_INFINITY,we;for(we=b-1;we>p;we--){let Oe=H[we].maxBitrate,st=!H[we].details||te;if(he=this.getTimeToLoadFrag(ue,ae,d*Oe,st),he<Math.min(_,d+ue))break}if(he>=oe)return;if(he>d*10)return;if(P)this.bwEstimator.sample(m-Math.min(E,q),h.loaded);else this.bwEstimator.sampleTTFB(m);let be=H[we].maxBitrate;if(this.getBwEstimate()*me>be)this.firstAutoFloor=Math.min(we,r.firstLevel),this.resetEstimator(be);let ye=this.findBestLevel(be,p,we,0,_,1,1);if(ye>-1)we=ye;this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${b} is loading too slowly;
13
- Fragment duration: ${s.duration.toFixed(3)}
14
- Time to underbuffer: ${_.toFixed(3)} s
15
- Estimated load time for current fragment: ${oe.toFixed(3)} s
16
- Estimated load time for down switch fragment: ${he.toFixed(3)} s
17
- TTFB estimate: ${q|0} ms
18
- Current BW estimate: ${lt(N)?N|0:"Unknown"} bps
19
- New BW estimate: ${this.getBwEstimate()|0} bps
20
- Switching to level ${we} @ ${be|0} bps`),r.nextLoadLevel=r.nextAutoLevel=we,this.clearTimer();let Te=()=>{this.clearTimer();let Oe=this.hls;if(this.fragCurrent===s&&Oe.loadLevel===we&&we>0){let st=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${we>0?"and switching down":""}
21
- Fragment duration: ${s.duration.toFixed(3)} s
22
- Time to underbuffer: ${st.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,we>p){let We=this.findBestLevel(Oe.levels[p].bitrate,p,we,0,st,1,1);if(We===-1)We=p;Oe.nextLoadLevel=Oe.nextAutoLevel=We,this.firstAutoFloor=Math.min(We,Oe.firstLevel),this.resetEstimator(Oe.levels[We].bitrate)}}};if(k||oe>he*2)Te();else this.timer=self.setInterval(Te,he*1000);r.trigger(O.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){if(!this.hls)return;if(e)this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e;this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new i9(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.FRAG_LOADING,this.onFragLoading,this),e.on(O.FRAG_LOADED,this.onFragLoaded,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this),e.on(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(O.LEVEL_LOADED,this.onLevelLoaded,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(O.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;if(!e)return;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.FRAG_LOADING,this.onFragLoading,this),e.off(O.FRAG_LOADED,this.onFragLoaded,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this),e.off(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(O.LEVEL_LOADED,this.onLevelLoaded,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(O.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(O.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){if(this.lastLoadedFragLevel>-1&&this.fragCurrent)this.lastLoadedFragLevel=this.fragCurrent.level;this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let n=t.frag;if(this.ignoreFragment(n))return;if(!n.bitrateTest){var s;this.fragCurrent=n,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(t.fatal)return;switch(t.details){case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ve.FRAG_LOAD_TIMEOUT:{let n=t.frag,{fragCurrent:s,partCurrent:i}=this;if(n&&Kg(n,s)){let r=performance.now(),o=i?i.stats:n.stats,l=r-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){let d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,n,s){let i=e+n/t,r=s?e+this.lastLevelLoadSec:0;return i+r}onLevelLoaded(e,t){let n=this.hls.config,{loading:s}=t.stats,i=s.end-s.first;if(lt(i))this.lastLevelLoadSec=i/1000;if(t.details.live)this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive);else this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD);if(this.timer>-1)this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var n;let{frag:s,part:i}=t,r=i?i.stats:s.stats;if(s.type===kt.MAIN)this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start);if(this.ignoreFragment(s))return;if(this.clearTimer(),s.level===this._nextAutoLevel)this._nextAutoLevel=-1;if(this.firstSelection=-1,(n=this.hls)!=null&&n.config.abrMaxWithRealBitrate){let o=i?i.duration:s.duration,l=this.hls.levels[s.level],c=(l.loaded?l.loaded.bytes:0)+r.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:c,duration:h},l.realBitrate=Math.round(8*c/h)}if(s.bitrateTest){let o={stats:r,frag:s,part:i,id:s.type};this.onFragBuffered(O.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}onFragBuffered(e,t){let{frag:n,part:s}=t,i=s!=null&&s.stats.loaded?s.stats:n.stats;if(i.aborted)return;if(this.ignoreFragment(n))return;let o=((n.bitrate||0)>=1e5?i.parsing.end:i.loading.end)-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());if(this.bwEstimator.sample(o,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest)this.bitrateTestDelay=o/1000;else if(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate())this.firstAutoFloor=-1}ignoreFragment(e){return e.type!==kt.MAIN||e.sn==="initSegment"}clearTimer(){if(this.timer>-1)self.clearInterval(this.timer),this.timer=-1}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:n}=e,s=this.getBwEstimate(),i=this.getStarvationDelay(),r=e.config.maxStarvationDelay,o=this.findBestLevel(s,n,t,i/2,r,1,1);if(o>-1)return o;let l=e.firstLevel,c=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,h=Math.min(Math.max(l,n),t,c);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${h}`),h}get forcedAutoLevel(){if(this.nextAutoLevelKey)return-1;return this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let i=n&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let r=this.hls.levels;if(r.length>Math.max(e,i)&&r[e].loadError<=r[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:n}=this;if(!n)return-1;if(n.levels.length<=1)return n.loadLevel;let{maxAutoLevel:s,config:i,minAutoLevel:r}=n,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay(),{abrBandWidthFactor:h,abrBandWidthUpFactor:d}=i;if(c){let k=this.findBestLevel(l,r,s,c,0,h,d);if(k>=0)return this.rebufferNotice=-1,k}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){let k=this.bitrateTestDelay;if(k)m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-k,this.info(`bitrate test took ${Math.round(1000*k)}ms, set first fragment max fetchDuration to ${Math.round(1000*m)} ms`),h=d=1}let p=this.findBestLevel(l,r,s,c,m,h,d);if(this.rebufferNotice!==p)this.rebufferNotice=p,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${p}`);if(p>-1)return p;let b=n.levels[r],v=n.loadLevelObj;if(v&&(b==null?void 0:b.bitrate)<v.bitrate)return r;return n.loadLevel}getStarvationDelay(){let e=this.hls,t=e==null?void 0:e.media;if(!t)return 1/0;let n=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/n}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,n,s,i,r,o){let{hls:l,lastLoadedFragLevel:c,fragCurrent:h,partCurrent:d}=this;if(!l)return-1;let m=s+i,p=c===-1?l.firstLevel:c,{levels:b,allAudioTracks:v,loadLevel:k,latestLevelDetails:A,config:T}=l;if(b.length===1)return 0;let E=b[p],I=!!(A!=null&&A.live),_=k===-1||c===-1,q,P="SDR",N=(E==null?void 0:E.frameRate)||0,{audioPreference:H,videoPreference:V}=T,U=this.audioTracksByGroup||(this.audioTracksByGroup=I9(v)),W=-1;if(_){if(this.firstSelection!==-1)return this.firstSelection;let te=this.codecTiers||(this.codecTiers=jE(b,U,t,n)),me=CE(te,P,e,H,V),{codecSet:he,videoRanges:we,minFramerate:be,minBitrate:ye,minIndex:Te,preferHDR:Oe}=me;W=Te,q=he,P=Oe?we[we.length-1]:we[0],N=be,e=Math.max(e,ye),this.log(`picked start tier ${ls(me)}`)}else q=E==null?void 0:E.codecSet,P=E==null?void 0:E.videoRange;let ce=d?d.duration:h?h.duration:0,ue=this.bwEstimator.getEstimateTTFB()/1000,oe=[];for(let te=n;te>=t;te--){var ae;let me=b[te],he=te>p;if(!me)continue;if(T.useMediaCapabilities&&!me.supportedResult&&!me.supportedPromise){let We=navigator.mediaCapabilities;if(typeof(We==null?void 0:We.decodingInfo)==="function"&&wE(me,U,P,N,e,H))me.supportedPromise=C9(me,U,We,this.supportedCache),me.supportedPromise.then((wt)=>{if(!this.hls)return;me.supportedResult=wt;let xt=this.hls.levels,ft=xt.indexOf(me);if(wt.error)this.warn(`MediaCapabilities decodingInfo error: "${wt.error}" for level ${ft} ${ls(wt)}`);else if(!wt.supported){if(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ft} ${ls(wt)}`),ft>-1&&xt.length>1){if(this.log(`Removing unsupported level ${ft}`),this.hls.removeLevel(ft),this.hls.loadLevel===-1)this.hls.nextLoadLevel=0}}else if(wt.decodingInfoResults.some((It)=>It.smooth===!1||It.powerEfficient===!1))this.log(`MediaCapabilities decodingInfo for level ${ft} not smooth or powerEfficient: ${ls(wt)}`)}).catch((wt)=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${wt}`)});else me.supportedResult=T9}if(q&&me.codecSet!==q||P&&me.videoRange!==P||he&&N>me.frameRate||!he&&N>0&&N<me.frameRate||(ae=me.supportedResult)!=null&&(ae=ae.decodingInfoResults)!=null&&ae.some((We)=>We.smooth===!1)){if(!_||te!==W){oe.push(te);continue}}let we=me.details,be=(d?we==null?void 0:we.partTarget:we==null?void 0:we.averagetargetduration)||ce||1,ye;if(!he)ye=r*e;else ye=o*e;let Te=ce&&s>=ce*2&&i===0?me.averageBitrate:me.maxBitrate,Oe=this.getTimeToLoadFrag(ue,ye,Te*be,!we||we.live);if(ye>=Te&&(te===c||me.loadError===0&&me.fragmentError===0||s9(me,T.errorPenaltyExpireMs))&&(Oe<=ue||!lt(Oe)||I&&!this.bitrateTestDelay||Oe<m)){let We=this.forcedAutoLevel;if(te!==k&&(We===-1||We!==k)){if(oe.length)this.trace(`Skipped level(s) ${oe.join(",")} of ${n} max with CODECS and VIDEO-RANGE:"${b[oe[0]].codecs}" ${b[oe[0]].videoRange}; not compatible with "${q}" ${P}`);this.info(`switch candidate:${p}->${te} adjustedbw(${Math.round(ye)})-bitrate=${Math.round(ye-Te)} ttfb:${ue.toFixed(1)} avgDuration:${be.toFixed(1)} maxFetchDuration:${m.toFixed(1)} fetchDuration:${Oe.toFixed(1)} firstSelection:${_} codecSet:${me.codecSet} videoRange:${me.videoRange} hls.loadLevel:${k}`)}if(_)this.firstSelection=te;return te}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);if(this._nextAutoLevel!==t)this.nextAutoLevelKey="",this._nextAutoLevel=t}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),t)}}var q9={search:function(e,t){let n=0,s=e.length-1,i=null,r=null;while(n<=s){i=(n+s)/2|0,r=e[i];let o=t(r);if(o>0)n=i+1;else if(o<0)s=i-1;else return r}return null}};function DE(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!lt(t))return null;let s=e[0].programDateTime;if(t<(s||0))return null;let i=e[e.length-1].endProgramDateTime;if(t>=(i||0))return null;for(let r=0;r<e.length;++r){let o=e[r];if(ME(t,n,o))return o}return null}function Qc(e,t,n=0,s=0,i=0.005){let r=null;if(e){r=t[1+e.sn-t[0].sn]||null;let l=e.endDTS-n;if(l>0&&l<0.0000015)n+=0.0000015;if(r&&e.level!==r.level&&r.end<=e.end)r=t[2+e.sn-t[0].sn]||null}else if(n===0&&t[0].start===0)r=t[0];if(r&&((!e||e.level===r.level)&&G5(n,s,r)===0||qE(r,e,Math.min(i,s))))return r;let o=q9.search(t,G5.bind(null,n,s));if(o&&(o!==e||!r))return o;return r}function qE(e,t,n){if((t==null?void 0:t.start)===0&&t.level<e.level&&(t.endPTS||0)>0){let s=t.tagList.reduce((i,r)=>{if(r[0]==="INF")i+=parseFloat(r[1]);return i},n);return e.start<=s}return!1}function G5(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let s=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));if(n.start+n.duration-s<=e)return 1;else if(n.start-s>e&&n.start)return-1;return 0}function ME(e,t,n){let s=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1000;return(n.endProgramDateTime||0)-s>e}function M9(e,t,n){if(e){if(e.startCC<=t&&e.endCC>=t){let s=e.fragments,{fragmentHint:i}=e;if(i)s=s.concat(i);let r;return q9.search(s,(o)=>{if(o.cc<t)return 1;if(o.cc>t)return-1;if(r=o,o.end<=n)return 1;if(o.start>n)return-1;return 0}),r||null}}return null}function F9(e,t){if(t===e.endSN&&e.fragmentHint)return e.fragmentHint;return e.fragments[1+t-e.startSN]||null}var gi={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},pi={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class L9 extends Ji{constructor(e){super("error-controller",e.logger);this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(O.ERROR,this.onError,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;if(!e)return;e.off(O.ERROR,this.onError,this),e.off(O.ERROR,this.onErrorOut,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.LEVEL_UPDATED,this.onLevelUpdated,this)}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){if((e==null?void 0:e.type)===kt.MAIN)return e.level;return this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,n=t.currentLevel;if((e=t.loadLevelObj)!=null&&e.details||n===-1)return t.loadLevel;return n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;let s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter((r)=>s.indexOf(r.groupId)>=0).some((r)=>{var o;return(o=r.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let s=this.hls,i=t.context;switch(t.details){case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case ve.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=hh();return}case ve.FRAG_GAP:case ve.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=gi.SendAlternateToPenaltyBox;return}case ve.PLAYLIST_UNCHANGED_ERROR:case ve.LEVEL_EMPTY_ERROR:case ve.LEVEL_PARSING_ERROR:{var r;let o=t.parent===kt.MAIN?t.level:s.loadLevel;if(t.details===ve.LEVEL_EMPTY_ERROR&&!!((r=t.context)!=null&&(r=r.levelDetails)!=null&&r.live))t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o);else t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o)}return;case ve.LEVEL_LOAD_ERROR:case ve.LEVEL_LOAD_TIMEOUT:if(typeof(i==null?void 0:i.level)==="number")t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level);return;case ve.AUDIO_TRACK_LOAD_ERROR:case ve.AUDIO_TRACK_LOAD_TIMEOUT:case ve.SUBTITLE_LOAD_ERROR:case ve.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let o=s.loadLevelObj;if(o&&(i.type===fn.AUDIO_TRACK&&o.hasAudioGroup(i.groupId)||i.type===fn.SUBTITLE_TRACK&&o.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=gi.SendAlternateToPenaltyBox,t.errorAction.flags=pi.MoveAllAlternatesMatchingHost;return}}return;case ve.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:gi.SendAlternateToPenaltyBox,flags:pi.MoveAllAlternatesMatchingHDCP};return;case ve.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ve.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ve.KEY_SYSTEM_NO_SESSION:t.errorAction={action:gi.SendAlternateToPenaltyBox,flags:pi.MoveAllAlternatesMatchingKey};return;case ve.BUFFER_ADD_CODEC_ERROR:case ve.REMUX_ALLOC_ERROR:case ve.BUFFER_APPEND_ERROR:if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,t.level);return;case ve.MEDIA_SOURCE_REQUIRES_RESET:if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,t.level);t.errorAction.flags|=pi.ResetMediaSource|pi.SwitchToSDR;return;case ve.INTERNAL_EXCEPTION:case ve.BUFFER_APPENDING_ERROR:case ve.BUFFER_APPEND_NO_PROGRESS:case ve.BUFFER_FULL_ERROR:case ve.LEVEL_SWITCH_ERROR:case ve.BUFFER_STALLED_ERROR:case ve.BUFFER_SEEK_OVER_HOLE:case ve.BUFFER_NUDGE_ON_STALL:t.errorAction=hh();return}if(t.type===Et.KEY_SYSTEM_ERROR)t.levelRetry=!1,t.errorAction=hh()}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,s=I5(n.config.playlistLoadPolicy,e),i=this.playlistError++;if(gh(s,i,Gd(e),e.response))return{action:gi.RetryRequest,flags:pi.None,retryConfig:s,retryCount:i};let o=this.getLevelSwitchAction(e,t);if(s)o.retryConfig=s,o.retryCount=i;return o}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),s=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:r}=t.config,o=I5(t9(e)?r:i,e),l=t.levels.reduce((h,d)=>h+d.fragmentError,0);if(s){if(e.details!==ve.FRAG_GAP)s.fragmentError++;if(!n9(e)){if(gh(o,l,Gd(e),e.response))return{action:gi.RetryRequest,flags:pi.None,retryConfig:o,retryCount:l}}}let c=this.getLevelSwitchAction(e,n);if(o)c.retryConfig=o,c.retryCount=l;return c}getLevelSwitchAction(e,t){let n=this.hls;if(t===null||t===void 0)t=n.loadLevel;let s=this.hls.levels[t];if(s){var i,r;let c=e.details;if(s.loadError++,s.loadErrorTime=self.performance.now(),c===ve.BUFFER_APPEND_ERROR)s.fragmentError++;let h=-1,{levels:d,loadLevel:m,minAutoLevel:p,maxAutoLevel:b}=n;if(!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError)n.loadLevel=-1;let v=(i=e.frag)==null?void 0:i.type,A=(v===kt.AUDIO&&c===ve.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&V5(e))&&d.some(({audioCodec:q})=>s.audioCodec!==q),E=e.sourceBufferName==="video"&&V5(e)&&d.some(({codecSet:q,audioCodec:P})=>s.codecSet!==q&&s.audioCodec===P),{type:I,groupId:_}=(r=e.context)!=null?r:{};for(let q=d.length;q--;){let P=(q+m)%d.length;if(P!==m&&P>=p&&P<=b&&(d[P].loadError===0||s9(d[P],n.config.errorPenaltyExpireMs))){var o,l;let N=d[P];if(c===ve.FRAG_GAP&&v===kt.MAIN&&e.frag){let H=d[P].details;if(H){let V=Qc(e.frag,H.fragments,e.frag.start);if(V!=null&&V.gap)continue}}else if(I===fn.AUDIO_TRACK&&N.hasAudioGroup(_)||I===fn.SUBTITLE_TRACK&&N.hasSubtitleGroup(_))continue;else if(v===kt.AUDIO&&(o=s.audioGroups)!=null&&o.some((H)=>N.hasAudioGroup(H))||v===kt.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some((H)=>N.hasSubtitleGroup(H))||A&&s.audioCodec===N.audioCodec||E&&s.codecSet===N.codecSet||!A&&s.audioCodec!==N.audioCodec)continue;h=P;break}}if(h>-1&&n.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:gi.SendAlternateToPenaltyBox,flags:pi.None,nextAutoLevel:h}}return{action:gi.SendAlternateToPenaltyBox,flags:pi.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var n,s;switch((n=t.errorAction)==null?void 0:n.action){case gi.DoNothing:break;case gi.SendAlternateToPenaltyBox:if(this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==ve.FRAG_GAP&&t.details!==ve.PLAYLIST_UNCHANGED_ERROR&&!O9(t))t.fatal=!0;break;case gi.RetryRequest:break}if((((s=t.errorAction)==null?void 0:s.flags)||0)&pi.ResetMediaSource)this.hls.recoverMediaError();if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let s=n.nextAutoLevel;if(n.flags===pi.None)this.switchLevel(e,s);else if(n.flags&pi.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let c=l;c--;)if(o[c].videoRange!=="SDR")o[c].fragmentError++,o[c].loadError++;else if(s===void 0)s=c}else if(n.flags&pi.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],c=l==null?void 0:l.attrs["HDCP-LEVEL"];n.hdcpLevel=c;let h=c==="NONE";if(c&&!h)t.maxHdcpLevel=t1[t1.indexOf(c)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);else{if(h)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");n.flags|=pi.MoveAllAlternatesMatchingKey}}if(n.flags&pi.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,c=l.length;for(let d=c;d--;)if(this.variantHasKey(l[d],o)){var i,r;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(i=l[d].audioGroups)==null?void 0:i.join(",")}" (${(r=e.frag)==null?void 0:r.type} fragment) ${Ys(o.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}let h=e.frag;if(this.hls.levels.length<c)n.resolved=!0;else if(h&&h.type!==kt.MAIN){let d=h.decryptdata;if(d&&!o.matches(d))n.resolved=!0}}}if(!n.resolved)this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction){if(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ve.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo"){let n=e1(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)if(s[i][`${e.sourceBufferName}Codec`]===n)this.log(`Removing level ${i} for ${e.details} ("${n}" not supported)`),this.hls.removeLevel(i)}}}}function V5(e){let t=e.details;if(t===ve.BUFFER_ADD_CODEC_ERROR||t===ve.MEDIA_SOURCE_REQUIRES_RESET)return!0;if(t===ve.BUFFER_APPEND_ERROR){if(!O9(e))return!0}return!1}function O9(e){return e.details===ve.BUFFER_APPEND_ERROR&&(e.error.name==="QuotaExceededError"||e.error.name==="InvalidStateError")}function hh(e){let t={action:gi.DoNothing,flags:pi.None};if(e)t.resolved=!0;return t}var Ss={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class P9{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=0.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;if(e)e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.BUFFER_APPENDED,this.onBufferAppended,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this),e.on(O.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;if(e)e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.BUFFER_APPENDED,this.onBufferAppended,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this),e.off(O.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let s=n.length;s--;){let i=n[s];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,n){let{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){let o=s[i[r]];if((o==null?void 0:o.body.type)===t&&(!n||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,n,s,i,r){if(this.timeRanges)this.timeRanges[e]=t;let o=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((l)=>{let c=this.fragments[l];if(!c||!this.hls)return;let h=c.body;if(o>=h.sn)return;if(!c.buffered&&(!c.loaded||r)){if(h.type===n)this.removeFragment(h);return}let d=c.range[e];if(!d)return;if(d.time.length===0){this.removeFragment(h);return}if(d.time.some((m)=>{let p=!this.isTimeBuffered(m.startPTS,m.endPTS,t);if(p)this.removeFragment(h);return p}),s&&s!==h&&lh()){let m=s.endPTS,p=h.startPTS;if(m&&p&&c.range.video){let b=p-m;if(b<0&&b>-0.1)this.removeFragment(h),this.hls.trigger(O.BUFFER_FLUSHING,{startOffset:m+0.004,endOffset:1/0,type:"video"})}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:n,part:s,id:i}=e;if(!t||!js(n))return;let r=Bc(n),o=this.fragments[r];if(!o||o.buffered&&n.gap)return;let l=!n.relurl;Object.keys(t).forEach((h)=>{let d=n.elementaryStreams[h];if(!d)return;let m=t[h],p=l||d.partial===!0;o.range[h]=this.getBufferedTimes(n,s,p,m),this.detectEvictedFragments(h,m,i,n,s)}),o.loaded=null;let c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,n),!kd(o))this.removeParts(n.sn-1,n.type);if(!s){let h=Math.min(0.004,n.duration);c.some((d)=>{var m;let p=(m=o.range[d])==null?void 0:m.time,b=p.length===0||p.length===1&&p[0].endPTS-p[0].startPTS<h;if(b)this.addAsGap(n);return b})}}else this.removeFragment(n)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){if(e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap)this.endListFragments[e.body.type]=e}removeParts(e,t){let n=this.activePartLists[t];if(!n)return;this.activePartLists[t]=$5(n,(s)=>s.fragment.sn>=e)}fragBuffered(e,t){let n=Bc(e),s=this.fragments[n];if(!s&&t){if(s=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap)this.hasGaps=!0}if(s)s.loaded=null,this.bufferedEnd(s,e);return s}getBufferedTimes(e,t,n,s){let i={time:[],partial:n},{start:r,end:o}=e,l=e.minEndPTS||o,c=e.maxStartPTS||r;for(let h=0;h<s.length;h++){let d=s.start(h)-this.bufferPadding,m=s.end(h)+this.bufferPadding;if(c>=d&&l<=m){i.time.push({startPTS:Math.max(r,s.start(h)),endPTS:Math.min(o,s.end(h))});break}else if(r<m&&o>d){let p=Math.max(r,s.start(h)),b=Math.min(o,s.end(h));if(b>p)i.partial=!0,i.time.push({startPTS:p,endPTS:b})}else if(o<=d)break}return i}getPartialFragment(e){let t=null,n,s,i,r=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach((c)=>{let h=l[c];if(!h)return;if(kd(h)){if(s=h.body.start-o,i=h.body.end+o,e>=s&&e<=i){if(n=Math.min(e-s,i-e),r<=n)t=h.body,r=n}}}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||kd(t))}getState(e){let t=Bc(e),n=this.fragments[t];if(n)if(!n.buffered)return Ss.APPENDING;else if(kd(n))return Ss.PARTIAL;else return Ss.OK;return Ss.NOT_LOADED}isTimeBuffered(e,t,n){let s,i;for(let r=0;r<n.length;r++){if(s=n.start(r)-this.bufferPadding,i=n.end(r)+this.bufferPadding,e>=s&&t<=i)return!0;if(t<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!js(t.frag)||t.frag.bitrateTest)return;let n=t.frag,s=t.part?null:t,i=Bc(n);this.fragments[i]={body:n,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:s,timeRanges:i}=t;if(!js(n))return;let r=n.type;if(s){let o=this.activePartLists[r];if(!o)this.activePartLists[r]=o=[];o.push(s)}this.timeRanges=i}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Bc(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let s=n.length;s--;){let i=t[n[s]];if((i==null?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,n){let{fragments:s}=this,i=0,r=0,o=Object.keys(s);for(let l=0;l<o.length;l++){let c=s[o[l]];if(!c||!c.buffered||c.body.type!==t)continue;let h=c.body;if(h.gap)return 0;let d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&h.bitrate*8*h.duration;if(h.end<=e&&d){if(i+=d,r=Math.max(r,h.end),i>=n)return r}}return r>0?r:0}removeFragmentsInRange(e,t,n,s,i){if(s&&!this.hasGaps)return;Object.keys(this.fragments).forEach((r)=>{let o=this.fragments[r];if(!o)return;let l=o.body;if(l.type!==n||s&&!l.gap)return;if(l.start<t&&l.end>e&&(o.buffered||i))this.removeFragment(l)})}removeFragment(e){let t=Bc(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let s=e.sn;this.activePartLists[e.type]=$5(n,(i)=>i.fragment.sn!==s)}if(delete this.fragments[t],e.endList)delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;if(t)t.forEach((n)=>n.clearElementaryStreamInfo())}}function kd(e){var t,n,s,i;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(s=e.range.audiovideo)!=null&&s.partial||(i=e.range.subs)!=null&&i.partial)}function Bc(e){return`${e.type}_${e.level}_${e.sn}`}function $5(e,t){return e.filter((n)=>{let s=t(n);if(!s)n.clearElementaryStreamInfo();return s})}var tl={cbc:0,ctr:1};class N9{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case tl.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tl.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function FE(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);if(n)return e.slice(0,t-n);return e}class B9{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let s=0;s<4;s++)n[s]=t.getUint32(s*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,s=n[0],i=n[1],r=n[2],o=n[3],l=this.invSubMix,c=l[0],h=l[1],d=l[2],m=l[3],p=new Uint32Array(256),b=0,v=0,k=0;for(k=0;k<256;k++)if(k<128)p[k]=k<<1;else p[k]=k<<1^283;for(k=0;k<256;k++){let A=v^v<<1^v<<2^v<<3^v<<4;A=A>>>8^A&255^99,e[b]=A,t[A]=b;let T=p[b],E=p[T],I=p[E],_=p[A]*257^A*16843008;if(s[b]=_<<24|_>>>8,i[b]=_<<16|_>>>16,r[b]=_<<8|_>>>24,o[b]=_,_=I*16843009^E*65537^T*257^b*16843008,c[A]=_<<24|_>>>8,h[A]=_<<16|_>>>16,d[A]=_<<8|_>>>24,m[A]=_,!b)b=v=1;else b=T^p[p[p[I^T]]],v^=p[p[v]]}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,s=0;while(s<t.length&&n)n=t[s]===this.key[s],s++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error("Invalid aes key size="+i);let r=this.ksRows=(i+6+1)*4,o,l,c=this.keySchedule=new Uint32Array(r),h=this.invKeySchedule=new Uint32Array(r),d=this.sBox,m=this.rcon,p=this.invSubMix,b=p[0],v=p[1],k=p[2],A=p[3],T,E;for(o=0;o<r;o++){if(o<i){T=c[o]=t[o];continue}if(E=T,o%i===0)E=E<<8|E>>>24,E=d[E>>>24]<<24|d[E>>>16&255]<<16|d[E>>>8&255]<<8|d[E&255],E^=m[o/i|0]<<24;else if(i>6&&o%i===4)E=d[E>>>24]<<24|d[E>>>16&255]<<16|d[E>>>8&255]<<8|d[E&255];c[o]=T=(c[o-i]^E)>>>0}for(l=0;l<r;l++){if(o=r-l,l&3)E=c[o];else E=c[o-4];if(l<4||o<=4)h[l]=E;else h[l]=b[d[E>>>24]]^v[d[E>>>16&255]]^k[d[E>>>8&255]]^A[d[E&255]];h[l]=h[l]>>>0}}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let s=this.keySize+6,i=this.invKeySchedule,r=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],d=o[3],m=this.uint8ArrayToUint32Array_(n),p=m[0],b=m[1],v=m[2],k=m[3],A=new Int32Array(e),T=new Int32Array(A.length),E,I,_,q,P,N,H,V,U,W,ce,ue,oe,ae,te=this.networkToHostOrderSwap;while(t<A.length){U=te(A[t]),W=te(A[t+1]),ce=te(A[t+2]),ue=te(A[t+3]),P=U^i[0],N=ue^i[1],H=ce^i[2],V=W^i[3],oe=4;for(ae=1;ae<s;ae++)E=l[P>>>24]^c[N>>16&255]^h[H>>8&255]^d[V&255]^i[oe],I=l[N>>>24]^c[H>>16&255]^h[V>>8&255]^d[P&255]^i[oe+1],_=l[H>>>24]^c[V>>16&255]^h[P>>8&255]^d[N&255]^i[oe+2],q=l[V>>>24]^c[P>>16&255]^h[N>>8&255]^d[H&255]^i[oe+3],P=E,N=I,H=_,V=q,oe=oe+4;E=r[P>>>24]<<24^r[N>>16&255]<<16^r[H>>8&255]<<8^r[V&255]^i[oe],I=r[N>>>24]<<24^r[H>>16&255]<<16^r[V>>8&255]<<8^r[P&255]^i[oe+1],_=r[H>>>24]<<24^r[V>>16&255]<<16^r[P>>8&255]<<8^r[N&255]^i[oe+2],q=r[V>>>24]<<24^r[P>>16&255]<<16^r[N>>8&255]<<8^r[H&255]^i[oe+3],T[t]=te(E^p),T[t+1]=te(q^b),T[t+2]=te(_^v),T[t+3]=te(I^k),p=U,b=W,v=ce,k=ue,t=t+4}return T.buffer}}class H9{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=LE(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function LE(e){switch(e){case tl.cbc:return"AES-CBC";case tl.ctr:return"AES-CTR";default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var OE=16;class d0{constructor(e,t){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,t!==!0)try{let n=self.crypto;if(n)this.subtle=n.subtle||n.webkitSubtle}catch(n){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);this.reset();let s=this.decryptRange;if(s){if(s.start===0&&s.end>=n.length)return n;return n.slice(s.start,s.end)}return FE(n)}reset(){if(this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter)this.softwareDecrypter=null}decrypt(e,t,n,s,i){if(this.decryptRange=i,this.useSoftware||i)return new Promise((r,o)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,n,s);let c=this.flush();if(c)r(c.buffer);else o(Error("[softwareDecrypt] Failed to decrypt data"))});return this.webCryptoDecrypt(new Uint8Array(e),t,n,s)}softwareDecrypt(e,t,n,s){let{currentIV:i,currentResult:r,remainderData:o}=this;if(s!==tl.cbc||t.byteLength!==16)return Rn.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;if(this.logOnce("JS AES decrypt"),o)e=Rr(o,e),this.remainderData=null;let l=this.getValidChunk(e);if(!l.length)return null;if(i)n=i;let c=this.softwareDecrypter;if(!c)c=this.softwareDecrypter=new B9;c.expandKey(t);let h=r;if(this.currentResult=c.decrypt(l.buffer,0,n),this.currentIV=l.slice(-16).buffer,!h)return null;return h}webCryptoDecrypt(e,t,n,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,s));this.key=t,this.fastAesKey=new H9(this.subtle,t,s)}return this.fastAesKey.expandKey().then((i)=>{if(!this.subtle)return Promise.reject(Error("web crypto not initialized"));return this.logOnce("WebCrypto AES decrypt"),new N9(this.subtle,new Uint8Array(n),s).decrypt(e.buffer,i)}).catch((i)=>(Rn.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,s)))}onWebCryptoError(e,t,n,s){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,s);let r=this.flush();if(r)return r.buffer}throw Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,n=e.length-e.length%OE;if(n!==e.length)t=e.slice(0,n),this.remainderData=e.slice(n);return t}logOnce(e){if(!this.logEnabled)return;Rn.log(`[decrypter]: ${e}`),this.logEnabled=!1}}var X5=Math.pow(2,17);class s1{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){if(this.loader)this.loader.destroy(),this.loader=null}abort(){if(this.loader)this.loader.abort()}load(e,t,n,s){let i=e.url;if(!i)return Promise.reject(new sa({type:Et.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,{fLoader:o,loader:l}=r;return new Promise((c,h)=>{if(this.loader)this.loader.destroy();if(e.gap)if(e.tagList.some((k)=>k[0]==="GAP")){h(K5(e));return}else e.gap=!1;let d=this.loader=o?new o(r):new l(r),m=W5(e,null,t);e.loader=d;let p=R5(r.fragLoadPolicy.default),b={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:X5};d.stats.retry=e.stats.retry,e.stats=d.stats;let v={onSuccess:(k,A,T,E)=>{this.resetLoader(e,d);let I=k.data;if(T.resetIV&&e.decryptdata)e.decryptdata.iv=new Uint8Array(I.slice(0,16)),I=I.slice(16);c({frag:e,part:null,payload:I,networkDetails:E})},onError:(k,A,T,E)=>{this.resetLoader(e,d),h(new sa({type:Et.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Ct({url:i,data:void 0},k),error:Error(`HTTP Error ${k.code} ${k.text}`),networkDetails:T,stats:E}))},onAbort:(k,A,T)=>{this.resetLoader(e,d),h(new sa({type:Et.NETWORK_ERROR,details:ve.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:T,stats:k}))},onTimeout:(k,A,T)=>{this.resetLoader(e,d),h(new sa({type:Et.NETWORK_ERROR,details:ve.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${b.timeout}ms`),networkDetails:T,stats:k}))}};if(n){let k=this.gateProgress(n,s);v.onProgress=(A,T,E,I)=>k({frag:e,part:null,payload:E,networkDetails:I})}d.load(m,b,v)})}gateProgress(e,t){let n=e;if(t){let s=[],i=!1;t.then(()=>{i=!0,s.forEach((r)=>e(r)),s.length=0}).catch(()=>{}),n=(r)=>{if(i)e(r);else s.push(r)}}return n}loadPart(e,t,n){this.abort();let s=this.config,{fLoader:i,loader:r}=s;return new Promise((o,l)=>{if(this.loader)this.loader.destroy();if(e.gap||t.gap){l(K5(e,t));return}let c=this.loader=i?new i(s):new r(s),h=W5(e,t);e.loader=c;let d=R5(s.fragLoadPolicy.default),m={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:X5};t.stats=c.stats,c.load(h,m,{onSuccess:(p,b,v,k)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let A={frag:e,part:t,payload:p.data,networkDetails:k};n(A),o(A)},onError:(p,b,v,k)=>{this.resetLoader(e,c),l(new sa({type:Et.NETWORK_ERROR,details:ve.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Ct({url:h.url,data:void 0},p),error:Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:v,stats:k}))},onAbort:(p,b,v)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new sa({type:Et.NETWORK_ERROR,details:ve.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:v,stats:p}))},onTimeout:(p,b,v)=>{this.resetLoader(e,c),l(new sa({type:Et.NETWORK_ERROR,details:ve.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${m.timeout}ms`),networkDetails:v,stats:p}))}})})}updateStatsFromPart(e,t){let n=e.stats,s=t.stats,i=s.total;if(n.loaded+=s.loaded,i){let l=Math.round(e.duration/t.duration),c=Math.min(Math.round(n.loaded/i),l),d=(l-c)*Math.round(n.loaded/c);n.total=n.loaded+d}else n.total=Math.max(n.loaded,n.total);let r=n.loading,o=s.loading;if(r.start)r.first+=o.first-o.start;else r.start=o.start,r.first=o.first;r.end=o.end}resetLoader(e,t){if(e.loader=null,e.url=null,this.loader===t)self.clearTimeout(this.partLoadTimeout),this.loader=null;t.destroy()}}function W5(e,t=null,n){let s=t||e,i={type:fn.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Zd(e,t,n);if(r.resetIV)i.resetIV=!0;if(r.byteRange)i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end;return i}function Zd(e,t=null,n){let s={},i=t||e,{byteRangeStartOffset:r,byteRangeEndOffset:o}=i;if(lt(r)&&lt(o)){var l;if((e.sn==="initSegment"||n)&&PE((l=e.decryptdata)==null?void 0:l.method)){let c=Math.floor(r/16)*16,h=Math.ceil(o/16)*16;if(s.decryptRange={start:r-c,end:o-c},c>=16)s.resetIV=!0,c=c-16;s.byteRange={start:c,end:h}}else s.byteRange={start:r,end:o}}return s}function K5(e,t){let n=Error(`GAP ${e.gap?"tag":"attribute"} found`),s={type:Et.MEDIA_ERROR,details:ve.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};if(t)s.part=t;return(t?t:e).stats.aborted=!0,new sa(s)}function PE(e){return e==="AES-128"||e==="AES-256"}class sa extends Error{constructor(e){super(e.error.message);this.data=void 0,this.data=e}}class D1 extends Ji{constructor(e,t){super(e,t);this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){if(!this._tickInterval)return this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0;return!1}clearInterval(){if(this._tickInterval)return self.clearInterval(this._tickInterval),this._tickInterval=null,!0;return!1}clearNextTick(){if(this._tickTimer)return self.clearTimeout(this._tickTimer),this._tickTimer=null,!0;return!1}tick(){if(this._tickCallCount++,this._tickCallCount===1){if(this.doTick(),this._tickCallCount>1)this.tickImmediate();this._tickCallCount=0}else this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class m0{constructor(e,t,n,s=0,i=-1,r=!1,o,l,c){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=xd(),this.buffering={audio:xd(),video:xd(),audiovideo:xd()},this.level=e,this.sn=t,this.id=n,this.size=s,this.part=i,this.partial=r,this.duration=o||0,this.decryptRange=c,this.iframe=l||!1}}function xd(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Y5={length:0,start:()=>0,end:()=>0};class qt{static isBuffered(e,t){if(e){let n=qt.getBuffered(e);for(let s=n.length;s--;)if(t>=n.start(s)&&t<=n.end(s))return!0}return!1}static bufferedRanges(e){if(e){let t=qt.getBuffered(e);return qt.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let n=0;n<e.length;n++)t.push({start:e.start(n),end:e.end(n)});return t}static bufferInfo(e,t,n){if(e){let s=qt.bufferedRanges(e);if(s.length)return qt.bufferedInfo(s,t,n)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,n){if(t=Math.max(0,t),e.length>1)e.sort((h,d)=>h.start-d.start||d.end-h.end);let s=-1,i=[];if(n)for(let h=0;h<e.length;h++){if(t>=e[h].start&&t<=e[h].end)s=h;let d=i.length;if(d){let m=i[d-1].end;if(e[h].start-m<n){if(e[h].end>m)i[d-1].end=e[h].end}else i.push(e[h])}else i.push(e[h])}else i=e;let r=0,o,l=t,c=t;for(let h=0;h<i.length;h++){let d=i[h].start,m=i[h].end;if(s===-1&&t>=d&&t<=m)s=h;if(t+n>=d&&t<m)l=d,c=m,r=c-t;else if(t+n<d){o=d;break}}return{len:r,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||Y5}catch(t){return Rn.log("failed to get media.buffered",t),Y5}}}var i1=/\{\$([a-zA-Z0-9-_]+)\}/g;function Q5(e){return i1.lastIndex=0,i1.test(e)}function q1(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(i1,(s)=>{let i=s.substring(2,s.length-1),r=n==null?void 0:n[i];if(r===void 0)return e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s;return r})}return t}function J5(e,t,n){let s=e.variableList;if(!s)e.variableList=s={};let i,r;if("QUERYPARAM"in t){i=t.QUERYPARAM;try{let o=new self.URL(n).searchParams;if(o.has(i))r=o.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(o){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else i=t.NAME,r=t.VALUE;if(i in s)e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`));else s[i]=r||""}function NE(e,t,n){let s=t.IMPORT;if(n&&s in n){let i=e.variableList;if(!i)e.variableList=i={};i[s]=n[s]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var BE=/^(\d+)x(\d+)$/,Z5=/(.+?)=(".*?"|.*?)(?:,|$)/g;class vs{constructor(e,t){if(typeof e==="string")e=vs.parseAttrList(e,t);Gn(this,e)}get clientAttrs(){return Object.keys(this).filter((e)=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);if(t>Number.MAX_SAFE_INTEGER)return 1/0;return t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let n=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)n[s]=parseInt(t.slice(s*2,s*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);if(t>Number.MAX_SAFE_INTEGER)return 1/0;return t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((s,i)=>(s[i.toLowerCase()]=!0,s),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=BE.exec(this[e]);if(t===null)return;return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,s={},i='"';Z5.lastIndex=0;while((n=Z5.exec(e))!==null){let r=n[1].trim(),o=n[2],l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1,c=!1;if(l)o=o.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=q1(t,o);else if(!c&&!l)switch(r){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Rn.warn(`${e}: attribute ${r} is missing quotes`)}s[r]=o}return s}}var HE="com.apple.hls.interstitial";function UE(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function zE(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}class M1{constructor(e,t,n=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(s=t==null?void 0:t.tagOrder)!=null?s:n,t){let i=t.attr;for(let r in i)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==i[r]){Rn.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=Gn(new vs({}),i,e)}if(this.attr=e,t)this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd;else this._startDate=new Date(e["START-DATE"]);if("END-DATE"in e){let i=(t==null?void 0:t.endDate)||new Date(e["END-DATE"]);if(lt(i.getTime()))this._endDate=i}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;if(e===void 0)return this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1});return e}get startTime(){let{tagAnchor:e}=this;if(e===null||e.programDateTime===null)return Rn.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN;return e.start+(this.startDate.getTime()-e.programDateTime)/1000}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;if(t!==null)return this._dateAtEnd=new Date(this._startDate.getTime()+t*1000);return null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(lt(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1000;return null}get plannedDuration(){if("PLANNED-DURATION"in this.attr)return this.attr.decimalFloatingPoint("PLANNED-DURATION");return null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===HE}get isValid(){return!!this.id&&!this._badValueForSameId&&lt(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr))}get invalidReason(){if(!this.id)return"Missing ID";if(this._badValueForSameId)return`Date range ${this._badValueForSameId} mismatch`;if(!lt(this.startDate.getTime()))return"Date range invalid start date";if(this.isInterstitial&&!(("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr)))return"Interstitial Date range missing X-ASSET-(LIST|URI)";if(!this.isValid)return"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)";return null}}var U9=10;class z9{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;if(this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.updated||this.advanced)this.misses=0;else this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some((t)=>{let n=t.decryptdata;if(!n)t.setKeyFormat(e.keyFormat),n=t.decryptdata;return!!n&&e.matches(n)})}get hasProgramDateTime(){if(this.fragments.length)return lt(this.fragments[this.fragments.length-1].programDateTime);return!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||U9}get drift(){let e=this.driftEndTime-this.driftStartTime;if(e>0)return(this.driftEnd-this.driftStart)*1000/e;return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].end;return this.fragmentEnd}get fragmentEnd(){if(this.fragments.length)return this.fragments[this.fragments.length-1].end;return 0}get fragmentStart(){if(this.fragments.length)return this.fragments[0].start;return 0}get age(){if(this.advancedDateTime)return Math.max(Date.now()-this.advancedDateTime,0)/1000;return 0}get lastPartIndex(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].index;return-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let n=e.length;n--;)if(e[n].index>t)return e[n].index;return t}}return 0}get lastPartSn(){var e;if((e=this.partList)!=null&&e.length)return this.partList[this.partList.length-1].fragment.sn;return this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function e0(e,t){if(e.length===t.length)return!e.some((n,s)=>n!==t[s]);return!1}function e3(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;return e0(e,t)}function $c(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function F1(e){switch(e){case"AES-128":case"AES-256":return tl.cbc;case"AES-256-CTR":return tl.ctr;default:throw Error(`invalid full segment method ${e}`)}}function r1(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(t)=>t.charCodeAt(0))}function GE(e){let t=r1(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function G9(e){let t=function(s,i,r){let o=s[i];s[i]=s[r],s[r]=o};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function V9(e){let t=e.split(":"),n=null;if(t[0]==="data"&&t.length===2){let s=t[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){let r=i[0]==="base64",o=i[1];if(r)s.splice(-1,1),n=_1(o);else n=GE(o)}}return n}var t0=typeof self<"u"?self:void 0,gs={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ji={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ad(e){switch(e){case ji.FAIRPLAY:return gs.FAIRPLAY;case ji.PLAYREADY:return gs.PLAYREADY;case ji.WIDEVINE:return gs.WIDEVINE;case ji.CLEARKEY:return gs.CLEARKEY}}var $9={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function jg(e){switch(e){case gs.FAIRPLAY:return ji.FAIRPLAY;case gs.PLAYREADY:return ji.PLAYREADY;case gs.WIDEVINE:return ji.WIDEVINE;case gs.CLEARKEY:return ji.CLEARKEY}}function Jf(e){let{drmSystems:t,widevineLicenseUrl:n}=e,s=t?[gs.FAIRPLAY,gs.WIDEVINE,gs.PLAYREADY,gs.CLEARKEY].filter((i)=>!!t[i]):[];if(!s[gs.WIDEVINE]&&n)s.push(gs.WIDEVINE);return s}var X9=function(e){if(t0!=null&&(e=t0.navigator)!=null&&e.requestMediaKeySystemAccess)return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);else return null}();function VE(e,t,n,s){let i;switch(e){case gs.FAIRPLAY:i=["cenc","sinf"];break;case gs.WIDEVINE:case gs.PLAYREADY:i=["cenc"];break;case gs.CLEARKEY:i=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return $E(i,t,n,s)}function $E(e,t,n,s){return[{initDataTypes:e,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map((r)=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:n.map((r)=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function XE(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some((n)=>n==="persistent-license")))}function L1(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=ia(t),s=n.substring(n.indexOf("<"),n.length),o=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(o){let l=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(l){let c=_1(l).subarray(0,16);return G9(c),c}}return null}var Hc={};class ho{static clearKeyUriToKeyIdMap(){Hc={}}static setKeyIdForUri(e,t){Hc[e]=t}static addKeyIdForUri(e){let t=Object.keys(Hc).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),Hc[e]=n,n}constructor(e,t,n,s=[1],i=null,r){if(this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=s,this.iv=i,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!$c(e),r!=null&&r.startsWith("0x"))this.keyId=new Uint8Array(h9(r))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&e0(e.keyFormatVersions,this.keyFormatVersions)&&e3(e.iv,this.iv)&&e3(e.keyId,this.keyId)}isSupported(){if(this.method){if($c(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";else switch(this.keyFormat){case ji.FAIRPLAY:case ji.WIDEVINE:case ji.PLAYREADY:case ji.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var n;if(!this.encrypted||!this.uri)return null;if($c(this.method)){let r=this.iv;if(!r){if(typeof e!=="number")Rn.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0;r=KE(e)}return new ho(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){let r=Hc[this.uri];if(r&&!e0(this.keyId,r))ho.setKeyIdForUri(this.uri,this.keyId);if(this.pssh)return this}let s=V9(this.uri);if(s)switch(this.keyFormat){case ji.WIDEVINE:if(this.pssh=s,!this.keyId){let r=k9(s.buffer).filter((o)=>o.systemId===$9.WIDEVINE);if(r.length){var i;let o=r[0];this.keyId=(i=o.kids)!=null&&i.length?o.kids[0]:null}}if(!this.keyId)this.keyId=t3(t);break;case ji.PLAYREADY:{let r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=sE(r,null,s),this.keyId=L1(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){let o=new Uint8Array(16);o.set(r,16-r.length),r=o}this.keyId=r;break}}if(((n=this.keyId)==null?void 0:n.byteLength)!==16){let r;if(r=WE(t),!r){if(r=t3(t),!r)r=Hc[this.uri]}if(r)this.keyId=r,ho.setKeyIdForUri(this.uri,r)}return this}}function WE(e){let t=e==null?void 0:e[ji.WIDEVINE];if(t)return t.keyId;return null}function t3(e){let t=e==null?void 0:e[ji.PLAYREADY];if(t){let n=V9(t.uri);if(n)return L1(n)}return null}function KE(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var n3=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,s3=/#EXT-X-MEDIA:(.*)/g,QE=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ig=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ZE=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class _a{static findGroup(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t)return s}}static resolve(e,t){return A1.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return QE.test(e)}static parseMasterPlaylist(e,t){let n=Q5(e),s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:n},i=[];if(n3.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=Error("no EXTM3U delimiter"),s;let r;while((r=n3.exec(e))!=null)if(r[1]){let l=new vs(r[1],s),c=i3(l,r[2],t,s,i);if(c)s.levels.push(c)}else if(r[3]){let l=r[3],c=r[4];switch(l){case"I-FRAME-STREAM-INF":{let h=new vs(c,s),d=i3(h,h.URI,t,s,i,!0);if(d)s.iframeVariants.push(d)}break;case"SESSION-DATA":{let h=new vs(c,s),d=h["DATA-ID"];if(d){if(s.sessionData===null)s.sessionData={};s.sessionData[d]=h}break}case"SESSION-KEY":{let h=r3(c,t,s);if(h.encrypted&&h.isSupported()){if(s.sessionKeys===null)s.sessionKeys=[];s.sessionKeys.push(h)}else Rn.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{let h=new vs(c,s);J5(s,h,t)}break}case"CONTENT-STEERING":{let h=new vs(c,s);s.contentSteering={uri:_a.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=a3(c);break}}}let o=i.length>0&&i.length<s.levels.length;if(s.levels=o?i:s.levels,s.levels.length===0)s.playlistParsingError=Error("no levels found in manifest");return s}static parseMasterPlaylistMedia(e,t,n){let s,i={},r=n.levels,o={AUDIO:r.map((c)=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:r.map((c)=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]},l=0;s3.lastIndex=0;while((s=s3.exec(e))!==null){let c=new vs(s[1],n),h=c.TYPE;if(h){let d=o[h],m=i[h]||[];i[h]=m;let p=c.LANGUAGE,b=c["ASSOC-LANGUAGE"],{CHANNELS:v,CHARACTERISTICS:k}=c,A=c["INSTREAM-ID"],T={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||p||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:p,url:c.URI?_a.resolve(c.URI,t):""};if(b)T.assocLang=b;if(v)T.channels=v;if(k)T.characteristics=k;if(A)T.instreamId=A;if(d!=null&&d.length){let E=_a.findGroup(d,T.groupId)||d[0];l3(T,E,"audioCodec"),l3(T,E,"textCodec")}m.push(T)}}return i}static parseLevelPlaylist(e,t,n,s,i,r){var o;let l={url:t},c=new z9(t),h=c.fragments,d=[],m=null,p=0,b=0,v=0,k=0,A=0,T=null,E=new ih(s,l),I,_,q,P=-1,N=!1,H=null,V;if(Ig.lastIndex=0,c.m3u8=e,c.hasVariableRefs=Q5(e),((o=Ig.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=Error("Missing format identifier #EXTM3U"),c;while((I=Ig.exec(e))!==null){if(N){if(N=!1,E=new ih(s,l),E.playlistOffset=v,E.setStart(v),E.sn=p,E.cc=k,A)E.bitrate=A;if(E.level=n,m){if(E.initSegment=m,m.rawProgramDateTime)E.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null;if(H)E.setByteRange(H),H=null}}let oe=I[1];if(oe){E.duration=parseFloat(oe);let ae=(" "+I[2]).slice(1);E.title=ae||null,E.tagList.push(ae?["INF",oe,ae]:["INF",oe])}else if(I[3]){if(lt(E.duration)){var U;if(E.playlistOffset=v,E.setStart(v),q)f3(E,q,c);E.sn=p,E.level=n,E.cc=k;let ae=(" "+I[3]).slice(1);E.relurl=q1(c,ae),a1(E,T,d),T=E,v+=E.duration,p++,b=0;let te=E.byteRange;if(te.length===2)E.bitrate=(te[1]-te[0])*8/E.duration|0;if(c.iframesOnly&&te[0]&&((U=m)==null?void 0:U.cc)!==k){let me=new ih(s,l);if(me.relurl=E.relurl,me.setByteRange(`${Math.min(te[0],1316)}@0`),me.level=n,me.sn="initSegment",q){if(me.levelkeys=q,q.identity)me._decryptdata=q.identity.getDecryptData(0)}m=me,E.initSegment=m}h.push(E),N=!0}}else{if(I=I[0].match(ZE),!I){Rn.warn("No matches on slow regex match for level playlist!");continue}for(_=1;_<I.length;_++)if(I[_]!==void 0)break;let ae=(" "+I[_]).slice(1),te=(" "+I[_+1]).slice(1),me=I[_+2]?(" "+I[_+2]).slice(1):null;switch(ae){case"BYTERANGE":if(T)E.setByteRange(te,T);else E.setByteRange(te);break;case"PROGRAM-DATE-TIME":if(E.rawProgramDateTime=te,E.tagList.push(["PROGRAM-DATE-TIME",te]),P===-1)P=h.length;break;case"PLAYLIST-TYPE":if(c.type)lo(c,ae,I);c.type=te.toUpperCase();break;case"MEDIA-SEQUENCE":if(c.startSN!==0)lo(c,ae,I);else if(T!==null)nC(c,ae,I);c.startSN=parseInt(te),p=c.startSN+c.skippedSegments;break;case"SKIP":{if(c.skippedSegments)lo(c,ae,I);let he=new vs(te,c),we=he.decimalInteger("SKIPPED-SEGMENTS");if(lt(we)){c.skippedSegments+=we;for(let ye=we;ye--;)h.push(null);p+=we}let be=he.enumeratedString("RECENTLY-REMOVED-DATERANGES");if(be)c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(be.split("\t"));break}case"TARGETDURATION":if(c.targetduration!==0)lo(c,ae,I);c.targetduration=Math.max(parseInt(te),1);break;case"VERSION":if(c.version!==null)lo(c,ae,I);c.version=parseInt(te);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":if(!c.live)lo(c,ae,I);c.live=!1;break;case"#":if(te||me)E.tagList.push(me?[te,me]:[te]);break;case"DISCONTINUITY":k++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([ae]);break;case"BITRATE":if(E.tagList.push([ae,te]),A=parseInt(te)*1000,lt(A))E.bitrate=A;else A=0;break;case"DATERANGE":{let he=new vs(te,c),we=new M1(he,c.dateRanges[he.ID],c.dateRangeTagCount);if(c.dateRangeTagCount++,we.isValid||c.skippedSegments)c.dateRanges[we.id]=we;else Rn.log(`Ignoring invalid DATERANGE tag: ${we.invalidReason}: ${te}`);E.tagList.push(["EXT-X-DATERANGE",te]);break}case"DEFINE":{{let he=new vs(te,c);if("IMPORT"in he)NE(c,he,r);else J5(c,he,t)}break}case"DISCONTINUITY-SEQUENCE":if(c.startCC!==0)lo(c,ae,I);c.startCC=k=parseInt(te),h.forEach((he)=>he&&(he.cc=k));break;case"KEY":{let he=r3(te,t,c);if(he.isSupported()){if(he.method==="NONE"){q=void 0;break}if(!q)q={};let we=q[he.keyFormat];if(!(we!=null&&we.matches(he))){if(we)q=Gn({},q);q[he.keyFormat]=he}}else Rn.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${te}"`);break}case"START":c.startTimeOffset=a3(te);break;case"MAP":{let he=new vs(te,c);if(E.duration){let we=new ih(s,l);if(c3(we,he,n,q),m=we,E.initSegment=m,m.rawProgramDateTime&&!E.rawProgramDateTime)E.rawProgramDateTime=m.rawProgramDateTime}else{let we=E.byteRangeEndOffset;if(we){let be=E.byteRangeStartOffset;H=`${we-be}@${be}`}else H=null;c3(E,he,n,q),m=E,N=!0}m.cc=k;break}case"SERVER-CONTROL":{if(V)lo(c,ae,I);V=new vs(te),c.canBlockReload=V.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=V.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&V.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=V.optionalFloat("PART-HOLD-BACK",0),c.holdBack=V.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{if(c.partTarget)lo(c,ae,I);let he=new vs(te);c.partTarget=he.decimalFloatingPoint("PART-TARGET");break}case"PART":{let he=c.partList;if(!he)he=c.partList=[];let we=b>0?he[he.length-1]:void 0,be=b++,ye=new vs(te,c),Te=new Z3(ye,E,l,be,we);he.push(Te),E.duration+=Te.duration;break}case"PRELOAD-HINT":{let he=new vs(te,c);c.preloadHint=he;break}case"RENDITION-REPORT":{let he=new vs(te,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(he);break}default:Rn.warn(`line parsed but not handled: ${I}`);break}}}if(T&&!T.relurl){if(h.pop(),v-=T.duration,c.partList)c.fragmentHint=T}else if(c.partList){if(a1(E,T,d),E.cc=k,c.fragmentHint=E,q)f3(E,q,c)}if(!c.targetduration)c.playlistParsingError=Error("Missing Target Duration");let W=h.length,ce=h[0],ue=h[W-1];if(v+=c.skippedSegments*c.targetduration,v>0&&W&&ue){c.averagetargetduration=v/W;let oe=ue.sn;if(c.endSN=oe!=="initSegment"?oe:0,!c.live)ue.endList=!0;if(P>0){if(tC(h,P,P>W-1?E:null),ce)d.unshift(ce)}}if(c.fragmentHint)v+=c.fragmentHint.duration;if(c.totalduration=v,d.length&&c.dateRangeTagCount&&ce)W9(d,c);return c.endCC=k,c}}function i3(e,t,n,s,i,r){var o;if(t===void 0)return null;let l=q1(s,t),c={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:_a.resolve(l,n)},h=e.decimalResolution("RESOLUTION");if(h)c.width=h.width,c.height=h.height;o3(e.CODECS,c);let d=e["SUPPLEMENTAL-CODECS"];if(d)c.supplemental={},o3(d,c.supplemental);if(!((o=c.unknownCodecs)!=null&&o.length))i.push(c);if(r)c.iframes=!0;return c}function W9(e,t){let n=e.length;if(!n)if(t.hasProgramDateTime){let l=t.fragments[t.fragments.length-1];e.push(l),n++}else return;let s=e[n-1],i=t.live?1/0:t.totalduration,r=Object.keys(t.dateRanges);for(let l=r.length;l--;){let c=t.dateRanges[r[l]],h=c.startDate.getTime();c.tagAnchor=s.ref;for(let d=n;d--;){var o;if(((o=e[d])==null?void 0:o.sn)<t.startSN)break;let m=eC(t,h,e,d,i);if(m){c.tagAnchor=m.ref;break}}}}function eC(e,t,n,s,i){let r=n[s];if(r){let l=r.programDateTime;if(t>=l||s===0){var o;let c=(((o=n[s+1])==null?void 0:o.start)||i)-r.start;if(t<=l+c*1000){let h=r.sn-e.startSN,d=e.fragments;if(h>=0&&h<d.length){if(d.length>n.length){let m=n[s+1]||d[d.length-1],p=Math.min(m.sn-e.startSN,d.length-1);for(let b=p;b>h;b--){let v=d[b].programDateTime;if(t>=v&&t<v+d[b].duration*1000)return d[b]}}return d[h]}}}}return null}function r3(e,t,n){var s,i;let r=new vs(e,n),o=(s=r.METHOD)!=null?s:"",l=r.URI,c=r.hexadecimalInteger("IV"),h=r.KEYFORMATVERSIONS,d=(i=r.KEYFORMAT)!=null?i:"identity";if(l&&r.IV&&!c)Rn.error(`Invalid IV: ${r.IV}`);let m=l?_a.resolve(l,t):"",p=(h?h:"1").split("/").map(Number).filter(Number.isFinite);return new ho(o,m,d,p,c,r.KEYID)}function a3(e){let n=new vs(e).decimalFloatingPoint("TIME-OFFSET");if(lt(n))return n;return null}function o3(e,t){let n=(e||"").split(/[ ,]+/).filter((s)=>s);["video","audio","text","image"].forEach((s)=>{let i=n.filter((r)=>I1(r,s));if(i.length)t[`${s}Codec`]=i.map((r)=>r.split("/")[0]).join(","),n=n.filter((r)=>i.indexOf(r)===-1)}),t.unknownCodecs=n}function l3(e,t,n){let s=t[n];if(s)e[n]=s}function tC(e,t,n){if(n||(n=e[t]),!n)return;for(let s=t;s--;){let i=e[s];if(!i)return;i.programDateTime=n.programDateTime-i.duration*1000,n=i}}function a1(e,t,n){if(e.rawProgramDateTime)n.push(e);else if(t!=null&&t.programDateTime)e.programDateTime=t.endProgramDateTime}function c3(e,t,n,s){if(e.relurl=t.URI,t.BYTERANGE)e.setByteRange(t.BYTERANGE);if(e.level=n,e.sn="initSegment",s)e.levelkeys=s;e.initSegment=null}function f3(e,t,n){e.levelkeys=t;let{encryptedFragments:s}=n;if((!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some((i)=>t[i].isCommonEncryption))s.push(e)}function lo(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function nC(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function Rg(e,t){let n=t.startPTS;if(lt(n)){let s=0,i;if(t.sn>e.sn)s=n-e.start,i=e;else s=e.start-n,i=t;if(i.duration!==s)i.setDuration(s)}else if(t.sn>e.sn)if(e.cc===t.cc&&e.minEndPTS)t.setStart(e.start+(e.minEndPTS-e.start));else t.setStart(e.start+e.duration);else t.setStart(Math.max(e.start-t.duration,0))}function K9(e,t,n,s,i,r,o,l){if(s-n<=0)l.warn("Fragment should have a positive duration",t),s=n+t.duration,r=i+t.duration;let h=n,d=s,{startPTS:m,endPTS:p}=t;if(lt(m)){let E=Math.abs(m-n);if(e&&E>e.totalduration)l.warn(`media timestamps and playlist times differ by ${E}s for level ${t.level} ${e.url}`);else if(!lt(t.deltaPTS))t.deltaPTS=E;else t.deltaPTS=Math.max(E,t.deltaPTS);h=Math.max(n,m),n=Math.min(n,m),i=t.startDTS!==void 0?Math.min(i,t.startDTS):i,d=Math.min(s,p),s=Math.max(s,p),r=t.endDTS!==void 0?Math.max(r,t.endDTS):r}let b=n-t.start;if(t.start!==0)t.setStart(n);t.setDuration(s-t.start),t.startPTS=n,t.maxStartPTS=h,t.startDTS=i,t.endPTS=s,t.minEndPTS=d,t.endDTS=r;let v=t.sn;if(!e||v<e.startSN||v>e.endSN)return 0;let k,A=v-e.startSN,T=e.fragments;T[A]=t;for(k=A;k>0;k--)Rg(T[k],T[k-1]);for(k=A;k<T.length-1;k++)Rg(T[k],T[k+1]);if(e.fragmentHint)Rg(T[T.length-1],e.fragmentHint);return e.PTSKnown=e.alignedSliding=!0,b}function sC(e,t,n){if(e===t)return;let s=null,i=e.fragments;for(let d=i.length-1;d>=0;d--){let m=i[d].initSegment;if(m){s=m;break}}if(e.fragmentHint)delete e.fragmentHint.endPTS;let r;aC(e,t,(d,m,p,b)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==d.cc){let v=d.cc-m.cc;for(let k=p;k<b.length;k++)b[k].cc+=v;t.endCC=b[b.length-1].cc}if(lt(d.startPTS)&&lt(d.endPTS)){if(m.setStart(m.startPTS=d.startPTS),m.startDTS=d.startDTS,m.maxStartPTS=d.maxStartPTS,m.endPTS=d.endPTS,m.endDTS=d.endDTS,m.minEndPTS=d.minEndPTS,m.setDuration(d.endPTS-d.startPTS),m.duration)r=m;t.PTSKnown=t.alignedSliding=!0}if(d.hasStreams)m.elementaryStreams=d.elementaryStreams;if(m.loader=d.loader,d.hasStats)m.stats=d.stats;if(d.initSegment)m.initSegment=d.initSegment,s=d.initSegment});let o=t.fragments,l=t.fragmentHint?o.concat(t.fragmentHint):o;if(s)l.forEach((d)=>{var m;if(d&&(!d.initSegment||d.initSegment.relurl===((m=s)==null?void 0:m.relurl)))d.initSegment=s});if(t.skippedSegments){if(t.deltaUpdateFailed=o.some((d)=>!d),t.deltaUpdateFailed){n.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)o.shift();t.startSN=o[0].sn}else{if(t.canSkipDateRanges)t.dateRanges=iC(e.dateRanges,t,n);let d=e.fragments.filter((m)=>m.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime){for(let m=1;m<l.length;m++)if(l[m].programDateTime===null)a1(l[m],l[m-1],d)}W9(d,t)}t.endCC=o[o.length-1].cc}if(!t.startCC){var c;let d=J9(e,t.startSN-1);t.startCC=(c=d==null?void 0:d.cc)!=null?c:o[0].cc}if(rC(e.partList,t.partList,(d,m)=>{m.elementaryStreams=d.elementaryStreams,m.stats=d.stats,m.gap=d.gap||m.gap}),r){let d=t.iframesOnly&&r.type===kt.MAIN;K9(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,d,n)}else Y9(e,t);if(o.length)t.totalduration=t.edge-o[0].start;t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let h=t.advancedDateTime;if(t.advanced&&h){let d=t.edge;if(!t.driftStart)t.driftStartTime=h,t.driftStart=d;t.driftEndTime=h,t.driftEnd=d}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;if(t.requestScheduled===-1)t.requestScheduled=e.requestScheduled}function iC(e,t,n){let{dateRanges:s,recentlyRemovedDateranges:i}=t,r=Gn({},e);if(i)i.forEach((c)=>{delete r[c]});let l=Object.keys(r).length;if(!l)return s;return Object.keys(s).forEach((c)=>{let h=r[c],d=new M1(s[c].attr,h);if(d.isValid){if(r[c]=d,!h)d.tagOrder+=l}else n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ls(s[c].attr)}"`)}),r}function rC(e,t,n){if(e&&t){let s=0;for(let i=0,r=e.length;i<r;i++){let o=e[i],l=t[i+s];if(o&&l&&o.index===l.index&&o.fragment.sn===l.fragment.sn)n(o,l);else s--}}}function aC(e,t,n){var s;let i=t.skippedSegments,r=Math.max(e.startSN,t.startSN)-t.startSN,o=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,l=t.startSN-e.startSN,c=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=(s=e.fragmentHint)!=null&&s.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=r;d<=o;d++){let m=h[l+d],p=c[d];if(i&&!p&&m)p=t.fragments[d]=m;if(m&&p){n(m,p,d,c);let b=m.relurl,v=p.relurl;if(b&&lC(b,v)){t.playlistParsingError=h3(`media sequence mismatch ${p.sn}:`,e,t,m,p);return}else if(m.cc!==p.cc){t.playlistParsingError=h3(`discontinuity sequence mismatch (${m.cc}!=${p.cc})`,e,t,m,p);return}}}}function h3(e,t,n,s,i){return Error(`${e} ${i.url}
23
- Playlist starting @${t.startSN}
24
- ${t.m3u8}
25
-
26
- Playlist starting @${n.startSN}
27
- ${n.m3u8}`)}function Y9(e,t,n=!0,s){let i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,o=i>=0,l=0;if(o&&i<r.length)l=r[i].start,s==null||s.log(`Aligning playlists based on SN ${t.startSN} (diff: ${l})`);else if(o&&t.startSN===e.endSN+1)l=e.fragmentEnd,s==null||s.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${l})`);else if(o&&n)l=e.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)l=e.fragmentStart,s==null||s.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${l})`);else return l;return oC(t,l),l}function oC(e,t){if(t){let n=e.fragments;for(let s=e.skippedSegments;s<n.length;s++)n[s].addStart(t);if(e.fragmentHint)e.fragmentHint.addStart(t)}}function Q9(e,t=1/0){let n=1000*e.targetduration;if(e.updated){let s=e.fragments,i=4;if(s.length&&n*4>t){let r=s[s.length-1].duration*1000;if(r>0&&r<n)n=r}}else n/=2;return Math.round(n)}function J9(e,t,n){var s;if(!e)return null;let i=e.fragments[t-e.startSN];if(i)return i;if(i=e.fragmentHint,((s=i)==null?void 0:s.sn)===t)return i;if(n&&t<e.startSN&&n.sn===t)return n;return null}function u3(e,t,n){if(!e)return null;return Z9(e.partList,t,n)}function Z9(e,t,n){if(e)for(let s=e.length;s--;){let i=e[s];if(i.index===n&&i.fragment.sn===t)return i}return null}function e6(e){e.forEach((t,n)=>{var s;(s=t.details)==null||s.fragments.forEach((i)=>{if(i.level=n,i.initSegment)i.initSegment.level=n})})}function lC(e,t){if(e!==t&&t)return d3(e)!==d3(t);return!1}function d3(e){return e.replace(/\?[^?]*$/,"")}function dh(e,t){for(let s=0,i=e.length;s<i;s++){var n;if(((n=e[s])==null?void 0:n.cc)===t)return e[s]}return null}function cC(e,t){if(e){if(t.startCC<e.endCC&&t.endCC>e.startCC)return!0}return!1}function m3(e,t){let n=e.start+t;e.setStart(n)}function t6(e,t){let n=t.fragments;for(let s=0,i=n.length;s<i;s++)m3(n[s],e);if(t.fragmentHint)m3(t.fragmentHint,e);t.alignedSliding=!0}function n0(e,t,n){if(!e)return;if(fC(t,e,n),!t.alignedSliding)hC(t,e,n);if(!t.alignedSliding&&!t.skippedSegments)Y9(e,t,!1,n)}function fC(e,t,n){if(!cC(t,e))return;let s=Math.min(t.endCC,e.endCC),i=dh(t.fragments,s),r=dh(e.fragments,s);if(!i||!r)return;let o=i.start-r.start;n.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${o})`),t6(o,e)}function hC(e,t,n){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,o,l=Math.min(t.endCC,e.endCC);if(t.startCC<l&&e.startCC<l)r=dh(i,l),o=dh(s,l);if(!r||!o)r=i[Math.floor(i.length/2)]||i.filter((p)=>!!p)[0],o=dh(s,r.cc)||s[Math.floor(s.length/2)];let c=r.programDateTime,h=o.programDateTime;if(!c||!h)return;let d=(h-c)/1000;if(Math.abs(d)>Math.max(60,e.totalduration)){n.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${e.totalduration})`);return}let m=d-(o.start-r.start);n.log(`Aligning playlists using PDT (diff: ${m})`),t6(m,e)}function Un(e,t,n){Bn(e,t,n),e.addEventListener(t,n)}function Bn(e,t,n){e.removeEventListener(t,n)}function s0(e){let t="",n=e.length;for(let s=0;s<n;s++)t+=`[${e.start(s).toFixed(3)}-${e.end(s).toFixed(3)}]`;return t}var Me={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class g0 extends D1{constructor(e,t,n,s,i){super(s,e.logger);this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Me.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:r,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,d=l?l.currentTime:0,m=qt.bufferInfo(c?c:l,d,r.maxBufferHole),p=m.len;if(this.log(`Media seeking to ${d}, state: ${h}, ${!p?"out of":"in"} buffer`),this.state===Me.ENDED)this.resetLoadingState();else if(o){let v=r.maxFragLookUpTolerance,k=o.start-v,A=o.start+o.duration+v;if(!p||A<m.start||k>m.end){let T=d<k,E=d>A;if(T||E)if(o.loader&&(E||!this.isFragmentNearlyDownloaded(o)))this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState();else this.fragPrevious=null}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);let v=this.lastCurrentTime;if(d>v)this.lastCurrentTime=d;if(!this.loadingParts){let k=Math.max(m.end,d),A=this.shouldLoadParts(this.getLevelDetails(),k);if(A)this.log(`LL-Part loading ON after seeking to ${d} with buffer @${k}`),this.loadingParts=A}}let b=!qt.isBuffered(l,d);if(!this.hls.hasEnoughToStart||b){if(this.log(`Setting ${b?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,b)this.startPosition=d}if(p<1&&this.state===Me.IDLE)this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new s1(e.config),this.initFragmentLoader=new s1(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new d0(e.config)}registerListeners(){let{hls:e}=this;e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Me.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;if(e!=null&&e.loader)e.abortRequests(),this.fragmentTracker.removeFragment(e);this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Me.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let n=this.getLevelDetails();if(n!=null&&n.live)return(this.hls.liveSyncPosition||n.fragmentStart)+this.timelineOffset;return e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){return}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let n=e.end||0,s=this.config.timelineOffset||0;if(n<=s)return!1;let i=e.buffered;if(this.config.maxBufferHole&&i&&i.length>1)e=qt.bufferedInfo(i,e.start,0);let r=e.nextStart;if(r&&r>s&&r<t.edge)return!1;if(this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let h=l[l.length-1];return qt.isBuffered(this.media,h.start+h.duration/2)}let c=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(c.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;Un(n,"seeking",this.onMediaSeeking),Un(n,"ended",this.onMediaEnded);let s=this.config;if(this.levels&&s.autoStartLoad&&this.state===Me.STOPPED)this.startLoad(s.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let n=!!t.transferMedia,s=this.media;if(s===null)return;if(s.ended)this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0;if(Bn(s,"seeking",this.onMediaSeeking),Bn(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){if(this.stopLoad(),this.transmuxer)this.transmuxer.destroy(),this.transmuxer=null;super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){if(this.state=Me.STOPPED,this.fragmentLoader)this.fragmentLoader.destroy();if(this.initFragmentLoader)this.initFragmentLoader.destroy();if(this.keyLoader)this.keyLoader.destroy();if(this.decrypter)this.decrypter.destroy();this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){let s=(i)=>{let r=i.frag;if(this.fragContextChanged(r)){this.warn(`${r.type} sn: ${r.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(r,!1,i.part)} was dropped during download.`),this.fragmentTracker.removeFragment(r);return}let o=++r.stats.chunkCount;this.log(`load progress ${r.type} sn: ${r.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(r,!1,i.part)} chunk: ${o}`),this._handleFragmentLoadProgress(i)};this._doFragLoad(e,t,n,s).then((i)=>{if(!i)return;let r=this.state,o=i.frag;if(this.fragContextChanged(o)){if(r===Me.FRAG_LOADING||!this.fragCurrent&&r===Me.PARSING)this.fragmentTracker.removeFragment(o),this.state=Me.IDLE;return}if("payload"in i)this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(O.FRAG_LOADED,i);this._handleFragmentLoadComplete(i)}).catch((i)=>{if(this.state===Me.STOPPED||this.state===Me.ERROR)return;this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(e)})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:n}=this;if(n.getState(e)===Ss.APPENDING){let i=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(e.duration,r?r.len:this.config.maxBufferLength),l=this.backtrackFragment;if((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))n.removeFragment(e)}else if(((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0)n.removeAllFragments();else if(n.hasParts(e.type)){if(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===Ss.PARTIAL)n.removeFragment(e)}}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,n=e.fragments[e.fragments.length-1];if(n.endList&&!t.isEndListAppended(this.playlistType)){let s=t.getPartialFragment(n.end);if(s)t.removeFragment(s),t.fragBuffered(n,!0)}t.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}if(!e.fragments[0])e.deltaUpdateFailed=!0}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,n=null){if(!(e-t))return;let s={startOffset:e,endOffset:t,type:n};this.hls.trigger(O.BUFFER_FLUSHING,s)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(O.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then((n)=>{var s;let i=n.frag;if(!this.levels||!Kg(i,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new sa({type:Et.NETWORK_ERROR,details:ve.INTERNAL_ABORTED,error:Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return n}).then((n)=>{let{frag:s,payload:i}=n,r=s.decryptdata;if(i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&$c(r.method)){let o=self.performance.now(),{decryptRange:l}=Zd(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,F1(r.method),l).catch((c)=>{throw t.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:s}),this.fragmentLoader.abort(),c}).then((c)=>{let h=self.performance.now();return t.trigger(O.FRAG_DECRYPTED,{frag:s,part:null,payload:c,stats:{tstart:o,tdecrypt:h}}),n.payload=c,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&js(e)&&t&&!t.data){var n;return(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch((i)=>{if(this.state===Me.STOPPED||this.state===Me.ERROR)throw i;if("data"in i)i.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(i);throw this.resetFragmentLoading(e),i})}}unhandledEncryptionError(e,t){var n,s;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(s=i.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let r=this.media,o=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${r?"attached mediaKeys: "+r.mediaKeys:"detached"})`);if(this.warn(o.message),!r||r.mediaKeys)return!1;return this.hls.trigger(O.ERROR,{type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!Kg(e,t)}fragBufferedComplete(e,t){let n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${n?s0(qt.getBuffered(n)):"(detached)"})`),js(e)){var s;if(e.type!==kt.SUBTITLE){let r=e.elementaryStreams;if(!Object.keys(r).some((o)=>!!r[o])){this.state=Me.IDLE;return}}let i=(s=this.levels)==null?void 0:s[e.level];if(i!=null&&i.fragmentError&&(t||this.fragmentTracker.getState(e)!==Ss.PARTIAL))this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,e.stats.retry=0}this.state=Me.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let n=e.frag,{part:s,partsLoaded:i}=e,r=!i||i.length===0||i.some((c)=>!c),{decryptRange:o}=Zd(n,s),l=new m0(n.level,n.sn,n.stats.chunkCount+1,0,s?s.index:-1,!r,n.duration,this.iframesOnly,o);this.log(`load complete ${n.type} sn: ${n.sn}${s?" part: "+s.index:""} of ${this.fragInfo(n,!1,s)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,n){var s;let i=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key))this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Me.KEY_LOADING,i=this.keyLoader.load(e,n).then((r)=>{if(!this.fragContextChanged(r.frag)){if(this.hls.trigger(O.KEY_LOADED,r),this.state===Me.KEY_LOADING)this.state=Me.IDLE;return r}}),this.hls.trigger(O.KEY_LOADING,{frag:e});else if(!e.encrypted){if(i=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),i)this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)}return i}_doFragLoad(e,t,n=null,s){this.fragCurrent=e;let i=t.details;if(!this.levels||!i)throw Error(`frag load aborted, missing level${i?"":" detail"}s`);let r=this.fragPrevious;if(!nh(e,r)){let p=this.shouldLoadParts(t.details,e.end);if(p!==this.loadingParts)this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${r==null?void 0:r.sn}->${e.sn}`),this.loadingParts=p}if(n=Math.max(e.start,n||0),this.loadingParts){let p=i.partList;if(p&&s){if(n>i.fragmentEnd&&i.fragmentHint)e=i.fragmentHint;let b=this.getNextPart(p,e,n);if(b>-1){let v=p[b];if(e=this.fragCurrent=v.fragment,!nh(e,r)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,v)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(v,t.details))return Promise.resolve(null);let k=this.loadKeyFor(e,i);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${v.index} (${b}/${p.length-1}) of ${this.fragInfo(e,!1,v)} cc: ${e.cc} [${i.startSN}-${i.endSN}], target: ${n}${v.byteRange.length?` range:${v.byteRange.join("-")}`:""}`),this.nextLoadPosition=v.start+v.duration,this.state=Me.FRAG_LOADING;let A,T=this.loadInitSegmentIfNeeded(e);if(k||T){let E=!!k;A=Promise.all([k,T]).then(([I])=>{if(E&&(!I||this.fragContextChanged(I.frag)))return null;return this.doFragPartsLoad(e,v,t,s)}).catch((I)=>this.handleFragLoadError(I))}else A=this.doFragPartsLoad(e,v,t,s).catch((E)=>this.handleFragLoadError(E));if(this.hls.trigger(O.FRAG_LOADING,{frag:e,part:v,targetBufferTime:n}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts"));return A}else if(!e.url||this.loadedEndOfParts(p,n))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${n} Check buffer at sn: ${e.sn} loaded parts: ${(o=i.partList)==null?void 0:o.filter((p)=>p.loaded).map((p)=>`[${p.start}-${p.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),c=this.loadKeyFor(e,i,l);if(this.fragContextChanged(e)){var h;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(h=this.fragCurrent)==null?void 0:h.relurl}`),l==null||l.catch(()=>null),c==null||c.catch(()=>null),Promise.resolve(null)}if(this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+i.startSN+"-"+i.endSN+"]"}, target: ${n}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),lt(e.sn)&&!this.bitrateTest)this.nextLoadPosition=e.start+e.duration;this.state=Me.FRAG_LOADING;let d=this.config.progressive&&e.type!==kt.SUBTITLE,m;if(d&&c)m=c.then((p)=>{if(!p||this.fragContextChanged(p.frag))return null;return this.fragmentLoader.load(e,this.iframesOnly,s,l)}).catch((p)=>this.handleFragLoadError(p));else m=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,d?s:void 0,d?l:void 0),c,l]).then(([p])=>{if(!d&&s)s(p);return p}).catch((p)=>this.handleFragLoadError(p));if(this.hls.trigger(O.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING"));return Promise.all([m,l]).then(([p])=>p)}doFragPartsLoad(e,t,n,s){return new Promise((i,r)=>{var o;let l=[],c=(o=n.details)==null?void 0:o.partList,h=(d)=>{this.fragmentLoader.loadPart(e,d,s).then((m)=>{l[d.index]=m;let p=m.part;this.hls.trigger(O.FRAG_LOADED,m);let b=u3(n.details,e.sn,d.index+1)||Z9(c,e.sn,d.index+1);if(b)h(b);else return i({frag:e,part:p,partsLoaded:l})}).catch(r)};h(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;if(t.frag&&t.details===ve.INTERNAL_ABORTED)this.handleFragLoadAborted(t.frag,t.part);else if(t.frag&&t.type===Et.KEY_SYSTEM_ERROR&&!t.fatal)t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag);this.hls.trigger(O.ERROR,t)}else this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==Me.PARSING){if(!this.fragCurrent&&this.state!==Me.STOPPED&&this.state!==Me.ERROR)this.state=Me.IDLE;return}let{frag:n,part:s,level:i}=t,r=self.performance.now();if(n.stats.parsing.end=r,s)s.stats.parsing.end=r;let o=this.getLevelDetails(),c=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);if(c!==this.loadingParts)this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${n.end}`),this.loadingParts=c;this.updateLevelTiming(n,s,i,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var n;let s=e.partList[0],i=s.end+(((n=e.fragmentHint)==null?void 0:n.duration)||0);if(t>=i){if(this.playhead>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:s,sn:i,part:r}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let o=t[s],l=o.details,c=r>-1?u3(l,i,r):null,h=c?c.fragment:J9(l,i,n);if(!h)return null;if(n&&n!==h)h.stats=n.stats;return{frag:h,part:c,level:o}}bufferFragmentData(e,t,n,s,i){if(this.state!==Me.PARSING)return;if(js(t)&&!this.fragContextChanged(t))this.fragPrevious=t;let{data1:r,data2:o}=e,l=r;if(o)l=Rr(r,o);if(!l.length)return;let c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,d={type:e.type,frag:t,part:n,chunkMeta:s,offset:h,parent:t.type,data:l};if(this.hls.trigger(O.BUFFER_APPENDING,d),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!qt.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,s=qt.bufferInfo(t,n,0),i=e.duration,r=Math.min(this.config.maxFragLookUpTolerance*2,i*0.25),o=Math.max(Math.min(e.start-r,s.end-r),n+r);if(e.start-o>r)this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let s=this.playhead,r=this.lastCurrentTime>s||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,t,r)}getFwdBufferInfoAtPos(e,t,n,s){let i=qt.bufferInfo(e,t,s);if(i.len===0&&i.nextStart!==void 0){let r=this.fragmentTracker.getBufferedFrag(t,n);if(r&&(i.nextStart<=r.end||r.gap)){let o=Math.max(Math.min(i.nextStart,r.end)-t,s);return qt.bufferInfo(e,t,o)}}return i}getMaxBufferLength(e){let{config:t}=this,n;if(e)n=Math.max(8*t.maxBufferSize/e,t.maxBufferLength);else n=t.maxBufferLength;return Math.min(n,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,n){let s=e.nextStart;if(s&&n.start>s){let i=e.buffered;if(i){let{len:r,bufferedIndex:o}=e;for(let l=i.length-1;l>o;l--)if(i[l].start<n.start)r+=i[l].end-i[l].start;return r>=t}}return!1}reduceMaxBufferLength(e,t){let n=this.config,s=Math.max(Math.min(e-t,n.maxBufferLength),t/2),i=Math.max(e-t*3,n.maxMaxBufferLength/2,s);if(i>=s)return n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0;return!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;if(t&&"fragment"in t)return t.fragment;return t}getNextFragment(e,t){let n=t.fragments,s=n.length;if(!s)return null;let{config:i}=this,r=t.fragmentStart,o=i.lowLatencyMode&&!!t.partList,l=null;if(t.live){let d=i.initialLiveManifestSize;if(s<d)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${d})`),null;if(!this.startFragRequested&&o&&!this.loadingParts)this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<r){var c;l=this.getInitialLiveFragment(t);let m=this.config.startPosition,p=this.hls.startPosition,b=this.hls.liveSyncPosition,v=((c=l)==null?void 0:c.start)||0,k,A;if(p!==-1&&p>=r)k=p,A=p===m?"config":"next load start";else if(b)k=b,A="live edge";else k=e,A="buffer pos";if(k<v)k=v,A="live frag start";if(k<r)k=r,A="playlist start";if(this.startPosition!=k||this.nextLoadPosition!=k){let E=t.live&&!this.filterReplacedPrimary(l,t)?-1:k;this.log(`Setting startPosition to ${E} next load ${k} ${p===-1?"":`(from ${m}) `}based on ${A}. live edge: ${b} live frag start: ${v} playlist start: ${r} buffer pos: ${e}`),this.startPosition=E,this.nextLoadPosition=k}}}else if(e<=r)l=n[0];if(!l){let d=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,d,t)}let h=this.filterReplacedPrimary(l,t);if(!h&&l){if(h=F9(t,l.sn),h)this.nextLoadPosition=h.start}return h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let n=this.fragmentTracker.getState(e);if(n===Ss.OK)return!0;if(n===Ss.PARTIAL){if(e.gap)return!0;if(e.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(e,t,n,s,i){let r=null;if(e.gap){if(r=this.getNextFragment(this.nextLoadPosition,t),r&&!r.gap&&n.nextStart){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,s,0);if(o!==null&&n.len+o.len>=i){let l=r.sn;if(this.loopSn!==l)this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l;return null}}}return this.loopSn=void 0,r}get primaryPrefetch(){if(i0(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(i0(this.config)&&("type"in e?e:e.fragment).type!==kt.SUBTITLE){let n=this.hls.interstitialsManager,s=n==null?void 0:n.bufferingItem;if(s){let i=s.event;if(i){if(!i.appendInPlace&&(Math.abs(e.start-s.start)>1||s.start===0))return null}else{if(e.end<=s.start&&(t==null?void 0:t.live)===!1)return null;if(e.start>=s.end&&s.nextEvent){if(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||e.start-s.end>1)return null}}}if(n6(e,n==null?void 0:n.playerQueue,this.playhead))return null}return e}getNextPart(e,t,n){let s=-1,i=!1,r=!0;for(let l=0,c=e.length;l<c;l++){let h=e[l];if(r=r&&!h.independent,s>-1&&n<h.start)break;let d=h.loaded||h.gap;if(d)s=-1;else if(i||(h.independent||r)&&h.fragment===t)s=l;i=d&&!h.gap}let o=e[s];if(o&&o.fragment!==t)this.log(`Need buffer at ${n} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`);return s}loadedEndOfParts(e,t){let n;for(let s=e.length;s--;){if(n=e[s],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,s=null;if(n){if(e.hasProgramDateTime){if(s=DE(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance),s)this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)}if(!s){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let r=t[i-e.startSN];if(n.cc===r.cc)s=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`)}if(!s){if(s=M9(e,n.cc,n.end),s)this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`)}}}else{let i=this.hls.liveSyncPosition;if(i!==null)s=this.getFragmentAtPosition(i,this.bitrateTest?e.fragmentEnd:e.edge,e)}return s}getFragmentAtPosition(e,t,n){let{config:s}=this,{fragPrevious:i}=this,{fragments:r,endSN:o}=n,{fragmentHint:l}=n,{maxFragLookUpTolerance:c}=s,h=n.partList,d=!!(this.loadingParts&&h!=null&&h.length&&l);if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn)r=r.concat(l),o=l.sn;if(i&&this.fragmentTracker.getState(i)===Ss.NOT_LOADED)i=null;let m;if(e<t){var p;let v=e<this.lastCurrentTime||e>t-c||(p=this.media)!=null&&p.paused||!this.startFragRequested?0:c;m=Qc(i,r,e,v)}else m=r[r.length-1];if(m){let b=m.sn-n.startSN,v=this.fragmentTracker.getState(m);if(v===Ss.OK||v===Ss.PARTIAL&&m.gap)i=m;if(nh(m,i)&&(!d||h[0].fragment.sn>m.sn||!n.live)){let k=r[b+1];if(m.sn<o&&this.fragmentTracker.getState(k)!==Ss.OK)m=k;else m=null}}return m}alignPlaylists(e,t,n){let s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let i=e.fragmentStart,r=!t,o=e.alignedSliding&&lt(i);if(r||!o&&!i){n0(n,e,this);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;if(n<t)n=-1;let s=this.timelineOffset;if(n===-1){let i=this.startTimeOffset!==null,r=i?this.startTimeOffset:e.startTimeOffset;if(r!==null&&lt(r)){if(n=t+r,r<0)n+=e.edge;n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${r} found in ${i?"multivariant":"media"} playlist`),this.startPosition=n}else if(e.live){let o=this.hls.liveSyncPosition;n=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${n}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=n=0;this.lastCurrentTime=n+s}this.nextLoadPosition=n+s}getLoadPosition(){var e;let{media:t}=this,n=0;if((e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly)n=t.currentTime;else if(this.nextLoadPosition>=0)n=this.nextLoadPosition;return n}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let n=(t=this.media)==null?void 0:t.currentTime;if(lt(n))return n;return this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==kt.MAIN)return!1;let t=this.getLevelDetails();if(t)return t.iframesOnly;return(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){if(this.transmuxer&&e.type===this.playlistType&&js(e)&&e.stats.aborted)this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e)}resetFragmentLoading(e){if(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Me.FRAG_LOADING_WAITING_RETRY)this.state=Me.IDLE}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let T=this.getCurrentContext(t.chunkMeta);if(T)t.frag=T.frag}let{frag:n,part:s}=t;if(!n||!this.levels||n.type!==e)return;if(this.fragContextChanged(n)){var i;this.warn(`Frag load error must match current frag to retry ${n.relurl} > ${(i=this.fragCurrent)==null?void 0:i.relurl}`);return}let r=t.details===ve.FRAG_GAP;if(r)this.fragmentTracker.addAsGap(n);let o=t.errorAction;if(!o){this.state=Me.ERROR;return}let{action:l,flags:c,retryCount:h=0,retryConfig:d}=o,m=!!d,p=m&&l===gi.RetryRequest,b=m&&!o.resolved&&c&pi.MoveAllAlternatesMatchingHost,v=this.hls.latestLevelDetails,k=v==null?void 0:v.live;if(!p&&b&&js(n)&&k&&n.sn<v.endSN&&!n9(t)){if(this.resetFragmentErrors(e),s)s.gap=!0;else this.treatAsGap(n);o.resolved=!0}else if((p||b)&&h<d.maxNumRetry){var A;let T=bh((A=t.response)==null?void 0:A.code),E=E1(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=Me.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,T){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${E}ms`)}else if(d)if(this.resetFragmentErrors(e),h<d.maxNumRetry){if(!r&&l!==gi.RemoveAlternatePermanently)o.resolved=!0}else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else if(l===gi.SendAlternateToPenaltyBox)this.state=Me.WAITING_LEVEL;else this.state=Me.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,n=t===1/0;if(!t||e>=t||n&&!bh(0)){if(n)this.log("Connection restored (online)");this.resetStartWhenNotLoaded(),this.state=Me.IDLE}}reduceLengthAndFlushBuffer(e){if(this.state===Me.PARSING||this.state===Me.PARSED){let{frag:t,parent:n}=e,s=this.getFwdBufferInfo(this.mediaBuffer,n),i=s&&s.len>0.5;if(i)this.reduceMaxBufferLength(s.len,(t==null?void 0:t.duration)||10);let r=!i;if(r)this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${n} buffer`);else if(s.nextStart&&t&&s.nextStart>t.start)this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,n===kt.AUDIO?n:void 0);if(t)this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start;return this.resetLoadingState(),r}return!1}resetFragmentErrors(e){if(e===kt.AUDIO)this.fragCurrent=null;if(!this.hls.hasEnoughToStart)this.startFragRequested=!1;if(this.state!==Me.STOPPED)this.state=Me.IDLE}afterBufferFlushed(e,t){if(!e)return;let n=qt.getBuffered(e);if(this.fragmentTracker.detectEvictedFragments(t,n,this.playlistType),this.state===Me.ENDED)this.resetLoadingState()}resetLoadingState(){if(this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Me.STOPPED)this.state=Me.IDLE}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();if(e!=null&&e.live)this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState();else this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,s){let i=n.details;if(!i){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((d,m)=>{let p=e.elementaryStreams[m];if(p){let b=p.endPTS-p.startPTS;if(b<=0)return this.warn(`Could not parse fragment ${e.sn} ${m} duration reliably (${b})`),d||!1;let v=s.partial?0:K9(i,e,p.startPTS,p.endPTS,p.startDTS,p.endDTS,this.iframesOnly,this);return this.hls.trigger(O.LEVEL_PTS_UPDATED,{details:i,level:n,drift:v,type:m,frag:e,start:p.startPTS,end:p.endPTS}),!0}return d},!1)){var o,l,c,h;let d=((o=this.transmuxer)==null?void 0:o.error)===null,m=((l=this.transmuxer)==null?void 0:l.error)!=null,p=((c=(h=this.levels)==null?void 0:h.length)!=null?c:0)>1;if(n.fragmentError===0||d&&(n.fragmentError<2||e.endList)||m&&p)this.treatAsGap(e,n);if(d){let b=Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(b.message),this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,error:b,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Me.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(O.FRAG_PARSED,{frag:e,part:t,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,n){var s,i;return`${this.playlistLabel()} ${e.level} (${n?"part":"frag"}:[${(s=t&&!n?e.startPTS:(n||e).start)!=null?s:NaN}-${(i=t&&!n?e.endPTS:(n||e).end)!=null?i:NaN}]${n&&e.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""})`}treatAsGap(e,t){if(t)t.fragmentError++;this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let n=(t=e.loader)==null?void 0:t.stats;if(!n)return!1;let s=n.loading.first>0,r=(n.total-n.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&r<=0.15}recoverWorkerError(e){if(e.event==="demuxerWorker"){if(this.fragmentTracker.removeAllFragments(),this.transmuxer)this.transmuxer.destroy(),this.transmuxer=null;this.resetStartWhenNotLoaded(),this.resetLoadingState()}}set state(e){let t=this._state;if(t!==e)this._state=e,this.log(`${t}->${e}`)}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let n=0,{hls:s,media:i,config:r,levels:o,playlistType:l}=this,c=this.getLevelDetails();if(i&&!i.paused&&o){var h;let p=l===kt.AUDIO?j9(e.audioCodec,128000):e.maxBitrate,b=1+s.ttfbEstimate/1000,v=s.bandwidthEstimate*r.abrBandWidthUpFactor,k=c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||((h=this.fragCurrent)==null?void 0:h.duration)||6;if(n=b+p*k/v,!e.details)n+=b}let d=this.playhead,m=!(c!=null&&c.live)||t.end-d>n*1.5;return{fetchdelay:n,okToFlushForwardBuffer:m}}scheduleTrackSwitch(e,t,n){let{media:s,playlistType:i}=this;if(!s||!e)return;let r=n?this.getBufferedFrag(this.playhead+t):null;if(r){let l=this.followingBufferedFrag(r);if(l){var o;this.abortCurrentFrag();let c=l.maxStartPTS?l.maxStartPTS:l.start,h=l.duration,d=Math.max(r.end,c+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?0.5:0.125)),h*(this.couldBacktrack?0.75:0.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>d)return;let p=i===kt.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,p),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let n=this.getAppendedFrag(this.playhead);if(n&&n.start>1){let s=t===kt.AUDIO;this.flushMainBuffer(0,n.start-(s?0:1),s?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){if(e)return this.getBufferedFrag(e.end+0.5);return null}abortCurrentFrag(){let e=this.fragCurrent;if(this.fragCurrent=null,e)e.abortRequests(),this.fragmentTracker.removeFragment(e);switch(this.state){case Me.KEY_LOADING:case Me.FRAG_LOADING:case Me.FRAG_LOADING_WAITING_RETRY:case Me.PARSING:case Me.PARSED:this.state=Me.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let n=e.currentTime;if(qt.isBuffered(e,n))t=this.getAppendedFrag(n);else if(qt.isBuffered(e,n+0.1))t=this.getAppendedFrag(n+0.1);if(t){if(this.backtrackFragment=void 0,!nh(t,this.fragPlaying))return this.fragPlaying=t,!0}}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:n,config:s,playlistType:i}=this;if(t!=null&&t.readyState&&e&&n&&s){let r=this.getBufferOutput(),o=this.getFwdBufferInfo(r,i);if(!o)return;let l=i===kt.AUDIO?n.nextAudioTrack:n.nextLoadLevel,c=e[l],{fetchdelay:h,okToFlushForwardBuffer:d}=this.calculateOptimalSwitchPoint(c,o);this.scheduleTrackSwitch(o,h,d)}this.tickImmediate()}}function n6(e,t,n){if(t)for(let s=t.length;s--;){let i=t[s].interstitial,r=i.startTime,o=Math.min(r+i.duration,i.resumeTime);if(i.appendInPlace){if(e.start>=r&&e.end<=o)return!0;if(n>e.start&&e.end>r&&e.start<o)return!0}}return!1}function i0(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}class O1{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(!e.length)return new Uint8Array(0);else if(e.length===1)n=e[0];else n=uC(e,t);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function uC(e,t){let n=new Uint8Array(t),s=0;for(let i=0;i<e.length;i++){let r=e[i];n.set(r,s),s+=r.length}return n}var qg={exports:{}},p3;function dC(){if(p3)return qg.exports;return p3=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function s(){}if(Object.create){if(s.prototype=Object.create(null),!new s().__proto__)n=!1}function i(c,h,d){this.fn=c,this.context=h,this.once=d||!1}function r(c,h,d,m,p){if(typeof d!=="function")throw TypeError("The listener must be a function");var b=new i(d,m||c,p),v=n?n+h:h;if(!c._events[v])c._events[v]=b,c._eventsCount++;else if(!c._events[v].fn)c._events[v].push(b);else c._events[v]=[c._events[v],b];return c}function o(c,h){if(--c._eventsCount===0)c._events=new s;else delete c._events[h]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var h=[],d,m;if(this._eventsCount===0)return h;for(m in d=this._events)if(t.call(d,m))h.push(n?m.slice(1):m);if(Object.getOwnPropertySymbols)return h.concat(Object.getOwnPropertySymbols(d));return h},l.prototype.listeners=function(h){var d=n?n+h:h,m=this._events[d];if(!m)return[];if(m.fn)return[m.fn];for(var p=0,b=m.length,v=Array(b);p<b;p++)v[p]=m[p].fn;return v},l.prototype.listenerCount=function(h){var d=n?n+h:h,m=this._events[d];if(!m)return 0;if(m.fn)return 1;return m.length},l.prototype.emit=function(h,d,m,p,b,v){var k=n?n+h:h;if(!this._events[k])return!1;var A=this._events[k],T=arguments.length,E,I;if(A.fn){if(A.once)this.removeListener(h,A.fn,void 0,!0);switch(T){case 1:return A.fn.call(A.context),!0;case 2:return A.fn.call(A.context,d),!0;case 3:return A.fn.call(A.context,d,m),!0;case 4:return A.fn.call(A.context,d,m,p),!0;case 5:return A.fn.call(A.context,d,m,p,b),!0;case 6:return A.fn.call(A.context,d,m,p,b,v),!0}for(I=1,E=Array(T-1);I<T;I++)E[I-1]=arguments[I];A.fn.apply(A.context,E)}else{var _=A.length,q;for(I=0;I<_;I++){if(A[I].once)this.removeListener(h,A[I].fn,void 0,!0);switch(T){case 1:A[I].fn.call(A[I].context);break;case 2:A[I].fn.call(A[I].context,d);break;case 3:A[I].fn.call(A[I].context,d,m);break;case 4:A[I].fn.call(A[I].context,d,m,p);break;default:if(!E)for(q=1,E=Array(T-1);q<T;q++)E[q-1]=arguments[q];A[I].fn.apply(A[I].context,E)}}}return!0},l.prototype.on=function(h,d,m){return r(this,h,d,m,!1)},l.prototype.once=function(h,d,m){return r(this,h,d,m,!0)},l.prototype.removeListener=function(h,d,m,p){var b=n?n+h:h;if(!this._events[b])return this;if(!d)return o(this,b),this;var v=this._events[b];if(v.fn){if(v.fn===d&&(!p||v.once)&&(!m||v.context===m))o(this,b)}else{for(var k=0,A=[],T=v.length;k<T;k++)if(v[k].fn!==d||p&&!v[k].once||m&&v[k].context!==m)A.push(v[k]);if(A.length)this._events[b]=A.length===1?A[0]:A;else o(this,b)}return this},l.prototype.removeAllListeners=function(h){var d;if(h){if(d=n?n+h:h,this._events[d])o(this,d)}else this._events=new s,this._eventsCount=0;return this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l}(qg),qg.exports}var mC=dC(),P1=fT(mC),xh="1.7.3",Jc={};function pC(){return typeof __HLS_WORKER_BUNDLE__==="function"}function gC(){let e=Jc[xh];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),n=self.URL.createObjectURL(t),i={worker:new self.Worker(n),objectURL:n,clientCount:1};return Jc[xh]=i,i}function yC(e){let t=Jc[e];if(t)return t.clientCount++,t;let n=new self.URL(e,self.location.href).href,i={worker:new self.Worker(n),scriptURL:n,clientCount:1};return Jc[e]=i,i}function vC(e){let t=Jc[e||xh];if(t){if(t.clientCount--===1){let{worker:s,objectURL:i}=t;if(delete Jc[e||xh],i)self.URL.revokeObjectURL(i);s.terminate()}}}function SC(e,t,n,s){let i=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],r=t[n+2],o=r>>2&15;if(o>12){let A=Error(`invalid ADTS sampling index:${o}`);e.emit(O.ERROR,O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!0,error:A,reason:A.message});return}let l=(r>>6&3)+1,c=t[n+3]>>6&3|(r&1)<<2,h=i[o],d=o;if(l===5||l===29)d-=3;let m,p=(d&14)>>1,b=(d&1)<<7|c<<3,v=0;if(l===1&&o>=6){v=5;let A=o-3;m=[v<<3|p,b|(A&14)>>1,(A&1)<<7|8,0]}else m=[l<<3|p,b];let k="mp4a.40."+(v||l);return Rn.log(`manifest codec:${s}, parsed codec:${k}, channels:${c}, rate:${h} (ADTS object type:${l} sampling index:${o} esds config:[${m.join(",")}])`),{config:m,samplerate:h,channelCount:c,codec:k,parsedCodec:k,manifestCodec:s}}function s6(e,t){return e[t]===255&&(e[t+1]&246)===240}function i6(e,t){return e[t+1]&1?7:9}function N1(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function kC(e,t){return t+5<e.length}function r0(e,t){return t+1<e.length&&s6(e,t)}function xC(e,t){return kC(e,t)&&s6(e,t)&&N1(e,t)<=e.length-t}function AC(e,t){if(r0(e,t)){let n=i6(e,t);if(t+n>=e.length)return!1;let s=N1(e,t);if(s<=n)return!1;let i=t+s;return i===e.length||r0(e,i)}return!1}function r6(e,t,n,s,i){if(!e.samplerate){let r=SC(t,n,s,i);if(!r)return;Gn(e,r)}}function a6(e){return 92160000/e}function TC(e,t){let n=i6(e,t);if(t+n<=e.length){let s=N1(e,t)-n;if(s>0)return{headerLength:n,frameLength:s}}}function o6(e,t,n,s,i){let r=a6(e.samplerate),o=s+i*r,l=TC(t,n),c;if(l){let{frameLength:m,headerLength:p}=l,b=p+m,v=Math.max(0,n+b-t.length);if(v)c=new Uint8Array(b-p),c.set(t.subarray(n+p,t.length),0);else c=t.subarray(n+p,n+b);let k={unit:c,pts:o};if(!v)e.samples.push(k);return{sample:k,length:b,missing:v}}let h=t.length-n;return c=new Uint8Array(h),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:o},length:h,missing:-1}}var zi=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Ea(e="",t=90000){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class b0{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){if(this.cachedData)e=Rr(this.cachedData,e),this.cachedData=null;let n=wh(e,0),s=n?n.length:0,i,r=this._audioTrack,o=this._id3Track,l=n?j1(n):void 0,c=e.length;if(this.basePTS===null||this.frameIndex===0&&lt(l))this.basePTS=EC(l,t,this.initPTS),this.lastPTS=this.basePTS;if(this.lastPTS===null)this.lastPTS=this.basePTS;if(n&&n.length>0)o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:zi.audioId3,duration:Number.POSITIVE_INFINITY});while(s<c){if(this.canParse(e,s)){let h=this.appendFrame(r,e,s);if(h)this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,i=s;else s=c}else if(CT(e,s))n=wh(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:zi.audioId3,duration:Number.POSITIVE_INFINITY}),s+=n.length,i=s;else s++;if(s===c&&i!==c){let h=e.slice(i);if(this.cachedData)this.cachedData=Rr(this.cachedData,h);else this.cachedData=h}}return{audioTrack:r,videoTrack:Ea(),id3Track:o,textTrack:Ea()}}demuxSampleAes(e,t,n){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;if(t)this.cachedData=null,this.demux(t,0);return{audioTrack:this._audioTrack,videoTrack:Ea(),id3Track:this._id3Track,textTrack:Ea()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}var EC=(e,t,n)=>{if(lt(e))return e*90;let s=n?n.baseTime*90000/n.timescale:0;return t*90000+s},CC=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],jC=[44100,48000,32000,22050,24000,16000,11025,12000,8000],_C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],IC=[0,1,1,4];function l6(e,t,n,s,i){if(n+24>t.length)return;let r=c6(t,n);if(r&&n+r.frameLength<=t.length){let o=r.samplesPerFrame*90000/r.sampleRate,l=s+i*o,c={unit:t.subarray(n,n+r.frameLength),pts:l,dts:l};return e.config=[],e.channelCount=r.channelCount,e.samplerate=r.sampleRate,e.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function c6(e,t){let n=e[t+1]>>3&3,s=e[t+1]>>1&3,i=e[t+2]>>4&15,r=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&r!==3){let o=e[t+2]>>1&1,l=e[t+3]>>6,c=n===3?3-s:s===3?3:4,h=CC[c*14+i-1]*1000,m=jC[(n===3?0:n===2?1:2)*3+r],p=l===3?1:2,b=_C[n][s],v=IC[s],k=b*8*v,A=Math.floor(b*h/m+o)*v,T=lh();if(!!T&&T<=87&&s===2&&h>=224000&&l===0)e[t+3]=e[t+3]|128;return{sampleRate:m,channelCount:p,frameLength:A,samplesPerFrame:k}}}function B1(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function f6(e,t){return t+1<e.length&&B1(e,t)}function RC(e,t){return B1(e,t)&&4<=e.length-t}function h6(e,t){if(t+1<e.length&&B1(e,t)){let s=c6(e,t),i=4;if(s!=null&&s.frameLength)i=s.frameLength;let r=t+i;return r===e.length||f6(e,r)}return!1}class H1{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new d0(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,tl.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,n){let s=e[t].unit;if(s.length<=16)return;let i=s.subarray(16,s.length-s.length%16),r=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(r).then((o)=>{let l=new Uint8Array(o);if(s.set(l,16),!this.decrypter.isSync())this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(e[t].unit.length<32)continue;if(this.decryptAacSample(e,t,n),!this.decrypter.isSync())return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),s=0;for(let i=32;i<e.length-16;i+=160,s+=16)n.set(e.subarray(i,i+16),s);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),s=0;for(let i=32;i<e.length-16;i+=160,s+=16)e.set(n.subarray(s,s+16),i);return e}decryptAvcSample(e,t,n,s,i){let r=S9(i.data),o=this.getAvcEncryptedData(r);this.decryptBuffer(o.buffer).then((l)=>{if(i.data=this.getAvcDecryptedUnit(r,l),!this.decrypter.isSync())this.decryptAvcSamples(e,t,n+1,s)}).catch(s)}decryptAvcSamples(e,t,n,s){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,n=0){if(t>=e.length){s();return}let i=e[t].units;for(;;n++){if(n>=i.length)break;let r=i[n];if(r.data.length<=48||r.type!==1&&r.type!==5)continue;if(this.decryptAvcSample(e,t,n,s,r),!this.decrypter.isSync())return}}}}class u6 extends b0{constructor(e,t){super();this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,n,s){super.resetInitSegment(e,t,n,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:90000,dropped:0}}static probe(e,t){if(!e)return!1;let n=wh(e,0),s=(n==null?void 0:n.length)||0;if(h6(e,s))return!1;for(let i=e.length;s<i;s++)if(AC(e,s))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return xC(e,t)}appendFrame(e,t,n){r6(e,this.observer,t,n,e.manifestCodec);let s=o6(e,t,n,this.basePTS,this.frameIndex);if((s==null?void 0:s.missing)===0)return s}demuxSampleAes(e,t,n){let s=this.demux(e,n),i=this.sampleAes=new H1(this.observer,this.config,t);return new Promise((r)=>{i.decryptAacSamples(s.audioTrack.samples,0,()=>{r(s)})})}}var d6=(e,t)=>{let n=0,s=5;t+=s;let i=new Uint32Array(1),r=new Uint32Array(1),o=new Uint8Array(1);while(s>0){o[0]=e[t];let l=Math.min(s,8),c=8-l;r[0]=4278190080>>>24+c<<c,i[0]=(o[0]&r[0])>>c,n=!n?i[0]:n<<l|i[0],t+=1,s-=l}return n};class m6 extends b0{constructor(e){super();this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,s){super.resetInitSegment(e,t,n,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:s,inputTimeScale:90000,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){let s=p6(e,t,n,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;let t=wh(e,0);if(!t)return!1;let n=t.length;if(e[n]===11&&e[n+1]===119&&j1(t)!==void 0)if(d6(e,n)<16)return!0;else throw Error("Containerless ec-3 is not supported");return!1}}function p6(e,t,n,s,i){if(n+8>t.length)return-1;if(t[n]!==11||t[n+1]!==119)return-1;let r=t[n+4]>>6;if(r>=3)return-1;let l=[48000,44100,32000][r],c=t[n+4]&63,d=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+r]*2;if(n+d>t.length)return-1;let m=t[n+6]>>5,p=0;if(m===2)p+=2;else{if(m&1&&m!==1)p+=2;if(m&4)p+=2}let b=(t[n+6]<<8|t[n+7])>>12-p&1,k=[2,1,2,3,3,4,4,5][m]+b,A=t[n+5]>>3,T=t[n+5]&7,E=new Uint8Array([r<<6|A<<1|T>>2,(T&3)<<6|m<<3|b<<2|c>>4,c<<4&224]),I=1536/l*90000,_=s+i*I,q=t.subarray(n,n+d);return e.config=E,e.channelCount=k,e.samplerate=l,e.samples.push({unit:q,pts:_}),d}class g6 extends b0{resetInitSegment(e,t,n,s){super.resetInitSegment(e,t,n,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:90000,dropped:0}}static probe(e){if(!e)return!1;let t=wh(e,0),n=(t==null?void 0:t.length)||0;if(t&&e[n]===11&&e[n+1]===119&&j1(t)!==void 0&&d6(e,n)<=16)return!1;for(let s=e.length;n<s;n++)if(h6(e,n))return Rn.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return RC(e,t)}appendFrame(e,t,n){if(this.basePTS===null)return;return l6(e,t,n,this.basePTS,this.frameIndex)}}var DC=/\/emsg[-/]ID3/i;class b6{constructor(e,t,n,s=Rn){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=t,this.logger=s}resetTimeStamp(){}resetInitSegment(e,t,n,s){let i=this.videoTrack=Ea("video",1),r=this.audioTrack=Ea("audio",1),o=this.txtTrack=Ea("text",1);if(this.id3Track=Ea("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=g9(e);if(l.video){let{id:c,timescale:h,codec:d,supplemental:m}=l.video;i.id=c,i.timescale=o.timescale=h,i.codec=d,i.supplemental=m}if(l.audio){let{id:c,timescale:h,codec:d}=l.audio;r.id=c,r.timescale=h,r.codec=d}o.id=u9.text,i.sampleDuration=0,i.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return UT(e,"moof")}demux(e,t,n){this.timeOffset=t;let s=e,i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){if(this.remainderData)s=Rr(this.remainderData,e);let c=ZT(s);this.remainderData=c.remainder,i.samples=c.valid||new Uint8Array}else i.samples=s;let o=this.extractID3Track(i,t),l=this.parseFragment(i,r,t,n);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let n=this.timeOffset,s=this.videoTrack,i=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,i,n,t);return{videoTrack:s,audioTrack:Ea(),id3Track:r,textTrack:Ea(),initData:this.initData,sampleData:o}}parseFragment(e,t,n,s){let i=this.initData;if(i&&s){let{samples:r,sampleData:o}=JT(n,e,i,this.logger,s.iframe);return t.samples=r,o}t.samples=eE(n,e)}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let s=Ut(e.samples,["emsg"]);if(s)s.forEach((i)=>{let r=tE(i);if(DC.test(r.schemeIdUri)){let o=g3(r,t),l=r.eventDuration===4294967295?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;if(l<=0.001)l=Number.POSITIVE_INFINITY;let c=r.payload;n.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:zi.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||zi.misbklv;if(r.schemeIdUri.startsWith(o)){let l=g3(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:l,pts:l,type:zi.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function g3(e,t){return lt(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var qC=1,MC=2,Zf=-1;class U1{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,s;if(!n||n.units.length===0)n=e[e.length-1];if((t=n)!=null&&t.units){let i=n.units;s=i[i.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,s=n.length;if(s){let i=n[s-1];e.pts=i.pts,e.dts=i.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let s=t.byteLength;if(s===0)return[];let i=e.naluState||0,r=i===Zf?0:i,o=[],l=0,c=0,h=-1,d=0;if(i===Zf)h=0,d=this.getNALuType(t,0),c=1;while(c<s){let m=t.indexOf(qC,c);if(m===-1)break;c=m+1;let p=m;while(p>0&&t[p-1]===0)p--;if(m-p+(p===0?r:0)<MC)continue;if(h>=0)o.push({data:t.subarray(h,p),type:d});else{let v=this.getLastNalUnit(e.samples);if(v){if(p>0)v.data=Rr(v.data,t.subarray(0,p));else if(r>0)v.data=v.data.subarray(0,v.data.byteLength-r);v.state=0}}if(c<s)h=c,d=this.getNALuType(t,c);else{l=Zf,h=-1;break}}if(l!==Zf){let m=s;while(m>0&&t[m-1]===0)m--;l=s-m+(m===0?r:0)}if(h>=0)o.push({data:t.subarray(h),type:d,state:l});else if(o.length===0&&l!==Zf){let m=this.getLastNalUnit(e.samples);if(m)m.data=Rr(m.data,t),m.state=l}return e.naluState=l,o}}class Xc{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,n=e.byteLength-t,s=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error("no bytes available");s.set(e.subarray(n,n+i)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;if(e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e)this.word<<=e,this.bitsAvailable-=e;else e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e}readBits(e){let t=Math.min(this.bitsAvailable,e),n=this.word>>>32-t;if(e>32)Rn.error("Cannot read more than 32 bits at a time");if(this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");if(t=e-t,t>0&&this.bitsAvailable)return n<<t|this.readBits(t);else return n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();if(1&e)return 1+e>>>1;else return-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class w6 extends U1{parsePES(e,t,n,s,i){let r=i.iframe,o=this.parseNALu(e,n.data,s),l=this.VideoSample,c,h=!1;if(n.data=null,l&&o.length&&!e.audFound)this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);if(o.forEach((d)=>{var m,p;switch(d.type){case 1:{if(r)break;let A=!1;c=!0;let T=d.data;if(h&&T.length>4){let E=this.readSliceType(T);if(E===2||E===4||E===7||E===9)A=!0}if(A){var b;if((b=l)!=null&&b.frame&&!l.key)this.pushAccessUnit(l,e),l=this.VideoSample=null}if(!l)l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts);l.frame=!0,l.key=A;break}case 5:if(c=!0,(m=l)!=null&&m.frame&&!l.key)this.pushAccessUnit(l,e),l=this.VideoSample=null;if(!l)l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts);l.key=!0,l.frame=!0;break;case 6:{if(r)break;c=!0,yh(d.data,1,n.pts,t.samples);break}case 7:{var v,k;c=!0,h=!0;let A=d.data,T=this.readSPS(A);if(!e.sps||e.width!==T.width||e.height!==T.height||((v=e.pixelRatio)==null?void 0:v[0])!==T.pixelRatio[0]||((k=e.pixelRatio)==null?void 0:k[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[A];let E=A.subarray(1,4),I="avc1.";for(let _=0;_<3;_++){let q=E[_].toString(16);if(q.length<2)q="0"+q;I+=q}e.codec=I}break}case 8:c=!0,e.pps=[d.data];break;case 9:if(c=!0,e.audFound=!0,(p=l)!=null&&p.frame)this.pushAccessUnit(l,e),l=null;if(!l)l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:c=!0;break;default:c=!1;break}if(l&&c)l.units.push(d)}),s&&l)this.pushAccessUnit(l,e),this.VideoSample=null}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Xc(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,s=8,i;for(let r=0;r<e;r++){if(s!==0)i=t.readEG(),s=(n+i+256)%256;n=s===0?n:s}}readSPS(e){let t=new Xc(e),n=0,s=0,i=0,r=0,o,l,c,h=t.readUByte.bind(t),d=t.readBits.bind(t),m=t.readUEG.bind(t),p=t.readBoolean.bind(t),b=t.skipBits.bind(t),v=t.skipEG.bind(t),k=t.skipUEG.bind(t),A=this.skipScalingList.bind(this);h();let T=h();if(d(5),b(3),h(),k(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let N=m();if(N===3)b(1);if(k(),k(),b(1),p()){l=N!==3?8:12;for(c=0;c<l;c++)if(p())if(c<6)A(16,t);else A(64,t)}}k();let E=m();if(E===0)m();else if(E===1){b(1),v(),v(),o=m();for(c=0;c<o;c++)v()}k(),b(1);let I=m(),_=m(),q=d(1);if(q===0)b(1);if(b(1),p())n=m(),s=m(),i=m(),r=m();let P=[1,1];if(p()){if(p())switch(h()){case 1:P=[1,1];break;case 2:P=[12,11];break;case 3:P=[10,11];break;case 4:P=[16,11];break;case 5:P=[40,33];break;case 6:P=[24,11];break;case 7:P=[20,11];break;case 8:P=[32,11];break;case 9:P=[80,33];break;case 10:P=[18,11];break;case 11:P=[15,11];break;case 12:P=[64,33];break;case 13:P=[160,99];break;case 14:P=[4,3];break;case 15:P=[3,2];break;case 16:P=[2,1];break;case 255:{P=[h()<<8|h(),h()<<8|h()];break}}}return{width:Math.ceil((I+1)*16-n*2-s*2),height:(2-q)*(_+1)*16-(q?2:4)*(i+r),pixelRatio:P}}}class y6 extends U1{constructor(...e){super(...e);this.initVPS=null}parsePES(e,t,n,s){let i=this.parseNALu(e,n.data,s),r=this.VideoSample,o,l=!1;n.data=null;let c=(h)=>(r=this.VideoSample=this.createVideoSample(h,n.pts,n.dts),r);if(i.forEach((h,d)=>{var m,p;if(this.startsNewAccessUnit(r,e,h,d)){this.pushAccessUnit(r,e);let v=h.type>=16&&h.type<=23;r=c(v),l=!1}switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:if(!r)r=c(!1);r.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var b;if((b=r)!=null&&b.frame&&!r.key)this.pushAccessUnit(r,e),r=this.VideoSample=null}if(!r)r=c(!0);r.key=!0,r.frame=!0;break;case 19:case 20:if(o=!0,(m=r)!=null&&m.frame&&!r.key)this.pushAccessUnit(r,e),r=this.VideoSample=null;if(!r)r=c(!0);r.key=!0,r.frame=!0;break;case 39:o=!0,yh(h.data,2,n.pts,t.samples);break;case 32:if(o=!0,!e.vps){if(typeof e.params!=="object")e.params={};e.params=Gn(e.params,this.readVPS(h.data)),this.initVPS=h.data}e.vps=[h.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],h.data))this.initVPS=e.vps[0],e.sps=e.pps=void 0;if(!e.sps){let v=this.readSPS(h.data);if(e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],typeof e.params!=="object")e.params={};for(let k in v.params)e.params[k]=v.params[k]}if(this.pushParameterSet(e.sps,h.data,e.vps),!r)r=c(!1);break;case 34:if(o=!0,typeof e.params==="object"){if(!e.pps){e.pps=[];let v=this.readPPS(h.data);for(let k in v)e.params[k]=v[k]}this.pushParameterSet(e.pps,h.data,e.vps)}break;case 35:if(o=!0,e.audFound=!0,(p=r)!=null&&p.frame)this.pushAccessUnit(r,e),r=null;if(!r)r=c(!1);break;default:o=!1;break}if(r&&o)r.units.push(h)}),s&&r)this.pushAccessUnit(r,e),this.VideoSample=null}pushParameterSet(e,t,n){if(!!n&&n[0]===this.initVPS||!n&&!e.length)e.push(t)}startsNewAccessUnit(e,t,n,s){if(!e)return!1;if(!t.audFound&&s===0)return!0;if(!e.frame)return!1;let{type:i,data:r}=n;if(i>=32&&i<=35||i===39||i>=41&&i<=44||i>=48&&i<=55)return!0;return i<=31&&r.length>2&&(r[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let s=0;s<e.byteLength;s++){if(s>=2){if(e[s]===3&&e[s-1]===0&&e[s-2]===0)continue}t[n]=e[s],n++}return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){if(super.pushAccessUnit(e,t),this.initVPS)this.initVPS=null}readVPS(e){let t=new Xc(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),s=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:s}}readSPS(e){let t=new Xc(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let s=t.readBits(2),i=t.readBoolean(),r=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),d=t.readUByte(),m=t.readUByte(),p=t.readUByte(),b=t.readUByte(),v=t.readUByte(),k=t.readUByte(),A=t.readUByte(),T=[],E=[];for(let Le=0;Le<n;Le++)T.push(t.readBoolean()),E.push(t.readBoolean());if(n>0)for(let Le=n;Le<8;Le++)t.readBits(2);for(let Le=0;Le<n;Le++){if(T[Le])t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte();if(E[Le])t.readUByte()}t.readUEG();let I=t.readUEG();if(I==3)t.skipBits(1);let _=t.readUEG(),q=t.readUEG(),P=t.readBoolean(),N=0,H=0,V=0,U=0;if(P)N+=t.readUEG(),H+=t.readUEG(),V+=t.readUEG(),U+=t.readUEG();let W=t.readUEG(),ce=t.readUEG(),ue=t.readUEG(),oe=t.readBoolean();for(let Le=oe?0:n;Le<=n;Le++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()){if(t.readBoolean())for(let Je=0;Je<4;Je++)for(let bt=0;bt<(Je===3?2:6);bt++)if(!t.readBoolean())t.readUEG();else{let Ft=Math.min(64,1<<4+(Je<<1));if(Je>1)t.readEG();for(let nn=0;nn<Ft;nn++)t.readEG()}}if(t.readBoolean(),t.readBoolean(),t.readBoolean())t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean();let me=t.readUEG(),he=0;for(let Le=0;Le<me;Le++){let Je=!1;if(Le!==0)Je=t.readBoolean();if(Je){if(Le===me)t.readUEG();t.readBoolean(),t.readUEG();let bt=0;for(let ut=0;ut<=he;ut++){let Ft=t.readBoolean(),nn=!1;if(!Ft)nn=t.readBoolean();if(Ft||nn)bt++}he=bt}else{let bt=t.readUEG(),ut=t.readUEG();he=bt+ut;for(let Ft=0;Ft<bt;Ft++)t.readUEG(),t.readBoolean();for(let Ft=0;Ft<ut;Ft++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let Le=t.readUEG();for(let Je=0;Je<Le;Je++){for(let bt=0;bt<ue+4;bt++)t.readBits(1);t.readBits(1)}}let be=0,ye=1,Te=1,Oe=!0,st=1,We=0;t.readBoolean(),t.readBoolean();let wt=!1;if(t.readBoolean()){if(t.readBoolean()){let mn=t.readUByte(),Vt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Fn=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];if(mn>0&&mn<16)ye=Vt[mn-1],Te=Fn[mn-1];else if(mn===255)ye=t.readBits(16),Te=t.readBits(16)}if(t.readBoolean())t.readBoolean();if(t.readBoolean()){if(t.readBits(3),t.readBoolean(),t.readBoolean())t.readUByte(),t.readUByte(),t.readUByte()}if(t.readBoolean())t.readUEG(),t.readUEG();if(t.readBoolean(),t.readBoolean(),t.readBoolean(),wt=t.readBoolean(),wt)t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(st=t.readBits(32),We=t.readBits(32),t.readBoolean())t.readUEG();if(t.readBoolean()){let Fn=t.readBoolean(),ns=t.readBoolean(),St=!1;if(Fn||ns){if(St=t.readBoolean(),St)t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5);if(t.readBits(4),t.readBits(4),St)t.readBits(4);t.readBits(5),t.readBits(5),t.readBits(5)}for(let it=0;it<=n;it++){Oe=t.readBoolean();let sn=Oe||t.readBoolean(),Lt=!1;if(sn)t.readEG();else Lt=t.readBoolean();let Ln=Lt?1:t.readUEG()+1;if(Fn)for(let is=0;is<Ln;is++){if(t.readUEG(),t.readUEG(),St)t.readUEG(),t.readUEG();t.skipBits(1)}if(ns)for(let is=0;is<Ln;is++){if(t.readUEG(),t.readUEG(),St)t.readUEG(),t.readUEG();t.skipBits(1)}}}}if(t.readBoolean())t.readBoolean(),t.readBoolean(),t.readBoolean(),be=t.readUEG()}let ft=_,It=q;if(P){let Le=1,Je=1;if(I===1)Le=Je=2;else if(I==2)Le=2;ft=_-Le*H-Le*N,It=q-Je*U-Je*V}let Wt=s?["A","B","C"][s]:"",hn=o<<24|l<<16|c<<8|h,zt=0;for(let Le=0;Le<32;Le++)zt=(zt|(hn>>Le&1)<<31-Le)>>>0;let tn=zt.toString(16);if(r===1&&tn==="2")tn="6";return{codecString:`hvc1.${Wt}${r}.${tn}.${i?"H":"L"}${A}.B0`,params:{general_tier_flag:i,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[d,m,p,b,v,k],general_level_idc:A,bit_depth:W+8,bit_depth_luma_minus8:W,bit_depth_chroma_minus8:ce,min_spatial_segmentation_idc:be,chroma_format_idc:I,frame_rate:{fixed:Oe,fps:We/st}},width:ft,height:It,pixelRatio:[ye,Te]}}readPPS(e){let t=new Xc(this.ebsp2rbsp(e));if(t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean())t.skipUEG();t.skipEG(),t.skipEG(),t.skipBits(4);let s=t.readBoolean(),i=t.readBoolean(),r=1;if(i&&s)r=0;else if(i)r=3;else if(s)r=2;return{parallelismType:r}}matchSPS(e,t){return ia(e).substring(3)===ia(t).substring(3)}}var Ks=188;class fo{constructor(e,t,n,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=n,this.logger=s,this.videoParser=null}static probe(e,t){let n=fo.syncOffset(e);if(n>0)t.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`);return n!==-1}static syncOffset(e){let t=e.length,n=Math.min(Ks*5,t-Ks)+1,s=0;while(s<n){let i=!1,r=-1,o=0;for(let l=s;l<t;l+=Ks)if(e[l]===71&&(t-l===Ks||e[l+Ks]===71)){if(o++,r===-1){if(r=l,r!==0)n=Math.min(r+Ks*99,e.length-Ks)+1}if(!i)i=a0(e,l)===0;if(i&&o>1&&(r===0&&o>2||l+Ks>n))return r}else if(o)return-1;else break;s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:u9[e],pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,n,s,i,r){if(this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=fo.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new v6(this.logger):null,this._audioTrack=fo.createTrack("audio",s),this._id3Track=fo.createTrack("id3"),this._txtTrack=fo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=n,e)this.demux(e,0,r,(i==null?void 0:i.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;if(e)e.pesData=null;if(t)t.pesData=null;if(n)n.pesData=null;this.aacOverFlow=null,this.remainderData=null}demux(e,t,n,s=!1,i=!1){if(!s)this.sampleAes=null;let r,o=this._videoTrack,l=this.videoIntegrityChecker,c=this._audioTrack,h=this._id3Track,d=this._txtTrack,m=n.iframe,{pid:p,pesData:b}=o,v=c.pid,k=h.pid,A=this._klvPid,T=c.pesData,E=h.pesData,I=null,_=null,q=this.pmtParsed,P=this._pmtId,N=e.length;if(this.remainderData)e=Rr(this.remainderData,e),N=e.length,this.remainderData=null;if(N<Ks&&!i)return this.remainderData=e,{audioTrack:c,videoTrack:o,id3Track:h,textTrack:d};let H=Math.max(0,fo.syncOffset(e));if(N-=(N-H)%Ks,N<e.byteLength&&!i)this.remainderData=new Uint8Array(e.buffer,N,e.buffer.byteLength-N);let V=0;for(let W=H;W<N;W+=Ks)if(e[W]===71){let ce=!!(e[W+1]&64),ue=a0(e,W),oe=(e[W+3]&48)>>4,ae;if(oe>1){if(ae=W+5+e[W+4],ae===W+Ks)continue}else ae=W+4;switch(ue){case p:if(ce){if(b&&!(l!=null&&l.isCorrupted)&&(r=Dl(b,this.logger))){if(this.readyVideoParser(o.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(o,d,r,!1,n)}b={data:[],size:0},l==null||l.reset(p)}if(l==null||l.handlePacket(e.subarray(W)),b)b.data.push(e.subarray(ae,W+Ks)),b.size+=W+Ks-ae;break;case v:if(m)break;if(ce){if(T&&(r=Dl(T,this.logger)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,r,n);break;case"mp3":this.parseMPEGPES(c,r);break;case"ac3":this.parseAC3PES(c,r);break}T={data:[],size:0}}if(T)T.data.push(e.subarray(ae,W+Ks)),T.size+=W+Ks-ae;break;case k:if(m)break;if(ce){if(E&&(r=Dl(E,this.logger)))this.parseID3PES(h,r);E={data:[],size:0}}if(E)E.data.push(e.subarray(ae,W+Ks)),E.size+=W+Ks-ae;break;case A:if(m)break;if(ce){if(I&&(r=Dl(I,this.logger)))this.parseKlvPES(h,r);I={data:[],size:0}}if(I)I.data.push(e.subarray(ae,W+Ks)),I.size+=W+Ks-ae;break;case 0:if(ce)ae+=e[ae]+1;P=this._pmtId=FC(e,ae);break;case P:{if(ce)ae+=e[ae]+1;let te=LC(e,ae,this.typeSupported,s,this.observer,this.logger,this.config,n);if(p=te.videoPid,p>0)o.pid=p,o.segmentCodec=te.segmentVideoCodec;if(v=te.audioPid,v>0)c.pid=v,c.segmentCodec=te.segmentAudioCodec;if(k=te.id3Pid,k>0)h.pid=k;if(A=te.klvPid,A>0)this._klvPid=A;if(_!==null&&!q)this.logger.warn(`MPEG-TS PMT found at ${W} after unknown PID '${_}'. Backtracking to sync byte @${H} to parse all TS packets.`),_=null,W=H-188;q=this.pmtParsed=!0;break}case 17:case 8191:break;default:_=ue;break}}else V++;if(V>0)o1(this.observer,Error(`Found ${V} TS packet/s that do not start with 0x47`),n,void 0,this.logger);o.pesData=b,c.pesData=T,h.pesData=E;let U={audioTrack:c,videoTrack:o,id3Track:h,textTrack:d};if(i)this.extractRemainingSamples(U,n);return U}flush(e,t){let{remainderData:n}=this;this.remainderData=null;let s;if(n)s=this.demux(n,0,t,!1,!0);else s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack};if(this.extractRemainingSamples(s,t),this.sampleAes)return this.decrypt(s,this.sampleAes);return s}extractRemainingSamples(e,t){let{audioTrack:n,videoTrack:s,id3Track:i,textTrack:r}=e,o=s.pesData,l=n.pesData,c=i.pesData,h=this.videoIntegrityChecker,d;if(o&&!(h!=null&&h.isCorrupted)&&(d=Dl(o,this.logger))){if(this.readyVideoParser(s.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(s,r,d,!0,t),s.pesData=null}else s.pesData=o;if(l&&(d=Dl(l,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,d,t);break;case"mp3":this.parseMPEGPES(n,d);break;case"ac3":this.parseAC3PES(n,d);break}n.pesData=null}else{if(l!=null&&l.size)this.logger.log("last AAC PES packet truncated,might overlap between fragments");n.pesData=l}if(c&&(d=Dl(c,this.logger)))this.parseID3PES(i,d),i.pesData=null;else i.pesData=c}demuxSampleAes(e,t,n,s){let i=this.demux(e,n,s,!0,!this.config.progressive),r=this.sampleAes=new H1(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){if(this.videoParser===null){if(e==="avc")this.videoParser=new w6;else if(e==="hevc")this.videoParser=new y6}}decrypt(e,t){return new Promise((n)=>{let{audioTrack:s,videoTrack:i}=e;if(s.samples&&s.segmentCodec==="aac")t.decryptAacSamples(s.samples,0,()=>{if(i.samples)t.decryptAvcSamples(i.samples,0,0,()=>{n(e)});else n(e)});else if(i.samples)t.decryptAvcSamples(i.samples,0,0,()=>{n(e)})})}destroy(){if(this.observer)this.observer.removeAllListeners();this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,n){let s=0,i=this.aacOverFlow,r=t.data;if(i){this.aacOverFlow=null;let m=i.missing,p=i.sample.unit.byteLength;if(m===-1)r=Rr(i.sample.unit,r);else{let b=p-m;i.sample.unit.set(r.subarray(0,m),b),e.samples.push(i.sample),s=i.missing}}let o,l;for(o=s,l=r.length;o<l-1;o++)if(r0(r,o))break;if(o!==s){let m,p=o<l-1;if(p)m=`AAC PES did not start with ADTS header,offset:${o}`;else m="No ADTS header found in AAC PES";if(o1(this.observer,Error(m),n,p,this.logger),!p)return}r6(e,this.observer,r,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){let m=a6(e.samplerate);c=i.sample.pts+m}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,d;while(o<l)if(d=o6(e,r,o,c,h),o+=d.length,!d.missing){h++;for(;o<l-1;o++)if(r0(r,o))break}else{this.aacOverFlow=d;break}}parseMPEGPES(e,t){let n=t.data,s=n.length,i=0,r=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}while(r<s)if(f6(n,r)){let l=l6(e,n,r,o,i);if(l)r+=l.length,i++;else break}else r++}parseAC3PES(e,t){{let{data:n,pts:s}=t;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let i=n.length,r=0,o=0,l;while(o<i&&(l=p6(e,n,o,s,r++))>0)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let n=Gn({},t,{type:this._videoTrack?zi.emsg:zi.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}parseKlvPES(e,t){var n;let s=(n=t.pts)!=null?n:t.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let i=t.data;if(i.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let r=0;while(r<i.length){var o;if(r+16>i.length)break;let l=r;if(r+=16,r>=i.length)break;let c=i[r];r+=1;let h=0;if(c&128){let b=c&127;if(b===0||b>4||r+b>i.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let v=0;v<b;v++)h=h<<8|i[r+v];r+=b}else h=c;if(r+h>i.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let d=r+h,m=i.subarray(l,d),p={data:m,len:m.byteLength,pts:s,dts:(o=t.dts)!=null?o:s,type:zi.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(p),r=d}}}function a0(e,t){return((e[t+1]&31)<<8)+e[t+2]}function FC(e,t){return(e[t+10]&31)<<8|e[t+11]}function LC(e,t,n,s,i,r,o,l){let c={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=(e[t+1]&15)<<8|e[t+2],d=t+3+h-4,m=(e[t+10]&15)<<8|e[t+11];t+=12+m;while(t<d){let p=a0(e,t),b=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!s){Mg("ADTS AAC",r);break}case 15:if(c.audioPid===-1)c.audioPid=p;break;case 21:if(c.id3Pid===-1)c.id3Pid=p;break;case 219:if(!s){Mg("H.264",r);break}case 27:if(c.videoPid===-1)c.videoPid=p;break;case 3:case 4:if(!n.mpeg&&!n.mp3)r.log("MPEG audio found, not supported in this browser");else if(c.audioPid===-1)c.audioPid=p,c.segmentAudioCodec="mp3";break;case 193:if(!s){Mg("AC-3",r);break}case 129:if(!n.ac3)r.log("AC-3 audio found, not supported in this browser");else if(c.audioPid===-1)c.audioPid=p,c.segmentAudioCodec="ac3";break;case 6:if(b>0){let v=t+5,k=b;while(k>2){switch(e[v]){case 106:if(c.audioPid===-1)if(n.ac3!==!0)r.log("AC-3 audio found, not supported in this browser for now");else c.audioPid=p,c.segmentAudioCodec="ac3";break;case 5:if(c.klvPid===-1&&o.enableEmsgKLVMetadata)c.klvPid=p,r.log(`KLV metadata PID found: ${p}`);break}let T=e[v+1]+2;v+=T,k-=T}}break;case 194:case 135:return o1(i,Error("Unsupported EC-3 in M2TS found"),l,void 0,r),c;case 36:if(c.videoPid===-1)c.videoPid=p,c.segmentVideoCodec="hevc",r.log("HEVC in M2TS found");break}t+=b+5}return c}function o1(e,t,n,s,i){i.warn(`parsing error: ${t.message}`),e.emit(O.ERROR,O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:n,error:t,reason:t.message})}function Mg(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Dl(e,t){let n=0,s,i,r,o,l,c=e.data;if(!e||e.size===0)return null;while(c[0].length<19&&c.length>1)c[0]=Rr(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>e.size-6)return null;let d=s[7];if(d&192)if(o=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64){if(l=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,o-l>5400000)t.warn(`${Math.round((o-l)/90000)}s delta between PTS and DTS, align them`),o=l}else l=o;r=s[8];let m=r+9;if(e.size<=m)return null;e.size-=m;let p=new Uint8Array(e.size);for(let b=0,v=c.length;b<v;b++){s=c[b];let k=s.byteLength;if(m)if(m>k){m-=k;continue}else s=s.subarray(m),k-=m,m=0;p.set(s,n),n+=k}if(i)i-=r+3;return{data:p,pts:o,dts:l,len:i}}return null}class v6{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=a0(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let n=(e[3]&48)>>4;if(n===0)return;let s=e[3]&15,i=this.lastContinuityCounter;this.lastContinuityCounter=s;let r=(n&1)!=0;if((n&2)!=0&&e[4]!=0&&(e[5]&128)!=0)return;if(i<0)return;let c=r?i+1&15:i;if(s!==c){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${s}, Expected-CC=${c} Last-CC=${i}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class S6{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);else if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);else if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}return}}var o0,OC={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Fg=new Uint8Array([0,0,0,0,0,0,0,0]),PC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),NC=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),BC=new Uint8Array([0,0,0,0,0,0,0,0]),eh=new Uint8Array([0,0,0,0,0,0,0,1]),b3=new Uint8Array([105,115,111,109]),HC=new Uint8Array([97,118,99,49]),UC=new Uint8Array([0,0,0,1]);class dt{static box(e,...t){let n=8,s=t.length,i=s;while(s--)n+=t[s].byteLength;let r=new Uint8Array(n);Gs(r,0,n),Gs(r,4,e);for(s=0,n=8;s<i;s++)r.set(t[s],n),n+=t[s].byteLength;return r}static hdlr(e){return dt.box(Pt.hdlr,OC[e])}static mdat(e){return dt.box(Pt.mdat,e)}static mdhd(e,t){t*=e;let n=Math.floor(t/(Aa+1)),s=Math.floor(t%(Aa+1));return dt.box(Pt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return dt.box(Pt.mdia,dt.mdhd(e.timescale||0,e.duration||0),dt.hdlr(e.type),dt.minf(e))}static mfhd(e){return dt.box(Pt.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){if(e.type==="audio")return dt.box(Pt.minf,dt.box(Pt.smhd,BC),dt.DINF,dt.stbl(e));else return dt.box(Pt.minf,dt.box(Pt.vmhd,NC),dt.DINF,dt.stbl(e))}static moof(e,t,n){return dt.box(Pt.moof,dt.mfhd(e),dt.traf(n,t))}static moov(e){let t=e.length,n=[];while(t--)n[t]=dt.trak(e[t]);return dt.box.apply(null,[Pt.moov,dt.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(dt.mvex(e)))}static mvex(e){let t=e.length,n=[];while(t--)n[t]=dt.trex(e[t]);return dt.box.apply(null,[Pt.mvex,...n])}static mvhd(e,t){t*=e;let n=Math.floor(t/(Aa+1)),s=Math.floor(t%(Aa+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return dt.box(Pt.mvhd,i)}static sdtp(e){let t=e.samples||[],n=new Uint8Array(4+t.length),s,i;for(s=0;s<t.length;s++)i=t[s].flags,n[s+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return dt.box(Pt.sdtp,n)}static stbl(e){return dt.box(Pt.stbl,dt.stsd(e),dt.box(Pt.stts,Fg),dt.box(Pt.stsc,Fg),dt.box(Pt.stsz,PC),dt.box(Pt.stco,Fg))}static avc1(e){let t=[],n=[],s,i,r;for(s=0;s<e.sps.length;s++)i=e.sps[s],r=i.byteLength,t.push(r>>>8&255),t.push(r&255),t=t.concat(Array.prototype.slice.call(i));for(s=0;s<e.pps.length;s++)i=e.pps[s],r=i.byteLength,n.push(r>>>8&255),n.push(r&255),n=n.concat(Array.prototype.slice.call(i));let o=dt.box(Pt.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(n))),{width:l,height:c}=e,h=e.pixelRatio[0],d=e.pixelRatio[1];return dt.box(Pt.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,dt.box(Pt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dt.box(Pt.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config,n=t.length;return new Uint8Array([0,0,0,0,3,23+n,0,1,0,4,15+n,64,21,0,0,0,0,0,0,0,0,0,0,0,5,n,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return dt.box(Pt.mp4a,dt.audioStsd(e),dt.box(Pt.esds,dt.esds(e)))}static mp3(e){return dt.box(Pt[".mp3"],dt.audioStsd(e))}static ac3(e){return dt.box(Pt["ac-3"],dt.audioStsd(e),dt.box(Pt.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return dt.box(Pt.stsd,eh,dt.mp4a(e));if(t==="ac3"&&e.config)return dt.box(Pt.stsd,eh,dt.ac3(e));if(t==="mp3"&&e.codec==="mp3")return dt.box(Pt.stsd,eh,dt.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return dt.box(Pt.stsd,eh,dt.avc1(e));if(t==="hevc"&&e.vps)return dt.box(Pt.stsd,eh,dt.hvc1(e))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,n=(e.duration||0)*(e.timescale||0),s=e.width||0,i=e.height||0,r=Math.floor(n/(Aa+1)),o=Math.floor(n%(Aa+1));return dt.box(Pt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,i>>8&255,i&255,0,0]))}static traf(e,t){let n=dt.sdtp(e),s=e.id,i=Math.floor(t/(Aa+1)),r=Math.floor(t%(Aa+1));return dt.box(Pt.traf,dt.box(Pt.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),dt.box(Pt.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255])),dt.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,dt.box(Pt.trak,dt.tkhd(e),dt.mdia(e))}static trex(e){let t=e.id;return dt.box(Pt.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let n=e.samples||[],s=n.length,i=12+16*s,r=new Uint8Array(i),o,l,c,h,d,m;t+=8+i,r.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0);for(o=0;o<s;o++)l=n[o],c=l.duration,h=l.size,d=l.flags,m=l.cts,r.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,m>>>24&255,m>>>16&255,m>>>8&255,m&255],12+16*o);return dt.box(Pt.trun,r)}static initSegment(e){let t=dt.moov(e);return Rr(dt.FTYP,t)}static hvc1(e){let t=e.params,n=[e.vps,e.sps,e.pps],s=4,i=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),n.length]),r=i.length;for(let b=0;b<n.length;b+=1){r+=3;for(let v=0;v<n[b].length;v+=1)r+=2+n[b][v].length}let o=new Uint8Array(r);o.set(i,0),r=i.length;let l=n.length-1;for(let b=0;b<n.length;b+=1){o.set(new Uint8Array([32+b|(b===l?128:0),0,n[b].length]),r),r+=3;for(let v=0;v<n[b].length;v+=1)o.set(new Uint8Array([n[b][v].length>>8,n[b][v].length&255]),r),r+=2,o.set(n[b][v],r),r+=n[b][v].length}let c=dt.box(Pt.hvcC,o),{width:h,height:d}=e,m=e.pixelRatio[0],p=e.pixelRatio[1];return dt.box(Pt.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,dt.box(Pt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),dt.box(Pt.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}o0=dt;dt.FTYP=o0.box(Pt.ftyp,b3,UC,b3,HC);dt.DINF=o0.box(Pt.dinf,o0.box(Pt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var k6=90000;function z1(e,t,n=1,s=!1){let i=e*t*n;return s?Math.round(i):i}function zC(e,t,n=1,s=!1){return z1(e,t,1/n,s)}function th(e,t=!1){return z1(e,1000,1/k6,t)}function GC(e,t=1){return z1(e,k6,1/t)}function w3(e){let{baseTime:t,timescale:n,trackId:s}=e;return`${t/n} (${t}/${n}) trackId: ${s}`}var VC=1e4,$C=1024,XC=1152,WC=1536,l1=8589934592;function y3(e,t,n,s){return{duration:t,size:n,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}class mh extends Ji{constructor(e,t,n,s){super("mp4-remuxer",s);this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;if(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)this.log(`Reset initPTS: ${t?w3(t):t} > ${e?w3(e):e}`);this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,n=e[0].pts,s=e.reduce((i,r)=>{let o=r.pts,l=o-i;if(l<-4294967296)t=!0,o=wr(o,n),l=o-i;if(l>0)return i;return o},n);if(t)this.debug("PTS rollover detected");return s}remux(e,t,n,s,i,r,o,l,c){let h,d,m,p,b,v,k=i,A=i,E=!c.iframe&&e.pid>-1,I=t.pid>-1,_=t.samples.length,q=e.samples.length>0,P=o&&_>0||_>1;if((!E||q)&&(!I||P)||this.ISGenerated||o){if(this.ISGenerated){var H,V,U,W;let ae=this.videoTrackConfig;if(ae&&(t.width!==ae.width||t.height!==ae.height||((H=t.pixelRatio)==null?void 0:H[0])!==((V=ae.pixelRatio)==null?void 0:V[0])||((U=t.pixelRatio)==null?void 0:U[1])!==((W=ae.pixelRatio)==null?void 0:W[1]))||!ae&&P||this.nextAudioTs===null&&q)this.resetInitSegment()}if(!this.ISGenerated)m=this.generateIS(e,t,i,r);let ce=this.isVideoContiguous,ue=-1,oe;if(P){if(ue=KC(t.samples),!ce&&this.config.forceKeyFrameOnDiscontinuity){if(v=!0,ue>0){this.warn(`Dropped ${ue} out of ${_} video samples due to a missing keyframe`);let ae=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(ue),t.dropped+=ue,A+=(t.samples[0].pts-ae)/t.inputTimeScale,oe=A}else if(ue===-1)this.warn(`No keyframe found out of ${_} video samples`),v=!1}}if(this.ISGenerated){if(q&&P&&i){let ae=this.getVideoStartPts(t.samples),me=(wr(e.samples[0].pts,ae)-ae)/t.inputTimeScale;k+=Math.max(0,me),A+=Math.max(0,-me)}if(q){if(!e.samplerate)this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(e,t,i,r);if(d=this.remuxAudio(e,k,this.isAudioContiguous,r,I||P||l===kt.AUDIO?A:void 0,c),P){let ae=d?d.endPTS-d.startPTS:0;if(!t.inputTimeScale)this.warn("regenerate InitSegment as video detected"),m=this.generateIS(e,t,i,r);h=this.remuxVideo(t,A,ce,ae,c)}}else if(P)h=this.remuxVideo(t,A,ce,0,c);if(h)h.firstKeyFrame=ue,h.independent=ue!==-1,h.firstKeyFramePTS=oe}}if(this.ISGenerated&&this._initPTS&&this._initDTS){if(n.samples.length)b=x6(n,i,this._initPTS,this._initDTS);if(s.samples.length)p=A6(s,i,this._initPTS)}return{audio:d,video:h,initSegment:m,independent:v,text:p,id3:b}}computeInitPts(e,t,n,s){let i=Math.round(n*t),r=wr(e,i);if(r<i){this.log(`Adjusting PTS for rollover in timeline near ${(i-r)/t} ${s}`);while(r<i)r+=l1}return r-i}generateIS(e,t,n,s){let i=e.samples,r=t.samples,o=this.typeSupported,l={},c=this._initPTS,h=!c||s,d="audio/mp4",m,p,b,v=-1;if(h)m=p=1/0;if(e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":if(o.mpeg)d="audio/mpeg",e.codec="";else if(o.mp3)e.codec="mp3";break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):dt.initSegment([e]),metadata:{channelCount:e.channelCount}},h){v=e.id,b=e.inputTimeScale;let k=this.computeInitPts(i[0].pts,b,n,"audio");if(!c||b!==c.timescale||n===0&&k<c.baseTime)m=p=k}}if(t.sps&&t.pps&&r.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:dt.initSegment([t]),metadata:{width:t.width,height:t.height}},h){v=t.id,b=t.inputTimeScale;let k=this.getVideoStartPts(r),A=wr(r[0].dts,k),T=this.computeInitPts(A,b,n,"video"),E=this.computeInitPts(k,b,n,"video");if(!c||b!==c.timescale||lt(m)||n===0&&E<c.baseTime)p=Math.min(p,T),m=Math.min(m,T)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length){if(this.ISGenerated=!0,h&&lt(m)){if(c)this.warn(`Timestamps at playlist time: ${s?"":"~"}${n} ${m/b} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`);this.log(`Found initPTS at playlist time: ${n} offset: ${m/b} (${m}/${b}) trackId: ${v}`),this._initPTS={baseTime:m,timescale:b,trackId:v},this._initDTS={baseTime:p,timescale:b,trackId:v}}else m=b=void 0;return{tracks:l,initPTS:m,timescale:b,trackId:v}}}remuxVideo(e,t,n,s,i){let{inputTimeScale:r,samples:o}=e,l=[],c=o.length,h=this._initPTS,d=h.baseTime*r/h.timescale,m=this.nextVideoTs,p=8,b=this.videoSampleDuration,v,k,{POSITIVE_INFINITY:A,NEGATIVE_INFINITY:T}=Number,E=!1;if(!n||m===null){let be=d+t*r,ye=o[0].pts-wr(o[0].dts,o[0].pts);if(lh()&&m!==null&&Math.abs(be-ye-(m+d))<15000)n=!0;else m=be-ye-d}let I=m+d;for(let be=0;be<c;be++){let ye=o[be];if(ye.pts=wr(ye.pts,I),ye.dts=wr(ye.dts,I),ye.dts<o[be>0?be-1:be].dts)E=!0}if(E)o.sort(function(be,ye){let Te=be.dts-ye.dts,Oe=be.pts-ye.pts;return Te||Oe});v=o[0].dts,k=o[o.length-1].dts;let _=k-v,q=_?Math.round(_/(c-1)):b||e.inputTimeScale/30;if(n){let be=v-I,ye=be>q,Te=be<-1;if(ye||Te){if(ye)this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${th(be,!0)} ms (${be}dts) hole between fragments detected at ${t.toFixed(3)}`);else this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${th(-be,!0)} ms (${be}dts) overlapping between fragments detected at ${t.toFixed(3)}`);if(!Te||I>=o[0].pts||lh()){v=I;let Oe=o[0].pts-be;if(ye)o[0].dts=v,o[0].pts=Oe;else{let st=!0;for(let We=0;We<o.length;We++){if(o[We].dts>Oe&&st)break;let wt=o[We].pts;if(o[We].dts-=be,o[We].pts-=be,We<o.length-1){let xt=o[We+1].pts,ft=o[We].pts,It=xt<=ft,Wt=xt<=wt;st=It==Wt}}}this.log(`Video: Initial PTS/DTS adjusted: ${th(Oe,!0)}/${th(v,!0)}, delta: ${th(be,!0)} ms`)}}}v=Math.max(0,v);let P=0,N=0,H=v;for(let be=0;be<c;be++){let ye=o[be],Te=ye.units,Oe=Te.length,st=0;for(let We=0;We<Oe;We++)st+=Te[We].data.length;if(N+=st,P+=Oe,ye.length=st,ye.dts<H)ye.dts=H,H+=q/4|0||1;else H=ye.dts;A=Math.min(ye.pts,A),T=Math.max(ye.pts,T)}k=o[c-1].dts;let V=N+4*P+8,U;try{U=new Uint8Array(V)}catch(be){this.observer.emit(O.ERROR,O.ERROR,{type:Et.MUX_ERROR,details:ve.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:be,bytes:V,reason:`fail allocating video mdat ${V}`});return}Gs(U,0,V),Gs(U,4,Pt.mdat);let W=!1,{POSITIVE_INFINITY:ce,POSITIVE_INFINITY:ue,NEGATIVE_INFINITY:oe,NEGATIVE_INFINITY:ae}=Number;for(let be=0;be<c;be++){let ye=o[be],Te=ye.units,Oe=0;for(let wt=0,xt=Te.length;wt<xt;wt++){let ft=Te[wt],It=ft.data,Wt=ft.data.byteLength;Gs(U,p,Wt),p+=4,U.set(It,p),p+=Wt,Oe+=4+Wt}let st;if(be<c-1)b=o[be+1].dts-ye.dts,st=o[be+1].pts-ye.pts;else{let wt=this.config,xt=be>0?ye.dts-o[be-1].dts:q;if(st=be>0?ye.pts-o[be-1].pts:q,wt.stretchShortVideoTrack&&this.nextAudioTs!==null){let ft=Math.floor(wt.maxBufferHole*r),It=(s?A+s*r:this.nextAudioTs+d)-ye.pts;if(It>ft){if(b=It-xt,b<0)b=xt;else W=!0;this.log(`It is approximately ${It/90} ms to the next segment; using duration ${b/90} ms for the last video frame.`)}else b=xt}else b=xt}let We=Math.round(ye.pts-ye.dts);if(ce=Math.min(ce,b),oe=Math.max(oe,b),ue=Math.min(ue,st),ae=Math.max(ae,st),!n&&be===0&&We>b){let wt=Math.round(We/q)*q;if(wt-We===1)this.log(`pad first CTS ${We} -> ${wt} of sn: ${i.sn}`),We=wt}l.push(y3(ye.key,b,Oe,We))}if(l.length){let be=lh();if(be){if(be<70){let ye=l[0].flags;ye.dependsOn=2,ye.isNonSync=0}}else if(oE()){if(ae-ue<oe-ce&&q/oe<0.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let ye=v;for(let Te=0,Oe=l.length;Te<Oe;Te++){let st=ye+l[Te].duration,We=ye+l[Te].cts;if(Te<Oe-1){let wt=st+l[Te+1].cts;l[Te].duration=wt-We}else l[Te].duration=Te?l[Te-1].duration:q;l[Te].cts=0,ye=st}}}}b=W||!b?q:b;let te=k+b;if(this.nextVideoTs=m=te-d,this.videoSampleDuration=b,this.isVideoContiguous=!0,i.iframe)if(l.length===1)l[0].duration=b=i.duration*r,this.nextVideoTs=m=v+b-d;else this.warn(`Not adjusting IFrame duration (sample count ${l.length})`);let me=dt.moof(i.sn,v,Gn(e,{samples:l})),he="video",we={data1:me,data2:U,startPTS:(A-d)/r,endPTS:(T+b-d)/r,startDTS:(v-d)/r,endDTS:m/r,type:he,hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,we}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return XC;case"ac3":return WC;default:return $C}}remuxAudio(e,t,n,s,i,r){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,c=o/l,h=this.getSamplesPerFrame(e),d=h*c,m=this._initPTS,p=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,b=[],v=i!==void 0,k=e.samples,A=p?0:8,T=this.nextAudioTs||-1,E=m.baseTime*o/m.timescale,I=E+t*o;if(this.isAudioContiguous=n=n||k.length&&T>0&&(s&&Math.abs(I-(T+E))<9000||Math.abs(wr(k[0].pts,I)-(T+E))<20*d),k.forEach(function(te){te.pts=wr(te.pts,I)}),!n||T<0){let te=k.length;if(k=k.filter((me)=>me.pts>=0),te!==k.length)this.warn(`Removed ${k.length-te} of ${te} samples (initPTS ${E} / ${o})`);if(!k.length)return;if(i===0)T=0;else if(s&&!v)T=Math.max(0,I-E);else T=k[0].pts-E}if(e.segmentCodec==="aac"){let te=this.config.maxAudioFramesDrift;for(let me=0,he=T+E;me<k.length;me++){let we=k[me],be=we.pts,ye=be-he,Te=Math.abs(1000*ye/o);if(ye<=-te*d&&v){if(me===0)this.warn(`Audio frame @ ${(be/o).toFixed(3)}s overlaps marker by ${Math.round(1000*ye/o)} ms.`),this.nextAudioTs=T=be-E,he=be}else if(ye>=te*d&&Te<VC&&v){let Oe=Math.round(ye/d);he=be-Oe*d;while(he<0&&Oe&&d)Oe--,he+=d;if(me===0)this.nextAudioTs=T=he-E;this.warn(`Injecting ${Oe} audio frames @ ${((he-E)/o).toFixed(3)}s due to ${Math.round(1000*ye/o)} ms gap.`);for(let st=0;st<Oe;st++){let We=S6.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);if(!We)this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),We=we.unit.subarray();k.splice(me,0,{unit:We,pts:he}),he+=d,me++}}we.pts=he,he+=d}}let _=null,q=null,P,N=0,H=k.length;while(H--)N+=k[H].unit.byteLength;for(let te=0,me=k.length;te<me;te++){let he=k[te],{unit:we,pts:be}=he;if(q!==null){let Te=b[te-1];Te.duration=Math.round((be-q)/c)}else{if(n&&e.segmentCodec==="aac")be=T+E;if(_=be,N>0){N+=A;try{P=new Uint8Array(N)}catch(Te){this.observer.emit(O.ERROR,O.ERROR,{type:Et.MUX_ERROR,details:ve.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:Te,bytes:N,reason:`fail allocating audio mdat ${N}`});return}if(!p)Gs(P,0,N),Gs(P,4,Pt.mdat)}else return}if(P)P.set(we,A);let ye=we.byteLength;A+=ye,b.push(y3(!0,h,ye,0)),q=be}let V=b.length;if(!V)return;let U=b[b.length-1];T=q-E,this.nextAudioTs=T+c*U.duration;let W=p?new Uint8Array(0):dt.moof(e.sequenceNumber++,_/c,Gn({},e,{samples:b}));e.samples=[];let ce=(_-E)/o,ue=this.nextAudioTs/o,ae={data1:W,data2:P,startPTS:ce,endPTS:ue,startDTS:ce,endDTS:ue,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,ae}}function wr(e,t){let n;if(t===null)return e;if(t<e)n=-l1;else n=l1;while(Math.abs(e-t)>4294967296)e+=n;return e}function KC(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function x6(e,t,n,s){let i=e.samples.length;if(!i)return;let r=e.inputTimeScale;for(let l=0;l<i;l++){let c=e.samples[l];c.pts=wr(c.pts-n.baseTime*r/n.timescale,t*r)/r,c.dts=wr(c.dts-s.baseTime*r/s.timescale,t*r)/r}let o=e.samples;return e.samples=[],{samples:o}}function A6(e,t,n){let s=e.samples.length;if(!s)return;let i=e.inputTimeScale;for(let o=0;o<s;o++){let l=e.samples[o];l.pts=wr(l.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((o,l)=>o.pts-l.pts);let r=e.samples;return e.samples=[],{samples:r}}class T6 extends Ji{constructor(e,t,n,s){super("passthrough-remuxer",s);this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){if(this.observer)this.observer.removeAllListeners();this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;if(t&&e){if(t.baseTime===e.baseTime&&t.timescale===e.timescale)return}this.initPTS=e}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,n,s){this.audioCodec=t,this.videoCodec=n,this.decryptdata=s,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,n){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:r,video:o}=this.initData=n||g9(e);if(t)$T(e,t);else{let c=r||o;if(c!=null&&c.encrypted)this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}if(r)s=v3(r,Zn.AUDIO,this);if(o)i=v3(o,Zn.VIDEO,this);let l={};if(r&&o)l.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"};else if(r)l.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"};else if(o)l.video={container:"video/mp4",codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"};else this.warn("initSegment does not contain moov or trak boxes.");this.initTracks=l}remux(e,t,n,s,i,r,o,l,c,h,d){var m,p;let{initPTS:b,lastEndTime:v}=this,k={audio:void 0,video:void 0,text:void 0,id3:n,initSegment:void 0};if(!lt(v))v=this.lastEndTime=i||0;let A=t.samples;if(!A.length)return k;let T=this.pendingInitSegment;if(T)this.pendingInitSegment=void 0,this.generateInitSegment(T,this.decryptdata,h);let E={initPTS:void 0,timescale:void 0,trackId:void 0},I=this.initData;if(!((m=I)!=null&&m.length))this.generateInitSegment(A),I=this.initData;if(!((p=I)!=null&&p.length))return this.warn("Failed to generate initSegment."),k;if(c.iframe&&I.audio&&I.video){var _;let Le=(_=this.initTracks)==null||(_=_.audiovideo)==null?void 0:_.initSegment,Je=Le?BT(Le):null;if(Je){var q;if(this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(Je,this.decryptdata),(q=this.initData)!=null&&q.length)I=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0}}if(this.emitInitSegment)E.tracks=this.initTracks,k.initSegment=E,this.emitInitSegment=!1;let P=c.iframe,N=d&&(!P||d.includeSampleDetails)?d.tracks:QT(A,I,c,this,P),H=I.audio?N[I.audio.id]:null,V=I.video?N[I.video.id]:null,U=!!I.audio,W=!!I.video,ce="";if(U)ce+="audio";if(W)ce+="video";let ue=Td(V,1/0),oe=Td(H,1/0),ae=Td(V,0,!0),te=Td(H,0,!0),me=i,he=0;if(V&&H&&I.audio&&(oe>ae||ue>te))this.warn(`audio and video track sample timestamps do not overlap. v: ${ue}-${ae} a: ${oe}-${te}}`,V,H);let we=!!H&&(!V||!b&&oe<ue||!!b&&b.trackId===I.audio.id),be=we?H:V;if(!be)return this.log(`No media samples found in ${l} ${c.level} ${c.part===-1?"":`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${i}`),k;let ye=A,Te,Oe;if(V&&V.sampleCount>=1&&I.video&&c.iframe){let{trun:Le,start:Je}=V,bt=Le.length===1,ut=!Le.length?[]:bt?Le[0].samples:Le[0].samples.concat(...Le.slice(1).map((Ft)=>Ft.samples));if(ut.length){let Ft=Le[0],nn=Ft;for(let it=Le.length;it--;)if(Le[it].samples.length){nn=Le[it];break}let mn=nn.lastSampleDurationOffset,{defaultSampleDurationOffset:Vt}=Ft,Fn=Math.abs(c.duration-(ae-ue))>0.05,ns=ut.length<V.sampleCount;if(!(Fn||ns||this.videoOnlyRemux||!bt))he=ae-ue;else{let it=ns?nn.sampleOffset+nn.samples.reduce((is,xs)=>is+xs.size,0):void 0,sn=Fn?c.duration:ae-ue,Lt=QC(ut,sn*I.video.timescale,mn,Vt),Ln=HT(A,I.video.id,ut.length,it,Lt);if(Ln)ye=Ln,Oe=YC(Je,ut);else this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`);he=Ln&&Lt?sn:ae-ue}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${Le.length})`),he=ae-ue}else he=we?te-oe:ae-ue;if(this.videoOnlyRemux&&ye===A)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),k;let st=be.timescale,We=be.start-i*st,wt=we?I.audio.id:I.video.id;if(me=be.start/st,(r||!b)&&(JC(b,me,i,he)||st!==b.timescale)){let Le=!1,Je=we?"audio":"video";if(b){let bt=i!==0?me/i:1+me/1;Le=me>=0&&Math.abs(1-bt)<0.001,this.log(`${Je} timestamps in track ${wt} at playlist time: ${r?"":"~"}${i} maps to ${me} with initPTS: ${b.baseTime/b.timescale} (${We/st-b.baseTime/b.timescale}s diff) (${ce}) drift estimate: ${bt} ${Le?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}if(!Le)this.log(`Found initPTS in ${Je} track ${wt} at playlist time: ${i} offset: ${me-i} (${We}/${st})`),b=null,E.initPTS=We,E.timescale=st,E.trackId=wt}if(!b){if(!E.timescale||E.trackId===void 0||E.initPTS===void 0)this.warn("Could not set initPTS"),E.initPTS=me,E.timescale=1,E.trackId=-1;this.initPTS=b={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId}}else E.initPTS=b.baseTime,E.timescale=b.timescale,E.trackId=b.trackId;let xt=me-b.baseTime/b.timescale,ft=xt+he,It=W&&(be==null?void 0:be.ptsMin)!==void 0?be.ptsMin/be.timescale-b.baseTime/b.timescale:xt,Wt=Oe!==void 0&&V?Oe/V.timescale-b.baseTime/b.timescale:W&&be!=null&&be.ptsMax?be.ptsMax/be.timescale-b.baseTime/b.timescale:ft;if(he>0)this.lastEndTime=ft;else this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp();let hn=(I.audio?I.audio.encrypted:!1)||(I.video?I.video.encrypted:!1),zt={data1:ye,data2:Te,startPTS:It,startDTS:xt,endPTS:Wt,endDTS:ft,type:ce,hasAudio:U,hasVideo:W,nb:1,dropped:0,encrypted:hn};k.audio=U&&!W?zt:void 0,k.video=W?zt:void 0;let tn=this.isVideoContiguous,Kn=V==null?void 0:V.sampleCount;if(Kn){let Le=V.keyFrameIndex,Je=Le!==-1;if(zt.nb=Kn,zt.dropped=Le===0||tn?0:Je?Le:Kn,zt.independent=Je,zt.firstKeyFrame=Le,Je&&V.keyFrameStart)zt.firstKeyFramePTS=(V.keyFrameStart-b.baseTime)/b.timescale;if(!tn)k.independent=Je;if(this.isVideoContiguous||(this.isVideoContiguous=Je),zt.dropped)this.warn(`fmp4 does not start with IDR: firstIDR ${Le}/${Kn} dropped: ${zt.dropped} start: ${zt.firstKeyFramePTS||"NA"}`)}if(k.initSegment=E,k.id3=x6(n,i,b,b),s.samples.length)k.text=A6(s,i,b);return k}}function Td(e,t,n=!1){return(e==null?void 0:e.start)!==void 0?(e.start+(n?e.duration:0))/e.timescale:t}function YC(e,t){let n=e,s=e;for(let i=0;i<t.length;i++){let{cts:r,duration:o}=t[i];s=Math.max(s,n+(r||0)+o),n+=o}return s}function QC(e,t,n,s){if(n!==void 0){let r=e[e.length-1],o=t;for(let l=0;l<e.length-1;l++)o-=e[l].duration;if(o<=0)o=r.duration;return r.duration=o,{durationOffset:n,value:o}}if(s===void 0)return;let i=Math.round(t/e.length);for(let r=0;r<e.length;r++)e[r].duration=i;return{durationOffset:s,value:i}}function JC(e,t,n,s){if(e===null)return!0;let i=Math.max(s,1),r=t-e.baseTime/e.timescale;return Math.abs(r-n)>=i}function v3(e,t,n){let s=e.codec;if(s&&s.length>4)return s;if(t===Zn.AUDIO){if(s==="ec-3"||s==="ac-3"||s==="alac")return s;if(s==="fLaC"||s==="Opus")return Wd(s,!1);return n.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}else if(s==="mjpg")return s;return n.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}var Yo;try{Yo=self.performance.now.bind(self.performance)}catch(e){Yo=Date.now}var Nd=[{demux:b6,remux:T6},{demux:fo,remux:mh},{demux:u6,remux:mh},{demux:g6,remux:mh}];Nd.splice(2,0,{demux:m6,remux:mh});class c1{constructor(e,t,n,s,i,r){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.id=i,this.logger=r}configure(e){if(this.transmuxConfig=e,this.decrypter)this.decrypter.reset()}push(e,t,n,s){if(!this.observer)return Ed(n);let i=n.transmuxing;i.executeStart=Yo();let r=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;if(s)this.currentTransmuxState=s;let{contiguous:c,discontinuity:h,trackSwitch:d,accurateTimeOffset:m,timeOffset:p,initSegmentChange:b}=s||o,{audioCodec:v,videoCodec:k,defaultInitPts:A,duration:T,initSegmentData:E}=l,I=ZC(r,t);if(I&&$c(I.method)){let N=this.getDecrypter(),H=F1(I.method);return this.asyncResult=!0,this.decryptionPromise=N.decrypt(r,I.key.buffer,I.iv.buffer,H,n.decryptRange).then((V)=>{let U=this.push(V,null,n);return this.decryptionPromise=null,U}),this.decryptionPromise}let _=this.needsProbing(h,d);if(_){let N=n.iframe&&E&&fo.probe(E,this.logger)?E:r,H=this.configureTransmuxer(N);if(H)return this.logger.warn(`[transmuxer] ${H.message}`),this.observer.emit(O.ERROR,O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,fatal:!1,error:H,reason:H.message}),i.executeEnd=Yo(),Ed(n)}if(h||d||b||_)this.resetInitSegment(E,v,k,T,t,n);if(h||b||_)this.resetInitialTimestamp(A);if(!c)this.resetContiguity();let q=this.transmux(r,I,p,m,n);this.asyncResult=Th(q);let P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,i.executeEnd=Yo(),q}flush(e){let t=e.transmuxing;t.executeStart=Yo();let{decrypter:n,currentTransmuxState:s,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let r=[],{timeOffset:o}=s;if(n){let d=n.flush();if(d)r.push(this.push(d.buffer,null,e))}let{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=Yo();let d=[Ed(e)];if(this.asyncResult)return Promise.resolve(d);return d}let h=l.flush(o,e);if(Th(h))return this.asyncResult=!0,h.then((d)=>(this.flushRemux(r,d,e),r));if(this.flushRemux(r,h,e),this.asyncResult)return Promise.resolve(r);return r}flushRemux(e,t,n){if(!this.remuxer)return;let{audioTrack:s,videoTrack:i,id3Track:r,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id} playlist ${n.level}`);let h=this.remuxer.remux(s,i,r,o,c,l,!0,this.id,n,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:n}),n.transmuxing.executeEnd=Yo()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;if(!t||!n)return;t.resetTimeStamp(e),n.resetTimeStamp(e)}resetContiguity(){let{demuxer:e,remuxer:t}=this;if(!e||!t)return;e.resetContiguity(),t.resetNextTimestamp()}resetInitSegment(e,t,n,s,i,r){let{demuxer:o,remuxer:l}=this;if(!o||!l)return;o.resetInitSegment(e,t,n,s,i,r),l.resetInitSegment(e,t,n,i)}destroy(){if(this.demuxer)this.demuxer.destroy(),this.demuxer=void 0;if(this.remuxer)this.remuxer.destroy(),this.remuxer=void 0;if(this.observer)this.observer.removeAllListeners();this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,n,s,i){let r;if((t==null?void 0:t.method)==="SAMPLE-AES")r=this.transmuxSampleAes(e,t,n,s,i);else r=this.transmuxUnencrypted(e,n,s,i);return r}transmuxUnencrypted(e,t,n,s){let{demuxer:i,remuxer:r}=this;if(!i||!r)return Ed(s);let o=i.demux(e,t,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:c,id3Track:h,textTrack:d}=o;return{remuxResult:r.remux(l,c,h,d,t,n,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(e,t,n,s,i){if(!this.demuxer)return Promise.reject(Error("no demuxer"));return this.demuxer.demuxSampleAes(e,t,n,i).then((r)=>({remuxResult:this.remuxer.remux(r.audioTrack,r.videoTrack,r.id3Track,r.textTrack,n,s,!1,this.id,i,r.initData,r.sampleData),chunkMeta:i}))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:s}=this;if(!n)return;let i;try{for(let d=0,m=Nd.length;d<m;d++){var r;if((r=Nd[d].demux)!=null&&r.probe(e,this.logger)){i=Nd[d];break}}}catch(d){return d}if(!i)return Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,c=i.demux,h=i.remux;if(!o||!(o instanceof c))this.logger.log(`Using ${c.name}`),this.demuxer=new c(n,t,s,this.logger),this.probe=c.probe;if(!l||!(l instanceof h))this.logger.log(`Using ${h.name}`),this.remuxer=new h(n,t,s,this.logger)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;if(!e)e=this.decrypter=new d0(this.config);return e}}function ZC(e,t){let n=null;if(e.byteLength>0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null)n=t;return n}var Ed=(e)=>({remuxResult:{},chunkMeta:e});function Th(e){return"then"in e&&e.then instanceof Function}class E6{constructor(e,t,n,s,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=s,this.defaultInitPts=i||null}}class C6{constructor(e,t,n,s,i,r){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=s,this.timeOffset=i,this.initSegmentChange=r}}var S3=0;class G1{constructor(e,t,n,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=S3++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=(l)=>{let c=l.data,h=this.hls;if(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo)return;switch(c.event){case"init":{var d;let m=(d=this.workerContext)==null?void 0:d.objectURL;if(m)self.URL.revokeObjectURL(m);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{if(h.logger[c.data.logType])h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=(l)=>{if(!this.hls)return;let c=Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=s;let r=(l,c)=>{if(c=c||{},c.frag=this.frag||void 0,l===O.ERROR)c=c,c.parent=this.id,c.part=this.part,this.error=c.error;this.hls.trigger(l,c)};this.observer=new P1,this.observer.on(O.FRAG_DECRYPTED,r),this.observer.on(O.ERROR,r);let o=N5(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(i.workerPath||pC()){try{if(i.workerPath)l.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=yC(i.workerPath);else l.log(`injecting Web Worker for "${t}"`),this.workerContext=gC();let{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ls(i)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new c1(this.observer,o,i,"",t,e.logger)}return}}this.transmuxer=new c1(this.observer,o,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=S3++;let t=this.hls.config,n=N5(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:ls(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),vC(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;if(t)t.destroy(),this.transmuxer=null}let e=this.observer;if(e)e.removeAllListeners();this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,s,i,r,o,l,c,h){var d,m;c.transmuxing.start=self.performance.now();let{instanceNo:p,transmuxer:b}=this,v=r?r.start:i.start,k=i.decryptdata,A=this.frag,T=A?i.cc!==A.cc:!0,E=A?c.level!==A.level:!0,I=A?c.sn-A.sn:-1,_=this.part?c.part-this.part.index:-1,q=I===0&&c.id>1&&c.id===(A==null?void 0:A.stats.chunkCount),P=!E&&(I===1||I===0&&(_===1||q&&_<=0)),N=self.performance.now();if(E||I||i.stats.parsing.start===0)i.stats.parsing.start=N;if(r&&(_||!P))r.stats.parsing.start=N;let H=!(A&&((d=i.initSegment)==null?void 0:d.url)===((m=A.initSegment)==null?void 0:m.url)),V=new C6(T,P,l,E,v,H);if(!P||T||H){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id} playlist: ${c.level} id: ${c.id}
28
- discontinuity: ${T}
29
- trackSwitch: ${E}
30
- contiguous: ${P}
31
- accurateTimeOffset: ${l}
32
- timeOffset: ${v}
33
- initSegmentChange: ${H}`);let U=new E6(n,s,t,o,h);this.configureTransmuxer(U)}if(this.frag=i,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:e,decryptdata:k,chunkMeta:c,state:V},e instanceof ArrayBuffer?[e]:[]);else if(b){let U=b.push(e,k,c,V);if(Th(U))U.then((W)=>{this.handleTransmuxComplete(W)}).catch((W)=>{this.transmuxerError(W,c,"transmuxer-interface push error")});else this.handleTransmuxComplete(U)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(n){let s=n.flush(e);if(Th(s))s.then((i)=>{this.handleFlushResult(i,e)}).catch((i)=>{this.transmuxerError(i,e,"transmuxer-interface flush error")});else this.handleFlushResult(s,e)}}transmuxerError(e,t,n){if(!this.hls)return;this.error=e,this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n})}handleFlushResult(e,t){e.forEach((n)=>{this.handleTransmuxComplete(n)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e});else if(n)n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}var k3=100;class j6 extends g0{constructor(e,t,n){super(e,t,n,"audio-stream-controller",kt.AUDIO);this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(O.LEVEL_LOADED,this.onLevelLoaded,this),e.on(O.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(O.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(O.BUFFER_RESET,this.onBufferReset,this),e.on(O.BUFFER_CREATED,this.onBufferCreated,this),e.on(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(O.FRAG_LOADING,this.onFragLoading,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;if(!e)return;super.unregisterListeners(),e.off(O.LEVEL_LOADED,this.onLevelLoaded,this),e.off(O.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(O.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(O.BUFFER_RESET,this.onBufferReset,this),e.off(O.BUFFER_CREATED,this.onBufferCreated,this),e.off(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(O.FRAG_LOADING,this.onFragLoading,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,t){let{frag:n,id:s,initPTS:i,timescale:r,trackId:o,timestampOffsets:l}=t;if(s===kt.MAIN){let c=n.cc,h=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${c} found from main: ${i/r} (${i}/${r}) trackId: ${o}`),this.mainAnchor=n,this.state===Me.WAITING_INIT_PTS){let d=this.waitingData;if(!d&&!this.loadingParts||d&&d.frag.cc!==c)this.syncWithAnchor(n,d==null?void 0:d.frag)}else if(!this.hls.hasEnoughToStart&&h&&h.cc!==c)h.abortRequests(),this.syncWithAnchor(n,h);else if(this.state===Me.IDLE)this.tick()}}getLoadPosition(){var e;if(!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1)return this.nextLoadPosition;return super.getLoadPosition()}syncWithAnchor(e,t){var n;let s=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(t){if((s==null?void 0:s.cc)===t.cc)return}let i=(s||e).cc,r=this.getLevelDetails(),o=this.getLoadPosition(),l=M9(r,i,o);if(l){if(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===Me.IDLE)this.doTickIdle()}}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Me.STOPPED;return}let n=this.lastCurrentTime;if(this.stopLoad(),this.setInterval(k3),n>0&&e===-1&&!t&&this.initPTS.length)this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n;if(this.state=Me.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType))this.startFragRequested=!1;this.tick()}doTick(){switch(this.state){case Me.IDLE:this.doTickIdle();break;case Me.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e==null?void 0:e[t],s=n==null?void 0:n.details;if(s&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(s))break;this.state=Me.WAITING_INIT_PTS}break}case Me.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Me.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:s,complete:i}=e,r=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Me.FRAG_LOADING;let o=s.flush().buffer,l={frag:t,part:n,payload:o,networkDetails:null};if(this._handleFragmentLoadProgress(l),i)super._handleFragmentLoadComplete(l)}else if(r&&r.cc!==e.frag.cc)this.syncWithAnchor(r,e.frag)}else this.state=Me.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;if(e)this.fragmentTracker.removeFragment(e.frag),this.waitingData=null;super.resetLoadingState()}onTickEnd(){let{media:e}=this;if(!(e!=null&&e.readyState))return;this.lastCurrentTime=e.currentTime,this.checkFragmentChanged()}doTickIdle(){var e;let{hls:t,levels:n,media:s,trackId:i}=this,r=t.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||!(n!=null&&n[i]))return;let o=n[i],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=Me.WAITING_TRACK,this.startFragRequested=!1;return}let c=this.getBufferOutput();if(this.bufferFlushed&&c)this.bufferFlushed=!1,this.afterBufferFlushed(c,Zn.AUDIO);let h=this.getFwdBufferInfo();if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(O.BUFFER_EOS,{type:"audio"}),this.state=Me.ENDED;return}let d=h.len,m=t.maxBufferLength,p=l.fragments,b=p[0].start,v=this.getLoadPosition(),k=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:h.end;if(this.switchingTrack&&s){let E=v;if(l.PTSKnown&&E<b&&E>=this.timelineOffset){if(h.end>b||h.nextStart)this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${E} -> ${b} + 0.05`),s.currentTime=b+0.05}}if(d>=m&&!this.switchingTrack&&k<p[p.length-1].start)return;let A=this.getNextFragment(k,l);if(A&&this.isLoopLoading(A,k))A=this.getNextFragmentLoopLoading(A,l,h,kt.MAIN,m);if(!A){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,m,A))return;let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&js(A)&&!A.endList&&(!l.live||!this.loadingParts&&k<this.hls.liveSyncPosition)){if(this.fragmentTracker.getState(T)===Ss.OK)this.mainFragLoading=T=null;if(T&&js(T)){if(A.start>T.end){let I=this.fragmentTracker.getFragAtPos(k,kt.MAIN);if(I&&I.end>T.end)T=I,this.mainFragLoading={frag:I,targetBufferTime:null}}if(A.start>T.end)return}}this.loadFragment(A,o,k)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((n)=>new Yc(n))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:s}=this;if(s)s.abortRequests(),this.removeUnbufferedFrags(s.start);if(this.resetLoadingState(),n){if(this.switchingTrack=t,!t.flushImmediate)this.nextTrackId=t.id,this.nextLevelSwitch();if(this.flushAudioIfNeeded(t),this.state!==Me.STOPPED)this.setInterval(k3),this.state=Me.IDLE,this.tick()}else this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval()}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let n=this.cachedTrackLoadedData;if(n)this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(O.AUDIO_TRACK_LOADED,n)}onAudioTrackLoaded(e,t){var n;let{levels:s}=this,{details:i,id:r,groupId:o,track:l}=t;if(!s){this.warn(`Audio tracks reset while loading track ${r} "${l.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){if(this.cachedTrackLoadedData=t,this.state!==Me.STOPPED)this.state=Me.WAITING_TRACK;return}this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${l.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);let h=s[r],d=0;if(i.live||(n=h.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(h.details){var m;d=this.alignPlaylists(i,h.details,(m=this.levelLastLoaded)==null?void 0:m.details)}if(!i.alignedSliding)n0(c,i,this),d=i.fragmentStart}if(h.details=i,this.levelLastLoaded=h,!this.startFragRequested)this.setStartPosition(c,d);if(this.hls.trigger(O.AUDIO_TRACK_UPDATED,{details:i,id:r,groupId:t.groupId}),this.state===Me.WAITING_TRACK&&!this.waitForCdnTuneIn(i))this.state=Me.IDLE;this.tick()}_handleFragmentLoadProgress(e){var t;let n=e.frag,{part:s,payload:i}=e,{config:r,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}let c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}let h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}let d=r.defaultAudioCodec||c.audioCodec||"mp4a.40.2",m=this.transmuxer;if(!m)m=this.transmuxer=new G1(this.hls,kt.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let p=this.initPTS[n.cc],b=(t=n.initSegment)==null?void 0:t.data;if(p!==void 0){let k=s?s.index:-1,A=k!==-1,T=new m0(n.level,n.sn,n.stats.chunkCount,i.byteLength,k,A,n.duration);m.push(i,b,d,"",n,s,h.totalduration,!1,T,p)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);let{cache:v}=this.waitingData=this.waitingData||{frag:n,part:s,cache:new O1,complete:!1};if(v.push(new Uint8Array(i)),this.state!==Me.STOPPED)this.state=Me.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let n=t.tracks.audio;if(n)this.mediaBuffer=n.buffer||null}onFragLoading(e,t){if(!this.audioOnly&&t.frag.type===kt.MAIN&&js(t.frag)){if(this.mainFragLoading=t,this.state===Me.IDLE)this.tick()}}onFragBuffered(e,t){let{frag:n,part:s}=t;if(n.type!==kt.AUDIO){if(!this.audioOnly&&n.type===kt.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo)this.audioOnly=!0,this.mainFragLoading=null;return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${s?" p: "+s.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(js(n)){let i=this.switchingTrack;if(i)this.bufferedTrack=i}if(this.fragBufferedComplete(n,s),this.media)this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,kt.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let n=this.fragPlaying,s=e==null?void 0:e.level;if(!n||n.level!==s){if(e)this.cleanupBackBuffer();if(this.switchingTrack)this.completeAudioSwitch(this.switchingTrack)}return!0}onError(e,t){var n;if(t.fatal){this.state=Me.ERROR;return}switch(t.details){case ve.FRAG_GAP:case ve.FRAG_PARSING_ERROR:case ve.FRAG_DECRYPT_ERROR:case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(kt.AUDIO,t);break;case ve.AUDIO_TRACK_LOAD_ERROR:case ve.AUDIO_TRACK_LOAD_TIMEOUT:case ve.LEVEL_PARSING_ERROR:if(!t.levelRetry&&this.state===Me.WAITING_TRACK&&((n=t.context)==null?void 0:n.type)===fn.AUDIO_TRACK)this.state=Me.IDLE;break;case ve.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;if(t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry)this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag);break;case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;if(!this.reduceLengthAndFlushBuffer(t))this.resetLoadingState();break;case ve.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;if(this.reduceLengthAndFlushBuffer(t))this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio");break;case ve.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){if(t!==Zn.VIDEO)this.flushing=!0}onBufferFlushed(e,{type:t}){if(t!==Zn.VIDEO){if(this.flushing=!1,this.bufferFlushed=!0,this.state===Me.ENDED)this.state=Me.IDLE;let n=this.getBufferOutput();if(n)this.afterBufferFlushed(n,t),this.tick()}}_handleTransmuxComplete(e){var t;let n="audio",{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,o=this.getCurrentContext(r);if(!o){this.resetWhenMissingContext(r);return}let{frag:l,part:c,level:h}=o,{details:d}=h,{audio:m,text:p,id3:b,initSegment:v}=i;if(this.fragContextChanged(l)||!d){if(this.fragmentTracker.removeFragment(l),v!=null&&v.tracks)this.resetTransmuxer();return}if(this.state=Me.PARSING,m&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:k}=this,A=k.nextAudioTrackBufferFlushForwardOffset,T=Math.max(this.getLoadPosition()+A,l.start);super.flushMainBuffer(T,Number.POSITIVE_INFINITY,kt.AUDIO)}if(v!=null&&v.tracks){let k=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(h,v.tracks,k,r),s.trigger(O.FRAG_PARSING_INIT_SEGMENT,{frag:k,id:"audio",tracks:v.tracks})}if(m){let{startPTS:k,endPTS:A,startDTS:T,endDTS:E}=m;if(c)c.elementaryStreams[Zn.AUDIO]={startPTS:k,endPTS:A,startDTS:T,endDTS:E};l.setElementaryStreamInfo(Zn.AUDIO,k,A,T,E),this.bufferFragmentData(m,l,c,r)}if(b!=null&&(t=b.samples)!=null&&t.length){let k=Gn({id:"audio",frag:l,details:d},b);s.trigger(O.FRAG_PARSING_METADATA,k)}if(p){let k=Gn({id:"audio",frag:l,details:d},p);s.trigger(O.FRAG_PARSING_USERDATA,k)}}_bufferInitSegment(e,t,n,s){if(this.state!==Me.PARSING)return;if(t.video)delete t.video;if(t.audiovideo)delete t.audiovideo;if(!t.audio)return;let i=t.audio;i.id=kt.AUDIO;let r=e.audioCodec;if(this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${r}/${i.codec}]`),(r==null?void 0:r.split(",").length)===1)i.levelCodec=r;this.hls.trigger(O.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:n,part:null,chunkMeta:s,parent:n.type,data:o};this.hls.trigger(O.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,n){let s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===Ss.NOT_LOADED||s===Ss.PARTIAL){var i;if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Me.WAITING_INIT_PTS;let r=this.mainDetails;if(r&&r.fragmentStart!==t.details.fragmentStart)n0(r,t.details,this)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:n,assocLang:s,characteristics:i,audioCodec:r,channels:o}=this.bufferedTrack;if(!Nl({name:t,lang:n,assocLang:s,characteristics:i,audioCodec:r,channels:o},e,Pl))if(Jd(e.url,this.hls))this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null;else this.bufferedTrack=e}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(O.AUDIO_TRACK_SWITCHED,Ct({},e))}get nextAudioTrack(){return this.nextTrackId}}class w0 extends Ji{constructor(e,t){super(t,e.logger);this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){if(this.timer!==-1)self.clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,n){let s=t==null?void 0:t.renditionReports;if(s){let i=-1;for(let r=0;r<s.length;r++){let o=s[r],l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){i=r;break}else if(l===e.substring(0,l.length))i=r}if(i!==-1){let r=s[i],o=parseInt(r["LAST-MSN"])||t.lastPartSn,l=parseInt(r["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let h=Math.min(t.age-t.partTarget,t.targetduration);if(l>=0&&h>t.partTarget)l+=1}let c=n&&B5(n);return new n1(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return e}playlistLoaded(e,t,n){let{details:s,stats:i}=t,r=s.fragments,o=self.performance.now(),l=i.loading.first?Math.max(0,Math.floor(o-i.loading.first)):0;s.advancedDateTime=Date.now()-l;let c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){let d=Math.max(c||0,0);s.appliedTimelineOffset=d,r.forEach((m)=>{m==null||m.setStart(m.playlistOffset+d)})}if(s.live||n!=null&&n.live){var h;let d="levelInfo"in t?t.levelInfo:t.track;s.reloaded(n);let m=(h=r[r.length-1])==null?void 0:h.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let _=Error(`${m} playlist ${d.id} hit max allowed unchanged reloads.`);this.warn(_);let{networkDetails:q,context:P}=t;this.hls.trigger(O.ERROR,{type:Et.NETWORK_ERROR,details:ve.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:_,reason:_.message,level:t.level,parent:m,context:P,networkDetails:q,stats:i});return}if(n){sC(n,s,this);let _=s.playlistParsingError;if(_){this.warn(_);let q=this.hls;if(!q.config.ignorePlaylistParsingErrors){let{networkDetails:P}=t;q.trigger(O.ERROR,{type:Et.NETWORK_ERROR,details:ve.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:_,reason:_.message,level:t.level,parent:m,networkDetails:P,stats:i});return}s.playlistParsingError=null}}if(s.requestScheduled===-1)s.requestScheduled=i.loading.start;let p=this.hls.mainForwardBufferInfo,b=p?p.end-p.len:0,v=(s.edge-b)*1000,k=Q9(s,v);if(s.requestScheduled+k<o)s.requestScheduled=o;else if(s.requestScheduled<=o)s.requestScheduled+=k;let A=t.deliveryDirectives;if(this.log(`live playlist ${e} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${A?` | requested ${A.msn} - ${A.part}`:""})`}`),!this.canLoad||!s.live)return;let T,E=void 0,I=void 0;if(s.canBlockReload&&s.advanced){let _=this.hls.config.lowLatencyMode,{lastPartSn:q,endSN:P,lastPartIndex:N}=s,H=N!==-1,V=q===P;if(H)if(V)E=P+1,I=_?0:N;else E=q,I=_?N+1:s.maxPartIndex;else E=P+1;let U=s.age,W=U+s.ageHeader,ce=Math.min(W-s.partTarget,s.targetduration*1.5);if(ce>0){if(W>s.targetduration*3)this.log(`Playlist last advanced ${U.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,I=void 0;else if(n!=null&&n.tuneInGoal&&W-s.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${ce} with playlist age: ${s.age}`),ce=0;else{let ue=Math.floor(ce/s.targetduration);if(E+=ue,I!==void 0){let oe=Math.round(ce%s.targetduration/s.partTarget);I+=oe}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${U.toFixed(2)}s goal: ${ce} skip sn ${ue} to part ${I}`)}s.tuneInGoal=ce}if(T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,I),_||!V){s.requestScheduled=o,this.loadingPlaylist(d,T);return}}else if(s.canBlockReload||s.canSkipUntil)T=this.getDeliveryDirectives(s,t.deliveryDirectives,E,I);if(T&&E!==void 0&&s.canBlockReload)s.requestScheduled=i.loading.first+Math.max(k-l*2,k/2);this.scheduleLoading(d,T,s)}else this.clearTimer()}scheduleLoading(e,t,n){let s=n||e.details;if(!s){this.loadingPlaylist(e,t);return}let i=self.performance.now(),r=s.requestScheduled;if(i>=r&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}let o=Math.max(r-i,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,n,s){let i=B5(e);if(t!=null&&t.skip&&e.deltaUpdateFailed)n=t.msn,s=t.part,i=Ld.No;return new n1(n,s,i)}checkRetry(e){let t=e.details,n=Gd(e),s=e.errorAction,{action:i,retryCount:r=0,retryConfig:o}=s||{},l=!!s&&!!o&&(i===gi.RetryRequest||!s.resolved&&i===gi.SendAlternateToPenaltyBox);if(l){var c;if(r>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;let d=bh((h=e.response)==null?void 0:h.code);if(this.clearTimer(),d)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else{let m=E1(o,r);this.warn(`Retrying playlist loading ${r+1}/${o.maxNumRetry} after "${t}" in ${m}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),m)}}e.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){if(this.clearTimer(),bh(0))this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else this.log("Connection restored (online)"),this.loadPlaylist()}}function _6(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Eh(e[n].attrs,t[n].attrs))return!1;return!0}function Eh(e,t,n){let s=e["STABLE-RENDITION-ID"];if(s&&!n)return s===t["STABLE-RENDITION-ID"];return!(n||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i)=>e[i]!==t[i])}class I6 extends w0{constructor(e){super(e,"audio-track-controller");this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.LEVEL_LOADING,this.onLevelLoading,this),e.on(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(O.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.LEVEL_LOADING,this.onLevelLoading,this),e.off(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(O.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(O.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:n,groupId:s,details:i}=t,r=this.tracksInGroup[n];if(!r||r.groupId!==s){this.warn(`Audio track with id:${n} and group:${s} not found in active group ${r==null?void 0:r.groupId}`);return}let o=r.details;if(r.details=t.details,this.log(`Audio track ${n} "${r.name}" lang:${r.lang} group:${s} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId)this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.audioGroups||null,s=this.groupIds,i=this.currentTrack;if(!n||(s==null?void 0:s.length)!==(n==null?void 0:n.length)||n!=null&&n.some((o)=>(s==null?void 0:s.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter((m)=>kh(m.groupId,n));if(o.length){if(this.selectDefaultTrack&&!o.some((m)=>m.default))this.selectDefaultTrack=!1;o.forEach((m,p)=>{m.id=p})}else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!i&&l){let m=ja(l,o,Pl);if(m>-1)i=o[m];else{let p=ja(l,this.tracks);i=this.tracks[p]}}let c=this.findTrackId(i);if(c===-1&&i)c=this.findTrackId(null);let h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(O.AUDIO_TRACKS_UPDATED,h);let d=this.trackId;if(c!==-1&&d===-1)this.setAudioTrack(c);else if(o.length&&d===-1){var r;let m=Error(`No audio track selected for current audio group-ID(s): ${(r=this.groupIds)==null?void 0:r.join(",")} track count: ${o.length}`);this.warn(m.message),this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(e,t){if(t.fatal||!t.context)return;if(t.context.type===fn.AUDIO_TRACK&&t.context.id===this.trackId&&kh(t.context.groupId,this.groupIds))this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let s=this.currentTrack;if(s&&Nl(e,s,Pl))return s;let i=ja(e,this.tracksInGroup,Pl);if(i>-1){let r=this.tracksInGroup[i];return this.setAudioTrack(i,"flushImmediate"in e&&e.flushImmediate),r}else if(s){let r=t.loadLevel;if(r===-1)r=t.firstAutoLevel;let o=RE(e,t.levels,n,r,Pl);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let r=ja(e,n);if(r>-1)return n[r]}}}return null}setAudioTrack(e,t=!0){let n=this.tracksInGroup;if(e<0||e>=n.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,i=n[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(O.AUDIO_TRACK_SWITCHING,Ct(Ct({},i),{},{flushImmediate:t})),r)return;let o=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let s=t[n];if(this.selectDefaultTrack&&!s.default)continue;if(!e||Nl(e,s,Pl))return n}if(e){let{name:n,lang:s,assocLang:i,characteristics:r,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){let h=t[c];if(Nl({name:n,lang:s,assocLang:i,characteristics:r,audioCodec:o,channels:l},h,Pl))return c}for(let c=0;c<t.length;c++){let h=t[c];if(Eh(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){let h=t[c];if(Eh(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;if(!this.shouldLoadPlaylist(t))return;if(Jd(t.url,this.hls))this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let{id:n,groupId:s}=e,i=this.getUrlWithDirectives(e.url,t),r=e.details,o=r==null?void 0:r.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||"":""):""} ${i}`),this.hls.trigger(O.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:s,deliveryDirectives:t||null,track:e})}}class R6{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,n){if(this.queues===null||this.tracks===null)return;let s=this.queues[t];if(s.push(e),s.length===1&&!n)this.executeNext(t)}appendBlocker(e){return new Promise((t)=>{let n={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise((t)=>{if(this.queues){let n={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){if(this.queues===null)return;[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e)=>{var t;let n=(t=e[0])==null?void 0:t.label;if(n==="async-blocker"||n==="async-blocker-prepend")e[0].execute(),e.splice(0,1);else if(n==="block-audio")e.splice(0,1)})}insertNext(e,t){if(this.queues===null)return;this.queues[t].splice(1,0,...e)}unblockAudio(){var e;if(this.queues===null)return;if(((e=this.current("audio"))==null?void 0:e.label)==="block-audio")this.shiftAndExecuteNext("audio")}audioBlocking(){if(this.queues===null)return!1;return this.queues.audio.some((e)=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let s=t[0];try{s.execute()}catch(i){var n;if(s.onError(i),this.queues===null||this.tracks===null)return;let r=(n=this.tracks[e])==null?void 0:n.buffer;if(!(r!=null&&r.updating))this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){if(this.queues===null)return;this.queues[e].shift(),this.executeNext(e)}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;if(e===null||t===null)return"<destroyed>";return`
34
- ${this.list("video")}
35
- ${this.list("audio")}
36
- ${this.list("audiovideo")}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let n=(t=this.tracks)==null?void 0:t[e],s=n==null?void 0:n.buffer;if(!s)return"none";return`SourceBuffer${s.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map((n)=>n.label).join(", "))||""}}var x3=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,D6="HlsJsTrackRemovedError",ej=0.25,tj=0.001;class q6 extends Error{constructor(e){super(e);this.name=D6}}class M6 extends Ji{constructor(e,t){super("buffer-controller",e.logger);this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=(n)=>{var s;if(!this.hls)return;if(((s=this.mediaSource)==null?void 0:s.readyState)!=="open")return;if(!this.media||this.media.seeking)return;this.hls.pauseBuffering()},this._onStartStreaming=(n)=>{if(!this.hls)return;this.hls.resumeBuffering()},this._onMediaSourceOpen=(n)=>{let{media:s,mediaSource:i}=this;if(n)this.log("Media source opened");if(!s||!i)return;if(Bn(i,"sourceopen",this._onMediaSourceOpen),Bn(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(O.MEDIA_ATTACHED,{media:s,mediaSource:i}),this.mediaSource!==null)this.checkPendingTracks()},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let n=this.media.error,{appendError:s,appendErrors:i}=this,r=!1;if(!s&&n)r=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry;let o=Error(`MediaSource closed while media attached${T3(r,n)}`);this.warn(o),this.hls.trigger(O.ERROR,Gn({fatal:r},s,{type:Et.MEDIA_ERROR,details:ve.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:n,_objectUrl:s}=this;if(n!==s)this.error(`Media element src was set while attaching MediaSource (${s} > ${n})`)},this._onMediaError=()=>{let{media:n}=this;if(n){var s,i;this.log(`Media error (code: ${(s=n.error)==null?void 0:s.code}): ${(i=n.error)==null?void 0:i.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=ST(Zo(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){if(this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue)this.operationQueue.destroy(),this.operationQueue=null;this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:e}=this;e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.BUFFER_RESET,this.onBufferReset,this),e.on(O.BUFFER_APPENDING,this.onBufferAppending,this),e.on(O.BUFFER_CODECS,this.onBufferCodecs,this),e.on(O.BUFFER_EOS,this.onBufferEos,this),e.on(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(O.FRAG_PARSED,this.onFragParsed,this),e.on(O.FRAG_CHANGED,this.onFragChanged,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.BUFFER_RESET,this.onBufferReset,this),e.off(O.BUFFER_APPENDING,this.onBufferAppending,this),e.off(O.BUFFER_CODECS,this.onBufferCodecs,this),e.off(O.BUFFER_EOS,this.onBufferEos,this),e.off(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(O.FRAG_PARSED,this.onFragParsed,this),e.off(O.FRAG_CHANGED,this.onFragChanged,this),e.off(O.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let n={};if(this.operationQueue){let i=this.isUpdating();if(!i)this.operationQueue.removeBlockers();let r=this.isQueued();if(i||r)this.warn(`Transfering MediaSource with${r?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`);this.operationQueue.destroy()}let s=this.transferData;if(s&&!this.sourceBufferCount&&s.mediaSource===t)Gn(n,s.tracks);else this.sourceBuffers.forEach((i)=>{let[r]=i;if(r)n[r]=Gn({},this.tracks[r]),this.removeBuffer(r);i[0]=i[1]=null});return{media:e,mediaSource:t,tracks:n}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var n;let s=2;if(t.audio&&!t.video||!t.altAudio)s=1;if(this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&s)this.bufferCreated()}onMediaAttaching(e,t){let n=this.media=t.media;this.transferData=this.overrides=void 0;let s=Zo(this.appendSource);if(s){let i=!!t.mediaSource;if(i||t.overrides)this.transferData=t,this.overrides=t.overrides;let r=this.mediaSource=t.mediaSource||new s;if(this.assignMediaSource(r),i)this._objectUrl=n.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{n.removeAttribute("src");let l=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||l&&r instanceof l,A3(n),nj(n,o),n.load()}catch(l){n.src=o}else n.src=o}if(Un(n,"emptied",this._onMediaEmptied),Un(n,"error",this._onMediaError),this.appendSource)Un(n,"seeking",this._onStartStreaming)}}assignMediaSource(e){var t,n;if(this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(n=e.constructor)==null?void 0:n.name}`),Un(e,"sourceopen",this._onMediaSourceOpen),Un(e,"sourceended",this._onMediaSourceEnded),Un(e,"sourceclose",this._onMediaSourceClose),this.appendSource)Un(e,"startstreaming",this._onStartStreaming),Un(e,"endstreaming",this._onEndStreaming)}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let n=this.tracks,s=t.tracks,i=s?Object.keys(s):null,r=i?i.length:0,o=()=>{Promise.resolve().then(()=>{if(this.media&&this.mediaSourceOpenOrEnded)this._onMediaSourceOpen()})};if(s&&i&&r){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
37
- required tracks: ${ls(n,(l,c)=>l==="initSegment"?void 0:c)};
38
- transfer tracks: ${ls(s,(l,c)=>l==="initSegment"?void 0:c)}}`),!r9(s,n)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,c=this.details,h=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(n)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(O.MEDIA_DETACHING,{}),this.onMediaAttaching(O.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,i.forEach((l)=>{let c=l,h=s[c];if(h){let d=h.buffer;if(d){let m=this.fragmentTracker,p=h.id;if(m.hasFragments(p)||m.hasParts(p)){let k=qt.getBuffered(d);m.detectEvictedFragments(c,k,p,null,null,!0)}let b=Lg(c),v=[c,d];if(this.sourceBuffers[b]=v,d.updating&&this.operationQueue)this.operationQueue.prependBlocker(c);this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:i,_objectUrl:r}=this;if(i){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([o])=>{if(o)this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=i.readyState==="open";try{let l=i.sourceBuffers;for(let c=l.length;c--;){if(o)l[c].abort();i.removeSourceBuffer(l[c])}if(o)i.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}if(this.sourceBufferCount)this.onBufferReset()}if(Bn(i,"sourceopen",this._onMediaSourceOpen),Bn(i,"sourceended",this._onMediaSourceEnded),Bn(i,"sourceclose",this._onMediaSourceClose),this.appendSource)Bn(i,"startstreaming",this._onStartStreaming),Bn(i,"endstreaming",this._onEndStreaming);this.mediaSource=null,this._objectUrl=null}if(s){if(Bn(s,"emptied",this._onMediaEmptied),Bn(s,"error",this._onMediaError),Bn(s,"seeking",this._onStartStreaming),!n){if(r)self.URL.revokeObjectURL(r);if(this.mediaSrc===r){if(s.removeAttribute("src"),this.appendSource)A3(s);s.load()}else this.warn("media|source.src was changed by a third party - skip cleanup")}this.media=null}}onBufferReset(){this.sourceBuffers.forEach(([e])=>{if(e)this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let n=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),n)try{var s;if((s=this.mediaSource)!=null&&s.sourceBuffers.length)this.mediaSource.removeSourceBuffer(n)}catch(i){this.warn(`onBufferReset ${e}`,i)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Lg(e)]=[null,null];let t=this.tracks[e];if(t)this.clearBufferAppendTimeoutId(t),t.buffer=void 0}resetQueue(){if(this.operationQueue)this.operationQueue.destroy();this.operationQueue=new R6(this.tracks)}onBufferCodecs(e,t){var n;let s=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);let r="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&(("audio"in t)||("video"in t)),o=!r&&this.sourceBufferCount&&this.media&&i.some((l)=>!s[l]);if(r||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`);return}if(i.forEach((l)=>{var c,h;let d=t[l],{id:m,codec:p,levelCodec:b,container:v,metadata:k,supplemental:A}=d,T=s[l],E=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],I=E!=null&&E.buffer?E:T,_=(I==null?void 0:I.pendingCodec)||(I==null?void 0:I.codec),q=I==null?void 0:I.levelCodec;if(!T)T=s[l]={buffer:void 0,listeners:[],codec:p,supplemental:A,container:v,levelCodec:b,metadata:k,id:m};let P=Fd(_,q),N=P==null?void 0:P.replace(x3,"$1"),H=Fd(p,b),V=(h=H)==null?void 0:h.replace(x3,"$1");if(H&&P&&N!==V){if(l.slice(0,5)==="audio")H=Wd(H,this.appendSource);if(this.log(`switching codec ${_} to ${H}`),H!==(T.pendingCodec||T.codec))T.pendingCodec=H;T.container=v,this.appendChangeType(l,v,H)}}),this.tracksReady||this.sourceBufferCount)t.tracks=this.sourceBufferTracks;if(this.sourceBufferCount)return;if(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((n=t.audio)==null?void 0:n.id)==="main")this.log("Main audio-only"),this.bufferCodecEventsTotal=1;if(this.mediaSourceOpenOrEnded)this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let s=`${t};codecs=${n}`,i={label:`change-type=${s}`,execute:()=>{let r=this.tracks[e];if(r){let o=r.buffer;if(o!=null&&o.changeType)this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),r.codec=n,r.container=t}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:(r)=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let n=e.start,s=n+e.duration*0.05;if(((t=this.fragmentTracker.getAppendedFrag(n,kt.MAIN))==null?void 0:t.gap)===!0)return;let r={label:"block-audio",execute:()=>{var o,l;if(this.lastVideoAppendEnd>s||qt.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,kt.MAIN))==null?void 0:l.gap)===!0)this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:(o)=>{this.warn("Error executing block-audio operation",o)}};this.append(r,"audio",!0)}unblockAudio(){if(this.operationQueue)this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:n}=this,{data:s,type:i,parent:r,frag:o,part:l,chunkMeta:c,offset:h}=t,d=c.buffering[i],m=js(o)&&!l&&!o.gap&&!c.partial&&!c.iframe,p=null,b=!1,{sn:v,cc:k}=o,A=self.performance.now();d.start=A;let T=o.stats.buffering,E=l?l.stats.buffering:null;if(T.start===0)T.start=A;if((E==null?void 0:E.start)===0)E.start=A;let I=n.audio,_=!1;if(i==="audio"&&(I==null?void 0:I.container)==="audio/mpeg")_=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c;let q=n.video,P=q==null?void 0:q.buffer;if(P&&v!=="initSegment"&&h!==void 0){let V=I==null?void 0:I.buffer,U=l||o;if(i==="audio"&&r!=="main"&&!(q.ending||q.ended)&&V&&qt.getBuffered(V).length){let ce=U.start+U.duration*0.05,ue=qt.getBuffered(P),oe=this.currentOp("video");if(!ue.length&&!oe)this.blockAudio(U);else if(!qt.isBuffered(P,ce)&&this.lastVideoAppendEnd<ce)this.blockAudio(U)}else if(i==="video"){let W=U.end,ce=this.lastVideoAppendEnd-W;if(this.lastVideoAppendEnd=W,ce<0||ce>U.duration)this.unblockAudio();else if(this.isAudioBlocked())this.executeNext("audio")}}let N=(l||o).start,H={label:`append-${i}`,execute:()=>{var V;d.executeStart=self.performance.now();let U=(V=this.tracks[i])==null?void 0:V.buffer;if(U){if(m)p=qt.timeRangesToArray(qt.getBuffered(U)),b=C3(Og(p,o),o);if(_)this.updateTimestampOffset(U,N,0.1,i,v,k);else if(h!==void 0&&lt(h))this.updateTimestampOffset(U,h,0.000001,i,v,k)}this.appendExecutor(s,i)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[i]);let V=self.performance.now();if(d.executeEnd=d.end=V,T.first===0)T.first=V;if((E==null?void 0:E.first)===0)E.first=V;let U={};if(this.sourceBuffers.forEach(([W,ce])=>{if(W)U[W]=qt.getBuffered(ce)}),m){let W=this.getFragmentAppendProgress(o),ce=U[i];if(ce&&p){let ue=qt.timeRangesToArray(ce),oe=Og(ue,o);W.progressed||(W.progressed=oe-Og(p,o)>tj);let ae=b&&C3(oe,o);W.fullyBuffered[i]=W.fullyBuffered[i]===void 0?ae:W.fullyBuffered[i]&&ae}}this.hls.trigger(O.BUFFER_APPENDED,{type:i,frag:o,part:l,chunkMeta:c,parent:r,timeRanges:U})},onError:(V)=>{var U;this.clearBufferAppendTimeoutId(this.tracks[i]);let W=V.code===DOMException.QUOTA_EXCEEDED_ERR||V.name=="QuotaExceededError"||"quota"in V;if(W){if(!this._quotaEvictionPending[i]){let ae=this.getBackBufferEvictionTarget(i,s.byteLength,o.type);if(ae>0){this._quotaEvictionPending[i]=!0,this.log(`QuotaExceededError on "${i}" append sn: ${v} - evicting back buffer to ${ae.toFixed(3)}s and retrying`);let te=this.getFlushOp(i,0,ae),me=this.getClearEvictionPendingOp(i);this.insertNext([te,H,me],i);return}this.warn(`QuotaExceededError on "${i}" sn: ${v} - no back buffer available to evict`)}}if(m)this.getFragmentAppendProgress(o).errored=!0;let ce={type:Et.MEDIA_ERROR,parent:r,details:ve.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:l,chunkMeta:c,error:V,err:V,fatal:!1},ue=(U=this.media)==null?void 0:U.error;if(V.name===D6&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))ce.errorAction=hh(!0);else{var oe;if(W)ce.details=ve.BUFFER_FULL_ERROR;let ae=++this.appendErrors[i],te=this.hls.config.appendErrorMaxRetry;if(this.warn(`Failed ${ae}/${te+1} times to append segment in "${i}" sourceBuffer with error: ${V.message}`),ae>=te)ce.fatal=!W;let me=(oe=this.mediaSource)==null?void 0:oe.readyState;if(me==="ended"||me==="closed"||!!ue)this.warn(`MediaSource readyState "${me}" during SourceBuffer${T3(ce.fatal,ue)}`),ce.details=ve.MEDIA_SOURCE_REQUIRES_RESET}if(this.appendError=ce,this.hls.trigger(O.ERROR,ce),W&&this.hls)this.trimBuffers(o.start,1)}};this.log(`queuing "${i}" append sn: ${v}${l?" p: "+l.index:""} of ${r} playlist ${o.level} cc: ${k} offset: ${h} bytes: ${s.byteLength}`),this.append(H,i,this.isPending(this.tracks[i]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{var s;let i=(s=this.tracks[e])==null?void 0:s.buffer;this.log(`Remove request ${t}-${n} from ${e} Source Buffer complete > buffer: ${i?s0(qt.getBuffered(i)):"(detached)"}`),this.hls.trigger(O.BUFFER_FLUSHED,{type:e,start:t,end:n})},onError:(s)=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,s),this.hls.trigger(O.BUFFER_FLUSHED,{type:e,start:0,end:0,error:s})}}}onBufferFlushing(e,t){let{type:n,startOffset:s,endOffset:i}=t;if(!n||n==="audio")this.unblockAudio();if(n)this.append(this.getFlushOp(n,s,i),n);else this.sourceBuffers.forEach(([r])=>{if(r)this.append(this.getFlushOp(r,s,i),r)})}onFragParsed(e,t){let{frag:n,part:s,chunkMeta:i}=t,r=[],o=s?s.elementaryStreams:n.elementaryStreams;if(o[Zn.AUDIOVIDEO])r.push("audiovideo");else{if(o[Zn.AUDIO])r.push("audio");if(o[Zn.VIDEO])r.push("video")}let l=()=>{let c=self.performance.now();if(n.stats.buffering.end=c,s)s.stats.buffering.end=c;let h=s?s.stats:n.stats;if(this.checkAppendProgress(n,s,i,r),!this.hls)return;if(this.hls.trigger(O.FRAG_BUFFERED,{frag:n,part:s,stats:h,id:n.type,chunkMeta:i}),!s&&n.gap&&h.retry)this.log(`Nothing buffered for ${n.type} level: ${n.level} sn: ${n.sn} retries ${h.retry}`)};if(r.length===0)this.log(`Fragments must have at least one ElementaryStreamType set. ${n.type} ${n.level} ${s?`part: ${s.index} of `:""}sn: ${n.sn}`);this.blockBuffers(l,r).catch((c)=>{this.warn(`Fragment buffered callback ${c.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var n,s;let i=(n=this.hls)==null?void 0:n.config;if(!i)return;let{backBufferLength:r,frontBufferFlushThreshold:o}=i;this.trimBuffers(o,r,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:c}=this,h=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach((d)=>{if(!l[d])return;if(c[d]=0,d===h)this.appendError=void 0;if(d==="audio"||d==="video"){if(c.audiovideo=0,h==="audiovideo")this.appendError=void 0}else if(c.audio=0,c.video=0,h!=="audiovideo")this.appendError=void 0})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var n;this.sourceBuffers.forEach(([r])=>{if(r){let o=this.tracks[r];if(!t.type||t.type===r){if(o.ending=!0,!o.ended)o.ended=!0,this.log(`${r} buffer reached EOS`)}}});let s=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;if(this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var o;return r&&!((o=this.tracks[r])!=null&&o.ended)}))if(this.unblockAudio(),s)this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:r}=this;if((r==null?void 0:r.readyState)!=="open"){if(r)this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(O.BUFFERED_TO_END,void 0)});else this.tracksEnded(),this.hls.trigger(O.BUFFERED_TO_END,void 0);else if(t.type==="video")this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];if(t)t.ending=!1}})}onLevelUpdated(e,{details:t}){if(!t.fragments.length)return;this.details=t,this.updateDuration()}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();if(!e)return;this.updateMediaSource(e)})}onError(e,t){if(t.details===ve.BUFFER_APPEND_ERROR&&t.frag){var n;let s=(n=t.errorAction)==null?void 0:n.nextAutoLevel;if(lt(s)&&s!==t.frag.level)this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,n){let{media:s}=this;if(!s)return 0;return this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,n,t)}getFragmentAppendProgress(e){var t;let n=E3(e),s=this.fragmentAppendProgress[n];if(((t=s)==null?void 0:t.stats)!==e.stats)s={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[n]=s;return s}checkAppendProgress(e,t,n,s){if(t||!js(e)||e.gap||n.iframe||n.partial)return;let i=E3(e),r=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];let o=e.stats.buffering;if(o.start&&!o.first)return;let l=(r==null?void 0:r.stats)===e.stats?r:void 0;if(l!=null&&l.errored)return;let c=s.length>0&&s.every((p)=>(l==null?void 0:l.fullyBuffered[p])===!0);if(l!=null&&l.progressed||c){delete this.appendsWithoutProgress[i];return}if(!l&&s.length===0)return;let h=(this.appendsWithoutProgress[i]||0)+1,d=this.hls;if(h>=d.config.appendErrorMaxRetry)delete this.appendsWithoutProgress[i];else this.appendsWithoutProgress[i]=h;this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${h} time${h>1?"s":""} without buffered range growth`),d.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:n,parent:e.type,appendsWithoutProgress:h,error:Error(`Fragment append did not increase buffered coverage (${h})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,t,n,s){let{hls:i,details:r,media:o}=this;if(!o||r===null)return;if(!this.sourceBufferCount)return;let l=i.config,c=o.currentTime,h=r.levelTargetDuration;t=r.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let d=-1/0;if(lt(t)&&t>=0){let m=Math.max(t,h);d=Math.floor(c/h)*h-m}if(n){let m=this.getLoopBackBufferFlushEnd(n,s!=null?s:null);if(m>0)d=Math.max(d,m)}if(d>0)this.flushBackBuffer(c,h,d);if(lt(e)&&e>0){let m=Math.max(l.maxBufferLength,e),p=Math.max(m,h),b=Math.floor(c/h)*h+p;this.flushFrontBuffer(c,h,b)}}getLoopBackBufferFlushEnd(e,t){var n;let{media:s}=this;if(((n=this.hls)==null?void 0:n.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!t||e.level<=t.level)return 0;let{video:i,audiovideo:r}=e.elementaryStreams;if(i!=null&&i.partial||r!=null&&r.partial)return 0;let o=this.getEarliestElementaryStreamStart(e)-ej;if(o<=0)return 0;return this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o}getEarliestElementaryStreamStart(e){let{audio:t,video:n,audiovideo:s}=e.elementaryStreams,i=e.start;if(s)i=Math.min(i,s.startDTS);else{if(t)i=Math.min(i,t.startDTS);if(n)i=Math.min(i,n.startDTS)}return i}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([s,i])=>{if(i){let c=qt.getBuffered(i);if(c.length>0&&n>c.start(0)){var r,o,l;this.hls.trigger(O.BACK_BUFFER_REACHED,{bufferEnd:n});let h=this.tracks[s];if((r=this.details)!=null&&r.live)this.hls.trigger(O.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(h!=null&&h.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(O.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:s})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([s,i])=>{if(i){let r=qt.getBuffered(i),o=r.length;if(o<2)return;let l=r.start(o-1),c=r.end(o-1);if(n>l||e>=l&&e<=c)return;this.hls.trigger(O.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;let{details:t,mediaSource:n}=this;if(!t||!this.media||(n==null?void 0:n.readyState)!=="open")return null;let s=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&!!n.setLiveSeekableRange){let c=Math.max(0,t.fragmentStart),h=Math.max(c,s);return{duration:1/0,start:c,end:h}}return{duration:1/0}}let i=(e=this.overrides)==null?void 0:e.duration;if(i){if(!lt(i))return null;return{duration:i}}let r=this.media.duration,o=lt(n.duration)?n.duration:0;if(s>o&&s>r||!lt(r))return{duration:s};return null}updateMediaSource({duration:e,start:t,end:n}){let s=this.mediaSource;if(!s||!this.media||s.readyState!=="open")return;if(s.duration!==e){if(lt(e))this.log(`Updating MediaSource duration to ${e.toFixed(3)}`);s.duration=e}if(t!==void 0&&n!==void 0)this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${t}-${n}.`),s.setLiveSeekableRange(t,n)}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ls(n)}`),this.tracksReady){var s;let i=(s=this.transferData)==null?void 0:s.tracks;if(i&&Object.keys(i).length)this.attachTransferred();else this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let s=this.tracks[t];e[t]={buffer:n,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(O.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(let i in e){let r=i,o=e[r];if(this.isPending(o)){let l=this.getTrackCodec(o,r),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(r)?" Queued":""} ${ls(o)}`);try{let h=n.addSourceBuffer(c),d=Lg(r),m=[r,h];t[d]=m,o.buffer=h}catch(h){var s;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(r),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[r],this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:r,mimeType:c,parent:o.id});return}this.trackSourceBuffer(r,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){if(!e)return;self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0}getTrackCodec(e,t){let{supplemental:n,codec:s}=e;if(n&&(t==="video"||t==="audiovideo")&&vh(n,"video"))s=dE(s,n);let i=Fd(s,e.levelCodec);if(i){if(t.slice(0,5)==="audio")return Wd(i,this.appendSource);return i}return""}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let s=this.getTrackCodec(t,e);if(this.tracks[e]={buffer:n,codec:s,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource)this.addBufferListener(e,"bufferedchange",(i,r)=>{let o=r.removedRanges;if(o!=null&&o.length)this.log(`${i} buffer removed ${s0(o)}`),this.hls.trigger(O.BUFFER_FLUSHED,{type:i,start:o.start(0),end:o.end(o.length-1)})})}get mediaSrc(){var e,t;let n=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(e){let t=this.currentOp(e);if(!t)return;t.onStart()}onSBUpdateEnd(e){var t,n;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);if(!s)return;if(s.onComplete(),(n=this.tracks[e])==null||(n=n.buffer)==null?void 0:n.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var n;let s=(n=this.mediaSource)==null?void 0:n.readyState,i=Error(`${e} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${i.message}`,t),this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});let r=this.currentOp(e);if(r)r.onError(i)}updateTimestampOffset(e,t,n,s,i,r){let o=t-e.timestampOffset;if(Math.abs(o)>=n)this.log(`Updating ${s} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${r})`),e.timestampOffset=t}removeExecutor(e,t,n){let{media:s,mediaSource:i}=this,r=this.tracks[e],o=r==null?void 0:r.buffer;if(!s||!i||!o)throw Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=lt(s.duration)?s.duration:1/0,c=lt(i.duration)?i.duration:1/0,h=Math.max(0,t);if(h>=c){var d;(d=this.currentOp(e))==null||d.onComplete(),this.shiftAndExecuteNext(e);return}let m=Math.min(n,l,c);if(m>h&&(!r.ending||r.ended))r.ended=!1,this.log(`Removing [${h},${m}] from the ${e} SourceBuffer`),o.remove(h,m);else throw Error(`Cannot remove ${m<=h?`invalid range (${h} >= ${m}) `:""}from the ${e} SourceBuffer${r.ending?" while track ending":""}`)}appendExecutor(e,t){let n=this.tracks[t],s=n==null?void 0:n.buffer;if(!s)throw new q6(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){let i=this.calculateAppendTimeoutTime(s);n.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,s,i),i)}s.appendBuffer(e)}appendTimeoutHandler(e,t,n){this.log(`Received timeout after ${n}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch(i){this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let s=this.currentOp(e);if(s)s.onError(Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=U9;if(this.details)t=this.details.levelTargetDuration;let n=2*t*1000;if(this.media===null)return n;let s=qt.bufferInfo(e,this.media.currentTime,0);if(!s.len)return n;return n=Math.max(s.len*1000,n),Math.max(this.hls.config.appendTimeout,n)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((t)=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){if(this.operationQueue)return this.operationQueue.audioBlocking();return!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:n}=this,i=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map((r)=>this.appendBlocker(r));return Promise.all(i).then((r)=>{if(n!==this.operationQueue)return;e(),this.stepOperationQueue(this.sourceBufferTypes)})}stepOperationQueue(e){e.forEach((t)=>{var n;let s=(n=this.tracks[t])==null?void 0:n.buffer;if(!s||s.updating||t==="audio"&&this.isAudioBlocked())return;this.shiftAndExecuteNext(t)})}append(e,t,n){if(this.operationQueue)this.operationQueue.append(e,t,n)}insertNext(e,t){if(this.operationQueue)this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){if(this.operationQueue)return this.operationQueue.current(e);return null}executeNext(e){if(e&&this.operationQueue)this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){if(this.operationQueue)this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter((e)=>!!e)}addBufferListener(e,t,n){let s=this.tracks[e];if(!s)return;let i=s.buffer;if(!i)return;let r=n.bind(this,e);s.listeners.push({event:t,listener:r}),Un(i,t,r)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;if(!n)return;t.listeners.forEach((s)=>{Bn(n,s.event,s.listener)}),t.listeners.length=0}}function A3(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach((n)=>{e.removeChild(n)})}function nj(e,t){let n=self.document.createElement("source");n.type="video/mp4",n.src=t,e.appendChild(n)}function Lg(e){return e==="audio"?1:0}function T3(e,t){return`${e?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function E3(e){return`${e.type}_${e.sn}_${e.level}`}function Og(e,t){let{start:n,end:s}=t,i=0;for(let r=0;r<e.length;r++){let o=e[r];if(o.start>=s)break;let l=Math.max(n,o.start),c=Math.min(s,o.end);if(c>l)i+=c-l}return i}function C3(e,t){return t.duration-e<=0.05}class V1{constructor(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){if(this.hls)this.unregisterListener();if(this.timer||this.observer)this.stopCapping();this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;if(e)e.on(O.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(O.BUFFER_CODECS,this.onBufferCodecs,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;if(e)e.off(O.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(O.BUFFER_CODECS,this.onBufferCodecs,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){if(!this.hls)return;let n=this.hls.levels[t.droppedLevel];if(this.isLevelAllowed(n))this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){let n=t.media;if(this.clientRect=null,!this.hls)return;if(n instanceof HTMLVideoElement){if(this.media=n,this.hls.config.capLevelToPlayerSize)this.observe()}else this.media=null;if((this.timer||this.observer)&&this.hls.levels.length>1)this.detectPlayerSize()}onManifestParsed(e,t){if(this.restrictedLevels=[],t.video)this.startCapping();this.onLevelsUpdated()}onLevelsUpdated(){if(!this.hls)return;if((this.timer||this.observer)&&(lt(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){let e=this.hls.levels;if(e.length>1&&e.some((t)=>!!t.videoCodec))this.startCapping()}}onBufferCodecs(e,t){if(t.video)this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,n=this.getMaxLevel(e.length-1);if(n!==this.autoLevelCapping)t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);if(t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController)this.streamController.nextLevelSwitch();this.autoLevelCapping=t.autoLevelCapping}else if(e.length===1)this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let n=t.filter((s,i)=>this.isLevelAllowed(s)&&i<=e);if(!this.observer)this.clientRect=null;return V1.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;if(e)this.observer=new e((t)=>{var n;let s=(n=t[0])==null?void 0:n.contentRect;if(s)this.clientRect=s,this.detectPlayerSize()});if(this.observer&&this.media)this.observer.observe(this.media)}startCapping(){var e;if(this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize))return;if(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),!this.observer)this.timer=self.setInterval(this.detectPlayerSize.bind(this),1000);this.detectPlayerSize()}stopCapping(){if(this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer)self.clearInterval(this.timer),this.timer=void 0;if(this.observer)this.observer.disconnect(),this.observer=void 0}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();if(t.width=n.width,t.height=n.height,!t.width&&!t.height)t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:n}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch(s){}return Math.min(e,n)}isLevelAllowed(e){return!this.restrictedLevels.some((n)=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let s=(o,l)=>{if(!l)return!0;return o.width!==l.width||o.height!==l.height},i=e.length-1,r=Math.max(t,n);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=r||l.height>=r)&&s(l,e[o+1])){i=o;break}}return i}}var Qi=class e{constructor(t,n){if(Array.isArray(t))t=t.map((s)=>s instanceof e?s:new e(s));this.value=t,this.params=n}},sj="Dict";function ij(e){if(Array.isArray(e))return JSON.stringify(e);if(e instanceof Map)return"Map{}";if(e instanceof Set)return"Set{}";if(typeof e==="object")return JSON.stringify(e);return String(e)}function rj(e,t,n,s){return Error(`failed to ${e} "${ij(t)}" as ${n}`,{cause:s})}var j3="Bare Item",aj="Boolean",oj="Byte Sequence",lj="Decimal",cj="Integer";function fj(e){return e<-999999999999999||999999999999999<e}var hj="String",uj=/[\x00-\x1f\x7f]+/,F6=class{constructor(e){this.description=e}},dj="Token",mj="Key";function Ra(e,t,n){return rj("serialize",e,t,n)}function pj(e){if(typeof e!=="boolean")throw Ra(e,aj);return e?"?1":"?0"}function gj(e){if(ArrayBuffer.isView(e)===!1)throw Ra(e,oj);return`:${kT(e)}:`}function L6(e){if(fj(e))throw Ra(e,cj);return e.toString()}function bj(e){return`@${L6(e.getTime()/1000)}`}function wj(e){let t=a9(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ra(e,lj);let n=t.toString();return n.includes(".")?n:`${n}.0`}function yj(e){if(uj.test(e))throw Ra(e,hj);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function vj(e){return e.description||e.toString().slice(7,-1)}function _3(e){let t=vj(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ra(t,dj);return t}function f1(e){switch(typeof e){case"number":if(!lt(e))throw Ra(e,j3);if(Number.isInteger(e))return L6(e);return wj(e);case"string":return yj(e);case"symbol":return _3(e);case"boolean":return pj(e);case"object":if(e instanceof Date)return bj(e);if(e instanceof Uint8Array)return gj(e);if(e instanceof F6)return _3(e);default:throw Ra(e,j3)}}function h1(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Ra(e,mj);return e}function $1(e){if(e==null)return"";return Object.entries(e).map(([t,n])=>{if(n===!0)return`;${h1(t)}`;return`;${h1(t)}=${f1(n)}`}).join("")}function O6(e){if(e instanceof Qi)return`${f1(e.value)}${$1(e.params)}`;else return f1(e)}function Sj(e){return`(${e.value.map(O6).join(" ")})${$1(e.params)}`}function kj(e,t={whitespace:!0}){if(typeof e!=="object"||e==null)throw Ra(e,sj);let n=e instanceof Map?e.entries():Object.entries(e),s=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([i,r])=>{if(r instanceof Qi===!1)r=new Qi(r);let o=h1(i);if(r.value===!0)o+=$1(r.params);else if(o+="=",Array.isArray(r.value))o+=Sj(r);else o+=O6(r);return o}).join(`,${s}`)}function P6(e,t){return kj(e,t)}var xj=["url"],Aj=["version","eventTargets","sid","transmissionMode"],Tj=["customData","headers"],I3=(e)=>{if(e instanceof Qi)return new Qi(Math.round(e.value),e.params);return Math.round(e)},Pg=(e)=>{if(Array.isArray(e))return e.map(I3);return I3(e)},u1=(e,t)=>{if(Array.isArray(e))return e.map((n)=>u1(n,t));if(e instanceof Qi&&typeof e.value==="string")return new Qi(u1(e.value,t),e.params);else{if(t.baseUrl)e=ET(e,TT(t.baseUrl));return t.version===1?encodeURIComponent(e):e}},R3=(e)=>{if(e instanceof Qi)return new Qi(Math.round(e.value/100)*100,e.params);return Math.round(e/100)*100},Cd=(e)=>{if(Array.isArray(e))return e.map(R3);return R3(e)},Ej=(e,t)=>{let n=e;if(t.version>=2){if(e instanceof Qi&&typeof e.value==="string")n=new Qi([e]);else if(typeof e==="string")n=[e]}return u1(n,t)},Cj={br:Pg,d:Pg,bl:Cd,dl:Cd,mtp:Cd,nor:Ej,rtp:Cd,tb:Pg},Ch=2,N6="bc",jj="ps",B6="pr",_j="e",D3="t",Ij="c",H6="b",X1="rr",U6="ce",jd={BITRATE_CHANGE:N6,ERROR:_j,RESPONSE_RECEIVED:X1,CUSTOM_EVENT:U6},z6=new Map([[jj,"sta"],[B6,"pr"],[Ij,"cid"],[H6,"bg"],[N6,"br"]]),W1="event",K1="request",G6=["cen","e","h","ts"],V6=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Rj=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Y1(e){return Rj.test(e)}var Dj=new Set(V6);function $6(e){return Dj.has(e)||Y1(e)}var X6=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],qj=new Set(X6);function W6(e){return qj.has(e)}var Mj=new Set(G6);function Fj(e){return $6(e)||W6(e)||Mj.has(e)}var Lj=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),y0=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Oj=new Set(y0);function Pj(e){return Oj.has(e)||Y1(e)}var Nj=new Set(["ot","sf","st","e","sta"]);function Bj(e){return Nj.has(e)}function Hj(e){if(typeof e==="number")return lt(e);return e!=null&&e!==""&&e!==!1}var Uj={[W1]:Fj,[K1]:$6};function K6(e,t){if(Array.isArray(e)){let n;if(t)n=e.find((s)=>{var i;return((i=s.params)==null?void 0:i.ot)===t});if(!n)n=e[0];return K6(n)}if(e instanceof Qi)return e.value;return e}function zj(e){let t={};for(let[s,i]of Object.entries(e)){if(i==null){t[s]=i;continue}if(s==="nor"){let r=(Array.isArray(i)?i:[i])[0];if(r instanceof Qi){var n;if(t.nor=r.value,(n=r.params)!=null&&n.r)t.nrr=r.params.r}else t.nor=r}else if(Lj.has(s))t[s]=K6(i,e.ot);else t[s]=i}return t}function Y6(e,t={}){let n={};if(e==null||typeof e!=="object")return n;let s=t.version||e.v||Ch,i=t.reportingMode||K1,r=s===1?zj(e):e,o=s===1?Pj:Uj[i],l=Object.keys(r).filter(o);if(r.e&&r.e!==X1)l=l.filter((b)=>!W6(b));let c=t.filter;if(typeof c==="function")l=l.filter(c);let h=i===W1;if(h){let b=r.e;if(!l.includes("e")&&b!=null)l.push("e");if(!l.includes("ts"))l.push("ts");if(!l.includes("cen")&&r.cen!=null&&b===U6)l.push("cen");let v=b?z6.get(b):void 0;if(v&&r[v]!=null&&!l.includes(v))l.push(v)}if(l.length===0)return n;if(s>1&&!l.includes("v"))l.push("v");let d={version:s,reportingMode:i,baseUrl:t.baseUrl};l.sort();for(let b of l){var m,p;let v=r[b],k=(m=(p=t.formatters)==null?void 0:p[b])!=null?m:Cj[b];if(typeof k==="function")v=k(v,d);if(b==="v")if(s===1)continue;else v=s;if(b==="pr"&&v===1&&!(h&&r.e===B6))continue;if(h&&b==="ts"&&!lt(v))v=Date.now();let A=h&&v===!1&&b==="bg"&&r.e===H6;if(!Hj(v)&&!A)continue;if(Bj(b)&&typeof v==="string")v=new F6(v);n[b]=v}return n}var co="CMCD-Object",Yi="CMCD-Request",zc="CMCD-Session",Jr="CMCD-Status",Gj={REQUEST:Yi},Vj={ab:co,br:co,d:co,lab:co,lb:co,ot:co,tab:co,tb:co,tpb:co,bl:Yi,cs:Yi,dfa:Yi,dl:Yi,ltc:Yi,mtp:Yi,nor:Yi,nrr:Yi,pb:Yi,sn:Yi,sta:Yi,su:Yi,tbl:Yi,cid:zc,msd:zc,sf:zc,sid:zc,st:zc,v:zc,bg:Jr,bs:Jr,bsa:Jr,bsd:Jr,bsda:Jr,cdn:Jr,ec:Jr,nr:Jr,pr:Jr,pt:Jr,rtp:Jr};function $j(e){return Object.keys(e).reduce((t,n)=>{var s;return(s=e[n])==null||s.forEach((i)=>t[i]=n),t},{})}function Xj(e,t){let n={};if(!e)return n;let s=Object.keys(e),i=t?$j(t):{};for(let o of s){var r;let l=Vj[o]||i[o]||Gj.REQUEST,c=(r=n[l])!=null?r:n[l]={};c[o]=e[o]}return n}function Wj(e,t){let n={},s=Xj(e,t);for(let[i,r]of Object.entries(s)){let o=P6(r,{whitespace:!1});if(o)n[i]=o}return n}var q3="CMCD";function Q6(e){return P6(e,{whitespace:!1})}function Kj(e,t={}){if(!e)return"";return Q6(Y6(e,t))}var Yj=30,m1=[...y0,...V6,...X6,...G6].filter((e,t,n)=>n.indexOf(e)===t),Qj="application/cmcd",Jj=1,Ei={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ea={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},Q1="query",J6="headers";function M3(e,t,n){var s;let i=new Set((s=t.enabledKeys)!=null?s:[]);return{version:t.version||Ch,reportingMode:e,filter:(r)=>i.has(r),baseUrl:n}}function Zj(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let s=e[n],i=t[n];if(s===i)continue;if(typeof s==="number"||typeof i==="number")return!1;if(s.value!==i.value)return!1;let r=s.params,o=i.params,l=r&&Object.keys(r)[0],c=o&&Object.keys(o)[0];if(l!==c)return!1;if(l!==void 0&&c!==void 0&&r&&o&&r[l]!==o[c])return!1}return!0}var e_=Object.is,t_=(e)=>e,Z6=Array.from(z6,([e,t])=>{if(t==="br")return{event:e,field:t,equal:(n,s)=>n===void 0||s===void 0?n===s:Zj(n,s),snapshot:(n)=>n.slice()};return{event:e,field:t,equal:e_,snapshot:t_}}),n_=new Map(Z6.map((e)=>[e.event,e]));function s_(e){let{url:t}=e,n=f0(e,xj);return fetch(t,n)}function i_(e){let{version:t=Ch,eventTargets:n=[],sid:s=o9(),transmissionMode:i=Q1}=e,r=f0(e,Aj);return Ct(Ct({},r),{},{version:t,transmissionMode:i,sid:s,eventTargets:n.reduce((o,l)=>{var c,h,d;if(l!=null&&l.url&&(c=l.events)!=null&&c.length)o.push({version:l.version||Ch,enabledKeys:((h=l.enabledKeys)==null?void 0:h.slice())||[],url:l.url,events:l.events.slice(),interval:(d=l.interval)!=null?d:Yj,batchSize:l.batchSize||1});return o},[])})}var r_=class{constructor(e,t=s_){var n;this.timeOrigin=performance.timeOrigin||((n=performance.timing)==null?void 0:n.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=i_(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(let s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),t.interval===0||!t.events.includes(D3))return;let n=()=>{this.recordTargetEvent(e,t,D3),this.processEventTargets()};e.intervalId=setInterval(n,t.interval*1000),n()})}stop(e=!1){if(e)this.flush();this.eventTargets.forEach((t)=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(e){if(e.sid&&e.sid!==this.data.sid)this.resetSession();if(e.msd&&!isNaN(e.msd))this.msd=e.msd;this.data=Ct(Ct(Ct({},this.data),e),{},{msd:void 0});for(let t of Z6)if(t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field]))this.recordEvent(t.event)}recordEvent(e,t={}){let n=n_.get(e);if(n){let s=n.field,i=t[s];if(i!==void 0)Gn(this.data,{[s]:i});let r=this.data[s];if(r===void 0)return;if(n.equal(r,this.lastEmitted[s]))return;Gn(this.lastEmitted,{[s]:n.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,n,s={}){var i;if(!t.events.includes(n))return;let r=Ct(Ct(Ct({},this.data),s),{},{e:n,ts:(i=s.ts)!=null?i:Date.now(),sn:e.sn++});if(!isNaN(this.msd)&&!e.msdSent)r.msd=this.msd,e.msdSent=!0;e.queue.push(r)}recordResponseReceived(e,t={}){var n,s,i;let{request:r}=e,o=(n=t.url)!=null?n:r==null?void 0:r.url;if(!o)return;let l=new URL(o);l.searchParams.delete(q3);let c={url:l.toString(),rc:e.status},h=e.resourceTiming;if(h){if(h.startTime!=null){if(c.ts=Math.round(this.timeOrigin+h.startTime),h.responseStart!=null)c.ttfb=Math.round(h.responseStart-h.startTime)}if(h.duration!=null)c.ttlb=Math.round(h.duration)}let d=(s=(i=r.customData)==null?void 0:i.cmcd)!=null?s:{};this.recordEvent(X1,Ct(Ct(Ct({},d),c),t))}applyRequestReport(e){var t;return(t=this.createRequestReport(e))!=null?t:e}isRequestReportingEnabled(){var e;return!!((e=this.config.enabledKeys)!=null&&e.length)}createRequestReport(e,t){var n;let{customData:s={},headers:i={}}=e,r=f0(e,Tj),o=Ct(Ct({},r),{},{headers:Ct({},i),customData:Ct(Ct({},s),{},{cmcd:{}})});if(!((n=this.config.enabledKeys)!=null&&n.length)||!o.url)return o;let l=new URL(o.url),c=Ct(Ct(Ct({},this.data),t),{},{sn:this.requestTarget.sn++}),h=M3(K1,this.config,o.url);if(!isNaN(this.msd)&&!this.requestTarget.msdSent)c.msd=this.msd,this.requestTarget.msdSent=!0;let d=o.customData.cmcd=Y6(c,h);switch(this.config.transmissionMode){case Q1:let m=Q6(d);if(m)l.searchParams.set(q3,m),o.url=l.toString();break;case J6:Gn(o.headers,Wj(d,h.customHeaderMap));break}return o}processEventTargets(e=!1){let t=!1;if(this.eventTargets.forEach((n,s)=>{let{queue:i}=n;if(!i.length)return;if(i.length<s.batchSize&&!e)return;let r=e?i.length:s.batchSize,o=i.splice(0,r);this.sendEventReport(s,o).catch(()=>{n.queue.unshift(...o)}),t||(t=i.length>0)}),t)this.processEventTargets()}async sendEventReport(e,t){let n=M3(W1,e),{status:s}=await this.requester({url:e.url,method:"POST",headers:{"Content-Type":Qj},body:t.map((i)=>Kj(i,n)).join(`
39
- `)+`
40
- `});if(s===410)this.disposeEventTarget(e);else if(s===429||s>499&&s<600)throw Error(`Event report failed with status ${s}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){let t=this.eventTargets.get(e);if(!t)return;this.disarmInterval(t),this.eventTargets.delete(e)}resetSession(){this.eventTargets.forEach((e)=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},a_={HLS:"h"},Ng={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function o_(e,t){return new Qi(e,t)}new Set(y0);new Set(m1);var l_=["includeKeys"];function F3(e){return Object.keys(e).every(Y1)}class ev{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{if(this.initialized)this.starved=!0,this.setPlayerState(ea.REBUFFERING);this.buffering=!0},this.onPlay=()=>{if(!this.initialized)this.setPlayerState(ea.STARTING)},this.onPlaying=()=>{if(!this.initialized)this.initialized=!0;this.buffering=!1,this.setPlayerState(ea.PLAYING)},this.onPause=()=>{if(this.media&&!this.media.ended)this.setPlayerState(ea.PAUSED)},this.onSeeking=()=>{if(this.initialized)this.setPlayerState(ea.SEEKING)},this.onSeeked=()=>{var s;if(!this.initialized)return;if((s=this.media)!=null&&s.paused)this.setPlayerState(ea.PAUSED)},this.onRateChange=()=>{if(this.reporter&&this.media)this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=(s)=>{try{this.apply(s,{ot:Ei.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=(s)=>{try{let{frag:o,part:l}=s,c=this.hls.levels[o.level],h=this.getObjectType(o,c),d={d:(l||o).duration*1000,ot:h};if(h===Ei.VIDEO||h===Ei.AUDIO||h===Ei.MUXED||h==null&&(o.type==="main"||o.type==="audio")){var i;let p=c.bitrate/1000;d.br=[p];let{cmcd:b}=this.config,v=(i=b==null?void 0:b.rtpSafetyFactor)!=null?i:5;if(d.rtp=Math.round(p*v/100)*100,h===Ei.MUXED||h==null&&o.type==="main"){let T=this.getTopBandwidth()/1000;if(lt(T))d.tb=[T];let E=this.getLowestBandwidth()/1000;if(lt(E))d.lb=[E]}let k=this.getBufferLength(o);if(lt(k)){var r;d.bl=[k];let T=((r=this.media)==null?void 0:r.playbackRate)||1;d.dl=Math.round(k/T/100)*100}if(this.playheadLevel)d.pb=[this.playheadLevel.bitrate/1000];let A=this.hls.maxAutoLevel;if(A>=0){let T=this.hls.levels[A];if(T)d.tpb=[T.bitrate/1000]}}let m=l?this.getNextPart(l):this.getNextFrag(o);if(m!=null&&m.url&&m.url!==o.url)if(m.byteRange.length>0)d.nor=[o_(m.url,{r:`${m.byteRange[0]}-${m.byteRange[1]}`})];else d.nor=[m.url];this.apply(s,d)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(s,i,r)=>{var o;let{cmcd:l}=this.config,c=l==null||(o=l.eventTargets)==null?void 0:o.some((h)=>{var d;return(d=h.events)==null?void 0:d.includes(jd.RESPONSE_RECEIVED)});if(!this.reporter||!(r.loading.first>0)||!c)return;try{this.reporter.recordResponseReceived({request:{url:s},status:i.code,resourceTiming:{startTime:r.loading.start,responseStart:r.loading.first,duration:r.loading.end-r.loading.start,encodedBodySize:r.total}})}catch(h){this.hls.logger.warn("Could not record fragment response CMCD data.",h)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;if(n!=null)t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners()}createReporter(){var e,t;let{cmcd:n}=this.config;if(n==null)return;let s=n.version||Jj;if(this.reporter=new r_({sid:n.sessionId||this.hls.sessionId,cid:n.contentId,version:s,transmissionMode:n.useHeaders===!0?J6:Q1,enabledKeys:(e=n.includeKeys)!=null?e:[...s>=Ch?m1:y0],eventTargets:((t=n.eventTargets)!=null?t:[]).map((i)=>{let{includeKeys:r}=i,o=f0(i,l_);return Ct(Ct({},o),{},{enabledKeys:r!=null?r:m1})})},n.loader),this.reporter.update({sf:a_.HLS,sta:this.playerState}),n.reporterCallback){let i=this.reporter,r={updateCustomData:(o)=>{if(F3(o))i.update(o)},recordCustomEvent:(o,l={})=>{if(F3(l))i.recordEvent(jd.CUSTOM_EVENT,Ct({cen:o},l))}};n.reporterCallback(r)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MEDIA_DETACHED,this.onMediaDetached,this),e.on(O.MEDIA_ENDED,this.onMediaEnded,this),e.on(O.ERROR,this.onError,this),e.on(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(O.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(O.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(O.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MEDIA_DETACHED,this.onMediaDetached,this),e.off(O.MEDIA_ENDED,this.onMediaEnded,this),e.off(O.ERROR,this.onError,this),e.off(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(O.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(O.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(O.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){if(this.unregisterListeners(),this.onMediaDetached(),this.reporter)this.reporter.stop(!0),this.reporter=void 0;this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){let n=this.media=t.media;this.setPlayerState(this.media.autoplay?ea.STARTING:ea.PRELOADING),Un(n,"waiting",this.onWaiting),Un(n,"play",this.onPlay),Un(n,"playing",this.onPlaying),Un(n,"pause",this.onPause),Un(n,"seeking",this.onSeeking),Un(n,"seeked",this.onSeeked),Un(n,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;if(!e)return;Bn(e,"waiting",this.onWaiting),Bn(e,"play",this.onPlay),Bn(e,"playing",this.onPlaying),Bn(e,"pause",this.onPause),Bn(e,"seeking",this.onSeeking),Bn(e,"seeked",this.onSeeked),Bn(e,"ratechange",this.onRateChange),this.media=null}onMediaEnded(e,t){this.setPlayerState(ea.ENDED)}onManifestLoading(e,t){if(this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter)this.reporter.stop(!0),this.reporter=void 0;if(this.createReporter(),!this.media)this.setPlayerState(ea.PRELOADING)}onError(e,t){if(t.fatal){if(this.setPlayerState(ea.FATAL_ERROR),this.reporter)this.reporter.recordEvent(jd.ERROR,{ec:[t.details]})}}onLevelSwitching(e,t){var n;if(!this.reporter)return;let s={br:[t.bitrate/1000]},i=(n=t.details)==null?void 0:n.fragments[0];if(i)s.ot=this.getObjectType(i,t);this.reporter.recordEvent(jd.BITRATE_CHANGE,s)}onLevelSwitched(e,t){let n=this.hls.levels[t.level];if(n)this.playheadLevel=n}setPlayerState(e){if(this.playerState=e,this.reporter)this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;if(!e)return;if(!e.live)return Ng.VOD;if(!!e.partList&&e.canBlockReload)return Ng.LOW_LATENCY;return Ng.LIVE}apply(e,t={}){var n;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1000],pr:(n=this.media)==null?void 0:n.playbackRate,st:this.getStreamType()});let s=t.ot===Ei.INIT||t.ot===Ei.VIDEO||t.ot===Ei.MUXED;if(this.starved&&s)t.bs=!0,t.su=!0,this.starved=!1;if(t.su==null)t.su=this.buffering;let i=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=i.url,e.headers=i.headers}getNextFrag(e){var t;let n=(t=this.hls.levels[e.level])==null?void 0:t.details;if(n){let s=e.sn-n.startSN;return n.fragments[s+1]}return}getNextPart(e){var t;let{index:n,fragment:s}=e,i=(t=this.hls.levels[s.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:r}=s;for(let o=i.length-1;o>=0;o--){let l=i[o];if(l.index===n&&l.fragment.sn===r)return i[o+1]}}return}getObjectType(e,t){let{type:n}=e;if(n==="subtitle")return Ei.TIMED_TEXT;if(e.sn==="initSegment")return Ei.INIT;if(n==="audio")return Ei.AUDIO;if(n==="main"){if(e.hasStreams){let s=e.elementaryStreams;if(s.audiovideo)return Ei.MUXED;if(s.video)return Ei.VIDEO;if(s.audio)return Ei.AUDIO}if(t){let{audioCodec:s,videoCodec:i}=t;if(!this.hls.audioTracks.length){if(s&&i)return Ei.MUXED;if(s)return Ei.AUDIO}if(i)return Ei.VIDEO}}return}getTopBandwidth(){let e=0,t=this.hls,n=t.maxAutoLevel,s=n>-1?n+1:t.levels.length;return t.levels.slice(0,s).forEach((r)=>{if(r.bitrate>e)e=r.bitrate}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,n=t.maxAutoLevel,s=n>-1?n+1:t.levels.length;return t.levels.slice(0,s).forEach((r)=>{if(r.bitrate<e)e=r.bitrate}),lt(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1000:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1000;let n=e||t;return n?n.len*1000:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let n=this.getEventBufferLength();if(!lt(n))return;this.reporter.update({bl:[n]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,r,o){t(i),this.loader.load(i,r,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=this.recordFragmentResponse,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,o,l){t(r);let{onSuccess:c}=l;this.loader.load(r,o,Ct(Ct({},l),{},{onSuccess:(h,d,m,p)=>{c(h,d,m,p),n(r.url,h,d)}}))}}}}var c_=300000;class tv extends Ji{constructor(e){super("content-steering",e.logger);this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;if(!e)return;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.ERROR,this.onError,this)}pathways(){return(this.levels||[]).reduce((e,t)=>{if(e.indexOf(t.pathwayId)===-1)e.push(t.pathwayId);return e},[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1000-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){if(this.started=!1,this.loader)this.loader.destroy(),this.loader=null;this.clearTimeout()}clearTimeout(){if(this.reloadTimer!==-1)self.clearTimeout(this.reloadTimer),this.reloadTimer=-1}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;if(t)this.levels=t.filter((n)=>n!==e)}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;if(n===null)return;if(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started)this.startLoad()}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if((n==null?void 0:n.action)===gi.SendAlternateToPenaltyBox&&n.flags&pi.MoveAllAlternatesMatchingHost){let s=this.levels,i=this._pathwayPriority,r=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:c}=t.context;if(o&&s)r=this.getPathwayForGroupId(o,c,r);else if(l)r=l}if(!(r in this.penalizedPathways))this.penalizedPathways[r]=performance.now();if(!i&&s)i=this.pathways();if(i&&i.length>1){if(this.updatePathwayPriority(i),n.resolved=this.pathwayId!==r,!n.resolved&&(t.details!==ve.BUFFER_APPEND_ERROR||t.fatal))this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${r} levels: ${s?s.length:s} priorities: ${ls(i)} penalized: ${ls(this.penalizedPathways)}`)}}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}if(t.length!==e.length)this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`);return t}getLevelsForPathway(e){if(this.levels===null)return[];return this.levels.filter((t)=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,n=this.penalizedPathways,s=performance.now();Object.keys(n).forEach((i)=>{if(s-n[i]>c_)delete n[i]});for(let i=0;i<e.length;i++){let r=e[i];if(r in n)continue;if(r===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(r),t.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,e6(t),this.hls.trigger(O.LEVELS_UPDATED,{levels:t});let c=this.hls.levels[o];if(l&&c&&this.levels){if(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate)this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`);this.hls.nextLoadLevel=o}break}}}getPathwayForGroupId(e,t,n){let s=this.getLevelsForPathway(n).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(t===fn.AUDIO_TRACK&&s[i].hasAudioGroup(e)||t===fn.SUBTITLE_TRACK&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return n}clonePathways(e){let t=this.levels;if(!t)return;let n={},s={};e.forEach((i)=>{let{ID:r,"BASE-ID":o,"URI-REPLACEMENT":l}=i;if(t.some((h)=>h.pathwayId===r))return;let c=this.getLevelsForPathway(o).map((h)=>{let d=new vs(h.attrs);d["PATHWAY-ID"]=r;let m=d.AUDIO&&`${d.AUDIO}_clone_${r}`,p=d.SUBTITLES&&`${d.SUBTITLES}_clone_${r}`;if(m)n[d.AUDIO]=m,d.AUDIO=m;if(p)s[d.SUBTITLES]=p,d.SUBTITLES=p;let b=nv(h.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),v=new Yc({attrs:d,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:b,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let k=1;k<h.audioGroups.length;k++)v.addGroupId("audio",`${h.audioGroups[k]}_clone_${r}`);if(h.subtitleGroups)for(let k=1;k<h.subtitleGroups.length;k++)v.addGroupId("text",`${h.subtitleGroups[k]}_clone_${r}`);return v});t.push(...c),L3(this.audioTracks,n,l,r),L3(this.subtitleTracks,s,l,r)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;if(this.loader)this.loader.destroy();this.loader=new n(t);let s;try{s=new self.URL(e)}catch(h){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){let h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Qo(s,"_HLS_pathway",this.pathwayId),Qo(s,"_HLS_throughput",""+h)}let i={type:fn.STEERING_MANIFEST,responseType:"json",url:s.href},r=t.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},l={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,d,m,p)=>{this.log(`Loaded steering manifest: "${s}"`);let b=h.data;if((b==null?void 0:b.VERSION)!==1){this.log(`Steering VERSION ${b.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=b.TTL;let{"RELOAD-URI":v,"PATHWAY-CLONES":k,"PATHWAY-PRIORITY":A}=b;if(v)try{this.uri=new self.URL(v,s).href}catch(E){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${v}`);return}if(this.scheduleRefresh(this.uri||m.url),k)this.clonePathways(k);let T={steeringManifest:b,url:s.toString()};if(this.hls.trigger(O.STEERING_MANIFEST_LOADED,T),A)this.updatePathwayPriority(A)},onError:(h,d,m,p)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${d.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let b=this.timeToLoad*1000;if(h.code===429){let v=this.loader;if(typeof(v==null?void 0:v.getResponseHeader)==="function"){let k=v.getResponseHeader("Retry-After");if(k)b=parseFloat(k)*1000}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,b)},onTimeout:(h,d,m)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(i,l,c)}scheduleRefresh(e,t=this.timeToLoad*1000){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;let s=(n=this.hls)==null?void 0:n.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1000)},t)}}function L3(e,t,n,s){if(!e)return;Object.keys(t).forEach((i)=>{let r=e.filter((o)=>o.groupId===i).map((o)=>{let l=Gn({},o);return l.details=void 0,l.attrs=new vs(l.attrs),l.url=l.attrs.URI=nv(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),l.groupId=l.attrs["GROUP-ID"]=t[i],l.attrs["PATHWAY-ID"]=s,l});e.push(...r)})}function nv(e,t,n,s){if(t){let{[n]:l}=s;if(l){let c=l[t];if(c)return c}}let{HOST:i,PARAMS:r}=s,o=new self.URL(e);if(i)o.hostname=i;if(r)Object.keys(r).sort().forEach((l)=>{if(l)Qo(o,l,r[l])});return o.href}class sv{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new P1,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){if(this.error=e,this.emitter.eventNames().length)this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){if(this.ok)return Promise.resolve();if(this.error)return Promise.reject(this.error);return new Promise((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();let e=this.licenseXhr;if(e){if(e.readyState!==XMLHttpRequest.DONE)e.abort();this.licenseXhr=void 0}this.onmessage=this.onkeystatuseschange=void 0}}class Ir extends Error{constructor(e,t){super(t);this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}class Wc extends Ji{constructor(e){super("eme",e.logger);this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=Wc.CDMCleanupPromise?[Wc.CDMCleanupPromise]:[],this.onMediaEncrypted=(t)=>{let{initDataType:n,initData:s}=t,i=`"${t.type}" event: init data type: "${n}"`;if(this.log(i),s===null)return;if(!this.keyFormatPromise){let r=Object.keys(this.keySystemAccessPromises);if(!r.length)r=Jf(this.config);let o=r.map(jg).filter((l)=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then((r)=>{let o,l=Ad(r),c=this.activeLevelKeys();if(l===gs.FAIRPLAY&&n==="sinf")try{let b=ia(new Uint8Array(s)),v=_1(JSON.parse(b).sinf),k=w9(v);if(!k)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(k.subarray(8,24))}catch(b){this.warn(`${i} Failed to parse sinf: ${b}`);return}else if(l===gs.PLAYREADY)o=L1(new Uint8Array(s));else if(l===gs.WIDEVINE){let b=k9(s).filter((v)=>v.systemId===$9.WIDEVINE);if(b.length){var h;let v=b[0];o=(h=v.kids)!=null&&h.length?v.kids[0]:null}}let d;if(o){let b=Ys(o);for(let v=0;v<c.length;v++){let k=c[v];if(k.keyId&&(e0(o,k.keyId)||k.uri.replace(/-/g,"").indexOf(b)!==-1)){if(!k.pssh)k.scheme=n,k.pssh=new Uint8Array(s),k.keyId=o,ho.setKeyIdForUri(k.uri,o);d=this.getSessionForKey(k,"encrypted-event-key-match");break}}}if(!d){if(c.length){var m,p;return(m=c[0]).scheme||(m.scheme=n),(p=c[0]).pssh||(p.pssh=new Uint8Array(s)),this.getSessionForKey(c[0],"encrypted-event-no-match")}if(o)throw Error(`Key ID ${Ys(o)} not encountered in playlist`);else this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).catch((r)=>this.handleError(r))},this.onWaitingForKey=(t)=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;if(e)e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHED,this.onMediaDetached,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.DESTROYING,this.onDestroying,this)}unregisterListeners(){let{hls:e}=this;if(e)e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHED,this.onMediaDetached,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.DESTROYING,this.onDestroying,this)}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(Error("destroyed"));let t=this.hls.levels,n=(r,o,l)=>!!r&&l.indexOf(r)===o,s=t.map((r)=>r.audioCodec).filter(n),i=t.map((r)=>r.videoCodec).filter(n);if(s.length+i.length===0)i.push("avc1.42e01e");return new Promise((r,o)=>{let l=(c)=>{let h=c.shift();this.getMediaKeysPromise(h,s,i).then((d)=>r({keySystem:h,mediaKeys:d})).catch((d)=>{if(c.length)l(c);else if(d instanceof Ir)o(d);else o(new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${n}`;if(X9===null&&self.location.protocol==="http:")s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;return Promise.reject(Error(s))}return n(e,t)}getMediaKeysPromise(e,t,n){var s;let i=VE(e,t,n,this.config.drmSystemOptions||{}),r=this.keySystemAccessPromises[e],o=(s=r)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ls(i)}`),o=this.requestMediaKeySystemAccess(e,i);let l=r=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch((c)=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then((c)=>{this.throwIfDestroyed(),this.log(`Access for key-system "${c.keySystem}" obtained`);let h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let d=l.mediaKeys=c.createMediaKeys().then((m)=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,h.then((p)=>{if(p)return this.setMediaKeysServerCertificate(m,e,p);return m})));return d.catch((m)=>{this.error(`Failed to create media-keys for "${e}"}: ${m}`)}),d})}return o.then(()=>r.mediaKeys)}getMediaKeySessionContext(e,t,n,s){let{mediaKeySessions:i}=this,r=` key-session "${e}" keyId: ${Ys(n.keyId||[])} keyUri: ${n.uri} for "${s}"`;for(let c=0;c<i.length;c++){let h=i[c];if(!h.initialized&&h.createdFor.levelKey.uri===n.uri)return this.log(`Reusing${r}`),h}this.log(`Creating${r}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:n,reason:s},initialized:!1};return i.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,n=this.keySystemAccessPromises[t];if(n)this.log("reset mediaKeys"),this.mediaKeys=null,n.hasMediaKeys=!1,delete n.mediaKeys,delete this.keySystemAccessPromises[t]}updateKeySession(e,t,n){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Ys(t.keyId||[])}
41
- } (data length: ${n.byteLength})`),s.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((e)=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>jg(e)).filter((e)=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:n})=>this.attemptSetMediaKeys(t,n))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let n=jg(t);if(!n)throw Error(`Unable to find format for key-system "${t}"`);return n})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});if(!this.keyFormatPromise)this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t);return this.keyFormatPromise}getKeyFormatPromise(e){let t=Jf(this.config),n=e.map(Ad).filter((s)=>!!s&&t.indexOf(s)!==-1);return this.selectKeySystem(n)}loadClear(e,t,n){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,i=t.length;s<i;s++){let r=t[s];if(e.cc<=r.cc&&(!js(e)||!js(r)||e.sn<r.sn)||!n&&s==i-1)return this.selectKeySystemFormat(r).then((o)=>{if(!this.hls)return;r.setKeyFormat(o);let l=Ad(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let s=Jf(this.config);if(s.length)return this.getKeySystemAccess(s)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){let s=Bg(e,t[n]);if(s)return s}return}loadKey(e){let t=e.decryptdata,n=this.getKeyStatus(t);if(n==="internal-error"){let o=O3(n,t);return o.data.frag=e,this.error(`${o.message} (${Ys(t.keyId||[])})`),Promise.reject(o)}let s=e.type,i=this.activeKeys,r=i[s];if(r&&!t.matches(r.decryptdata))i.previous||(i.previous=[]),i.previous.push(r),delete i[s];i[s]||(i[s]=e);for(let o=this.mediaKeySessions.length;o--;){let l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ys(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,n){let s=this.getSessionForKey(e,t);return s.catch((i)=>this.handleError(i,n)),s.then((i)=>e)}getSessionForKey(e,t){let n=this.findContextForKey(e);if(n!==void 0)return Promise.resolve(n);let s=e.uri,i=this.sessionSetupByUri[s],r;if(i===void 0)r=this.resolveSessionForKey(e,t);else r=i.catch(()=>{return}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t)));this.sessionSetupByUri[s]=r;let o=()=>{if(this.sessionSetupByUri[s]===r)delete this.sessionSetupByUri[s]};return r.then(o,o),r}findContextForKey(e){let{mediaKeySessions:t}=this;for(let n=t.length;n--;){let s=t[n];if(Bg(e,s))return s}return}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:n,mediaKeys:s})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){let r=this.mediaKeySessions[i];if(Bg(e,r))return r;let o=this.getUsableKeyPromise(r,e,t);if(o)return o}return this.attemptSetMediaKeys(n,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(n,s,e,t))).then((i)=>{this.throwIfDestroyed();let r=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,e,r,o,t)})})}getUsableKeyPromise(e,t,n){let s=e.keyRequests[t.uri];if(s)return this.log(`Waiting for usable key (${n} keyId: ${u_(t)} format: "${t.keyFormat}" URI: ${t.uri})`),s.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e,t){if(!this.hls)return;if(e instanceof Ir){if(t)e.data.frag=t;let n=e.data.decryptdata;this.error(`${e.message}${n?` (${Ys(n.keyId||[])})`:""}`),this.hls.trigger(O.ERROR,e.data)}else this.error(e.message),this.hls.trigger(O.ERROR,{type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=Ad(e.keyFormat),n=t?[t]:Jf(this.config);return this.attemptKeySystemAccess(n)}getKeySystemSelectionPromise(e){if(!e.length)e=Jf(this.config);if(e.length===0)throw new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ls({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map((n)=>n.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let s=Promise.all(n).then(()=>{if(!this.media)return new Promise((i,r)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return r(Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(i).catch(r)}});return this.media.setMediaKeys(t)});return this.mediaKeys=t,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((i)=>n.indexOf(i)===-1)})}filterInitData(e,t,n,s,i){var r;let o=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(o)try{let c=o.call(this.hls,n,s,Gn({},e,{decryptdata:t,reason:i}),i);if(!c)throw Error("Invalid response from configured generateRequest filter");t.scheme=c.initDataType?c.initDataType:"cenc";let h=c.initData?c.initData:null;return t.pssh=h?new Uint8Array(h):null,c}catch(c){var l;if(this.warn(c.message),(l=this.hls)!=null&&l.config.debug)throw c}return{initDataType:n,initData:s}}generateRequestWithPreferredKeySession(e,t,n,s,i){let r=this.getUsableKeyPromise(e,t,i);if(r)return r;let o=this.filterInitData(e,t,n,s,i);if(o)s=o.initData?o.initData:null,n=o.initDataType;if(s===null)if(i.startsWith("encrypted-event"))return Promise.reject(Error(`missing initialization data for "${i}"`));else return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);let l=t.uri,c=new sv;e.keyRequests[l]=c;let h=(m)=>{let p=e.mediaKeysSession;if(!p){let k=Error("invalid state");c.errored=k;return}let{messageType:b,message:v}=m;if(c.status=b,this.log(`"${b}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),b==="license-request"||b==="license-renewal")this.renewLicense(e,t,v).catch((k)=>{if(c.errored=k,!c.hasListeners)this.handleError(k);this.removeSession(e)});else if(b==="license-release"){if(e.keySystem===gs.FAIRPLAY)this.updateKeySession(e,t,r1("acknowledged")).then(()=>this.removeSession(e)).catch((k)=>this.handleError(k))}else this.warn(`unhandled media key message type "${b}"`)};c.onmessage=h,Un(e.mediaKeysSession,"message",h);let d=!1;return this.generateRequest(e,t,n,s,i,d)}generateRequest(e,t,n,s,i,r){if(r){let p=this.filterInitData(e,t,n,s,i);if(p)s=p.initData?p.initData:s,n=p.initDataType}let o=t.uri,l=e.keyRequests[o],c=Ys(t.keyId||[]),h=(p)=>{let b;if(p.startsWith("usable"))l.resolve();else if(p==="internal-error"||p==="output-restricted"||p==="output-downscaled")b=O3(p,t);else if(p==="expired")b=Error(`key expired (keyId: ${c})`);else if(p==="released")b=Error("key released");else if(p==="status-pending");else this.warn(`unhandled key status change "${p}" (keyId: ${c})`);if(b){if(l.errored=b,!l.hasListeners)this.handleError(b)}},d=(p)=>{if(!e.mediaKeysSession){let _=Error("invalid state");l.errored=_;return}let v=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(v).some((_)=>v[_]!=="status-pending"))return;let A=this.activeLevelKeys();for(let _=0;_<A.length;_++){let q=Ys(A[_].keyId||[]);if(v[q]==="expired"){var T;this.log(`Expired key ${ls(v)} in key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}"`),this.renewKeySession(t,e).catch((P)=>this.handleError(P));break}}let E=v[c];if(E)h(E);else{var I;let _=1000;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(I=e.keyStatusTimeouts)[c]||(I[c]=self.setTimeout(()=>{var q;if(!e.mediaKeysSession)return;let P=this.getKeyStatus(t);if(P&&P!=="status-pending"){var N;return this.log(`No status for keyId ${c} in key-session "${(N=e.mediaKeysSession)==null?void 0:N.sessionId}". Using session key-status ${P} from other session.`),h(P)}this.log(`key status for ${c} in key-session "${(q=e.mediaKeysSession)==null?void 0:q.sessionId}" timed out after 1000ms`),E="internal-error",h(E)},1000)),this.log(`No status for keyId ${c} (${ls(v)}).`)}};l.onkeystatuseschange=d,Un(e.mediaKeysSession,"keystatuseschange",d);let m=l.useable;return this.log(`Generating key-session request for "${i}" keyId: ${c} URI: ${o} (init data type: ${n} length: ${s.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(n,s).then(()=>{var p;l.status="generated",this.log(`Request generated for key-session "${(p=e.mediaKeysSession)==null?void 0:p.sessionId}" keyId: ${c} URI: ${o}`)}).catch((p)=>{throw this.log(`mediaKeysSession.generateRequest failed: ${p}`),new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:t,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>m).catch((p)=>{var b;this.log(`mediaKeysSession.generateRequest failed: ${p}`);let v=(b=p.data)==null?void 0:b.details;if((v===ve.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||v===ve.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some((k)=>e.keyStatuses[k]==="usable"))return this.handleError(p),e;return this.removeSession(e).then(()=>{throw p})}).then(()=>e)}getKeyStatuses(e){let t={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i==="string"&&typeof s==="object"){let l=i;i=s,s=l}let r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===gs.PLAYREADY&&r.length===16){let l=Ys(r);t[l]=s,G9(r)}let o=Ys(r);this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${n}"`),t[o]=s}),t}fetchServerCertificate(e){let t=this.config,s=new t.loader(t),i=h_(e,t);if(!i)return this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve();return this.log(`Fetching server certificate for "${e}"`),new Promise((r,o)=>{let l={type:fn.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(m,p,b,v)=>{r(m.data)},onError:(m,p,b,v)=>{o(new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:Ct({url:l.url,data:void 0},m)},`"${e}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,b)=>{o(new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:b,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(m,p,b)=>{o(Error("aborted"))}};s.load(l,h,d)})}setMediaKeysServerCertificate(e,t,n){return new Promise((s,i)=>{e.setServerCertificate(n).then((r)=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${n.byteLength}) on "${t}"`),s(e)}).catch((r)=>{i(new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:r,fatal:!0},r.message))})})}renewLicense(e,t,n){return this.requestLicense(e,t,new Uint8Array(n)).then((s)=>this.updateKeySession(e,t,new Uint8Array(s)).catch((i)=>{throw new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){let n=ia(new Uint16Array(t.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let s=new DOMParser().parseFromString(n,"application/xml"),i=s.querySelectorAll("HttpHeader");if(i.length>0){let h;for(let d=0,m=i.length;d<m;d++){var r,o;h=i[d];let p=(r=h.querySelector("name"))==null?void 0:r.textContent,b=(o=h.querySelector("value"))==null?void 0:o.textContent;if(p&&b)e.setRequestHeader(p,b)}}let l=s.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw Error("Cannot find <Challenge> in key message");return r1(atob(c))}setupLicenseXHR(e,t,n,s,i){let r=this.config.licenseXhrSetup;if(!r)return e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i});return Promise.resolve().then(()=>(this.throwIfDestroyed(),r.call(this.hls,e,t,Ct(Ct({},n),{},{decryptdata:s}),i))).catch((o)=>{if(!n.mediaKeysSession)throw o;return e.open("POST",t,!0),r.call(this.hls,e,t,Ct(Ct({},n),{},{decryptdata:s}),i)}).then((o)=>{if(!e.readyState)e.open("POST",t,!0);return{xhr:e,licenseChallenge:o?o:i}})}requestLicense(e,t,n){return new Promise((s,i)=>{let r=f_(e.keySystem,this.config);if(!r)return i(Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return i(Error("License emitter removed"));this.log(`Sending license request to URL: ${r}`);let l=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;if(c.responseType="arraybuffer",c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error("invalid state"));if(c.readyState===4)if(c.status===200){o.requestErrors=[];let h=c.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);let d=this.config.licenseResponseCallback;if(d)try{h=d.call(this.hls,c,r,Ct(Ct({},e),{},{decryptdata:t}))}catch(m){this.error(m)}s(h)}else{let h=l.errorRetry,d=h?h.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>d||c.status>=400&&c.status<500)i(new Ir({type:Et.KEY_SYSTEM_ERROR,details:ve.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:c,response:{url:r,data:void 0,code:c.status,text:c.statusText}},`License Request XHR failed (${r}). Status: ${c.status} (${c.statusText})`));else{let m=d-o.requestErrors.length;this.warn(`Retrying license request, ${m} attempts left`),this.requestLicense(e,t,n).then(s,i)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE)o.licenseXhr.abort();o.licenseXhr=c,this.setupLicenseXHR(c,r,e,t,n).then(({xhr:h,licenseChallenge:d})=>{if(e.keySystem==gs.PLAYREADY)d=this.unpackPlayReadyKeyMessage(h,d);h.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,Un(n,"encrypted",this.onMediaEncrypted),Un(n,"waitingforkey",this.onWaitingForKey);let s=this.mediaResolved;if(s)s();else this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;if(e)Bn(e,"encrypted",this.onMediaEncrypted),Bn(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t)t();if(!this.mediaKeys&&!this.mediaKeySessions.length)return;let n=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ho.clearKeyUriToKeyIdMap();let i=s.length;Wc.CDMCleanupPromise=Promise.all(s.map((r)=>this.removeSession(r)).concat((n==null||(e=n.setMediaKeys(null))==null?void 0:e.catch((r)=>{if(this.log(`Could not clear media keys: ${r}`),!this.hls)return;this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${r}`)})}))||Promise.resolve())).catch((r)=>{if(this.log(`Could not close sessions and clear media keys: ${r}`),!this.hls)return;this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${r}`)})}).then(()=>{if(i)this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!t||!this.config.emeEnabled)return;if(!this.keyFormatPromise){let n=t.reduce((s,i)=>{if(s.indexOf(i.keyFormat)===-1)s.push(i.keyFormat);return s},[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach((o)=>{let l=e.keyRequests[o];if(l.onmessage)t.removeEventListener("message",l.onmessage);if(l.onkeystatuseschange)t.removeEventListener("keystatuseschange",l.onkeystatuseschange);l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;let n=this.mediaKeySessions.indexOf(e);if(n>-1)this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:s}=e;if(s)Object.keys(s).forEach((o)=>self.clearTimeout(s[o]));let{drmSystemOptions:i}=this.config;return(XE(i)?new Promise((o,l)=>{self.setTimeout(()=>l(Error("MediaKeySession.remove() timeout")),8000),t.remove().then(o).catch(l)}):Promise.resolve()).catch((o)=>{if(this.log(`Could not remove session: ${o}`),!this.hls)return;this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch((o)=>{if(this.log(`Could not close session: ${o}`),!this.hls)return;this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}Wc.CDMCleanupPromise=void 0;function f_(e,t){let{drmSystems:n,widevineLicenseUrl:s}=t,i=n==null?void 0:n[e];if(i)return i.licenseUrl;if(e===gs.WIDEVINE&&s)return s}function h_(e,t){let{drmSystems:n}=t,s=n==null?void 0:n[e];if(s)return s.serverCertificateUrl}function u_(e){if(e.keyFormat===ji.FAIRPLAY)return e.uri;if(e.keyId===null)throw Error("keyId is null");return Ys(e.keyId)}function Bg(e,t){let n=e.keyId,s=t.mediaKeysSession;if(n&&s){let i=t.mediaKeysSession.keyStatuses;if(i.size){if(i.has(n))return i.get(n);return t.keyStatuses[Ys(n)]}}return}function O3(e,t){let n=e==="output-restricted",s=n?ve.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ve.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ir({type:Et.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${e}"`)}class iv{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(O.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(O.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){if(this.timer)clearInterval(this.timer);this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let s=t.media instanceof self.HTMLVideoElement?t.media:null;if(this.media=s,s&&typeof s.getVideoPlaybackQuality==="function")this.isVideoPlaybackQualityAvailable=!0;self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let s=performance.now();if(t){if(this.lastTime){let i=s-this.lastTime,r=n-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1000*r/i,c=this.hls;if(c.trigger(O.FPS_DROP,{currentDropped:r,currentDecoded:o,totalDroppedFrames:n}),l>0){if(r>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;if(c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h))h=h-1,c.trigger(O.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch()}}}this.lastTime=s,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var J1=function(){if(t0!=null&&t0.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function n(l,c){if(typeof c!=="string")return!1;if(!Array.isArray(l))return!1;let h=c.toLowerCase();if(~l.indexOf(h))return h;return!1}function s(l){return n(e,l)}function i(l){return n(t,l)}function r(l,...c){let h=1;for(;h<arguments.length;h++){let d=arguments[h];for(let m in d)l[m]=d[m]}return l}function o(l,c,h){let d=this,m={enumerable:!0};d.hasBeenReset=!1;let p="",b=!1,v=l,k=c,A=h,T=null,E="",I=!0,_="auto",q="start",P=50,N="middle",H=50,V="middle";Object.defineProperty(d,"id",r({},m,{get:function(){return p},set:function(U){p=""+U}})),Object.defineProperty(d,"pauseOnExit",r({},m,{get:function(){return b},set:function(U){b=!!U}})),Object.defineProperty(d,"startTime",r({},m,{get:function(){return v},set:function(U){if(typeof U!=="number")throw TypeError("Start time must be set to a number.");v=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",r({},m,{get:function(){return k},set:function(U){if(typeof U!=="number")throw TypeError("End time must be set to a number.");k=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",r({},m,{get:function(){return A},set:function(U){A=""+U,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",r({},m,{get:function(){return T},set:function(U){T=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",r({},m,{get:function(){return E},set:function(U){let W=s(U);if(W===!1)throw SyntaxError("An invalid or illegal string was specified.");E=W,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",r({},m,{get:function(){return I},set:function(U){I=!!U,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",r({},m,{get:function(){return _},set:function(U){if(typeof U!=="number"&&U!=="auto")throw SyntaxError("An invalid number or illegal string was specified.");_=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",r({},m,{get:function(){return q},set:function(U){let W=i(U);if(!W)throw SyntaxError("An invalid or illegal string was specified.");q=W,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",r({},m,{get:function(){return P},set:function(U){if(U<0||U>100)throw Error("Position must be between 0 and 100.");P=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",r({},m,{get:function(){return N},set:function(U){let W=i(U);if(!W)throw SyntaxError("An invalid or illegal string was specified.");N=W,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",r({},m,{get:function(){return H},set:function(U){if(U<0||U>100)throw Error("Size must be between 0 and 100.");H=U,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",r({},m,{get:function(){return V},set:function(U){let W=i(U);if(!W)throw SyntaxError("An invalid or illegal string was specified.");V=W,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class rv{decode(e,t){if(!e)return"";if(typeof e!=="string")throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function av(e){function t(s,i,r,o){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(o||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);if(!n)return null;if(parseFloat(n[2])>59)return t(n[2],n[3],0,n[4]);return t(n[1],n[2],n[3],n[4])}class ov{constructor(){this.values=Object.create(null)}set(e,t){if(!this.get(e)&&t!=="")this.values[e]=t}get(e,t,n){if(n)return this.has(e)?this.values[e]:t[n];return this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let s=0;s<n.length;++s)if(t===n[s]){this.set(e,t);break}}integer(e,t){if(/^-?\d+$/.test(t))this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}}function lv(e,t,n,s){let i=s?e.split(s):[e];for(let r in i){if(typeof i[r]!=="string")continue;let o=i[r].split(n);if(o.length!==2)continue;let l=o[0],c=o[1];t(l,c)}}var p1=new J1(0,0,""),_d=p1.align==="middle"?"middle":"center";function d_(e,t,n){let s=e;function i(){let l=av(e);if(l===null)throw Error("Malformed timestamp: "+s);return e=e.replace(/^[^\sa-zA-Z-]+/,""),l}function r(l,c){let h=new ov;lv(l,function(p,b){let v;switch(p){case"region":for(let k=n.length-1;k>=0;k--)if(n[k].id===b){h.set(p,n[k].region);break}break;case"vertical":h.alt(p,b,["rl","lr"]);break;case"line":if(v=b.split(","),h.integer(p,v[0]),h.percent(p,v[0]))h.set("snapToLines",!1);if(h.alt(p,v[0],["auto"]),v.length===2)h.alt("lineAlign",v[1],["start",_d,"end"]);break;case"position":if(v=b.split(","),h.percent(p,v[0]),v.length===2)h.alt("positionAlign",v[1],["start",_d,"end","line-left","line-right","auto"]);break;case"size":h.percent(p,b);break;case"align":h.alt(p,b,["start",_d,"end","left","right"]);break}},/:/,/\s/),c.region=h.get("region",null),c.vertical=h.get("vertical","");let d=h.get("line","auto");if(d==="auto"&&p1.line===-1)d=-1;c.line=d,c.lineAlign=h.get("lineAlign","start"),c.snapToLines=h.get("snapToLines",!0),c.size=h.get("size",100),c.align=h.get("align",_d);let m=h.get("position","auto");if(m==="auto"&&p1.position===50)m=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50;c.position=m}function o(){e=e.replace(/^\s+/,"")}if(o(),t.startTime=i(),o(),e.slice(0,3)!=="-->")throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);e=e.slice(3),o(),t.endTime=i(),o(),r(e,t)}function cv(e){return e.replace(/<br(?: \/)?>/gi,`
42
- `)}class fv{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new rv,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;if(e)t.buffer+=t.decoder.decode(e,{stream:!0});function n(){let i=t.buffer,r=0;i=cv(i);while(r<i.length&&i[r]!=="\r"&&i[r]!==`
43
- `)++r;let o=i.slice(0,r);if(i[r]==="\r")++r;if(i[r]===`
44
- `)++r;return t.buffer=i.slice(r),o}function s(i){lv(i,function(r,o){},/:/)}try{let i="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;i=n();let o=i.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;while(t.buffer){if(!/\r\n|\n/.test(t.buffer))return this;if(!r)i=n();else r=!1;switch(t.state){case"HEADER":if(/:/.test(i))s(i);else if(!i)t.state="ID";continue;case"NOTE":if(!i)t.state="ID";continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new J1(0,0,""),t.state="CUE",i.indexOf("-->")===-1){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{d_(i,t.cue,t.regionList)}catch(o){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=i.indexOf("-->")!==-1;if(!i||o&&(r=!0)){if(t.oncue&&t.cue)t.oncue(t.cue);t.cue=null,t.state="ID";continue}if(t.cue===null)continue;if(t.cue.text)t.cue.text+=`
45
- `;t.cue.text+=i}continue;case"BADCUE":if(!i)t.state="ID"}}}catch(i){if(t.state==="CUETEXT"&&t.cue&&t.oncue)t.oncue(t.cue);t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if(e.cue||e.state==="HEADER")e.buffer+=`
46
-
47
- `,e.parse();if(e.state==="INITIAL"||e.state==="BADWEBVTT")throw Error("Malformed WebVTT signature.")}catch(t){if(e.onparsingerror)e.onparsingerror(t)}if(e.onflush)e.onflush();return this}}function ph(e){let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()}var m_=/\r\n|\n\r|\n|\r/g,P3="Missing initPTS for VTT ",p_=function(t){let n=parseInt(t.slice(-3)),s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!lt(n)||!lt(s)||!lt(i)||!lt(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1000*s,n+=60000*i,n+=3600000*r,n};function Z1(e,t,n){return ph(e.toString())+ph(t.toString())+ph(n)}function g_(e,t,n,s,i,r,o){let l=new fv,c=yr(new Uint8Array(e)).trim().replace(m_,`
48
- `).split(`
49
- `),h=[],d=t?GC(t.baseTime,t.timescale):0,m="00:00.000",p=0,b=0,v=!1,k,A=!0;l.oncue=function(T){let E=n[s],I=n.ccOffset,_=(p-d)/90000;if(v){if(E!=null&&E.new)I=n.ccOffset=E.start;if(_){if(!t){k=Error(P3+"MPEGTS");return}I=_-n.presentationOffset}}else if(!t){k=Error(P3+"without X-TIMESTAMP-MAP");return}else I=-t.baseTime/t.timescale;let q=T.endTime-T.startTime,P=wr((T.startTime+I-b)*90000,i*90000)/90000;T.startTime=Math.max(P,0),T.endTime=Math.max(P+q,0);let N=T.text.trim();if(T.text=decodeURIComponent(encodeURIComponent(N)),!T.id)T.id=Z1(T.startTime,T.endTime,N);else if(s)T.id=`hlsjscc${s}_${T.id}`;if(T.endTime>0)h.push(T)},l.onparsingerror=function(T){k=T},l.onflush=function(){if(k){o(k);return}r(h)},c.forEach((T)=>{if(A){if(T.startsWith("X-TIMESTAMP-MAP=")){A=!1,v=!0,T.slice(16).split(",").forEach((E)=>{if(E.startsWith("LOCAL:"))m=E.slice(6);else if(E.startsWith("MPEGTS:"))p=parseInt(E.slice(7))});try{b=p_(m)/1000}catch(E){k=E}return}else if(T==="")A=!1}l.parse(T+`
50
- `)}),l.flush()}var g1="stpp.ttml.im1t",hv=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,uv=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,b_={left:"start",center:"center",right:"end",start:"start",end:"end"};function N3(e,t,n,s){let i=Ut(new Uint8Array(e),["mdat"]);if(i.length===0){s(Error("Could not parse IMSC1 mdat"));return}let r=i.map((l)=>yr(l)),o=zC(t.baseTime,1,t.timescale);try{r.forEach((l)=>n(w_(l,o)))}catch(l){s(l)}}function w_(e,t){let i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},o=Object.keys(r).reduce((m,p)=>(m[p]=i.getAttribute(`ttp:${p}`)||r[p],m),{});if(!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate"))o.tickRate=Number(o.frameRate)*Number(o.subFrameRate);let l=i.getAttribute("xml:space")!=="preserve",c=B3(Hg(i,"styling","style")),h=B3(Hg(i,"layout","region")),d=Hg(i,"body","[begin]");return[].map.call(d,(m)=>{let p=dv(m,l);if(!p||!m.hasAttribute("begin"))return null;let b=zg(m.getAttribute("begin"),o),v=zg(m.getAttribute("dur"),o),k=zg(m.getAttribute("end"),o);if(b===null)throw H3(m);if(k===null){if(v===null)throw H3(m);k=b+v}let A=new J1(b-t,k-t,p);A.id=Z1(A.startTime,A.endTime,A.text);let T=h[m.getAttribute("region")],E=c[m.getAttribute("style")],I=y_(T,E,c),{textAlign:_}=I;if(_){let q=b_[_];if(q)A.lineAlign=q;A.align=_}return Gn(A,I),A}).filter((m)=>m!==null)}function Hg(e,t,n){let s=e.getElementsByTagName(t)[0];if(s)return[].slice.call(s.querySelectorAll(n));return[]}function B3(e){return e.reduce((t,n)=>{let s=n.getAttribute("xml:id");if(s)t[s]=n;return t},{})}function dv(e,t){return[].slice.call(e.childNodes).reduce((n,s,i)=>{var r;if(s.nodeName==="br"&&i)return n+`
51
- `;if((r=s.childNodes)!=null&&r.length)return dv(s,t);else if(t)return n+s.textContent.trim().replace(/\s+/g," ");return n+s.textContent},"")}function y_(e,t,n){let i=null,r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;if(o&&n.hasOwnProperty(o))i=n[o];return r.reduce((l,c)=>{let h=Ug(t,"http://www.w3.org/ns/ttml#styling",c)||Ug(e,"http://www.w3.org/ns/ttml#styling",c)||Ug(i,"http://www.w3.org/ns/ttml#styling",c);if(h)l[c]=h;return l},{})}function Ug(e,t,n){if(!e)return null;return e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function H3(e){return Error(`Could not parse ttml timestamp ${e}`)}function zg(e,t){if(!e)return null;let n=av(e);if(n===null){if(hv.test(e))n=v_(e,t);else if(uv.test(e))n=S_(e,t)}return n}function v_(e,t){let n=hv.exec(e),s=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+s/t.frameRate}function S_(e,t){let n=uv.exec(e),s=Number(n[1]);switch(n[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1000;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}function eb(e,t,n,s="",i="disabled"){let r=e.ownerDocument.createElement("track");if(r.kind=t,r.label=n,s)r.srclang=s;return r.src="data:,WEBVTT",r.track.mode=i,e.appendChild(r),r}function k_(e){if(e.forced&&cE())return"forced";else if(e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics))return"captions";return"subtitles"}function b1(e,t){let n=e.mode;if(n==="disabled")e.mode="hidden";if(e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(s){Rn.debug(`[texttrack-utils]: ${s}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(i){Rn.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}if(n==="disabled")e.mode=n}function w1(e,t,n,s){let i=e.mode;if(i==="disabled")e.mode="hidden";if(e.cues&&e.cues.length>0){let r=A_(e.cues,t,n);for(let o=0;o<r.length;o++)if(!s||s(r[o]))e.removeCue(r[o])}if(i==="disabled")e.mode=i}function x_(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let s=0,i=n,r;while(s<=i)if(r=Math.floor((i+s)/2),t<e[r].startTime)i=r-1;else if(t>e[r].startTime&&s<n)s=r+1;else return r;return e[s].startTime-t<t-e[i].startTime?s:i}function A_(e,t,n){let s=[],i=x_(e,t);if(i>-1)for(let r=i,o=e.length;r<o;r++){let l=e[r];if(l.startTime>=t&&l.endTime<=n)s.push(l);else if(l.startTime>n)return s}return s}class mv extends w0{constructor(e){super(e,"subtitle-track-controller");this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(!this.useTextTrackPolling)self.clearInterval(this.subtitlePollingInterval);if(!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,n=!1;if(this.currentTrack){var s;let o=(s=this.currentTrack.trackNode)==null?void 0:s.track.mode;if(o==="showing")t=this.trackId,n=!0;else if(o==="hidden")t=this.trackId}if(!n)for(let o=0;o<this.tracksInGroup.length;o++){var i;let l=(i=this.tracksInGroup[o].trackNode)==null?void 0:i.track.mode;if(l==="showing"){t=o;break}else if(t<0&&l==="hidden")t=o}if(t>-1){var r;this._subtitleDisplay=((r=this.tracksInGroup[t].trackNode)==null?void 0:r.track.mode)==="showing"}this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){if(this._subtitleDisplay=e,this.trackId>-1)this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.LEVEL_LOADING,this.onLevelLoading,this),e.on(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(O.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(O.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.LEVEL_LOADING,this.onLevelLoading,this),e.off(O.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(O.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(O.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach((n)=>{if(!n.trackNode)n.trackNode=eb(this.media,k_(n),n.name,n.lang)});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;if((t==null?void 0:t.mode)==="disabled")t.mode=this._subtitleDisplay?"showing":"hidden"}onMediaAttached(e,t){let n=t.media;this.media=n;let s=this.trackId;if(this.queuedDefaultTrack>-1)s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1;if(this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(n.textTracks&&("onchange"in n.textTracks)),this.useTextTrackPolling)this.pollTrackChange(500);else n.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let s=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),!this.useTextTrackPolling)n.textTracks.removeEventListener("change",this.asyncPollTrackChange);if(this.trackId>-1)this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1);if(this.media=null,s)return;if(this.hls.config.renderTextTracksNatively)this.tracksInGroup.forEach((i)=>{let r=i.trackNode;if(r)r.track.mode="hidden",r.remove(),i.trackNode=void 0})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:n,groupId:s,details:i}=t,r=this.tracksInGroup[n];if(!r||r.groupId!==s){this.warn(`Subtitle track with id:${n} and group:${s} not found in active group ${r==null?void 0:r.groupId}`);return}let o=r.details;if(r.details=t.details,this.log(`Subtitle track ${n} "${r.name}" lang:${r.lang} group:${s} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId)this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.subtitleGroups||null,s=this.groupIds,i=this.currentTrack;if(!n||(s==null?void 0:s.length)!==(n==null?void 0:n.length)||n!=null&&n.some((r)=>(s==null?void 0:s.indexOf(r))===-1)){this.groupIds=n;let r=[];if(this.tracks.forEach((h)=>{if(h.textCodec===g1?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT){if(!n||n.indexOf(h.groupId)>-1)h.id=r.length,r.push(h);else if(h.trackNode)h.trackNode.remove(),h.trackNode=void 0}}),r.length===this.tracksInGroup.length){let h=!1;for(let d=0;d<r.length;d++)if(r[d]!==this.tracksInGroup[d]){h=!0;break}if(!h)return}if(r.length){if(this.selectDefaultTrack&&!r.some((h)=>h.default))this.selectDefaultTrack=!1}this.tracksInGroup=r,this.trackId=-1,this.currentTrack=null;let o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;let h=ja(o,r);if(h>-1)i=r[h];else{let d=ja(o,this.tracks);i=this.tracks[d]}}let l=this.findTrackId(i);if(l===-1&&i)l=this.findTrackId(null);let c={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(O.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let s=0;s<t.length;s++){let i=t[s];if(n&&!i.default||!n&&!e)continue;if(!e||Nl(i,e))return s}if(e){for(let s=0;s<t.length;s++){let i=t[s];if(Eh(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){let i=t[s];if(Eh(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){if(t.fatal||!t.context)return;if(t.context.type===fn.SUBTITLE_TRACK&&t.context.id===this.trackId&&kh(t.context.groupId,this.groupIds))this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let n=this.currentTrack;if(n&&Nl(e,n))return n;let s=ja(e,this.tracksInGroup);if(s>-1){let i=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),i}else if(n)return null;else{let i=ja(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){if(super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack))this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let{id:n,groupId:s}=e,i=this.getUrlWithDirectives(e.url,t),r=e.details,o=r==null?void 0:r.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||"":""):""} ${i}`),this.hls.trigger(O.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:s,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach((t)=>{if(t.trackNode){let n=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",s=t.trackNode.track;if(s.mode!==n)s.mode=n}})}setSubtitleTrack(e,t=!1){let n=this.tracksInGroup;if(!this.media)this.queuedDefaultTrack=e;if(e<-1||e>=n.length||!lt(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let s=this.currentTrack,i=n[e]||null;if(this.trackId=e,this.currentTrack=i,t)this.toggleTrackModes();if(!i){if(s)this.hls.trigger(O.SUBTITLE_TRACK_SWITCH,{id:e});return}let r=!!i.details&&!i.details.live;if(i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));let{id:o,groupId:l="",name:c,type:h,url:d}=i;this.hls.trigger(O.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:c,type:h,url:d});let m=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(m)}}var Bd=2,T_=100;class pv extends D1{constructor(e,t){super("gap-controller",e.logger);this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;if((n=this.media)!=null&&n.seeking)return;this.waiting=self.performance.now(),this.tick()},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(O.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;if(e)e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.BUFFER_APPENDED,this.onBufferAppended,this)}unregisterListeners(){let{hls:e}=this;if(e)e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.BUFFER_APPENDED,this.onBufferAppended,this)}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(T_),this.mediaSource=t.mediaSource;let n=this.media=t.media;Un(n,"playing",this.onMediaPlaying),Un(n,"waiting",this.onMediaWaiting),Un(n,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;if(n)Bn(n,"playing",this.onMediaPlaying),Bn(n,"waiting",this.onMediaWaiting),Bn(n,"ended",this.onMediaEnded),this.media=null;this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;if(this.media)return Math.max(this.media.currentTime,t);return t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();if(this.media.currentTime<t)return;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var n,s;let i=(n=this.hls)==null?void 0:n.config;if(!i)return;let r=this.media;if(!r)return;let{seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o,h=r.paused&&!o||r.ended||r.playbackRate===0;if(this.seeking=o,e!==t){if(t)this.ended=0;if(this.moved=!0,!o){if(this.skipRetry=this.nudgeRetry=0,i.nudgeOnVideoHole&&!h&&e>t)this.nudgeOnVideoHole(e,t)}if(this.waiting===0)this.stallResolved(e);return}if(c||l){if(l)this.stallResolved(e);return}if(h){if(this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls)this.ended=e||1,this.hls.trigger(O.MEDIA_ENDED,{stalled:!1});return}if(!qt.getBuffered(r).length){this.skipRetry=this.nudgeRetry=0;return}let d=qt.bufferInfo(r,e,0),m=this.fragmentTracker;if(m&&this.hls)G3(d,e,m,this.hls);let p=d.nextStart||0;if(o&&m&&this.hls){let q=U3(this.hls.inFlightFragments,e),P=d.len>Bd,N=!p||q||p-e>Bd&&!m.getPartialFragment(e);if(P||N)return;this.moved=!1}let b=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&m){if(!(d.len>0)&&!p)return;let P=Math.max(p,d.start||0)-e,H=b!=null&&b.live?b.targetduration*2:Bd,V=rh(e,m);if(P>0&&(P<=H||V)){if(!r.paused)this._trySkipBufferHole(V);return}}let v=i.detectStallWithCurrentTimeMs,k=self.performance.now(),A=this.waiting,T=this.stalled;if(T===null)if(A>0&&k-A<v)T=this.stalled=A;else{this.stalled=k;return}let E=k-T;if(!o&&(E>=v||A&&this.moved)&&this.hls){var I;if(((I=this.mediaSource)==null?void 0:I.readyState)==="ended"&&!(b!=null&&b.live)&&Math.abs(e-((b==null?void 0:b.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(O.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return;if(r.currentTime!==e){let q=e;e=r.currentTime,this.moved=!0,this.log(`currentTime changed ${q} > ${e}`);return}}let _=qt.bufferInfo(r,e,i.maxBufferHole);this._tryFixBufferStall(_,E,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls){if(this.stalled=null,this.stallReported){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(O.STALL_RESOLVED,{})}}}nudgeOnVideoHole(e,t){var n;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&s&&s.length>1&&e>s.end(0)){let i=qt.bufferedInfo(qt.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){let r=qt.timeRangesToArray(s),o=qt.bufferedInfo(r,t,0).bufferedIndex;if(o>-1&&o<r.length-1){let l=qt.bufferedInfo(r,e,0).bufferedIndex,c=r[o].end,h=r[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){let d=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=0.000001;let m=rh(e,this.fragmentTracker);if(m&&"fragment"in m)m=m.fragment;else if(!m)m=void 0;let p=qt.bufferInfo(this.media,e,0);this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:m,buffer:p.len,bufferInfo:p})}}}}}_tryFixBufferStall(e,t,n){var s,i;let{fragmentTracker:r,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!r||!l)return;let c=(i=this.hls)==null?void 0:i.latestLevelDetails,h=rh(n,r);if(h||c!=null&&c.live&&n<c.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}let d=e.buffered,m=this.adjacentTraversal(e,n);if((d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-n<l.maxBufferHole||m))&&(t>l.highBufferWatchdogPeriod*1000||this.waiting))this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e)}adjacentTraversal(e,t){let n=this.fragmentTracker,s=e.nextStart;if(n&&s){let i=n.getFragAtPos(t,kt.MAIN),r=n.getFragAtPos(s,kt.MAIN);if(i&&r)return r.sn-i.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:s,stalled:i}=this;if(!s&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${ls(e)})`);this.warn(r.message),t.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n,hls:s}=this,i=s==null?void 0:s.config;if(!n||!t||!i)return 0;let r=n.currentTime,o=qt.bufferInfo(n,r,0);G3(o,r,t,s);let l=r<o.start?o.start:o.nextStart;if(l){let h=o.len<=i.maxBufferHole,d=o.len>0&&o.len<1&&n.readyState<3,m=l-r;if(m>0&&(h||d)){if(m>i.maxBufferHole){let A=!1;if(r===0){let T=t.getAppendedFrag(0,kt.MAIN);if(T&&l<T.end)A=!0}if(!A&&e){var c;if(!((c=s.loadLevelObj)!=null&&c.details))return 0;if(U3(s.inFlightFragments,l))return 0;let E=!1,I=e.end;while(I<l){let _=rh(I,t),q=_?_.duration:0;if(q>0)I+=q;else{E=!0;break}}if(E)return 0}}let{nudgeMaxRetry:p,skipBufferHolePadding:b}=i,v=++this.skipRetry>p,k=Math.max(l,r)+b;if(!v)this.warn(`skipping hole, adjusting currentTime from ${r} to ${k}`),this.moved=!0,n.currentTime=k;if(!(e!=null&&e.gap)||v){let A=Error(v?`Playhead still not moving after seeking over buffer hole from ${r} to ${k} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${r} to ${k}`),T={type:Et.MEDIA_ERROR,details:ve.BUFFER_SEEK_OVER_HOLE,fatal:v,error:A,reason:A.message,buffer:o.len,bufferInfo:o};if(e)if("fragment"in e)T.part=e;else T.frag=e;s.trigger(O.ERROR,T)}return k}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:s}=this,i=t==null?void 0:t.config;if(!n||!i)return 0;let r=n.currentTime;if(this.nudgeRetry++,s<i.nudgeMaxRetry){let o=r+(s+1)*i.nudgeOffset,l=Error(`Nudging 'currentTime' from ${r} to ${o}`);this.warn(l.message),n.currentTime=o,t.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=Error(`Playhead still not moving while enough data buffered @${r} after ${i.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function U3(e,t){let n=z3(e.main);if(n&&n.start<=t)return n;let s=z3(e.audio);if(s&&s.start<=t)return s;return null}function z3(e){if(!e)return null;switch(e.state){case Me.IDLE:case Me.STOPPED:case Me.ENDED:case Me.ERROR:return null}return e.frag}function rh(e,t){return t.getAppendedFrag(e,kt.MAIN)||t.getPartialFragment(e)}function G3(e,t,n,s){let i=s.latestLevelDetails,r=rh(t,n);if(i0(s.config)&&!e.nextStart&&i&&r&&s.interstitialsManager){let o="type"in r?r:r.fragment,l=F9(i,o.sn);if((l==null?void 0:l.level)===o.level&&n6(l,s.interstitialsManager.playerQueue,t))e.nextStart=l.start}}var E_=0.25;function y1(){if(typeof self>"u")return;return self.VTTCue||self.TextTrackCue}function Gg(e,t,n,s,i){let r=new e(t,n,"");try{if(r.value=s,i)r.type=i}catch(o){r=new e(t,n,ls(i?Ct({type:i},s):s))}return r}var Id=(()=>{let e=y1();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class gv{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{if(!this.hls)return;this.hls.trigger(O.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;if(e)e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(O.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){let{hls:e}=this;if(e)e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(O.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(O.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;if(t)this.updateDateRangeCues(t)}onMediaDetaching(e,t){if(this.media=null,!!t.transferMedia)return;if(this.id3Track)this.id3Track.remove(),this.id3Track=null;this.dateRangeCuesAppended={}}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return eb(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:s}=this.hls.config;if(!n&&!s)return;let{samples:i}=t;if(!this.id3Track)this.id3Track=this.createTrack(this.media);let r=y1();if(!r)return;for(let o=0;o<i.length;o++){let l=i[o].type;if(l===zi.emsg&&!n||!s)continue;let c=c9(i[o].data),h=i[o].pts,d=h+i[o].duration;if(d>Id)d=Id;if(d-h<=0)d=h+E_;for(let p=0;p<c.length;p++){let b=c[p];if(!f9(b)){this.updateId3CueEnds(h,l);let v=Gg(r,h,d,b,l);if(v)this.id3Track.track.addCue(v)}}}}updateId3CueEnds(e,t){var n;let s=(n=this.id3Track)==null?void 0:n.track.cues;if(s)for(let i=s.length;i--;){let r=s[i];if(r.type===t&&r.startTime<e&&r.endTime===Id)r.endTime=e}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:s}){let{id3Track:i,hls:r}=this;if(!r)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=r;if(i&&(o||l)){let c;if(s==="audio")c=(h)=>h.type===zi.audioId3&&l;else if(s==="video")c=(h)=>h.type===zi.emsg&&o;else c=(h)=>h.type===zi.audioId3&&l||h.type===zi.emsg&&o;w1(i.track,t,n,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){if(Math.abs(t.drift)>0.01)this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:n,timelineOffset:s,enableDateRangeMetadataCues:i,interstitialsController:r}=this.hls.config;if(!i)return;let o=y1();if(n&&s&&!r){let{fragmentStart:v,fragmentEnd:k}=e,A=this.assetCue;if(A)A.startTime=v,A.endTime=k;else if(o){if(A=this.assetCue=Gg(o,v,k,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),A)A.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(A),A.addEventListener("enter",this.onEventCueEnter)}}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c),d=this.dateRangeCuesAppended;if(l&&t){var m;if((m=l.track.cues)!=null&&m.length){let v=Object.keys(d).filter((k)=>h.indexOf(k)===-1);for(let k=v.length;k--;){var p;let A=v[k],T=(p=d[A])==null?void 0:p.cues;if(delete d[A],T)Object.keys(T).forEach((E)=>{let I=T[E];if(I){I.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(I)}catch(_){}}})}}else d=this.dateRangeCuesAppended={}}let b=e.fragments[e.fragments.length-1];if(h.length===0||!lt(b==null?void 0:b.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));for(let v=0;v<h.length;v++){let k=h[v],A=c[k],T=A.startTime,E=d[k],I=(E==null?void 0:E.cues)||{},_=(E==null?void 0:E.durationKnown)||!1,q=Id,{duration:P,endDate:N}=A;if(N&&P!==null)q=T+P,_=!0;else if(A.endOnNext&&!_){let V=h.reduce((U,W)=>{if(W!==A.id){let ce=c[W];if(ce.class===A.class&&ce.startDate>A.startDate&&(!U||A.startDate<U.startDate))return ce}return U},null);if(V)q=V.startTime,_=!0}let H=Object.keys(A.attr);for(let V=0;V<H.length;V++){let U=H[V];if(!UE(U))continue;let W=I[U];if(W){if(_&&!(E!=null&&E.durationKnown))W.endTime=q;else if(Math.abs(W.startTime-T)>0.01)W.startTime=T,W.endTime=q}else if(o){let ce=A.attr[U];if(zE(U))ce=h9(ce);let oe=Gg(o,T,q,{key:U,data:ce},zi.dateRange);if(oe){if(oe.id=k,this.id3Track.track.addCue(oe),I[U]=oe,r){if(U==="X-ASSET-LIST"||U==="X-ASSET-URL")oe.addEventListener("enter",this.onEventCueEnter)}}}}d[k]={cues:I,dateRange:A,durationKnown:_}}}}function bv(){return self.SourceBuffer||self.WebKitSourceBuffer}function wv(){if(!Zo())return!1;let t=bv();return!t||t.prototype&&typeof t.prototype.appendBuffer==="function"&&typeof t.prototype.remove==="function"}function C_(){if(!wv())return!1;let e=Zo();return typeof(e==null?void 0:e.isTypeSupported)==="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t)=>e.isTypeSupported(Sh(t,"video")))||["mp4a.40.2","fLaC"].some((t)=>e.isTypeSupported(Sh(t,"audio"))))}function j_(){var e;let t=bv();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==="function"}var ka={DISABLED:0,SWITCHING:1,SWITCHED:2},__=100;class tb extends g0{constructor(e,t,n){super(e,t,n,"stream-controller",kt.MAIN);this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=ka.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,i=s?s.currentTime:null;if(i===null||!lt(i))return;if(this.log(`Media seeked to ${i}`),!this.getBufferedFrag(i))return;let r=this.getFwdBufferInfoAtPos(s,i,kt.MAIN,0);if(!r||r.len===0){this.log(`Main buffer empty at ${i} on "seeked" event: ${r?r.len:r}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(O.MANIFEST_PARSED,this.onManifestParsed,this),e.on(O.LEVEL_LOADING,this.onLevelLoading,this),e.on(O.LEVEL_LOADED,this.onLevelLoaded,this),e.on(O.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(O.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(O.BUFFER_CREATED,this.onBufferCreated,this),e.on(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(O.MANIFEST_PARSED,this.onManifestParsed,this),e.off(O.LEVEL_LOADED,this.onLevelLoaded,this),e.off(O.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(O.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(O.BUFFER_CREATED,this.onBufferCreated,this),e.off(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:s}=this;if(this.stopLoad(),this.setInterval(__),this.level=-1,!this.startFragRequested){let i=s.startLevel;if(i===-1)if(s.config.testBandwidth&&this.levels.length>1)i=0,this.bitrateTest=!0;else i=s.firstAutoLevel;s.nextLoadLevel=i,this.level=s.loadLevel,this._hasEnoughToStart=!!t}if(n>0&&e===-1&&!t&&this.initPTS.length)this.log(`Override startPosition with lastCurrentTime @${n}`),e=n;if(this.state=Me.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType))this._hasEnoughToStart=this.startFragRequested=!1;this.tick()}else this._forceStartLoad=!0,this.state=Me.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Me.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e==null?void 0:e[t],s=n==null?void 0:n.details;if(s&&(!s.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(s))break;this.state=Me.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Me.IDLE;break}break}case Me.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}if(this.state===Me.IDLE)this.doTickIdle();this.onTickEnd()}onTickEnd(){var e;if(super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1)this.lastCurrentTime=this.media.currentTime;this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let r=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let v={type:this.targetBufferType()};this.hls.trigger(O.BUFFER_EOS,v),this.state=Me.ENDED;return}if(!this.buffering)return;if(e.loadLevel!==i&&e.manualLevel===-1)this.log(`Adapting to level ${i} from level ${this.level}`);this.level=e.nextLoadLevel=i;let c=r.details;if(!c||this.state===Me.WAITING_LEVEL||this.waitForLive(r)){this.level=i,this.state=Me.WAITING_LEVEL,this.startFragRequested=!1;return}let h=o.len,d=this.getMaxBufferLength(r.maxBitrate);if(h>=d)return;if(this.backtrackFragment&&this.backtrackFragment.start>o.end)this.backtrackFragment=void 0;let m=this.backtrackFragment?this.backtrackFragment.start:o.end,p=this.getNextFragment(m,c);if(this.couldBacktrack&&!this.fragPrevious&&p&&js(p)&&this.fragmentTracker.getState(p)!==Ss.OK){var b;let k=((b=this.backtrackFragment)!=null?b:p).sn-c.startSN,A=c.fragments[k-1];if(A&&p.cc===A.cc)p=A,this.fragmentTracker.removeFragment(A)}else if(this.backtrackFragment&&o.len)this.backtrackFragment=void 0;if(p&&this.isLoopLoading(p,m)){if(!p.gap){let k=this.audioOnly&&!this.altAudio?Zn.AUDIO:Zn.VIDEO,A=(k===Zn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(A)this.afterBufferFlushed(A,k)}p=this.getNextFragmentLoopLoading(p,c,o,kt.MAIN,d)}if(!p)return;if(this.exceedsMaxBuffer(o,d,p))return;this.loadFragment(p,r,m)}loadFragment(e,t,n){let s=this.fragmentTracker.getState(e);if(s===Ss.NOT_LOADED||s===Ss.PARTIAL)if(this.bitrateTest)this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t);else super.loadFragment(e,t,n);else this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==ka.DISABLED){var e;if((((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime)super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){if(this.mediaBuffer&&this.altAudio===ka.SWITCHED)return this.mediaBuffer;return this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let n=this.fragPlaying;if(n){let s=n.level;if(this.hls.trigger(O.FRAG_CHANGED,{frag:n,previousFrag:e}),(e==null?void 0:e.level)!==s)this.hls.trigger(O.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===ka.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;Un(n,"playing",this.onMediaPlaying),Un(n,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;if(n)Bn(n,"playing",this.onMediaPlaying),Bn(n,"seeked",this.onMediaSeeked);if(this.videoBuffer=null,super.onMediaDetaching(e,t),!!t.transferMedia)return;this._hasEnoughToStart=!1}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(O.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=ka.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,s=!1;for(let i=0;i<t.levels.length;i++){let r=t.levels[i].audioCodec;if(r)n=n||r.indexOf("mp4a.40.2")!==-1,s=s||r.indexOf("mp4a.40.5")!==-1}if(this.audioCodecSwitch=n&&s&&!j_(),this.audioCodecSwitch)this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:n}=this;if(!n||this.state!==Me.IDLE)return;let s=t.levelInfo;if(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))this.state=Me.WAITING_LEVEL}onLevelLoaded(e,t){var n;let{levels:s,startFragRequested:i}=this,{level:r,details:o}=t,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let c=t.levelInfo,h=this.fragCurrent;if(h&&(this.state===Me.FRAG_LOADING||this.state===Me.FRAG_LOADING_WAITING_RETRY)){if(h.level!==t.level&&h.loader)this.abortCurrentFrag()}let d=0;if(o.live||(n=c.details)!=null&&n.live){var m;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,c.details,(m=this.levelLastLoaded)==null?void 0:m.details)}if(c.details=o,this.levelLastLoaded=c,!i)this.setStartPosition(o,d);if(this.hls.trigger(O.LEVEL_UPDATED,{details:o,level:r}),this.state===Me.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Me.IDLE}if(i&&o.live)this.synchronizeToLiveEdge(o);this.initPTS.some((p,b)=>{if(b>=o.startCC)return!0;delete this.initPTS[b]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let s=this.hls.liveSyncPosition,i=this.playhead,{fragmentStart:r,edge:o}=e,l=i>=r-t.maxFragLookUpTolerance&&i<=o;if(s!==null&&n.duration>s&&(i<s||!l)){let h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if(!l&&n.readyState<4||i<o-h){if(!this._hasEnoughToStart)this.nextLoadPosition=s;if(n.readyState)if(this.warn(`Playback: ${i} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var c;let d=qt.bufferInfo(n,s,0);if(!((c=d.buffered)!=null&&c.length)){n.currentTime=s;return}if(d.start<=i){n.currentTime=s;return}let{nextStart:p}=qt.bufferedInfo(d.buffered,i,0);if(p)n.currentTime=p}else n.currentTime=s}}}_handleFragmentLoadProgress(e){var t;let n=e.frag,{part:s,payload:i}=e,{levels:r}=this;if(!r){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}let o=r[n.level];if(!o){this.warn(`Level ${n.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}let c=o.videoCodec,h=l.PTSKnown||!l.live,d=(t=n.initSegment)==null?void 0:t.data,m=this._getAudioCodec(o),p=this.transmuxer=this.transmuxer||new G1(this.hls,kt.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),b=s?s.index:-1,v=b!==-1,{decryptRange:k,byteRange:A}=Zd(n,s,this.iframesOnly),T=new m0(n.level,n.sn,n.stats.chunkCount,A?A.end-A.start:i.byteLength,b,v,n.duration,this.iframesOnly,k),E=this.initPTS[n.cc];p.push(i,d,m,c,n,s,l.totalduration,h,T,E)}onAudioTrackSwitching(e,t){let n=this.hls,s=this.altAudio!==ka.DISABLED;if(!Jd(t.url,n)){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let r=this.fragCurrent;if(r)this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r);this.resetTransmuxer(),this.resetLoadingState()}else if(this.audioOnly)this.resetTransmuxer();if(s){this.altAudio=ka.DISABLED,this.fragmentTracker.removeAllFragments(),n.once(O.BUFFER_FLUSHED,()=>{if(!this.hls)return;this.hls.trigger(O.AUDIO_TRACK_SWITCHED,t)}),n.trigger(O.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(O.AUDIO_TRACK_SWITCHED,t)}else this.altAudio=ka.SWITCHING}onAudioTrackSwitched(e,t){let n=Jd(t.url,this.hls);if(n){let s=this.videoBuffer;if(s&&this.mediaBuffer!==s)this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s}this.altAudio=n?ka.SWITCHED:ka.DISABLED,this.tick()}onBufferCreated(e,t){let n=t.tracks,s,i,r=!1;for(let o in n){let l=n[o];if(l.id==="main"){if(i=o,s=l,o==="video"){let c=n[o];if(c)this.videoBuffer=c.buffer}}else r=!0}if(r&&s)this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer;else this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:s}=t,i=n.type===kt.MAIN;if(i){if(this.fragContextChanged(n)){if(this.warn(`Fragment ${n.sn}${s?" p: "+s.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Me.PARSED)this.state=Me.IDLE;return}let l=!1;if(js(n))l=!!n.gap&&!n.tagList.some((c)=>c[0]==="GAP");if(this.fragBufferedComplete(n,s),l){var r;n.stats.retry++;let c=(r=this.levels)==null?void 0:r[n.level];if(c)c.fragmentError++}}let o=this.media;if(!o)return;if(!this._hasEnoughToStart&&qt.getBuffered(o).length)this._hasEnoughToStart=!0,this.seekToStartPos();if(i)this.tick()}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var n;if(t.fatal){this.state=Me.ERROR;return}switch(t.details){case ve.FRAG_GAP:case ve.FRAG_PARSING_ERROR:case ve.FRAG_DECRYPT_ERROR:case ve.FRAG_LOAD_ERROR:case ve.FRAG_LOAD_TIMEOUT:case ve.KEY_LOAD_ERROR:case ve.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(kt.MAIN,t);break;case ve.LEVEL_LOAD_ERROR:case ve.LEVEL_LOAD_TIMEOUT:case ve.LEVEL_PARSING_ERROR:if(!t.levelRetry&&this.state===Me.WAITING_LEVEL&&((n=t.context)==null?void 0:n.type)===fn.LEVEL)this.state=Me.IDLE;break;case ve.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;if(t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry)this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag);break;case ve.BUFFER_ADD_CODEC_ERROR:case ve.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(t))this.resetLoadingState();break;case ve.BUFFER_FULL_ERROR:if(t.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(t))if(!this.config.interstitialsController&&this.config.assetPlayerId)this._hasEnoughToStart=!0;else this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ve.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){if(this.state=Me.IDLE,!this._hasEnoughToStart)this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime;this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Zn.AUDIO||!this.altAudio){let n=(t===Zn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(n)this.afterBufferFlushed(n,t),this.tick()}}onLevelsUpdated(e,t){if(this.level>-1&&this.fragCurrent){if(this.level=this.fragCurrent.level,this.level===-1)this.resetWhenMissingContext(this.fragCurrent)}this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let s=this.timelineOffset;if(s&&n)n+=s;let i=this.getLevelDetails(),r=qt.getBuffered(e),o=r.length?r.start(0):0,l=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);if(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((i==null?void 0:i.partTarget)||0)))this.log(`adjusting start position by ${l} to match buffer start`),n+=l,this.startPosition=n;if(t<n)this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;if(this.audioCodecSwap&&t)if(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1)t="mp4a.40.2";else t="mp4a.40.5";return t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((n)=>{let{hls:s}=this,i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=Me.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let r=i.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),s.trigger(O.FRAG_LOADED,n),i.bitrateTest=!1}).catch((n)=>{if(this.state===Me.STOPPED||this.state===Me.ERROR)return;this.warn(n),this.resetFragmentLoading(e)})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,r=this.getCurrentContext(i);if(!r){this.resetWhenMissingContext(i);return}let{frag:o,part:l,level:c}=r,{video:h,text:d,id3:m,initSegment:p}=s,{details:b}=c,v=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Me.PARSING,p){let k=p.tracks;if(k){let I=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(c,k,I,i),n.trigger(O.FRAG_PARSING_INIT_SEGMENT,{frag:I,id:t,tracks:k})}let{initPTS:A,timescale:T}=p,E=this.initPTS[o.cc];if(lt(A)&&(!E||E.baseTime!==A||E.timescale!==T)){let I=p.trackId;this.initPTS[o.cc]={baseTime:A,timescale:T,trackId:I};let _=this.initPTS.slice(0);n.trigger(O.INIT_PTS_FOUND,{timestampOffsets:_,frag:o,id:t,initPTS:A,timescale:T,trackId:I})}}if(h&&b){if(v&&h.type==="audiovideo")this.logMuxedErr(o);let k=b.fragments[o.sn-1-b.startSN],A=o.sn===b.startSN,T=!k||o.cc>k.cc;if(s.independent!==!1){let{startPTS:E,endPTS:I,startDTS:_,endDTS:q}=h;if(l)l.elementaryStreams[h.type]={startPTS:E,endPTS:I,startDTS:_,endDTS:q};else{if(h.firstKeyFrame&&h.independent&&i.id===1&&!T)this.couldBacktrack=!0;if(h.dropped&&h.independent){let P=this.getMainFwdBufferInfo(),N=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,H=h.firstKeyFramePTS?h.firstKeyFramePTS:E;if(!A&&N<H-this.config.maxBufferHole&&!T){this.backtrack(o);return}else if(T)o.gap=!0;o.setElementaryStreamInfo(h.type,o.start,I,o.start,q,!0)}else if(A&&E-(b.appliedTimelineOffset||0)>Bd)o.gap=!0}if(o.setElementaryStreamInfo(h.type,E,I,_,q),this.backtrackFragment)this.backtrackFragment=o;this.bufferFragmentData(h,o,l,i,A||T)}else if(A||T)o.gap=!0;else{this.backtrack(o);return}}if(v){let{startPTS:k,endPTS:A,startDTS:T,endDTS:E}=v;if(l)l.elementaryStreams[Zn.AUDIO]={startPTS:k,endPTS:A,startDTS:T,endDTS:E};o.setElementaryStreamInfo(Zn.AUDIO,k,A,T,E),this.bufferFragmentData(v,o,l,i)}if(b&&m!=null&&m.samples.length){let k={id:t,frag:o,details:b,samples:m.samples};n.trigger(O.FRAG_PARSING_METADATA,k)}if(b&&d){let k={id:t,frag:o,details:b,samples:d.samples};n.trigger(O.FRAG_PARSING_USERDATA,k)}}logMuxedErr(e){this.warn(`${js(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,s){if(this.state!==Me.PARSING)return;if(this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly){if(delete t.audio,t.audiovideo)this.logMuxedErr(n)}let{audio:i,video:r,audiovideo:o}=t;if(i){let c=e.audioCodec,h=Fd(i.codec,c);if(h==="mp4a")h="mp4a.40.5";if(this.audioCodecSwitch){if(h)if(h.indexOf("mp4a.40.5")!==-1)h="mp4a.40.2";else h="mp4a.40.5";let d=i.metadata;if(d&&"channelCount"in d&&(d.channelCount||1)!==1&&!lE())h="mp4a.40.5"}if(h&&h.indexOf("mp4a.40.5")!==-1&&fE()&&i.container!=="audio/mpeg")h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`);if(c&&c!==h)this.log(`Swapping manifest audio codec "${c}" for "${h}"`);i.levelCodec=h,i.id=kt.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${i.codec}]`),delete t.audiovideo}if(r){r.levelCodec=e.videoCodec,r.id=kt.MAIN;let c=r.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${r.codec!==c?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.supplemental:""}`),delete t.audiovideo}if(o){if(this.iframesOnly)this.logMuxedErr(n);this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio}let l=Object.keys(t);if(l.length){if(this.hls.trigger(O.BUFFER_CODECS,t),!this.hls)return;l.forEach((c)=>{let d=t[c].initSegment;if(d!=null&&d.byteLength)this.hls.trigger(O.BUFFER_APPENDING,{type:c,data:d,frag:n,part:null,chunkMeta:s,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,kt.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e==null?void 0:e[t];if(!n)return this.config.maxBufferLength;return this.getMaxBufferLength(n.maxBitrate)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Me.IDLE}get nextLevel(){let e=this.nextBufferedFrag;if(e)return e.level;return-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(lt(t))return this.getAppendedFrag(t);return null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(lt(t)){let n=this.getLevelDetails(),s=this.currentFrag||(n?Qc(null,n.fragments,t):null);if(s){let i=s.programDateTime;if(i!==null){let r=i+(t-s.start)*1000;return new Date(r)}}}return null}get currentLevel(){let e=this.currentFrag;if(e)return e.level;return-1}get nextBufferedFrag(){let e=this.currentFrag;if(e)return this.followingBufferedFrag(e);return null}get forceStartLoad(){return this._forceStartLoad}}class nb extends tb{constructor(...e){super(...e);this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let t=this.media;if(t!=null&&t.seeking)t.currentTime=t.currentTime},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:n}=t,s=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=e,this.state){case Me.STOPPED:case Me.ENDED:case Me.ERROR:this.state=Me.IDLE}if(this.state===Me.IDLE)this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,t];else this.nextOp=[s,t];this.hls.off(O.BUFFERED_TO_END,this.onBufferedToEnd);let i=this.media;if(n&&i){if(this.seekTo(s))this.currentOp=[s,t],this.nextOp=void 0,this.flushPipeline(s,!0)}}seekTo(e){let t=this.media;if(t){var n;let s=(n=this.getLevelDetails())==null?void 0:n.edge,i=s!==void 0?s:t.duration;if(e>=i)e=i-0.01;if(qt.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,kt.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let n=this.cached;n.push(e),this.cachedSize+=t.buffer.byteLength;let s=this.hls.config.iframeCacheLimit;while(this.cachedSize>s&&n.length>1){let i=n.shift();if(i.data)this.cachedSize-=i.data.byteLength,i.data=void 0;else{this.cached=n.filter((r)=>!!r.data),this.cachedSize=n.reduce((r,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:s}=e;if(this.cacheFragmentData&&!n&&s!=null&&s.byteLength&&!t.data&&js(t))this.cacheSet(t,new Uint8Array(s.slice(0)));super._handleFragmentLoadProgress(e)}loadFragment(e,t,n){let s=this.fragmentTracker.getState(e);if((s===Ss.NOT_LOADED||s===Ss.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,n)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let n=e.decryptdata;return(n==null?void 0:n.keyFormat)!=="identity"||!!n.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let n=e.stats=new c0;n.loading.start=n.loading.first=n.loading.end=self.performance.now(),n.loaded=n.total=t.byteLength,n.chunkCount=1,this.state=Me.FRAG_LOADING;let s={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(O.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:n,nextOp:s}=this;if(this.currentOp=this.nextOp=void 0,this.state=Me.STOPPED,n!=null&&n[1].seekOnAppend){if(this.flushPipeline(n[0],!s),!this.seekTo(n[0]))this.log(`Could not seek to ${n[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?s0(qt.getBuffered(this.media)):"none"}`)}if(s)this.loadMediaAt.apply(this,s)}flushPipeline(e,t){if(t){let n=this.media;if(n){let s=qt.bufferInfo(n,e,0),i=s.len?s.nextStart:0;if(i)this.fragmentTracker.removeFragmentsInRange(i,1/0,kt.MAIN),this.flushMainBuffer(i,1/0)}this.hls.once(O.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(O.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,n){let s=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,n||s||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let n=t.duration;return{len:n,start:e,end:e+n,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,kt.MAIN);return!!(t!=null&&t.endList)}}class yv extends nb{constructor(...e){super(...e);this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let n=(t=this._img)==null?void 0:t.src;if(n)self.URL.revokeObjectURL(n);this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case Me.STOPPED:case Me.ENDED:case Me.ERROR:this.state=Me.IDLE}if(this.state===Me.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Me.IDLE){let n=this.getBufferedAt(e);if(n)this.fragCurrent=n,this.updateImage(n,null)}}else{let n=this.fragCurrent;if(!n||e>=n.start&&e<n.end)this.queued=[t]}}updateImage(e,t,n){let s=e.data;if(!s)this.fragmentTracker.removeFragment(e);let i=this._img;if(i&&s){let r=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=r,i.onload=()=>{if(!this.hls)return;let h=this.hls.levels[e.level];if(h!=null&&h.fragmentError)h.fragmentError=0,e.stats.retry=0;let d=self.performance.now(),m=t?t.stats:e.stats;m.buffering.end=e.stats.buffering.end=d,this.hls.trigger(O.FRAG_BUFFERED,{frag:e,part:t,stats:m,id:e.type,chunkMeta:n})},i.onerror=()=>{this.handleError("Image decode error",e,t,n)};let l=i.src;if(l)self.URL.revokeObjectURL(l);let c=new Blob([s],{type:"image/jpeg"});i.src=self.URL.createObjectURL(c)}else this.state=Me.STOPPED,this.processQueued()}processQueued(){let e=this.queued;if(this.queued=void 0,e)this.loadMediaAt.apply(this,e)}handleError(e,t,n,s){if(!this.hls)return;let i=Error(e);this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_PARSING_ERROR,chunkMeta:s,frag:t,part:n,fatal:!1,error:i,err:i})}_bufferInitSegment(){}bufferFragmentData(e,t,n,s){super.bufferFragmentData(e,t,n,s,!0);let i=Ut(new Uint8Array(e.data1),["mdat"]);if(i.length===0){this.handleError("Could not find I-Frame mdat",t,n,s);return}let r=t;this.cacheSet(r,i[0]),this.updateImage(r,n,s)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){let n=this.getAppendedFrag(t);if(n&&!nh(n,this.fragPlaying))return this.fragPlaying=n,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}var I_=10,R_="Image I-Frame player does not accept HTMLMediaElements",V3={seekOnAppend:!0},Rd,Vg;class vv extends Ji{constructor(e,t){super("iframes",e.logger);this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Rd||(Rd=D_(t)),Vg||(Vg=q_(Rd)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;if(e)e.on(O.MANIFEST_LOADING,this.clearAsset,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this),e.on(O.DESTROYING,this.onDestroying,this)}unregisterListeners(){let e=this.hls;if(e)e.off(O.MANIFEST_LOADING,this.clearAsset,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this),e.off(O.DESTROYING,this.onDestroying,this)}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach((e)=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var n;let s=(n=this.hls)==null?void 0:n.pathwayPriority;if(t.length&&s)this.iframeInstances.forEach((i)=>{i.pathwayPriority=s})}onInitPtsFound(e,{id:t,timestampOffsets:n}){if(t===kt.MAIN)this.initPTS=n}onFragBuffered(e,t){var n;let s=this.hls;if(!s)return;if(s.hasEnoughToStart&&(((n=s.mainForwardBufferInfo)==null?void 0:n.len)||0)>I_)this.iframeInstances.forEach((i)=>{if(!i.loadingEnabled){var r;i.startLoad(((r=this.hls)==null||(r=r.media)==null?void 0:r.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(Rd,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let n=(t=this.hls)==null?void 0:t.iframeVariants.filter((s)=>s.imageCodec);return this.createInstance(Vg,n,e,"image-")}createInstance(e,t,n,s){let{hls:i}=this;if(!i)return null;let{url:r,userConfig:o,latestLevelDetails:l,loadLevelObj:c,loadLevel:h,bandwidthEstimate:d,sessionId:m}=i,{stats:p,variableList:b}=this;if(!(t!=null&&t.length)||!p||!r)return null;let v=`${s||""}iframe-player-${this.instanceCounter++}`,k=i.levels,A=c||k[h],T=R9(A,o.videoPreference),E=(A==null?void 0:A.pathwayId)||".",I=Ct(Ct({},o),{},{loggerId:v,primarySessionId:m,videoPreference:T,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},n),_=new e(I,r,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter((q)=>!q.url),this.iframeInstances.push(_),_.trigger(O.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:p,networkDetails:null,url:r,variableList:b}),_}}function D_(e){return class extends e{constructor(n,s,i,r){n.streamController||(n.streamController=nb);super(n);this._url=s,this.streamController.setInitPts(i),this.streamController.initDetails=r}loadSource(){}loadMediaAt(n,s=V3){if(n<0)return;let i=Ct(Ct({},V3),s);if(!this.loadingEnabled)this.startLoad(n);this.streamController.loadMediaAt(n,i)}}}function q_(e){return class extends e{constructor(n,s,i,r){n.cmcdController=void 0,n.emeController=void 0,n.streamController||(n.streamController=yv),n.capLevelController=void 0,n.bufferController=void 0;super(n,s,i,r)}attachImage(n){this.streamController.image=n}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw Error(R_)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(n){if(n<0)return null;if(!this.loadingEnabled)this.startLoad(n);this.streamController.loadMediaAt(n)}}}var Jo=0.025,l0=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function M_(e,t,n){return`${e.identifier}-${n+1}-${ph(t)}`}class Sv{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;if(this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,!this.supplementsPrimary)this.assetListResponse=null,this.assetList=[],this._duration=null}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let n=this.playoutLimit;if(e<=0||isNaN(n))return!1;if(n===0)return!0;return(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>n}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t){if(!$3(t,e))return e;return Ud(e,t)}}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,n=Ud(t,e);return t-n<0.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=lt(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t){if(!$3(t,e))return e;return Ud(e,t)}}return e}get appendInPlace(){if(this.appendInPlaceStarted)return!0;if(this.appendInPlaceDisabled)return!1;if(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Jo))return!0;return!1}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){if(this._timelineStart!==null)return this._timelineStart;return this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;if(this._duration!==null)t=this._duration;else if(this.dateRange.duration)t=this.dateRange.duration;else t=this.dateRange.plannedDuration||0;if(!isNaN(e)&&e<t)t=e;return t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){if(this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE")return l0.Range;return l0.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return F_(this)}}function Ud(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Jo)?t.start:t.start+t.duration}function $3(e,t){return t>e.start-Jo&&t<e.start+e.duration+Jo}function kv(e,t,n){let s=new self.URL(e,n);if(s.protocol!=="data:")Qo(s,"_HLS_primary_id",t);return s}function $g(e,t){while((n=e.assetList[++t])!=null&&n.error)var n;return t}function F_(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Gc(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class xv{constructor(e,t,n,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{if(this.reachedPlayout(this.currentTime)&&this.hls)this.hls.trigger(O.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=s;let r=()=>{this.hasDetails=!0};i.once(O.LEVEL_LOADED,r),i.once(O.AUDIO_TRACK_LOADED,r),i.once(O.SUBTITLE_TRACK_LOADED,r),i.on(O.MEDIA_ATTACHING,(o,{media:l})=>{if(this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit){if(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace)i.on(O.BUFFER_APPENDED,()=>{let h=this.bufferedEnd;if(this.reachedPlayout(h))this._bufferedEosTime=h,i.trigger(O.BUFFERED_TO_END,void 0)})}})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(!e)return;if(!e.url){let t=this.assetItem.uri;try{t=kv(t,e.config.primarySessionId||"").href}catch(n){}e.loadSource(t)}else if(e.levels.length&&!e.started)e.startLoad(-1,!0)}bufferedInPlaceToEnd(e,t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),r=qt.bufferInfo(e,i,0.02);return this.getAssetTime(r.end)>=s-0.02}reachedPlayout(e){let n=this.interstitial.playoutLimit;return this.startOffset+e>=n}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e){if(this._bufferedEosTime)return this._bufferedEosTime;return this.currentTime}let t=qt.bufferInfo(e,e.currentTime,0.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;if(!e)return this._currentTime||0;return this.getAssetTime(e.currentTime)}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let n=t-this.startOffset;if(n>0&&n<e)return n}return e}get remaining(){let e=this.duration;if(!e)return 0;return Math.max(0,e-this.currentTime)}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>0.000011111111111111112&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){let e=this.mediaAttached;if(e)this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout)}bufferSnapShot(){if(this.mediaAttached){var e;if((e=this.hls)!=null&&e.bufferedToEnd)this._bufferedEosTime=this.bufferedEnd}}destroy(){if(this.removeMediaListeners(),this.hls)this.hls.destroy();this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=(n)=>delete n.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var s;(s=this.hls)==null||s.on(e,t)}once(e,t,n){var s;(s=this.hls)==null||s.once(e,t)}off(e,t,n){var s;(s=this.hls)==null||s.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Gc(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}var Xg=0.033;class Av extends Ji{constructor(e,t){super("interstitials-sched",t);this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){if(this.eventMap={},this.setDurations(0,0,0),this.events)this.events.forEach((e)=>e.reset());this.events=this.items=null}resetErrorsInRange(e,t){if(this.events)return this.events.reduce((n,s)=>{if(e<=s.startOffset&&t>s.startOffset)return delete s.error,n+1;return n},0);return 0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e?this.eventMap[e]||null:null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;if(e.nextEvent)n=this.findEventIndex(e.nextEvent.identifier)-1;else if(e.previousEvent)n=this.findEventIndex(e.previousEvent.identifier)+1;let s=this.items;if(s){if(!s[n]){if(t===void 0)t=e.start;n=this.findItemIndexAtTime(t)}while(n>=0&&(i=s[n])!=null&&i.event){var i;n--}}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let s=0;s<n.length;s++){let i=n[s];if(t&&t!=="primary")i=i[t];let r=i.start,o=n[s].event,l=o!=null&&o.cue.pre?o.duration:i.end;if(e===r||e>r&&e<l)return s}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let s=e;s<=t;s++){if(!n[s])break;let i=n[s].event;if(i!=null&&i.restrictions.jump&&!i.appendInPlace)return s}return-1}findEventIndex(e){let t=this.items;if(t)for(let s=t.length;s--;){var n;if(((n=t[s].event)==null?void 0:n.identifier)===e)return s}return-1}findAssetIndex(e,t){let n=e.assetList,s=n.length;if(s>1)for(let i=0;i<s;i++){let r=n[i];if(!r.error){let o=r.timelineStart;if(t===o||t>o&&(t<o+(r.duration||0)||i===s-1))return i}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let n=t.assetList,s=n[n.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t,n=0){let s=e.main.details,{dateRanges:i}=s,r=this.events,o=this.parseDateRanges(i,{url:s.url},t),l=Object.keys(i),c=r?r.filter((h)=>l.indexOf(h.identifier)===-1):[];if(o.length)o.sort((h,d)=>{let m=h.cue.pre,p=h.cue.post,b=d.cue.pre,v=d.cue.post;if(m&&!b)return-1;if(b&&!m)return 1;if(p&&!v)return 1;if(v&&!p)return-1;if(!m&&!b&&!p&&!v){let k=h.startTime,A=d.startTime;if(k!==A)return k-A}return h.dateRange.tagOrder-d.dateRange.tagOrder});this.events=o,c.forEach((h)=>{this.removeEvent(h)}),this.updateSchedule(e,c,n)}updateSchedule(e,t=[],n=0,s=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let r=this.items,o=this.parseSchedule(i,e,n);if(s||t.length||(r==null?void 0:r.length)!==o.length||o.some((c,h)=>Math.abs(c.playout.start-r[h].playout.start)>0.005||Math.abs(c.playout.end-r[h].playout.end)>0.005))this.items=o,this.onScheduleUpdate(t,r)}}parseDateRanges(e,t,n){let s=[],i=Object.keys(e);for(let r=0;r<i.length;r++){let o=i[r],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];if(c)c.setDateRange(l);else if(c=new Sv(l,t),this.eventMap[o]=c,n===!1)c.appendInPlace=n;s.push(c)}}return s}parseSchedule(e,t,n=0){let s=[],i=t.main.details,r=i.live?1/0:i.edge,o=0;if(e=e.filter((c)=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,h=0;if(e.forEach((d,m)=>{let p=d.cue.pre,b=d.cue.post,v=e[m-1]||null,k=d.appendInPlace,A=b?r:d.startOffset,T=d.duration,E=d.timelineOccupancy===l0.Range?T:0,I=p&&i.live?n+(d.resumeOffset||0):0,_=I||d.resumptionOffset,q=(v==null?void 0:v.startTime)===A,P=A+d.cumulativeDuration,N=k?P+T:A+_;if(p||!b&&A<=0){let V=h;h+=E,d.timelineStart=P;let U=o;o+=T,s.push({event:d,start:P,end:N,playout:{start:U,end:o},integrated:{start:V,end:h}})}else if(A<=r){if(!q){let W=A-c;if(W>Xg){let ce=c,ue=h;h+=W;let oe=o;o+=W;let ae={previousEvent:e[m-1]||null,nextEvent:d,start:ce,end:ce+W,playout:{start:oe,end:o},integrated:{start:ue,end:h}};s.push(ae)}else if(W>0&&v)v.cumulativeDuration+=W,s[s.length-1].end=A}if(b)N=P;d.timelineStart=P;let V=h;h+=E;let U=o;o+=T,s.push({event:d,start:P,end:N,playout:{start:U,end:o},integrated:{start:V,end:h}})}else return;let H=I||d.resumeTime;if(b||H>r)c=r;else if(!p&&N&&d.appendInPlaceStarted&&H-N>Xg)c=N;else c=H}),c<r){var l;let d=c,m=h,p=r-c;h+=p;let b=o;o+=p,s.push({previousEvent:((l=s[s.length-1])==null?void 0:l.event)||null,nextEvent:null,start:c,end:d+p,playout:{start:b,end:o},integrated:{start:m,end:h}})}this.setDurations(r,o,h)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,s=n.live?1/0:n.edge,i=0,r=-1;e.forEach((o,l)=>{let c=o.cue.pre,h=o.cue.post,d=c?0:h?s:o.startTime;if(this.updateAssetDurations(o),r===d)o.cumulativeDuration=i;else i=0,r=d;if(!h&&o.snapOptions.in)o.resumeAnchor=Qc(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0;if(o.appendInPlace&&!o.appendInPlaceStarted){if(!this.primaryCanResumeInPlaceAt(o,t))o.appendInPlace=!1}if(!o.appendInPlace&&l+1<e.length){if(e[l+1].startTime-e[l].resumeTime<Xg){if(e[l+1].appendInPlace=!1,e[l+1].appendInPlace)this.warn(`Could not change append strategy for abutting event ${o}`)}}let p=lt(o.resumeOffset)?o.resumeOffset:o.duration;i+=p})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,s=e.startTime+e.resumptionOffset;if(Math.abs(n-s)>Jo)return this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(t).some((r)=>{let o=t[r].details,l=o.edge;if(n>=l)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${l}`),!1;let c=Qc(null,o.fragments,n);if(!c)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let h=r==="audio"?0.175:0;if(!(Math.abs(c.start-n)<Jo+h||Math.abs(c.end-n)<Jo+h))return this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0;return!1})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,s=!1,i=!1;for(let r=0;r<e.assetList.length;r++){let o=e.assetList[r],l=t+n;o.startOffset=n,o.timelineStart=l,s||(s=o.duration===null),i||(i=!!o.error);let c=o.error?0:o.duration||0;n+=c}if(s&&!i)e.duration=Math.max(n,e.duration);else e.duration=n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function br(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class Tv{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,s;try{s=kv(n,this.hls.sessionId,e.baseUrl)}catch(m){let p=this.assignAssetListError(e,ve.ASSET_LIST_LOAD_ERROR,m,n);this.hls.trigger(O.ERROR,p);return}if(t&&s.protocol!=="data:")Qo(s,"_HLS_start_offset",""+t);let i=this.hls.config,o=new i.loader(i),l={type:fn.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},c=i.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(m,p,b,v)=>{let k=m.data,A=k==null?void 0:k.ASSETS;if(!Array.isArray(A)){let T=this.assignAssetListError(e,ve.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),b.url,p,v);this.hls.trigger(O.ERROR,T);return}e.assetListResponse=k,this.hls.trigger(O.ASSET_LIST_LOADED,{event:e,assetListResponse:k,networkDetails:v})},onError:(m,p,b,v)=>{let k=this.assignAssetListError(e,ve.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,v,b);this.hls.trigger(O.ERROR,k)},onTimeout:(m,p,b)=>{let v=this.assignAssetListError(e,ve.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,b);this.hls.trigger(O.ERROR,v)}};return o.load(l,h,d),this.hls.trigger(O.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,s,i,r){return e.error=n,{type:Et.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:s,error:n,networkDetails:r,stats:i}}}function X3(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Ml(e,t){return`[${e}] Advancing timeline position to ${t}`}class Ev extends Ji{constructor(e,t){super("interstitials",e.logger);this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;let s=n-this.timelinePos;if(Math.abs(s)<0.0000000014172335600907028)return;let r=s<=-0.01;if(this.timelinePos===-1&&!this.effectivePlayingItem)this.checkStart();this.timelinePos=n,this.bufferedPos=n;let o=this.playingItem;if(!o){this.checkBuffer();return}if(r){if(this.schedule.resetErrorsInRange(n,n-s))this.updateSchedule(!0)}if(this.checkBuffer(),r&&n<o.start||n>=o.end){var l;let p=this.findItemIndex(o),b=this.schedule.findItemIndexAtTime(n);if(b===-1)b=p+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${n} (resolving from ${p} to ${b})`);if(!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused)this.shouldPlay=!1;if(!r){if(b>p){let v=this.schedule.findJumpRestrictedIndex(p+1,b);if(v>p){this.setSchedulePosition(v);return}}}this.setSchedulePosition(b);return}let c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){let p=o.event.assetList[0];if(p)this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,p)}return}let h=c.timelineStart,d=c.duration||0;if(r&&n<h||n>=h+d){var m;if((m=o.event)!=null&&m.appendInPlace)this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(n);this.setScheduleToAssetAtTime(n,c)}},this.onTimeupdate=()=>{let n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem)this.checkStart();if(n>this.timelinePos){if(this.timelinePos=n,n>this.bufferedPos)this.checkBuffer()}else return;let s=this.playingItem;if(!s||this.playingLastItem)return;if(n>=s.end){this.timelinePos=s.end;let o=this.findItemIndex(s);this.setSchedulePosition(o+1)}let i=this.playingAsset;if(!i)return;let r=i.timelineStart+(i.duration||0);if(n>=r)this.setScheduleToAssetAtTime(n,i)},this.onScheduleUpdate=(n,s)=>{let i=this.schedule;if(!i)return;let r=this.playingItem,o=i.events||[],l=i.items||[],c=i.durations,h=n.map((v)=>v.identifier),d=!!(o.length||h.length);if(d||s)this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
52
- Schedule: ${l.map((v)=>br(v))} pos: ${this.timelinePos}`);if(h.length)this.log(`Removed events ${h}`);let m=null,p=null;if(r)if(m=this.updateItem(r,this.timelinePos),this.itemsMatch(r,m))this.playingItem=m;else this.waitingItem=null;this.waitingItem=this.updateItem(this.waitingItem);let b=this.bufferingItem;if(b){if(p=this.updateItem(b,this.bufferedPos),this.itemsMatch(b,p))this.bufferingItem=p;else if(b.event)this.bufferingItem=this.playingItem,this.clearInterstitial(b.event,null)}if(n.forEach((v)=>{v.assetList.forEach((k)=>{this.clearAssetPlayer(k.identifier,null)})}),this.playerQueue.forEach((v)=>{if(v.interstitial.appendInPlace){let k=v.assetItem.timelineStart,A=v.timelineOffset-k;if(A)try{v.timelineOffset=k}catch(T){if(Math.abs(A)>Jo)this.warn(`${T} ("${v.assetId}" ${v.timelineOffset}->${k})`)}}}),d||s){if(this.hls.trigger(O.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(r)&&h.indexOf(r.event.identifier)>-1){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}if(r)this.trimInPlace(m,r);if(b&&p!==m)this.trimInPlace(p,b);this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Tv(e),this.schedule=new Av(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;if(e)e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(O.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(O.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(O.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(O.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(O.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(O.BUFFER_APPENDED,this.onBufferAppended,this),e.on(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(O.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(O.MEDIA_ENDED,this.onMediaEnded,this),e.on(O.ERROR,this.onError,this),e.on(O.DESTROYING,this.onDestroying,this)}unregisterListeners(){let e=this.hls;if(e)e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(O.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(O.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(O.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(O.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(O.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(O.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(O.BUFFER_CODECS,this.onBufferCodecs,this),e.off(O.BUFFER_APPENDED,this.onBufferAppended,this),e.off(O.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(O.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(O.MEDIA_ENDED,this.onMediaEnded,this),e.off(O.ERROR,this.onError,this),e.off(O.DESTROYING,this.onDestroying,this)}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){if(this.unregisterListeners(),this.stopLoad(),this.assetListLoader)this.assetListLoader.destroy();if(this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule)this.schedule.destroy();this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;if(e)this.removeMediaListeners(e)}removeMediaListeners(e){Bn(e,"play",this.onPlay),Bn(e,"pause",this.onPause),Bn(e,"seeking",this.onSeeking),Bn(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;Un(n,"seeking",this.onSeeking),Un(n,"timeupdate",this.onTimeupdate),Un(n,"play",this.onPlay),Un(n,"pause",this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!s){this.clearScheduleState();let i=this.findItemIndex(n);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,s=this.media;if(this.media=null,n)return;if(s)this.removeMediaListeners(s);if(this.detachedData){let i=this.getBufferingPlayer();if(i)this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia();this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=(d)=>d?e.getAssetPlayer(d.identifier):d,s=(d,m,p,b,v)=>{if(d){let k=d[m].start,A=d.event;if(A){if(m==="playout"||A.timelineOccupancy!==l0.Point){let T=n(p);if((T==null?void 0:T.interstitial)===A)k+=T.assetItem.startOffset+T[v]}}else{let T=b==="bufferedPos"?r():e[b];k+=T-d.start}return k}return 0},i=(d,m)=>{var p;if(d!==0&&m!=="primary"&&(p=e.schedule)!=null&&p.length){var b;let v=e.schedule.findItemIndexAtTime(d),k=(b=e.schedule.items)==null?void 0:b[v];if(k){let A=k[m].start-k.start;return d+A}}return d},r=()=>{let d=e.bufferedPos;if(d===Number.MAX_VALUE)return o("primary");return Math.max(d,0)},o=(d)=>{var m,p;if((m=e.primaryDetails)!=null&&m.live)return e.primaryDetails.edge;return((p=e.schedule)==null?void 0:p.durations[d])||0},l=(d,m)=>{var p,b;let v=e.effectivePlayingItem;if(v!=null&&(p=v.event)!=null&&p.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${m}"`);let k=e.effectivePlayingItem,A=e.schedule.findItemIndexAtTime(d,m),T=(b=e.schedule.items)==null?void 0:b[A],E=e.getBufferingPlayer(),I=E==null?void 0:E.interstitial,_=I==null?void 0:I.appendInPlace,q=k&&e.itemsMatch(k,T);if(k&&(_||q)){let P=n(e.playingAsset),N=(P==null?void 0:P.media)||e.primaryMedia;if(N){let H=m==="primary"?N.currentTime:s(k,m,e.playingAsset,"timelinePos","currentTime"),V=d-H,U=(_?H:N.currentTime)+V;if(U>=0&&(!P||_||U<=P.duration)){N.currentTime=U;return}}}if(T){let P=d;if(m!=="primary"){let H=T[m].start,V=d-H;P=T.start+V}let N=!e.isInterstitial(T);if((!e.isInterstitial(k)||k.event.appendInPlace)&&(N||T.event.appendInPlace)){let H=e.media||(_?E==null?void 0:E.media:null);if(H)H.currentTime=P}else if(k){let H=e.findItemIndex(k);if(A>H){let U=e.schedule.findJumpRestrictedIndex(H+1,A);if(U>H){e.setSchedulePosition(U);return}}let V=0;if(N)e.timelinePos=P,e.checkBuffer();else{let U=T.event.assetList,W=d-(T[m]||T).start;for(let ce=U.length;ce--;){let ue=U[ce];if(ue.duration&&W>=ue.startOffset&&W<ue.startOffset+ue.duration){V=ce;break}}}e.setSchedulePosition(A,V)}}},c=()=>{let d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;let m=t();if(e.isInterstitial(m))return m;return null},h={get bufferedEnd(){let d=t(),m=e.bufferingItem;if(m&&m===d){var p;return s(m,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((p=e.bufferingAsset)==null?void 0:p.startOffset)||0}return 0},get currentTime(){let d=c(),m=e.effectivePlayingItem;if(m&&m===d)return s(m,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start;return 0},set currentTime(d){let m=c(),p=e.effectivePlayingItem;if(p&&p===m)l(d+p.playout.start,"playout")},get duration(){let d=c();if(d)return d.playout.end-d.playout.start;return 0},get assetPlayers(){var d;let m=(d=c())==null?void 0:d.event.assetList;if(m)return m.map((p)=>e.getAssetPlayer(p.identifier));return[]},get playingIndex(){var d;let m=(d=c())==null?void 0:d.event;if(m&&e.effectivePlayingAsset)return m.findAssetIndex(e.effectivePlayingAsset);return-1},get scheduleItem(){return c()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){if(c())return h;return null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return r()},get currentTime(){let d=e.timelinePos;return d>0?d:0},set currentTime(d){l(d,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return s(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){l(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){return i(e.seekableStart,"integrated")}},skip:()=>{let d=e.effectivePlayingItem,m=d==null?void 0:d.event;if(m&&!m.restrictions.skip){let p=e.findItemIndex(d);if(m.appendInPlace){let b=d.playout.start+d.event.duration;l(b+0.001,"playout")}else e.advanceAfterAssetEnded(m,p,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,n=(e=this.schedule)==null?void 0:e.items;if(!this.playbackStarted||!t||!n)return!1;return this.findItemIndex(t)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let s=this.media;if(!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace)s=this.primaryMedia;let i=(t=s)==null?void 0:t.currentTime;if(i===void 0||!lt(i))return;return i}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);if(n)this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,s=e.media;if(n&&s===this.primaryMedia){if(this.bufferingAsset=null,!t||this.isInterstitial(t)&&!t.event.appendInPlace){if(t&&s){this.detachedData={media:s};return}}let i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ls(i)}`),this.detachedData=i}else if(t&&s)this.shouldPlay||(this.shouldPlay=!s.paused)}transferMediaTo(e,t){var n,s;if(e.media===t)return;let i=null,r=this.hls,o=e!==r,l=o&&e.interstitial.appendInPlace,c=(n=this.detachedData)==null?void 0:n.mediaSource,h;if(r.media){if(l)i=r.transferMedia(),this.detachedData=i;h="Primary"}else{let b=this.getBufferingPlayer();if(b)i=b.transferMedia(),this.detachedData=i,h=`${b}`;else if(c)h="detached MediaSource";else h="detached media"}if(!i){if(c)i=this.detachedData,this.log(`using detachedData: MediaSource ${ls(i)}`);else if(!this.detachedData||r.media===t){let b=this.playerQueue;if(b.length>1)b.forEach((v)=>{if(o&&v.interstitial.appendInPlace!==l){let k=v.interstitial;if(this.clearInterstitial(v.interstitial,null),k.appendInPlace=!1,k.appendInPlace)this.warn(`Could not change append strategy for queued assets ${k}`)}});this.hls.detachMedia(),this.detachedData={media:t}}}let d=i&&"mediaSource"in i&&((s=i.mediaSource)==null?void 0:s.readyState)!=="closed";if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!d&&!o){e.attachMedia(t);return}let m=d&&i?Ct({},i):{media:t},p=this.schedule;if(p&&o){let b=e.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:b||e.appendInPlace===!1}}if(!d&&l){let b=e,v=b.assetItem.timelineStart;if(v){let k=b.hls,A=Math.max(this.timelinePos-v,Number.EPSILON);if(k.startPosition!==A){if(this.log(`Set ${b} startPosition: ${A}`),k.config.startPosition=A,k.loadingEnabled)k.startLoad(A)}}}e.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events,n=this.hls;if(!t||this.playbackDisabled||!this.media||!n)return;if(this.bufferedPos===-1)this.bufferedPos=0;let s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){if(!n.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let r=n.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Ml("checkStart (preroll)",r));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(r>=0||!this.primaryLive){this.log(Ml("checkStart",r));let o=this.timelinePos=r>0?r:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else if(n.liveSyncPosition===0)this.setSchedulePosition(0);else this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(Ml("checkStart (playing item)",i.start));let r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){let n=e.event,s=n.findAssetIndex(t),i=$g(n,s);if(!n.isAssetPastPlayoutLimit(i))this.bufferedToEvent(e,i);else if(this.schedule){var r;let o=this.getNextItemIndex(e,!0),l=(r=this.schedule.items)==null?void 0:r[o];if(l)this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!lt(e.resumeOffset)&&this.hls){let n=this.getLiveStartPos();if(t){let s=this.getBufferingPlayer(),i=s!=null&&s.interstitial.cue.pre?s.remaining:0;return n+i}return n}}getNextItemIndex(e,t){if(this.schedule){let n=this.livePrerollResumption(e.event,t);if(n!==void 0)return this.log(`find next item index @${n}`),this.schedule.findItemIndexAtTime(n)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,n){let s=$g(e,n);if(!e.isAssetPastPlayoutLimit(s)){if(e.appendInPlace){let i=e.assetList[s];if(i)this.advanceInPlace(i.timelineStart)}this.setSchedulePosition(t,s)}else if(this.schedule){let i=this.schedule.items;if(i){let r=i[t],o=r.event?this.getNextItemIndex(r):t+1,l=i.length;if(o>=l){this.setSchedulePosition(-1);return}let c=e.resumeTime;if(this.timelinePos<c){if(this.log(Ml("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&!i[o].event)this.hls.startLoad(c+0.01);this.checkBuffer(this.bufferedPos<c)}this.setSchedulePosition(o)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let s=t.parentIdentifier,i=n.getEvent(s);if(i){let r=n.findEventIndex(s),o=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,r,o-1)}}setSchedulePosition(e,t){var n;let s=(n=this.schedule)==null?void 0:n.items;if(!s||this.playbackDisabled)return;let i=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i?br(i):i}) pos: ${this.timelinePos}`);let r=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(r)){let d=r.event,m=this.playingAsset,p=m==null?void 0:m.identifier,b=p?this.getAssetPlayer(p):null;if(b&&p&&(!this.eventItemsMatch(r,i)||t!==void 0&&p!==d.assetList[t].identifier)){var l;let v=d.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${v+1}/${d.assetList.length} ${Gc(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(O.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:v,event:d,schedule:s.slice(0),scheduleIndex:e,player:b}),r!==this.playingItem){if(this.itemsMatch(r,this.playingItem)&&!this.playingAsset)this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),v);return}if(this.retreiveMediaSource(p,i),b.media&&!((l=this.detachedData)!=null&&l.mediaSource))b.detachMedia()}if(!this.eventItemsMatch(r,i)){if(this.endedItem=r,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${br(r)}`),d.hasPlayed=!0,this.hls.trigger(O.INTERSTITIAL_ENDED,{event:d,schedule:s.slice(0),scheduleIndex:e}),d.cue.once&&this.hls){var c;this.updateSchedule();let v=(c=this.schedule)==null?void 0:c.items;if(i&&v){let k=this.findItemIndex(i),A=this.livePrerollResumption(d);if(A!==void 0){let T=A,E=this.getNextItemIndex(r);if(!this.isInterstitial(s[E])){var h;let I=(h=this.primaryDetails)==null?void 0:h.fragments;if(d.snapOptions.in&&I){let _=Qc(null,I,A);if(_)T=Math.min(Math.max(s[E].start,Ud(T,_)),s[E].end)}}if(this.log(Ml("live join (preroll)",T)),this.timelinePos=T,E!==k&&(E||E===0)){this.advanceSchedule(E,v,void 0,r,o);return}}this.advanceSchedule(k,v,t,r,o)}return}}}this.advanceSchedule(e,s,t,r,o)}advanceSchedule(e,t,n,s,i){let r=this.schedule;if(!r)return;let o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length)c.forEach((h)=>{let d=h.interstitial,m=r.findEventIndex(d.identifier);if(m<e||m>e+1)this.clearInterstitial(d,o)});if(this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let h=o.event;if(n===void 0){n=h.cue.pre?0:r.findAssetIndex(h,this.timelinePos);let b=$g(h,n-1);if(h.isAssetPastPlayoutLimit(b)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,n);return}n=b}let d=this.waitingItem;if(!this.assetsBuffered(o,l))this.setBufferingItem(o);let m=this.preloadAssets(h,n);if(!this.eventItemsMatch(o,d||s))this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${br(o)} ${h.appendInPlace?"append in place":""}`),h.hasPlayed=!1,this.hls.trigger(O.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e});if(!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader)h.assetListLoader.destroy(),h.assetListLoader=void 0;if(!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let p=h.assetList[n];if(!p){this.advanceAfterAssetEnded(h,e,n||0);return}if(!m)m=this.getAssetPlayer(p.identifier);if(m===null||m.destroyed){let b=h.assetList.length;this.warn(`asset ${n+1}/${b} player destroyed ${h}`),m=this.createAssetPlayer(h,p,n),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)){if(h.appendInPlace&&this.isAssetBuffered(p))return}if(this.startAssetPlayer(m,n,t,e,l),this.shouldPlay)X3(m.media)}else if(o){if(this.resumePrimary(o,e,s),this.shouldPlay)X3(this.hls.media)}else if(i&&this.isInterstitial(s)){if(this.endedItem=null,this.playingItem=s,!s.event.appendInPlace)this.attachPrimary(r.durations.primary,null)}}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var s,i;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${br(e)}`);let r=this.timelinePos;if(!((s=this.detachedData)!=null&&s.mediaSource)){if(r<e.start||r>=e.end||r<this.seekableStart)r=this.getPrimaryResumption(e,t),this.log(Ml("resumePrimary",r)),this.timelinePos=r;this.attachPrimary(r,e)}else if(this.primaryLive)this.startLoadingPrimaryAt(r);if(!n)return;let o=(i=this.schedule)==null?void 0:i.items;if(!o)return;this.log(`INTERSTITIALS_PRIMARY_RESUMED ${br(e)}`),this.hls.trigger(O.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer()}get seekableStart(){var e;return this.primaryLive?((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0:0}getPrimaryResumption(e,t,n){let s=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let i=this.endedItem||this.playingItem,r=i!=null&&i.event?this.livePrerollResumption(i.event,n):void 0;if(r!==void 0)return r;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:c}=o;if(s<l||s>c&&!n){let h=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${l}-${c}]) snapping to liveSync ${h}`),h||l}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var e;let t=this.hls.startPosition,n=this.hls.liveSyncPosition||0,s=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;if(t===-1||n&&n-t<s)return n||0;return t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);if(t!=null&&t.hls)return t.hls.bufferedToEnd;return qt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){if(t)this.setBufferingItem(t);else this.bufferingItem=this.playingItem;this.bufferingAsset=null;let s=this.primaryMedia;if(!s)return;let i=this.hls;if(i.media)this.checkBuffer();else if(this.transferMediaTo(i,s),n)this.startLoadingPrimaryAt(e,n);if(!n)this.log(Ml("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n)}startLoadingPrimaryAt(e,t){let n=this.hls,{loadingEnabled:s,bufferingEnabled:i,startPosition:r}=n,o=n.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${r} skip seek: ${t} has enough ${o} loadingEnabled: ${s} bufferingEnabled: ${i}`),!t&&o||!s||Math.abs(r-e)>0.1){let l=this.primaryDetails;if(l!=null&&l.live&&e+0.5>=l.edge){let c=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${c?br(c):null}`),n.pauseBuffering(),this.bufferPastEdge=!0;return}n.startLoad(e,t)}else if(!i)n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(O.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(O.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let s=Ct(Ct({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=s;let i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,i===-1?0:i),!this.schedule.items)return;if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+0.5<o.edge){this.bufferPastEdge=!1;let c=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${c?br(c):null}`),(c==null?void 0:c.end)===1/0){let d=this.playingItem,m=this.isInterstitial(d)&&d.event.appendInPlace;this.hls.startLoad(Math.max(l,c.start),m)}else{let d=this.getBufferingPlayer();if(d){if(d.bufferedInPlaceToEnd(this.primaryMedia,d.currentTime)&&d.hls)d.hls.trigger(O.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Ct(Ct({},this.altSelection),{},{audio:n});return}let i=Ct(Ct({},s),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],s=this.mediaSelection;if(!s){this.altSelection=Ct(Ct({},this.altSelection),{},{subtitles:n});return}let i=Ct(Ct({},s),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=U5(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(t)||s.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=U5(t);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(t)||t.id!==-1&&s.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;if(n)this.requiredTracks=n}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){let s=t[n];if(s.cue.post){let i=this.getEventItem(s.identifier);if(i&&this.eventItemsMatch(i,this.bufferingItem))this.bufferedToItem(i,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let n=this.findItemIndex(t);this.setSchedulePosition(n+1)}else this.shouldPlay=!1}updateItem(e,t){var n;let s=(n=this.schedule)==null?void 0:n.items;if(e&&s){let i=this.findItemIndex(e,t);return s[i]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>0.25){e.event.assetList.forEach((i,r)=>{if(e.event.isAssetPastPlayoutLimit(r))this.clearAssetPlayer(i.identifier,null)});let n=e.end+0.25,s=qt.bufferInfo(this.primaryMedia,n,0);if(s.end>n||(s.nextStart||0)>n){this.log(`trim buffered interstitial ${br(e)} (was ${br(t)})`);let i=!0;this.attachPrimary(n,null,i),this.flushFrontBuffer(n)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var n;return!!t&&(e===t||e.event.identifier===((n=t.event)==null?void 0:n.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let n=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(n)&&n.event.identifier===e)return n}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,n;let s=this.mediaSelection;if(!s)return;let i=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(n=this.schedule)==null||n.updateSchedule(s,[],i,e)}checkBuffer(e){var t;let n=(t=this.schedule)==null?void 0:t.items;if(!n)return;let s=qt.bufferInfo(this.primaryMedia,this.timelinePos,0);if(e)this.bufferedPos=this.timelinePos;e||(e=s.len<1),this.updateBufferedPos(s.end,n,e)}updateBufferedPos(e,t,n){let s=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let r=this.playingItem,o=this.findItemIndex(r),l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let h=this.findItemIndex(i),d=Math.min(h+1,t.length-1),m=t[d];if(l===-1&&i&&e>=i.end||(c=m.event)!=null&&c.appendInPlace&&e+0.01>=m.start)l=d;if(this.isInterstitial(i)){let p=i.event;if(d-o>1&&p.appendInPlace===!1)return;if(p.assetList.length===0&&p.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(m);else{let p=this.primaryDetails;if(this.primaryLive&&p&&e>p.edge-p.targetduration&&m.start<p.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(m))this.preloadAssets(m.event,0)}}else if(n&&r&&!this.itemsMatch(r,i)){if(l===o)this.bufferedToItem(r);else if(l===o+1)this.bufferedToItem(t[l])}}assetsBuffered(e,t){if(e.event.assetList.length===0)return!1;return!e.event.assetList.some((s)=>{let i=this.getAssetPlayer(s.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:s,events:i}=n;if(!s||!i)return t;let r=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${br(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(r){let c=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,d)=>{let m=this.getAssetPlayer(h.identifier);if(m){if(d===c)m.loadSource();m.resumeBuffering()}})}else this.hls.resumeBuffering(),this.playerQueue.forEach((c)=>c.pauseBuffering());this.hls.trigger(O.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else if(this.bufferingItem!==e)this.bufferingItem=e;return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(this.playbackDisabled)return;if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let s=this.getPrimaryResumption(e,this.findItemIndex(e),!0),i=this.bufferedPos=Math.max(s,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),r=this.detachedData;if(r)if(r.mediaSource)this.attachPrimary(i,e,!0);else this.startLoadingPrimaryAt(i);else{let o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(i,l)}}}bufferedToEvent(e,t){let n=e.event,s=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(s||!i){let r=this.preloadAssets(n,t);if(r!=null&&r.interstitial.appendInPlace){let o=this.primaryMedia;if(o)this.bufferAssetPlayer(r,o)}}}preloadAssets(e,t){let n=e.assetUrl,s=e.assetList.length,i=s===0&&!e.assetListLoader,r=e.cue.once;if(i){let l=e.timelineStart,c=this.playingItem,h=this.getBufferingPlayer();if(e.appendInPlace){var o;if(!this.isInterstitial(c)&&(c==null||(o=c.nextEvent)==null?void 0:o.identifier)===e.identifier)this.flushFrontBuffer(l+0.25)}let d,m=0;if((!h||h.interstitial.cue.pre)&&this.primaryLive){if(m=this.getLiveStartPos(),h)m+=h.remaining}if(m&&!(e.cue.pre||e.cue.post)){let b=m-l;if(b>0)d=Math.round(b*1000)/1000}if(this.log(`Load interstitial asset ${t+1}/${n?1:s} ${e}${m?` live-start: ${m} start-offset: ${d} (timeline-start: ${l})`:""}`),n)return this.createAsset(e,0,0,l,e.duration,n);let p=this.assetListLoader.loadAssetList(e,d);if(p)e.assetListLoader=p}else if(!r&&s){for(let c=t;c<s;c++){let h=e.assetList[c],d=this.getAssetPlayerQueueIndex(h.identifier);if((d===-1||this.playerQueue[d].destroyed)&&!h.error)this.createAssetPlayer(e,h,c)}let l=e.assetList[t];if(l){let c=this.getAssetPlayer(l.identifier);if(c)c.loadSource();return c}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let n=this.primaryDetails;if(n&&e>=n.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach((i)=>{this.hls.trigger(O.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,s,i,r){let o={parentIdentifier:e.identifier,identifier:M_(e,r,t),duration:i,startOffset:n,timelineStart:s,uri:r};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let s=this.hls,i=s.userConfig,r=s.loadLevelObj||s.levels[s.currentLevel],o=R9(r,i.videoPreference),l=s.audioTracks[s.audioTrack],c=s.subtitleTracks[s.subtitleTrack],h=0;if(this.primaryLive||e.appendInPlace){let I=this.timelinePos-t.timelineStart;if(I>=0){let _=t.duration;if(_&&I<_)h=I}}let d=t.identifier,m=Ct(Ct({},i),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||i.audioPreference,subtitlePreference:c||i.subtitlePreference});if(e.appendInPlace){if(e.appendInPlaceStarted=!0,t.timelineStart)m.timelineOffset=t.timelineStart}let p=m.cmcd;if(p!=null&&p.sessionId&&p.contentId)m.cmcd=Gn({},p,{contentId:ph(t.uri)});if(this.getAssetPlayer(d))this.warn(`Duplicate date range identifier ${e} and asset ${d}`);let b=new xv(this.HlsPlayerClass,m,e,t);this.playerQueue.push(b),e.assetList[n]=t;let v=!0,k=(I)=>{if(I.live){let P=Error(`Interstitials MUST be VOD assets ${e}`),N={fatal:!0,type:Et.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:P},H=this.findEventIndex(e.identifier);this.handleAssetItemError(N,e,H,n,P.message);return}let _=I.edge-I.fragmentStart,q=t.duration;if(v||q===null||_>q)v=!1,this.log(`Interstitial asset "${d}" duration change ${q} > ${_}`),t.duration=_,this.updateSchedule()};b.on(O.LEVEL_UPDATED,(I,{details:_})=>k(_)),b.on(O.LEVEL_PTS_UPDATED,(I,{details:_})=>k(_)),b.on(O.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let A=(I,_)=>{let q=this.getAssetPlayer(d);if(q&&_.tracks){q.off(O.BUFFER_CODECS,A),q.tracks=_.tracks;let P=this.primaryMedia;if(this.bufferingAsset===q.assetItem&&P&&!q.media)this.bufferAssetPlayer(q,P)}};b.on(O.BUFFER_CODECS,A);let T=()=>{let I=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${I}`),!I||!this.schedule)return;let _=this.getEventItem(e.identifier);if(_)this.advanceAssetBuffering(_,I.assetItem)};b.on(O.BUFFERED_TO_END,T);let E=(I)=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;let q=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,q,I)};return b.once(O.MEDIA_ENDED,E(n)),b.once(O.PLAYOUT_LIMIT_REACHED,E(1/0)),b.on(O.ERROR,(I,_)=>{if(!this.schedule)return;let q=this.getAssetPlayer(d);if(_.details===ve.BUFFER_STALLED_ERROR){if(q!=null&&q.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(_.details===ve.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(_,e,this.findEventIndex(e.identifier),n,`Asset player error ${_.error} ${e}`)}),b.on(O.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;let _=Error(`Asset player destroyed unexpectedly ${d}`),q={fatal:!0,type:Et.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:_};this.handleAssetItemError(q,e,this.findEventIndex(e.identifier),n,_.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Gc(t)}`),this.hls.trigger(O.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:b}),b}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach((n)=>{this.clearAssetPlayer(n.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let s=this.playerQueue[n];this.log(`clear ${s} toSegment: ${t?br(t):t}`),this.transferMediaFromPlayer(s,t),this.playerQueue.splice(n,1),s.destroy()}}emptyPlayerQueue(){let e;while(e=this.playerQueue.pop())e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,s,i){let{interstitial:r,assetItem:o,assetId:l}=e,c=r.assetList.length,h=this.playingAsset;if(this.endedAsset=null,this.playingAsset=o,(h==null?void 0:h.identifier)!==l){if(h)this.clearAssetPlayer(h.identifier,n[s]),delete h.error;this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Gc(o)}`),this.hls.trigger(O.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:r,schedule:n.slice(0),scheduleIndex:s,player:e})}this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var n;if(!this.schedule)return;let{interstitial:s,assetItem:i}=e,r=this.getEventItem(s.identifier);if(!r)return;if(e.loadSource(),this.setBufferingItem(r),this.bufferingAsset=i,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(r,i);return}let o=this.getBufferingPlayer();if(o===e)return;let l=s.appendInPlace;if(l&&(o==null?void 0:o.interstitial.appendInPlace)===!1)return;let c=(o==null?void 0:o.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(l&&i!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!r9(c,e.tracks)){let h=Error(`Asset ${Gc(i)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),d={fatal:!0,type:Et.OTHER_ERROR,details:ve.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=s.findAssetIndex(i);this.handleAssetItemError(d,s,this.findEventIndex(s.identifier),m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let s=n.currentTime,i=t.findAssetIndex(e,s),r=e.assetList[i];if(r){let o=this.getAssetPlayer(r.identifier);if(o){let l=o.currentTime||s-r.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${s})`),l&&(c/n.playbackRate<0.5||o.bufferedInPlaceToEnd(n,o.currentTime))&&o.hls){let h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,i)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let n=`advance currentTime to ${e}, duration: ${t.duration}`;if(t.duration>e)this.log(n),t.currentTime=e;else this.log(`Cannot ${n}`)}}handleAssetItemError(e,t,n,s,i){if(e.details===ve.BUFFER_STALLED_ERROR)return;let r=t.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${r?Gc(r):r} ${e.error}`),!this.schedule)return;let o=(r==null?void 0:r.identifier)||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,d=Gn({},e,{fatal:!1,errorAction:hh(!0),asset:r,assetListIndex:s,event:t,schedule:h,scheduleIndex:n,player:c});if(this.hls.trigger(O.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;let m=this.playingAsset,p=this.bufferingAsset,b=Error(i);if(r)this.clearAssetPlayer(o,null),r.error=b;if(!t.assetList.some((v)=>!v.error))t.error=b;else for(let v=s;v<t.assetList.length;v++)this.resetAssetPlayer(t.assetList[v].identifier);if(this.updateSchedule(!0),t.error)this.primaryFallback(t);else if((m==null?void 0:m.identifier)===o)this.advanceAfterAssetEnded(t,n,s);else if((p==null?void 0:p.identifier)===o&&this.isInterstitial(this.bufferingItem))this.advanceAssetBuffering(this.bufferingItem,p)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,s=this.playingItem,i=this.seekableStart,r=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(n)){if(this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${br(n)} startPosition: ${r} seekableStart: ${i} error: ${e.error}`),o===-1)o=r;o=Math.max(o,i);let c=this.updateItem(n,o);if(this.itemsMatch(n,c))this.clearInterstitial(e,null);if(e.appendInPlace)this.attachPrimary(t,null),this.flushFrontBuffer(t)}else if(o===-1){this.checkStart();return}if(!this.schedule)return;if(!this.isInterstitial(s))return;let l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var n,s;let i=t.event,r=i.identifier,o=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(r)))return;let{timelineStart:l,duration:c}=i,h=0;o.forEach((b,v)=>{let k=parseFloat(b.DURATION);this.createAsset(i,v,h,l+h,k,b.URI),h+=k}),i.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${i}`);let d=this.waitingItem,m=(d==null?void 0:d.event.identifier)===r;this.updateSchedule();let p=(s=this.bufferingItem)==null?void 0:s.event;if(m){let b=this.findEventIndex(r),v=this.getEventItem(r);if(v){if(!this.playingItem&&this.timelinePos>v.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==b){i.error=Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}}this.setBufferingItem(v)}this.setSchedulePosition(b)}else if((p==null?void 0:p.identifier)===r){let b=i.assetList[0];if(b){let v=this.getAssetPlayer(b.identifier);if(p.appendInPlace){let k=this.primaryMedia;if(v&&k)this.bufferAssetPlayer(v,k)}else if(v)v.loadSource()}}}onError(e,t){if(!this.schedule)return;switch(t.details){case ve.ASSET_LIST_PARSING_ERROR:case ve.ASSET_LIST_LOAD_ERROR:case ve.ASSET_LIST_LOAD_TIMEOUT:{let n=t.interstitial;if(n)this.updateSchedule(!0),this.primaryFallback(n);break}case ve.BUFFER_STALLED_ERROR:{let n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}let s=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${s==null?void 0:s.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Cv{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;let{media:n}=this,s=this.levelDetails;if(!n||!s||!this.hls)return;this.currentTime=n.currentTime;let i=this.hls.config,r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=i;if(!o||l===1||!s.live)return;let c=this.targetLatency;if(c===null)return;let h=r-c,d=Math.min(this.maxLatency,c+s.targetduration),m=h<d,p=i0(i)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(m&&h>0.05&&this.forwardBufferLength>1&&!p){let b=Math.min(2,Math.max(1,l)),v=Math.round(2/(1+Math.exp(-0.75*h-this.edgeStalled))*20)/20,k=Math.min(b,Math.max(1,v));this.changeMediaPlaybackRate(n,k)}else if(n.playbackRate!==1&&n.playbackRate!==0)this.changeMediaPlaybackRate(n,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:n,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:o,lowLatencyMode:l}=t,c=this.hls.userConfig,h=l?s||n:n;if(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||h===0)h=r!==void 0?r:o*i;let d=i;return h+Math.min(this.stallCount*t.liveSyncOnStallIncrease,d)}set targetLatency(e){if(!this.hls)return;this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let n=this.levelDetails;if(n===null)return null;let s=n.edge,i=e-t-this.edgeStalled,r=s-n.totalduration,o=s-(this.hls.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(r,i),o)}get drift(){let e=this.levelDetails;if(e===null)return 1;return e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;if(!e)return;e.on(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(O.ERROR,this.onError,this),e.on(O.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}unregisterListeners(){let{hls:e}=this;if(!e)return;e.off(O.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(O.ERROR,this.onError,this),e.off(O.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){if(this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){if(t.advanced)this.onTimeupdate();if(!t.live&&this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var n;let s=this.hls,i=this.media||t.event.appendInPlace&&(s==null||(n=s.interstitialsManager)==null?void 0:n.playerQueue.reduce((r,o)=>r||o.media,null));if(s&&i&&i.playbackRate>1&&i.playbackRate<=s.config.maxLiveSyncPlaybackRate)this.changeMediaPlaybackRate(i,1)}onError(e,t){var n;if(t.details!==ve.BUFFER_STALLED_ERROR)return;if(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live)this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency")}changeMediaPlaybackRate(e,t){var n,s;if(e.playbackRate===t)return;(n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t}estimateLiveEdge(){let e=this.levelDetails;if(e===null)return null;return e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();if(e===null)return null;return e-this.currentTime}}var W3=500;class jv extends g0{constructor(e,t,n){super(e,t,n,"subtitle-stream-controller",kt.SUBTITLE);this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(O.LEVEL_LOADED,this.onLevelLoaded,this),e.on(O.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(O.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(O.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(O.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(O.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(O.LEVEL_LOADED,this.onLevelLoaded,this),e.off(O.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(O.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(O.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(O.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(O.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Me.IDLE,this.setInterval(W3),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:n,part:s,success:i}=t;if(!i)return;let r=this.tracksBuffered[this.currentTrackId];if(!r)return;let o,l=(s||n).start;for(let h=0;h<r.length;h++)if(l>=r[h].start&&l<=r[h].end){o=r[h];break}let c=l+(s||n).duration;if(o)o.end=c;else o={start:l,end:c},r.push(o);if(!s||c>=n.end){let h=this.fragmentTracker.fragBuffered(n);if(s&&h)h.range.subs={time:[{startPTS:n.start,endPTS:c}],partial:!0};if(js(n)&&!this.fragContextChanged(n))this.fragPrevious=n;if(this.fragBufferedComplete(n,s),this.media)this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:n,endOffset:s}=t;if(n===0&&s!==Number.POSITIVE_INFINITY){let i=s-1;if(i<=0)return;t.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach((r)=>{if(!r)return;for(let o=0;o<r.length;){if(r[o].end<=i){r.shift();continue}else if(r[o].start<i)r[o].start=i;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(n,i,kt.SUBTITLE)}}onError(e,t){let n=t.frag;if((n==null?void 0:n.type)===kt.SUBTITLE){if(t.details===ve.FRAG_GAP)this.fragmentTracker.addAsGap(n);if(this.fragCurrent)this.fragCurrent.abortRequests();if(this.state!==Me.STOPPED)this.state=Me.IDLE}}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&_6(this.levels,t)){this.levels=t.map((n)=>new Yc(n));return}this.tracksBuffered=[],this.levels=t.map((n)=>{let s=new Yc(n);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,kt.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let s=this.levels[this.currentTrackId];if(!(s!=null&&s.details)){this.mediaBuffer=null;return}if(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Me.STOPPED)this.setInterval(W3)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:s,levels:i}=this,{details:r,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=i[o];if(o>=i.length||!l)return;this.log(`Subtitle track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=this.mainDetails,h=0;if(r.live||(n=l.details)!=null&&n.live){if(r.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}if(l.details){var d;h=this.alignPlaylists(r,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(!r.alignedSliding)n0(c,r,this),h=r.fragmentStart}if(l.details=r,this.levelLastLoaded=l,c&&!this.startFragRequested)this.setStartPosition(c,h);if(o!==s)return;this.hls.trigger(O.SUBTITLE_TRACK_UPDATED,{details:r,id:o,groupId:t.groupId}),this.tickImmediate()}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:s}=e;if(!n||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t))return;this.decryptPayload(s,t,n)}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e;if(this.fragContextChanged(t)||!(n!=null&&n.byteLength)||!this.shouldDecrypt(t))return;this.decryptPayload(n,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&$c(t.method))}decryptPayload(e,t,n){let s=t.decryptdata,i=performance.now();this.decrypter.decrypt(new Uint8Array(e),s.key.buffer,s.iv.buffer,F1(s.method)).then((r)=>{if(this.fragContextChanged(t))return;this.hls.trigger(O.FRAG_DECRYPTED,{frag:t,part:n,payload:r,stats:{tstart:i,tdecrypt:performance.now()}})}).catch((r)=>{if(this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.FRAG_DECRYPT_ERROR,fatal:!1,error:r,reason:r.message,frag:t,part:n}),!n)this.warn(`${r.name}: ${r.message}`),this.state=Me.IDLE})}doTick(){if(this.state===Me.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:n,levels:s}=this,i=s[n],r=i==null?void 0:i.details;if(!r||this.waitForLive(i)||this.waitForCdnTuneIn(r)){this.startFragRequested=!1;return}let{config:o}=this,l=this.playhead,c=qt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,o.maxBufferHole),{end:h,len:d}=c,m=Math.max(this.hls.maxBufferLength+r.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(d>m||d&&!this.buffering)return;let p=this.getNextFragment(h,r);if(!p)return;if(js(p)){var t;let b=p.sn-r.startSN,v=r.fragments[b-1];if(p.cc===(v==null?void 0:v.cc)&&!((t=r.partList)!=null&&t.length)&&this.fragmentTracker.getState(v)===Ss.NOT_LOADED)p=v}this.loadFragment(p,i,h)}}loadFragment(e,t,n){let s=this.fragmentTracker.getState(e);if(s===Ss.NOT_LOADED||s===Ss.PARTIAL)super.loadFragment(e,t,n)}get mediaBufferTimeRanges(){return new _v(this.tracksBuffered[this.currentTrackId]||[])}}class _v{constructor(e){this.buffered=void 0;let t=(n,s,i)=>{if(s=s>>>0,s>i-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][n]};this.buffered={get length(){return e.length},end(n){return t("end",n,e.length)},start(n){return t("start",n,e.length)}}}}var L_={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Iv=(e)=>String.fromCharCode(L_[e]||e),na=15,ta=42,O_={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},P_={17:2,18:4,21:6,22:8,23:10,19:13,20:15},N_={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},B_={25:2,26:4,29:6,30:8,31:10,27:13,28:15},H_=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Rv{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==="function"?t():t;Rn.log(`${this.time} [${e}] ${n}`)}}}var Fl=function(t){let n=[];for(let s=0;s<t.length;s++)n.push(t[s].toString(16));return n},v1=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class sb{constructor(){this.styles=v1}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=v1}setStyles(e){let t=this.styles,n=Object.prototype.hasOwnProperty;this.styles={foreground:n.call(e,"foreground")?e.foreground:t.foreground,underline:n.call(e,"underline")?e.underline:t.underline,italics:n.call(e,"italics")?e.italics:t.italics,background:n.call(e,"background")?e.background:t.background,flash:n.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Dv{constructor(){this.uchar=" ",this.penState=new sb}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class qv{constructor(e){this.chars=[],this.pos=0,this.currPenState=new sb,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ta;t++)this.chars.push(new Dv);this.logger=e}equals(e){let t=this.chars,n=e.chars;for(let s=0;s<ta;s++){let i=t[s],r=n[s];if(i.uchar!==r.uchar)return!1;let o=i.penState.styles,l=r.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<ta;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<ta;t++){let n=e[t];if(n.uchar!==" ")return!1;let s=n.penState.styles;if(s!==v1&&(s.foreground!=="white"||s.underline||s.italics||s.background!=="black"||s.flash))return!1}return!0}setCursor(e){if(this.pos!==e)this.pos=e;if(this.pos<0)this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0;else if(this.pos>=ta)this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ta-1}moveCursor(e){let t=Math.min(this.pos+e,ta);if(e>1)for(let n=this.pos+1;n<t;n++)this.chars[n].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){if(e>=144)this.backSpace();let t=Iv(e);if(this.pos>=ta){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<ta;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let n=0;n<ta;n++){let s=this.chars[n].uchar;if(s!==" ")t=!1;e.push(s)}if(t)return"";else return e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class zd{constructor(e){this.rows=[],this.currRow=na-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<na;t++)this.rows.push(new qv(e));this.logger=e}reset(){for(let e=0;e<na;e++)this.rows[e].clear();this.currRow=na-1}equals(e){let t=!0;for(let n=0;n<na;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<na;t++){let n=this.rows[t].chars,s=e.rows[t].chars;for(let i=0;i<ta;i++){let r=n[i],o=s[i];r.uchar=o.uchar,r.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<na;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ls(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1)t=this.nrRollUpRows-1;if(this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<na;o++)this.rows[o].clear();let i=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){let o=r.rows[i].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(r.rows[i+c])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let i=e.indent,r=Math.max(i-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ls(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],n="",s=-1;for(let i=0;i<na;i++){let r=this.rows[i].getTextString();if(r)if(s=i+1,e)t.push("Row "+s+": '"+r+"'");else t.push(r.trim())}if(t.length>0)if(e)n="["+t.join(" | ")+"]";else n=t.join(`
53
- `);return n}getTextAndFormat(){return this.rows}}class Mv{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new zd(n),this.nonDisplayedMemory=new zd(n),this.lastOutputScreen=new zd(n),this.currRollUpRow=this.displayedMemory.rows[na-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[na-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){if(e===this.mode)return;if(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON")this.writeScreen=this.nonDisplayedMemory;else this.writeScreen=this.displayedMemory,this.writeScreen.reset();if(this.mode!=="MODE_ROLL-UP")this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null;this.mode=e}insertChars(e){for(let n=0;n<e.length;n++)this.writeScreen.insertChar(e[n]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";if(this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate()}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){if(this.logger.log(2,"BS - BackSpace"),this.mode==="MODE_TEXT")return;if(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory)this.outputDataUpdate()}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,!t.italics){let n=Math.floor(e/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=s[n]}else t.foreground="white";this.logger.log(2,"MIDROW: "+ls(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;if(t===null)return;if(this.outputFilter){if(this.cueStartTime===null&&!this.displayedMemory.isEmpty())this.cueStartTime=t;else if(!this.displayedMemory.equals(this.lastOutputScreen)){if(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue)this.outputFilter.dispatchCue();this.cueStartTime=this.displayedMemory.isEmpty()?null:t}this.lastOutputScreen.copy(this.displayedMemory)}}cueSplitAtTime(e){if(this.outputFilter){if(!this.displayedMemory.isEmpty()){if(this.outputFilter.newCue)this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory);this.cueStartTime=e}}}}class S1{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=z_(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Rv,this.field=e,this.outputFilters=[null,t,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var n;this.outputFilters[e]=t,(n=this.channels[e])==null||n.setHandler(t)}getChannel(e){let t=this.channels[e];if(!t)t=this.channels[e]=new Mv(this.field+e-1,this.outputFilters[e],this.logger);return t}addData(e,t){this.logger.time=e;for(let n=0;n<t.length;n+=2){let s=t[n]&127,i=t[n+1]&127,r=!1,o=null;if(s===0&&i===0)continue;else this.logger.log(3,()=>"["+Fl([t[n],t[n+1]])+"] -> ("+Fl([s,i])+")");let l=this.cmdHistory;if(s>=16&&s<=31){if(U_(s,i,l)){Dd(null,null,l),this.logger.log(3,()=>"Repeated command ("+Fl([s,i])+") is dropped");continue}if(Dd(s,i,this.cmdHistory),r=this.parseCmd(s,i),!r)r=this.parseMidrow(s,i);if(!r)r=this.parsePAC(s,i);if(!r)r=this.parseBackgroundAttributes(s,i)}else Dd(null,null,l);if(!r){if(o=this.parseChars(s,i),o){let h=this.currentChannel;if(h&&h>0)this.getChannel(h).insertChars(o);else this.logger.log(2,"No channel found yet. TEXT-MODE?")}}if(!r&&!o)this.logger.log(2,()=>"Couldn't parse cleaned data "+Fl([s,i])+" orig: "+Fl([t[n],t[n+1]]))}}parseCmd(e,t){let n=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=33&&t<=35;if(!(n||s))return!1;let i=e===20||e===21||e===23?1:2,r=this.getChannel(i);if(e===20||e===21||e===28||e===29){if(t===32)r.ccRCL();else if(t===33)r.ccBS();else if(t===34)r.ccAOF();else if(t===35)r.ccAON();else if(t===36)r.ccDER();else if(t===37)r.ccRU(2);else if(t===38)r.ccRU(3);else if(t===39)r.ccRU(4);else if(t===40)r.ccFON();else if(t===41)r.ccRDC();else if(t===42)r.ccTR();else if(t===43)r.ccRTD();else if(t===44)r.ccEDM();else if(t===45)r.ccCR();else if(t===46)r.ccENM();else if(t===47)r.ccEOC()}else r.ccTO(t-32);return this.currentChannel=i,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17)n=1;else n=2;if(n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let s=this.channels[n];if(!s)return!1;return s.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Fl([e,t])+")"),!0}return!1}parsePAC(e,t){let n,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,i=(e===16||e===24)&&t>=64&&t<=95;if(!(s||i))return!1;let r=e<=23?1:2;if(t>=64&&t<=95)n=r===1?O_[e]:N_[e];else n=r===1?P_[e]:B_[e];return this.getChannel(r).setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0}interpretPAC(e,t){let n,s={color:null,italics:!1,indent:null,underline:!1,row:e};if(t>95)n=t-96;else n=t-64;if(s.underline=(n&1)===1,n<=13)s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)];else if(n<=15)s.italics=!0,s.color="white";else s.indent=Math.floor((n-16)/2)*4;return s}parseChars(e,t){let n,s=null,i=null;if(e>=25)n=2,i=e-8;else n=1,i=e;if(i>=17&&i<=19){let r;if(i===17)r=t+80;else if(i===18)r=t+112;else r=t+144;this.logger.log(2,()=>"Special char '"+Iv(r)+"' in channel "+n),s=[r]}else if(e>=32&&e<=127)s=t===0?[e]:[e,t];if(s)this.logger.log(3,()=>"Char codes = "+Fl(s).join(","));return s}parseBackgroundAttributes(e,t){let n=(e===16||e===24)&&t>=32&&t<=47,s=(e===23||e===31)&&t>=45&&t<=47;if(!(n||s))return!1;let i,r={};if(e===16||e===24){if(i=Math.floor((t-32)/2),r.background=H_[i],t%2===1)r.background=r.background+"_semi"}else if(t===45)r.background="transparent";else if(r.foreground="black",t===47)r.underline=!0;let o=e<=23?1:2;return this.getChannel(o).setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];if(t)t.reset()}Dd(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];if(n)n.cueSplitAtTime(e)}}}function Dd(e,t,n){n.a=e,n.b=t}function U_(e,t,n){return n.a===e&&n.b===t}function z_(){return{a:null,b:null}}class oh{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){if(this.startTime===null)return;this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null}newCue(e,t,n){if(this.startTime===null||this.startTime>e)this.startTime=e;this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Fv{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=K3(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(O.FRAG_LOADING,this.onFragLoading,this),e.on(O.FRAG_LOADED,this.onFragLoaded,this),e.on(O.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(O.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(O.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(O.BUFFER_APPENDED,this.onBufferAppended,this),e.on(O.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(O.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(O.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(O.FRAG_LOADING,this.onFragLoading,this),e.off(O.FRAG_LOADED,this.onFragLoaded,this),e.off(O.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(O.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(O.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(O.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(O.BUFFER_APPENDED,this.onBufferAppended,this),e.off(O.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new oh(this,"textTrack1"),t=new oh(this,"textTrack2"),n=new oh(this,"textTrack3"),s=new oh(this,"textTrack4");this.cea608Parser1=new S1(1,e,t),this.cea608Parser2=new S1(3,n,s)}addCues(e,t,n,s,i){let r=!1;for(let l=i.length;l--;){let c=i[l],h=G_(c[0],c[1],t,n);if(h>=0){if(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],n),r=!0,h/(n-t)>0.5)return}}if(!r)i.push([t,n]);if(this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let c=this.Cues.newCue(null,t,n,s);if(c.length)l.push.apply(l,c)}else{let c=this.captionsTracks[e].track;this.Cues.newCue(c,t,n,s)}}else{var o;let l=this.Cues.newCue(null,t,n,s),c=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(O.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:c})}}onInitPtsFound(e,{id:t,timestampOffsets:n}){let{unparsedVttFrags:s}=this;if(t===kt.MAIN)this.initPTS=n;if(s.length)this.unparsedVttFrags=[],s.forEach((i)=>{if(this.initPTS[i.frag.cc])this.onFragLoaded(O.FRAG_LOADED,i);else this.hls.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i.frag,part:null,error:Error("Subtitle discontinuity domain does not match main")})})}createCaptionsTrack(e){if(this.config.renderTextTracksNatively)this.createNativeTrack(e);else this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:n,cueCache:s,media:i}=this,{label:r,languageCode:o}=t[e];if(i)s[e]=[],n[e]=eb(i,"captions",r,o,"hidden")}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n=t.label,s={_id:e,label:n,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(O.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,n)return;if(this.config.renderTextTracksNatively){let{captionsTracks:s,cueCache:i}=this;for(let r in s)s[r].remove(),delete i[r]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}onManifestLoading(){if(this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=K3(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2)this.cea608Parser1.reset(),this.cea608Parser2.reset()}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!_6(this.tracks,n)){let s=n.map((i)=>({label:i.name,kind:i.type.toLowerCase(),default:i.default,subtitleTrack:i}));this.hls.trigger(O.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}this.tracks=n}onManifestLoaded(e,t){if(this.config.enableCEA708Captions&&t.captions)t.captions.forEach((n)=>{let s=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!s)return;let i=`textTrack${s[1]}`,r=this.captionsProperties[i];if(!r)return;if(r.label=n.name,n.lang)r.languageCode=n.lang;r.media=n})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===kt.MAIN){var n,s;let{cea608Parser1:i,cea608Parser2:r,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(n=(s=t.part)==null?void 0:s.index)!=null?n:-1;if(i&&r){if(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)i.reset(),r.reset()}this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){let{frag:n,payload:s}=t;if(n.level<this.tracks.length&&n.type===kt.SUBTITLE){var i;if(s.byteLength||(i=n.initSegment)!=null&&(i=i.data)!=null&&i.byteLength){let r=n.decryptdata,o="stats"in t;if(r==null||!r.encrypted||o){let l=this.tracks[n.level],c=this.vttCCs;if(!c[n.cc])c[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc;if((l==null?void 0:l.textCodec)===g1)this._parseIMSC1(t);else this._parseVTTs(t)}}else{let r="part"in t?t.part:null;this.hls.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:r,error:Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:n}=e,s="part"in e?e.part:null,i=this.hls;N3(n,this.initPTS[t.cc],(r)=>{this._appendCues(r,t.level),i.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:s})},(r)=>{i.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${r}`),i.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:s,error:r})})}_parseVTTs(e){var t;let{frag:n,payload:s}=e,i="part"in e?e.part:null,{initPTS:r,unparsedVttFrags:o}=this,l=r.length-1;if(!r[n.cc]&&l===-1){o.push(e);return}let c=this.hls,h=(t=n.initSegment)==null?void 0:t.data,d=h?Rr(h,new Uint8Array(s)).buffer:s;g_(d,this.initPTS[n.cc],this.vttCCs,n.cc,(i&&!h?i:n).start,(m)=>{this._appendCues(m,n.level),c.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n,part:i})},(m)=>{let p=m.message.startsWith("Missing initPTS");if(c.logger.log(`${p?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${n.sn} @${n.start}): ${m}`),p){o.push(e);return}else if(this.config.enableIMSC1)this._fallbackToIMSC1(e);c.trigger(O.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:i,error:m})})}_fallbackToIMSC1(e){let{frag:t,payload:n}=e,s=this.tracks[t.level];if(!s.textCodec)N3(n,this.initPTS[t.cc],()=>{s.textCodec=g1,this._parseIMSC1(e)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){var s;let i=(s=this.tracks[t].trackNode)==null?void 0:s.track;if(!i||i.mode==="disabled")return;e.forEach((r)=>b1(i,r))}else{let i=this.tracks[t];if(!i)return;let r=i.default?"default":"subtitles"+t;n.trigger(O.CUES_PARSED,{type:"subtitles",cues:e,track:r,subtitleTrack:i})}}onFragDecrypted(e,t){let{frag:n}=t;if(n.type===kt.SUBTITLE)this.onFragLoaded(O.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:s}=t;if(n.type===kt.MAIN&&this.closedCaptionsForLevel(n)==="NONE")return;for(let i=0;i<s.length;i++){let r=s[i].bytes;if(r){if(!this.cea608Parser1)this.initCea608Parsers();let o=this.extractCea608Data(r);this.cea608Parser1.addData(s[i].pts,o[0]),this.cea608Parser2.addData(s[i].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var n;let{type:s,timeRanges:i}=t;if(s==="video"&&(n=i[s])!=null&&n.length){let{captionsTracks:r,cueCache:o}=this;Object.keys(o).forEach((l)=>{var c;let h=(c=r[l])==null?void 0:c.track;if(h){let d=o[l];for(let m=0;m<d.length;m++)b1(h,d[m])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:n,endOffset:s,endOffsetSubtitles:i,type:r}=t,{media:o}=this;if(!o||o.currentTime<s)return;if(!r||r==="video"){let{captionsTracks:l,cueCache:c}=this;Object.keys(l).forEach((h)=>w1(l[h].track,n,s)),Object.keys(c).forEach((h)=>{let d=c[h];for(let m=d.length;m--;){let p=d[m];if(p.startTime>=n&&p.endTime<=s)d.splice(m,1)}})}if(this.config.renderTextTracksNatively){if(n===0&&i!==void 0)this.tracks.forEach((l)=>{var c;let h=(c=l.trackNode)==null?void 0:c.track;if(h)w1(h,n,i)})}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,s=2;for(let i=0;i<n;i++){let r=e[s++],o=127&e[s++],l=127&e[s++];if(o===0&&l===0)continue;if((4&r)!==0){let h=3&r;if(h===0||h===1)t[h].push(o),t[h].push(l)}}return t}}function G_(e,t,n,s){return Math.min(t,s)-Math.max(e,n)}function K3(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var V_=/\s/,$_={newCue(e,t,n,s){let i=[],r,o,l,c,h,d=self.VTTCue||self.TextTrackCue;for(let p=0;p<s.rows.length;p++)if(r=s.rows[p],l=!0,c=0,h="",!r.isEmpty()){var m;for(let k=0;k<r.chars.length;k++)if(V_.test(r.chars[k].uchar)&&l)c++;else h+=r.chars[k].uchar,l=!1;if(r.cueStartTime=t,t===n)n+=0.0001;if(c>=16)c--;else c++;let b=cv(h.trim()),v=Z1(t,n,b);if(!(e!=null&&(m=e.cues)!=null&&m.getCueById(v)))o=new d(t,n,b),o.id=v,o.line=p+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o)}if(e&&i.length)i.sort((p,b)=>{if(p.line==="auto"||b.line==="auto")return 0;if(p.line>8&&b.line>8)return b.line-p.line;return p.line-b.line}),i.forEach((p)=>b1(e,p));return i}};class ib{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new c0}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,n){let s=this.stats;if(s.loading.start)throw Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}abort(){var e;if(this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort)this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gh(e,t,!0))this.retry(e);else{var n;Rn.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);let s=this.callbacks;if(s)this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails())}}retry(e){let{context:t,stats:n}=this;this.retryDelay=E1(e,n.retry),n.retry++,Rn.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function X_(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}var W_=/(\d+)-(\d+)\/(\d+)/;class k1 extends ib{constructor(e){super();this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||eI}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){if(self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end)this.stats.aborted=!0,this.controller.abort()}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:n}=this;if(!e||!t)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;let s=K_(t,this.controller.signal),i=t.responseType==="arraybuffer",r=i?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&lt(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(Th(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((h)=>{var d;this.response=h;let m=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(m-n.loading.start)),!h.ok){let{status:b,statusText:v}=h;throw new Lv(v||"fetch, bad network response",b,h)}n.loading.first=m,n.total=Z_(h.headers)||n.total;let p=(d=this.callbacks)==null?void 0:d.onProgress;if(p&&lt(e.highWaterMark))return this.loadProgressively(h,n,t,e.highWaterMark,p);if(i)return h.arrayBuffer();if(t.responseType==="json")return h.json();return h.text()}).then((h)=>{var d,m;let p=this.response;if(!p)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);let b=h[r];if(b)n.loaded=n.total=b;let v={url:p.url,data:h,code:p.status},k=(d=this.callbacks)==null?void 0:d.onProgress;if(k&&!lt(e.highWaterMark))k(n,t,h,p);(m=this.callbacks)==null||m.onSuccess(v,n,t,p)}).catch((h)=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;let d=!h?0:h.code||0,m=!h?null:h.message,p=e.loadPolicy.errorRetry,b=n.retry,v={url:t.url,data:void 0,code:d};if(gh(p,b,!1,v))this.retry(p);else{var k;Rn.error(`${d} while loading ${t.url}`),(k=this.callbacks)==null||k.onError({code:d,text:m},t,h?h.details:null,n)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,s=0,i){let r=new O1,o=e.body.getReader(),l=()=>o.read().then((c)=>{if(c.done){if(r.dataLength)i(t,n,r.flush().buffer,e);return Promise.resolve(new ArrayBuffer(0))}let h=c.value,d=h.length;if(t.loaded+=d,d<s||r.dataLength){if(r.push(h),r.dataLength>=s)i(t,n,r.flush().buffer,e)}else i(t,n,h.buffer,e);return l()}).catch(()=>Promise.reject());return l()}}function K_(e,t){let n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Gn({},e.headers))};if(e.rangeEnd)n.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return n}function Q_(e){let t=W_.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Z_(e){let t=e.get("Content-Range");if(t){let s=Q_(t);if(lt(s))return s}let n=e.get("Content-Length");if(n)return parseInt(n)}function eI(e,t){return new self.Request(e.url,t)}class Lv extends Error{constructor(e,t,n){super(e);this.code=void 0,this.details=void 0,this.code=t,this.details=n}}var tI=(e,t,n)=>Math.max(t,Math.min(e,n)),nI=/^age:\s*[\d.]+\s*$/im;class rb extends ib{constructor(e){super();this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;if(self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e){if(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4)this.stats.aborted=!0,e.abort()}}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let i=this.xhrSetup;if(i)Promise.resolve().then(()=>{if(this.loader!==n||this.stats.aborted)return;return i.call(this,n,t.url,t)}).catch((r)=>{if(this.loader!==n||this.stats.aborted)return;return n.open("GET",t.url,!0),i.call(this,n,t.url,t)}).then(()=>{if(this.loader!==n||this.stats.aborted)return;this.openAndSendXhr(n,t,e)}).catch((r)=>{var o;(o=this.callbacks)==null||o.onError({code:n.status,text:r.message},t,n,s);return});else this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){if(!e.readyState)e.open("GET",t.url,!0);let s=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:r}=n.loadPolicy;if(s)for(let o in s)e.setRequestHeader(o,s[o]);if(t.rangeEnd)e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`);e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&lt(i)?i:r,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let s=t.readyState,i=this.config;if(n.aborted)return;if(s>=2){if(n.loading.first===0){if(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs)self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start))}if(s===4){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){let b=h!=null?h:t.response;if(b!=null){var r,o;n.loading.end=Math.max(self.performance.now(),n.loading.first);let v=t.responseType==="arraybuffer"?b.byteLength:b.length;n.loaded=n.total=v,n.bwEstimate=n.total*8000/(n.loading.end-n.loading.first);let k=(r=this.callbacks)==null?void 0:r.onProgress;if(k)k(n,e,b,t);let A={url:t.responseURL,data:b,code:c};if(e.rangeEnd&&v!==e.rangeEnd-e.rangeStart)Rn.warn(`Payload length ${v} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`);(o=this.callbacks)==null||o.onSuccess(A,n,e,t);return}}let d=i.loadPolicy.errorRetry,m=n.retry,p={url:e.url,data:void 0,code:c};if(gh(d,m,!1,p))this.retry(d);else{var l;Rn.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,n)}}}}loadprogress(e){let t=this.stats;if(t.loaded=e.loaded,e.lengthComputable)t.total=e.total}getCacheAge(){let e=null;if(this.loader&&nI.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){if(this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders()))return this.loader.getResponseHeader(e);return null}}var sI={maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:null,errorRetry:null},iI=Ct(Ct({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:0.25,maxBufferSize:60000000,maxFragLookUpTolerance:0.25,maxBufferHole:0.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:0.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:0.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5000,fpsDroppedMonitoringThreshold:0.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:rb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:500000,abrEwmaDefaultEstimateMax:5000000,abrBandWidthFactor:0.95,abrBandWidthUpFactor:0.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:X9,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:sI},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1000,maxRetryDelayMs:8000}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:120000,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1000,maxRetryDelayMs:8000}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:30000,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1000,maxRetryDelayMs:8000}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1000,manifestLoadingMaxRetryTimeout:64000,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1000,levelLoadingMaxRetryTimeout:64000,fragLoadingTimeOut:20000,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1000,fragLoadingMaxRetryTimeout:64000,streamController:tb,abrController:D9,bufferController:M6,capLevelController:V1,errorController:L9,fpsController:iv,id3TrackController:gv,gapController:pv,latencyController:Cv},rI()),{},{subtitleStreamController:jv,subtitleTrackController:mv,timelineController:Fv,audioStreamController:j6,audioTrackController:I6,emeController:Wc,cmcdController:ev,contentSteeringController:tv,iframeController:vv,interstitialsController:Ev});function rI(){return{cueHandler:$_,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function aI(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(t.liveMaxUnchangedPlaylistRefresh!==void 0){let o=t.liveMaxUnchangedPlaylistRefresh,l=tI(o,2,1/0);if(l!==o)n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${o} to ${l}.`);t.liveMaxUnchangedPlaylistRefresh=l}let s=x1(e),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach((o)=>{let l=`${o==="level"?"playlist":o}LoadPolicy`,c=t[l]===void 0,h=[];if(r.forEach((d)=>{let m=`${o}Loading${d}`,p=t[m];if(p!==void 0&&c){h.push(m);let b=s[l].default;switch(t[l]={default:b},d){case"TimeOut":b.maxLoadTimeMs=p,b.maxTimeToFirstByteMs=p;break;case"MaxRetry":b.errorRetry.maxNumRetry=p,b.timeoutRetry.maxNumRetry=p;break;case"RetryDelay":b.errorRetry.retryDelayMs=p,b.timeoutRetry.retryDelayMs=p;break;case"MaxRetryTimeout":b.errorRetry.maxRetryDelayMs=p,b.timeoutRetry.maxRetryDelayMs=p;break}}}),h.length)n.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${l}": ${ls(t[l])}`)}),Ct(Ct({},s),t)}function x1(e){if(e&&typeof e==="object"){if(Array.isArray(e))return e.map(x1);return Object.keys(e).reduce((t,n)=>(t[n]=x1(e[n]),t),{})}return e}function oI(e,t){let n=e.loader;if(n!==k1&&n!==rb)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else if(X_())e.loader=k1,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader")}class Ov extends w0{constructor(e,t){super(e,"level-controller");this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(O.LEVEL_LOADED,this.onLevelLoaded,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(O.FRAG_BUFFERED,this.onFragBuffered,this),e.on(O.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(O.LEVEL_LOADED,this.onLevelLoaded,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(O.FRAG_BUFFERED,this.onFragBuffered,this),e.off(O.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t)=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,s=[],i={},r={},o=!1,l=!1,c=!1,h=!1;t.levels.forEach((d)=>{let m=d.attrs,p=Y3(d,n),{audioCodec:b,videoCodec:v,imageCodec:k,width:A,height:T}=d;if(!p){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}o||(o=!!(A&&T)),l||(l=!!v),c||(c=!!b),h||(h=!!k);let{CODECS:E,"FRAME-RATE":I,"HDCP-LEVEL":_,"PATHWAY-ID":q,RESOLUTION:P,"VIDEO-RANGE":N}=m,V=`${`${q||"."}-`}${d.bitrate}-${P}-${I}-${E}-${N}-${_}`;if(!i[V]){let U=this.createLevel(d);i[V]=U,r[V]=1,s.push(U)}else if(i[V].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let U=r[V]+=1;d.attrs["PATHWAY-ID"]=Array(U+1).join(".");let W=this.createLevel(d);i[V]=W,s.push(W)}else if(!d.iframes)i[V].addGroupId("audio",m.AUDIO),i[V].addGroupId("text",m.SUBTITLES)}),this.filterAndSortMediaOptions(s,t,o,l,c,h)}createLevel(e){let t=new Yc(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!Nv(n.videoCodec,this.hls.config.preferManagedMediaSource)){let s=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(s.message),t.supportedResult=E9(s,[])}return t}filterAndSortMediaOptions(e,t,n,s,i,r){var o;let l=[],c=[],h=e,d=((o=t.stats)==null?void 0:o.parsing)||{},m=this.hls.config.preferManagedMediaSource;if((n||s)&&i)h=h.filter(({videoCodec:_,videoRange:q,width:P,height:N})=>(!!_||!!(P&&N))&&xE(q));if(s&&r)h=h.filter((_)=>!_.imageCodec);if(h.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",q=_;if(t.levels.length)q=`one or more CODECS in variant not supported: ${ls(t.levels.map((N)=>N.attrs.CODECS).filter((N,H,V)=>V.indexOf(N)===H))}`,this.warn(q),_+=` (${q})`;let P=Error(_);this.hls.trigger(O.ERROR,{type:Et.MEDIA_ERROR,details:ve.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:P,reason:q})}}),d.end=performance.now();return}if(t.audioTracks)l=t.audioTracks.filter((_)=>!_.audioCodec||Pv(_.audioCodec,m)),Q3(l);if(t.subtitles)c=t.subtitles,Q3(c);let p=h.slice(0);h.sort((_,q)=>{if(_.attrs["HDCP-LEVEL"]!==q.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(q.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&_.height!==q.height)return _.height-q.height;if(_.frameRate!==q.frameRate)return _.frameRate-q.frameRate;if(_.videoRange!==q.videoRange)return Yd.indexOf(_.videoRange)-Yd.indexOf(q.videoRange);if(_.videoCodec!==q.videoCodec){let P=O5(_.videoCodec),N=O5(q.videoCodec);if(P!==N)return N-P}if(_.uri===q.uri&&_.codecSet!==q.codecSet){let P=Xd(_.codecSet),N=Xd(q.codecSet);if(P!==N)return N-P}if(_.averageBitrate!==q.averageBitrate)return _.averageBitrate-q.averageBitrate;return 0});let b=p[0];if(this.steering){if(h=this.steering.filterParsedLevels(h),h.length!==p.length){for(let _=0;_<p.length;_++)if(p[_].pathwayId===h[0].pathwayId){b=p[_];break}}}this._levels=h;for(let _=0;_<h.length;_++)if(h[_]===b){var v;this._firstLevel=_;let q=b.bitrate,P=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${q}`),((v=this.hls.userConfig)==null?void 0:v.abrEwmaDefaultEstimate)===void 0){let N=Math.min(q,this.hls.config.abrEwmaDefaultEstimateMax);if(N>P&&P===this.hls.abrEwmaDefaultEstimate)this.hls.bandwidthEstimate=N}break}let k=t.iframeVariants.filter((_)=>Y3(_,m));this._iframeVariants=k;let A=i&&!s,T=this.hls.config,E=!!(T.audioStreamController&&T.audioTrackController),I={levels:h,audioTracks:l,subtitleTracks:c,iframeVariants:k,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:s,altAudio:E&&!A&&l.some((_)=>!!_.url)};d.end=performance.now(),this.hls.trigger(O.MANIFEST_PARSED,I)}get iframeVariants(){if(this._iframeVariants.length===0)return null;return this._iframeVariants}get levels(){if(this._levels.length===0)return null;return this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let h=Error("invalid level idx"),d=e<0;if(this.hls.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:h,reason:h.message}),d)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,s=this.currentLevel,i=s?s.attrs["PATHWAY-ID"]:void 0,r=t[e],o=r.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=r,n===e&&s&&i===o)return;this.log(`Switching to level ${e} (${r.height?r.height+"p ":""}${r.videoRange?r.videoRange+" ":""}${r.codecSet?r.codecSet+" ":""}@${r.bitrate})${o?" with Pathway "+o:""} from level ${n}${i?" with Pathway "+i:""}`);let l={level:e,attrs:r.attrs,details:r.details,bitrate:r.bitrate,averageBitrate:r.averageBitrate,maxBitrate:r.maxBitrate,realBitrate:r.realBitrate,width:r.width,height:r.height,codecSet:r.codecSet,audioCodec:r.audioCodec,videoCodec:r.videoCodec,audioGroups:r.audioGroups,subtitleGroups:r.subtitleGroups,loaded:r.loaded,loadError:r.loadError,fragmentError:r.fragmentError,name:r.name,id:r.id,uri:r.uri,url:r.url,urlId:0,audioGroupIds:r.audioGroupIds,textGroupIds:r.textGroupIds};this.hls.trigger(O.LEVEL_SWITCHING,l);let c=r.details;if(!c||c.live){let h=this.switchParams(r.uri,s==null?void 0:s.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){if(this.manualLevelIndex=e,this._startLevel===void 0)this._startLevel=e;if(e!==-1)this.level=e}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;if(e!==void 0)return e;return this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){if(this.steering)return this.steering.pathways();return[]}get pathwayPriority(){if(this.steering)return this.steering.pathwayPriority;return null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),n=e.filter((s)=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){if(t.fatal||!t.context)return;if(t.context.type===fn.LEVEL&&t.context.level===this.level)this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===kt.MAIN){let n=t.elementaryStreams;if(!Object.keys(n).some((i)=>!!n[i]))return;let s=this._levels[t.level];if(s!=null&&s.loadError)this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0}}onLevelLoaded(e,t){var n;let{level:s,details:i}=t,r=t.levelInfo;if(!r){var o;if(this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip)i.deltaUpdateFailed=!0;return}if(r===this.currentLevel||t.withoutMultiVariant){if(r.fragmentError===0)r.loadError=0;let l=r.details;if(l===t.details&&l.advanced)l=void 0;this.playlistLoaded(s,t,l)}else if((n=t.deliveryDirectives)!=null&&n.skip)i.deltaUpdateFailed=!0}loadPlaylist(e){if(super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel))this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],r=e.details,o=r==null?void 0:r.age;this.log(`Loading level index ${s}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${o&&r.live?" age "+o.toFixed(1)+(r.type?" "+r.type||"":""):""} ${n}`),this.hls.trigger(O.LEVEL_LOADING,{url:n,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){if(this.manualLevelIndex!==-1)return this.manualLevelIndex;else return this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let s=this.hls.config.abrSwitchInterval;if(s>0){let i=performance.now(),r=i-this.lastABRSwitchTime,o=s*1000;if(this.lastABRSwitchTime>-1&&r<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms < ${o}ms / ${s}s)`);return}this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(r)}ms >= ${o}ms / ${s}s)`)}}if(this.level=e,this.manualLevelIndex===-1)this.hls.nextAutoLevel=e}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((i,r)=>{if(r!==e)return!0;if(this.steering)this.steering.removeLevel(i);if(i===this.currentLevel){if(this.currentLevel=null,this.currentLevelIndex=-1,i.details)i.details.fragments.forEach((o)=>o.level=-1)}return!1});if(e6(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details)this.currentLevelIndex=this.currentLevel.details.fragments[0].level;if(this.manualLevelIndex>-1)this.manualLevelIndex=this.currentLevelIndex;let s=n.length-1;if(this._firstLevel=Math.min(this._firstLevel,s),this._startLevel)this._startLevel=Math.min(this._startLevel,s);this.hls.trigger(O.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;if(this._maxAutoLevel!==t)this._maxAutoLevel=t,this.hls.trigger(O.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n})}}function Pv(e,t){return vh(e,"audio",t)}function Nv(e,t){return vh(e,"video",t)}function Y3(e,t){let{audioCodec:n,videoCodec:s}=e;if(n)e.audioCodec=n=Wd(n,t)||void 0;if(s)s=e.videoCodec=mE(s);let{unknownCodecs:i}=e;if((i==null?void 0:i.length)||0||n&&!Pv(n,t)||s&&!Nv(s,t))return!1;return!0}function Q3(e){let t={};e.forEach((n)=>{let s=n.groupId||"";n.id=t[s]=t[s]||0,t[s]++})}class Bv extends Ji{constructor(e,t){super("key-loader",t);this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let n in this.keyLoaderInfo){let s=this.keyLoaderInfo[n].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;if(t)t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,n){if(this.emeController)return this.emeController.loadClear(e,t,n);return null}load(e,t){if(!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled)return this.emeController.selectKeySystemFormat(e).then((n)=>this.loadInternal(e,t,n));return this.loadInternal(e,t)}loadInternal(e,t,n){if(n)e.setKeyFormat(n);let s=e.decryptdata;if(!s){let r=Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Wo(e,ve.KEY_LOAD_ERROR,r))}let i=e;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if(s.keyFormat==="identity")return this.loadKeyHTTP(i);return t?t.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(i);default:return Promise.reject(Wo(e,ve.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let n=WT(e.initSegment.data);if(n.length){let s=n[0],i=e.decryptdata.uri;if(s.some((r)=>r!==0))this.log(`Using keyId found in init segment ${Ys(s)} keyUri: ${i}`),ho.setKeyIdForUri(i,s);else{let r=ho.addKeyIdForUri(i);this.log(`Patching empty keyId with ${Ys(r)} keyUri: ${i}`),s=r}e.decryptdata.keyId=s}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Wo(e,ve.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,n=t.uri;if(!n)return Promise.reject(Wo(e,ve.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let s=this.keyLoaderInfo[n];if(s){if(s.decryptdata.key)return t.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then((c)=>(t.key=s.decryptdata.key,Ct(Ct({},c),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ys(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let i=this.config,o=new i.loader(i);e.keyLoader=o;let l=this.keyLoaderInfo[n]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((c,h)=>{let d={type:fn.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:n},m=i.keyLoadPolicy.default,p={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},b={onSuccess:(v,k,A,T)=>{let{frag:E,keyInfo:I,url:_}=A;if(!E.decryptdata||I!==this.keyLoaderInfo[_])return h(Wo(E,ve.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),T));I.decryptdata.key=E.decryptdata.key=new Uint8Array(v.data),E.keyLoader=I.loader=I.keyLoadPromise=null,c({frag:E,keyInfo:I})},onError:(v,k,A,T)=>{this.resetLoader(k),h(Wo(e,ve.KEY_LOAD_ERROR,Error(`HTTP Error ${v.code} loading key ${v.text}`),A,Ct({url:n,data:void 0},v)))},onTimeout:(v,k,A)=>{this.resetLoader(k),h(Wo(e,ve.KEY_LOAD_TIMEOUT,Error("key loading timed out"),A))},onAbort:(v,k,A)=>{this.resetLoader(k),h(Wo(e,ve.INTERNAL_ABORTED,Error("key loading aborted"),A))}};o.load(d,p,b)})}resetLoader(e){let{frag:t,keyInfo:n,url:s}=e,i=n.loader;if(t.keyLoader===i)t.keyLoader=n.loader=n.keyLoadPromise=null;if(delete this.keyLoaderInfo[s],i)i.destroy()}}function Wo(e,t=ve.KEY_LOAD_ERROR,n,s,i){return new sa({type:Et.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:s||null})}function J3(e){let{type:t}=e;switch(t){case fn.AUDIO_TRACK:return kt.AUDIO;case fn.SUBTITLE_TRACK:return kt.SUBTITLE;default:return kt.MAIN}}function Wg(e,t){let n=e.url;if(n===void 0||n.indexOf("data:")===0)n=t.url;return n}class Hv{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(O.MANIFEST_LOADING,this.onManifestLoading,this),e.on(O.LEVEL_LOADING,this.onLevelLoading,this),e.on(O.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(O.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(O.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(O.MANIFEST_LOADING,this.onManifestLoading,this),e.off(O.LEVEL_LOADING,this.onLevelLoading,this),e.off(O.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(O.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(O.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,{pLoader:n,loader:s}=t,r=new(n||s)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){if(this.loaders[e])delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];if(t)t.destroy();this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:fn.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:s,pathwayId:i,url:r,deliveryDirectives:o,levelInfo:l}=t;this.load({id:n,level:s,pathwayId:i,responseType:"text",type:fn.LEVEL,url:r,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:n,groupId:s,url:i,deliveryDirectives:r,track:o}=t;this.load({id:n,groupId:s,level:null,responseType:"text",type:fn.AUDIO_TRACK,url:i,deliveryDirectives:r,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:s,url:i,deliveryDirectives:r,track:o}=t;this.load({id:n,groupId:s,level:null,responseType:"text",type:fn.SUBTITLE_TRACK,url:i,deliveryDirectives:r,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[fn.LEVEL];if(n){let s=n.context;if(s&&!t.levels.some((i)=>i===s.levelOrTrack))n.abort(),delete this.loaders[fn.LEVEL]}}load(e){var t;let n=this.hls.config,s=this.getInternalLoader(e);if(s){let c=this.hls.logger,h=s.context;if((h==null?void 0:h.levelOrTrack)===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){if(h.url===e.url)c.log(`[playlist-loader]: ignore ${e.url} ongoing request`);else c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let i;if(e.type===fn.MANIFEST)i=n.manifestLoadPolicy.default;else i=Gn({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null});if(s=this.createInternalLoader(e),lt((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===fn.LEVEL&&e.level!==null)c=this.hls.levels[e.level].details;else if(e.type===fn.AUDIO_TRACK&&e.id!==null)c=this.hls.audioTracks[e.id].details;else if(e.type===fn.SUBTITLE_TRACK&&e.id!==null)c=this.hls.subtitleTracks[e.id].details;if(c){let h=c.partTarget,d=c.targetduration;if(h&&d){let m=Math.max(h*3,d*0.8)*1000;i=Gn({},i,{maxTimeToFirstByteMs:Math.min(m,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,i.maxTimeToFirstByteMs)})}}}let r=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:r.maxNumRetry||0,retryDelay:r.retryDelayMs||0,maxRetryDelay:r.maxRetryDelayMs||0},l={onSuccess:(c,h,d,m)=>{let p=this.getInternalLoader(d);this.resetInternalLoader(d.type);let b=c.data;if(h.parsing.start=performance.now(),_a.isMediaPlaylist(b)||d.type!==fn.MANIFEST)this.handleTrackOrLevelPlaylist(c,h,d,m||null,p);else this.handleMasterPlaylist(c,h,d,m)},onError:(c,h,d,m)=>{this.handleNetworkError(h,d,!1,c,m)},onTimeout:(c,h,d)=>{this.handleNetworkError(h,d,!0,void 0,c)}};s.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;if(e||n)this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t)}handleMasterPlaylist(e,t,n,s){let i=this.hls,r=e.data,o=Wg(e,n),l=_a.parseMasterPlaylist(r,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,l.playlistParsingError,s,t);return}let{contentSteering:c,levels:h,iframeVariants:d,sessionData:m,sessionKeys:p,startTimeOffset:b,variableList:v}=l;this.variableList=v,h.forEach((E)=>{let{unknownCodecs:I}=E;if(I){let{preferManagedMediaSource:_}=this.hls.config,{audioCodec:q,videoCodec:P}=E;for(let N=I.length;N--;){let H=I[N];if(vh(H,"audio",_))E.audioCodec=q=q?`${q},${H}`:H,Kc.audio[q.substring(0,4)]=2,I.splice(N,1);else if(vh(H,"video",_))E.videoCodec=P=P?`${P},${H}`:H,Kc.video[P.substring(0,4)]=2,I.splice(N,1)}}});let{AUDIO:k=[],SUBTITLES:A,"CLOSED-CAPTIONS":T}=_a.parseMasterPlaylistMedia(r,o,l);if(k.length){if(!k.some((I)=>!I.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO)this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),k.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new vs({}),bitrate:0,url:""})}i.trigger(O.MANIFEST_LOADED,{levels:h,audioTracks:k,subtitles:A,iframeVariants:d,captions:T,contentSteering:c,url:o,stats:t,networkDetails:s,sessionData:m,sessionKeys:p,startTimeOffset:b,variableList:v})}handleTrackOrLevelPlaylist(e,t,n,s,i){let r=this.hls,{id:o,level:l,type:c}=n,h=Wg(e,n),d=lt(l)?l:lt(o)?o:0,m=J3(n),p=_a.parseLevelPlaylist(e.data,h,d,m,0,this.variableList);if(c===fn.MANIFEST){let b={attrs:new vs({}),bitrate:0,details:p,name:"",url:h};p.requestScheduled=t.loading.start+Q9(p,0),r.trigger(O.MANIFEST_LOADED,{levels:[b],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=p,this.handlePlaylistLoaded(p,e,t,n,s,i)}handleManifestParsingError(e,t,n,s,i){this.hls.trigger(O.ERROR,{type:Et.NETWORK_ERROR,details:ve.MANIFEST_PARSING_ERROR,fatal:t.type===fn.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:s,stats:i})}handleNetworkError(e,t,n=!1,s,i){let r=`A network ${n?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;if(e.type===fn.LEVEL)r+=`: ${e.level} id: ${e.id}`;else if(e.type===fn.AUDIO_TRACK||e.type===fn.SUBTITLE_TRACK)r+=` id: ${e.id} group-id: "${e.groupId}"`;let o=Error(r);this.hls.logger.warn(`[playlist-loader]: ${r}`);let l=ve.UNKNOWN,c=!1,h=this.getInternalLoader(e);switch(e.type){case fn.MANIFEST:l=n?ve.MANIFEST_LOAD_TIMEOUT:ve.MANIFEST_LOAD_ERROR,c=!0;break;case fn.LEVEL:l=n?ve.LEVEL_LOAD_TIMEOUT:ve.LEVEL_LOAD_ERROR,c=!1;break;case fn.AUDIO_TRACK:l=n?ve.AUDIO_TRACK_LOAD_TIMEOUT:ve.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case fn.SUBTITLE_TRACK:l=n?ve.SUBTITLE_TRACK_LOAD_TIMEOUT:ve.SUBTITLE_LOAD_ERROR,c=!1;break}if(h)this.resetInternalLoader(e.type);let d={type:Et.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:i};if(s){let m=e.url;if(t&&"url"in t)m=t.url;d.response=Ct({url:m,data:void 0},s)}this.hls.trigger(O.ERROR,d)}handlePlaylistLoaded(e,t,n,s,i,r){let o=this.hls,{type:l,level:c,levelOrTrack:h,id:d,groupId:m,deliveryDirectives:p}=s,b=Wg(t,s),v=J3(s),k=typeof s.level==="number"&&v===kt.MAIN?c:void 0;if(h&&"iframes"in h&&h.iframes&&!e.iframesOnly)e.playlistParsingError=Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0;let A=e.playlistParsingError;if(A){if(this.hls.logger.warn(`${A} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(O.ERROR,{type:Et.NETWORK_ERROR,details:ve.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:A,reason:A.message,response:t,context:s,level:k,parent:v,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=Error("No Segments found in Playlist");o.trigger(O.ERROR,{type:Et.NETWORK_ERROR,details:ve.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:T,reason:T.message,response:t,context:s,level:k,parent:v,networkDetails:i,stats:n});return}if(e.live&&r){if(r.getCacheAge)e.ageHeader=r.getCacheAge()||0;if(!r.getCacheAge||isNaN(e.ageHeader))e.ageHeader=0}switch(l){case fn.MANIFEST:case fn.LEVEL:if(k){if(!h)k=0;else if(h!==o.levels[k]){let T=o.levels.indexOf(h);if(T>-1)k=T}}o.trigger(O.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:k||0,id:d||0,stats:n,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:l===fn.MANIFEST,context:s});break;case fn.AUDIO_TRACK:o.trigger(O.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:m||"",stats:n,networkDetails:i,deliveryDirectives:p,context:s});break;case fn.SUBTITLE_TRACK:o.trigger(O.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:m||"",stats:n,networkDetails:i,deliveryDirectives:p,context:s});break}}}class es{static get version(){return xh}static isMSESupported(){return wv()}static isSupported(){return C_()}static getMediaSource(){return Zo()}static get Events(){return O}static get MetadataSchema(){return zi}static get ErrorTypes(){return Et}static get ErrorDetails(){return ve}static get DefaultConfig(){if(!es.defaultConfig)return iI;return es.defaultConfig}static set DefaultConfig(e){es.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new P1,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=vT(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),n=this.config=aI(es.DefaultConfig,e,t);if(this.userConfig=e,n.progressive)oI(n,t);let{streamController:s,abrController:i,bufferController:r,capLevelController:o,errorController:l,fpsController:c,id3TrackController:h,iframeController:d,gapController:m}=n,p=new l(this),b=this.abrController=new i(this),v=new P9(this),k=n.interstitialsController,A=k?this.interstitialsController=new k(this,es):null,T=r?this.bufferController=new r(this,v):null,E=o?this.capLevelController=new o(this):null,I=c?new c(this):null,_=n.cmcdController,q=_?this.cmcdController=new _(this):null,P=new Hv(this),N=n.contentSteeringController,H=N?new N(this):null,V=this.levelController=new Ov(this,H),U=h?new h(this):void 0,W=new Bv(this.config,this.logger),ce=this.streamController=new s(this,v,W),ue=this.gapController=m?new m(this,v):void 0;if(E)E.setStreamController(ce);let oe=[P,V,ce];if(A)oe.splice(1,0,A);if(H)oe.splice(1,0,H);this.networkControllers=oe;let ae=[b];if(T)ae.push(T);if(ue)ae.push(ue);if(E)ae.push(E);if(I)I.setStreamController(ce),ae.push(I);if(U)ae.push(U);ae.push(v),this.audioTrackController=this.createController(n.audioTrackController,oe);let te=n.audioStreamController;if(te)oe.push(this.audioStreamController=new te(this,v,W));this.subtitleTrackController=this.createController(n.subtitleTrackController,oe);let me=n.subtitleStreamController;if(me)oe.push(this.subtititleStreamController=new me(this,v,W));if(this.createController(n.timelineController,ae),W.emeController=this.emeController=this.createController(n.emeController,ae),q)ae.push(q);this.latencyController=this.createController(n.latencyController,ae),this.coreComponents=ae,this.iframeController=d?new d(this,es):void 0,oe.push(p);let he=p.onErrorOut;if(typeof he==="function")this.on(O.ERROR,he,p);this.on(O.MANIFEST_LOADED,P.onManifestLoaded,P)}createController(e,t){if(e){let n=new e(this);if(t)t.push(n);return n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,s){this._emitter.off(e,t,n,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);else try{return this.emit(e,e,t)}catch(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;let s=e===O.ERROR;this.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.INTERNAL_EXCEPTION,fatal:s,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(O.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((t)=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach((t)=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let i=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(O.ERROR,{type:Et.OTHER_ERROR,details:ve.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}if(this.logger.log("attachMedia"),this._media)this.logger.warn("media must be detached before attaching"),this.detachMedia();let t="media"in e,n=t?e.media:e,s=t?e:{media:n};this._media=n,this.trigger(O.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(O.MEDIA_DETACHING,e),this._media=null,this.trigger(O.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,n={transferMedia:t};return this.trigger(O.MEDIA_DETACHING,n),this.trigger(O.MEDIA_DETACHED,n),t}loadSource(e){var t;this.stopLoad();let n=this.media,s=this._url,i=this._url=A1.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});if(this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&s&&(s!==i||(t=this.bufferController)!=null&&t.hasSourceTypes()))this.detachMedia(),this.attachMedia(n);this.trigger(O.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length;n++)if(this.networkControllers[n].startLoad(e,t),!this.started||!this.networkControllers)break}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length;e++)if(this.networkControllers[e].stopLoad(),this.started||!this.networkControllers)break}get loadingEnabled(){return this.started&&this.streamController.state!==Me.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){if(!this.bufferingEnabled)this.logger.log("resume buffering"),this.networkControllers.forEach((e)=>{if(e.resumeBuffering)e.resumeBuffering()})}pauseBuffering(){if(this.bufferingEnabled)this.logger.log("pause buffering"),this.networkControllers.forEach((e)=>{if(e.pauseBuffering)e.pauseBuffering()})}get inFlightFragments(){let e={[kt.MAIN]:this.streamController.inFlightFrag};if(this.audioStreamController)e[kt.AUDIO]=this.audioStreamController.inFlightFrag;if(this.subtititleStreamController)e[kt.SUBTITLE]=this.subtititleStreamController.inFlightFrag;return e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,n=e==null?void 0:e.currentTime;if(this.detachMedia(),e){if(this.attachMedia(e),t){if(n)this.startLoad(n);else if(!this.config.autoStartLoad)this.startLoad()}}}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;if(!e)e=this._sessionId=o9();return e}get levels(){let e=this.levelController.levels;return e?e:[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;if(e===-1&&this.abrController.forcedAutoLevel>-1)return this.abrController.forcedAutoLevel;return e}set startLevel(e){if(this.logger.log(`set startLevel:${e}`),e!==-1)e=Math.max(e,this.minAutoLevel);this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,n=!!e;if(t&&n!==this.config.capLevelToPlayerSize){if(n)t.startCapping();else t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch();this.config.capLevelToPlayerSize=n}}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.getEstimate()}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.defaultEstimate}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;if(!e)return NaN;return e.getEstimateTTFB()}set autoLevelCapping(e){if(this._autoLevelCapping!==e)this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated()}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){if(kE(e)&&this._maxHdcpLevel!==e)this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated()}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let s=0;s<n;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,s;if(t===-1&&e!=null&&e.length)s=e.length-1;else s=t;if(n)for(let i=s;i--;){let r=e[i].attrs["HDCP-LEVEL"];if(r&&r<=n)return i}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;if(t)t.audioTrack=e}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;if(t)t.nextAudioTrack=e}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;if(t)t.subtitleTrack=e}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;if(t)t.subtitleDisplay=e}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){if(!this.latencyController)return;this.latencyController.targetLatency=e}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){if(this.interstitialsController)return this.interstitialsController.interstitialsManager;return null}get iframeVariants(){let e=this.levelController.iframeVariants;return e?e:[]}createIFramePlayer(e){if(this._url&&this.iframeController)return this.iframeController.createIFramePlayer(e);return null}createImageIFramePlayer(e){if(this._url&&this.iframeController)return this.iframeController.createImageIFramePlayer(e);return null}getMediaDecodingInfo(e,t=this.allAudioTracks){let n=I9(t);return C9(e,n,navigator.mediaCapabilities)}}es.defaultConfig=void 0;Z();var lI=1000;function v0(e,t,n,s){let[i,r]=w(0),o=M(!1),l=M(!1),c=M(null),h=M(i);h.current=i,S(()=>{r(0);let m=e.current;if(!m)return;let p=()=>{l.current=!0},b=()=>{l.current=!1};return m.addEventListener("play",p),m.addEventListener("pause",b),l.current=!m.paused,()=>{m.removeEventListener("play",p),m.removeEventListener("pause",b)}},[e.current]),S(()=>{let m=e.current;if(!m)return;let p=null,b=null,v=!0,k=Date.now(),A=!1,T=-1,E=()=>{k=Date.now(),A=!1,T=-1},I=()=>{if(!v)return;if(m.paused||m.ended)return;let N=m,H=!!N.requestVideoFrameCallback,V=Vd(t),U=Date.now()-k,W=A&&U>V,ce=!A&&U>lI;if(s||!H||W||ce){let oe=Math.floor(m.currentTime*t+0.45),ae=Math.max(0,Math.min(oe,n-1));r(ae)}if(b=requestAnimationFrame(I),N.requestVideoFrameCallback&&p===null)p=N.requestVideoFrameCallback((oe,ae)=>{p=null,k=Date.now(),A=!0,T=ae.mediaTime;let te=Math.floor(ae.mediaTime*t+0.45),me=Math.max(0,Math.min(te,n-1));r(me)})},_=()=>{E(),I()},q=()=>{if(p!==null){let ce=m;if(ce.cancelVideoFrameCallback)try{ce.cancelVideoFrameCallback(p)}catch{}p=null}if(b!==null)cancelAnimationFrame(b),b=null;let N=Vd(t),V=A&&T>=0&&Date.now()-k<=N?T:m.currentTime,U=Math.floor(V*t+0.45),W=Math.max(0,Math.min(U,n-1));if(r(W),!m.ended){let ce=Ia(W,t);m.currentTime=ce}},P=()=>{r(n-1)};if(m.addEventListener("play",_),m.addEventListener("pause",q),m.addEventListener("ended",P),!m.paused)E(),I();return()=>{if(v=!1,m.removeEventListener("play",_),m.removeEventListener("pause",q),m.removeEventListener("ended",P),p!==null){let N=m;if(N.cancelVideoFrameCallback)try{N.cancelVideoFrameCallback(p)}catch{}}if(b!==null)cancelAnimationFrame(b)}},[e.current,t,n]);let d=Q(async(m)=>{let p=e.current;if(!p)return;let b=Math.round(m),v=Math.max(0,Math.min(b,n-1));if(o.current){c.current=v,r(v);return}o.current=!0,r(v);let k=async(A)=>{let T=Ia(A,t),E=!p.paused;if(p.currentTime=T,await new Promise((P)=>{let N=null,H=()=>{if(N)clearTimeout(N);p.removeEventListener("seeked",H),P()};p.addEventListener("seeked",H),N=setTimeout(()=>{p.removeEventListener("seeked",H),P()},500)}),!E&&!l.current)p.pause();let I=Math.floor(p.currentTime*t+0.45),_=Math.max(0,Math.min(I,n-1));r(_);let q=p;if(q.requestVideoFrameCallback)q.requestVideoFrameCallback((P,N)=>{let H=Math.floor(N.mediaTime*t+0.45),V=Math.max(0,Math.min(H,n-1));r(V)});if(c.current!==null){let P=c.current;c.current=null,await k(P)}else o.current=!1};await k(v)},[e,t,n]);return S(()=>{let m=(p)=>{let b=p.target;if(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement||b.isContentEditable)return;if(p.key==="ArrowRight"){p.preventDefault();let v=p.shiftKey?10:1;d(h.current+v)}else if(p.key==="ArrowLeft"){p.preventDefault();let v=p.shiftKey?10:1;d(h.current-v)}};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[d]),S(()=>{let m=e.current;if(!m)return;let p=()=>{if(!o.current){let b=Math.floor(m.currentTime*t+0.45),v=Math.max(0,Math.min(b,n-1));r(v);let k=Ia(v,t),A=1/t;if(Math.abs(m.currentTime-k)>A/4)m.currentTime=k}};return m.addEventListener("seeked",p),()=>{m.removeEventListener("seeked",p)}},[e.current,t,n]),{currentFrame:i,setCurrentFrame:r,seekToFrame:d,isSeeking:o}}Z();var cI=(e)=>{if(isNaN(e))return"00:00";let t=new Date(e*1000),n=t.getUTCHours(),s=t.getUTCMinutes(),i=t.getUTCSeconds().toString().padStart(2,"0");if(n)return`${n}:${s.toString().padStart(2,"0")}:${i}`;return`${s}:${i}`},fI=({totalFrames:e,currentFrame:t,fps:n,previewUrl:s,onSeek:i,buffered:r=0,metadata:o})=>{let l=M(null),c=M(null),[h,d]=w(null),[m,p]=w(!1),[b,v]=w(!1),k=M(i);S(()=>{k.current=i},[i]),S(()=>{if(c.current&&s)c.current.load()},[s]);let A=Q((U)=>{if(!l.current)return 0;let W=l.current.getBoundingClientRect();return Math.max(0,Math.min(U-W.left,W.width))/W.width},[]),T=Q((U)=>{if(b)return;if(!l.current)return;let W=l.current.getBoundingClientRect(),ue=Math.max(0,Math.min(U.clientX-W.left,W.width))/W.width;if(d(ue),p(!0),c.current&&e){let oe=ue*e,ae=1/n,te=oe*ae+ae/2,me=c.current;if(Number.isFinite(te))me.currentTime=te}},[e,n,b]),E=()=>{if(!b)p(!1),d(null)},I=(U)=>{if(U.button!==0)return;U.preventDefault(),v(!0);let W=A(U.clientX);d(W),p(!0),k.current(W*e)},_=(U)=>{v(!0);let W=A(U.touches[0].clientX);d(W),p(!0),k.current(W*e)};S(()=>{if(!b)return;let U=(oe)=>{let ae=A(oe.clientX);if(d(ae),p(!0),c.current&&e){let te=ae*e,me=1/n,he=te*me+me/2,we=c.current;if(Number.isFinite(he))we.currentTime=he}k.current(ae*e)},W=(oe)=>{v(!1);let ae=!1;if(l.current){let me=l.current.getBoundingClientRect();ae=oe.clientX>=me.left&&oe.clientX<=me.right&&oe.clientY>=me.top&&oe.clientY<=me.bottom}if(!ae)p(!1),d(null);let te=A(oe.clientX);k.current(te*e)},ce=(oe)=>{if(oe.touches.length===0)return;let ae=A(oe.touches[0].clientX);if(d(ae),p(!0),c.current&&e){let te=ae*e,me=1/n,he=te*me+me/2,we=c.current;if(Number.isFinite(he))we.currentTime=he}k.current(ae*e)},ue=(oe)=>{v(!1);let ae=oe.changedTouches.length>0?oe.changedTouches[0].clientX:null,te=oe.changedTouches.length>0?oe.changedTouches[0].clientY:null,me=!1;if(ae!==null&&te!==null&&l.current){let he=l.current.getBoundingClientRect();me=ae>=he.left&&ae<=he.right&&te>=he.top&&te<=he.bottom}if(!me)p(!1),d(null);if(ae!==null){let he=A(ae);k.current(he*e)}};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",W),window.addEventListener("touchmove",ce,{passive:!0}),window.addEventListener("touchend",ue),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",W),window.removeEventListener("touchmove",ce),window.removeEventListener("touchend",ue)}},[b,e,n,A]);let q=b&&h!==null?h*100:e>0?t/e*100:0,P=h!==null?h*100:0,N=()=>{if(h===null)return{};return{left:`${P}%`,transform:`translateX(-${P}%)`}},H=180,V={width:`${H}px`,height:"auto"};if(o&&o.originalWidth&&o.originalHeight){let{originalWidth:U,originalHeight:W}=o;if(U>=W){let ce=H*W/U;V={width:`${H}px`,height:`${ce}px`}}else V={width:`${H*U/W}px`,height:`${H}px`}}return g("div",{ref:l,className:"group relative h-1.5 w-full cursor-pointer touch-none rounded-full bg-muted transition-colors duration-200",onMouseMove:T,onMouseLeave:E,onMouseDown:I,onTouchStart:_,"data-testid":"seekbar",children:[a("video",{ref:c,src:s,className:"hidden",preload:"auto",muted:!0,playsInline:!0}),m&&e>0&&a("div",{className:"pointer-events-none absolute bottom-full z-50 mb-3 flex w-max flex-col",style:N(),children:g("div",{className:"relative overflow-hidden rounded-lg border-2 border-border bg-popover shadow-2xl",children:[a("video",{src:s,className:"bg-black object-cover",style:V,muted:!0,ref:(U)=>{if(U&&c.current)U.currentTime=c.current.currentTime}}),a("div",{className:"absolute bottom-0 w-full bg-popover/80 py-0.5 text-center text-xs font-medium text-popover-foreground",children:cI(h*e/n)})]})}),a("div",{className:"absolute top-0 left-0 h-full rounded-full bg-muted-foreground/30 transition-all duration-200",style:{width:`${r}%`}}),m&&a("div",{className:"absolute top-0 left-0 h-full rounded-full bg-primary/30",style:{width:`${P}%`}}),a("div",{className:"relative absolute top-0 left-0 h-full rounded-full bg-primary",style:{width:`${q}%`},"data-testid":"seekbar-fill",children:a("div",{className:B("absolute top-1/2 right-0 h-3.5 w-3.5 -translate-y-1/2 translate-x-1/2 rounded-full border border-border bg-primary shadow-md transition-transform duration-100",m||b?"scale-100":"scale-0 group-hover:scale-100")})})]})},S0=fI;var $d=({state:e,zoom:t,isControlsVisible:n,buffered:s,data:i,resolutions:r,togglePlay:o,toggleLoop:l,toggleMute:c,handleVolumeChange:h,changePlaybackRate:d,changeResolution:m,handleDownload:p,toggleFullScreen:b,onZoomChange:v,onZoomReset:k,frameRate:A,totalFrames:T,currentFrame:E,seekToFrame:I,floatOverlayInFullScreen:_=!0,onMouseEnter:q,onMouseLeave:P,allowDownload:N=!0,isLoading:H})=>{let V=H??e.isLoading??!1,{videoTimeDisplayMode:U,setVideoTimeDisplayMode:W}=ar();if(!i.media?.metadata)return null;let ce=e.isFullScreen&&_,ue=i.proxyType==="audio",oe=i.media?.metadata?.startTimecode,ae=Math.max(0,T-1),te=U==="frames"?`${E} / ${ae} fr`:U==="standard"?`${ro(E,A,"standard")} / ${fi(T/A)}`:`${ro(E,A,U,oe)} / ${ro(ae,A,U,oe)}`;return a("div",{className:B("transition-all duration-300 ease-in-out z-20 text-foreground",ce?"absolute bottom-0 left-0 right-0 px-4 py-4 bg-card/90 backdrop-blur-md border-t border-border":"relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200",n?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"),onMouseEnter:q,onMouseLeave:P,children:g("div",{className:B("transition-opacity duration-200",V&&"pointer-events-none opacity-60 select-none"),children:[a("div",{className:"mb-4 px-1",children:a(S0,{totalFrames:T,currentFrame:E,fps:A,buffered:s,previewUrl:i.media.videoPreview?.url,onSeek:I,metadata:{...i.media.metadata,frameRate:A}})}),g("div",{className:"flex items-center justify-between text-foreground",children:[g("div",{className:"flex items-center gap-4",children:[a("button",{onClick:o,className:"hover:text-primary transition-colors","data-testid":"play-toggle","data-playing":e.isPlaying,"aria-label":e.isPlaying?"Pause":"Play",children:e.isPlaying?a(Mc,{className:"w-6 h-6 fill-current"}):a(ya,{className:"w-6 h-6 fill-current"})}),a("button",{onClick:l,className:B("transition-colors",e.isLooping?"text-primary":"text-muted-foreground"),title:"Loop",children:a(cd,{className:"w-5 h-5"})}),g("div",{className:"flex items-center gap-3 group/vol",children:[a("button",{onClick:c,className:"hover:text-primary",children:e.isMuted||e.volume===0?a(dd,{className:"w-6 h-6"}):a(ud,{className:"w-6 h-6"})}),a("div",{className:"w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out",children:a("div",{className:"w-24 px-1",children:a(_s,{value:e.isMuted?[0]:[e.volume],onValueChange:(me)=>h(me[0]),max:1,step:0.05})})})]}),g("div",{className:"flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]",children:[a("span",{className:"text-muted-foreground font-mono","data-testid":"time-readout",children:te}),g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:a("button",{className:"h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none",children:a(Be,{className:"h-3.5 w-3.5"})})}),g(Fe,{align:"start",className:"w-40 z-30",children:[a(En,{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider",children:"Format"}),g(de,{onClick:()=>W("standard"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:"Standard Time"}),U==="standard"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]}),g(de,{onClick:()=>W("frames"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:"Frames"}),U==="frames"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]}),g(de,{onClick:()=>W("timecode"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:"Timecode"}),U==="timecode"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]})]})]})]})]}),g("div",{className:"relative flex items-center gap-3",children:[!ue&&g("div",{className:"flex items-center gap-1",children:[g("div",{className:"flex items-center gap-1 rounded-md bg-muted p-0.5",children:[a("button",{onClick:()=>v(t*0.8),className:"p-1 hover:text-primary rounded",title:yg(),children:a(ss,{size:14})}),g("span",{className:"text-xs w-8 text-center tabular-nums",children:[Math.round(t*100),"%"]}),a("button",{onClick:()=>v(t*1.2),className:"p-1 hover:text-primary rounded",title:_g(),children:a(Re,{size:14})})]}),a("button",{onClick:k,className:"text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors",children:fh()})]}),g(De,{children:[a(Ne,{asChild:!0,children:g("button",{className:"w-8 text-sm font-bold hover:text-primary",children:[e.playbackRate,"x"]})}),a(Fe,{children:[0.5,1,1.5,2].map((me)=>g(de,{onClick:()=>d(me),className:B("rounded py-1 px-2 text-left text-xs",e.playbackRate===me?"bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground":"text-foreground"),children:[me,"x"]},me))})]}),!ue&&r.length>0&&g(De,{children:[a(Ne,{asChild:!0,children:g("button",{className:"flex items-center gap-1.5 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors",children:[a(xa,{className:"h-3.5 w-3.5"}),g("span",{className:"flex items-center gap-1",children:[a("span",{children:e.currentResolution==="Auto"?e.activeAutoResolution?`${Vc()} (${e.activeAutoResolution})`:Vc():e.currentResolution==="Original"?Zl():e.currentResolution}),e.isCurrentHdr&&a("span",{className:"px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30",children:wd()})]})]})}),g(Fe,{children:[a(En,{children:F0()}),i.media?.isHls&&a(de,{onClick:()=>m({resolution:"Auto",width:i.media?.metadata?.originalWidth??0,height:i.media?.metadata?.originalHeight??0}),className:B("flex w-full items-center justify-between cursor-pointer",e.currentResolution==="Auto"?"text-primary font-medium":"text-foreground"),children:a("span",{children:Vc()})}),r.map((me)=>{let he=`${me.resolution}-${me.hdr?"hdr":"sdr"}`,we=e.currentResolution===me.resolution&&Boolean(e.isCurrentHdr)===Boolean(me.hdr),be=Boolean(i.media?.isHls)&&e.isHlsManualSupported===!1;return g(de,{disabled:be,onClick:()=>!be&&m(me),className:B("flex w-full items-center justify-between",we?"text-primary font-medium":"text-foreground",be?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[g("div",{className:"flex items-center gap-1.5",children:[a("span",{children:me.resolution==="Original"?Zl():me.resolution}),me.hdr&&a("span",{className:"px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30",children:wd()})]}),g("span",{className:"pl-5 text-xs text-muted-foreground",children:[me.width,"x",me.height]})]},he)})]})]}),N&&(ue?a("button",{onClick:()=>p(i.media?.original?.key||""),className:"transition-colors hover:text-primary",title:Dr(),disabled:!i.media?.original?.key,children:a(Bt,{className:"h-5 w-5"})}):g(De,{children:[a(Ne,{asChild:!0,children:a("button",{className:"transition-colors hover:text-primary",title:Dr(),children:a(Bt,{className:"h-5 w-5"})})}),g(Fe,{children:[a(En,{children:Dr()}),(i.media?.videoTranscodes&&i.media.videoTranscodes.length>0?i.media.videoTranscodes:r).map((me)=>{let he=ii(me),we=me.key||`${he}-${me.hdr?"hdr":"sdr"}`;return g(de,{onClick:()=>p(me.key??""),className:"flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground cursor-pointer",children:[g("div",{className:"flex items-center gap-1.5",children:[a("span",{children:he}),me.hdr&&a("span",{className:"px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30",children:wd()})]}),a("span",{className:"text-xs text-muted-foreground",children:"MP4"})]},we)}),i.media?.original?.key&&g(Y,{children:[a(ur,{}),g(de,{onClick:()=>p(i.media?.original?.key??""),className:"flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground",children:[a("span",{children:Zl()}),a("span",{className:"text-xs text-muted-foreground",children:i.name?.split(".").pop()?.toUpperCase()||"RAW"})]})]})]})]})),a("button",{onClick:b,className:"transition-colors hover:text-primary",title:Ap(),children:e.isFullScreen?a(li,{className:"h-6 w-6"}):a(ai,{className:"h-6 w-6"})})]})]})]})})};var Uv=({state:e,isControlsVisible:t,buffered:n,data:s,resolutions:i,togglePlay:r,toggleLoop:o,toggleMute:l,changePlaybackRate:c,changeResolution:h,toggleFullScreen:d,frameRate:m,totalFrames:p,currentFrame:b,seekToFrame:v,floatOverlayInFullScreen:k=!0,onMouseEnter:A,onMouseLeave:T,isLoading:E})=>{let I=E??e.isLoading??!1,{videoTimeDisplayMode:_,setVideoTimeDisplayMode:q}=ar();if(!s.media?.metadata)return null;let P=e.isFullScreen&&k,N=s.proxyType==="audio",H=s.media?.metadata?.startTimecode,V=Math.max(0,p-1),U=_==="frames"?`${b} / ${V} fr`:_==="standard"?`${ro(b,m,"standard")} / ${fi(p/m)}`:`${ro(b,m,_,H)} / ${ro(V,m,_,H)}`;return a("div",{className:B("transition-all duration-300 ease-in-out z-20 text-foreground",P?"absolute bottom-0 left-0 right-0 px-3 py-3 bg-card/90 backdrop-blur-md border-t border-border":"relative w-full bg-card border-t border-border px-3 py-2.5 z-10 transition-colors duration-200",t?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"),onMouseEnter:A,onMouseLeave:T,children:g("div",{className:B("transition-opacity duration-200",I&&"pointer-events-none opacity-60 select-none"),children:[a("div",{className:"mb-2 px-0.5",children:a(S0,{totalFrames:p,currentFrame:b,fps:m,buffered:n,previewUrl:s.media.videoPreview?.url,onSeek:v,metadata:{...s.media.metadata,frameRate:m}})}),g("div",{className:"flex items-center justify-between text-foreground gap-1 select-none",children:[g("div",{className:"flex items-center gap-2 min-w-0",children:[a("button",{onClick:r,className:"p-1 hover:text-primary transition-colors cursor-pointer shrink-0","data-testid":"play-toggle","data-playing":e.isPlaying,"aria-label":e.isPlaying?"Pause":"Play",children:e.isPlaying?a(Mc,{className:"w-5 h-5 fill-current"}):a(ya,{className:"w-5 h-5 fill-current"})}),a("button",{onClick:l,className:"p-1 hover:text-primary transition-colors cursor-pointer shrink-0","aria-label":e.isMuted?"Unmute":"Mute",children:e.isMuted||e.volume===0?a(dd,{className:"w-5 h-5"}):a(ud,{className:"w-5 h-5"})}),g("div",{className:"flex items-center gap-0.5 text-xs font-medium tabular-nums min-w-0",children:[a("span",{className:"text-muted-foreground font-mono truncate text-[11px] sm:text-xs","data-testid":"time-readout",children:U}),g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:a("button",{className:"h-5 w-5 inline-flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none shrink-0","aria-label":bw(),children:a(Be,{className:"h-3 w-3"})})}),g(Fe,{align:"start",className:"w-40 z-30",children:[a(En,{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider",children:bC()}),g(de,{onClick:()=>q("standard"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:rM()}),_==="standard"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]}),g(de,{onClick:()=>q("frames"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:wC()}),_==="frames"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]}),g(de,{onClick:()=>q("timecode"),className:"flex items-center justify-between cursor-pointer text-xs",children:[a("span",{children:WM()}),_==="timecode"&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]})]})]})]})]}),g("div",{className:"flex items-center gap-1 shrink-0",children:[g(De,{modal:!1,children:[a(Ne,{asChild:!0,children:g("button",{className:"flex items-center gap-1 rounded border border-border px-1.5 py-1 text-xs font-semibold hover:bg-muted transition-colors cursor-pointer",title:tg(),"aria-label":tg(),children:[a(xa,{className:"h-3.5 w-3.5"}),g("span",{className:"flex items-center gap-1 text-[11px]",children:[a("span",{children:!N&&e.currentResolution?e.currentResolution==="Auto"?e.activeAutoResolution?`${Vc()} (${e.activeAutoResolution})`:Vc():e.currentResolution==="Original"?Zl():e.currentResolution:`${e.playbackRate}x`}),!N&&e.isCurrentHdr&&a("span",{className:"px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30",children:wd()})]})]})}),g(Fe,{align:"end",className:"w-48 z-30",children:[!N&&i.length>0&&g(Y,{children:[a(En,{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider",children:F0()}),s.media?.isHls&&a(de,{onClick:()=>h({resolution:"Auto",width:s.media?.metadata?.originalWidth??0,height:s.media?.metadata?.originalHeight??0}),className:B("flex w-full items-center justify-between text-xs cursor-pointer",e.currentResolution==="Auto"?"text-primary font-medium":"text-foreground"),children:a("span",{children:Vc()})}),i.map((W)=>{let ce=`${W.resolution}-${W.hdr?"hdr":"sdr"}`,ue=e.currentResolution===W.resolution&&Boolean(e.isCurrentHdr)===Boolean(W.hdr),oe=Boolean(s.media?.isHls)&&e.isHlsManualSupported===!1;return g(de,{disabled:oe,onClick:()=>!oe&&h(W),className:B("flex w-full items-center justify-between text-xs",ue?"text-primary font-medium":"text-foreground",oe?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[g("div",{className:"flex items-center gap-1.5",children:[a("span",{children:W.resolution==="Original"?Zl():W.resolution}),W.hdr&&a("span",{className:"px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30",children:wd()})]}),g("span",{className:"text-[10px] text-muted-foreground",children:[W.width,"x",W.height]})]},ce)}),a(ur,{})]}),a(En,{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wider",children:d1()}),[0.5,1,1.5,2].map((W)=>g(de,{onClick:()=>c(W),className:B("flex items-center justify-between text-xs cursor-pointer",e.playbackRate===W?"text-primary font-medium":"text-foreground"),children:[g("span",{children:[W,"x"]}),e.playbackRate===W&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]},W)),a(ur,{}),g(de,{onClick:o,className:"flex items-center justify-between text-xs cursor-pointer",children:[g("span",{className:"flex items-center gap-1.5",children:[a(cd,{className:"h-3.5 w-3.5"}),a("span",{children:DS()})]}),e.isLooping&&a(qe,{className:"h-3.5 w-3.5 text-primary"})]})]})]}),a("button",{onClick:d,className:"p-1 hover:text-primary transition-colors cursor-pointer shrink-0",title:Ap(),"aria-label":Ap(),children:e.isFullScreen?a(li,{className:"h-5 w-5"}):a(ai,{className:"h-5 w-5"})})]})]})]})})};Z();var hI=Math.PI/180;function uI(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}var nl=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},tt={_global:nl,version:"10.3.2",isBrowser:uI(),isUnminified:/param/.test(function(e){}.toString()),dblClickWindow:400,getAngle(e){return tt.angleDeg?e*hI:e},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return tt.DD.isDragging},isTransforming(){var e,t;return(t=(e=tt.Transformer)===null||e===void 0?void 0:e.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!tt.DD.node},releaseCanvasOnDestroy:!0,document:nl.document,_injectGlobal(e){if(typeof nl.Konva<"u")console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment.");nl.Konva=e}},Qt=(e)=>{tt[e.prototype.getClassName()]=e};tt._injectGlobal(tt);var dI=`Konva.js unsupported environment.
54
-
55
- Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined.
56
-
57
- To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module.
58
-
59
- bash: npm install canvas
60
- js: import "konva/canvas-backend";
61
-
62
- or
63
-
64
- bash: npm install skia-canvas
65
- js: import "konva/skia-backend";
66
- `,zv=()=>{if(typeof document>"u")throw Error(dI)};class _i{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new _i(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){let t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){let t=Math.cos(e),n=Math.sin(e),s=this.m[0]*t+this.m[2]*n,i=this.m[1]*t+this.m[3]*n,r=this.m[0]*-n+this.m[2]*t,o=this.m[1]*-n+this.m[3]*t;return this.m[0]=s,this.m[1]=i,this.m[2]=r,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){let n=this.m[0]+this.m[2]*t,s=this.m[1]+this.m[3]*t,i=this.m[2]+this.m[0]*e,r=this.m[3]+this.m[1]*e;return this.m[0]=n,this.m[1]=s,this.m[2]=i,this.m[3]=r,this}multiply(e){let t=this.m[0]*e.m[0]+this.m[2]*e.m[1],n=this.m[1]*e.m[0]+this.m[3]*e.m[1],s=this.m[0]*e.m[2]+this.m[2]*e.m[3],i=this.m[1]*e.m[2]+this.m[3]*e.m[3],r=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=n,this.m[2]=s,this.m[3]=i,this.m[4]=r,this.m[5]=o,this}invert(){let e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,n=-this.m[1]*e,s=-this.m[2]*e,i=this.m[0]*e,r=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=n,this.m[2]=s,this.m[3]=i,this.m[4]=r,this.m[5]=o,this}getMatrix(){return this.m}decompose(){let e=this.m[0],t=this.m[1],n=this.m[2],s=this.m[3],i=this.m[4],r=this.m[5],o=e*s-t*n,l={x:i,y:r,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){let c=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/c):-Math.acos(e/c),l.scaleX=c,l.scaleY=o/c,l.skewX=(e*n+t*s)/o,l.skewY=0}else if(n!=0||s!=0){let c=Math.sqrt(n*n+s*s);l.rotation=Math.PI/2-(s>0?Math.acos(-n/c):-Math.acos(n/c)),l.scaleX=o/c,l.scaleY=c,l.skewX=0,l.skewY=(e*n+t*s)/o}return l.rotation=ge._getRotation(l.rotation),l}}var mI="[object Array]",pI="[object Number]",bI="[object String]",wI="[object Boolean]",yI=Math.PI/180,Wv=180/Math.PI,k0="#",vI="",SI="0",kI="Konva warning: ",Gv="Konva error: ",xI={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},_h=null,AI=typeof window<"u"?window:{},ab=new WeakMap,TI=(e,t)=>{if(typeof e.requestAnimationFrame==="function")e.requestAnimationFrame(t);else if(typeof requestAnimationFrame<"u")requestAnimationFrame(t);else setTimeout(t,16)},Vv=new Map,$v=(e)=>{let t=e.trim();return t.indexOf(",")===-1?t.split(/\s*\/\s*|\s+/):t.split(/\s*,\s*/)},Kv="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?",EI=new RegExp(`^(${Kv})(%?)$`,"i"),Bl=(e,t)=>{let n=EI.exec(e);if(!n)return NaN;return n[2]?Number(n[1])/100*t:Number(n[1])},x0=/^#[0-9a-f]+$/i,Xv=(e)=>Math.min(Math.max(e,0),1),CI=new RegExp(`^(${Kv})(deg|grad|rad|turn)?$`,"i"),jI={deg:1,grad:0.9,rad:Wv,turn:360},ge={_isElement(e){return!!(e&&e.nodeType==1)},_isFunction(e){return!!(e&&e.constructor&&e.call&&e.apply)},_isPlainObject(e){return!!e&&e.constructor===Object},_isArray(e){return Object.prototype.toString.call(e)===mI},_isNumber(e){return Object.prototype.toString.call(e)===pI&&!isNaN(e)&&isFinite(e)},_isString(e){return Object.prototype.toString.call(e)===bI},_isBoolean(e){return Object.prototype.toString.call(e)===wI},isObject(e){return e instanceof Object},isValidSelector(e){if(typeof e!=="string")return!1;let t=e[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(e){if(e===0)return 1;if(e>0)return 1;else return-1},requestAnimFrame(e,t){let n=t&&!t.closed&&t||AI,s=ab.get(n);if(!s)s=[],ab.set(n,s),TI(n,function(){ab.delete(n),s.forEach(function(i){i()})});s.push(e)},createCanvasElement(){zv();let e=document.createElement("canvas");try{e.style=e.style||{}}catch(t){}return e},createImageElement(){return zv(),document.createElement("img")},_isInDocument(e){return!!e.isConnected},_urlToImage(e,t){let n=ge.createImageElement();n.onload=function(){t(n)},n.src=e},_rgbToHex(e,t,n){return(16777216+(e<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(e){e=e.replace(k0,vI);let t=parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let e=(Math.random()*16777215<<0).toString(16);while(e.length<6)e=SI+e;return k0+e},isCanvasFarblingActive(){if(_h!==null)return _h;if(typeof document>"u")return _h=!1,!1;let e=this.createCanvasElement();e.width=10,e.height=10;let t=e.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);let n=t.getImageData(0,0,10,10).data,s=!1;for(let i=0;i<100;i++)if(n[i*4]!==40||n[i*4+1]!==40||n[i*4+2]!==40||n[i*4+3]!==255){s=!0;break}return _h=s,this.releaseCanvas(e),_h},getHitColor(){let e=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(e):e},getHitColorKey(e,t,n){if(this.isCanvasFarblingActive())e=Math.round(e/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5;return k0+this._rgbToHex(e,t,n)},getSnappedHexColor(e){let t=this._hexToRgb(e);return k0+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(e){var t;let{r:n=0,g:s=0,b:i=0}=(t=ge.colorToRGBA(e))!==null&&t!==void 0?t:{};return{r:n,g:s,b:i}},colorToRGBA(e){e=(e||"").trim()||"black";let t=ge._namedColorToRBA(e)||ge._hex3ColorToRGBA(e)||ge._hex4ColorToRGBA(e)||ge._hex6ColorToRGBA(e)||ge._hex8ColorToRGBA(e)||ge._rgbColorToRGBA(e)||ge._hslColorToRGBA(e);if(t&&[t.r,t.g,t.b,t.a].every(ge._isNumber))return t},_namedColorToRBA(e){let t=xI[e.toLowerCase()];if(!t)return null;return{r:t[0],g:t[1],b:t[2],a:t.length>3?t[3]:1}},_rgbColorToRGBA(e){let t=/^rgba?\(([^)]*)\)$/i.exec(e);if(!t)return;let n=$v(t[1]);if(n.length<3||n.length>4)return;return{r:Bl(n[0],255),g:Bl(n[1],255),b:Bl(n[2],255),a:n.length>3?Bl(n[3],1):1}},_hex8ColorToRGBA(e){if(e.length===9&&x0.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:parseInt(e.slice(7,9),16)/255}},_hex6ColorToRGBA(e){if(e.length===7&&x0.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1}},_hex4ColorToRGBA(e){if(e.length===5&&x0.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:parseInt(e[4]+e[4],16)/255}},_hex3ColorToRGBA(e){if(e.length===4&&x0.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1}},_hslColorToRGBA(e){let t=/^hsla?\(([^)]*)\)$/i.exec(e);if(!t)return;let n=$v(t[1]);if(n.length<3||n.length>4)return;let s=CI.exec(n[0]);if(!s)return;let i=s[2],r=Number(s[1])*(i?jI[i.toLowerCase()]:1);if(!isFinite(r))return;let o=(r%360+360)%360/360,l=Xv(Bl(n[1],100)/100),c=Xv(Bl(n[2],100)/100),h=n.length>3?Bl(n[3],1):1,d=c<0.5?c*(1+l):c+l-c*l,m=2*c-d,p=[0,0,0];for(let b=0;b<3;b++){let v=o+0.3333333333333333*-(b-1);if(v<0)v++;if(v>1)v--;let k;if(6*v<1)k=m+(d-m)*6*v;else if(2*v<1)k=d;else if(3*v<2)k=m+(d-m)*(0.6666666666666666-v)*6;else k=m;p[b]=k*255}return{r:Math.round(p[0]),g:Math.round(p[1]),b:Math.round(p[2]),a:h}},haveIntersection(e,t){return!(t.x>e.x+e.width||t.x+t.width<e.x||t.y>e.y+e.height||t.y+t.height<e.y)},cloneObject(e){let t={};for(let n in e)if(this._isPlainObject(e[n]))t[n]=this.cloneObject(e[n]);else if(this._isArray(e[n]))t[n]=this.cloneArray(e[n]);else t[n]=e[n];return t},cloneArray(e){return e.slice(0)},degToRad(e){return e*yI},radToDeg(e){return e*Wv},_degToRad(e){return ge.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),ge.degToRad(e)},_radToDeg(e){return ge.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),ge.radToDeg(e)},_getRotation(e){return tt.angleDeg?ge.radToDeg(e):e},_capitalize(e){let t=Vv.get(e);if(t!==void 0)return t;let n=e.charAt(0).toUpperCase()+e.slice(1);return Vv.set(e,n),n},throw(e){throw Error(Gv+e)},error(e){console.error(Gv+e)},warn(e){if(!tt.showWarnings)return;console.warn(kI+e)},each(e,t){for(let n in e)t(n,e[n])},_inRange(e,t,n){return t<=e&&e<n},_getProjectionToSegment(e,t,n,s,i,r){let o,l,c,h=(e-n)*(e-n)+(t-s)*(t-s);if(h==0)o=e,l=t,c=(i-n)*(i-n)+(r-s)*(r-s);else{let d=((i-e)*(n-e)+(r-t)*(s-t))/h;if(d<0)o=e,l=t,c=(e-i)*(e-i)+(t-r)*(t-r);else if(d>1)o=n,l=s,c=(n-i)*(n-i)+(s-r)*(s-r);else o=e+d*(n-e),l=t+d*(s-t),c=(o-i)*(o-i)+(l-r)*(l-r)}return[o,l,c]},_getProjectionToLine(e,t,n){let s=ge.cloneObject(e),i=Number.MAX_VALUE;return t.forEach(function(r,o){if(!n&&o===t.length-1)return;let l=t[(o+1)%t.length],c=ge._getProjectionToSegment(r.x,r.y,l.x,l.y,e.x,e.y),h=c[0],d=c[1],m=c[2];if(m<i)s.x=h,s.y=d,i=m}),s},_prepareArrayForTween(e,t,n){let s=[],i=[];if(e.length>t.length){let o=t;t=e,e=o}for(let o=0;o<e.length;o+=2)s.push({x:e[o],y:e[o+1]});for(let o=0;o<t.length;o+=2)i.push({x:t[o],y:t[o+1]});let r=[];return i.forEach(function(o){let l=ge._getProjectionToLine(o,s,n);r.push(l.x),r.push(l.y)}),r},_prepareToStringify(e){let t;e.visitedByCircularReferenceRemoval=!0;for(let n in e){if(!(e.hasOwnProperty(n)&&e[n]&&typeof e[n]=="object"))continue;if(t=Object.getOwnPropertyDescriptor(e,n),e[n].visitedByCircularReferenceRemoval||ge._isElement(e[n]))if(t.configurable)delete e[n];else return null;else if(ge._prepareToStringify(e[n])===null)if(t.configurable)delete e[n];else return null}return delete e.visitedByCircularReferenceRemoval,e},_assign(e,t){for(let n in t)e[n]=t[n];return e},_getFirstPointerId(e){if(!e.touches)return e.pointerId||999;else return e.changedTouches[0].identifier},releaseCanvas(...e){if(!tt.releaseCanvasOnDestroy)return;e.forEach((t)=>{t.width=0,t.height=0})},drawRoundedRectPath(e,t,n,s){let i=t<0?t:0,r=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let o=0,l=0,c=0,h=0;if(typeof s==="number")o=l=c=h=Math.min(s,t/2,n/2);else o=Math.min(s[0]||0,t/2,n/2),l=Math.min(s[1]||0,t/2,n/2),h=Math.min(s[2]||0,t/2,n/2),c=Math.min(s[3]||0,t/2,n/2);e.moveTo(i+o,r),e.lineTo(i+t-l,r),e.arc(i+t-l,r+l,l,Math.PI*3/2,0,!1),e.lineTo(i+t,r+n-h),e.arc(i+t-h,r+n-h,h,0,Math.PI/2,!1),e.lineTo(i+c,r+n),e.arc(i+c,r+n-c,c,Math.PI/2,Math.PI,!1),e.lineTo(i,r+o),e.arc(i+o,r+o,o,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(e,t,n,s,i){s=Math.abs(s);for(let r=0;r<n;r++){let o=t[(r-1+n)%n],l=t[r],c=t[(r+1)%n],h={x:l.x-o.x,y:l.y-o.y},d={x:c.x-l.x,y:c.y-l.y},m=Math.hypot(h.x,h.y),p=Math.hypot(d.x,d.y),b;if(typeof i==="number")b=i;else b=r<i.length?i[r]:0;b=s*Math.cos(Math.PI/n)*Math.min(1,b/s*2);let k={x:h.x/m,y:h.y/m},A={x:d.x/p,y:d.y/p},T={x:l.x-k.x*b,y:l.y-k.y*b},E={x:l.x+A.x*b,y:l.y+A.y*b};if(r===0)e.moveTo(T.x,T.y);else e.lineTo(T.x,T.y);e.arcTo(l.x,l.y,E.x,E.y,b)}}};function _I(e){let t=[],n=e.length,s=ge;for(let i=0;i<n;i++){let r=e[i];if(s._isNumber(r))r=Math.round(r*1000)/1000;else if(!s._isString(r))r=r+"";t.push(r)}return t}var Yv=",",II="(",RI=")",DI="([",qI="])",MI=";",FI="()",LI="=",Qv=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],OI=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],PI=100,A0=null;function ob(){if(A0!==null)return A0;try{let t=ge.createCanvasElement().getContext("2d");if(!t)return A0=!1,!1;return!!t&&"filter"in t}catch(e){return A0=!1,!1}}class ef{constructor(e){if(this.canvas=e,tt.enableTrace)this.traceArr=[],this._enableTrace()}fillShape(e){if(e.fillEnabled())this._fill(e)}_fill(e){}strokeShape(e){if(e.hasStroke())this._stroke(e)}_stroke(e){}fillStrokeShape(e){if(e.attrs.fillAfterStrokeEnabled)this.strokeShape(e),this.fillShape(e);else this.fillShape(e),this.strokeShape(e)}getTrace(e,t){let n=this.traceArr,s=n.length,i="",r,o,l,c;for(r=0;r<s;r++){if(o=n[r],l=o.method,l)if(c=o.args,i+=l,e)i+=FI;else if(ge._isArray(c[0]))i+=DI+c.join(Yv)+qI;else{if(t)c=c.map((h)=>typeof h==="number"?Math.floor(h):h);i+=II+c.join(Yv)+RI}else if(i+=o.property,!e)i+=LI+o.val;i+=MI}return i}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;if(t.push(e),n=t.length,n>=PI)t.shift()}reset(){let e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){let t=this.getCanvas();if(e)this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0);else this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){let t=e.attrs.lineCap;if(t)this.setAttr("lineCap",t)}_applyOpacity(e){let t=e.getAbsoluteOpacity();if(t!==1)this.setAttr("globalAlpha",t)}_applyLineJoin(e){let t=e.attrs.lineJoin;if(t)this.setAttr("lineJoin",t)}_applyMiterLimit(e){let t=e.attrs.miterLimit;if(t!=null)this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,n,s,i,r){this._context.arc(e,t,n,s,i,r)}arcTo(e,t,n,s,i){this._context.arcTo(e,t,n,s,i)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,n,s,i,r){this._context.bezierCurveTo(e,t,n,s,i,r)}clearRect(e,t,n,s){this._context.clearRect(e,t,n,s)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){let n=arguments;if(n.length===2)return this._context.createImageData(e,t);else if(n.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,n,s){return this._context.createLinearGradient(e,t,n,s)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,n,s,i,r){return this._context.createRadialGradient(e,t,n,s,i,r)}drawImage(e,t,n,s,i,r,o,l,c){let h=arguments,d=this._context;if(h.length===3)d.drawImage(e,t,n);else if(h.length===5)d.drawImage(e,t,n,s,i);else if(h.length===9)d.drawImage(e,t,n,s,i,r,o,l,c)}ellipse(e,t,n,s,i,r,o,l){this._context.ellipse(e,t,n,s,i,r,o,l)}isPointInPath(e,t,n,s){if(n)return this._context.isPointInPath(n,e,t,s);return this._context.isPointInPath(e,t,s)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,n,s){this._context.fillRect(e,t,n,s)}strokeRect(e,t,n,s){this._context.strokeRect(e,t,n,s)}fillText(e,t,n,s){if(s)this._context.fillText(e,t,n,s);else this._context.fillText(e,t,n)}measureText(e){return this._context.measureText(e)}getImageData(e,t,n,s){return this._context.getImageData(e,t,n,s)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,n,s){this._context.rect(e,t,n,s)}roundRect(e,t,n,s,i){this._context.roundRect(e,t,n,s,i)}putImageData(e,t,n){this._context.putImageData(e,t,n)}quadraticCurveTo(e,t,n,s){this._context.quadraticCurveTo(e,t,n,s)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){if(this._context.setLineDash)this._context.setLineDash(e);else if("mozDash"in this._context)this._context.mozDash=e;else if("webkitLineDash"in this._context)this._context.webkitLineDash=e}getLineDash(){return this._context.getLineDash()}setTransform(e,t,n,s,i,r){this._context.setTransform(e,t,n,s,i,r)}stroke(e){if(e)this._context.stroke(e);else this._context.stroke()}strokeText(e,t,n,s){this._context.strokeText(e,t,n,s)}transform(e,t,n,s,i,r){this._context.transform(e,t,n,s,i,r)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=Qv.length,n=this.setAttr,s,i,r=function(o){let l=e[o],c;e[o]=function(){return i=_I(Array.prototype.slice.call(arguments,0)),c=l.apply(e,arguments),e._trace({method:o,args:i}),c}};for(s=0;s<t;s++)r(Qv[s]);e.setAttr=function(){n.apply(e,arguments);let o=arguments[0],l=arguments[1];if(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")l=l/this.canvas.getPixelRatio();e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){let t=e.attrs.globalCompositeOperation;if(!(!t||t==="source-over"))this.setAttr("globalCompositeOperation",t)}}OI.forEach(function(e){Object.defineProperty(ef.prototype,e,{get(){return this._context[e]},set(t){this._context[e]=t}})});class lb extends ef{constructor(e,{willReadFrequently:t=!1}={}){super(e);this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){let t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){let t=this._context;if("patternQuality"in t)t.patternQuality=t.imageSmoothingEnabled?"good":"nearest";this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){let t=e._getLinearGradient();if(t)this.setAttr("fillStyle",t),e._fillFunc(this)}_fillRadialGradient(e){let t=e._getRadialGradient();if(t)this.setAttr("fillStyle",t),e._fillFunc(this)}_fill(e){let t=e.fill(),n=e.getFillPriority();if(t&&n==="color"){this._fillColor(e);return}let s=e.getFillPatternImage();if(s&&n==="pattern"){this._fillPattern(e);return}let i=e.getFillLinearGradientColorStops();if(i&&n==="linear-gradient"){this._fillLinearGradient(e);return}let r=e.getFillRadialGradientColorStops();if(r&&n==="radial-gradient"){this._fillRadialGradient(e);return}if(t)this._fillColor(e);else if(s)this._fillPattern(e);else if(i)this._fillLinearGradient(e);else if(r)this._fillRadialGradient(e)}_strokeLinearGradient(e){let t=e.getStrokeLinearGradientStartPoint(),n=e.getStrokeLinearGradientEndPoint(),s=e.getStrokeLinearGradientColorStops(),i=this.createLinearGradient(t.x,t.y,n.x,n.y);if(s){for(let r=0;r<s.length;r+=2)i.addColorStop(s[r],s[r+1]);this.setAttr("strokeStyle",i)}}_stroke(e){let t=e.dash(),n=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!n){this.save();let i=this.getCanvas().getPixelRatio();this.setTransform(i,0,0,i,0,0)}if(this._applyLineCap(e),t&&e.dashEnabled())this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset());if(this.setAttr("lineWidth",e.strokeWidth()),!e.getShadowForStrokeEnabled())this.setAttr("shadowColor","rgba(0,0,0,0)");if(e.getStrokeLinearGradientColorStops())this._strokeLinearGradient(e);else this.setAttr("strokeStyle",e.stroke());if(e._strokeFunc(this),!n)this.restore()}}_applyShadow(e){var t,n,s;let i=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",r=(n=e.getShadowBlur())!==null&&n!==void 0?n:5,o=(s=e.getShadowOffset())!==null&&s!==void 0?s:{x:0,y:0},l=e.getAbsoluteScale(),c=this.canvas.getPixelRatio(),h=l.x*c,d=l.y*c;this.setAttr("shadowColor",i),this.setAttr("shadowBlur",r*Math.min(Math.abs(h),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*h),this.setAttr("shadowOffsetY",o.y*d)}}class cb extends ef{constructor(e){super(e);this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){if(e.hasHitStroke())this._stroke(e)}_stroke(e){if(e.hasHitStroke()){let t=e.getStrokeScaleEnabled();if(!t){this.save();let i=this.getCanvas().getPixelRatio();this.setTransform(i,0,0,i,0,0)}this._applyLineCap(e);let n=e.hitStrokeWidth(),s=n==="auto"?e.strokeWidth():n;if(this.setAttr("lineWidth",s),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),!t)this.restore()}}}var T0;function NI(){if(T0)return T0;let e=ge.createCanvasElement(),t=e.getContext("2d");return T0=function(){let n=tt._global.devicePixelRatio||1,s=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return n/s}(),ge.releaseCanvas(e),T0}class Ih{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;let n=(e||{}).pixelRatio||tt.pixelRatio||NI();this.pixelRatio=n,this._canvas=ge.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){let t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";let t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";let t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}setSizeIfChanged(e,t){if(this.width!==e*this.pixelRatio||this.height!==t*this.pixelRatio)this.setSize(e,t)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch(n){try{return this._canvas.toDataURL()}catch(s){return ge.error("Unable to get data URL. "+s.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class qr extends Ih{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e);this.context=new lb(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class Hl extends Ih{constructor(e={width:0,height:0}){super(e);this.hitCanvas=!0,this.context=new cb(this),this.setSize(e.width,e.height)}}var In={get isDragging(){let e=!1;return In._dragElements.forEach((t)=>{if(t.dragStatus==="dragging")e=!0}),e},justDragged:!1,get node(){let e;return In._dragElements.forEach((t)=>{e=t.node}),e},_dragElements:new Map,_listenToWindow(e){let t=(s)=>In._endDragBefore(s,e),n=(s)=>In._drag(s,e);e.addEventListener("mouseup",t,!0),e.addEventListener("touchend",t,!0),e.addEventListener("touchcancel",t,!0),e.addEventListener("mousemove",n),e.addEventListener("touchmove",n),e.addEventListener("mouseup",In._endDragAfter,!1),e.addEventListener("touchend",In._endDragAfter,!1),e.addEventListener("touchcancel",In._endDragAfter,!1)},_drag(e,t){let n=[];In._dragElements.forEach((s,i)=>{let{node:r}=s,o=r.getStage();if(t&&o._getOwnerWindow()!==t)return;if(o.setPointersPositions(e),s.pointerId===void 0)s.pointerId=ge._getFirstPointerId(e);let l=o._changedPointerPositions.find((c)=>c.id===s.pointerId);if(!l)return;if(s.dragStatus!=="dragging"){let c=r.dragDistance();if(Math.max(Math.abs(l.x-s.startPointerPos.x),Math.abs(l.y-s.startPointerPos.y))<c)return;if(r.startDrag({evt:e}),!r.isDragging())return}r._setDragPosition(e,s),n.push(r)}),n.forEach((s)=>{if(!s.getStage())return;s.fire("dragmove",{type:"dragmove",target:s,evt:e},!0)})},_endDragBefore(e,t){let n=[];In._dragElements.forEach((s)=>{let{node:i}=s,r=i.getStage();if(e&&(!t||r._getOwnerWindow()===t))r.setPointersPositions(e);if(!r._changedPointerPositions.find((c)=>c.id===s.pointerId))return;if(s.dragStatus==="dragging"||s.dragStatus==="stopped")In.justDragged=!0,tt._mouseListenClick=!1,tt._touchListenClick=!1,tt._pointerListenClick=!1,s.dragStatus="stopped";let l=s.node.getLayer()||s.node instanceof tt.Stage&&s.node;if(l&&n.indexOf(l)===-1)n.push(l)}),n.forEach((s)=>{s.draw()})},_endDragAfter(e){In._dragElements.forEach((t,n)=>{if(t.dragStatus==="stopped")t.node.fire("dragend",{type:"dragend",target:t.node,evt:e},!0);if(t.dragStatus!=="dragging")In._dragElements.delete(n)})}};function sl(e){if(ge._isString(e))return'"'+e+'"';if(Object.prototype.toString.call(e)==="[object Number]")return e;if(ge._isBoolean(e))return e;return Object.prototype.toString.call(e)}function E0(e){if(e>255)return 255;else if(e<0)return 0;return Math.round(e)}function Pe(){if(tt.isUnminified)return function(e,t){if(!ge._isNumber(e))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.');return e}}function il(e){if(tt.isUnminified)return function(t,n){let s=ge._isNumber(t),i=ge._isArray(t)&&t.length==e;if(!s&&!i)ge.warn(sl(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array<number>('+e+")");return t}}function Rh(){if(tt.isUnminified)return function(e,t){if(!(ge._isNumber(e)||e==="auto"))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".');return e}}function Da(){if(tt.isUnminified)return function(e,t){if(!ge._isString(e))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.');return e}}function fb(){if(tt.isUnminified)return function(e,t){let n=ge._isString(e),s=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;if(!(n||s))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.');return e}}function Jv(){if(tt.isUnminified)return function(e,t){let n=Int8Array?Object.getPrototypeOf(Int8Array):null;if(n&&e instanceof n)return e;if(!ge._isArray(e))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.');else e.forEach(function(s){if(!ge._isNumber(s))ge.warn('"'+t+'" attribute has non numeric element '+s+". Make sure that all elements are numbers.")});return e}}function Ri(){if(tt.isUnminified)return function(e,t){if(!(e===!0||e===!1))ge.warn(sl(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.');return e}}function Zv(e){if(tt.isUnminified)return function(t,n){if(t===void 0||t===null)return t;if(!ge.isObject(t))ge.warn(sl(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e);return t}}var Dh="get",qh="set",le={addGetterSetter(e,t,n,s,i){le.addGetter(e,t,n),le.addSetter(e,t,s,i),le.addOverloadedGetterSetter(e,t)},addGetter(e,t,n){let s=Dh+ge._capitalize(t);e.prototype[s]=e.prototype[s]||function(){let i=this.attrs[t];return i===void 0?n:i}},addSetter(e,t,n,s){let i=qh+ge._capitalize(t);if(!e.prototype[i])le.overWriteSetter(e,t,n,s)},overWriteSetter(e,t,n,s){let i=qh+ge._capitalize(t);e.prototype[i]=function(r){if(n&&r!==void 0&&r!==null)r=n.call(this,r,t);if(this._setAttr(t,r),s)s.call(this);return this}},addComponentsGetterSetter(e,t,n,s,i){let r=n.length,o=ge._capitalize,l=Dh+o(t),c=qh+o(t);e.prototype[l]=function(){let d={};for(let m=0;m<r;m++){let p=n[m];d[p]=this.getAttr(t+o(p))}return d};let h=Zv(n);e.prototype[c]=function(d){let m=this.attrs[t];if(s)d=s.call(this,d,t);if(h)h.call(this,d,t);for(let p in d){if(!d.hasOwnProperty(p))continue;this._setAttr(t+o(p),d[p])}if(!d)n.forEach((p)=>{this._setAttr(t+o(p),void 0)});if(this._fireChangeEvent(t,m,d),i)i.call(this);return this},le.addOverloadedGetterSetter(e,t)},addOverloadedGetterSetter(e,t){let n=ge._capitalize(t),s=qh+n,i=Dh+n;e.prototype[t]=function(){if(arguments.length)return this[s](arguments[0]),this;return this[i]()}},addDeprecatedGetterSetter(e,t,n,s){ge.error("Adding deprecated "+t);let i=Dh+ge._capitalize(t),r=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";e.prototype[i]=function(){ge.error(r);let o=this.attrs[t];return o===void 0?n:o},le.addSetter(e,t,s,function(){ge.error(r)}),le.addOverloadedGetterSetter(e,t)},backCompat(e,t){ge.each(t,function(n,s){let i=e.prototype[s],r=Dh+ge._capitalize(n),o=qh+ge._capitalize(n);function l(){i.apply(this,arguments),ge.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+s+'" instead.')}e.prototype[n]=l,e.prototype[r]=l,e.prototype[o]=l})},afterSetFilter(){this._filterUpToDate=!1}};function BI(e){let t=/(\w+)\(([^)]+)\)/g,n;while((n=t.exec(e))!==null){let[,s,i]=n;switch(s){case"blur":{let r=parseFloat(i.replace("px",""));return function(o){this.blurRadius(r*0.5);let l=tt.Filters;if(l&&l.Blur)l.Blur.call(this,o)}}case"brightness":{let r=i.includes("%")?parseFloat(i)/100:parseFloat(i);return function(o){this.brightness(r);let l=tt.Filters;if(l&&l.Brightness)l.Brightness.call(this,o)}}case"contrast":{let r=parseFloat(i);return function(o){let l=100*(Math.sqrt(r)-1);this.contrast(l);let c=tt.Filters;if(c&&c.Contrast)c.Contrast.call(this,o)}}case"grayscale":return function(r){let o=tt.Filters;if(o&&o.Grayscale)o.Grayscale.call(this,r)};case"sepia":return function(r){let o=tt.Filters;if(o&&o.Sepia)o.Sepia.call(this,r)};case"invert":return function(r){let o=tt.Filters;if(o&&o.Invert)o.Invert.call(this,r)};default:ge.warn(`CSS filter "${s}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}var C0="absoluteOpacity",e4="allEventListeners",mo="absoluteTransform",t4="absoluteScale",Ul="canvas",HI="Change",UI="children",zI="konva",hb="listening",VI="mouseenter",$I="mouseleave",XI="pointerenter",WI="pointerleave",KI="touchenter",YI="touchleave";var n4="set",s4="Shape",j0=" ",i4="stage",rl="transform",ZI="Stage",ub="visible",eR=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(j0),tR=1;class Ue{constructor(e){this._id=tR++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){if((e===rl||e===mo)&&this._cache.get(e))this._cache.get(e).dirty=!0;else if(e)this._cache.delete(e);else this._cache.clear()}_getCache(e,t){let n=this._cache.get(e);if(n===void 0||(e===rl||e===mo)&&n.dirty===!0)n=t.call(this),this._cache.set(e,n);return n}_calculate(e,t,n){if(!this._attachedDepsListeners.get(e)){let s=t.map((i)=>i+"Change.konva").join(j0);this.on(s,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,n)}_getCanvasCache(){return this._cache.get(Ul)}_clearSelfAndDescendantCache(e){if(this._clearCache(e),e===mo)this.fire("absoluteTransformChange")}static _runAfterAbsTransformCascade(e){if(Ue._absTransformCascadeDepth>0)Ue._pendingAfterCascade.push(e);else e()}clearCache(){if(this._cache.has(Ul)){let{scene:e,filter:t,hit:n}=this._cache.get(Ul);ge.releaseCanvas(e._canvas,t._canvas,...n?[n._canvas]:[]),this._cache.delete(Ul)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){let t=e||{},n={};if(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)n=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0});let s=Math.ceil(t.width||n.width),i=Math.ceil(t.height||n.height),r=t.pixelRatio,o=t.x===void 0?Math.floor(n.x):t.x,l=t.y===void 0?Math.floor(n.y):t.y,c=t.offset||0,h=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!s||!i){ge.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}let m=Math.abs(Math.round(n.x)-o)>0.5?1:0,p=Math.abs(Math.round(n.y)-l)>0.5?1:0;s+=c*2+m,i+=c*2+p,o-=c,l-=c;let b=new qr({pixelRatio:r,width:s,height:i}),v=new qr({pixelRatio:r,width:0,height:0,willReadFrequently:!0}),k=b.getContext(),A=new qr({width:b.width/b.pixelRatio+Math.abs(o),height:b.height/b.pixelRatio+Math.abs(l),pixelRatio:b.pixelRatio}),T=A.getContext();if(b.isCache=!0,this._cache.delete(Ul),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1)b.getContext()._context.imageSmoothingEnabled=!1,v.getContext()._context.imageSmoothingEnabled=!1;if(k.save(),T.save(),k.translate(-o,-l),T.translate(-o,-l),A.x=o,A.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(C0),this._clearSelfAndDescendantCache(t4),this.drawScene(b,this,A),this._isUnderCache=!1,k.restore(),h)k.save(),k.beginPath(),k.rect(0,0,s,i),k.closePath(),k.setAttr("strokeStyle","red"),k.setAttr("lineWidth",5),k.stroke(),k.restore();return ge.releaseCanvas(A._canvas),this._cache.set(Ul,{scene:b,filter:v,hit:null,hitConfig:{pixelRatio:d,width:s,height:i},x:o,y:l}),this._requestDraw(),this}_getCachedHitCanvas(e){if(e===this)return null;let t=this._getCanvasCache();if(!t)return null;if(t.hit)return t.hit;let n=new Hl(t.hitConfig);n.isCache=!0;let s=n.getContext();return s.save(),s.translate(-t.x,-t.y),this.drawHit(n,this),s.restore(),t.hit=n,n}isCached(){return this._cache.has(Ul)}getClientRect(e){throw Error('abstract "getClientRect" method call')}_transformedRect(e,t){let n=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}],s=1/0,i=1/0,r=-1/0,o=-1/0,l=this.getAbsoluteTransform(t);return n.forEach(function(c){let h=l.point(c);if(s===void 0)s=r=h.x,i=o=h.y;s=Math.min(s,h.x),i=Math.min(i,h.y),r=Math.max(r,h.x),o=Math.max(o,h.y)}),{x:s,y:i,width:r-s,height:o-i}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);let t=this._getCanvasCache();e.translate(t.x,t.y);let n=this._getCachedSceneCanvas(),s=n.pixelRatio;e.drawImage(n._canvas,0,0,n.width/s,n.height/s),e.restore()}_drawCachedHitCanvas(e,t){let n=this._getCanvasCache();e.save(),e.translate(n.x,n.y),e.drawImage(t._canvas,0,0,t.width/t.pixelRatio,t.height/t.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),{scene:n,filter:s}=t,i=s.getContext(),r,o,l,c;if(!e||e.length===0)return n;if(this._filterUpToDate)return s;let h=!0;for(let m=0;m<e.length;m++){let p=typeof e[m]==="string"&&!ob();if(typeof e[m]!=="string"||!ob()){h=!1;break}}let d=n.pixelRatio;if(s.setSize(n.width/n.pixelRatio,n.height/n.pixelRatio),h){let m=e.join(" ");return i.save(),i.setAttr("filter",m),i.drawImage(n._canvas,0,0,n.getWidth()/d,n.getHeight()/d),i.restore(),this._filterUpToDate=!0,s}try{r=e.length,i.clear(),i.drawImage(n._canvas,0,0,n.getWidth()/d,n.getHeight()/d),o=i.getImageData(0,0,s.getWidth(),s.getHeight());for(l=0;l<r;l++){if(c=e[l],typeof c==="string")c=BI(c);c.call(this,o),i.putImageData(o,0,0)}}catch(m){ge.error("Unable to apply filter. "+m.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,s}on(...e){let t=e[0],n=e[1],s=e[2];if(this._cache)this._cache.delete(e4);if(e.length===3)return this._delegate.apply(this,e);let i=t.split(j0);for(let r=0;r<i.length;r++){let l=i[r].split("."),c=l[0],h=l[1]||"";if(!this.eventListeners[c])this.eventListeners[c]=[];this.eventListeners[c].push({name:h,handler:n})}return this}off(e,t){let n=(e||"").split(j0),s=n.length,i,r,o,l,c,h;if(this._cache&&this._cache.delete(e4),!e)for(r in this.eventListeners)this._off(r);for(i=0;i<s;i++)if(o=n[i],l=o.split("."),c=l[0],h=l[1],c){if(this.eventListeners[c])this._off(c,h,t)}else for(r in this.eventListeners)this._off(r,h,t);return this}dispatchEvent(e){let t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(n){t.call(this,n.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,n){let s=this;return this.on(e,function(i){let r=i.target.findAncestors(t,!0,s);for(let o=0;o<r.length;o++)i=ge.cloneObject(i),i.currentTarget=r[o],n.call(r[o],i)}),this}remove(){if(this.isDragging())this.stopDrag();return In._dragElements.delete(this._id),In._dragElements.forEach((e,t)=>{if(this.isAncestorOf(e.node))In._dragElements.delete(t)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(mo),this._clearSelfAndDescendantCache(C0),this._clearSelfAndDescendantCache(t4),this._clearSelfAndDescendantCache(i4),this._clearSelfAndDescendantCache(ub),this._clearSelfAndDescendantCache(hb)}_remove(){this._clearCaches();let e=this.getParent();if(e&&e.children)e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){let t="get"+ge._capitalize(e);if(ge._isFunction(this[t]))return this[t]();return this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];while(e)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,n;if(!e)return this;for(t in e){if(t===UI)continue;if(n=n4+ge._capitalize(t),ge._isFunction(this[n]))this[n](e[t]);else this._setAttr(t,e[t])}}),this}isListening(){return this._getCache(hb,this._isListening)}_isListening(e){if(!this.listening())return!1;let n=this.getParent();if(n&&n!==e&&this!==e)return n._isListening(e);else return!0}isVisible(){return this._getCache(ub,this._isVisible)}_isVisible(e){if(!this.visible())return!1;let n=this.getParent();if(n&&n!==e&&this!==e)return n._isVisible(e);else return!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);let n=this.getLayer(),s=!1;In._dragElements.forEach((r)=>{if(r.dragStatus!=="dragging")return;else if(r.node.nodeType==="Stage")s=!0;else if(r.node.getLayer()===n)s=!0});let i=!t&&!tt.hitOnDragEnabled&&(s||tt.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let e=this.getDepth(),t=this,n=0,s,i,r,o;function l(h){s=[],i=h.length;for(r=0;r<i;r++){if(o=h[r],n++,o.nodeType!==s4)s=s.concat(o.getChildren().slice());if(o._id===t._id)r=i}if(s.length>0&&s[0].getDepth()<=e)l(s)}let c=this.getStage();if(t.nodeType!==ZI&&c)l(c.getChildren());return n}getDepth(){let e=0,t=this.parent;while(t)e++,t=t.parent;return e}_batchTransformChanges(e){if(this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache)this._clearCache(rl),this._clearSelfAndDescendantCache(mo);this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){let e=this.getStage();if(!e)return null;let t=e.getPointerPosition();if(!t)return null;let n=this.getAbsoluteTransform().copy();return n.invert(),n.point(t)}getAbsolutePosition(e){let t=!1,n=this.parent;while(n){if(n.isCached()){t=!0;break}n=n.parent}if(t&&!e)e=!0;let s=this.getAbsoluteTransform(e).getMatrix(),i=new _i,r=this.offset();return i.m=s.slice(),i.translate(r.x,r.y),i.getTranslation()}setAbsolutePosition(e){let{x:t,y:n,...s}=this._clearTransform();this.attrs.x=t,this.attrs.y=n,this._clearCache(rl);let i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(e.x,e.y),e={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(s),this.setPosition({x:e.x,y:e.y}),this._clearCache(rl),this._clearSelfAndDescendantCache(mo),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){let e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let{x:t,y:n}=e,s=this.x(),i=this.y();if(t!==void 0)s+=t;if(n!==void 0)i+=n;return this.setPosition({x:s,y:i}),this}_eachAncestorReverse(e,t){let n=[],s=this.getParent(),i,r;if(t&&t._id===this._id)return;n.unshift(this);while(s&&(!t||s._id!==t._id))n.unshift(s),s=s.parent;i=n.length;for(r=0;r<i;r++)e(n[r])}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return ge.warn("Node has no parent. moveToTop function is ignored."),!1;let e=this.index,t=this.parent.getChildren().length;if(e<t-1)return this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0;return!1}moveUp(){if(!this.parent)return ge.warn("Node has no parent. moveUp function is ignored."),!1;let e=this.index,t=this.parent.getChildren().length;if(e<t-1)return this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0;return!1}moveDown(){if(!this.parent)return ge.warn("Node has no parent. moveDown function is ignored."),!1;let e=this.index;if(e>0)return this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0;return!1}moveToBottom(){if(!this.parent)return ge.warn("Node has no parent. moveToBottom function is ignored."),!1;let e=this.index;if(e>0)return this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0;return!1}setZIndex(e){if(!this.parent)return ge.warn("Node has no parent. zIndex parameter is ignored."),this;if(e<0||e>=this.parent.children.length)ge.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");let t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(C0,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity(),t=this.getParent();if(t&&!t._isUnderCache)e*=t.getAbsoluteOpacity();return e}moveTo(e){if(this.getParent()!==e)this._remove(),e.add(this);return this}toObject(){let e=this.getAttrs(),t,n,s,i,r,o={attrs:{},className:this.getClassName()};for(t in e){if(n=e[t],r=ge.isObject(n)&&!ge._isPlainObject(n)&&!ge._isArray(n),r)continue;if(s=typeof this[t]==="function"&&this[t],delete e[t],i=s?s.call(this):null,e[t]=n,i!==n)o.attrs[t]=n}return ge._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,n){let s=[];if(t&&this._isMatch(e))s.push(this);let i=this.parent;while(i){if(i===n)return s;if(i._isMatch(e))s.push(i);i=i.parent}return s}isAncestorOf(e){return!1}findAncestor(e,t,n){return this.findAncestors(e,t,n)[0]}_isMatch(e){if(!e)return!1;if(typeof e==="function")return e(this);let t=e.replace(/ /g,"").split(","),n=t.length,s,i;for(s=0;s<n;s++){if(i=t[s],!ge.isValidSelector(i))ge.warn('Selector "'+i+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),ge.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),ge.warn("Konva is awesome, right?");if(i.charAt(0)==="#"){if(this.id()===i.slice(1))return!0}else if(i.charAt(0)==="."){if(this.hasName(i.slice(1)))return!0}else if(this.className===i||this.nodeType===i)return!0}return!1}getLayer(){let e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(i4,this._getStage)}_getStage(){let e=this.getParent();if(e)return e.getStage();else return null}fire(e,t={},n){if(t.target=t.target||this,n)this._fireAndBubble(e,t);else this._fire(e,t);return this}getAbsoluteTransform(e){if(e)return this._getAbsoluteTransform(e);else return this._getCache(mo,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new _i,this._eachAncestorReverse(function(n){let s=n.transformsEnabled();if(s==="all")t.multiply(n.getTransform());else if(s==="position")t.translate(n.x()-n.offsetX(),n.y()-n.offsetY())},e),t;else{if(t=this._cache.get(mo)||new _i,this.parent)this.parent.getAbsoluteTransform().copyInto(t);else t.reset();let n=this.transformsEnabled();if(n==="all")t.multiply(this.getTransform());else if(n==="position"){let s=this.attrs.x||0,i=this.attrs.y||0,r=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(s-r,i-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;while(t){if(t._isUnderCache)e=t;t=t.getParent()}let s=this.getAbsoluteTransform(e).decompose();return{x:s.scaleX,y:s.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(rl,this._getTransform)}_getTransform(){var e,t;let n=this._cache.get(rl)||new _i;n.reset();let s=this.x(),i=this.y(),r=tt.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,c=this.attrs.skewX||0,h=this.attrs.skewY||0,d=this.attrs.offsetX||0,m=this.attrs.offsetY||0;if(s!==0||i!==0)n.translate(s,i);if(r!==0)n.rotate(r);if(c!==0||h!==0)n.skew(c,h);if(o!==1||l!==1)n.scale(o,l);if(d!==0||m!==0)n.translate(-1*d,-1*m);return n.dirty=!1,n}clone(e){let t=ge.cloneObject(this.attrs),n,s,i,r,o;for(n in e)t[n]=e[n];let l=new this.constructor(t);for(n in this.eventListeners){s=this.eventListeners[n],i=s.length;for(r=0;r<i;r++)if(o=s[r],o.name.indexOf(zI)<0){if(!l.eventListeners[n])l.eventListeners[n]=[];l.eventListeners[n].push(o)}}return l}_toKonvaCanvas(e){e=e||{};let t=this.getClientRect(),n=this.getStage(),s=e.x!==void 0?e.x:Math.floor(t.x),i=e.y!==void 0?e.y:Math.floor(t.y),r=e.pixelRatio||1,o=new qr({width:e.width||Math.ceil(t.width)||(n?n.width():0),height:e.height||Math.ceil(t.height)||(n?n.height():0),pixelRatio:r}),l=o.getContext(),c=new qr({width:o.width/o.pixelRatio+Math.abs(s),height:o.height/o.pixelRatio+Math.abs(i),pixelRatio:o.pixelRatio});if(e.imageSmoothingEnabled===!1)l._context.imageSmoothingEnabled=!1;if(l.save(),s||i)l.translate(-1*s,-1*i);return this.drawScene(o,void 0,c),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};let t=e.mimeType||null,n=e.quality||null,s=this._toKonvaCanvas(e).toDataURL(t,n);if(e.callback)e.callback(s);return s}toImage(e){return new Promise((t,n)=>{try{let s=e===null||e===void 0?void 0:e.callback;if(s)delete e.callback;ge._urlToImage(this.toDataURL(e),function(i){t(i),s===null||s===void 0||s(i)})}catch(s){n(s)}})}toBlob(e){return new Promise((t,n)=>{try{let s=e===null||e===void 0?void 0:e.callback;if(s)delete e.callback;this.toCanvas(e).toBlob((i)=>{t(i),s===null||s===void 0||s(i)},e===null||e===void 0?void 0:e.mimeType,e===null||e===void 0?void 0:e.quality)}catch(s){n(s)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){if(this.attrs.dragDistance!==void 0)return this.attrs.dragDistance;else if(this.parent)return this.parent.getDragDistance();else return tt.dragDistance}_off(e,t,n){let s=this.eventListeners[e],i,r,o;for(i=0;i<s.length;i++)if(r=s[i].name,o=s[i].handler,(r!=="konva"||t==="konva")&&(!t||r===t)&&(!n||n===o)){if(s.splice(i,1),s.length===0){delete this.eventListeners[e];break}i--}}_fireChangeEvent(e,t,n){this._fire(e+HI,{oldVal:t,newVal:n})}addName(e){if(!this.hasName(e)){let t=this.name(),n=t?t+" "+e:e;this.name(n)}return this}hasName(e){if(!e)return!1;let t=this.name();if(!t)return!1;return(t||"").split(/\s/g).indexOf(e)!==-1}removeName(e){let t=(this.name()||"").split(/\s/g),n=t.indexOf(e);if(n!==-1)t.splice(n,1),this.name(t.join(" "));return this}setAttr(e,t){let n=this[n4+ge._capitalize(e)];if(ge._isFunction(n))n.call(this,t);else this._setAttr(e,t);return this}_requestDraw(){if(tt.autoDrawEnabled){let e=this.getLayer()||this.getStage();e===null||e===void 0||e.batchDraw()}}_setAttr(e,t){let n=this.attrs[e];if(n===t&&!ge.isObject(t))return;if(t===void 0||t===null)delete this.attrs[e];else this.attrs[e]=t;if(this._shouldFireChangeEvents)this._fireChangeEvent(e,n,t);this._requestDraw()}_setComponentAttr(e,t,n){let s;if(n!==void 0){if(s=this.attrs[e],!s)this.attrs[e]=this.getAttr(e);this.attrs[e][t]=n,this._fireChangeEvent(e,s,n)}}_fireAndBubble(e,t,n){if(t&&this.nodeType===s4)t.target=this;let s=[VI,$I,XI,WI,KI,YI];if(!(s.indexOf(e)!==-1&&(n&&(this===n||this.isAncestorOf&&this.isAncestorOf(n))||this.nodeType==="Stage"&&!n))){this._fire(e,t);let r=s.indexOf(e)!==-1&&n&&n.isAncestorOf&&n.isAncestorOf(this)&&!n.isAncestorOf(this.parent);if((t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!r)if(n&&n.parent)this._fireAndBubble.call(this.parent,e,t,n);else this._fireAndBubble.call(this.parent,e,t)}}_getProtoListeners(e){var t,n;let{nodeType:s}=this,i=Ue.protoListenerMap.get(s)||{},r=i===null||i===void 0?void 0:i[e];if(r===void 0){r=[];let o=new Set,l=Object.getPrototypeOf(this);while(l){let c=(n=(t=l.eventListeners)===null||t===void 0?void 0:t[e])!==null&&n!==void 0?n:[];for(let h=0;h<c.length;h++){let d=c[h];if(!o.has(d))o.add(d),r.push(d)}l=Object.getPrototypeOf(l)}i[e]=r,Ue.protoListenerMap.set(s,i)}return r}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;let n=this._getProtoListeners(e);if(n)for(let i=0;i<n.length;i++)n[i].handler.call(this,t);let s=this.eventListeners[e];if(s){let i=s.slice(),r=i.length;for(let l=0;l<i.length;l++)i[l].handler.call(this,t);let o=this.eventListeners[e];if(o)for(let l=r;l<o.length;l++)o[l].handler.call(this,t)}}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){let t=e?e.pointerId:void 0,n=this.getStage(),s=this.getAbsolutePosition();if(!n)return;let i=n._getPointerById(t)||n._changedPointerPositions[0]||s;In._dragElements.set(this._id,{node:this,startPointerPos:i,offset:{x:i.x-s.x,y:i.y-s.y},dragStatus:"ready",pointerId:t,startEvent:e})}startDrag(e,t=!0){if(!In._dragElements.has(this._id))this._createDragElement(e);let n=In._dragElements.get(this._id);n.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:n.startEvent&&n.startEvent.evt||e&&e.evt},t)}_setDragPosition(e,t){let n=this.getStage()._getPointerById(t.pointerId);if(!n)return;let s={x:n.x-t.offset.x,y:n.y-t.offset.y},i=this.dragBoundFunc();if(i!==void 0){let r=i.call(this,s,e);if(!r)ge.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.");else s=r}if(!this._lastPos||this._lastPos.x!==s.x||this._lastPos.y!==s.y)this.setAbsolutePosition(s),this._requestDraw();this._lastPos=s}stopDrag(e){let t=In._dragElements.get(this._id);if(t)t.dragStatus="stopped";In._endDragBefore(e),In._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){let e=In._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(e.evt.button===void 0||tt.dragButtons.indexOf(e.evt.button)>=0))return;if(this.isDragging())return;let s=!1;if(In._dragElements.forEach((i)=>{if(this.isAncestorOf(i.node))s=!0}),!s)this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;let t=In._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",s=t&&t.dragStatus==="ready";if(n)this.stopDrag();else if(s)In._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){let t=this.getStage();if(!t)return!1;let n={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return ge.haveIntersection(n,this.getClientRect())}static create(e,t){if(ge._isString(e))e=JSON.parse(e);return this._createNode(e,t)}static _createNode(e,t){let n=Ue.prototype.getClassName.call(e),s=e.children,i,r,o;if(t)e.attrs.container=t;if(!tt[n])ge.warn('Can not find a node with class name "'+n+'". Fallback to "Shape".'),n="Shape";if(i=new tt[n](e.attrs),s){r=s.length;for(o=0;o<r;o++)i.add(Ue._createNode(s[o]))}return i}}Ue._absTransformCascadeDepth=0;Ue._pendingAfterCascade=[];Ue.protoListenerMap=new Map;Ue.prototype.nodeType="Node";Ue.prototype._attrsAffectingSize=[];Ue.prototype.eventListeners={};Ue.prototype.on(eR,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(rl),this._clearSelfAndDescendantCache(mo)});Ue.prototype.on("visibleChange.konva",function(){this._clearSelfAndDescendantCache(ub)});Ue.prototype.on("listeningChange.konva",function(){this._clearSelfAndDescendantCache(hb)});Ue.prototype.on("opacityChange.konva",function(){this._clearSelfAndDescendantCache(C0)});var cs=le.addGetterSetter;cs(Ue,"zIndex");cs(Ue,"absolutePosition");cs(Ue,"position");cs(Ue,"x",0,Pe());cs(Ue,"y",0,Pe());cs(Ue,"globalCompositeOperation","source-over",Da());cs(Ue,"opacity",1,Pe());cs(Ue,"name","",Da());cs(Ue,"id","",Da());cs(Ue,"rotation",0,Pe());le.addComponentsGetterSetter(Ue,"scale",["x","y"]);cs(Ue,"scaleX",1,Pe());cs(Ue,"scaleY",1,Pe());le.addComponentsGetterSetter(Ue,"skew",["x","y"]);cs(Ue,"skewX",0,Pe());cs(Ue,"skewY",0,Pe());le.addComponentsGetterSetter(Ue,"offset",["x","y"]);cs(Ue,"offsetX",0,Pe());cs(Ue,"offsetY",0,Pe());cs(Ue,"dragDistance",void 0,Pe());cs(Ue,"width",0,Pe());cs(Ue,"height",0,Pe());cs(Ue,"listening",!0,Ri());cs(Ue,"preventDefault",!0,Ri());cs(Ue,"filters",void 0,function(e){return this._filterUpToDate=!1,e});cs(Ue,"visible",!0,Ri());cs(Ue,"transformsEnabled","all",Da());cs(Ue,"size");cs(Ue,"dragBoundFunc");cs(Ue,"draggable",!1,Ri());le.backCompat(Ue,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class bi extends Ue{constructor(){super(...arguments);this.children=[]}getChildren(e){let t=this.children||[];if(e)return t.filter(e);return t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach((e)=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach((e)=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let n=0;n<e.length;n++)this.add(e[n]);return this}let t=e[0];if(t.getParent())return t.moveTo(this),this;return this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this}destroy(){if(this.hasChildren())this.destroyChildren();return super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){let t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){let n=[];return this._descendants((s)=>{let i=s._isMatch(e);if(i)n.push(s);if(i&&t)return!0;return!1}),n}_descendants(e){let t=!1,n=this.getChildren();for(let s of n){if(t=e(s),t)return!0;if(!s.hasChildren())continue;if(t=s._descendants(e),t)return!0}return!1}toObject(){let e=Ue.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach((t)=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();while(t){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){let t=Ue.prototype.clone.call(this,e);return this.getChildren().forEach(function(n){t.add(n.clone())}),t}getAllIntersections(e){let t=[];return this.find("Shape").forEach((n)=>{if(n.isVisible()&&n.intersects(e))t.push(n)}),t}_clearSelfAndDescendantCache(e){var t;let n=e==="absoluteTransform";if(n)Ue._absTransformCascadeDepth++;try{if(super._clearSelfAndDescendantCache(e),this.isCached())return;(t=this.children)===null||t===void 0||t.forEach(function(s){s._clearSelfAndDescendantCache(e)})}finally{if(n&&--Ue._absTransformCascadeDepth===0){let s=Ue._pendingAfterCascade;if(s.length){Ue._pendingAfterCascade=[];for(let i=0;i<s.length;i++)s[i]()}}}}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,n){t.index=n}),this._requestDraw()}drawScene(e,t,n){let s=this.getLayer(),i=e||s&&s.getCanvas(),r=i&&i.getContext(),o=this._getCanvasCache(),l=o&&o.scene,c=i&&i.isCache;if(!this.isVisible()&&!c)return this;if(l){r.save();let h=this.getAbsoluteTransform(t).getMatrix();r.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(r),r.restore()}else this._drawChildren("drawScene",i,t,n);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;let n=this.getLayer(),s=e||n&&n.hitCanvas,i=s&&s.getContext(),r=this._getCachedHitCanvas(t);if(r){i.save();let o=this.getAbsoluteTransform(t).getMatrix();i.transform(o[0],o[1],o[2],o[3],o[4],o[5]),this._drawCachedHitCanvas(i,r),i.restore()}else this._drawChildren("drawHit",s,t);return this}_drawChildren(e,t,n,s){var i;let r=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),c=this.clipFunc(),h=typeof o==="number"&&typeof l==="number"||c,d=n===this;if(h){r.save();let p=this.getAbsoluteTransform(n),b=p.getMatrix();r.transform(b[0],b[1],b[2],b[3],b[4],b[5]),r.beginPath();let v;if(c)v=c.call(this,r,this);else{let k=this.clipX(),A=this.clipY();r.rect(k||0,A||0,o,l)}r.clip.apply(r,v),b=p.copy().invert().getMatrix(),r.transform(b[0],b[1],b[2],b[3],b[4],b[5])}let m=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";if(m)r.save(),r._applyGlobalCompositeOperation(this);if((i=this.children)===null||i===void 0||i.forEach(function(p){p[e](t,n,s)}),m)r.restore();if(h)r.restore()}getClientRect(e={}){var t;let{skipTransform:n,relativeTo:s}=e,i,r,o,l,c={x:1/0,y:1/0,width:0,height:0},h=this;(t=this.children)===null||t===void 0||t.forEach(function(p){if(!p.visible())return;let b=p.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});if(b.width===0&&b.height===0)return;if(i===void 0)i=b.x,r=b.y,o=b.x+b.width,l=b.y+b.height;else i=Math.min(i,b.x),r=Math.min(r,b.y),o=Math.max(o,b.x+b.width),l=Math.max(l,b.y+b.height)});let d=this.find("Shape"),m=!1;for(let p=0;p<d.length;p++)if(d[p]._isVisible(this)){m=!0;break}if(m&&i!==void 0)c={x:i,y:r,width:o-i,height:l-r};else c={x:0,y:0,width:0,height:0};if(!n)return this._transformedRect(c,s);return c}}le.addComponentsGetterSetter(bi,"clip",["x","y","width","height"]);le.addGetterSetter(bi,"clipX",void 0,Pe());le.addGetterSetter(bi,"clipY",void 0,Pe());le.addGetterSetter(bi,"clipWidth",void 0,Pe());le.addGetterSetter(bi,"clipHeight",void 0,Pe());le.addGetterSetter(bi,"clipFunc");var Mh=new Map,r4=tt._global.PointerEvent!==void 0;function _0(e){return Mh.get(e)}function I0(e){return{evt:e,pointerId:e.pointerId}}function R0(e,t){return Mh.get(e)===t}function D0(e,t){var n;zl(e);let s=t.getStage();if(!s)return;if(Mh.set(e,t),r4){try{(n=s.content)===null||n===void 0||n.setPointerCapture(e)}catch(i){}t._fire("gotpointercapture",I0(new PointerEvent("gotpointercapture")))}}function zl(e,t){var n;let s=Mh.get(e);if(!s)return;let i=s.getStage();if(Mh.delete(e),r4){try{(n=i===null||i===void 0?void 0:i.content)===null||n===void 0||n.releasePointerCapture(e)}catch(r){}s._fire("lostpointercapture",I0(new PointerEvent("lostpointercapture")))}}var nR="Stage",sR="string",o4="px",iR="mouseout",h4="mouseleave",u4="mouseover",d4="mouseenter",m4="mousemove",p4="mousedown",g4="mouseup",Fh="pointermove",Oh="pointerdown",nf="pointerup",Nh="pointercancel",aR="lostpointercapture",q0="pointerout",Bh="pointerleave",M0="pointerover",L0="pointerenter",mb="contextmenu",b4="touchstart",w4="touchend",y4="touchmove",v4="touchcancel",pb="wheel",oR=5,lR=[[d4,"_pointerenter"],[p4,"_pointerdown"],[m4,"_pointermove"],[g4,"_pointerup"],[h4,"_pointerleave"],[b4,"_pointerdown"],[y4,"_pointermove"],[w4,"_pointerup"],[v4,"_pointercancel"],[u4,"_pointerover"],[pb,"_wheel"],[mb,"_contextmenu"],[Oh,"_pointerdown"],[Fh,"_pointermove"],[nf,"_pointerup"],[Nh,"_pointercancel"],[Bh,"_pointerleave"],[aR,"_lostpointercapture"]],db={mouse:{[q0]:iR,[Bh]:h4,[M0]:u4,[L0]:d4,[Fh]:m4,[Oh]:p4,[nf]:g4,[Nh]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[q0]:"touchout",[Bh]:"touchleave",[M0]:"touchover",[L0]:"touchenter",[Fh]:y4,[Oh]:b4,[nf]:w4,[Nh]:v4,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[q0]:q0,[Bh]:Bh,[M0]:M0,[L0]:L0,[Fh]:Fh,[Oh]:Oh,[nf]:nf,[Nh]:Nh,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Hh=(e)=>{if(e.indexOf("pointer")>=0)return"pointer";if(e.indexOf("touch")>=0)return"touch";return"mouse"},tf=(e)=>{let t=Hh(e);if(t==="pointer")return tt.pointerEventsEnabled&&db.pointer;if(t==="touch")return db.touch;if(t==="mouse")return db.mouse};function l4(e={}){if(e.clipFunc||e.clipWidth||e.clipHeight)ge.warn("Stage does not support clipping. Please use clip for Layers or Groups.");return e}var cR="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",sf=[],c4=new WeakSet,f4=(e)=>{if(!e||c4.has(e))return;c4.add(e),In._listenToWindow(e),e.document.addEventListener("visibilitychange",()=>{sf.forEach((t)=>{t.batchDraw()})})};class rf extends bi{constructor(e){super(l4(e));this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),sf.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{l4(this.attrs)}),this._checkVisibility()}_validateAdd(e){let t=e.getType()==="Layer",n=e.getType()==="FastLayer";if(!(t||n))ge.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;let e=this.visible()?"":"none";this.content.style.display=e}_getOwnerWindow(){var e;let t=this.content||this.container();return((e=t===null||t===void 0?void 0:t.ownerDocument)===null||e===void 0?void 0:e.defaultView)||(tt.isBrowser?window:null)}setContainer(e){if(typeof e===sR){let t;if(e.charAt(0)==="."){let n=e.slice(1);e=document.getElementsByClassName(n)[0]}else{if(e.charAt(0)!=="#")t=e;else t=e.slice(1);e=document.getElementById(t)}if(!e)throw"Can not find container in document with id "+t}if(this._setAttr("container",e),this.content){if(this.content.parentElement)this.content.parentElement.removeChild(this.content);e.appendChild(this.content),f4(this._getOwnerWindow())}return this}shouldDrawHit(){return!0}clear(){let e=this.children,t=e.length;for(let n=0;n<t;n++)e[n].clear();return this}clone(e){if(!e)e={};return e.container=typeof document<"u"&&document.createElement("div"),bi.prototype.clone.call(this,e)}destroy(){super.destroy();let e=this.content;if(e&&ge._isInDocument(e))this.container().removeChild(e);let t=sf.indexOf(this);if(t>-1)sf.splice(t,1);return ge.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){let e=this._pointerPositions[0]||this._changedPointerPositions[0];if(!e)return ge.warn(cR),null;return{x:e.x,y:e.y}}_getPointerById(e){return this._pointerPositions.find((t)=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();let t=new qr({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),n=t.getContext()._context,s=this.children;if(e.x||e.y)n.translate(-1*e.x,-1*e.y);return s.forEach(function(i){if(!i.isVisible())return;let r=i._toKonvaCanvas(e);n.drawImage(r._canvas,e.x,e.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}),t}getIntersection(e){if(!e)return null;let t=this.children,n=t.length,s=n-1;for(let i=s;i>=0;i--){let r=t[i].getIntersection(e);if(r)return r}return null}_resizeDOM(){let e=this.width(),t=this.height();if(this.content)this.content.style.width=e+o4,this.content.style.height=t+o4;this.children.forEach((n)=>{n.setSize({width:e,height:t}),n.draw()})}_syncBufferSize(e){return e.setSizeIfChanged(this.width(),this.height()),e}add(e,...t){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.add(arguments[s]);return this}super.add(e);let n=this.children.length;if(n>oR)ge.warn("The stage has "+n+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group.");if(e.setSize({width:this.width(),height:this.height()}),e.draw(),tt.isBrowser)this.content.appendChild(e.canvas._canvas);return this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return R0(e,this)}setPointerCapture(e){D0(e,this)}releaseCapture(e){zl(e,this)}getLayers(){return this.children}_bindContentEvents(){if(!tt.isBrowser)return;lR.forEach(([e,t])=>{this.content.addEventListener(e,(n)=>{this[t](n)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);let t=tf(e.type);if(t)this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);let t=tf(e.type);if(t)this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];if(t&&!t.getStage())t=null;return t}_pointerleave(e){let t=tf(e.type),n=Hh(e.type);if(!t)return;this.setPointersPositions(e);let s=this._getTargetShape(n),i=!(tt.isDragging()||tt.isTransforming())||tt.hitOnDragEnabled;if(s&&i)s._fireAndBubble(t.pointerout,{evt:e}),s._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[n+"targetShape"]=null;else if(i)this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this});this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){let t=tf(e.type),n=Hh(e.type);if(!t)return;this.setPointersPositions(e);let s=!1;if(this._changedPointerPositions.forEach((i)=>{let r=this.getIntersection(i);if(In.justDragged=!1,tt["_"+n+"ListenClick"]=!0,!r||!r.isListening()){this[n+"ClickStartShape"]=void 0;return}if(tt.capturePointerEventsEnabled)r.setPointerCapture(i.id);this[n+"ClickStartShape"]=r,r._fireAndBubble(t.pointerdown,{evt:e,pointerId:i.id}),s=!0;let o=e.type.indexOf("touch")>=0;if(r.preventDefault()&&e.cancelable&&o)e.preventDefault()}),!s)this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){let t=tf(e.type),n=Hh(e.type);if(!t)return;let s=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(tt.isDragging()&&In.node.preventDefault()&&e.cancelable&&s)e.preventDefault();if(this.setPointersPositions(e),!(!(tt.isDragging()||tt.isTransforming())||tt.hitOnDragEnabled))return;let r={},o=!1,l=this._getTargetShape(n);if(this._changedPointerPositions.forEach((c)=>{let h=_0(c.id)||this.getIntersection(c),d=c.id,m={evt:e,pointerId:d},p=l!==h;if(p&&l)l._fireAndBubble(t.pointerout,{...m},h),l._fireAndBubble(t.pointerleave,{...m},h);if(h){if(r[h._id])return;r[h._id]=!0}if(h&&h.isListening()){if(o=!0,p)h._fireAndBubble(t.pointerover,{...m},l),h._fireAndBubble(t.pointerenter,{...m},l),this[n+"targetShape"]=h;h._fireAndBubble(t.pointermove,{...m})}else if(l)this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[n+"targetShape"]=null}),!o)this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){let t=tf(e.type),n=Hh(e.type);if(!t)return;this.setPointersPositions(e);let s=In.justDragged||n==="pointer"&&tt.isDragging(),i=tt["_"+n+"ListenClick"]&&!s,r=this[n+"ClickStartShape"],o=this[n+"ClickEndShape"],l={},c=!1;if(this._changedPointerPositions.forEach((h)=>{let d=_0(h.id)||this.getIntersection(h);if(d){if(d.releaseCapture(h.id),l[d._id])return;l[d._id]=!0}let m=h.id,p={evt:e,pointerId:m},b=!1;if(tt["_"+n+"InDblClickWindow"])b=!0,clearTimeout(this[n+"DblTimeout"]);else if(!s)tt["_"+n+"InDblClickWindow"]=!0,clearTimeout(this[n+"DblTimeout"]);if(this[n+"DblTimeout"]=setTimeout(function(){tt["_"+n+"InDblClickWindow"]=!1},tt.dblClickWindow),d&&d.isListening()){if(c=!0,this[n+"ClickEndShape"]=d,d._fireAndBubble(t.pointerup,{...p}),i&&r===d){if(d._fireAndBubble(t.pointerclick,{...p}),b&&o&&o===d)d._fireAndBubble(t.pointerdblclick,{...p})}}else{if(this[n+"ClickEndShape"]=null,!c)this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),c=!0;if(i)this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:m});if(b)this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:m})}}),!c)this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id});if(tt["_"+n+"ListenClick"]=!1,e.cancelable&&n!=="touch"&&n!=="pointer")e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);let t=this.getIntersection(this.getPointerPosition());if(t&&t.isListening())t._fireAndBubble(mb,{evt:e});else this._fire(mb,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);let t=this.getIntersection(this.getPointerPosition());if(t&&t.isListening())t._fireAndBubble(pb,{evt:e});else this._fire(pb,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);let t=_0(e.pointerId)||this.getIntersection(this.getPointerPosition());if(t)t._fireAndBubble(nf,I0(e));zl(e.pointerId)}_lostpointercapture(e){zl(e.pointerId)}setPointersPositions(e){let t=this._getContentPosition(),n=null,s=null;if(e=e?e:window.event,e.touches!==void 0)this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,(i)=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-t.left)/t.scaleX,y:(i.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,(i)=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-t.left)/t.scaleX,y:(i.clientY-t.top)/t.scaleY})});else n=(e.clientX-t.left)/t.scaleX,s=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:n,y:s},this._pointerPositions=[{x:n,y:s,id:ge._getFirstPointerId(e)}],this._changedPointerPositions=[{x:n,y:s,id:ge._getFirstPointerId(e)}]}_setPointerPosition(e){ge.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};let e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new qr({width:0,height:0}),this.bufferHitCanvas=new Hl({pixelRatio:1,width:0,height:0}),!tt.isBrowser)return;let e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=e.ownerDocument.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),f4(this._getOwnerWindow()),this._resizeDOM()}cache(){return ge.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}rf.prototype.nodeType=nR;Qt(rf);le.addGetterSetter(rf,"container");var S4="hasShadow",k4="shadowRGBA",x4="patternImage",A4="linearGradient",T4="radialGradient",O0;function gb(){if(O0)return O0;return O0=ge.createCanvasElement().getContext("2d"),O0}var Vl={};function fR(e){let t=this.attrs.fillRule;if(t)e.fill(t);else e.fill()}function hR(e){e.stroke()}function uR(e){let t=this.attrs.fillRule;if(t)e.fill(t);else e.fill()}function dR(e){e.stroke()}function mR(){this._clearCache(S4)}function pR(){this._clearCache(k4)}function gR(){this._clearCache(x4)}function bR(){this._clearCache(A4)}function wR(){this._clearCache(T4)}class Xe extends Ue{constructor(e){super(e);let t,n=0;while(!0){if(t=ge.getHitColor(),t&&!(t in Vl))break;if(n++,n>=1e4){ge.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=ge.getRandomColor();break}}this.colorKey=t,Vl[t]=this}getContext(){return ge.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return ge.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(S4,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(x4,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){let t=gb().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){let n=new _i;n.translate(this.fillPatternX(),this.fillPatternY()),n.rotate(tt.getAngle(this.fillPatternRotation())),n.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),n.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());let s=n.getMatrix(),i=typeof DOMMatrix>"u"?{a:s[0],b:s[1],c:s[2],d:s[3],e:s[4],f:s[5]}:new DOMMatrix(s);t.setTransform(i)}return t}}_getLinearGradient(){return this._getCache(A4,this.__getLinearGradient)}__getLinearGradient(){let e=this.fillLinearGradientColorStops();if(e){let t=gb(),n=this.fillLinearGradientStartPoint(),s=this.fillLinearGradientEndPoint(),i=t.createLinearGradient(n.x,n.y,s.x,s.y);for(let r=0;r<e.length;r+=2)i.addColorStop(e[r],e[r+1]);return i}}_getRadialGradient(){return this._getCache(T4,this.__getRadialGradient)}__getRadialGradient(){let e=this.fillRadialGradientColorStops();if(e){let t=gb(),n=this.fillRadialGradientStartPoint(),s=this.fillRadialGradientEndPoint(),i=t.createRadialGradient(n.x,n.y,this.fillRadialGradientStartRadius(),s.x,s.y,this.fillRadialGradientEndRadius());for(let r=0;r<e.length;r+=2)i.addColorStop(e[r],e[r+1]);return i}}getShadowRGBA(){return this._getCache(k4,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;let e=ge.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){let e=this.hitStrokeWidth();if(e==="auto")return this.hasStroke();return this.strokeEnabled()&&!!e}intersects(e){let t=this.getStage();if(!t)return!1;let n=t._syncBufferSize(t.bufferHitCanvas);return n.getContext().clear(),this.drawHit(n,void 0,!0),n.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return Ue.prototype.destroy.call(this),delete Vl[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;let s=e||this.hasFill(),i=this.hasStroke(),r=this.getAbsoluteOpacity()!==1;if(s&&i&&r)return!0;let o=this.hasShadow(),l=this.shadowForStrokeEnabled();if(s&&i&&o&&l)return!0;return!1}setStrokeHitEnabled(e){if(ge.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e)this.hitStrokeWidth("auto");else this.hitStrokeWidth(0)}getStrokeHitEnabled(){if(this.hitStrokeWidth()===0)return!1;else return!0}getSelfRect(){let e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,n=this.getParent();while(n){if(n.isCached()){t=!0;break}n=n.getParent()}let s=e.skipTransform,i=e.relativeTo||t&&this.getStage()||void 0,r=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,c=r.width+l,h=r.height+l,d=!e.skipShadow&&this.hasShadow(),m=d?this.shadowOffsetX():0,p=d?this.shadowOffsetY():0,b=c+Math.abs(m),v=h+Math.abs(p),k=d&&this.shadowBlur()||0,A=b+k*2,T=v+k*2,E={width:A,height:T,x:-(l/2+k)+Math.min(m,0)+r.x,y:-(l/2+k)+Math.min(p,0)+r.y};if(!s)return this._transformedRect(E,i);return E}drawScene(e,t,n){let s=this.getLayer(),i=e||s.getCanvas(),r=i.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),c=this.hasShadow(),h,d=!1,m=t===this;if(!this.isVisible()&&!m)return this;if(o){r.save();let p=this.getAbsoluteTransform(t).getMatrix();return r.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(r),r.restore(),this}if(!l)return this;if(r.save(),this._useBufferCanvas()){h=this.getStage();let p=n||h._syncBufferSize(h.bufferCanvas),b=p.getContext();if(n)b.save(),b.setTransform(1,0,0,1,0,0),b.clearRect(0,0,p.width,p.height),b.restore();else b.clear();b.save(),b.imageSmoothingEnabled=r.imageSmoothingEnabled,b._applyLineJoin(this),b._applyMiterLimit(this);let v=this.getAbsoluteTransform(t).getMatrix();b.transform(v[0],v[1],v[2],v[3],v[4],v[5]),l.call(this,b,this),b.restore();let k=p.pixelRatio;if(c)r._applyShadow(this);if(!m)r._applyOpacity(this),r._applyGlobalCompositeOperation(this);r.drawImage(p._canvas,p.x||0,p.y||0,p.width/k,p.height/k)}else{if(r._applyLineJoin(this),r._applyMiterLimit(this),!m){let p=this.getAbsoluteTransform(t).getMatrix();r.transform(p[0],p[1],p[2],p[3],p[4],p[5]),r._applyOpacity(this),r._applyGlobalCompositeOperation(this)}if(c)r._applyShadow(this);l.call(this,r,this)}return r.restore(),this}drawHit(e,t,n=!1){if(!this.shouldDrawHit(t,n))return this;let s=this.getLayer(),i=e||s.hitCanvas,r=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCachedHitCanvas(t);if(!this.colorKey)ge.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()");if(l){r.save();let h=this.getAbsoluteTransform(t).getMatrix();return r.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(r,l),r.restore(),this}if(!o)return this;if(r.save(),r._applyLineJoin(this),r._applyMiterLimit(this),this!==t){let h=this.getAbsoluteTransform(t).getMatrix();r.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,r,this),r.restore(),this}drawHitFromCache(e=0){let t=this._getCachedSceneCanvas(),n=this._getCachedHitCanvas(),s=n.getContext(),i=n.getWidth(),r=n.getHeight();s.clear(),s.drawImage(t._canvas,0,0,i,r);try{let o=s.getImageData(0,0,i,r),l=o.data,c=l.length,h=ge._hexToRgb(this.colorKey);for(let d=0;d<c;d+=4)if(l[d+3]>e)l[d]=h.r,l[d+1]=h.g,l[d+2]=h.b,l[d+3]=255;else l[d+3]=0;s.putImageData(o,0,0)}catch(o){ge.error("Unable to draw hit graph from cached scene canvas. "+o.message)}return this}hasPointerCapture(e){return R0(e,this)}setPointerCapture(e){D0(e,this)}releaseCapture(e){zl(e,this)}}Xe.prototype._fillFunc=fR;Xe.prototype._strokeFunc=hR;Xe.prototype._fillFuncHit=uR;Xe.prototype._strokeFuncHit=dR;Xe.prototype._centroid=!1;Xe.prototype.nodeType="Shape";Qt(Xe);Xe.prototype.eventListeners={};Xe.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",mR);Xe.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",pR);Xe.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",gR);Xe.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",bR);Xe.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",wR);le.addGetterSetter(Xe,"stroke",void 0,fb());le.addGetterSetter(Xe,"strokeWidth",2,Pe());le.addGetterSetter(Xe,"fillAfterStrokeEnabled",!1);le.addGetterSetter(Xe,"hitStrokeWidth","auto",Rh());le.addGetterSetter(Xe,"strokeHitEnabled",!0,Ri());le.addGetterSetter(Xe,"perfectDrawEnabled",!0,Ri());le.addGetterSetter(Xe,"shadowForStrokeEnabled",!0,Ri());le.addGetterSetter(Xe,"lineJoin");le.addGetterSetter(Xe,"lineCap");le.addGetterSetter(Xe,"miterLimit");le.addGetterSetter(Xe,"sceneFunc");le.addGetterSetter(Xe,"hitFunc");le.addGetterSetter(Xe,"dash");le.addGetterSetter(Xe,"dashOffset",0,Pe());le.addGetterSetter(Xe,"shadowColor",void 0,Da());le.addGetterSetter(Xe,"shadowBlur",0,Pe());le.addGetterSetter(Xe,"shadowOpacity",1,Pe());le.addComponentsGetterSetter(Xe,"shadowOffset",["x","y"]);le.addGetterSetter(Xe,"shadowOffsetX",0,Pe());le.addGetterSetter(Xe,"shadowOffsetY",0,Pe());le.addGetterSetter(Xe,"fillPatternImage");le.addGetterSetter(Xe,"fill",void 0,fb());le.addGetterSetter(Xe,"fillPatternX",0,Pe());le.addGetterSetter(Xe,"fillPatternY",0,Pe());le.addGetterSetter(Xe,"fillLinearGradientColorStops");le.addGetterSetter(Xe,"strokeLinearGradientColorStops");le.addGetterSetter(Xe,"fillRadialGradientStartRadius",0);le.addGetterSetter(Xe,"fillRadialGradientEndRadius",0);le.addGetterSetter(Xe,"fillRadialGradientColorStops");le.addGetterSetter(Xe,"fillPatternRepeat","repeat");le.addGetterSetter(Xe,"fillEnabled",!0);le.addGetterSetter(Xe,"strokeEnabled",!0);le.addGetterSetter(Xe,"shadowEnabled",!0);le.addGetterSetter(Xe,"dashEnabled",!0);le.addGetterSetter(Xe,"strokeScaleEnabled",!0);le.addGetterSetter(Xe,"fillPriority","color");le.addComponentsGetterSetter(Xe,"fillPatternOffset",["x","y"]);le.addGetterSetter(Xe,"fillPatternOffsetX",0,Pe());le.addGetterSetter(Xe,"fillPatternOffsetY",0,Pe());le.addComponentsGetterSetter(Xe,"fillPatternScale",["x","y"]);le.addGetterSetter(Xe,"fillPatternScaleX",1,Pe());le.addGetterSetter(Xe,"fillPatternScaleY",1,Pe());le.addComponentsGetterSetter(Xe,"fillLinearGradientStartPoint",["x","y"]);le.addComponentsGetterSetter(Xe,"strokeLinearGradientStartPoint",["x","y"]);le.addGetterSetter(Xe,"fillLinearGradientStartPointX",0);le.addGetterSetter(Xe,"strokeLinearGradientStartPointX",0);le.addGetterSetter(Xe,"fillLinearGradientStartPointY",0);le.addGetterSetter(Xe,"strokeLinearGradientStartPointY",0);le.addComponentsGetterSetter(Xe,"fillLinearGradientEndPoint",["x","y"]);le.addComponentsGetterSetter(Xe,"strokeLinearGradientEndPoint",["x","y"]);le.addGetterSetter(Xe,"fillLinearGradientEndPointX",0);le.addGetterSetter(Xe,"strokeLinearGradientEndPointX",0);le.addGetterSetter(Xe,"fillLinearGradientEndPointY",0);le.addGetterSetter(Xe,"strokeLinearGradientEndPointY",0);le.addComponentsGetterSetter(Xe,"fillRadialGradientStartPoint",["x","y"]);le.addGetterSetter(Xe,"fillRadialGradientStartPointX",0);le.addGetterSetter(Xe,"fillRadialGradientStartPointY",0);le.addComponentsGetterSetter(Xe,"fillRadialGradientEndPoint",["x","y"]);le.addGetterSetter(Xe,"fillRadialGradientEndPointX",0);le.addGetterSetter(Xe,"fillRadialGradientEndPointY",0);le.addGetterSetter(Xe,"fillPatternRotation",0);le.addGetterSetter(Xe,"fillRule",void 0,Da());le.backCompat(Xe,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var yR="beforeDraw",vR="draw",E4=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],SR=E4.length;class qa extends bi{constructor(e){super(e);this.canvas=new qr,this.hitCanvas=new Hl({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);let t=this.getStage();if(t&&t.content)if(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1)t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas);else t.content.appendChild(this.getNativeCanvasElement());return this}moveToTop(){Ue.prototype.moveToTop.call(this);let e=this.getStage();if(e&&e.content)e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement());return!0}moveUp(){if(!Ue.prototype.moveUp.call(this))return!1;let t=this.getStage();if(!t||!t.content)return!1;if(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1)t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas);else t.content.appendChild(this.getNativeCanvasElement());return!0}moveDown(){if(Ue.prototype.moveDown.call(this)){let e=this.getStage();if(e){let t=e.children;if(e.content)e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas)}return!0}return!1}moveToBottom(){if(Ue.prototype.moveToBottom.call(this)){let e=this.getStage();if(e){let t=e.children;if(e.content)e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas)}return!0}return!1}getLayer(){return this}remove(){let e=this.getNativeCanvasElement();if(Ue.prototype.remove.call(this),e&&e.parentNode&&ge._isInDocument(e))e.parentNode.removeChild(e);return this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this._syncHitCanvasSize(),this._setSmoothEnabled(),this}_syncHitCanvasSize(){let e=this.isListening();this.hitCanvas.setSizeIfChanged((e?this.getWidth():0)||0,(e?this.getHeight():0)||0)}_validateAdd(e){let t=e.getType();if(t!=="Group"&&t!=="Shape")ge.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),Ue.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){if(this.visible())this.canvas._canvas.style.display="block";else this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){ge.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){ge.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){var e;if(!this._waitingForDraw)this._waitingForDraw=!0,ge.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1},(e=this.getStage())===null||e===void 0?void 0:e._getOwnerWindow());return this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,n=!1;while(!0){for(let s=0;s<SR;s++){let i=E4[s],r=this._getIntersection({x:e.x+i.x*t,y:e.y+i.y*t}),o=r.shape;if(o)return o;if(n=!!r.antialiased,!r.antialiased)break}if(n)t+=1;else return null}}_getIntersection(e){if(!this.hitCanvas.width||!this.hitCanvas.height)return{};let t=this.hitCanvas.pixelRatio,n=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,s=n[3];if(s===255){let i=ge.getHitColorKey(n[0],n[1],n[2]),r=Vl[i];if(r)return{shape:r};return{antialiased:!0}}else if(s>0)return{antialiased:!0};return{}}drawScene(e,t,n){let s=this.getLayer(),i=e||s&&s.getCanvas();if(this._fire(yR,{node:this}),this.clearBeforeDraw())i.getContext().clear();return bi.prototype.drawScene.call(this,i,t,n),this._fire(vR,{node:this}),this}drawHit(e,t){let n=this.getLayer(),s=e||n&&n.hitCanvas;if(!e&&n){if(n._syncHitCanvasSize(),n.clearBeforeDraw())n.getHitCanvas().getContext().clear()}return bi.prototype.drawHit.call(this,s,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){ge.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return ge.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;let e=this.parent;if(!!this.hitCanvas._canvas.parentNode)e.content.removeChild(this.hitCanvas._canvas);else e.content.appendChild(this.hitCanvas._canvas)}destroy(){return ge.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}qa.prototype.nodeType="Layer";Qt(qa);le.addGetterSetter(qa,"imageSmoothingEnabled",!0);le.addGetterSetter(qa,"clearBeforeDraw",!0);le.addGetterSetter(qa,"hitGraphEnabled",!0,Ri());class Uh extends qa{constructor(e){super(e);this.listening(!1),ge.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Uh.prototype.nodeType="FastLayer";Qt(Uh);class Ma extends bi{_validateAdd(e){let t=e.getType();if(t!=="Group"&&t!=="Shape")ge.throw("You may only add groups and shapes to groups.")}}Ma.prototype.nodeType="Group";Qt(Ma);var bb=function(){if(nl.performance&&nl.performance.now)return function(){return nl.performance.now()};return function(){return new Date().getTime()}}();class Gi{constructor(e,t){this.id=Gi.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:bb(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];if(e)t=Array.isArray(e)?e:[e];return this.layers=t,this}getLayers(){return this.layers}addLayer(e){let t=this.layers,n=t.length;for(let s=0;s<n;s++)if(t[s]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){let t=Gi.animations,n=t.length;for(let s=0;s<n;s++)if(t[s].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=bb(),Gi._addAnimation(this),this}stop(){return Gi._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1000/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){let t=e.id,n=this.animations,s=n.length;for(let i=0;i<s;i++)if(n[i].id===t){this.animations.splice(i,1);break}}static _runFrames(){let e={},t=this.animations;for(let n=0;n<t.length;n++){let s=t[n],{layers:i,func:r}=s;s._updateFrameObject(bb());let o=i.length,l;if(r)l=r.call(s,s.frame)!==!1;else l=!0;if(!l)continue;for(let c=0;c<o;c++){let h=i[c];if(h._id!==void 0)e[h._id]=h}}for(let n in e){if(!e.hasOwnProperty(n))continue;e[n].batchDraw()}}static _animationLoop(){let e=Gi;if(e.animations.length)e._runFrames(),ge.requestAnimFrame(e._animationLoop);else e.animRunning=!1}static _handleAnimation(){if(!this.animRunning)this.animRunning=!0,ge.requestAnimFrame(this._animationLoop)}}Gi.animations=[];Gi.animIdCounter=0;Gi.animRunning=!1;var kR={node:1,duration:1,easing:1,onFinish:1,yoyo:1},xR=1,C4=2,j4=3,_4=["fill","stroke","shadowColor"],AR=0;function P0(e){return ge.colorToRGBA(e)||ge.throw('can not tween the color "'+e+'", because it is not a valid color.')}class I4{constructor(e,t,n,s,i,r,o){this.prop=e,this.propFunc=t,this.begin=s,this._pos=s,this.duration=r,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=n,this._change=i-this.begin,this.pause()}fire(e){let t=this[e];if(t)t()}setTime(e){if(e>this.duration)if(this.yoyo)this._time=this.duration,this.reverse();else this.finish();else if(e<0)if(this.yoyo)this._time=0,this.play();else this.reset();else this._time=e,this.update()}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){if(e===void 0)e=this._time;return this.func(e,this.begin,this._change,this.duration)}play(){this.state=C4,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=j4,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){let e=this.getTimer()-this._startTime;if(this.state===C4)this.setTime(e);else if(this.state===j4)this.setTime(this.duration-e)}pause(){this.state=xR,this.fire("onPause")}getTimer(){return new Date().getTime()}}class fs{constructor(e){let t=this,n=e.node,s=n._id,i=e.easing||af.Linear,r=!!e.yoyo,o,l;if(typeof e.duration>"u")o=0.3;else if(e.duration===0)o=0.001;else o=e.duration;this.node=n,this._id=AR++;let c=n.getLayer()||(n instanceof tt.Stage?n.getLayers():null);if(!c)ge.error("Tween constructor have `node` that is not in a layer. Please add node into layer first.");if(this.anim=new Gi(function(){t.tween.onEnterFrame()},c),this.tween=new I4(l,function(h){t._tweenFunc(h)},i,0,1,o*1000,r),this._addListeners(),!fs.attrs[s])fs.attrs[s]={};if(!fs.attrs[s][this._id])fs.attrs[s][this._id]={};if(!fs.tweens[s])fs.tweens[s]={};for(l in e)if(kR[l]===void 0)this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){let n=this.node,s=n._id,i,r,o,l,c,h=fs.tweens[s][e];if(h)delete fs.attrs[s][h][e];let d=n.getAttr(e);if(ge._isArray(t)){if(i=[],r=Math.max(t.length,d.length),e==="points"&&t.length!==d.length)if(t.length>d.length)l=d,d=ge._prepareArrayForTween(d,t,n.closed());else o=t,t=ge._prepareArrayForTween(t,d,n.closed());if(e.indexOf("fill")===0)for(let m=0;m<r;m++)if(m%2===0)i.push(t[m]-d[m]);else{let p=P0(d[m]);c=P0(t[m]),d[m]=p,i.push({r:c.r-p.r,g:c.g-p.g,b:c.b-p.b,a:c.a-p.a})}else for(let m=0;m<r;m++)i.push(t[m]-d[m])}else if(_4.indexOf(e)!==-1)d=P0(d),c=P0(t),i={r:c.r-d.r,g:c.g-d.g,b:c.b-d.b,a:c.a-d.a};else i=t-d;fs.attrs[s][this._id][e]={start:d,diff:i,end:t,trueEnd:o,trueStart:l},fs.tweens[s][e]=this._id}_tweenFunc(e){let t=this.node,n=fs.attrs[t._id][this._id],s,i,r,o,l,c,h,d;for(s in n){if(i=n[s],r=i.start,o=i.diff,d=i.end,ge._isArray(r))if(l=[],h=Math.max(r.length,d.length),s.indexOf("fill")===0)for(c=0;c<h;c++)if(c%2===0)l.push((r[c]||0)+o[c]*e);else l.push("rgba("+Math.round(r[c].r+o[c].r*e)+","+Math.round(r[c].g+o[c].g*e)+","+Math.round(r[c].b+o[c].b*e)+","+(r[c].a+o[c].a*e)+")");else for(c=0;c<h;c++)l.push((r[c]||0)+o[c]*e);else if(_4.indexOf(s)!==-1)l="rgba("+Math.round(r.r+o.r*e)+","+Math.round(r.g+o.g*e)+","+Math.round(r.b+o.b*e)+","+(r.a+o.a*e)+")";else l=r+o*e;t.setAttr(s,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{let e=this.node,t=fs.attrs[e._id][this._id];if(t.points&&t.points.trueEnd)e.setAttr("points",t.points.trueEnd);if(this.onFinish)this.onFinish.call(this)},this.tween.onReset=()=>{let e=this.node,t=fs.attrs[e._id][this._id];if(t.points&&t.points.trueStart)e.points(t.points.trueStart);if(this.onReset)this.onReset()},this.tween.onUpdate=()=>{if(this.onUpdate)this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1000),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){let e=this.node._id,t=this._id,n=fs.tweens[e];if(this.pause(),this.anim)this.anim.stop();for(let s in n)delete fs.tweens[e][s];if(delete fs.attrs[e][t],fs.tweens[e]){if(Object.keys(fs.tweens[e]).length===0)delete fs.tweens[e];if(Object.keys(fs.attrs[e]).length===0)delete fs.attrs[e]}}}fs.attrs={};fs.tweens={};Ue.prototype.to=function(e){let t=e.onFinish;e.node=this,e.onFinish=function(){if(this.destroy(),t)t()},new fs(e).play()};var af={BackEaseIn(e,t,n,s){return n*(e/=s)*e*(2.70158*e-1.70158)+t},BackEaseOut(e,t,n,s){return n*((e=e/s-1)*e*(2.70158*e+1.70158)+1)+t},BackEaseInOut(e,t,n,s){let i=1.70158;if((e/=s/2)<1)return n/2*(e*e*(((i*=1.525)+1)*e-i))+t;return n/2*((e-=2)*e*(((i*=1.525)+1)*e+i)+2)+t},ElasticEaseIn(e,t,n,s,i,r){let o=0;if(e===0)return t;if((e/=s)===1)return t+n;if(!r)r=s*0.3;if(!i||i<Math.abs(n))i=n,o=r/4;else o=r/(2*Math.PI)*Math.asin(n/i);return-(i*Math.pow(2,10*(e-=1))*Math.sin((e*s-o)*(2*Math.PI)/r))+t},ElasticEaseOut(e,t,n,s,i,r){let o=0;if(e===0)return t;if((e/=s)===1)return t+n;if(!r)r=s*0.3;if(!i||i<Math.abs(n))i=n,o=r/4;else o=r/(2*Math.PI)*Math.asin(n/i);return i*Math.pow(2,-10*e)*Math.sin((e*s-o)*(2*Math.PI)/r)+n+t},ElasticEaseInOut(e,t,n,s,i,r){let o=0;if(e===0)return t;if((e/=s/2)===2)return t+n;if(!r)r=s*0.44999999999999996;if(!i||i<Math.abs(n))i=n,o=r/4;else o=r/(2*Math.PI)*Math.asin(n/i);if(e<1)return-0.5*(i*Math.pow(2,10*(e-=1))*Math.sin((e*s-o)*(2*Math.PI)/r))+t;return i*Math.pow(2,-10*(e-=1))*Math.sin((e*s-o)*(2*Math.PI)/r)*0.5+n+t},BounceEaseOut(e,t,n,s){if((e/=s)<0.36363636363636365)return n*(7.5625*e*e)+t;else if(e<0.7272727272727273)return n*(7.5625*(e-=0.5454545454545454)*e+0.75)+t;else if(e<0.9090909090909091)return n*(7.5625*(e-=0.8181818181818182)*e+0.9375)+t;else return n*(7.5625*(e-=0.9545454545454546)*e+0.984375)+t},BounceEaseIn(e,t,n,s){return n-af.BounceEaseOut(s-e,0,n,s)+t},BounceEaseInOut(e,t,n,s){if(e<s/2)return af.BounceEaseIn(e*2,0,n,s)*0.5+t;else return af.BounceEaseOut(e*2-s,0,n,s)*0.5+n*0.5+t},EaseIn(e,t,n,s){return n*(e/=s)*e+t},EaseOut(e,t,n,s){return-n*(e/=s)*(e-2)+t},EaseInOut(e,t,n,s){if((e/=s/2)<1)return n/2*e*e+t;return-n/2*(--e*(e-2)-1)+t},StrongEaseIn(e,t,n,s){return n*(e/=s)*e*e*e*e+t},StrongEaseOut(e,t,n,s){return n*((e=e/s-1)*e*e*e*e+1)+t},StrongEaseInOut(e,t,n,s){if((e/=s/2)<1)return n/2*e*e*e*e*e+t;return n/2*((e-=2)*e*e*e*e+2)+t},Linear(e,t,n,s){return n*e/s+t}};var of=ge._assign(tt,{Util:ge,Transform:_i,Node:Ue,Container:bi,Stage:rf,stages:sf,Layer:qa,FastLayer:Uh,Group:Ma,DD:In,Shape:Xe,shapes:Vl,Animation:Gi,Tween:fs,Easings:af,Context:ef,Canvas:Ih});class ra extends Xe{_sceneFunc(e){let t=tt.getAngle(this.angle()),n=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,n),e.arc(0,0,this.innerRadius(),t,0,!n),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){let e=this.innerRadius(),t=this.outerRadius(),n=this.clockwise(),s=tt.getAngle(this.angle());if(s%(Math.PI*2)===0)return s!==0?{x:-t,y:-t,width:t*2,height:t*2}:{x:e,y:0,width:t-e,height:0};let i=tt.getAngle(n?360-this.angle():this.angle()),r=Math.cos(Math.min(i,Math.PI)),o=1,l=Math.sin(Math.min(Math.max(Math.PI,i),3*Math.PI/2)),c=Math.sin(Math.min(i,Math.PI/2)),h=r*(r>0?e:t),d=o*(o>0?t:e),m=l*(l>0?e:t),p=c*(c>0?t:e);return{x:h,y:n?-1*p:m,width:d-h,height:p-m}}}ra.prototype._centroid=!0;ra.prototype.className="Arc";ra.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Qt(ra);le.addGetterSetter(ra,"innerRadius",0,Pe());le.addGetterSetter(ra,"outerRadius",0,Pe());le.addGetterSetter(ra,"angle",0,Pe());le.addGetterSetter(ra,"clockwise",!1,Ri());var TR=[[],[],[-0.5773502691896257,0.5773502691896257],[0,-0.7745966692414834,0.7745966692414834],[-0.33998104358485626,0.33998104358485626,-0.8611363115940526,0.8611363115940526],[0,-0.5384693101056831,0.5384693101056831,-0.906179845938664,0.906179845938664],[0.6612093864662645,-0.6612093864662645,-0.2386191860831969,0.2386191860831969,-0.932469514203152,0.932469514203152],[0,0.4058451513773972,-0.4058451513773972,-0.7415311855993945,0.7415311855993945,-0.9491079123427585,0.9491079123427585],[-0.1834346424956498,0.1834346424956498,-0.525532409916329,0.525532409916329,-0.7966664774136267,0.7966664774136267,-0.9602898564975363,0.9602898564975363],[0,-0.8360311073266358,0.8360311073266358,-0.9681602395076261,0.9681602395076261,-0.3242534234038089,0.3242534234038089,-0.6133714327005904,0.6133714327005904],[-0.14887433898163122,0.14887433898163122,-0.4333953941292472,0.4333953941292472,-0.6794095682990244,0.6794095682990244,-0.8650633666889845,0.8650633666889845,-0.9739065285171717,0.9739065285171717],[0,-0.26954315595234496,0.26954315595234496,-0.5190961292068118,0.5190961292068118,-0.7301520055740494,0.7301520055740494,-0.8870625997680953,0.8870625997680953,-0.978228658146057,0.978228658146057],[-0.1252334085114689,0.1252334085114689,-0.3678314989981802,0.3678314989981802,-0.5873179542866175,0.5873179542866175,-0.7699026741943047,0.7699026741943047,-0.9041172563704749,0.9041172563704749,-0.9815606342467192,0.9815606342467192],[0,-0.2304583159551348,0.2304583159551348,-0.44849275103644687,0.44849275103644687,-0.6423493394403402,0.6423493394403402,-0.8015780907333099,0.8015780907333099,-0.9175983992229779,0.9175983992229779,-0.9841830547185881,0.9841830547185881],[-0.10805494870734367,0.10805494870734367,-0.31911236892788974,0.31911236892788974,-0.5152486363581541,0.5152486363581541,-0.6872929048116855,0.6872929048116855,-0.827201315069765,0.827201315069765,-0.9284348836635735,0.9284348836635735,-0.9862838086968123,0.9862838086968123],[0,-0.20119409399743451,0.20119409399743451,-0.3941513470775634,0.3941513470775634,-0.5709721726085388,0.5709721726085388,-0.7244177313601701,0.7244177313601701,-0.8482065834104272,0.8482065834104272,-0.937273392400706,0.937273392400706,-0.9879925180204854,0.9879925180204854],[-0.09501250983763744,0.09501250983763744,-0.2816035507792589,0.2816035507792589,-0.45801677765722737,0.45801677765722737,-0.6178762444026438,0.6178762444026438,-0.755404408355003,0.755404408355003,-0.8656312023878318,0.8656312023878318,-0.9445750230732326,0.9445750230732326,-0.9894009349916499,0.9894009349916499],[0,-0.17848418149584785,0.17848418149584785,-0.3512317634538763,0.3512317634538763,-0.5126905370864769,0.5126905370864769,-0.6576711592166907,0.6576711592166907,-0.7815140038968014,0.7815140038968014,-0.8802391537269859,0.8802391537269859,-0.9506755217687678,0.9506755217687678,-0.9905754753144174,0.9905754753144174],[-0.0847750130417353,0.0847750130417353,-0.2518862256915055,0.2518862256915055,-0.41175116146284263,0.41175116146284263,-0.5597708310739475,0.5597708310739475,-0.6916870430603532,0.6916870430603532,-0.8037049589725231,0.8037049589725231,-0.8926024664975557,0.8926024664975557,-0.9558239495713977,0.9558239495713977,-0.9915651684209309,0.9915651684209309],[0,-0.16035864564022537,0.16035864564022537,-0.31656409996362983,0.31656409996362983,-0.46457074137596094,0.46457074137596094,-0.600545304661681,0.600545304661681,-0.7209661773352294,0.7209661773352294,-0.8227146565371428,0.8227146565371428,-0.9031559036148179,0.9031559036148179,-0.96020815213483,0.96020815213483,-0.9924068438435844,0.9924068438435844],[-0.07652652113349734,0.07652652113349734,-0.22778585114164507,0.22778585114164507,-0.37370608871541955,0.37370608871541955,-0.5108670019508271,0.5108670019508271,-0.636053680726515,0.636053680726515,-0.7463319064601508,0.7463319064601508,-0.8391169718222188,0.8391169718222188,-0.912234428251326,0.912234428251326,-0.9639719272779138,0.9639719272779138,-0.9931285991850949,0.9931285991850949],[0,-0.1455618541608951,0.1455618541608951,-0.2880213168024011,0.2880213168024011,-0.4243421202074388,0.4243421202074388,-0.5516188358872198,0.5516188358872198,-0.6671388041974123,0.6671388041974123,-0.7684399634756779,0.7684399634756779,-0.8533633645833173,0.8533633645833173,-0.9200993341504008,0.9200993341504008,-0.9672268385663063,0.9672268385663063,-0.9937521706203895,0.9937521706203895],[-0.06973927331972223,0.06973927331972223,-0.20786042668822127,0.20786042668822127,-0.34193582089208424,0.34193582089208424,-0.469355837986757,0.469355837986757,-0.5876404035069116,0.5876404035069116,-0.6944872631866827,0.6944872631866827,-0.7878168059792081,0.7878168059792081,-0.8658125777203002,0.8658125777203002,-0.926956772187174,0.926956772187174,-0.9700604978354287,0.9700604978354287,-0.9942945854823992,0.9942945854823992],[0,-0.1332568242984661,0.1332568242984661,-0.26413568097034495,0.26413568097034495,-0.3903010380302908,0.3903010380302908,-0.5095014778460075,0.5095014778460075,-0.6196098757636461,0.6196098757636461,-0.7186613631319502,0.7186613631319502,-0.8048884016188399,0.8048884016188399,-0.8767523582704416,0.8767523582704416,-0.9329710868260161,0.9329710868260161,-0.9725424712181152,0.9725424712181152,-0.9947693349975522,0.9947693349975522],[-0.06405689286260563,0.06405689286260563,-0.1911188674736163,0.1911188674736163,-0.3150426796961634,0.3150426796961634,-0.4337935076260451,0.4337935076260451,-0.5454214713888396,0.5454214713888396,-0.6480936519369755,0.6480936519369755,-0.7401241915785544,0.7401241915785544,-0.820001985973903,0.820001985973903,-0.8864155270044011,0.8864155270044011,-0.9382745520027328,0.9382745520027328,-0.9747285559713095,0.9747285559713095,-0.9951872199970213,0.9951872199970213]],ER=[[],[],[1,1],[0.8888888888888888,0.5555555555555556,0.5555555555555556],[0.6521451548625461,0.6521451548625461,0.34785484513745385,0.34785484513745385],[0.5688888888888889,0.47862867049936647,0.47862867049936647,0.23692688505618908,0.23692688505618908],[0.3607615730481386,0.3607615730481386,0.46791393457269104,0.46791393457269104,0.17132449237917036,0.17132449237917036],[0.4179591836734694,0.3818300505051189,0.3818300505051189,0.27970539148927664,0.27970539148927664,0.1294849661688697,0.1294849661688697],[0.362683783378362,0.362683783378362,0.31370664587788727,0.31370664587788727,0.22238103445337448,0.22238103445337448,0.10122853629037626,0.10122853629037626],[0.3302393550012598,0.1806481606948574,0.1806481606948574,0.08127438836157441,0.08127438836157441,0.31234707704000286,0.31234707704000286,0.26061069640293544,0.26061069640293544],[0.29552422471475287,0.29552422471475287,0.26926671930999635,0.26926671930999635,0.21908636251598204,0.21908636251598204,0.1494513491505806,0.1494513491505806,0.06667134430868814,0.06667134430868814],[0.2729250867779006,0.26280454451024665,0.26280454451024665,0.23319376459199048,0.23319376459199048,0.18629021092773426,0.18629021092773426,0.1255803694649046,0.1255803694649046,0.05566856711617366,0.05566856711617366],[0.24914704581340277,0.24914704581340277,0.2334925365383548,0.2334925365383548,0.20316742672306592,0.20316742672306592,0.16007832854334622,0.16007832854334622,0.10693932599531843,0.10693932599531843,0.04717533638651183,0.04717533638651183],[0.2325515532308739,0.22628318026289723,0.22628318026289723,0.2078160475368885,0.2078160475368885,0.17814598076194574,0.17814598076194574,0.13887351021978725,0.13887351021978725,0.09212149983772845,0.09212149983772845,0.04048400476531588,0.04048400476531588],[0.2152638534631578,0.2152638534631578,0.2051984637212956,0.2051984637212956,0.18553839747793782,0.18553839747793782,0.15720316715819355,0.15720316715819355,0.12151857068790319,0.12151857068790319,0.08015808715976021,0.08015808715976021,0.03511946033175186,0.03511946033175186],[0.2025782419255613,0.19843148532711158,0.19843148532711158,0.1861610000155622,0.1861610000155622,0.16626920581699392,0.16626920581699392,0.13957067792615432,0.13957067792615432,0.10715922046717194,0.10715922046717194,0.07036604748810812,0.07036604748810812,0.03075324199611727,0.03075324199611727],[0.1894506104550685,0.1894506104550685,0.18260341504492358,0.18260341504492358,0.16915651939500254,0.16915651939500254,0.14959598881657674,0.14959598881657674,0.12462897125553388,0.12462897125553388,0.09515851168249279,0.09515851168249279,0.062253523938647894,0.062253523938647894,0.027152459411754096,0.027152459411754096],[0.17944647035620653,0.17656270536699264,0.17656270536699264,0.16800410215645004,0.16800410215645004,0.15404576107681028,0.15404576107681028,0.13513636846852548,0.13513636846852548,0.11188384719340397,0.11188384719340397,0.08503614831717918,0.08503614831717918,0.0554595293739872,0.0554595293739872,0.02414830286854793,0.02414830286854793],[0.1691423829631436,0.1691423829631436,0.16427648374583273,0.16427648374583273,0.15468467512626524,0.15468467512626524,0.14064291467065065,0.14064291467065065,0.12255520671147846,0.12255520671147846,0.10094204410628717,0.10094204410628717,0.07642573025488905,0.07642573025488905,0.0497145488949698,0.0497145488949698,0.02161601352648331,0.02161601352648331],[0.1610544498487837,0.15896884339395434,0.15896884339395434,0.15276604206585967,0.15276604206585967,0.1426067021736066,0.1426067021736066,0.12875396253933621,0.12875396253933621,0.11156664554733399,0.11156664554733399,0.09149002162245,0.09149002162245,0.06904454273764123,0.06904454273764123,0.0448142267656996,0.0448142267656996,0.019461788229726478,0.019461788229726478],[0.15275338713072584,0.15275338713072584,0.14917298647260374,0.14917298647260374,0.14209610931838204,0.14209610931838204,0.13168863844917664,0.13168863844917664,0.11819453196151841,0.11819453196151841,0.10193011981724044,0.10193011981724044,0.08327674157670475,0.08327674157670475,0.06267204833410907,0.06267204833410907,0.04060142980038694,0.04060142980038694,0.017614007139152118,0.017614007139152118],[0.14608113364969041,0.14452440398997005,0.14452440398997005,0.13988739479107315,0.13988739479107315,0.13226893863333747,0.13226893863333747,0.12183141605372853,0.12183141605372853,0.10879729916714838,0.10879729916714838,0.09344442345603386,0.09344442345603386,0.0761001136283793,0.0761001136283793,0.057134425426857205,0.057134425426857205,0.036953789770852494,0.036953789770852494,0.016017228257774335,0.016017228257774335],[0.13925187285563198,0.13925187285563198,0.13654149834601517,0.13654149834601517,0.13117350478706238,0.13117350478706238,0.12325237681051242,0.12325237681051242,0.11293229608053922,0.11293229608053922,0.10041414444288096,0.10041414444288096,0.08594160621706773,0.08594160621706773,0.06979646842452049,0.06979646842452049,0.052293335152683286,0.052293335152683286,0.03377490158481415,0.03377490158481415,0.0146279952982722,0.0146279952982722],[0.13365457218610619,0.1324620394046966,0.1324620394046966,0.12890572218808216,0.12890572218808216,0.12304908430672953,0.12304908430672953,0.11499664022241136,0.11499664022241136,0.10489209146454141,0.10489209146454141,0.09291576606003515,0.09291576606003515,0.07928141177671895,0.07928141177671895,0.06423242140852585,0.06423242140852585,0.04803767173108467,0.04803767173108467,0.030988005856979445,0.030988005856979445,0.013411859487141771,0.013411859487141771],[0.12793819534675216,0.12793819534675216,0.1258374563468283,0.1258374563468283,0.12167047292780339,0.12167047292780339,0.1155056680537256,0.1155056680537256,0.10744427011596563,0.10744427011596563,0.09761865210411388,0.09761865210411388,0.08619016153195327,0.08619016153195327,0.0733464814110803,0.0733464814110803,0.05929858491543678,0.05929858491543678,0.04427743881741981,0.04427743881741981,0.028531388628933663,0.028531388628933663,0.0123412297999872,0.0123412297999872]],CR=[[1],[1,1],[1,2,1],[1,3,3,1]],yb=(e,t,n)=>{let s,i,r=20,o=n/2;s=0;for(let l=0;l<20;l++)i=o*TR[20][l]+o,s+=ER[20][l]*jR(e,t,i);return o*s},vb=(e,t,n)=>{if(n===void 0)n=1;let s=e[0]-2*e[1]+e[2],i=t[0]-2*t[1]+t[2],r=2*e[1]-2*e[0],o=2*t[1]-2*t[0],l=4*(s*s+i*i),c=4*(s*r+i*o),h=r*r+o*o;if(l===0)return n*Math.sqrt(Math.pow(e[2]-e[0],2)+Math.pow(t[2]-t[0],2));let d=c/(2*l),m=h/l,p=n+d,b=m-d*d,v=p*p+b>0?Math.sqrt(p*p+b):0,k=d*d+b>0?Math.sqrt(d*d+b):0,A=d+Math.sqrt(d*d+b)!==0?b*Math.log(Math.abs((p+v)/(d+k))):0;return Math.sqrt(l)/2*(p*v-d*k+A)};function jR(e,t,n){let s=wb(1,n,e),i=wb(1,n,t),r=s*s+i*i;return Math.sqrt(r)}var wb=(e,t,n)=>{let s=n.length-1,i,r;if(s===0)return 0;if(e===0){r=0;for(let o=0;o<=s;o++)r+=CR[s][o]*Math.pow(1-t,s-o)*Math.pow(t,o)*n[o];return r}else{i=Array(s);for(let o=0;o<s;o++)i[o]=s*(n[o+1]-n[o]);return wb(e-1,t,i)}},Sb=(e,t,n)=>{let s=1,i=e/t,r=(e-n(i))/t,o=0;while(s>0.001){let l=n(i+r),c=Math.abs(e-l)/t;if(c<s)s=c,i+=r;else{let h=n(i-r),d=Math.abs(e-h)/t;if(d<s)s=d,i-=r;else r/=2}if(o++,o>500)break}return i},R4=(e,t,n,s)=>{let i=1-s;return i*i*e+2*i*s*t+s*s*n},N0=(e,t,n,s,i,r)=>{let o=[];for(let l of[[e,n,i],[t,s,r]]){let c=(l[0]-l[1])/(l[0]-2*l[1]+l[2]);if(c>0&&c<1)o.push(R4(e,n,i,c),R4(t,s,r,c))}return o},D4=(e,t,n,s,i)=>{let r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*n+i*i*i*s},zh=(e,t,n,s,i,r,o,l)=>{let c=[];for(let h of[[e,n,i,o],[t,s,r,l]]){let d=-3*h[0]+9*h[1]-9*h[2]+3*h[3],m=6*h[0]-12*h[1]+6*h[2],p=-3*h[0]+3*h[1],b=m*m-4*d*p;if(b<0)continue;let v=-(m+(m<0?-1:1)*Math.sqrt(b))/2;for(let k of[v/d,p/v])if(k>0&&k<1)c.push(D4(e,n,i,o,k),D4(t,s,r,l,k))}return c};function kb(e,t,n,s,i,r,o){let l=Math.sqrt(Math.pow(n-e,2)+Math.pow(s-t,2)),c=Math.sqrt(Math.pow(i-n,2)+Math.pow(r-s,2)),h=l+c;if(h===0)return[n,s,n,s];let d=o*l/h,m=o*c/h,p=n-d*(i-e),b=s-d*(r-t),v=n+m*(i-e),k=s+m*(r-t);return[p,b,v,k]}function q4(e,t){let n=e.length,s=[];for(let i=2;i<n-2;i+=2){let r=kb(e[i-2],e[i-1],e[i],e[i+1],e[i+2],e[i+3],t);if(isNaN(r[0]))continue;s.push(r[0]),s.push(r[1]),s.push(e[i]),s.push(e[i+1]),s.push(r[2]),s.push(r[3])}return s}function _R(e){let t=[];for(let n=0;n+7<e.length;n+=6)t.push(e[n+6],e[n+7],...zh(e[n],e[n+1],e[n+2],e[n+3],e[n+4],e[n+5],e[n+6],e[n+7]));return t}class Mr extends Xe{constructor(e){super(e);this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_hasTension(){return this.tension()!==0&&this.points().length>4}_eachTensionSegment(e,t){let n=this.points(),s=n.length,i=this.closed(),r=this.getTensionPoints(),o=r.length,l=n[0],c=n[1],h=i?0:4;if(!i)e(l,c,r[0],r[1],r[2],r[3]),l=r[2],c=r[3];while(h<o-2){let d=r[h++],m=r[h++],p=r[h++],b=r[h++],v=r[h++],k=r[h++];t(l,c,d,m,p,b,v,k),l=v,c=k}if(!i)e(l,c,r[o-2],r[o-1],n[s-2],n[s-1])}_sceneFunc(e){let t=this.points(),n=t.length,s=this.closed(),i=this.bezier();if(!n)return;let r=0;if(e.beginPath(),e.moveTo(t[0],t[1]),this._hasTension())this._eachTensionSegment((o,l,c,h,d,m)=>e.quadraticCurveTo(c,h,d,m),(o,l,c,h,d,m,p,b)=>e.bezierCurveTo(c,h,d,m,p,b));else if(i){r=2;while(r<n)e.bezierCurveTo(t[r++],t[r++],t[r++],t[r++],t[r++],t[r++])}else for(r=2;r<n;r+=2)e.lineTo(t[r],t[r+1]);if(s)e.closePath(),e.fillStrokeShape(this);else e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){if(this.closed())return this._getTensionPointsClosed();else return q4(this.points(),this.tension())}_getTensionPointsClosed(){let e=this.points(),t=e.length,n=this.tension(),s=kb(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),i=kb(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),r=q4(e,n);return[s[2],s[3]].concat(r).concat([i[0],i[1],e[t-2],e[t-1],i[2],i[3],s[0],s[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};if(this._hasTension()){let l=[e[0],e[1]];this._eachTensionSegment((c,h,d,m,p,b)=>l.push(p,b,...N0(c,h,d,m,p,b)),(c,h,d,m,p,b,v,k)=>l.push(v,k,...zh(c,h,d,m,p,b,v,k))),e=l}else if(this.bezier())e=[e[0],e[1],..._R(e)];let t=e[0],n=e[0],s=e[1],i=e[1],r,o;for(let l=0;l<e.length/2;l++)r=e[l*2],o=e[l*2+1],t=Math.min(t,r),n=Math.max(n,r),s=Math.min(s,o),i=Math.max(i,o);return{x:t,y:s,width:n-t,height:i-s}}}Mr.prototype.className="Line";Mr.prototype._attrsAffectingSize=["points","bezier","tension"];Qt(Mr);le.addGetterSetter(Mr,"closed",!1);le.addGetterSetter(Mr,"bezier",!1);le.addGetterSetter(Mr,"tension",0,Pe());le.addGetterSetter(Mr,"points",[],Jv());class ts extends Xe{constructor(e){super(e);this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ts.parsePathData(this.data()),this.pathLength=ts.getPathLength(this.dataArray)}_sceneFunc(e){let t=this.dataArray;e.beginPath();let n=!1;for(let s=0;s<t.length;s++){let i=t[s].command,r=t[s].points;switch(i){case"L":e.lineTo(r[0],r[1]);break;case"M":e.moveTo(r[0],r[1]);break;case"C":e.bezierCurveTo(r[0],r[1],r[2],r[3],r[4],r[5]);break;case"Q":e.quadraticCurveTo(r[0],r[1],r[2],r[3]);break;case"A":let o=r[0],l=r[1],c=r[2],h=r[3],d=r[4],m=r[5],p=r[6],b=r[7],v=c>h?c:h,k=c>h?1:c/h,A=c>h?h/c:1;e.translate(o,l),e.rotate(p),e.scale(k,A),e.arc(0,0,v,d,d+m,1-b),e.scale(1/k,1/A),e.rotate(-p),e.translate(-o,-l);break;case"z":n=!0,e.closePath();break}}if(!n&&!this.hasFill())e.strokeShape(this);else e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){let c=l.points[4],h=l.points[5],d=l.points[4]+h,m=Math.PI/180;if(Math.abs(c-d)<m)m=Math.abs(c-d);if(h<0)for(let p=c-m;p>d;p-=m){let b=ts.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);e.push(b.x,b.y)}else for(let p=c+m;p<d;p+=m){let b=ts.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);e.push(b.x,b.y)}}else if(l.command==="C")e.push(l.start.x,l.start.y,l.points[4],l.points[5],...zh(l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]));else if(l.command==="Q")e.push(l.start.x,l.start.y,l.points[2],l.points[3],...N0(l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3]));else e=e.concat(l.points)});let t=e[0],n=e[0],s=e[1],i=e[1],r,o;for(let l=0;l<e.length/2;l++){if(r=e[l*2],o=e[l*2+1],!isNaN(r))t=Math.min(t,r),n=Math.max(n,r);if(!isNaN(o))s=Math.min(s,o),i=Math.max(i,o)}return{x:t,y:s,width:n-t,height:i-s}}getLength(){return this.pathLength}getPointAtLength(e){return ts.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,n,s){return Math.sqrt((n-e)*(n-e)+(s-t)*(s-t))}static getPathLength(e){let t=0;for(let n=0;n<e.length;++n)t+=e[n].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let n,s=0,i=t.length;if(!i)return null;while(s<i&&e>t[s].pathLength)e-=t[s].pathLength,++s;if(s===i){let l=s-1;while(l>0&&t[l].points.length<2)l--;return n=t[l].points.slice(-2),{x:n[0],y:n[1]}}if(e<0.01)if(t[s].command==="M")return n=t[s].points.slice(0,2),{x:n[0],y:n[1]};else return{x:t[s].start.x,y:t[s].start.y};let r=t[s],o=r.points;switch(r.command){case"L":return ts.getPointOnLine(e,r.start.x,r.start.y,o[0],o[1]);case"C":return ts.getPointOnCubicBezier(Sb(e,ts.getPathLength(t),(v)=>yb([r.start.x,o[0],o[2],o[4]],[r.start.y,o[1],o[3],o[5]],v)),r.start.x,r.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ts.getPointOnQuadraticBezier(Sb(e,ts.getPathLength(t),(v)=>vb([r.start.x,o[0],o[2]],[r.start.y,o[1],o[3]],v)),r.start.x,r.start.y,o[0],o[1],o[2],o[3]);case"A":let l=o[0],c=o[1],h=o[2],d=o[3],m=o[5],p=o[6],b=o[4];return b+=m*e/r.pathLength,ts.getPointOnEllipticalArc(l,c,h,d,b,p)}return null}static getPointOnLine(e,t,n,s,i,r,o){r=r!==null&&r!==void 0?r:t,o=o!==null&&o!==void 0?o:n;let l=this.getLineLength(t,n,s,i);if(l<0.0000000001)return{x:t,y:n};if(s===t)return{x:r,y:o+(i>n?e:-e)};let c=(i-n)/(s-t),h=Math.sqrt(e*e/(1+c*c))*(s<t?-1:1),d=c*h;if(Math.abs(o-n-c*(r-t))<0.0000000001)return{x:r+h,y:o+d};let m=((r-t)*(s-t)+(o-n)*(i-n))/(l*l),p=t+m*(s-t),b=n+m*(i-n),v=this.getLineLength(r,o,p,b),k=Math.sqrt(e*e-v*v),A=Math.sqrt(k*k/(1+c*c))*(s<t?-1:1),T=c*A;return{x:p+A,y:b+T}}static getPointOnCubicBezier(e,t,n,s,i,r,o,l,c){function h(k){return k*k*k}function d(k){return 3*k*k*(1-k)}function m(k){return 3*k*(1-k)*(1-k)}function p(k){return(1-k)*(1-k)*(1-k)}let b=l*h(e)+r*d(e)+s*m(e)+t*p(e),v=c*h(e)+o*d(e)+i*m(e)+n*p(e);return{x:b,y:v}}static getPointOnQuadraticBezier(e,t,n,s,i,r,o){function l(p){return p*p}function c(p){return 2*p*(1-p)}function h(p){return(1-p)*(1-p)}let d=r*l(e)+s*c(e)+t*h(e),m=o*l(e)+i*c(e)+n*h(e);return{x:d,y:m}}static getPointOnEllipticalArc(e,t,n,s,i,r){let o=Math.cos(r),l=Math.sin(r),c={x:n*Math.cos(i),y:s*Math.sin(i)};return{x:e+(c.x*o-c.y*l),y:t+(c.x*l+c.y*o)}}static parsePathData(e){if(!e)return[];let t=e,n=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<n.length;d++)t=t.replace(new RegExp(n[d],"g"),"|"+n[d]);let s=t.split("|"),i=[],r=[],o=0,l=0,c=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi,h;for(let d=1;d<s.length;d++){let m=s[d],p=m.charAt(0);m=m.slice(1),r.length=0;while(h=c.exec(m))r.push(h[0]);let b=[],v=p==="A"||p==="a"?0:-1;for(let k=0,A=r.length;k<A;k++){let T=r[k];if(T==="00"){if(b.push(0,0),v>=0){if(v+=2,v>=7)v-=7}continue}if(v>=0){if(v===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(T)){if(b.push(parseInt(T[0],10)),b.push(parseInt(T[1],10)),b.push(parseFloat(T.slice(2))),v+=3,v>=7)v-=7;continue}if(T==="11"||T==="10"||T==="01"){if(b.push(parseInt(T[0],10)),b.push(parseInt(T[1],10)),v+=2,v>=7)v-=7;continue}if(T==="0"||T==="1"){if(b.push(parseInt(T,10)),v+=1,v>=7)v-=7;continue}}else if(v===4){if(/^[01]\d+(?:\.\d+)?$/.test(T)){if(b.push(parseInt(T[0],10)),b.push(parseFloat(T.slice(1))),v+=2,v>=7)v-=7;continue}if(T==="0"||T==="1"){if(b.push(parseInt(T,10)),v+=1,v>=7)v-=7;continue}}let E=parseFloat(T);if(!isNaN(E))b.push(E);else b.push(0);if(v+=1,v>=7)v-=7}else{let E=parseFloat(T);if(!isNaN(E))b.push(E);else b.push(0)}}while(b.length>0){if(isNaN(b[0]))break;let k="",A=[],T=o,E=l,I,_,q,P,N,H,V,U,W,ce;switch(p){case"l":o+=b.shift(),l+=b.shift(),k="L",A.push(o,l);break;case"L":o=b.shift(),l=b.shift(),A.push(o,l);break;case"m":let ue=b.shift(),oe=b.shift();if(o+=ue,l+=oe,k="M",i.length>2&&i[i.length-1].command==="z"){for(let ae=i.length-2;ae>=0;ae--)if(i[ae].command==="M"){o=i[ae].points[0]+ue,l=i[ae].points[1]+oe;break}}A.push(o,l),p="l";break;case"M":o=b.shift(),l=b.shift(),k="M",A.push(o,l),p="L";break;case"h":o+=b.shift(),k="L",A.push(o,l);break;case"H":o=b.shift(),k="L",A.push(o,l);break;case"v":l+=b.shift(),k="L",A.push(o,l);break;case"V":l=b.shift(),k="L",A.push(o,l);break;case"C":A.push(b.shift(),b.shift(),b.shift(),b.shift()),o=b.shift(),l=b.shift(),A.push(o,l);break;case"c":A.push(o+b.shift(),l+b.shift(),o+b.shift(),l+b.shift()),o+=b.shift(),l+=b.shift(),k="C",A.push(o,l);break;case"S":if(_=o,q=l,I=i[i.length-1],I.command==="C")_=o+(o-I.points[2]),q=l+(l-I.points[3]);A.push(_,q,b.shift(),b.shift()),o=b.shift(),l=b.shift(),k="C",A.push(o,l);break;case"s":if(_=o,q=l,I=i[i.length-1],I.command==="C")_=o+(o-I.points[2]),q=l+(l-I.points[3]);A.push(_,q,o+b.shift(),l+b.shift()),o+=b.shift(),l+=b.shift(),k="C",A.push(o,l);break;case"Q":A.push(b.shift(),b.shift()),o=b.shift(),l=b.shift(),A.push(o,l);break;case"q":A.push(o+b.shift(),l+b.shift()),o+=b.shift(),l+=b.shift(),k="Q",A.push(o,l);break;case"T":if(_=o,q=l,I=i[i.length-1],I.command==="Q")_=o+(o-I.points[0]),q=l+(l-I.points[1]);o=b.shift(),l=b.shift(),k="Q",A.push(_,q,o,l);break;case"t":if(_=o,q=l,I=i[i.length-1],I.command==="Q")_=o+(o-I.points[0]),q=l+(l-I.points[1]);o+=b.shift(),l+=b.shift(),k="Q",A.push(_,q,o,l);break;case"A":P=b.shift(),N=b.shift(),H=b.shift(),V=b.shift(),U=b.shift(),W=o,ce=l,o=b.shift(),l=b.shift(),k="A",A=this.convertEndpointToCenterParameterization(W,ce,o,l,V,U,P,N,H);break;case"a":P=b.shift(),N=b.shift(),H=b.shift(),V=b.shift(),U=b.shift(),W=o,ce=l,o+=b.shift(),l+=b.shift(),k="A",A=this.convertEndpointToCenterParameterization(W,ce,o,l,V,U,P,N,H);break}i.push({command:k||p,points:A,start:{x:T,y:E},pathLength:this.calcLength(T,E,k||p,A)})}if(p==="z"||p==="Z")i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(e,t,n,s){let i,r,o,l,c=ts;switch(n){case"L":return c.getLineLength(e,t,s[0],s[1]);case"C":return yb([e,s[0],s[2],s[4]],[t,s[1],s[3],s[5]],1);case"Q":return vb([e,s[0],s[2]],[t,s[1],s[3]],1);case"A":i=0;let h=s[4],d=s[5],m=s[4]+d,p=Math.PI/180;if(Math.abs(h-m)<p)p=Math.abs(h-m);if(r=c.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],h,0),d<0)for(l=h-p;l>m;l-=p)o=c.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],l,0),i+=c.getLineLength(r.x,r.y,o.x,o.y),r=o;else for(l=h+p;l<m;l+=p)o=c.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],l,0),i+=c.getLineLength(r.x,r.y,o.x,o.y),r=o;return o=c.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],m,0),i+=c.getLineLength(r.x,r.y,o.x,o.y),i}return 0}static convertEndpointToCenterParameterization(e,t,n,s,i,r,o,l,c){let h=c*(Math.PI/180),d=Math.cos(h)*(e-n)/2+Math.sin(h)*(t-s)/2,m=-1*Math.sin(h)*(e-n)/2+Math.cos(h)*(t-s)/2,p=d*d/(o*o)+m*m/(l*l);if(p>1)o*=Math.sqrt(p),l*=Math.sqrt(p);let b=Math.sqrt((o*o*(l*l)-o*o*(m*m)-l*l*(d*d))/(o*o*(m*m)+l*l*(d*d)));if(i===r)b*=-1;if(isNaN(b))b=0;let v=b*o*m/l,k=b*-l*d/o,A=(e+n)/2+Math.cos(h)*v-Math.sin(h)*k,T=(t+s)/2+Math.sin(h)*v+Math.cos(h)*k,E=function(V){return Math.sqrt(V[0]*V[0]+V[1]*V[1])},I=function(V,U){return(V[0]*U[0]+V[1]*U[1])/(E(V)*E(U))},_=function(V,U){return(V[0]*U[1]<V[1]*U[0]?-1:1)*Math.acos(I(V,U))},q=_([1,0],[(d-v)/o,(m-k)/l]),P=[(d-v)/o,(m-k)/l],N=[(-1*d-v)/o,(-1*m-k)/l],H=_(P,N);if(I(P,N)<=-1)H=Math.PI;if(I(P,N)>=1)H=0;if(r===0&&H>0)H=H-2*Math.PI;if(r===1&&H<0)H=H+2*Math.PI;return[A,T,o,l,q,H,h,r]}}ts.prototype.className="Path";ts.prototype._attrsAffectingSize=["data"];Qt(ts);le.addGetterSetter(ts,"data");class po extends Mr{_sceneFunc(e){super._sceneFunc(e);let t=Math.PI*2,n=this.points(),s=n,i=this.tension()!==0&&n.length>4;if(i)s=this.getTensionPoints();let r=this.pointerLength(),o=n.length,l,c;if(i){let m=[s[s.length-4],s[s.length-3],s[s.length-2],s[s.length-1],n[o-2],n[o-1]],p=ts.calcLength(s[s.length-4],s[s.length-3],"C",m),b=ts.getPointOnQuadraticBezier(Math.min(1,1-r/p),m[0],m[1],m[2],m[3],m[4],m[5]);l=n[o-2]-b.x,c=n[o-1]-b.y}else l=n[o-2]-n[o-4],c=n[o-1]-n[o-3];let h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();if(this.pointerAtEnding())e.save(),e.beginPath(),e.translate(n[o-2],n[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-r,d/2),e.lineTo(-r,-d/2),e.closePath(),e.restore(),this.__fillStroke(e);if(this.pointerAtBeginning()){if(e.save(),e.beginPath(),e.translate(n[0],n[1]),i)l=(s[0]+s[2])/2-n[0],c=(s[1]+s[3])/2-n[1];else l=n[2]-n[0],c=n[3]-n[1];e.rotate((Math.atan2(-c,-l)+t)%t),e.moveTo(0,0),e.lineTo(-r,d/2),e.lineTo(-r,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)}}__fillStroke(e){let t=this.dashEnabled();if(t)this.attrs.dashEnabled=!1,e.setLineDash([]);if(e.fillStrokeShape(this),t)this.attrs.dashEnabled=!0}getSelfRect(){let e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}po.prototype.className="Arrow";Qt(po);le.addGetterSetter(po,"pointerLength",10,Pe());le.addGetterSetter(po,"pointerWidth",10,Pe());le.addGetterSetter(po,"pointerAtBeginning",!1);le.addGetterSetter(po,"pointerAtEnding",!0);class al extends Xe{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){if(this.radius()!==e/2)this.radius(e/2)}setHeight(e){if(this.radius()!==e/2)this.radius(e/2)}}al.prototype._centroid=!0;al.prototype.className="Circle";al.prototype._attrsAffectingSize=["radius"];Qt(al);le.addGetterSetter(al,"radius",0,Pe());class Fa extends Xe{_sceneFunc(e){let t=this.radiusX(),n=this.radiusY();if(e.beginPath(),e.save(),t!==n)e.scale(1,n/t);e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}Fa.prototype.className="Ellipse";Fa.prototype._centroid=!0;Fa.prototype._attrsAffectingSize=["radiusX","radiusY"];Qt(Fa);le.addComponentsGetterSetter(Fa,"radius",["x","y"]);le.addGetterSetter(Fa,"radiusX",0,Pe());le.addGetterSetter(Fa,"radiusY",0,Pe());class Zi extends Xe{constructor(e){super(e);this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",(t)=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){let e=this.image();if(e&&e.complete)return;if(e&&e.readyState===4)return;if(e&&e.addEventListener)e.addEventListener("load",this._loadListener)}_removeImageLoad(e){if(e&&e.removeEventListener)e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){let e=!!this.cornerRadius(),t=this.hasShadow();if(e&&t)return!0;return super._useBufferCanvas(!0)}_sceneFunc(e){let t=this.getWidth(),n=this.getHeight(),s=this.cornerRadius(),i=this.attrs.image,r;if(i){let o=this.attrs.cropWidth,l=this.attrs.cropHeight;if(o&&l)r=[i,this.cropX(),this.cropY(),o,l,0,0,t,n];else r=[i,0,0,t,n]}if(this.hasFill()||this.hasStroke()||s)e.beginPath(),s?ge.drawRoundedRectPath(e,t,n,s):e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this);if(i){if(s)e.clip();e.drawImage.apply(e,r)}}_hitFunc(e){let t=this.width(),n=this.height(),s=this.cornerRadius();if(e.beginPath(),!s)e.rect(0,0,t,n);else ge.drawRoundedRectPath(e,t,n,s);e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,n;return(n=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&n!==void 0?n:0}getHeight(){var e,t,n;return(n=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&n!==void 0?n:0}static fromURL(e,t,n=null){let s=ge.createImageElement();s.onload=function(){let i=new Zi({image:s});t(i)},s.onerror=n,s.crossOrigin="Anonymous",s.src=e}}Zi.prototype.className="Image";Zi.prototype._attrsAffectingSize=["image"];Qt(Zi);le.addGetterSetter(Zi,"cornerRadius",0,il(4));le.addGetterSetter(Zi,"image");le.addComponentsGetterSetter(Zi,"crop",["x","y","width","height"]);le.addGetterSetter(Zi,"cropX",0,Pe());le.addGetterSetter(Zi,"cropY",0,Pe());le.addGetterSetter(Zi,"cropWidth",0,Pe());le.addGetterSetter(Zi,"cropHeight",0,Pe());var M4=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],IR="Change.konva",RR="none",xb="up",Ab="right",Tb="down",Eb="left",DR=M4.length;class Gh extends Ma{constructor(e){super(e);this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,n,s=function(){t._sync()};for(n=0;n<DR;n++)e.on(M4[n]+IR,s)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),n,s,i,r,o,l,c;if(e&&t){switch(n=e.width(),s=e.height(),i=t.pointerDirection(),r=t.pointerWidth(),c=t.pointerHeight(),o=0,l=0,i){case xb:o=n/2,l=-1*c;break;case Ab:o=n+r,l=s/2;break;case Tb:o=n/2,l=s+c;break;case Eb:o=-1*r,l=s/2;break}t.setAttrs({x:-1*o,y:-1*l,width:n,height:s}),e.setAttrs({x:-1*o,y:-1*l})}}}Gh.prototype.className="Label";Qt(Gh);class go extends Xe{_sceneFunc(e){let t=this.width(),n=this.height(),s=this.pointerDirection(),i=this.pointerWidth(),r=this.pointerHeight(),o=this.cornerRadius(),l=0,c=0,h=0,d=0;if(typeof o==="number")l=c=h=d=Math.min(o,t/2,n/2);else l=Math.min(o[0]||0,t/2,n/2),c=Math.min(o[1]||0,t/2,n/2),d=Math.min(o[2]||0,t/2,n/2),h=Math.min(o[3]||0,t/2,n/2);if(e.beginPath(),e.moveTo(l,0),s===xb)e.lineTo((t-i)/2,0),e.lineTo(t/2,-1*r),e.lineTo((t+i)/2,0);if(e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),s===Ab)e.lineTo(t,(n-r)/2),e.lineTo(t+i,n/2),e.lineTo(t,(n+r)/2);if(e.lineTo(t,n-d),e.arc(t-d,n-d,d,0,Math.PI/2,!1),s===Tb)e.lineTo((t+i)/2,n),e.lineTo(t/2,n+r),e.lineTo((t-i)/2,n);if(e.lineTo(h,n),e.arc(h,n-h,h,Math.PI/2,Math.PI,!1),s===Eb)e.lineTo(0,(n+r)/2),e.lineTo(-1*i,n/2),e.lineTo(0,(n-r)/2);e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,n=this.pointerWidth(),s=this.pointerHeight(),i=this.pointerDirection(),r=this.width(),o=this.height();if(i===xb)t-=s,o+=s;else if(i===Tb)o+=s;else if(i===Eb)e-=n*1.5,r+=n;else if(i===Ab)r+=n*1.5;return{x:e,y:t,width:r,height:o}}}go.prototype.className="Tag";Qt(go);le.addGetterSetter(go,"pointerDirection",RR);le.addGetterSetter(go,"pointerWidth",0,Pe());le.addGetterSetter(go,"pointerHeight",0,Pe());le.addGetterSetter(go,"cornerRadius",0,il(4));class ol extends Xe{_sceneFunc(e){let t=this.cornerRadius(),n=this.width(),s=this.height();if(e.beginPath(),!t)e.rect(0,0,n,s);else ge.drawRoundedRectPath(e,n,s,t);e.closePath(),e.fillStrokeShape(this)}}ol.prototype.className="Rect";Qt(ol);le.addGetterSetter(ol,"cornerRadius",0,il(4));class La extends Xe{_sceneFunc(e){let t=this._getPoints(),n=this.radius(),s=this.sides(),i=this.cornerRadius();if(e.beginPath(),!i){e.moveTo(t[0].x,t[0].y);for(let r=1;r<t.length;r++)e.lineTo(t[r].x,t[r].y)}else ge.drawRoundedPolygonPath(e,t,s,n,i);e.closePath(),e.fillStrokeShape(this)}_getPoints(){let e=this.attrs.sides,t=this.attrs.radius||0,n=[];for(let s=0;s<e;s++)n.push({x:t*Math.sin(s*2*Math.PI/e),y:-1*t*Math.cos(s*2*Math.PI/e)});return n}getSelfRect(){let e=this._getPoints(),t=e[0].x,n=e[0].x,s=e[0].y,i=e[0].y;return e.forEach((r)=>{t=Math.min(t,r.x),n=Math.max(n,r.x),s=Math.min(s,r.y),i=Math.max(i,r.y)}),{x:t,y:s,width:n-t,height:i-s}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}La.prototype.className="RegularPolygon";La.prototype._centroid=!0;La.prototype._attrsAffectingSize=["radius"];Qt(La);le.addGetterSetter(La,"radius",0,Pe());le.addGetterSetter(La,"sides",0,Pe());le.addGetterSetter(La,"cornerRadius",0,il(4));var F4=Math.PI*2;class bo extends Xe{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,F4,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),F4,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}bo.prototype.className="Ring";bo.prototype._centroid=!0;bo.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Qt(bo);le.addGetterSetter(bo,"innerRadius",0,Pe());le.addGetterSetter(bo,"outerRadius",0,Pe());class Fr extends Xe{constructor(e){super(e);this._updated=!0,this.anim=new Gi(()=>{let t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){if(!this.anim.isRunning())return;clearInterval(this.interval),this._setInterval()})}_sceneFunc(e){let t=this.animation(),n=this.frameIndex(),s=n*4,i=this.animations()[t],r=this.frameOffsets(),o=i[s+0],l=i[s+1],c=i[s+2],h=i[s+3],d=this.image();if(this.hasFill()||this.hasStroke())e.beginPath(),e.rect(0,0,c,h),e.closePath(),e.fillStrokeShape(this);if(d)if(r){let m=r[t],p=n*2;e.drawImage(d,o,l,c,h,m[p+0],m[p+1],c,h)}else e.drawImage(d,o,l,c,h,0,0,c,h)}_hitFunc(e){let t=this.animation(),n=this.frameIndex(),s=n*4,i=this.animations()[t],r=this.frameOffsets(),o=i[s+2],l=i[s+3];if(e.beginPath(),r){let c=r[t],h=n*2;e.rect(c[h+0],c[h+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){let e=this;this.interval=setInterval(function(){e._updateIndex()},1000/this.frameRate())}start(){if(this.isRunning())return;let e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){let e=this.frameIndex(),t=this.animation(),n=this.animations(),s=n[t],i=s.length/4;if(e<i-1)this.frameIndex(e+1);else this.frameIndex(0)}}Fr.prototype.className="Sprite";Qt(Fr);le.addGetterSetter(Fr,"animation");le.addGetterSetter(Fr,"animations");le.addGetterSetter(Fr,"frameOffsets");le.addGetterSetter(Fr,"image");le.addGetterSetter(Fr,"frameIndex",0,Pe());le.addGetterSetter(Fr,"frameRate",17,Pe());le.backCompat(Fr,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Oa extends Xe{_sceneFunc(e){let t=this.innerRadius(),n=this.outerRadius(),s=this.numPoints();e.beginPath(),e.moveTo(0,0-n);for(let i=1;i<s*2;i++){let r=i%2===0?n:t,o=r*Math.sin(i*Math.PI/s),l=-1*r*Math.cos(i*Math.PI/s);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Oa.prototype.className="Star";Oa.prototype._centroid=!0;Oa.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Qt(Oa);le.addGetterSetter(Oa,"numPoints",5,Pe());le.addGetterSetter(Oa,"innerRadius",0,Pe());le.addGetterSetter(Oa,"outerRadius",0,Pe());function cf(e){return[...e].reduce((t,n,s,i)=>{if(/\p{Emoji}/u.test(n)){let r=i[s+1];if(r&&/\p{Emoji_Modifier}|\u200D/u.test(r))t.push(n+r),i[s+1]="";else t.push(n)}else if(/\p{Regional_Indicator}{2}/u.test(n+(i[s+1]||"")))t.push(n+i[s+1]);else if(s>0&&/\p{Mn}|\p{Me}|\p{Mc}/u.test(n))t[t.length-1]+=n;else if(n)t.push(n);return t},[])}var lf="auto",qR="center",B4="inherit",Vh="justify",MR="Change.konva",H4="2d",L4="-",U4="left",FR="text",LR="Text",OR="top",PR="bottom",O4="middle",z4="normal",NR="px ",B0=" ",BR="right",P4="rtl",HR="word",UR="char",N4="none",Cb="…",G4=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],zR=G4.length,$h=null;function GR(){if($h!==null)return $h;$h=!1;try{let e=document.createElement("canvas");e.width=10,e.height=10;let t=e.getContext(H4);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);let n=t.getImageData(0,0,10,10).data;for(let s=3;s<n.length;s+=4)if(n[s]>0){$h=!0;break}}}catch(e){}return $h}function VR(e){return e.split(",").map((t)=>{t=t.trim();let n=t.indexOf(" ")>=0,s=t.indexOf('"')>=0||t.indexOf("'")>=0;if(n&&!s)t=`"${t}"`;return t}).join(", ")}var H0;function jb(){if(H0)return H0;return H0=ge.createCanvasElement().getContext(H4),H0}function $R(e){if(this._partialFillStyle)e.setAttr("fillStyle",this._partialFillStyle);e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function XR(e){if(e.setAttr("miterLimit",2),this._partialStrokeStyle)e.setAttr("strokeStyle",this._partialStrokeStyle);e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function WR(e){if(e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage)e.fill=e.fill||"black";return e}class Xn extends Xe{constructor(e){super(WR(e));this._partialTextX=0,this._partialTextY=0;for(let t=0;t<zR;t++)this.on(G4[t]+MR,this._setTextData);this._setTextData()}_sceneFunc(e){var t,n;let s=this.textArr,i=s.length;if(!this.text())return;let r=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,c=this.verticalAlign(),h=this.direction(),d=0,m=this.align(),p=this.getWidth(),b=this.letterSpacing(),v=this.charRenderFunc(),k=this.fill(),A=this.textDecoration(),T=this.underlineOffset(),E=A.indexOf("underline")!==-1,I=A.indexOf("line-through")!==-1,_;h=h===B4?e.direction:h;let q=l/2,P=O4;if(!tt.legacyTextRendering){let V=this.measureSize("M");P="alphabetic";let U=(t=V.fontBoundingBoxAscent)!==null&&t!==void 0?t:V.actualBoundingBoxAscent,W=(n=V.fontBoundingBoxDescent)!==null&&n!==void 0?n:V.actualBoundingBoxDescent;q=(U-W)/2+l/2}if(h===P4)e.setAttr("direction",h);if(e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",P),e.setAttr("textAlign",U4),c===O4)d=(this.getHeight()-i*l-r*2)/2;else if(c===PR)d=this.getHeight()-i*l-r*2;e.translate(r,d+r);let N=v?e.fillStyle:void 0,H=v?e.strokeStyle:void 0;for(_=0;_<i;_++){let V=0,U=0,W=s[_],{text:ce,width:ue,lastInParagraph:oe}=W;if(e.save(),m===BR)V+=p-ue-r*2;else if(m===qR)V+=(p-ue-r*2)/2;if(E){e.save(),e.beginPath();let te=T!==null&&T!==void 0?T:!tt.legacyTextRendering?Math.round(o/4):Math.round(o/2),me=V,he=q+U+te;e.moveTo(me,he);let we=m===Vh&&!oe?p-r*2:ue;e.lineTo(me+Math.round(we),he),e.lineWidth=o/15;let be=this._getLinearGradient();e.strokeStyle=be||k,e.stroke(),e.restore()}let ae=V;if(h!==P4&&(b!==0||m===Vh||v)){let te=ce.split(" ").length-1,me=cf(ce);for(let he=0;he<me.length;he++){let we=me[he];if(we===" "&&!oe&&m===Vh)V+=(p-r*2-ue)/te;if(this._partialTextX=V,this._partialTextY=q+U,this._partialText=we,v){e.save();let ye=s.slice(0,_).reduce((We,wt)=>We+cf(wt.text).length,0),Te=he+ye;v({char:we,index:Te,x:V,y:q+U,lineIndex:_,column:he,isLastInLine:oe,width:this.measureSize(we).width,context:e});let Oe=e.fillStyle;if(Oe!==N)this._partialFillStyle=Oe;let st=e.strokeStyle;if(st!==H)this._partialStrokeStyle=st}if(e.fillStrokeShape(this),v)this._partialFillStyle=void 0,this._partialStrokeStyle=void 0,e.restore();V+=this.measureSize(we).width+b}}else{if(b!==0)e.setAttr("letterSpacing",`${b}px`);this._partialTextX=V,this._partialTextY=q+U,this._partialText=ce,e.fillStrokeShape(this)}if(I){e.save(),e.beginPath();let te=!tt.legacyTextRendering?-Math.round(o/4):0,me=ae;e.moveTo(me,q+U+te);let he=m===Vh&&!oe?p-r*2:ue;e.lineTo(me+Math.round(he),q+U+te),e.lineWidth=o/15;let we=this._getLinearGradient();e.strokeStyle=we||k,e.stroke(),e.restore()}if(e.restore(),i>1)q+=l}}_hitFunc(e){let t=this.getWidth(),n=this.getHeight();e.beginPath(),e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this)}setText(e){let t=ge._isString(e)?e:e===null||e===void 0?"":e+"";return this._setAttr(FR,t),this}getWidth(){return this.attrs.width===lf||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===lf||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return ge.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,n,s,i,r,o,l,c,h,d,m;let p=jb(),b=this.fontSize(),v;p.save(),p.font=this._getContextFont(),v=p.measureText(e),p.restore();let k=b/100;return{actualBoundingBoxAscent:(t=v.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*k,actualBoundingBoxDescent:(n=v.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(s=v.actualBoundingBoxLeft)!==null&&s!==void 0?s:-7.421875*k,actualBoundingBoxRight:(i=v.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*k,alphabeticBaseline:(r=v.alphabeticBaseline)!==null&&r!==void 0?r:0,emHeightAscent:(o=v.emHeightAscent)!==null&&o!==void 0?o:100*k,emHeightDescent:(l=v.emHeightDescent)!==null&&l!==void 0?l:-20*k,fontBoundingBoxAscent:(c=v.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*k,fontBoundingBoxDescent:(h=v.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*k,hangingBaseline:(d=v.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*k,ideographicBaseline:(m=v.ideographicBaseline)!==null&&m!==void 0?m:-21*k,width:v.width,height:b}}_getContextFont(){return this.fontStyle()+B0+this.fontVariant()+B0+(this.fontSize()+NR)+VR(this.fontFamily())}_addTextLine(e){if(this.align()===Vh)e=e.trim();let n=this._getTextWidth(e);return this.textArr.push({text:e,width:n,lastInParagraph:!1})}_getTextWidth(e){let t=this.letterSpacing(),n=e.length;return jb().measureText(e).width+t*n}_setTextData(){let e=this.text().split(`
67
- `),t=+this.fontSize(),n=0,s=this.lineHeight()*t,i=this.attrs.width,r=this.attrs.height,o=i!==lf&&i!==void 0,l=r!==lf&&r!==void 0,c=this.padding(),h=i-c*2,d=r-c*2,m=0,p=this.wrap(),b=p!==N4,v=p!==UR&&b,k=this.ellipsis();this.textArr=[],jb().font=this._getContextFont();let A=k?this._getTextWidth(Cb):0;for(let T=0,E=e.length;T<E;++T){let I=e[T],_=this._getTextWidth(I);if(o&&_>h)while(I.length>0){let q=cf(I),P=0,N=q.length,H="",V=0;while(P<N){let U=P+N>>>1,W=q.slice(0,U+1).join(""),ce=this._getTextWidth(W);if((k&&l&&m+s>d?ce+A:ce)<=h)P=U+1,H=W,V=ce;else N=U}if(H){if(v){let W=cf(H),ce=q[W.length],ue=ce===B0||ce===L4,oe;if(ue&&V<=h)oe=W.length;else{let ae=W.lastIndexOf(B0),te=W.lastIndexOf(L4);oe=Math.max(ae,te)+1}if(oe>0)P=oe,H=q.slice(0,P).join(""),V=this._getTextWidth(H)}if(H=H.trimRight(),this._addTextLine(H),n=Math.max(n,V),m+=s,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(I=q.slice(P).join("").trimLeft(),I.length>0){if(_=this._getTextWidth(I),_<=h){this._addTextLine(I),m+=s,n=Math.max(n,_);break}}}else break}else if(this._addTextLine(I),m+=s,n=Math.max(n,_),this._shouldHandleEllipsis(m)&&T<E-1)this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1])this.textArr[this.textArr.length-1].lastInParagraph=!0;if(l&&m+s>d)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){let t=+this.fontSize(),n=this.lineHeight()*t,s=this.attrs.height,i=s!==lf&&s!==void 0,r=this.padding(),o=s-r*2;return this.wrap()===N4||i&&e+n>o}_tryToAddEllipsisToLastLine(){let e=this.attrs.width,t=e!==lf&&e!==void 0,n=this.padding(),s=e-n*2,i=this.ellipsis(),r=this.textArr[this.textArr.length-1];if(!r||!i)return;if(t){if(!(this._getTextWidth(r.text+Cb)<s))r.text=r.text.slice(0,r.text.length-3)}this.textArr.splice(this.textArr.length-1,1),this._addTextLine(r.text+Cb)}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){let e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();if(e&&t)return!0;if(t&&this.getAbsoluteOpacity()!==1&&GR())return!0;return super._useBufferCanvas()}}Xn.prototype._fillFunc=$R;Xn.prototype._strokeFunc=XR;Xn.prototype.className=LR;Xn.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];Qt(Xn);le.overWriteSetter(Xn,"width",Rh());le.overWriteSetter(Xn,"height",Rh());le.addGetterSetter(Xn,"direction",B4);le.addGetterSetter(Xn,"fontFamily","Arial");le.addGetterSetter(Xn,"fontSize",12,Pe());le.addGetterSetter(Xn,"fontStyle",z4);le.addGetterSetter(Xn,"fontVariant",z4);le.addGetterSetter(Xn,"padding",0,Pe());le.addGetterSetter(Xn,"align",U4);le.addGetterSetter(Xn,"verticalAlign",OR);le.addGetterSetter(Xn,"lineHeight",1,Pe());le.addGetterSetter(Xn,"wrap",HR);le.addGetterSetter(Xn,"ellipsis",!1,Ri());le.addGetterSetter(Xn,"letterSpacing",0,Pe());le.addGetterSetter(Xn,"text","",Da());le.addGetterSetter(Xn,"textDecoration","");le.addGetterSetter(Xn,"underlineOffset",void 0,Pe());le.addGetterSetter(Xn,"charRenderFunc",void 0);var KR="",V4="normal";function $4(e){e.fillText(this.partialText,0,0)}function X4(e){e.strokeText(this.partialText,0,0)}class Fs extends Xe{constructor(e){super(e);this.dummyCanvas=ge.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva directionChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return ts.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;let t=this.pathLength;if(e>t)return null;return ts.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ts.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();let t=this.textDecoration(),n=this.fill(),s=this.fontSize(),i=this.glyphInfo,r=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;if(r)e.beginPath();for(let l=0;l<i.length;l++){e.save();let c=i[l].p0;if(e.translate(c.x,c.y),e.rotate(i[l].rotation),this.partialText=i[l].text,e.fillStrokeShape(this),r){if(l===0)e.moveTo(0,s/2+1);e.lineTo(i[l].width,s/2+1)}e.restore()}if(r)e.strokeStyle=n,e.lineWidth=s/20,e.stroke();if(o){e.beginPath();for(let l=0;l<i.length;l++){e.save();let c=i[l].p0;if(e.translate(c.x,c.y),e.rotate(i[l].rotation),l===0)e.moveTo(0,0);e.lineTo(i[l].width,0),e.restore()}e.strokeStyle=n,e.lineWidth=s/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();let t=this.glyphInfo;if(t.length>=1){let n=t[0].p0;e.moveTo(n.x,n.y)}for(let n=0;n<t.length;n++){let s=t[n].p1;e.lineTo(s.x,s.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return ge.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return Xn.prototype.setText.call(this,e)}_getContextFont(){return Xn.prototype._getContextFont.call(this)}_getTextSize(e){let n=this.dummyCanvas.getContext("2d");n.save(),n.font=this._getContextFont();let s=n.measureText(e);return n.restore(),{width:s.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){let e=cf(this.text());if(this.direction()==="rtl")e.reverse();let t=[],n=0;for(let p=0;p<e.length;p++)t.push({char:e[p],width:this._getTextSize(e[p]).width}),n+=t[p].width;let{width:s,height:i}=this._getTextSize(this.attrs.text);if(this.textWidth=n,this.textHeight=i,this.glyphInfo=[],!this.attrs.data)return null;let r=this.letterSpacing(),o=this.align(),l=this.kerningFunc(),c=Math.max(0,n-s),h=Math.max(this.textWidth+((this.attrs.text||"").length-1)*r,0),d=0;if(o==="center")d=Math.max(0,this.pathLength/2-h/2);if(o==="right")d=Math.max(0,this.pathLength-h);let m=d;for(let p=0;p<t.length;p++){let b=this._getPointAtLength(m);if(!b)return;let v=t[p].char,k=t[p].width+r;if(v===" "&&o==="justify"){let P=this.text().split(" ").length-1;k+=(this.pathLength-h)/P}let A=m+k,T=this._getPointAtLength(A>this.pathLength&&A-this.pathLength<=c?this.pathLength:A);if(!T)return;let E=ts.getLineLength(b.x,b.y,T.x,T.y),I=0;if(l)try{I=l(t[p-1].char,v)*this.fontSize()}catch(P){I=0}b.x+=I,T.x+=I,this.textWidth+=I;let _=ts.getPointOnLine(I+E/2,b.x,b.y,T.x,T.y),q=Math.atan2(T.y-b.y,T.x-b.x);this.glyphInfo.push({transposeX:_.x,transposeY:_.y,text:e[p],rotation:q,p0:b,p1:T,width:E}),m+=k}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};let e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,n=e[0]||0,s=e[1]||0,i=e[1]||0,r,o;for(let c=0;c<e.length/2;c++)r=e[c*2],o=e[c*2+1],t=Math.min(t,r),n=Math.max(n,r),s=Math.min(s,o),i=Math.max(i,o);let l=this.fontSize();return{x:t-l/2,y:s-l/2,width:n-t+l,height:i-s+l}}destroy(){return ge.releaseCanvas(this.dummyCanvas),super.destroy()}}Fs.prototype._fillFunc=$4;Fs.prototype._strokeFunc=X4;Fs.prototype._fillFuncHit=$4;Fs.prototype._strokeFuncHit=X4;Fs.prototype.className="TextPath";Fs.prototype._attrsAffectingSize=["text","fontSize","data"];Qt(Fs);le.addGetterSetter(Fs,"data");le.addGetterSetter(Fs,"fontFamily","Arial");le.addGetterSetter(Fs,"fontSize",12,Pe());le.addGetterSetter(Fs,"fontStyle",V4);le.addGetterSetter(Fs,"align","left");le.addGetterSetter(Fs,"letterSpacing",0,Pe());le.addGetterSetter(Fs,"textBaseline","middle");le.addGetterSetter(Fs,"fontVariant",V4);le.addGetterSetter(Fs,"text",KR);le.addGetterSetter(Fs,"textDecoration","");le.addGetterSetter(Fs,"kerningFunc",void 0);le.addGetterSetter(Fs,"direction","inherit");var Y4="tr-konva",YR=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map((e)=>e+`.${Y4}`).join(" "),W4="nodesRect",QR=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],JR={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ZR="ontouchstart"in tt._global;function eD(e,t,n){if(e==="rotater")return n;t+=ge.degToRad(JR[e]||0);let s=(ge.radToDeg(t)%360+360)%360;if(ge._inRange(s,337.5,360)||ge._inRange(s,0,22.5))return"ns-resize";else if(ge._inRange(s,22.5,67.5))return"nesw-resize";else if(ge._inRange(s,67.5,112.5))return"ew-resize";else if(ge._inRange(s,112.5,157.5))return"nwse-resize";else if(ge._inRange(s,157.5,202.5))return"ns-resize";else if(ge._inRange(s,202.5,247.5))return"nesw-resize";else if(ge._inRange(s,247.5,292.5))return"ew-resize";else if(ge._inRange(s,292.5,337.5))return"nwse-resize";else return ge.error("Transformer has unknown angle for cursor detection: "+s),"pointer"}var U0=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],K4=1e8;function tD(e){return{x:e.x+e.width/2*Math.cos(e.rotation)+e.height/2*Math.sin(-e.rotation),y:e.y+e.height/2*Math.cos(e.rotation)+e.width/2*Math.sin(e.rotation)}}function Q4(e,t,n){let s=n.x+(e.x-n.x)*Math.cos(t)-(e.y-n.y)*Math.sin(t),i=n.y+(e.x-n.x)*Math.sin(t)+(e.y-n.y)*Math.cos(t);return{...e,rotation:e.rotation+t,x:s,y:i}}function nD(e,t){let n=tD(e);return Q4(e,t,n)}function sD(e,t,n){let s=t;for(let i=0;i<e.length;i++){let r=tt.getAngle(e[i]),o=Math.abs(r-t)%(Math.PI*2);if(Math.min(o,Math.PI*2-o)<n)s=r}return s}var _b=0;class wn extends Ma{constructor(e){super(e);if(this._movingAnchorName=null,this._transforming=!1,this._transformWindow=null,this._elementsCreated=!1,this._updateScheduled=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(YR,this.update),this.getNode())this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return ge.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return Y4+this._id}setNodes(e=[]){if(this._nodes&&this._nodes.length)this.detach();let t=e.filter((s)=>{if(s.isAncestorOf(this))return ge.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1;return!0});if(this._nodes=e=t,e.length===1&&this.useSingleNodeRotation())this.rotation(e[0].getAbsoluteRotation());else this.rotation(0);if(this._nodes.forEach((s)=>{let i=()=>{if(this._transforming)return;if(this.nodes().length===1&&this.useSingleNodeRotation())this.rotation(this.nodes()[0].getAbsoluteRotation());if(this._resetTransformCache(),!this.isDragging())this._scheduleUpdate()};if(s._attrsAffectingSize.length){let r=s._attrsAffectingSize.map((o)=>o+"Change."+this._getEventNamespace()).join(" ");s.on(r,i)}s.on(QR.map((r)=>r+`.${this._getEventNamespace()}`).join(" "),i),s.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),this._proxyDrag(s)}),this._resetTransformCache(),!!this.findOne(".top-left"))this.update();return this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,(n)=>{if(t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back"))this.startDrag(n,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,(n)=>{if(!t)return;let s=e.getAbsolutePosition(),i=s.x-t.x,r=s.y-t.y;this.nodes().forEach((o)=>{if(o===e)return;if(o.isDragging())return;let l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+i,y:l.y+r}),o.startDrag(n)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){if(this._nodes)this._nodes.forEach((e)=>{e.off("."+this._getEventNamespace())});this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(W4),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(W4,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),n){let s=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=e.getAbsoluteScale(n),r=e.getAbsolutePosition(n),o=s.x*i.x-e.offsetX()*i.x,l=s.y*i.y-e.offsetY()*i.y,c=(tt.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),h={x:r.x+o*Math.cos(c)+l*Math.sin(-c),y:r.y+l*Math.cos(c)+o*Math.sin(c),width:s.width*i.x,height:s.height*i.y,rotation:c};return Q4(h,-tt.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-K4,y:-K4,width:0,height:0,rotation:0};let t=[];this.nodes().map((c)=>{let h=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],m=c.getAbsoluteTransform();d.forEach(function(p){let b=m.point(p);t.push(b)})});let n=new _i;n.rotate(-tt.getAngle(this.rotation()));let s=1/0,i=1/0,r=-1/0,o=-1/0;t.forEach(function(c){let h=n.point(c);if(s===void 0)s=r=h.x,i=o=h.y;s=Math.min(s,h.x),i=Math.min(i,h.y),r=Math.max(r,h.x),o=Math.max(o,h.y)}),n.invert();let l=n.point({x:s,y:i});return{x:l.x,y:l.y,width:r-s,height:o-i,rotation:tt.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),U0.forEach((e)=>{this._createAnchor(e)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(e){let t=new ol({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ZR?10:"auto"}),n=this;t.on("mousedown touchstart",function(s){n._handleMouseDown(s)}),t.on("dragstart",(s)=>{t.stopDrag(),s.cancelBubble=!0}),t.on("dragend",(s)=>{s.cancelBubble=!0}),t.on("mouseenter",()=>{let s=tt.getAngle(this.rotation()),i=this.rotateAnchorCursor(),r=eD(e,s,i);t.getStage().content&&(t.getStage().content.style.cursor=r),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){let e=new Xe({name:"back",width:0,height:0,sceneFunc(t,n){let s=n.getParent(),i=s.padding(),r=n.width(),o=n.height();if(t.beginPath(),t.rect(-i,-i,r+i*2,o+i*2),s.rotateEnabled()&&s.rotateLineVisible()){let l=s.rotateAnchorAngle(),c=s.rotateAnchorOffset(),h=ge.degToRad(l),d=Math.sin(h),m=-Math.cos(h),p=r/2,b=o/2,v=1/0;if(m<0)v=Math.min(v,-b/m);else if(m>0)v=Math.min(v,(o-b)/m);if(d<0)v=Math.min(v,-p/d);else if(d>0)v=Math.min(v,(r-p)/d);let k=p+d*v,A=b+m*v,T=ge._sign(o),E=k+d*c*T,I=A+m*c*T;t.moveTo(k,A),t.lineTo(E,I)}t.fillStrokeShape(n)},hitFunc:(t,n)=>{if(!this.shouldOverdrawWholeArea())return;let s=this.padding();t.beginPath(),t.rect(-s,-s,n.width()+s*2,n.height()+s*2),t.fillStrokeShape(n)}});this.add(e),this._proxyDrag(e),e.on("dragstart",(t)=>{t.cancelBubble=!0}),e.on("dragmove",(t)=>{t.cancelBubble=!0}),e.on("dragend",(t)=>{t.cancelBubble=!0}),this.on("dragmove",(t)=>{this.update()})}_handleMouseDown(e){var t;if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];let n=this._getNodeRect(),{width:s,height:i}=n,r=Math.sqrt(Math.pow(s,2)+Math.pow(i,2));this.sin=Math.abs(i/r),this.cos=Math.abs(s/r);let o=(t=this.getStage())===null||t===void 0?void 0:t._getOwnerWindow();if(this._transformWindow=o||null,o)o.addEventListener("mousemove",this._handleMouseMove),o.addEventListener("touchmove",this._handleMouseMove),o.addEventListener("mouseup",this._handleMouseUp,!0),o.addEventListener("touchend",this._handleMouseUp,!0);this._transforming=!0;let l=e.target.getAbsolutePosition(),c=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:c.x-l.x,y:c.y-l.y},_b++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach((h)=>{h._fire("transformstart",{evt:e.evt,target:h})})}_handleMouseMove(e){let t,n,s,i=this.findOne("."+this._movingAnchorName),r=i.getStage();r.setPointersPositions(e);let o=r.getPointerPosition(),l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y},c=i.getAbsolutePosition();if(this.anchorDragBoundFunc())l=this.anchorDragBoundFunc()(c,l,e);i.setAbsolutePosition(l);let h=i.getAbsolutePosition();if(c.x===h.x&&c.y===h.y)return;if(this._movingAnchorName==="rotater"){let E=this._getNodeRect();t=i.x()-E.width/2,n=-i.y()+E.height/2;let I=tt.getAngle(this.rotateAnchorAngle()),_=Math.atan2(-n,t)+Math.PI/2-I;if(E.height<0)_-=Math.PI;let P=tt.getAngle(this.rotation())+_,N=tt.getAngle(this.rotationSnapTolerance()),V=sD(this.rotationSnaps(),P,N)-E.rotation,U=nD(E,V);this._fitNodesInto(U,e);return}let d=this.shiftBehavior(),m;if(d==="inverted")m=this.keepRatio()&&!e.shiftKey;else if(d==="none")m=this.keepRatio();else m=this.keepRatio()||e.shiftKey;let p=this.centeredScaling()||e.altKey,b=!1;if(this._movingAnchorName==="top-left"){if(m){b=!0;let E=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};s=Math.sqrt(Math.pow(E.x-i.x(),2)+Math.pow(E.y-i.y(),2));let I=this.findOne(".top-left").x()>E.x?-1:1,_=this.findOne(".top-left").y()>E.y?-1:1;t=s*this.cos*I,n=s*this.sin*_,this.findOne(".top-left").x(E.x-t),this.findOne(".top-left").y(E.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){b=!0;let E=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};s=Math.sqrt(Math.pow(i.x()-E.x,2)+Math.pow(E.y-i.y(),2));let I=this.findOne(".top-right").x()<E.x?-1:1,_=this.findOne(".top-right").y()>E.y?-1:1;t=s*this.cos*I,n=s*this.sin*_,this.findOne(".top-right").x(E.x+t),this.findOne(".top-right").y(E.y-n)}var v=i.position();this.findOne(".top-left").y(v.y),this.findOne(".bottom-right").x(v.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){b=!0;let E=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};s=Math.sqrt(Math.pow(E.x-i.x(),2)+Math.pow(i.y()-E.y,2));let I=E.x<i.x()?-1:1,_=i.y()<E.y?-1:1;t=s*this.cos*I,n=s*this.sin*_,i.x(E.x-t),i.y(E.y+n)}v=i.position(),this.findOne(".top-left").x(v.x),this.findOne(".bottom-right").y(v.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(i.y());else if(this._movingAnchorName==="bottom-right"){if(m){b=!0;let E=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};s=Math.sqrt(Math.pow(i.x()-E.x,2)+Math.pow(i.y()-E.y,2));let I=this.findOne(".bottom-right").x()<E.x?-1:1,_=this.findOne(".bottom-right").y()<E.y?-1:1;t=s*this.cos*I,n=s*this.sin*_,this.findOne(".bottom-right").x(E.x+t),this.findOne(".bottom-right").y(E.y+n)}}else console.error(Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(p=this.centeredScaling()||e.altKey,p){let E=this.findOne(".top-left"),I=this.findOne(".bottom-right"),_=E.x(),q=E.y(),P=this.getWidth()-I.x(),N=this.getHeight()-I.y();I.move({x:-_,y:-q}),E.move({x:P,y:N})}let k=this.findOne(".top-left").getAbsolutePosition();t=k.x,n=k.y;let A=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),T=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:A,height:T,rotation:tt.getAngle(this.rotation())},e,b)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1;let n=this._transformWindow;if(this._transformWindow=null,n)n.removeEventListener("mousemove",this._handleMouseMove),n.removeEventListener("touchmove",this._handleMouseMove),n.removeEventListener("mouseup",this._handleMouseUp,!0),n.removeEventListener("touchend",this._handleMouseUp,!0);let s=this.getNode();if(_b--,this._fire("transformend",{evt:e,target:s}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),s)this._nodes.forEach((i)=>{var r;i._fire("transformend",{evt:e,target:i}),(r=i.getLayer())===null||r===void 0||r.batchDraw()});this._movingAnchorName=null}}_fitNodesInto(e,t,n=!1){let s=tt.autoDrawEnabled;tt.autoDrawEnabled=!1;try{return this._doFitNodesInto(e,t,n)}finally{tt.autoDrawEnabled=s}}_doFitNodesInto(e,t,n=!1){let s=this._getNodeRect(),i=1;if(ge._inRange(e.width,-this.padding()*2-1,1)){this.update();return}if(ge._inRange(e.height,-this.padding()*2-1,1)){this.update();return}let r=new _i;r.rotate(tt.getAngle(this.rotation()));let o=n?0:this.padding()*2,l=null,c=null;if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){let A=r.point({x:-o,y:0});e.x+=A.x,e.y+=A.y,e.width+=o,l={axis:"width",from:"left",to:"right",offset:A}}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){let A=r.point({x:o,y:0});e.width+=o,l={axis:"width",from:"right",to:"left",offset:A}}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){let A=r.point({x:0,y:-o});e.x+=A.x,e.y+=A.y,e.height+=o,c={axis:"height",from:"top",to:"bottom",offset:A}}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){let A=r.point({x:0,y:o});e.height+=o,c={axis:"height",from:"bottom",to:"top",offset:A}}if(this.boundBoxFunc()){let A=this.boundBoxFunc()(s,e);if(A)e=A;else ge.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}for(let A of[l,c])if(A&&e[A.axis]<0&&this._movingAnchorName)this._movingAnchorName=this._movingAnchorName.replace(A.from,A.to),this._anchorDragOffset.x-=A.offset.x,this._anchorDragOffset.y-=A.offset.y;let h=1e7,d=new _i;d.translate(s.x,s.y),d.rotate(s.rotation),d.scale(s.width/h,s.height/h);let m=new _i,p=e.width/h,b=e.height/h;if(this.flipEnabled()===!1)m.translate(e.x,e.y),m.rotate(e.rotation),m.translate(e.width<0?e.width:0,e.height<0?e.height:0),m.scale(Math.abs(p),Math.abs(b));else m.translate(e.x,e.y),m.rotate(e.rotation),m.scale(p,b);let v=m.multiply(d.invert()),k=new Set;this._nodes.forEach((A)=>{if(!A.getStage())return;let T=A.getParent().getAbsoluteTransform(),E=A.getTransform().copy();E.translate(A.offsetX(),A.offsetY());let I=new _i;I.multiply(T.copy().invert()).multiply(v).multiply(T).multiply(E);let _=I.decompose();A.setAttrs(_);let q=A.getLayer();if(q)k.add(q)}),this.rotation(ge._getRotation(e.rotation)),this._nodes.forEach((A)=>{this._fire("transform",{evt:t,target:A}),A._fire("transform",{evt:t,target:A})}),this._resetTransformCache(),this.update(),k.add(this.getLayer()),k.forEach((A)=>A&&A.batchDraw())}_scheduleUpdate(){if(this._updateScheduled)return;this._updateScheduled=!0,Ue._runAfterAbsTransformCascade(()=>{var e;if(this._updateScheduled=!1,!((e=this._nodes)===null||e===void 0?void 0:e.length)||this._transforming||this.isDragging())return;this.update()})}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;let t=this._getNodeRect();this.rotation(ge._getRotation(t.rotation));let{width:n,height:s}=t,i=this.enabledAnchors(),r=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.forEach((q)=>{q.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:r&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:l/2+o,visible:r&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:r&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:s/2,offsetX:l/2+o,visible:r&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:s/2,offsetX:l/2-o,visible:r&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:s,offsetX:l/2+o,offsetY:l/2-o,visible:r&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:s,offsetY:l/2-o,visible:r&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:s,offsetX:l/2-o,offsetY:l/2-o,visible:r&&i.indexOf("bottom-right")>=0});let h=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),m=ge.degToRad(h),p=Math.sin(m),b=-Math.cos(m),v=n/2,k=s/2,A=1/0;if(b<0)A=Math.min(A,-k/b);else if(b>0)A=Math.min(A,(s-k)/b);if(p<0)A=Math.min(A,-v/p);else if(p>0)A=Math.min(A,(n-v)/p);let T=v+p*A,E=k+b*A,I=ge._sign(s);this._batchChangeChild(".rotater",{x:T+p*d*I,y:E+b*d*I-o*b,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:s,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some((q)=>q.draggable()),x:0,y:0});let _=this.anchorStyleFunc();if(_)c.forEach((q)=>{_(q)});(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();let e=this.findOne("."+this._movingAnchorName);if(e)e.stopDrag()}}destroy(){if(this.getStage()&&this._cursorChange)this.getStage().content&&(this.getStage().content.style.cursor="");return Ma.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...e){if(this._elementsCreated)return ge.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this;return super.add(...e)}toObject(){return Ue.prototype.toObject.call(this)}clone(e){return Ue.prototype.clone.call(this,e)}getClientRect(){if(this.nodes().length>0)return super.getClientRect();else return{x:0,y:0,width:0,height:0}}}wn.isTransforming=()=>_b>0;function iD(e){if(!(e instanceof Array))ge.warn("enabledAnchors value should be an array");if(e instanceof Array)e.forEach(function(t){if(U0.indexOf(t)===-1)ge.warn("Unknown anchor name: "+t+". Available names are: "+U0.join(", "))});return e||[]}wn.prototype.className="Transformer";Qt(wn);le.addGetterSetter(wn,"enabledAnchors",U0,iD);le.addGetterSetter(wn,"flipEnabled",!0,Ri());le.addGetterSetter(wn,"resizeEnabled",!0);le.addGetterSetter(wn,"anchorSize",10,Pe());le.addGetterSetter(wn,"rotateEnabled",!0);le.addGetterSetter(wn,"rotateLineVisible",!0);le.addGetterSetter(wn,"rotationSnaps",[]);le.addGetterSetter(wn,"rotateAnchorOffset",50,Pe());le.addGetterSetter(wn,"rotateAnchorAngle",0,Pe());le.addGetterSetter(wn,"rotateAnchorCursor","crosshair");le.addGetterSetter(wn,"rotationSnapTolerance",5,Pe());le.addGetterSetter(wn,"borderEnabled",!0);le.addGetterSetter(wn,"anchorStroke","rgb(0, 161, 255)");le.addGetterSetter(wn,"anchorStrokeWidth",1,Pe());le.addGetterSetter(wn,"anchorFill","white");le.addGetterSetter(wn,"anchorCornerRadius",0,Pe());le.addGetterSetter(wn,"borderStroke","rgb(0, 161, 255)");le.addGetterSetter(wn,"borderStrokeWidth",1,Pe());le.addGetterSetter(wn,"borderDash");le.addGetterSetter(wn,"keepRatio",!0);le.addGetterSetter(wn,"shiftBehavior","default");le.addGetterSetter(wn,"centeredScaling",!1);le.addGetterSetter(wn,"ignoreStroke",!1);le.addGetterSetter(wn,"padding",0,Pe());le.addGetterSetter(wn,"nodes");le.addGetterSetter(wn,"node");le.addGetterSetter(wn,"boundBoxFunc");le.addGetterSetter(wn,"anchorDragBoundFunc");le.addGetterSetter(wn,"anchorStyleFunc");le.addGetterSetter(wn,"shouldOverdrawWholeArea",!1);le.addGetterSetter(wn,"useSingleNodeRotation",!0);le.backCompat(wn,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class aa extends Xe{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,tt.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}aa.prototype.className="Wedge";aa.prototype._centroid=!0;aa.prototype._attrsAffectingSize=["radius"];Qt(aa);le.addGetterSetter(aa,"radius",0,Pe());le.addGetterSetter(aa,"angle",0,Pe());le.addGetterSetter(aa,"clockwise",!1);le.backCompat(aa,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function J4(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var rD=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],aD=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function oD(e,t){let{data:n,width:s,height:i}=e,r,o,l,c,h,d,m,p,b,v,k,A,T,E,I,_,q,P,N,H,V=t+t+1,U=s-1,W=i-1,ce=t+1,ue=ce*(ce+1)/2,oe=new J4,ae=rD[t],te=aD[t],me=null,he=oe,we=null,be=null;for(let ye=1;ye<V;ye++)if(he=he.next=new J4,ye===ce)me=he;he.next=oe,l=o=0;for(let ye=0;ye<i;ye++){A=T=E=I=c=h=d=m=0,p=ce*(_=n[o]),b=ce*(q=n[o+1]),v=ce*(P=n[o+2]),k=ce*(N=n[o+3]),c+=ue*_,h+=ue*q,d+=ue*P,m+=ue*N,he=oe;for(let Te=0;Te<ce;Te++)he.r=_,he.g=q,he.b=P,he.a=N,he=he.next;for(let Te=1;Te<ce;Te++)r=o+((U<Te?U:Te)<<2),c+=(he.r=_=n[r])*(H=ce-Te),h+=(he.g=q=n[r+1])*H,d+=(he.b=P=n[r+2])*H,m+=(he.a=N=n[r+3])*H,A+=_,T+=q,E+=P,I+=N,he=he.next;we=oe,be=me;for(let Te=0;Te<s;Te++){if(n[o+3]=N=m*ae>>te,N!==0)N=255/N,n[o]=(c*ae>>te)*N,n[o+1]=(h*ae>>te)*N,n[o+2]=(d*ae>>te)*N;else n[o]=n[o+1]=n[o+2]=0;c-=p,h-=b,d-=v,m-=k,p-=we.r,b-=we.g,v-=we.b,k-=we.a,r=l+((r=Te+t+1)<U?r:U)<<2,A+=we.r=n[r],T+=we.g=n[r+1],E+=we.b=n[r+2],I+=we.a=n[r+3],c+=A,h+=T,d+=E,m+=I,we=we.next,p+=_=be.r,b+=q=be.g,v+=P=be.b,k+=N=be.a,A-=_,T-=q,E-=P,I-=N,be=be.next,o+=4}l+=s}for(let ye=0;ye<s;ye++){T=E=I=A=h=d=m=c=0,o=ye<<2,p=ce*(_=n[o]),b=ce*(q=n[o+1]),v=ce*(P=n[o+2]),k=ce*(N=n[o+3]),c+=ue*_,h+=ue*q,d+=ue*P,m+=ue*N,he=oe;for(let Oe=0;Oe<ce;Oe++)he.r=_,he.g=q,he.b=P,he.a=N,he=he.next;let Te=s;for(let Oe=1;Oe<=t;Oe++)if(o=Te+ye<<2,c+=(he.r=_=n[o])*(H=ce-Oe),h+=(he.g=q=n[o+1])*H,d+=(he.b=P=n[o+2])*H,m+=(he.a=N=n[o+3])*H,A+=_,T+=q,E+=P,I+=N,he=he.next,Oe<W)Te+=s;o=ye,we=oe,be=me;for(let Oe=0;Oe<i;Oe++){if(r=o<<2,n[r+3]=N=m*ae>>te,N>0)N=255/N,n[r]=(c*ae>>te)*N,n[r+1]=(h*ae>>te)*N,n[r+2]=(d*ae>>te)*N;else n[r]=n[r+1]=n[r+2]=0;c-=p,h-=b,d-=v,m-=k,p-=we.r,b-=we.g,v-=we.b,k-=we.a,r=ye+((r=Oe+ce)<W?r:W)*s<<2,c+=A+=we.r=n[r],h+=T+=we.g=n[r+1],d+=E+=we.b=n[r+2],m+=I+=we.a=n[r+3],we=we.next,p+=_=be.r,b+=q=be.g,v+=P=be.b,k+=N=be.a,A-=_,T-=q,E-=P,I-=N,be=be.next,o+=s}}}var Z4=function(t){let n=Math.round(this.blurRadius());if(n>0)oD(t,n)};le.addGetterSetter(Ue,"blurRadius",0,Pe(),le.afterSetFilter);var e8=function(e){let t=this.brightness()*255,n=e.data,s=n.length;for(let i=0;i<s;i+=4)n[i]+=t,n[i+1]+=t,n[i+2]+=t};le.addGetterSetter(Ue,"brightness",0,Pe(),le.afterSetFilter);var t8=function(e){let t=this.brightness(),n=e.data,s=n.length;for(let i=0;i<s;i+=4)n[i]=Math.min(255,n[i]*t),n[i+1]=Math.min(255,n[i+1]*t),n[i+2]=Math.min(255,n[i+2]*t)};var n8=function(e){let t=Math.pow((this.contrast()+100)/100,2),n=e.data,s=n.length,i=150,r=150,o=150;for(let l=0;l<s;l+=4)i=n[l],r=n[l+1],o=n[l+2],i/=255,i-=0.5,i*=t,i+=0.5,i*=255,r/=255,r-=0.5,r*=t,r+=0.5,r*=255,o/=255,o-=0.5,o*=t,o+=0.5,o*=255,i=i<0?0:i>255?255:i,r=r<0?0:r>255?255:r,o=o<0?0:o>255?255:o,n[l]=i,n[l+1]=r,n[l+2]=o};le.addGetterSetter(Ue,"contrast",0,Pe(),le.afterSetFilter);var s8=function(e){var t,n,s,i,r,o,l,c,h;let{data:d,width:m,height:p}=e,b=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:0.5)),v=Math.min(1,Math.max(0,(i=(s=this.embossWhiteLevel)===null||s===void 0?void 0:s.call(this))!==null&&i!==void 0?i:0.5)),A=(l={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(o=(r=this.embossDirection)===null||r===void 0?void 0:r.call(this))!==null&&o!==void 0?o:"top-left"])!==null&&l!==void 0?l:315,T=!!((h=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&h!==void 0?h:!1),E=b*10,I=v*255,_=A*Math.PI/180,q=Math.cos(_),P=Math.sin(_),N=0.12549019607843137*E,H=new Uint8ClampedArray(d),V=new Float32Array(m*p);for(let oe=0,ae=0;ae<d.length;ae+=4,oe++)V[oe]=0.2126*H[ae]+0.7152*H[ae+1]+0.0722*H[ae+2];let U=[-1,0,1,-2,0,2,-1,0,1],W=[-1,-2,-1,0,0,0,1,2,1],ce=[-m-1,-m,-m+1,-1,0,1,m-1,m,m+1],ue=(oe)=>oe<0?0:oe>255?255:oe;for(let oe=1;oe<p-1;oe++)for(let ae=1;ae<m-1;ae++){let te=oe*m+ae,me=0,he=0;me+=V[te+ce[0]]*U[0],he+=V[te+ce[0]]*W[0],me+=V[te+ce[1]]*U[1],he+=V[te+ce[1]]*W[1],me+=V[te+ce[2]]*U[2],he+=V[te+ce[2]]*W[2],me+=V[te+ce[3]]*U[3],he+=V[te+ce[3]]*W[3],me+=V[te+ce[5]]*U[5],he+=V[te+ce[5]]*W[5],me+=V[te+ce[6]]*U[6],he+=V[te+ce[6]]*W[6],me+=V[te+ce[7]]*U[7],he+=V[te+ce[7]]*W[7],me+=V[te+ce[8]]*U[8],he+=V[te+ce[8]]*W[8];let we=q*me+P*he,be=ue(I+we*N),ye=te*4;if(T){let Te=be-I;d[ye]=ue(H[ye]+Te),d[ye+1]=ue(H[ye+1]+Te),d[ye+2]=ue(H[ye+2]+Te),d[ye+3]=H[ye+3]}else d[ye]=d[ye+1]=d[ye+2]=be,d[ye+3]=H[ye+3]}for(let oe=0;oe<m;oe++){let ae=oe*4,te=((p-1)*m+oe)*4;d[ae]=H[ae],d[ae+1]=H[ae+1],d[ae+2]=H[ae+2],d[ae+3]=H[ae+3],d[te]=H[te],d[te+1]=H[te+1],d[te+2]=H[te+2],d[te+3]=H[te+3]}for(let oe=1;oe<p-1;oe++){let ae=oe*m*4,te=(oe*m+(m-1))*4;d[ae]=H[ae],d[ae+1]=H[ae+1],d[ae+2]=H[ae+2],d[ae+3]=H[ae+3],d[te]=H[te],d[te+1]=H[te+1],d[te+2]=H[te+2],d[te+3]=H[te+3]}return e};le.addGetterSetter(Ue,"embossStrength",0.5,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"embossWhiteLevel",0.5,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"embossDirection","top-left",void 0,le.afterSetFilter);le.addGetterSetter(Ue,"embossBlend",!1,void 0,le.afterSetFilter);function Ib(e,t,n,s,i){let r=n-t,o=i-s;if(r===0)return s+o/2;if(o===0)return s;let l=(e-t)/r;return l=o*l+s,l}var i8=function(e){let t=e.data,n=t.length,s=t[0],i=s,r,o=t[1],l=o,c,h=t[2],d=h,m,p=this.enhance();if(p===0)return;for(let I=0;I<n;I+=4){if(r=t[I+0],r<s)s=r;else if(r>i)i=r;if(c=t[I+1],c<o)o=c;else if(c>l)l=c;if(m=t[I+2],m<h)h=m;else if(m>d)d=m}if(i===s)i=255,s=0;if(l===o)l=255,o=0;if(d===h)d=255,h=0;let b,v,k,A,T,E;if(p>0)b=i+p*(255-i),v=s-p*(s-0),k=l+p*(255-l),A=o-p*(o-0),T=d+p*(255-d),E=h-p*(h-0);else{let I=(i+s)*0.5;b=i+p*(i-I),v=s+p*(s-I);let _=(l+o)*0.5;k=l+p*(l-_),A=o+p*(o-_);let q=(d+h)*0.5;T=d+p*(d-q),E=h+p*(h-q)}for(let I=0;I<n;I+=4)t[I+0]=Ib(t[I+0],s,i,v,b),t[I+1]=Ib(t[I+1],o,l,A,k),t[I+2]=Ib(t[I+2],h,d,E,T)};le.addGetterSetter(Ue,"enhance",0,Pe(),le.afterSetFilter);var r8=function(e){let t=e.data,n=t.length;for(let s=0;s<n;s+=4){let i=0.34*t[s]+0.5*t[s+1]+0.16*t[s+2];t[s]=i,t[s+1]=i,t[s+2]=i}};le.addGetterSetter(Ue,"hue",0,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"saturation",0,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"luminance",0,Pe(),le.afterSetFilter);var a8=function(e){let t=e.data,n=t.length,i=Math.pow(2,this.saturation()),r=Math.abs(this.hue()+360)%360,o=this.luminance()*127,l=1*i*Math.cos(r*Math.PI/180),c=1*i*Math.sin(r*Math.PI/180),h=0.299+0.701*l+0.167*c,d=0.587-0.587*l+0.33*c,m=0.114-0.114*l-0.497*c,p=0.299-0.299*l-0.328*c,b=0.587+0.413*l+0.035*c,v=0.114-0.114*l+0.293*c,k=0.299-0.3*l+1.25*c,A=0.587-0.586*l-1.05*c,T=0.114+0.886*l-0.2*c,E,I,_,q;for(let P=0;P<n;P+=4)E=t[P+0],I=t[P+1],_=t[P+2],q=t[P+3],t[P+0]=h*E+d*I+m*_+o,t[P+1]=p*E+b*I+v*_+o,t[P+2]=k*E+A*I+T*_+o,t[P+3]=q};var o8=function(e){let t=e.data,n=t.length,s=Math.pow(2,this.value()),i=Math.pow(2,this.saturation()),r=Math.abs(this.hue()+360)%360,o=s*i*Math.cos(r*Math.PI/180),l=s*i*Math.sin(r*Math.PI/180),c=0.299*s+0.701*o+0.167*l,h=0.587*s-0.587*o+0.33*l,d=0.114*s-0.114*o-0.497*l,m=0.299*s-0.299*o-0.328*l,p=0.587*s+0.413*o+0.035*l,b=0.114*s-0.114*o+0.293*l,v=0.299*s-0.3*o+1.25*l,k=0.587*s-0.586*o-1.05*l,A=0.114*s+0.886*o-0.2*l;for(let T=0;T<n;T+=4){let E=t[T+0],I=t[T+1],_=t[T+2],q=t[T+3];t[T+0]=c*E+h*I+d*_,t[T+1]=m*E+p*I+b*_,t[T+2]=v*E+k*I+A*_,t[T+3]=q}};le.addGetterSetter(Ue,"hue",0,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"saturation",0,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"value",0,Pe(),le.afterSetFilter);var l8=function(e){let t=e.data,n=t.length;for(let s=0;s<n;s+=4)t[s]=255-t[s],t[s+1]=255-t[s+1],t[s+2]=255-t[s+2]};var lD=function(e,t,n){let s=e.data,i=t.data,{width:r,height:o}=e,l=n.polarCenterX||r/2,c=n.polarCenterY||o/2,h=Math.sqrt(l*l+c*c),d=r-l,m=o-c,p=Math.sqrt(d*d+m*m);h=p>h?p:h;let b=o,v=r,k=360/v*Math.PI/180;for(let A=0;A<v;A+=1){let T=Math.sin(A*k),E=Math.cos(A*k);for(let I=0;I<b;I+=1){d=Math.floor(l+h*I/b*E),m=Math.floor(c+h*I/b*T);let _=(m*r+d)*4,q=s[_+0],P=s[_+1],N=s[_+2],H=s[_+3];_=(A+I*r)*4,i[_+0]=q,i[_+1]=P,i[_+2]=N,i[_+3]=H}}},cD=function(e,t,n){let s=e.data,i=t.data,{width:r,height:o}=e,l=n.polarCenterX||r/2,c=n.polarCenterY||o/2,h=Math.sqrt(l*l+c*c),d=r-l,m=o-c,p=Math.sqrt(d*d+m*m);h=p>h?p:h;let b=o,v=r,k=n.polarRotation||0,A,T;for(d=0;d<r;d+=1)for(m=0;m<o;m+=1){let E=d-l,I=m-c,_=Math.sqrt(E*E+I*I)*b/h,q=(Math.atan2(I,E)*180/Math.PI+360+k)%360;q=q*v/360,A=Math.floor(q),T=Math.floor(_);let P=(T*r+A)*4,N=s[P+0],H=s[P+1],V=s[P+2],U=s[P+3];P=(m*r+d)*4,i[P+0]=N,i[P+1]=H,i[P+2]=V,i[P+3]=U}},c8=function(e){let{width:t,height:n}=e,s,i,r,o,l,c,h,d,m,p,b=Math.round(this.kaleidoscopePower()),v=Math.round(this.kaleidoscopeAngle()),k=Math.floor(t*(v%360)/360);if(b<1)return;let A=ge.createCanvasElement();A.width=t,A.height=n;let T=A.getContext("2d").getImageData(0,0,t,n);ge.releaseCanvas(A),lD(e,T,{polarCenterX:t/2,polarCenterY:n/2});let E=t/Math.pow(2,b);while(E<=8)E=E*2,b-=1;E=Math.ceil(E);let I=E,_=0,q=I,P=1;if(k+E>t)_=I,q=0,P=-1;for(i=0;i<n;i+=1)for(s=_;s!==q;s+=P)r=Math.round(s+k)%t,m=(t*i+r)*4,l=T.data[m+0],c=T.data[m+1],h=T.data[m+2],d=T.data[m+3],p=(t*i+s)*4,T.data[p+0]=l,T.data[p+1]=c,T.data[p+2]=h,T.data[p+3]=d;for(i=0;i<n;i+=1){I=Math.floor(E);for(o=0;o<b;o+=1){for(s=0;s<I+1;s+=1)m=(t*i+s)*4,l=T.data[m+0],c=T.data[m+1],h=T.data[m+2],d=T.data[m+3],p=(t*i+I*2-s-1)*4,T.data[p+0]=l,T.data[p+1]=c,T.data[p+2]=h,T.data[p+3]=d;I*=2}}cD(T,e,{polarRotation:0})};le.addGetterSetter(Ue,"kaleidoscopePower",2,Pe(),le.afterSetFilter);le.addGetterSetter(Ue,"kaleidoscopeAngle",0,Pe(),le.afterSetFilter);function z0(e,t,n){let s=(n*e.width+t)*4,i=[];return i.push(e.data[s++],e.data[s++],e.data[s++],e.data[s++]),i}function Xh(e,t){return Math.sqrt(Math.pow(e[0]-t[0],2)+Math.pow(e[1]-t[1],2)+Math.pow(e[2]-t[2],2))}function fD(e){let t=[0,0,0];for(let n=0;n<e.length;n++)t[0]+=e[n][0],t[1]+=e[n][1],t[2]+=e[n][2];return t[0]/=e.length,t[1]/=e.length,t[2]/=e.length,t}function hD(e,t){let n=z0(e,0,0),s=z0(e,e.width-1,0),i=z0(e,0,e.height-1),r=z0(e,e.width-1,e.height-1),o=t||10;if(Xh(n,s)<o&&Xh(s,r)<o&&Xh(r,i)<o&&Xh(i,n)<o){let l=fD([s,n,r,i]),c=[];for(let h=0;h<e.width*e.height;h++){let d=Xh(l,[e.data[h*4],e.data[h*4+1],e.data[h*4+2]]);c[h]=d<o?0:255}return c}}function uD(e,t){for(let n=0;n<e.width*e.height;n++)e.data[4*n+3]=t[n]}function dD(e,t,n){let s=[1,1,1,1,0,1,1,1,1],i=Math.round(Math.sqrt(s.length)),r=Math.floor(i/2),o=[];for(let l=0;l<n;l++)for(let c=0;c<t;c++){let h=l*t+c,d=0;for(let m=0;m<i;m++)for(let p=0;p<i;p++){let b=l+m-r,v=c+p-r;if(b>=0&&b<n&&v>=0&&v<t){let k=b*t+v,A=s[m*i+p];d+=e[k]*A}}o[h]=d===2040?255:0}return o}function mD(e,t,n){let s=[1,1,1,1,1,1,1,1,1],i=Math.round(Math.sqrt(s.length)),r=Math.floor(i/2),o=[];for(let l=0;l<n;l++)for(let c=0;c<t;c++){let h=l*t+c,d=0;for(let m=0;m<i;m++)for(let p=0;p<i;p++){let b=l+m-r,v=c+p-r;if(b>=0&&b<n&&v>=0&&v<t){let k=b*t+v,A=s[m*i+p];d+=e[k]*A}}o[h]=d>=1020?255:0}return o}function pD(e,t,n){let s=[0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111,0.1111111111111111],i=Math.round(Math.sqrt(s.length)),r=Math.floor(i/2),o=[];for(let l=0;l<n;l++)for(let c=0;c<t;c++){let h=l*t+c,d=0;for(let m=0;m<i;m++)for(let p=0;p<i;p++){let b=l+m-r,v=c+p-r;if(b>=0&&b<n&&v>=0&&v<t){let k=b*t+v,A=s[m*i+p];d+=e[k]*A}}o[h]=d}return o}var f8=function(e){let t=this.threshold(),n=hD(e,t);if(n)n=dD(n,e.width,e.height),n=mD(n,e.width,e.height),n=pD(n,e.width,e.height),uD(e,n);return e};le.addGetterSetter(Ue,"threshold",0,Pe(),le.afterSetFilter);var h8=function(e){let t=this.noise()*255,n=e.data,s=n.length,i=t/2;for(let r=0;r<s;r+=4)n[r+0]+=i-2*i*Math.random(),n[r+1]+=i-2*i*Math.random(),n[r+2]+=i-2*i*Math.random()};le.addGetterSetter(Ue,"noise",0.2,Pe(),le.afterSetFilter);var u8=function(e){let t=Math.ceil(this.pixelSize()),{width:n,height:s}=e,i=Math.ceil(n/t),r=Math.ceil(s/t),o=e.data;if(t<=0){ge.error("pixelSize value can not be <= 0");return}for(let l=0;l<i;l+=1)for(let c=0;c<r;c+=1){let h=0,d=0,m=0,p=0,b=l*t,v=b+t,k=c*t,A=k+t,T=0;for(let E=b;E<v;E+=1){if(E>=n)continue;for(let I=k;I<A;I+=1){if(I>=s)continue;let _=(n*I+E)*4;h+=o[_+0],d+=o[_+1],m+=o[_+2],p+=o[_+3],T+=1}}h=h/T,d=d/T,m=m/T,p=p/T;for(let E=b;E<v;E+=1){if(E>=n)continue;for(let I=k;I<A;I+=1){if(I>=s)continue;let _=(n*I+E)*4;o[_+0]=h,o[_+1]=d,o[_+2]=m,o[_+3]=p}}}};le.addGetterSetter(Ue,"pixelSize",8,Pe(),le.afterSetFilter);var d8=function(e){let t=Math.round(this.levels()*254)+1,n=e.data,s=n.length,i=255/t;for(let r=0;r<s;r+=1)n[r]=Math.floor(n[r]/i)*i};le.addGetterSetter(Ue,"levels",0.5,Pe(),le.afterSetFilter);var m8=function(e){let t=e.data,n=t.length,s=this.red(),i=this.green(),r=this.blue();for(let o=0;o<n;o+=4){let l=(0.34*t[o]+0.5*t[o+1]+0.16*t[o+2])/255;t[o]=l*s,t[o+1]=l*i,t[o+2]=l*r,t[o+3]=t[o+3]}};le.addGetterSetter(Ue,"red",0,function(e){if(this._filterUpToDate=!1,e>255)return 255;else if(e<0)return 0;else return Math.round(e)});le.addGetterSetter(Ue,"green",0,function(e){if(this._filterUpToDate=!1,e>255)return 255;else if(e<0)return 0;else return Math.round(e)});le.addGetterSetter(Ue,"blue",0,E0,le.afterSetFilter);var p8=function(e){let t=e.data,n=t.length,s=this.red(),i=this.green(),r=this.blue(),o=this.alpha();for(let l=0;l<n;l+=4){let c=1-o;t[l]=s*o+t[l]*c,t[l+1]=i*o+t[l+1]*c,t[l+2]=r*o+t[l+2]*c}};le.addGetterSetter(Ue,"red",0,function(e){if(this._filterUpToDate=!1,e>255)return 255;else if(e<0)return 0;else return Math.round(e)});le.addGetterSetter(Ue,"green",0,function(e){if(this._filterUpToDate=!1,e>255)return 255;else if(e<0)return 0;else return Math.round(e)});le.addGetterSetter(Ue,"blue",0,E0,le.afterSetFilter);le.addGetterSetter(Ue,"alpha",1,function(e){if(this._filterUpToDate=!1,e>1)return 1;else if(e<0)return 0;else return e});var g8=function(e){let t=e.data,n=t.length;for(let s=0;s<n;s+=4){let i=t[s+0],r=t[s+1],o=t[s+2];t[s+0]=Math.min(255,i*0.393+r*0.769+o*0.189),t[s+1]=Math.min(255,i*0.349+r*0.686+o*0.168),t[s+2]=Math.min(255,i*0.272+r*0.534+o*0.131)}};var b8=function(e){let n=e.data;for(let s=0;s<n.length;s+=4){let i=n[s],r=n[s+1],o=n[s+2];if(0.2126*i+0.7152*r+0.0722*o>=128)n[s]=255-i,n[s+1]=255-r,n[s+2]=255-o}return e};var w8=function(e){let t=this.threshold()*255,n=e.data,s=n.length;for(let i=0;i<s;i+=1)n[i]=n[i]<t?0:255};le.addGetterSetter(Ue,"threshold",0.5,Pe(),le.afterSetFilter);var gD=of.Util._assign(of,{Arc:ra,Arrow:po,Circle:al,Ellipse:Fa,Image:Zi,Label:Gh,Tag:go,Line:Mr,Path:ts,Rect:ol,RegularPolygon:La,Ring:bo,Sprite:Fr,Star:Oa,Text:Xn,TextPath:Fs,Transformer:wn,Wedge:aa,Filters:{Blur:Z4,Brightness:t8,Brighten:e8,Contrast:n8,Emboss:s8,Enhance:i8,Grayscale:r8,HSL:a8,HSV:o8,Invert:l8,Kaleidoscope:c8,Mask:f8,Noise:h8,Pixelate:u8,Posterize:d8,RGB:m8,RGBA:p8,Sepia:g8,Solarize:b8,Threshold:w8}});Z();var ff=of;var R8=se(y8());var Rb=1;var G0=32,Db=2;Z();var v8={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0},S8=!1,k8=!1,hf=".react-konva-event",vD=!1;var SD=`ReactKonva: You have a Konva node with draggable = true and position defined but no onDragMove or onDragEnd events are handled.
68
- Position of a node will be changed during drag&drop, so you should update state of the react app as well.
69
- Consider to add onDragMove or onDragEnd events.
70
- For more info see: https://github.com/konvajs/react-konva/issues/256
71
- `,kD=`ReactKonva: You are using "zIndex" attribute for a Konva node.
72
- react-konva may get confused with ordering. Just define correct order of elements in your render function of a component.
73
- For more info see: https://github.com/konvajs/react-konva/issues/194
74
- `,xD={},x8=()=>{};function A8(e){x8=e}var qb=!1;function AD(e){return function(...t){let n=e.apply(this,t);if(!qb){qb=!0;try{x8()}finally{qb=!1}}return n}}function uf(e,t,n=xD){if(!S8&&"zIndex"in t)console.warn(kD),S8=!0;if(!k8&&t.draggable){var s=t.x!==void 0||t.y!==void 0,i=t.onDragEnd||t.onDragMove;if(s&&!i)console.warn(SD),k8=!0}for(var r in n){if(v8[r])continue;var o=r.slice(0,2)==="on",l=n[r]!==t[r];if(o&&l){var c=r.substr(2).toLowerCase();if(c.substr(0,7)==="content")c="content"+c.substr(7,1).toUpperCase()+c.substr(8);e.off(c+hf)}var h=!t.hasOwnProperty(r);if(h)e.setAttr(r,void 0)}var d=vD||t._useStrictMode,m={},p=!1;let b={};for(var r in t){if(v8[r])continue;var o=r.slice(0,2)==="on",v=n[r]!==t[r];if(o&&v){var c=r.substr(2).toLowerCase();if(c.substr(0,7)==="content")c="content"+c.substr(7,1).toUpperCase()+c.substr(8);if(t[r])b[c]=t[r]}if(!o&&(t[r]!==n[r]||d&&t[r]!==e.getAttr(r)))p=!0,m[r]=t[r]}if(p)e.setAttrs(m),vo(e);for(var c in b)e.off(c+hf),e.on(c+hf,AD(b[c]))}function vo(e){if(!tt.autoDrawEnabled){var t=e.getLayer()||e.getStage();t&&t.batchDraw()}}Hf();var T8={},TD={};ff.Node.prototype._applyProps=uf;var E8=G0;function ED(e,t){if(typeof t==="string"){console.error(`Do not use plain text as child of Konva.Node. You are using text: ${t}`);return}e.add(t),vo(e)}function CD(e,t,n){let s=ff[e];if(!s)console.error(`Konva has no node with the type ${e}. Group will be used instead. If you use minimal version of react-konva, just import required nodes into Konva: "import "konva/lib/shapes/${e}" If you want to render DOM elements as part of canvas tree take a look into this demo: https://konvajs.github.io/docs/react/DOM_Portal.html`),s=ff.Group;let i={},r={};for(var o in t){if(o==="ref")continue;var l=o.slice(0,2)==="on";if(l)r[o]=t[o];else i[o]=t[o]}let c=new s(i);return uf(c,r),c}function jD(e,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${e}"`)}function _D(e,t,n){return!1}function ID(e){return e}function RD(){return null}function DD(){return null}function qD(e,t,n,s){return TD}function MD(){}function FD(e){}function LD(e,t){return!1}function OD(){return T8}function PD(){return T8}var ND=setTimeout,BD=clearTimeout,HD=!0,UD=typeof queueMicrotask==="function"?queueMicrotask:(e)=>Promise.resolve(null).then(e),zD=-1;function GD(e,t){return!1}var VD=!1,$D=!1,XD=!0,WD=!1,KD=!1;function YD(e,t){if(t.parent===e)t.moveToTop();else e.add(t);vo(e)}function QD(e,t){if(t.parent===e)t.moveToTop();else e.add(t);vo(e)}function C8(e,t,n){t._remove(),e.add(t),t.setZIndex(n.getZIndex()),vo(e)}function JD(e,t,n){C8(e,t,n)}function ZD(e,t){t.destroy(),t.off(hf),vo(e)}function eq(e,t){t.destroy(),t.off(hf),vo(e)}function tq(e,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function nq(e,t,n){}function sq(e,t,n,s){uf(e,s,n)}function iq(e){e.hide(),vo(e)}function rq(e){}function aq(e,t){if(t.visible==null||t.visible)e.show()}function oq(e,t){}function lq(e){}function cq(){}function fq(){return null}function hq(){}function uq(){}function dq(){return G0}function mq(){}function pq(){return null}function gq(e){E8=e}function bq(){return E8}function wq(){return Db}function yq(){return!1}function vq(){}function Sq(){return null}function kq(){return-1.1}function xq(){}function Aq(){return!1}function Tq(){return!0}function Eq(){}function Cq(){}function jq(){return null}var _q=null,Iq=Rt(null);function Rq(){}Z();function j8(e,t,n){if(!e)return;if(n(e)===!0)return e;let s=t?e.return:e.child;for(;s;){let i=j8(s,t,n);if(i)return i;s=t?null:s.sibling}}function _8(e){try{return Object.defineProperties(e,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch(t){return e}}var Fb=_8(Rt(null));class V0 extends xi{render(){return ne(Fb.Provider,{value:this._reactInternals},this.props.children)}}function Dq(){let e=Zt(Fb);if(e===null)throw Error("its-fine: useFiber must be called within a <FiberProvider />!");let t=Ff();return G(()=>{for(let n of[e,e==null?void 0:e.alternate]){if(!n)continue;let s=j8(n,!1,(i)=>{let r=i.memoizedState;for(;r;){if(r.memoizedState===t)return!0;r=r.next}});if(s)return s}},[e,t])}var qq=Symbol.for("react.context"),Mq=(e)=>e!==null&&typeof e=="object"&&("$$typeof"in e)&&e.$$typeof===qq;function Fq(){let e=Dq(),[t]=w(()=>new Map);t.clear();let n=e;for(;n;){let s=n.type;Mq(s)&&s!==Fb&&!t.has(s)&&t.set(s,Tl(_8(s))),n=n.return}return t}function I8(){let e=Fq();return G(()=>Array.from(e.keys()).reduce((t,n)=>(s)=>ne(t,null,ne(n.Provider,{...s,value:e.get(n)})),(t)=>ne(V0,{...t})),[e])}if(Ci.indexOf("19")===-1)throw Error("react-konva version 19 is only compatible with React 19. Make sure to have the last version of react-konva and react or downgrade react-konva to version 18.");function Lq(e){let t=M({});return nt(()=>{t.current=e}),nt(()=>()=>{t.current={}},[]),t.current}var Oq=()=>{let e=M(0);return G(()=>{e.current++},[]),e.current>1},Pq=(e)=>{let t=M(null),n=M(null),s=M(null),i=Lq(e),r=I8(),o=M(null),l=(d)=>{let{forwardedRef:m}=e;if(!m)return;if(typeof m==="function")m(d);else m.current=d},c=Oq(),h=()=>{l(null),$l.flushSyncFromReconciler(()=>{$l.updateContainer(null,s.current,null)}),n.current?.destroy(),n.current=null};return nt(()=>{if(o.current)clearTimeout(o.current),o.current=null;if(n.current)l(n.current);else n.current=new ff.Stage({width:e.width,height:e.height,container:t.current}),l(n.current),s.current=$l.createContainer(n.current,Rb,null,!1,null,"",console.error,console.error,console.error,null),$l.updateContainer(ne(r,{},e.children),s.current,null,()=>{});return()=>{if(c)o.current=setTimeout(h,0);else h()}},[]),nt(()=>{l(n.current),uf(n.current,e,i),$l.updateContainer(ne(r,{},e.children),s.current,null),$l.flushSyncWork()}),ne("div",{ref:t,id:e.id,accessKey:e.accessKey,className:e.className,role:e.role,style:e.style,tabIndex:e.tabIndex,title:e.title})},D8="Layer";var Lb="Group";var Ob="Rect";var Pb="Line";var q8="Image";var Nb="Arrow";var $l=R8.default(Mb);A8(()=>$l.flushSyncWork());var M8=J((e,t)=>ne(V0,{},ne(Pq,{...e,forwardedRef:t})));var O8=se(L8(),1);var Nq=({width:e,height:t,mediaDimensions:n,imageUrl:s,canvasElement:i,annotations:r,scale:o,offset:l,onPan:c,onClick:h,className:d,isDrawing:m=!1,currentTool:p="arrow",currentColor:b="#ef4444",onAddAnnotation:v})=>{let[k]=O8.default(s||"","anonymous"),A=M(null),T=M(!1),E=M({x:0,y:0}),I=M(null),_=M(null),q=M(null),P=M(null);S(()=>{if(i&&A.current)A.current.getLayer()?.batchDraw()},[i]);let N=(ce,ue=!1,oe)=>{let ae=ce.getAbsoluteTransform().copy();ae.invert();let te=oe||ce.getStage()?.getPointerPosition();if(te){let me=ae.point(te);if(ue)return{x:Math.max(0,Math.min(n.width,me.x)),y:Math.max(0,Math.min(n.height,me.y))};return me}return null},H=M({isDrawing:m,currentTool:p,currentColor:b,onPan:c,offset:l,scale:o,mediaDimensions:n,onAddAnnotation:v});H.current={isDrawing:m,currentTool:p,currentColor:b,onPan:c,offset:l,scale:o,mediaDimensions:n,onAddAnnotation:v};let V=()=>{if(!T.current)return;T.current=!1;let{isDrawing:ce,onAddAnnotation:ue,mediaDimensions:oe,currentTool:ae,currentColor:te}=H.current;if(ce&&ue){let{width:me,height:he}=oe,we=(be,ye)=>be/ye;if(ae==="freehand"&&_.current){_.current.visible(!1);let be=_.current.points(),ye=[];for(let Te=0;Te<be.length;Te+=2)ye.push([we(be[Te],me),we(be[Te+1],he)]);if(ye.length>1)ue({type:"freehand",color:te,points:ye})}else if(ae==="line"&&_.current){_.current.visible(!1);let be=_.current.points(),ye={type:"line",color:te,points:[[we(be[0],me),we(be[1],he)],[we(be[2],me),we(be[3],he)]]};ue(ye)}else if(ae==="box"&&q.current){q.current.visible(!1);let be=q.current.x(),ye=q.current.y(),Te=q.current.width(),Oe=q.current.height(),st=[we(be,me),we(ye,he)],We=[we(be+Te,me),we(ye+Oe,he)];ue({type:"box",color:te,points:[st,We]})}else if(ae==="arrow"&&P.current){P.current.visible(!1);let be=P.current.points(),ye={type:"arrow",color:te,points:[[we(be[0],me),we(be[1],he)],[we(be[2],me),we(be[3],he)]]};ue(ye)}}};S(()=>{let ce=(oe)=>{if(!T.current)return;let ae=A.current?.getStage();if(!ae)return;let me=ae.container().getBoundingClientRect(),he,we;if("clientX"in oe)he=oe.clientX,we=oe.clientY;else he=oe.touches[0].clientX,we=oe.touches[0].clientY;let be={x:he-me.left,y:we-me.top};if("touches"in oe&&oe.touches.length>1){E.current=be;return}let{isDrawing:ye,currentTool:Te,onPan:Oe,offset:st}=H.current;if(ye){if(Te==="select")return;let We=N(A.current,!0,be);if(!We||!I.current)return;let wt=I.current,xt=A.current?.getLayer();if(Te==="freehand"&&_.current){let ft=_.current.points().concat([We.x,We.y]);_.current.points(ft)}else if(Te==="line"&&_.current)_.current.points([wt.x,wt.y,We.x,We.y]);else if(Te==="box"&&q.current)q.current.width(We.x-wt.x),q.current.height(We.y-wt.y);else if(Te==="arrow"&&P.current)P.current.points([wt.x,wt.y,We.x,We.y]);xt?.batchDraw()}else{if(!Oe)return;let We=be.x-E.current.x,wt=be.y-E.current.y;E.current=be,Oe({x:st.x+We,y:st.y+wt})}},ue=(oe)=>{if("touches"in oe&&oe.touches.length>0)return;V()};return window.addEventListener("mousemove",ce),window.addEventListener("mouseup",ue),window.addEventListener("touchmove",ce),window.addEventListener("touchend",ue),()=>{window.removeEventListener("mousemove",ce),window.removeEventListener("mouseup",ue),window.removeEventListener("touchmove",ce),window.removeEventListener("touchend",ue)}},[]);let U=(ce)=>{if(m){if(p==="select")return;if(!ce.target.getStage())return;let oe=N(A.current);if(!oe)return;if(oe.x<0||oe.x>n.width||oe.y<0||oe.y>n.height)return;T.current=!0,I.current=oe;let ae=A.current?.getLayer();if(!ae)return;if(p==="freehand"&&_.current)_.current.points([oe.x,oe.y]),_.current.stroke(b),_.current.visible(!0);else if(p==="line"&&_.current)_.current.points([oe.x,oe.y,oe.x,oe.y]),_.current.stroke(b),_.current.visible(!0);else if(p==="box"&&q.current)q.current.position(oe),q.current.width(0),q.current.height(0),q.current.stroke(b),q.current.visible(!0);else if(p==="arrow"&&P.current)P.current.points([oe.x,oe.y,oe.x,oe.y]),P.current.stroke(b),P.current.fill(b),P.current.visible(!0);ae.batchDraw()}else{if(!c)return;T.current=!0;let ue=ce.target.getStage();if(ue){let oe=ue.getPointerPosition();if(oe)E.current=oe}}},W=(ce,ue)=>{let{width:oe,height:ae}=n;switch(ce.type){case"box":{let[te,me]=ce.points,he=Math.min(te[0],me[0])*oe,we=Math.min(te[1],me[1])*ae,be=Math.abs(me[0]-te[0])*oe,ye=Math.abs(me[1]-te[1])*ae;return a(Ob,{x:he,y:we,width:be,height:ye,stroke:ce.color,strokeWidth:2.6/o,listening:!1},ue)}case"arrow":{let te=ce.points.flat().map((me,he)=>he%2===0?me*oe:me*ae);return a(Nb,{points:te,stroke:ce.color,strokeWidth:2.6/o,fill:ce.color,pointerLength:10/o,pointerWidth:10/o,listening:!1},ue)}case"line":case"freehand":{let te=ce.points.flat().map((me,he)=>he%2===0?me*oe:me*ae);return a(Pb,{points:te,stroke:ce.color,strokeWidth:2.6/o,tension:0.5,lineCap:"round",lineJoin:"round",listening:!1},ue)}default:return null}};return a("div",{className:d,style:{width:e,height:t,overflow:"hidden",pointerEvents:!m&&!c?"none":"auto",cursor:m&&p!=="select"?"crosshair":c?T.current?"grabbing":"grab":"default"},children:a(M8,{width:e,height:t,scaleX:o,scaleY:o,x:l.x,y:l.y,onMouseDown:U,onClick:!m?h:void 0,onTap:!m?h:void 0,onTouchStart:U,children:a(D8,{children:g(Lb,{ref:A,width:n.width,height:n.height,children:[(i||k)&&a(q8,{image:i||k,width:n.width,height:n.height}),r.map(W),g(Lb,{listening:!1,children:[a(Pb,{ref:_,strokeWidth:2.6/o,lineCap:"round",lineJoin:"round",visible:!1}),a(Ob,{ref:q,strokeWidth:2.6/o,visible:!1}),a(Nb,{ref:P,points:[],strokeWidth:2.6/o,pointerLength:10/o,pointerWidth:10/o,visible:!1})]})]})})})})},Or=Nq;function Na(e,t,n,s){if(e<=0||t<=0||n<=0||s<=0)return 1;return Math.min(e/n,t/s)}function Pr(e,t,n,s,i){return{x:(e-n*i)/2,y:(t-s*i)/2}}function Kh(e,t,n=0.02){return e>t*(1+n)}function Bq(e,t=0.01,n=50){return Math.min(n,Math.max(t,e))}function oa(e,t,n,s,i,r=0.01,o=50){let l=Bq(e*n,r,o),c=l/e;return{zoom:l,pan:{x:s-(s-t.x)*c,y:i-(i-t.y)*c}}}function P8(e,t){let n=t===1?e*16:t===2?e*100:e,s=Math.exp(-n*0.01);return Math.min(2,Math.max(0.5,s))}Z();function ll({containerRef:e,zoom:t,pan:n,baseScale:s,onZoomChange:i,onPanChange:r}){let o=M({zoom:t,pan:n,baseScale:s,onZoomChange:i,onPanChange:r});o.current={zoom:t,pan:n,baseScale:s,onZoomChange:i,onPanChange:r},S(()=>{let l=e.current;if(!l)return;let c=new Map,h=null,d=(A)=>{let T=o.current;if(A.ctrlKey){A.preventDefault();let E=l.getBoundingClientRect(),I=A.clientX-E.left,_=A.clientY-E.top;T.onZoomChange(oa(T.zoom,T.pan,P8(A.deltaY,A.deltaMode),I,_));return}if(Kh(T.zoom,T.baseScale))A.preventDefault(),T.onPanChange({x:T.pan.x-A.deltaX,y:T.pan.y-A.deltaY})},m=(A,T)=>Math.hypot(T.x-A.x,T.y-A.y),p=(A,T,E)=>({x:(A.x+T.x)/2-E.left,y:(A.y+T.y)/2-E.top}),b=(A)=>{for(let T of Array.from(A.touches))c.set(T.identifier,{x:T.clientX,y:T.clientY});if(c.size===2){A.preventDefault();let T=l.getBoundingClientRect(),[E,I]=Array.from(c.values());h={lastDist:m(E,I),lastMid:p(E,I,T)}}},v=(A)=>{for(let U of Array.from(A.touches))c.set(U.identifier,{x:U.clientX,y:U.clientY});if(!h||c.size<2)return;A.preventDefault();let T=l.getBoundingClientRect(),[E,I]=Array.from(c.values()),_=p(E,I,T),q=m(E,I),P=o.current,N=h.lastDist>0?q/h.lastDist:1,H=oa(P.zoom,P.pan,N,_.x,_.y),V=H.pan;if(Kh(H.zoom,P.baseScale))V={x:V.x+(_.x-h.lastMid.x),y:V.y+(_.y-h.lastMid.y)};P.onZoomChange({zoom:H.zoom,pan:V}),h.lastDist=q,h.lastMid=_},k=(A)=>{for(let T of Array.from(A.changedTouches))c.delete(T.identifier);if(c.size<2)h=null};return l.addEventListener("wheel",d,{passive:!1}),l.addEventListener("touchstart",b,{passive:!1}),l.addEventListener("touchmove",v,{passive:!1}),l.addEventListener("touchend",k,{passive:!1}),l.addEventListener("touchcancel",k,{passive:!1}),()=>{l.removeEventListener("wheel",d),l.removeEventListener("touchstart",b),l.removeEventListener("touchmove",v),l.removeEventListener("touchend",k),l.removeEventListener("touchcancel",k)}},[e])}var Hq=J(({file:e,onPlay:t,onPause:n,onTimeUpdate:s,annotations:i,startTime:r,shareId:o,children:l,allowDownload:c,autoPlay:h},d)=>{let m=M(null),p=M(null),[b,v]=w(void 0),[k,A]=w(!0),T=Boolean(e.media?.isHls&&e.media.hls?.url),I=(T?e.media?.hls?.resolutions??[]:e.media?.videoTranscodes??[]).map((je)=>({...je,resolution:ii(je)})),_=(T||I.length>0)&&!!e.media?.metadata,q=()=>{if(I.length===0)return null;if(typeof window>"u")return I[0];let je=typeof window.matchMedia==="function"&&window.matchMedia("(dynamic-range: high)").matches,ot=I.some((Hn)=>Hn.hdr),At=I.some((Hn)=>!Hn.hdr),Yt=I;if(je&&ot)Yt=I.filter((Hn)=>Hn.hdr);else if(!je&&At)Yt=I.filter((Hn)=>!Hn.hdr);let _n=window.innerWidth*(window.devicePixelRatio||1),gn=[...Yt].sort((Hn,Vn)=>{let Qn=Hn.width??0,Bs=Vn.width??0;return Qn-Bs});return gn.find((Hn)=>(Hn.width??0)>=_n)||gn[gn.length-1]},P=T?null:q(),[N,H]=w({isPlaying:!1,progress:0,currentTime:0,duration:e.media?.metadata?.duration||0,volume:1,isMuted:!1,isLooping:!1,playbackRate:1,isFullScreen:!1,showFrames:!1,currentResolution:T?"Auto":P?.resolution??"",currentSrc:T?e.media.hls.url:P?.url??"",isCurrentHdr:P?.hdr??!1}),[V,U]=w(!1),W=M(null),ce=M(null),ue=M(null),oe=M(null);bn(d,()=>({play:()=>{if(oe.current)oe.current(),oe.current=null;p.current?.play().catch(()=>{})},pause:()=>{p.current?.pause()},seekTo:(je)=>{if(oe.current)oe.current(),oe.current=null;if(U(!0),p.current)p.current.currentTime=je},getCurrentTime:()=>(p.current?p.current.currentTime:0)??0,getDuration:()=>(p.current?p.current.duration:0)??0}));let ae=M(!1),[te,me]=w(1),[he,we]=w({x:0,y:0}),[be,ye]=w(!1),[Te,Oe]=w({width:0,height:0});S(()=>{let je=T?null:q();if(H((ot)=>({...ot,isPlaying:!1,progress:0,currentTime:0,duration:e.media?.metadata?.duration||0,currentResolution:T?"Auto":je?.resolution??"",currentSrc:T?e.media?.hls?.url??"":je?.url??"",isCurrentHdr:je?.hdr??!1})),v(void 0),ye(!1),Fn.current)clearTimeout(Fn.current),Fn.current=null;nn(!1),Vt(!0),Je(0),ns.current=null,U(!1)},[e.id,Boolean(T?e.media?.hls?.url:P?.url)]);let st=e.media?.metadata?.originalWidth||1920,We=e.media?.metadata?.originalHeight||1080,wt=Na(Te.width,Te.height,st,We),xt=(je)=>{ye(!0);let ot=oa(te,he,je/te,Te.width/2,Te.height/2);me(ot.zoom),we(ot.pan)},ft=()=>{if(ye(!1),Te.width>0&&Te.height>0){let je=Na(Te.width,Te.height,st,We);me(je),we(Pr(Te.width,Te.height,st,We,je))}},{isDrawing:It,currentTool:Wt,currentColor:hn,addAnnotation:zt,annotations:tn}=un(),Kn=[...i||[],...tn];S(()=>{if(!W.current)return;let je=new ResizeObserver((ot)=>{let At=ot[0];if(At)Oe({width:At.contentRect.width,height:At.contentRect.height})});return je.observe(W.current),()=>je.disconnect()},[]),S(()=>{if(Te.width<=0||Te.height<=0)return;if(be)return;let je=Na(Te.width,Te.height,st,We);me(je),we(Pr(Te.width,Te.height,st,We,je))},[Te.width,Te.height,st,We,be]),ll({containerRef:W,zoom:te,pan:he,baseScale:wt,onZoomChange:(je)=>{ye(!0),me(je.zoom),we(je.pan)},onPanChange:we}),S(()=>()=>{p.current=null},[]);let[Le,Je]=w(0),[bt,ut]=w(!0),[Ft,nn]=w(!1),[mn,Vt]=w(!0),Fn=M(null),ns=M(null),St=e.media?.metadata,it=St?.frameRate||30,sn=St?.totalFrames||0,Lt=St?.duration||0,Ln=e.proxyType==="audio",is=Kd({dbTotalFrames:sn,containerDuration:Lt,frameRate:it}),{currentFrame:xs,seekToFrame:Ls}=v0(p,it,is,Ln),ha=Q((je)=>{if(oe.current)oe.current(),oe.current=null;return U(!0),Ls(je)},[Ls]),Pi=xs/it,nr=is/it,To=nr>0?Pi/nr*100:0,pl={...N,currentTime:Pi,duration:nr,progress:To,activeAutoResolution:b,isHlsManualSupported:k,isLoading:mn};S(()=>{if(s)s(xs/it)},[xs,it,s]);let sr=T?e.media?.hls?.url??"":q()?.url??"";S(()=>{let je=p.current;if(!je)return;if(!sr)return;if(m.current)m.current.destroy(),m.current=null;if(Fn.current)clearTimeout(Fn.current),Fn.current=null;nn(!1),Vt(!0),v(void 0);let ot=()=>{let Hs=je.play();if(Hs!==void 0)Hs.catch(()=>{je.muted=!0,H((Bi)=>({...Bi,isMuted:!0})),je.play()?.catch(()=>{})})},At=null;if(T){if(es.isSupported())A(!0),At=new es({autoStartLoad:!0,startLevel:-1,capLevelToPlayerSize:!1,enableWorker:!0}),m.current=At,At.attachMedia(je),At.loadSource(sr),At.on(es.Events.MANIFEST_PARSED,()=>{if(h)if(je.readyState>=2)ot();else je.addEventListener("canplay",ot,{once:!0})}),At.on(es.Events.LEVEL_SWITCHED,(Hs,Bi)=>{let ys=At?.levels[Bi.level];if(ys){let ac=I.find((Io)=>Io.width===ys.width&&Io.height===ys.height);if(ac?.resolution)v(ac.resolution);else{let Io=ys.width&&ys.height?Math.min(ys.width,ys.height):ys.height||ys.width;v(Io?`${Io}p`:void 0)}}}),At.on(es.Events.ERROR,(Hs,Bi)=>{if(Bi.fatal)switch(Bi.type){case es.ErrorTypes.NETWORK_ERROR:At?.startLoad();break;case es.ErrorTypes.MEDIA_ERROR:At?.recoverMediaError();break;default:At?.destroy();break}});else if(je.canPlayType("application/vnd.apple.mpegurl")){if(A(!1),je.src=sr,h)if(je.readyState>=2)ot();else je.addEventListener("canplay",ot,{once:!0})}}else if(je.src=sr,h)if(je.readyState>=2)ot();else je.addEventListener("canplay",ot,{once:!0});let Yt=()=>{if(Fn.current)clearTimeout(Fn.current),Fn.current=null},_n=()=>{if(Yt(),Vt(!1),nn(!0),oe.current)oe.current(),oe.current=null;H((Hs)=>({...Hs,isPlaying:!0})),U(!0),t?.()},gn=()=>{H((Hs)=>({...Hs,isPlaying:!1})),n?.()},ws=()=>{Yt(),Vt(!1),H((Hs)=>({...Hs,isPlaying:!1}))},Hn=()=>{Yt(),Vt(!1),nn(!0)},Vn=()=>{Yt(),Vt(!1),nn(!0)},Qn=()=>{Yt(),Vt(!1)},Bs=()=>{Yt(),Fn.current=setTimeout(()=>{Vt(!0)},200)},rs=()=>{Yt(),Vt(!0),nn(!1)},Ni=()=>{let Hs=je.duration||e.media?.metadata?.duration||0;if(Hs>0&&je.buffered.length>0){let Bi=0;for(let ys=0;ys<je.buffered.length;ys++)if(je.buffered.start(ys)<=je.currentTime&&je.currentTime<=je.buffered.end(ys)){Bi=je.buffered.end(ys);break}if(Bi===0)Bi=je.buffered.end(je.buffered.length-1);Je(Bi/Hs*100)}},Vr=()=>{H((Hs)=>({...Hs,volume:je.volume,isMuted:je.muted}))},xf=()=>{H((Hs)=>({...Hs,playbackRate:je.playbackRate}))},Af=()=>{Yt(),Vt(!1),console.error("Video Error:",je.error)};if(je.readyState>=2)Vt(!1),nn(!0);return je.addEventListener("play",_n),je.addEventListener("pause",gn),je.addEventListener("ended",ws),je.addEventListener("loadeddata",Hn),je.addEventListener("canplay",Vn),je.addEventListener("playing",Qn),je.addEventListener("waiting",Bs),je.addEventListener("loadstart",rs),je.addEventListener("timeupdate",Ni),je.addEventListener("progress",Ni),je.addEventListener("volumechange",Vr),je.addEventListener("ratechange",xf),je.addEventListener("error",Af),je.volume=N.volume,()=>{if(Yt(),je.removeEventListener("play",_n),je.removeEventListener("pause",gn),je.removeEventListener("ended",ws),je.removeEventListener("loadeddata",Hn),je.removeEventListener("canplay",Vn),je.removeEventListener("playing",Qn),je.removeEventListener("waiting",Bs),je.removeEventListener("loadstart",rs),je.removeEventListener("timeupdate",Ni),je.removeEventListener("progress",Ni),je.removeEventListener("volumechange",Vr),je.removeEventListener("ratechange",xf),je.removeEventListener("error",Af),m.current)m.current.destroy(),m.current=null}},[e.id,sr,T,h]),S(()=>{if(!Ft)return;if(r!==void 0&&r!==null&&r>0){if(r!==ns.current){ns.current=r;let je=Math.floor(r*it+0.45);U(!0),Ls(je)}}},[r,it,Ls,Ft]);let $a=Q(()=>{if(ue.current)clearTimeout(ue.current);if(N.isFullScreen&&!ae.current)ue.current=setTimeout(()=>{ut(!1)},1200)},[N.isFullScreen]),ua=Q(()=>{ut(!0),$a()},[$a]),Xa=Q(()=>{if(ae.current=!0,ue.current)clearTimeout(ue.current);ut(!0)},[]),da=Q(()=>{ae.current=!1,$a()},[$a]),Co=Q(()=>{if(N.isFullScreen){if(ue.current)clearTimeout(ue.current);ut(!1)}},[N.isFullScreen]);S(()=>()=>{if(ue.current)clearTimeout(ue.current)},[]),S(()=>{if(!N.isFullScreen){if(ut(!0),ue.current)clearTimeout(ue.current)}else ua()},[N.isPlaying,N.isFullScreen,ua]);let ma=Q(()=>{if(mn)return;if(un.getState().isDrawing)return;if(oe.current)oe.current(),oe.current=null;let je=p.current;if(!je)return;if(je.paused||je.ended){let ot=je.play();if(ot!==void 0)ot.catch((At)=>{if(At.name==="AbortError")return;console.error("Play failed:",At)})}else je.pause()},[mn]);S(()=>{let je=(ot)=>{let At=document.activeElement;if(At&&(At.tagName==="INPUT"||At.tagName==="TEXTAREA"||At instanceof HTMLElement&&At.isContentEditable))return;let Yt=ot.key===" ",_n=At&&(At.tagName==="BUTTON"||At.tagName==="A"||At.tagName==="SELECT"||At.tagName==="OPTION"||At.getAttribute("role")==="button"||At.getAttribute("role")==="link"||At.getAttribute("role")==="checkbox"||At.getAttribute("role")==="radio"||At.getAttribute("role")==="menuitem");if(Yt&&_n)return;if(ot.key===" "||ot.key.toLowerCase()==="k")ot.preventDefault(),ma()};return window.addEventListener("keydown",je),()=>{window.removeEventListener("keydown",je)}},[ma]);let jo=()=>{let je=p.current;if(!je)return;let ot=!N.isLooping;je.loop=ot,H((At)=>({...At,isLooping:ot}))},ir=(je)=>{H((At)=>({...At,volume:je,isMuted:je===0}));let ot=p.current;if(!ot)return;if(ot.volume=je,je>0&&ot.muted)ot.muted=!1;else if(je===0&&!ot.muted)ot.muted=!0},_o=()=>{let je=p.current;if(!je)return;if(je.muted){if(je.muted=!1,je.volume===0)je.volume=0.5}else je.muted=!0},Ze=(je)=>{let ot=p.current;if(!ot)return;ot.playbackRate=je,H((At)=>({...At,playbackRate:je}))},pn=(je)=>{let ot=p.current;if(!ot)return;if(oe.current)oe.current(),oe.current=null;if(T&&m.current){let gn=m.current,ws=ot.paused,Hn=xs;if(je.resolution==="Auto"){if(N.currentResolution==="Auto"&&gn.currentLevel===-1)return;gn.currentLevel=-1,H((Vn)=>({...Vn,currentResolution:"Auto"}))}else{let Vn=gn.levels.findIndex((Qn)=>Qn.height===je.height||Math.max(Qn.width,Qn.height)===Math.max(je.width,je.height));if(Vn!==-1){if(Vn===gn.currentLevel&&N.currentResolution===je.resolution)return;gn.currentLevel=Vn,H((Qn)=>({...Qn,currentResolution:je.resolution,isCurrentHdr:je.hdr??!1}))}}if(ws){let Vn=null,Qn=()=>{if(Vn)clearTimeout(Vn),Vn=null;if(ot.removeEventListener("seeked",Bs),gn.off?.(es.Events.ERROR,Qn),oe.current===Qn)oe.current=null},Bs=()=>{Qn();let rs=Ia(Hn,it),Ni=1/it;if(Math.abs(ot.currentTime-rs)>Ni/4)ot.currentTime=rs};Vn=setTimeout(Qn,1500),oe.current=Qn,ot.addEventListener("seeked",Bs),gn.once?.(es.Events.ERROR,Qn)}return}let At=!ot.paused,Yt=ot.currentTime;H((gn)=>({...gn,currentResolution:je.resolution,currentSrc:je.url,isCurrentHdr:je.hdr??!1})),ot.src=je.url||"";let _n=()=>{if(ot.removeEventListener("loadedmetadata",_n),ot.currentTime=Yt,At){let gn=ot.play();if(gn!==void 0)gn.catch((ws)=>{if(ws.name!=="AbortError")console.error("Play after seek failed:",ws)})}ot.playbackRate=N.playbackRate};ot.addEventListener("loadedmetadata",_n)},Xt=()=>{let je=ce.current,ot=p.current;if(je&&typeof je.requestFullscreen==="function"){if(!document.fullscreenElement)je.requestFullscreen().catch(()=>{}),H((Yt)=>({...Yt,isFullScreen:!0}));else if(document.exitFullscreen)document.exitFullscreen().catch(()=>{}),H((Yt)=>({...Yt,isFullScreen:!1}));return}let At=ot;if(At&&typeof At.webkitEnterFullscreen==="function"){if(!At.webkitDisplayingFullscreen)try{At.webkitEnterFullscreen()}catch(Yt){console.error("Failed to enter iOS fullscreen:",Yt)}else if(typeof At.webkitExitFullscreen==="function")try{At.webkitExitFullscreen()}catch(Yt){console.error("Failed to exit iOS fullscreen:",Yt)}return}H((Yt)=>({...Yt,isFullScreen:!Yt.isFullScreen}))},us=async(je)=>{try{let ot=o?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:o,fileId:e.id},json:{key:je}}):await R.api.files["download-url"].$post({json:{key:je,assetId:e.id}});if(!ot.ok)return;let{url:At}=await ot.json(),Yt=document.createElement("a");Yt.href=At,Yt.download="",document.body.appendChild(Yt),Yt.click(),document.body.removeChild(Yt)}catch{}};S(()=>{let je=()=>{H((_n)=>({..._n,isFullScreen:!!document.fullscreenElement}))};document.addEventListener("fullscreenchange",je);let ot=p.current,At=()=>{H((_n)=>({..._n,isFullScreen:!0}))},Yt=()=>{H((_n)=>({..._n,isFullScreen:!1}))};if(ot)ot.addEventListener("webkitbeginfullscreen",At),ot.addEventListener("webkitendfullscreen",Yt);return()=>{if(document.removeEventListener("fullscreenchange",je),ot)ot.removeEventListener("webkitbeginfullscreen",At),ot.removeEventListener("webkitendfullscreen",Yt)}},[]);let Zs=te,Gr=hs();if(!_){if(e.status==="failed"){let je=e.media?.error;return g("div",{"data-testid":"video-viewer-failed-state",className:"flex h-full w-full flex-col items-center justify-center gap-3 p-6 text-center",children:[a(_r,{className:"h-12 w-12 text-destructive/80"}),g("div",{className:"space-y-1 max-w-md",children:[a("h3",{className:"text-base font-semibold text-foreground",children:J_()}),a("p",{className:"text-sm text-muted-foreground",children:Y_()}),je&&a("div",{title:je,className:"mt-3 rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-xs text-destructive text-left line-clamp-3 break-words",children:je})]})]})}return a("div",{className:"flex h-full w-full items-center justify-center",children:a("p",{className:"text-muted-foreground",children:gI()})})}return g("div",{ref:ce,className:B("group shadow-2xl font-sans select-none flex flex-col mx-auto relative",N.isFullScreen?"h-full w-full rounded-none bg-black":"w-full h-full",!bt&&N.isFullScreen?"cursor-none":""),onMouseMove:ua,onMouseLeave:Co,children:[g("div",{className:"flex-1 flex flex-col-reverse md:flex-row min-h-0 relative",children:[!N.isFullScreen&&l,g("div",{ref:W,className:B("flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0 touch-none"),onClick:ma,"data-testid":"video-area",children:[!Ln&&a("div",{className:"absolute pointer-events-none overflow-hidden",style:{left:0,top:0,width:st,height:We,transform:`translate(${he.x}px, ${he.y}px) scale(${Zs})`,transformOrigin:"0 0"},children:a("video",{ref:p,className:B("w-full h-full block object-contain pointer-events-none",!V&&e.preview?.thumbnailUrl&&"blur-md scale-105"),playsInline:!0,preload:"auto",poster:e.preview?.thumbnailUrl||void 0})}),Ln&&a("video",{ref:p,className:"absolute inset-0 pointer-events-none opacity-0",playsInline:!0,preload:"auto"}),Ln?a("div",{className:"flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none",children:a(Ps,{className:B("w-16 h-16 text-foreground/75 transition-transform duration-500",N.isPlaying?"animate-pulse scale-110 text-primary":"")})}):Te.width>0&&a(Or,{width:Te.width,height:Te.height,mediaDimensions:{width:st,height:We},annotations:Kn,scale:Zs,offset:he,className:"absolute inset-0",isDrawing:It,currentTool:Wt,currentColor:hn,onAddAnnotation:zt}),mn&&a("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200","data-testid":"video-loading-spinner",children:a("div",{className:"w-16 h-16 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30",children:a(K,{className:"w-8 h-8 text-white animate-spin"})})}),!mn&&!V&&!It&&a("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200","data-testid":"video-play-overlay",children:a("div",{className:"w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30",children:a(ya,{className:"w-10 h-10 text-white ml-1 fill-white"})})})]})]}),Gr?a(Uv,{state:pl,zoom:te,isControlsVisible:bt,buffered:Le,data:e,resolutions:I,togglePlay:ma,toggleLoop:jo,toggleMute:_o,handleVolumeChange:ir,changePlaybackRate:Ze,changeResolution:pn,handleDownload:us,toggleFullScreen:Xt,onZoomChange:xt,onZoomReset:ft,frameRate:it,totalFrames:is,currentFrame:xs,seekToFrame:ha,onMouseEnter:Xa,onMouseLeave:da,allowDownload:c,isLoading:mn}):a($d,{state:pl,zoom:te,isControlsVisible:bt,buffered:Le,data:e,resolutions:I,togglePlay:ma,toggleLoop:jo,toggleMute:_o,handleVolumeChange:ir,changePlaybackRate:Ze,changeResolution:pn,handleDownload:us,toggleFullScreen:Xt,onZoomChange:xt,onZoomReset:ft,frameRate:it,totalFrames:is,currentFrame:xs,seekToFrame:ha,onMouseEnter:Xa,onMouseLeave:da,allowDownload:c,isLoading:mn})]})}),N8=Hq;Z();function gu(e){if(!e||e.length<2)return null;let t=[...e].sort((n,s)=>s.version-n.version);return{left:t[0],right:t[1]}}function B8(e,t){return Math.max(0,Math.min(e,Math.max(0,t-1)))}function Uq(e){return(Boolean(e.media?.isHls&&e.media.hls?.url)?e.media?.hls?.resolutions??[]:e.media?.videoTranscodes??[]).map((s)=>({...s,resolution:ii(s)}))}function H8(e){if(e.length===0)return null;if(typeof window>"u")return e[0];let t=typeof window.matchMedia==="function"&&window.matchMedia("(dynamic-range: high)").matches,n=e.some((c)=>c.hdr),s=e.some((c)=>!c.hdr),i=e;if(t&&n)i=e.filter((c)=>c.hdr);else if(!t&&s)i=e.filter((c)=>!c.hdr);let r=window.innerWidth*(window.devicePixelRatio||1),o=[...i].sort((c,h)=>(c.width??0)-(h.width??0));return o.find((c)=>(c.width??0)>=r)||o[o.length-1]}var U8=J(function({file:t,shareId:n,isActive:s,muted:i=!0,volume:r=1,annotations:o,onStateChange:l,onActivate:c,onRequestTogglePlay:h,onTimeUpdate:d,onPlay:m},p){let b=M(null),v=M(null),k=M(null),{isDrawing:A,currentTool:T,currentColor:E,addAnnotation:I,annotations:_}=un(),[q,P]=w({width:0,height:0}),[N,H]=w(1),[V,U]=w(!1),[W,ce]=w(null),[ue,oe]=w(!1),[ae,te]=w(!1),[me,he]=w(!1),[we,be]=w(1),[ye,Te]=w(0),[Oe,st]=w(r),[We,wt]=w(i),[xt,ft]=w(!1),[It,Wt]=w(!0),hn=M(null),zt=t.media?.metadata,tn=zt?.frameRate||30,Kn=zt?.totalFrames||0,Le=zt?.duration||0,Je=Kd({dbTotalFrames:Kn,containerDuration:Le,frameRate:tn}),bt=Boolean(t.media?.isHls&&t.media.hls?.url),ut=Uq(t),Ft=bt?null:H8(ut),[nn,mn]=w(bt?"Auto":Ft?.resolution??""),[Vt,Fn]=w(Ft?.hdr),[ns,St]=w(void 0),it=M(null),sn=!bt||Boolean(es.isSupported()),Lt=M(bt?t.media.hls.url:Ft?.url),Ln=t.proxyType==="audio",{currentFrame:is,seekToFrame:xs}=v0(k,tn,Je,Ln),Ls=M(N);Ls.current=N;let ha=M(is);ha.current=is,S(()=>{if(!v.current)return;let Ze=new ResizeObserver((pn)=>{let Xt=pn[0];if(Xt)P({width:Xt.contentRect.width,height:Xt.contentRect.height})});return Ze.observe(v.current),()=>Ze.disconnect()},[]);let Pi=zt?.originalWidth||1920,nr=zt?.originalHeight||1080;S(()=>{if(q.width>0&&q.height>0&&!V){let Ze=Math.min(q.width/Pi,q.height/nr);H(Ze)}},[q.width,q.height,Pi,nr,V]),S(()=>{let Ze=bt?null:H8(ut);if(mn(bt?"Auto":Ze?.resolution??""),Fn(Ze?.hdr),St(void 0),Lt.current=bt?t.media.hls.url:Ze?.url,hn.current)clearTimeout(hn.current),hn.current=null;Wt(!0),ft(!1),te(!1)},[t.id,Boolean(bt?t.media?.hls?.url:Ft?.url)]),S(()=>{let Ze=k.current;if(!Ze)return;let pn=bt?t.media.hls.url:Lt.current??"";if(!pn)return;if(b.current)b.current.destroy(),b.current=null;if(hn.current)clearTimeout(hn.current),hn.current=null;ft(!1),Wt(!0);let Xt=null;if(bt){if(es.isSupported())Xt=new es({autoStartLoad:!0,startLevel:-1,capLevelToPlayerSize:!1,enableWorker:!0}),b.current=Xt,Xt.attachMedia(Ze),Xt.loadSource(pn),Xt.on(es.Events.LEVEL_SWITCHED,(Qn,Bs)=>{let rs=Xt?.levels[Bs.level];if(rs){let Ni=ut.find((Vr)=>Vr.width===rs.width&&Vr.height===rs.height);if(Ni?.resolution)St(Ni.resolution);else{let Vr=rs.width&&rs.height?Math.min(rs.width,rs.height):rs.height||rs.width;St(Vr?`${Vr}p`:void 0)}}}),Xt.on(es.Events.ERROR,(Qn,Bs)=>{if(Bs.fatal)switch(Bs.type){case es.ErrorTypes.NETWORK_ERROR:Xt?.startLoad();break;case es.ErrorTypes.MEDIA_ERROR:Xt?.recoverMediaError();break;default:Xt?.destroy();break}});else if(Ze.canPlayType("application/vnd.apple.mpegurl"))Ze.src=pn}else Ze.src=pn;let us=()=>{if(hn.current)clearTimeout(hn.current),hn.current=null},Zs=()=>{if(us(),Wt(!1),ft(!0),it.current)it.current(),it.current=null;oe(!0),te(!0),m?.()},Gr=()=>oe(!1),je=()=>{us(),Wt(!1),oe(!1)},ot=()=>{us(),Wt(!1),ft(!0)},At=()=>{us(),Wt(!1),ft(!0)},Yt=()=>{us(),Wt(!1)},_n=()=>{us(),hn.current=setTimeout(()=>{Wt(!0)},200)},gn=()=>{us(),Wt(!0),ft(!1)},ws=()=>{let Qn=Ze.duration||Le||0;if(Qn>0&&Ze.buffered.length>0){let Bs=0;for(let rs=0;rs<Ze.buffered.length;rs++)if(Ze.buffered.start(rs)<=Ze.currentTime&&Ze.currentTime<=Ze.buffered.end(rs)){Bs=Ze.buffered.end(rs);break}if(Bs===0)Bs=Ze.buffered.end(Ze.buffered.length-1);Te(Bs/Qn*100)}},Hn=()=>{st(Ze.volume||0),wt(Ze.muted||!1)},Vn=()=>be(Ze.playbackRate||1);if(Ze.readyState>=2)Wt(!1),ft(!0);return Ze.addEventListener("play",Zs),Ze.addEventListener("pause",Gr),Ze.addEventListener("ended",je),Ze.addEventListener("loadeddata",ot),Ze.addEventListener("canplay",At),Ze.addEventListener("playing",Yt),Ze.addEventListener("waiting",_n),Ze.addEventListener("loadstart",gn),Ze.addEventListener("timeupdate",ws),Ze.addEventListener("progress",ws),Ze.addEventListener("volumechange",Hn),Ze.addEventListener("ratechange",Vn),()=>{if(us(),Ze.removeEventListener("play",Zs),Ze.removeEventListener("pause",Gr),Ze.removeEventListener("ended",je),Ze.removeEventListener("loadeddata",ot),Ze.removeEventListener("canplay",At),Ze.removeEventListener("playing",Yt),Ze.removeEventListener("waiting",_n),Ze.removeEventListener("loadstart",gn),Ze.removeEventListener("timeupdate",ws),Ze.removeEventListener("progress",ws),Ze.removeEventListener("volumechange",Hn),Ze.removeEventListener("ratechange",Vn),it.current)it.current(),it.current=null;if(b.current)b.current.destroy(),b.current=null}},[t.id]),S(()=>{let Ze=k.current;if(!Ze||!xt)return;Ze.muted=i,Ze.volume=r},[i,r,xt]),S(()=>{l({kind:"video",zoom:N,video:{frameRate:tn,totalFrames:Je,currentFrame:is,isPlaying:ue,volume:Oe,isMuted:We,playbackRate:we,isLooping:me,currentResolution:nn,isCurrentHdr:Vt,resolutions:ut,buffered:ye,activeAutoResolution:ns,isHlsManualSupported:sn,isLoading:It}})},[N,tn,Je,is,ue,Oe,We,we,me,nn,Vt,ye,ns,sn,It]),S(()=>{if(s)d?.(is/tn)},[is,tn,s,d]);let To=Q((Ze)=>{let Xt=Ls.current*Ze;if(Xt<0.01||Xt>50)return;H(Xt),U(!0)},[]),pl=Q(()=>{U(!1),ce(null)},[]),sr=Q((Ze)=>B8(Ze,Je),[Je]),$a=Q(async(Ze)=>{let pn=Ze??t.media?.original?.key;if(!pn||!t.id)return;try{let Xt=n?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:n,fileId:t.id},json:{key:pn}}):await R.api.files["download-url"].$post({json:{key:pn,assetId:t.id}});if(!Xt.ok)return;let{url:us}=await Xt.json(),Zs=document.createElement("a");Zs.href=us,Zs.download="",document.body.appendChild(Zs),Zs.click(),document.body.removeChild(Zs)}catch{}},[t.id,t.media?.original?.key,n]),ua=Q((Ze,pn)=>{let Xt=k.current;if(!Xt)return;if(it.current)it.current(),it.current=null;if(bt){if(!b.current)return;let ot=b.current,At=Xt.paused,Yt=ha.current;if(Ze==="Auto"){if(nn==="Auto"&&ot.currentLevel===-1)return;ot.currentLevel=-1,mn("Auto")}else{let _n=ut.find((gn)=>gn.resolution===Ze);if(_n){let gn=ot.levels.findIndex((ws)=>ws.height===_n.height||Math.max(ws.width,ws.height)===Math.max(_n.width,_n.height));if(gn!==-1){if(gn===ot.currentLevel&&nn===Ze)return;ot.currentLevel=gn,mn(Ze),Fn(_n.hdr)}}}if(At){let _n=null,gn=()=>{if(_n)clearTimeout(_n),_n=null;if(Xt.removeEventListener("seeked",ws),ot.off?.(es.Events.ERROR,gn),it.current===gn)it.current=null},ws=()=>{gn();let Hn=Ia(Yt,tn),Vn=1/tn;if(Math.abs(Xt.currentTime-Hn)>Vn/4)Xt.currentTime=Hn};_n=setTimeout(gn,1500),it.current=gn,Xt.addEventListener("seeked",ws),ot.once?.(es.Events.ERROR,gn)}return}let us=pn!==void 0?ut.find((ot)=>ot.resolution===Ze&&Boolean(ot.hdr)===Boolean(pn)):ut.find((ot)=>ot.resolution===Ze);if(!us)return;let Zs=!Xt.paused,Gr=Xt.currentTime;mn(Ze),Fn(us.hdr),Lt.current=us.url,Xt.src=us.url||"";let je=()=>{if(Xt.removeEventListener("loadedmetadata",je),Xt.currentTime=Gr,Zs){let ot=Xt.play();if(ot!==void 0)ot.catch(()=>{})}Xt.playbackRate=we};Xt.addEventListener("loadedmetadata",je)},[ut,bt,tn,we,nn]);bn(p,()=>({getKind:()=>"video",play:()=>{if(it.current)it.current(),it.current=null;let Ze=k.current?.play();if(Ze!==void 0)Ze.catch(()=>{})},pause:()=>k.current?.pause(),togglePlay:()=>{let Ze=k.current;if(!Ze)return;if(it.current)it.current(),it.current=null;if(Ze.paused||Ze.ended){let pn=Ze.play();if(pn!==void 0)pn.catch(()=>{})}else Ze.pause()},seekToFrame:(Ze)=>{if(it.current)it.current(),it.current=null;return te(!0),xs(sr(Ze))},seekToSecond:(Ze)=>{if(it.current)it.current(),it.current=null;te(!0);let pn=Math.floor(Ze*tn+0.45);xs(sr(pn))},stepFrame:(Ze)=>{if(it.current)it.current(),it.current=null;return te(!0),xs(sr(ha.current+Ze))},setMuted:(Ze)=>{if(k.current)k.current.muted=Ze},setVolume:(Ze)=>{let pn=k.current;if(!pn)return;if(pn.volume=Ze,Ze>0&&pn.muted)pn.muted=!1;else if(Ze===0&&!pn.muted)pn.muted=!0},setPlaybackRate:(Ze)=>{if(k.current)k.current.playbackRate=Ze},toggleLoop:()=>{let Ze=k.current;if(!Ze)return;let pn=!Ze.loop;Ze.loop=pn,he(pn)},changeResolution:ua,zoomBy:To,fit:pl,panBy:(Ze,pn)=>ce((Xt)=>{let us=Ls.current,Zs=Xt??{x:(q.width-Pi*us)/2,y:(q.height-nr*us)/2};return{x:Zs.x+Ze,y:Zs.y+pn}}),download:(Ze)=>$a(Ze)}),[xs,sr,tn,To,pl,ua,$a,q.width,q.height,Pi,nr]);let Xa=[...o??[],...s?_:[]],da=N,Co=(q.width-Pi*da)/2,ma=(q.height-nr*da)/2,jo=W?.x??Co,ir=W?.y??ma,_o=Q(()=>{if(un.getState().isDrawing)return;if(!s){c?.();return}if(It)return;h?.()},[s,It,c,h]);if(!t.media?.metadata||ut.length===0)return a("div",{className:"flex h-full w-full items-center justify-center bg-black",children:a("p",{className:"text-muted-foreground",children:"Media is not available."})});return g("div",{ref:v,className:B("relative flex flex-1 cursor-pointer items-center justify-center overflow-hidden bg-black"),onClick:_o,"data-testid":"compare-video-area",children:[!Ln&&a("div",{className:"absolute pointer-events-none overflow-hidden",style:{left:0,top:0,width:Pi,height:nr,transform:`translate(${jo}px, ${ir}px) scale(${da})`,transformOrigin:"0 0"},children:a("video",{ref:k,className:B("w-full h-full block object-contain pointer-events-none",!ae&&t.preview?.thumbnailUrl&&"blur-md scale-105"),playsInline:!0,preload:"auto",poster:t.preview?.thumbnailUrl||void 0})}),Ln&&a("video",{ref:k,className:"absolute inset-0 pointer-events-none opacity-0",playsInline:!0,preload:"auto"}),Ln?a("div",{className:"flex flex-col items-center justify-center text-muted-foreground w-full h-full pointer-events-none select-none",children:a(Ps,{className:B("w-16 h-16 text-foreground/75 transition-transform duration-500",ue?"animate-pulse scale-110 text-primary":"")})}):q.width>0&&a(Or,{width:q.width,height:q.height,mediaDimensions:{width:Pi,height:nr},annotations:Xa,scale:da,offset:{x:jo,y:ir},className:"absolute inset-0",onClick:_o,isDrawing:s&&A,currentTool:T,currentColor:E,onAddAnnotation:s?I:void 0}),It&&a("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20 transition-opacity duration-200","data-testid":"compare-video-loading-spinner",children:a("div",{className:"flex h-14 w-14 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm",children:a(K,{className:"h-7 w-7 text-white animate-spin"})})}),!It&&!ae&&!A&&a("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20 transition-opacity duration-200","data-testid":"compare-video-play-overlay",children:a("div",{className:"flex h-16 w-16 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm",children:a(ya,{className:"ml-1 h-8 w-8 fill-white text-white"})})})]})});var z8={id:"video",name:"Video",match:(e)=>e.proxyType==="video"||e.proxyType==="audio",viewer:N8,comparePane:U8,commentsConfig:{hasTimestamp:!0,hasAnnotations:!0}};Z();function $0(){let[e,t]=w({width:window.innerWidth,height:window.innerHeight});return nt(()=>{function n(){t({width:window.innerWidth,height:window.innerHeight})}return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}Z();function Hd({zoom:e,onZoomIn:t,onZoomOut:n,onFit:s,onDownload:i,canDownload:r,onCopy:o,copied:l=!1,canCopy:c=!0,allowDownload:h=!0,fullscreen:d}){return g("div",{className:"relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200",children:[g("div",{className:"flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto",children:[a("button",{onClick:n,className:"p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors",title:yg(),children:a(ss,{size:16})}),g("span",{className:"w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none",children:[Math.round(e*100),"%"]}),a("button",{onClick:t,className:"p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors",title:_g(),children:a(Re,{size:16})})]}),a("button",{onClick:s,className:"text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200",children:fh()}),o&&g("button",{onClick:o,disabled:!c,className:"flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200",title:Ww(),children:[l?a(qe,{size:14,className:"text-green-500"}):a(Zr,{size:14}),l?Qw():Km()]}),h&&g("button",{onClick:i,disabled:!r,className:"flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200",title:YE(),children:[a(Bt,{size:14}),Dr()]}),d&&a("button",{onClick:d.onToggle,className:"p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors",title:Ap(),children:d.isFullScreen?a(li,{size:16}):a(ai,{size:16})})]})}var zq=J(({file:e,annotations:t,shareId:n,children:s,allowDownload:i},r)=>{bn(r,()=>({play:()=>{},pause:()=>{},seekTo:()=>{}}));let{width:o}=$0(),{isDrawing:l,currentTool:c,currentColor:h,addAnnotation:d,annotations:m}=un(),[p,b]=w({width:0,height:0}),[v,k]=w(1),[A,T]=w({x:0,y:0}),[E,I]=w(!1),[_,q]=w(!1),P=M(null);S(()=>{I(!1),q(!1)},[e.id]),S(()=>{let he=P.current;if(!he)return;let we=new ResizeObserver((be)=>{let ye=be[0];if(ye)b({width:ye.contentRect.width,height:ye.contentRect.height})});return we.observe(he),()=>we.disconnect()},[]);let N=e.media?.metadata?.originalWidth??1920,H=e.media?.metadata?.originalHeight??1080,{width:V,height:U}=p,W=Na(V,U,N,H);S(()=>{if(V<=0||U<=0)return;if(E)return;k(W),T(Pr(V,U,N,H,W))},[V,U,W,N,H,E]);let ce=(he)=>{I(!0);let we=oa(v,A,he,V/2,U/2);k(we.zoom),T(we.pan)},ue=()=>{I(!1),k(W),T(Pr(V,U,N,H,W))};ll({containerRef:P,zoom:v,pan:A,baseScale:W,onZoomChange:(he)=>{I(!0),k(he.zoom),T(he.pan)},onPanChange:T});let oe=Yp(e.media?.imageTranscodes,o)?.url??"",ae=async()=>{let he=e.media?.original?.key;if(!he||!e.id)return;try{let we=n?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:n,fileId:e.id},json:{key:he}}):await R.api.files["download-url"].$post({json:{key:he,assetId:e.id}});if(!we.ok)return;let{url:be}=await we.json(),ye=document.createElement("a");ye.href=be,ye.download="",document.body.appendChild(ye),ye.click(),document.body.removeChild(ye)}catch{}},te=async()=>{let he=oe;if(!he)return;try{let we=(async()=>{let ye=await(await fetch(he)).blob(),Te=new Image;Te.crossOrigin="anonymous";let Oe=URL.createObjectURL(ye);Te.src=Oe;try{await new Promise((xt,ft)=>{Te.onload=xt,Te.onerror=(It)=>ft(Error("Failed to load image: "+String(It)))});let st=document.createElement("canvas");st.width=Te.width,st.height=Te.height;let We=st.getContext("2d");if(!We)throw Error("Could not get canvas context");We.drawImage(Te,0,0);let wt=await new Promise((xt)=>{st.toBlob(xt,"image/png")});if(!wt)throw Error("Failed to convert image to PNG");return wt}finally{URL.revokeObjectURL(Oe)}})();await navigator.clipboard.write([new ClipboardItem({"image/png":we})]),q(!0),setTimeout(()=>q(!1),2000)}catch(we){console.error("Failed to copy image to clipboard:",we)}},me=[...t||[],...m];return g("div",{className:"flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative",children:[g("div",{className:"flex-1 flex flex-col-reverse md:flex-row min-h-0 relative",children:[s,a("div",{ref:P,className:"flex-1 relative overflow-hidden touch-none",children:oe?a(Or,{width:V,height:U,mediaDimensions:{width:N,height:H},imageUrl:oe,annotations:me,scale:v,offset:A,onPan:Kh(v,W)?T:void 0,className:"absolute inset-0 z-0",isDrawing:l,currentTool:c,currentColor:h,onAddAnnotation:d}):a("div",{className:"flex h-full w-full items-center justify-center",children:a("p",{className:"text-muted-foreground",children:"Preview unavailable"})})})]}),a(Hd,{zoom:v,onZoomIn:()=>ce(1.2),onZoomOut:()=>ce(0.8),onFit:ue,onDownload:ae,canDownload:!!e.media?.original?.key,onCopy:te,copied:_,canCopy:!!oe,allowDownload:i})]})}),G8=zq;Z();var Gq=0.01,Vq=50,V8=J(function({file:t,shareId:n,isActive:s,annotations:i,onStateChange:r,onUserPan:o,onActivate:l},c){let{width:h}=$0(),{isDrawing:d,currentTool:m,currentColor:p,addAnnotation:b,annotations:v}=un(),[k,A]=w({width:0,height:0}),[T,E]=w(1),[I,_]=w({x:0,y:0}),q=M(null),P=M(T);P.current=T;let N=M(I);N.current=I;let H=Q((be)=>{if(q.current)q.current.disconnect(),q.current=null;if(be!==null){let ye=new ResizeObserver((Te)=>{let Oe=Te[0];if(Oe)A({width:Oe.contentRect.width,height:Oe.contentRect.height})});ye.observe(be),q.current=ye}},[]),V=t.media?.metadata?.originalWidth??1920,U=t.media?.metadata?.originalHeight??1080,{width:W,height:ce}=k,ue=1;if(W>0&&ce>0)ue=Math.min(W/V,ce/U);S(()=>{if(W>0&&ce>0)E(ue),_({x:(W-V*ue)/2,y:(ce-U*ue)/2})},[t.id,W,ce,ue,V,U]);let oe=Q((be)=>{let ye=W/2,Te=ce/2,Oe=P.current,st=Oe*be;if(st<Gq||st>Vq)return;let We=N.current;_({x:ye-(ye-We.x)*(st/Oe),y:Te-(Te-We.y)*(st/Oe)}),E(st)},[W,ce]),ae=Q(()=>{E(ue),_({x:(W-V*ue)/2,y:(ce-U*ue)/2})},[ue,W,ce,V,U]),te=Yp(t.media?.imageTranscodes,h)?.url??"",me=Q(async()=>{let be=t.media?.original?.key;if(!be||!t.id)return;try{let ye=n?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:n,fileId:t.id},json:{key:be}}):await R.api.files["download-url"].$post({json:{key:be,assetId:t.id}});if(!ye.ok)return;let{url:Te}=await ye.json(),Oe=document.createElement("a");Oe.href=Te,Oe.download="",document.body.appendChild(Oe),Oe.click(),document.body.removeChild(Oe)}catch{}},[t.id,t.media?.original?.key,n]);bn(c,()=>({getKind:()=>"image",play:()=>{},pause:()=>{},togglePlay:()=>{},seekToFrame:()=>{},seekToSecond:()=>{},stepFrame:()=>{},setMuted:()=>{},setVolume:()=>{},setPlaybackRate:()=>{},toggleLoop:()=>{},changeResolution:()=>{},zoomBy:(be)=>oe(be),fit:ae,panBy:(be,ye)=>_((Te)=>({x:Te.x+be,y:Te.y+ye})),download:me}),[oe,ae,me]),S(()=>{r({kind:"image",zoom:T})},[T,r]);let he=[...i,...s?v:[]],we=Q((be)=>{let ye=N.current,Te=be.x-ye.x,Oe=be.y-ye.y;if(_(be),Te!==0||Oe!==0)o?.(Te,Oe)},[o]);if(!te)return a("div",{className:"flex flex-1 items-center justify-center bg-gray-100 dark:bg-gray-950",children:a("p",{className:"text-muted-foreground",children:"Preview unavailable"})});return a("div",{ref:H,className:"relative flex-1 overflow-hidden bg-black",onMouseDown:l,children:a(Or,{width:W,height:ce,mediaDimensions:{width:V,height:U},imageUrl:te,annotations:he,scale:T,offset:I,onPan:we,className:"absolute inset-0 z-0",isDrawing:s&&d,currentTool:m,currentColor:p,onAddAnnotation:s?b:void 0})})});var $8={id:"image",name:"Image",match:(e)=>e.proxyType==="image",viewer:G8,comparePane:V8,commentsConfig:{hasTimestamp:!1,hasAnnotations:!0}};var Sr=typeof process==="object"&&process+""==="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),ko=[1/0,1/0,-1/0,-1/0],Yl=new Float32Array(ko),Vb=[0.001,0,0,0.001,0,0];var vr={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},hl={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3};var Jt={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},Tn={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},$q={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048};var ni={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},nm={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Is={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27};var mf={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5};var gm={ERRORS:0,WARNINGS:1,INFOS:5},za={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Yh={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},Xq={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},bm=gm.WARNINGS;function Wq(e){if(Number.isInteger(e))bm=e}function Kq(){return bm}function wm(e){if(bm>=gm.INFOS)console.info(`Info: ${e}`)}function on(e){if(bm>=gm.WARNINGS)console.warn(`Warning: ${e}`)}function Dn(e){throw Error(e)}function Rs(e,t){if(!e)Dn(t)}function Yq(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function v7(e,t=null,n=null){if(!e)return null;if(n&&typeof e==="string"){if(n.addDefaultProtocol&&e.startsWith("www.")){if(e.match(/\./g)?.length>=2)e=`http://${e}`}if(n.tryConvertEncoding)try{e=Jq(e)}catch{}}let s=t?URL.parse(e,t):URL.parse(e);return Yq(s)?s:null}function S7(e,t,n=!1){let s=URL.parse(e);if(s)return s.hash=t,s.href;if(n&&v7(e,"http://example.com"))return e.split("#",1)[0]+`${t?`#${t}`:""}`;return""}function $b(e){return e.substring(e.lastIndexOf("/")+1)}function Mt(e,t,n,s=!1){return Object.defineProperty(e,t,{value:n,enumerable:!s,configurable:!0,writable:!1}),n}var rc=function(){function t(n,s){this.message=n,this.name=s}return t.prototype=Error(),t.constructor=t,t}();class am extends rc{constructor(e,t){super(e,"PasswordException");this.code=t}}class sm extends rc{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class om extends rc{constructor(e){super(e,"InvalidPDFException")}}class iu extends rc{constructor(e,t,n){super(e,"ResponseException");this.status=t,this.missing=n}}class k7 extends rc{constructor(e){super(e,"FormatError")}}class Ao extends rc{constructor(e){super(e,"AbortException")}}function Qq(e){if(typeof e!=="object"||e?.length===void 0)Dn("Invalid argument for bytesToString");let t=e.length,n=8192;if(t<n)return String.fromCharCode.apply(null,e);let s=[];for(let i=0;i<t;i+=n){let r=Math.min(i+n,t),o=e.subarray(i,r);s.push(String.fromCharCode.apply(null,o))}return s.join("")}function ym(e){if(typeof e!=="string")Dn("Invalid argument for stringToBytes");let t=e.length,n=new Uint8Array(t);for(let s=0;s<t;++s)n[s]=e.charCodeAt(s)&255;return n}class Wn{static get isLittleEndian(){let e=new Uint8Array(4);e[0]=1;let t=new Uint32Array(e.buffer,0,1);return Mt(this,"isLittleEndian",t[0]===1)}static get isOffscreenCanvasSupported(){return Mt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Mt(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return Mt(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return Mt(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){let{platform:e,userAgent:t}=navigator;return Mt(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCanvasFilterSupported(){let e;if(this.isOffscreenCanvasSupported)e=new OffscreenCanvas(1,1).getContext("2d");else if(typeof document<"u")e=document.createElement("canvas").getContext("2d");return Mt(this,"isCanvasFilterSupported",e?.filter!==void 0)}static get isAlphaColorInputSupported(){if(typeof document>"u")return Mt(this,"isAlphaColorInputSupported",!1);let e=document.createElement("input");return e.type="color",e.setAttribute("alpha",""),e.value="#ff000080",Mt(this,"isAlphaColorInputSupported",e.value!=="#ff0000")}static get isBackdropFilterSupported(){return Mt(this,"isBackdropFilterSupported",typeof CSS<"u"&&CSS.supports("backdrop-filter","blur(1px)"))}}class ct{static get hexNums(){return Mt(this,"hexNums",Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0")))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){let s=e[n],i=e[n+1];e[n]=s*t[0]+i*t[2]+t[4],e[n+1]=s*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){let s=t[0],i=t[1],r=t[2],o=t[3],l=t[4],c=t[5];for(let h=0;h<6;h+=2){let d=e[n+h],m=e[n+h+1];e[n+h]=d*s+m*r+l,e[n+h+1]=d*i+m*o+c}}static applyInverseTransform(e,t){let n=e[0],s=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-s*t[2]+t[2]*t[5]-t[4]*t[3])/i,e[1]=(-n*t[1]+s*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,n){let s=t[0],i=t[1],r=t[2],o=t[3],l=t[4],c=t[5],h=e[0],d=e[1],m=e[2],p=e[3],b=s*h+l,v=b,k=s*m+l,A=k,T=o*d+c,E=T,I=o*p+c,_=I;if(i!==0||r!==0){let q=i*h,P=i*m,N=r*d,H=r*p;b+=N,A+=N,k+=H,v+=H,T+=q,_+=q,I+=P,E+=P}n[0]=Math.min(n[0],b,k,v,A),n[1]=Math.min(n[1],T,I,E,_),n[2]=Math.max(n[2],b,k,v,A),n[3]=Math.max(n[3],T,I,E,_)}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){let n=e[0],s=e[1],i=e[2],r=e[3],o=n**2+s**2,l=n*i+s*r,c=i**2+r**2,h=(o+c)/2,d=Math.sqrt(h**2-(o*c-l**2));t[0]=Math.sqrt(h+d||1),t[1]=Math.sqrt(h-d||1)}static normalizeRect(e){let t=e.slice(0);if(e[0]>e[2])t[0]=e[2],t[2]=e[0];if(e[1]>e[3])t[1]=e[3],t[3]=e[1];return t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),s=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>s)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),r=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));if(i>r)return null;return[n,i,s,r]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,s,i){i[0]=Math.min(i[0],e,n),i[1]=Math.min(i[1],t,s),i[2]=Math.max(i[2],e,n),i[3]=Math.max(i[3],t,s)}static#e(e,t,n,s,i,r,o,l,c,h){if(c<=0||c>=1)return;let d=1-c,m=c*c,p=m*c,b=d*(d*(d*e+3*c*t)+3*m*n)+p*s,v=d*(d*(d*i+3*c*r)+3*m*o)+p*l;h[0]=Math.min(h[0],b),h[1]=Math.min(h[1],v),h[2]=Math.max(h[2],b),h[3]=Math.max(h[3],v)}static#t(e,t,n,s,i,r,o,l,c,h,d,m){if(Math.abs(c)<0.000000000001){if(Math.abs(h)>=0.000000000001)this.#e(e,t,n,s,i,r,o,l,-d/h,m);return}let p=h**2-4*d*c;if(p<0)return;let b=Math.sqrt(p),v=2*c;this.#e(e,t,n,s,i,r,o,l,(-h+b)/v,m),this.#e(e,t,n,s,i,r,o,l,(-h-b)/v,m)}static bezierBoundingBox(e,t,n,s,i,r,o,l,c){c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,l),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,l),this.#t(e,n,i,o,t,s,r,l,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,s,r,l,3*(-t+3*(s-r)+l),6*(t-2*s+r),3*(s-t),c)}}function Jq(e){return decodeURIComponent(escape(e))}var Bb=null,X8=null;function Zq(e){if(!Bb)Bb=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,X8=new Map([["ſt","ſt"]]);return e.replaceAll(Bb,(t,n,s)=>n?n.normalize("NFKC"):X8.get(s))}function x7(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),Qq(e)}function eM(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;let[s,i,...r]=n;if(!e(s)&&!Number.isInteger(s))return!1;if(!t(i))return!1;let o=r.length,l=!0;switch(i.name){case"XYZ":if(o<2||o>3)return!1;break;case"Fit":case"FitB":return o===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(o>1)return!1;break;case"FitR":if(o!==4)return!1;l=!1;break;default:return!1}for(let c of r){if(typeof c==="number"||l&&c===null)continue;return!1}return!0}var wf=()=>[],s2=()=>new Map,Xb=()=>Object.create(null),tM=()=>new Set;if(typeof Iterator.prototype.join!=="function")Iterator.prototype.join=function(e){return[...this].join(e)};function bs(e,t,n){return Math.min(Math.max(e,t),n)}class hu{constructor({viewBox:e,userUnit:t,scale:n,rotation:s,offsetX:i=0,offsetY:r=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=s,this.offsetX=i,this.offsetY=r,n*=t;let l=(e[2]+e[0])/2,c=(e[3]+e[1])/2,h,d,m,p;if(s%=360,s<0)s+=360;switch(s){case 180:h=-1,d=0,m=0,p=1;break;case 90:h=0,d=1,m=1,p=0;break;case 270:h=0,d=-1,m=-1,p=0;break;case 0:h=1,d=0,m=0,p=-1;break;default:throw Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(o)m=-m,p=-p;let b,v,k,A;if(h===0)b=Math.abs(c-e[1])*n+i,v=Math.abs(l-e[0])*n+r,k=(e[3]-e[1])*n,A=(e[2]-e[0])*n;else b=Math.abs(l-e[0])*n+i,v=Math.abs(c-e[1])*n+r,k=(e[2]-e[0])*n,A=(e[3]-e[1])*n;this.transform=[h*n,d*n,m*n,p*n,b-h*n*l-m*n*c,v-d*n*l-p*n*c],this.width=k,this.height=A}get rawDims(){let e=this.viewBox;return Mt(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:t=this.rotation,offsetX:n=this.offsetX,offsetY:s=this.offsetY,dontFlip:i=!1}={}){return new hu({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:s,dontFlip:i})}convertToViewportPoint(e,t){let n=[e,t];return ct.applyTransform(n,this.transform),n}convertToPdfPoint(e,t){let n=[e,t];return ct.applyInverseTransform(n,this.transform),n}}class ru{static textContent(e){let t=[],n={items:t,styles:Object.create(null)};function s(i){if(!i)return;let r=null,o=i.name;if(o==="#text")r=i.value;else if(!ru.shouldBuildText(o))return;else if(i?.attributes?.textContent)r=i.attributes.textContent;else if(i.value)r=i.value;if(r!==null)t.push({str:r});if(!i.children)return;for(let l of i.children)s(l)}return s(e),n}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}}var nM=/url\(|image-set\(/i,sM=/^on/i;class i2{static get _allowedHtmlElements(){return Mt(this,"_allowedHtmlElements",new Set(["a","b","br","button","div","i","img","input","label","li","ol","option","p","select","span","sub","sup","textarea","ul"]))}static get _allowedSvgElements(){return Mt(this,"_allowedSvgElements",new Set(["ellipse","line","path","rect","svg"]))}static get _allowedRichTextElements(){return Mt(this,"_allowedRichTextElements",new Set(["a","b","br","div","i","li","ol","p","span","sub","sup","ul"]))}static get _allowedRichTextAttributes(){return Mt(this,"_allowedRichTextAttributes",new Set(["class","dir","style"]))}static get _allowedRichTextStyles(){return Mt(this,"_allowedRichTextStyles",new Set(["color","font","fontFamily","fontSize","fontStretch","fontStyle","fontWeight","kerningMode","letterSpacing","lineHeight","margin","marginBottom","marginLeft","marginRight","marginTop","orphans","paddingLeft","paddingRight","breakAfter","breakBefore","breakInside","tabInterval","tabStop","textAlign","textDecoration","textIndent","transform","verticalAlign","widows"]))}static setupStorage(e,t,n,s,i){let r=s.getValue(t,{value:null});switch(n.name){case"textarea":if(r.value!==null)e.textContent=r.value;if(i==="print")break;e.addEventListener("input",(o)=>{s.setValue(t,{value:o.target.value})});break;case"input":if(n.attributes.type==="radio"||n.attributes.type==="checkbox"){if(r.value===n.attributes.xfaOn)e.setAttribute("checked",!0);else if(r.value===n.attributes.xfaOff)e.removeAttribute("checked");if(i==="print")break;e.addEventListener("change",(o)=>{s.setValue(t,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(r.value!==null)e.setAttribute("value",r.value);if(i==="print")break;e.addEventListener("input",(o)=>{s.setValue(t,{value:o.target.value})})}break;case"select":if(r.value!==null){e.setAttribute("value",r.value);for(let o of n.children)if(o.attributes.value===r.value)o.attributes.selected=!0;else if(Object.hasOwn(o.attributes,"selected"))delete o.attributes.selected}e.addEventListener("input",(o)=>{let l=o.target.options,c=l.selectedIndex===-1?"":l[l.selectedIndex].value;s.setValue(t,{value:c})});break}}static setAttributes({html:e,element:t,storage:n=null,intent:s,linkService:i}){let{attributes:r}=t,o=e instanceof HTMLAnchorElement;if(r.type==="radio")r.name=`${r.name}-${s}`;for(let[l,c]of Object.entries(r)){if(c===null||c===void 0)continue;if(sM.test(l))continue;if(s==="richText"&&!this._allowedRichTextAttributes.has(l))continue;switch(l){case"class":if(c.length)e.setAttribute(l,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":if(s==="richText"){let h=this._allowedRichTextStyles;for(let[d,m]of Object.entries(c))if(h.has(d)&&!nM.test(m))e.style[d]=m}else Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:if(!o||l!=="href"&&l!=="newWindow")e.setAttribute(l,c)}}if(o)i?.addLinkAttributes(e,r.href,r.newWindow);if(n&&r.dataId)this.setupStorage(e,r.dataId,t,n)}static#e(e,t,n){if(n==="richText")return!t&&this._allowedRichTextElements.has(e)?document.createElement(e):null;if(t)return t==="http://www.w3.org/2000/svg"&&this._allowedSvgElements.has(e)?document.createElementNS("http://www.w3.org/2000/svg",e):null;return this._allowedHtmlElements.has(e)?document.createElement(e):null}static render(e){let{annotationStorage:t,linkService:n,xfaHtml:s}=e,i=e.intent||"display",r=this.#e(s.name,s.attributes?.xmlns,i)??document.createElement("div");if(s.attributes)this.setAttributes({html:r,element:s,intent:i,linkService:n});let o=i!=="richText",l=e.div;if(l.append(r),e.viewport){let d=`matrix(${e.viewport.transform.join(",")})`;l.style.transform=d}if(o)l.setAttribute("class","xfaLayer xfaFont");let c=[];if(s.children.length===0){if(s.value){let d=document.createTextNode(s.value);if(r.append(d),o&&ru.shouldBuildText(s.name))c.push(d)}return{textDivs:c}}let h=[[s,-1,r]];while(h.length>0){let[d,m,p]=h.at(-1);if(m+1===d.children.length){h.pop();continue}let b=d.children[++h.at(-1)[1]];if(b===null)continue;let{name:v}=b;if(v==="#text"){let A=document.createTextNode(b.value);c.push(A),p.append(A);continue}let k=this.#e(v,b.attributes?.xmlns,i);if(!k)continue;if(p.append(k),b.attributes)this.setAttributes({html:k,element:b,storage:t,intent:i,linkService:n});if(b.children?.length>0)h.push([b,-1,k]);else if(b.value){let A=document.createTextNode(b.value);if(o&&ru.shouldBuildText(v))c.push(A);k.append(A)}}for(let d of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))d.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){let{width:s,height:i}=e.attributes.style;return new hu({viewBox:[0,0,parseInt(s,10),parseInt(i,10)],userUnit:1,scale:t,rotation:n})}}class nc{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function r2(e,t="text"){if(tu(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case"blob":return n.blob();case"bytes":return n.bytes();case"json":return n.json()}return n.text()}return new Promise((n,s)=>{let i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType=t==="bytes"?"arraybuffer":t,i.onreadystatechange=()=>{if(i.readyState!==XMLHttpRequest.DONE)return;if(i.status===200||i.status===0){switch(t){case"bytes":n(new Uint8Array(i.response));return;case"blob":case"json":n(i.response);return}n(i.responseText);return}s(Error(i.statusText))},i.send(null)})}class vm extends rc{constructor(e,t=0){super(e,"RenderingCancelledException");this.extraDelay=t}}function Sm(e){let t=e.length,n=0;while(n<t&&e[n].trim()==="")n++;return e.substring(n,n+5).toLowerCase()==="data:"}function a2(e){return typeof e==="string"&&/\.pdf$/i.test(e)}function iM(e){return[e]=e.split(/[#?]/,1),$b(e)}function aM(e,t="document.pdf"){if(typeof e!=="string")return t;if(Sm(e))return on('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;let s=((l)=>{try{return new URL(l)}catch{}try{return new URL(decodeURIComponent(l))}catch{}try{return new URL(l,"https://foo.bar")}catch{}try{return new URL(decodeURIComponent(l),"https://foo.bar")}catch{}return null})(e);if(!s)return t;let i=(l)=>{try{let c=decodeURIComponent(l);if(c.includes("/")){if(c=$b(c),c.length===4&&r.test(c))return l}return c}catch{return l}},r=/\.pdf$/i,o=$b(s.pathname);if(r.test(o))return i(o);if(s.searchParams.size>0){let l=(h)=>[...h].findLast((d)=>r.test(d)),c=l(s.searchParams.values())??l(s.searchParams.keys());if(c)return i(c)}if(s.hash){let{hash:l}=s,c=-1;for(let{index:h}of l.matchAll(/\.pdf\b/gi))c=h;if(c>0){let h=c;while(h>0&&!"/?#=".includes(l[h-1]))h--;if(h<c)return i(l.slice(h,c+4))}}return t}class Wb{#e=new Map;times=[];time(e){if(this.#e.has(e))on(`Timer is already running for ${e}`);this.#e.set(e,Date.now())}timeEnd(e){if(!this.#e.has(e))on(`Timer has not been started for ${e}`);this.times.push({name:e,start:this.#e.get(e),end:Date.now()}),this.#e.delete(e)}toString(){let e=Math.max(...this.times.map((t)=>t.name.length));return this.times.map((t)=>`${t.name.padEnd(e)} ${t.end-t.start}ms
75
- `).join("")}}function tu(e,t){let n=t?URL.parse(e,t):URL.parse(e);return/https?:/.test(n?.protocol??"")}function ca(e){e.preventDefault()}function si(e){e.preventDefault(),e.stopPropagation()}class lm{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!=="string")return null;this.#e||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?");let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),s=parseInt(t[2],10);s=s>=1&&s<=12?s-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let r=parseInt(t[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let l=parseInt(t[6],10);l=l>=0&&l<=59?l:0;let c=t[7]||"Z",h=parseInt(t[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(t[9],10)||0;if(d=d>=0&&d<=59?d:0,c==="-")r+=h,o+=d;else if(c==="+")r-=h,o-=d;return new Date(Date.UTC(n,s,i,r,o,l))}}function uu(e){if(e.startsWith("#")){let n=e.slice(1);return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16),n.length>=8?parseInt(n.slice(6,8),16)/255:1]}if(e.startsWith("rgb(")){let[n,s,i]=e.slice(4,-1).split(",").map((r)=>parseInt(r,10));return[n,s,i,1]}if(e.startsWith("rgba(")){let n=e.slice(5,-1).split(",");return[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10),parseFloat(n[3])]}let t=e.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);if(t)return[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!=="none"?parseFloat(t[4]):1];return null}function du(e){let t=uu(e);if(!t)return on(`Not a valid color format: "${e}"`),[0,0,0];return t.slice(0,3)}function oM(e){let t=document.createElement("span");t.style.visibility="hidden",t.style.colorScheme="only light",document.body.append(t);for(let n of e.keys()){t.style.color=n;let s=window.getComputedStyle(t).color;e.set(n,du(s))}t.remove()}function ds(e){let{a:t,b:n,c:s,d:i,e:r,f:o}=e.getTransform();return[t,n,s,i,r,o]}function Ba(e){let{a:t,b:n,c:s,d:i,e:r,f:o}=e.getTransform().invertSelf();return[t,n,s,i,r,o]}function sc(e,t,n=!1,s=!0){if(t instanceof hu){let{pageWidth:i,pageHeight:r}=t.rawDims,{style:o}=e,l=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-x))`,c=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-y))`;if(!n||t.rotation%180===0)o.width=l,o.height=c;else o.width=c,o.height=l}if(s)e.setAttribute("data-main-rotation",t.rotation)}class fa{constructor(){let{pixelRatio:e}=fa;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(e,t,n,s,i=-1){let r=1/0,o=1/0,l=1/0;if(n=fa.capPixels(n,i),n>0)r=Math.sqrt(n/(e*t));if(s!==-1)o=s/e,l=s/t;let c=Math.min(r,o,l);if(this.sx>c||this.sy>c)return this.sx=c,this.sy=c,!0;return!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){let n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}}var Kb=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class A7{static get isDarkMode(){return Mt(this,"isDarkMode",!!window?.matchMedia?.("(prefers-color-scheme: dark)").matches)}}class T7{static get commentForegroundColor(){let e=document.createElement("span");e.classList.add("comment","sidebar");let{style:t}=e;t.width=t.height="0",t.display="none",t.color="var(--comment-fg-color)",document.body.append(e);let{color:n}=window.getComputedStyle(e);return e.remove(),Mt(this,"commentForegroundColor",du(n))}}function lM(e,t){t=bs(t??1,0,1);let n=255*(1-t);return e.map((s)=>Math.round(s*t+n))}function W8(e,t){let n=e[0]/255,s=e[1]/255,i=e[2]/255,r=Math.max(n,s,i),o=Math.min(n,s,i),l=(r+o)/2;if(r===o)t[0]=t[1]=0;else{let c=r-o;switch(t[1]=l<0.5?c/(r+o):c/(2-r-o),r){case n:t[0]=((s-i)/c+(s<i?6:0))*60;break;case s:t[0]=((i-n)/c+2)*60;break;case i:t[0]=((n-s)/c+4)*60;break}}t[2]=l}function Yb(e,t){let n=e[0],s=e[1],i=e[2],r=(1-Math.abs(2*i-1))*s,o=r*(1-Math.abs(n/60%2-1)),l=i-r/2;switch(Math.floor(n/60)){case 0:t[0]=r+l,t[1]=o+l,t[2]=l;break;case 1:t[0]=o+l,t[1]=r+l,t[2]=l;break;case 2:t[0]=l,t[1]=r+l,t[2]=o+l;break;case 3:t[0]=l,t[1]=o+l,t[2]=r+l;break;case 4:t[0]=o+l,t[1]=l,t[2]=r+l;break;case 5:case 6:t[0]=r+l,t[1]=l,t[2]=o+l;break}}function Qb(e){return e<=0.03928?e/12.92:((e+0.055)/1.055)**2.4}function K8(e,t,n){Yb(e,n),n.map(Qb);let s=0.2126*n[0]+0.7152*n[1]+0.0722*n[2];Yb(t,n),n.map(Qb);let i=0.2126*n[0]+0.7152*n[1]+0.0722*n[2];return s>i?(s+0.05)/(i+0.05):(i+0.05)/(s+0.05)}var Y8=new Map;function cM(e,t){let n=e[0]+e[1]*256+e[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776,s=Y8.get(n);if(s)return s;let i=new Float32Array(9),r=i.subarray(0,3),o=i.subarray(3,6);W8(e,o);let l=i.subarray(6,9);W8(t,l);let c=l[2]<0.5,h=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),K8(o,l,r)<h){let d,m;if(c)d=o[2],m=1;else d=0,m=o[2];let p=0.005;while(m-d>p){let b=o[2]=(d+m)/2;if(c===K8(o,l,r)<h)d=b;else m=b}o[2]=c?m:d}return Yb(o,r),s=ct.makeHexColor(Math.round(r[0]*255),Math.round(r[1]*255),Math.round(r[2]*255)),Y8.set(n,s),s}function E7({html:e,dir:t,className:n},s){let i=document.createDocumentFragment();if(typeof e==="string"){let r=document.createElement("p");r.dir=t||"auto";let o=e.split(/\r\n?|\n/);for(let l=0,c=o.length;l<c;++l){let h=o[l];if(r.append(document.createTextNode(h)),l<c-1)r.append(document.createElement("br"))}i.append(r)}else i2.render({xfaHtml:e,div:i,intent:"richText"});i.firstElementChild.classList.add("richText",n),s.append(i)}function C7(e){let t=new Path2D;if(!e)return t;for(let n=0,s=e.length;n<s;)switch(e[n++]){case Yh.moveTo:t.moveTo(e[n++],e[n++]);break;case Yh.lineTo:t.lineTo(e[n++],e[n++]);break;case Yh.curveTo:t.bezierCurveTo(e[n++],e[n++],e[n++],e[n++],e[n++],e[n++]);break;case Yh.quadraticCurveTo:t.quadraticCurveTo(e[n++],e[n++],e[n++],e[n++]);break;case Yh.closePath:t.closePath();break;default:on(`Unrecognized drawing path operator: ${e[n-1]}`);break}return t}class nu{#e=null;#t=null;#n;#s=null;#i=null;#a=null;#r=null;#o=null;static#l=null;constructor(e){this.#n=e,nu.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"})}render(){let e=this.#e=document.createElement("div");e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");let t=this.#n._uiManager._signal;if(t instanceof AbortSignal&&!t.aborted)e.addEventListener("contextmenu",ca,{signal:t}),e.addEventListener("pointerdown",nu.#c,{signal:t});let n=this.#s=document.createElement("div");n.className="buttons",e.append(n);let s=this.#n.toolbarPosition;if(s){let{style:i}=e,r=this.#n._uiManager.direction==="ltr"?1-s[0]:s[0];i.insetInlineEnd=`${100*r}%`,i.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}return e}get div(){return this.#e}static#c(e){e.stopPropagation()}#u(e){this.#n._focusEventsAllowed=!1,si(e)}#h(e){this.#n._focusEventsAllowed=!0,si(e)}#d(e){let t=this.#n._uiManager._signal;if(!(t instanceof AbortSignal)||t.aborted)return!1;return e.addEventListener("focusin",this.#u.bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",this.#h.bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",ca,{signal:t}),!0}hide(){this.#e.classList.add("hidden"),this.#t?.hideDropdown()}show(){this.#e.classList.remove("hidden"),this.#i?.shown(),this.#a?.shown()}addDeleteButton(){let{editorType:e,_uiManager:t}=this.#n,n=document.createElement("button");if(n.classList.add("basic","deleteButton"),n.tabIndex=0,n.setAttribute("data-l10n-id",nu.#l[e]),this.#d(n))n.addEventListener("click",(s)=>{t.delete()},{signal:t._signal});this.#s.append(n)}get#p(){let e=document.createElement("div");return e.className="divider",e}async addAltText(e){let t=await e.render();this.#d(t),this.#s.append(t,this.#p),this.#i=e}addComment(e,t=null){if(this.#a)return;let n=e.renderForToolbar();if(!n)return;this.#d(n);let s=this.#r=this.#p;if(!t)this.#s.append(n,s);else this.#s.insertBefore(n,t),this.#s.insertBefore(s,t);this.#a=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let t=e.renderButton();this.#d(t),this.#s.append(t,this.#p)}async addEditSignatureButton(e){let t=this.#o=await e.renderEditButton(this.#n);this.#d(t),this.#s.append(t,this.#p)}removeButton(e){switch(e){case"comment":this.#a?.removeToolbarCommentButton(),this.#a=null,this.#r?.remove(),this.#r=null;break}}async addButton(e,t){switch(e){case"colorPicker":if(t)this.addColorPicker(t);break;case"altText":if(t)await this.addAltText(t);break;case"editSignature":if(t)await this.addEditSignatureButton(t);break;case"delete":this.addDeleteButton();break;case"comment":if(t)this.addComment(t);break}}async addButtonBefore(e,t,n){if(!t&&e==="comment")return;let s=this.#s.querySelector(n);if(!s)return;if(e==="comment")this.addComment(t,s)}updateEditSignatureButton(e){if(this.#o)this.#o.title=e}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}}class j7{#e=null;#t=null;#n;constructor(e){this.#n=e}#s(){let e=this.#t=document.createElement("div");e.className="editToolbar",e.setAttribute("role","toolbar"),e.dir=this.#n.direction;let t=this.#n._signal;if(t instanceof AbortSignal&&!t.aborted)e.addEventListener("contextmenu",ca,{signal:t});let n=this.#e=document.createElement("div");if(n.className="buttons",e.append(n),this.#n.hasCommentManager())this.#a("commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{this.#n.commentSelection("floating_button")});return this.#a("highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{this.#n.highlightSelection("floating_button")}),e}#i(e,t){let n=0,s=0;for(let i of e){let r=i.y+i.height;if(r<n)continue;let o=i.x+(t?i.width:0);if(r>n){s=o,n=r;continue}if(t){if(o>s)s=o}else if(o<s)s=o}return[t?1-s:s,n]}show(e,t,n){let[s,i]=this.#i(t,n),{style:r}=this.#t||=this.#s();e.append(this.#t),r.insetInlineEnd=`${100*s}%`,r.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){this.#t.remove()}#a(e,t,n,s){let i=document.createElement("button");i.classList.add("basic",e),i.tabIndex=0,i.setAttribute("data-l10n-id",t);let r=document.createElement("span");i.append(r),r.className="visuallyHidden",r.setAttribute("data-l10n-id",n);let o=this.#n._signal;if(o instanceof AbortSignal&&!o.aborted)i.addEventListener("contextmenu",ca,{signal:o}),i.addEventListener("click",s,{signal:o});this.#e.append(i)}}var fM="59968104-cc61-4cf9-b570-014b35b3709c",Hb=Object.freeze({internal:fM});function _7(e,t,n){for(let s of n)t.addEventListener(s,e[s].bind(e))}class zn{static#e=NaN;static#t=null;static#n=NaN;static#s=null;static initializeAndAddPointerId(e){(zn.#t||=new Set).add(e)}static setPointer(e,t){zn.#e||=t,zn.#s??=e}static setTimeStamp(e){zn.#n=e}static isSamePointerId(e){return zn.#e===e}static isSamePointerIdOrRemove(e){if(zn.#e===e)return!0;return zn.#t?.delete(e),!1}static isSamePointerType(e){return zn.#s===e}static isInitializedAndDifferentPointerType(e){return zn.#s!==null&&!zn.isSamePointerType(e)}static isSameTimeStamp(e){return zn.#n===e}static isUsingMultiplePointers(){return zn.#t?.size>=1}static clearPointerType(){zn.#s=null}static clearPointerIds(){zn.#e=NaN,zn.#t=null}static clearTimeStamp(){zn.#n=NaN}}class I7{#e=0;get id(){return`pdfjs_internal_editor_${this.#e++}`}}class o2{#e=x7();#t=0;#n=null;static get _isSVGFittingCanvas(){let n=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),s=new Image;s.src='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>';let i=s.decode().then(()=>(n.drawImage(s,0,0,1,1,0,0,1,3),new Uint32Array(n.getImageData(0,0,1,1).data.buffer)[0]===0));return Mt(this,"_isSVGFittingCanvas",i)}async#s(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n===null)return null;if(n?.bitmap)return n.refCounter+=1,n;try{n||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let s;if(typeof t==="string")n.url=t,s=await r2(t,"blob");else if(t instanceof File)s=n.file=t;else if(t instanceof Blob)s=t;if(s.type==="image/svg+xml"){let i=o2._isSVGFittingCanvas,r=new FileReader,o=new Image,l=new Promise((c,h)=>{o.onload=()=>{n.bitmap=o,n.isSvg=!0,c()},r.onload=async()=>{let d=n.svgUrl=r.result;o.src=await i?`${d}#svgView(preserveAspectRatio(none))`:d},o.onerror=r.onerror=h});r.readAsDataURL(s),await l}else n.bitmap=await createImageBitmap(s);n.refCounter=1}catch(s){on(s),n=null}if(this.#n.set(e,n),n)this.#n.set(n.id,n);return n}async getFromFile(e){let{lastModified:t,name:n,size:s,type:i}=e;return this.#s(`${t}_${n}_${s}_${i}`,e)}async getFromUrl(e){return this.#s(e,e)}async getFromBlob(e,t){let n=await t;return this.#s(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:n}=t;return delete t.blobPromise,this.getFromBlob(t.id,n)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let s=new OffscreenCanvas(t.width,t.height);return s.getContext("2d").drawImage(t,0,0),n={bitmap:s.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);if(!t?.isSvg)return null;return t.svgUrl}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return;if(t.refCounter-=1,t.refCounter!==0)return;let{bitmap:n}=t;if(!t.url&&!t.file){let s=new OffscreenCanvas(n.width,n.height);s.getContext("bitmaprenderer").transferFromImageBitmap(n),t.blobPromise=s.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}}class R7{#e=[];#t=!1;#n;#s=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:s,type:i=NaN,overwriteIfSameType:r=!1,keepUndo:o=!1}){if(s)e();if(this.#t)return;let l={cmd:e,undo:t,post:n,type:i};if(this.#s===-1){if(this.#e.length>0)this.#e.length=0;this.#s=0,this.#e.push(l);return}if(r&&this.#e[this.#s].type===i){if(o)l.undo=this.#e[this.#s].undo;this.#e[this.#s]=l;return}let c=this.#s+1;if(c===this.#n)this.#e.splice(0,1);else if(this.#s=c,c<this.#e.length)this.#e.splice(c);this.#e.push(l)}undo(){if(this.#s===-1)return;this.#t=!0;let{undo:e,post:t}=this.#e[this.#s];e(),t?.(),this.#t=!1,this.#s-=1}redo(){if(this.#s<this.#e.length-1){this.#s+=1,this.#t=!0;let{cmd:e,post:t}=this.#e[this.#s];e(),t?.(),this.#t=!1}}hasSomethingToUndo(){return this.#s!==-1}hasSomethingToRedo(){return this.#s<this.#e.length-1}cleanType(e){if(this.#s===-1)return;for(let t=this.#s;t>=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#s-t),this.#s=t;return}this.#e.length=0,this.#s=-1}destroy(){this.#e=null}}class kr{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(e){this.callbacks=new Map;let{isMac:t}=Wn.platform;for(let[n,s,i={}]of e){let r=n.some((o)=>o.startsWith("mac+"));for(let o of n){let l=o;if(r){let d=o.startsWith("mac+");if(t!==d)continue;if(d)l=o.slice(4)}let[c,h]=kr.#e(l);if(c===null)continue;this.callbacks.getOrInsertComputed(c,wf).push({callback:s,options:i,modifiers:h})}}}static#e(e){let t=null,n=0;for(let s of e.split("+")){if(s=s.trim(),!s)continue;let i=s.toUpperCase(),r=kr[i];if(r){n|=r;continue}if(t!==null){on(`KeyboardManager: multiple keys in shortcut "${e}"`);break}t=i==="SPACE"?" ":s}if(t===null)on(`KeyboardManager: no key found in shortcut "${e}"`);return[t,n]}static#t(e){let t=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(e);if(!t)return null;return t[1]?.toLowerCase()??t[2]}exec(e,t){let n=this.callbacks.get(t.key);if(!n){if(/^[a-z]$/i.test(t.key))return;let h=kr.#t(t.code);if(h===null||h===t.key)return;if(n=this.callbacks.get(h),!n)return}let s=(t.altKey?kr.ALT:0)|(t.ctrlKey?kr.CTRL:0)|(t.metaKey?kr.META:0)|(t.shiftKey?kr.SHIFT:0),i=n.find((h)=>h.modifiers===s);if(!i)return;let{callback:r,options:{bubbles:o=!1,args:l=[],checker:c=null}}=i;if(c&&!c(e,t))return;if(r.bind(e,...l,t)(),!o)si(t)}}class l2{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let e=new Map([["CanvasText",null],["Canvas",null]]);return oM(e),Mt(this,"_colors",e)}convert(e){let t=du(e);if(!window.matchMedia("(forced-colors: active)").matches)return t;for(let[n,s]of this._colors)if(s.every((i,r)=>i===t[r]))return l2._colorsMapping.get(n);return t}getHexCode(e){let t=this._colors.get(e);if(!t)return e;return ct.makeHexColor(...t)}}class dl{#e=new AbortController;#t=null;#n=null;#s=new Map;#i=new Map;#a=null;#r=null;#o=null;#l=null;#c=null;#u=new R7;#h=null;#d=null;#p=null;#g=0;#f=new Set;#m=null;#b=null;#w=new Set;_editorUndoBar=null;#y=!1;#v=!1;#x=!1;#k=null;#A=null;#T=null;#I=null;#j=!1;#C=null;#D=new I7;#R=!1;#q=!1;#B=!1;#M=null;#L=null;#G=null;#O=null;#H=null;#E=Jt.NONE;#S=new Set;#P=null;#U=null;#V=null;#Y=null;#W=null;#K={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#F=[0,0];#$=null;#X=null;#ee=null;#te=null;#N=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let e=dl.prototype,t=(r)=>r.#X.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),n=(r,{target:o})=>{if(o instanceof HTMLInputElement){let{type:l}=o;return l!=="text"&&l!=="number"}return!0},s=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return Mt(this,"_keyboardManager",new kr([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:n}],[["ctrl+z","mac+meta+z"],e.undo,{checker:n}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:n}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:n}],[["Enter"],e.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#X.contains(o)&&!r.isEnterHandled}],[["Space"],e.addNewEditorFromKeyboard,{checker:(r,{target:o})=>!(o instanceof HTMLButtonElement)&&r.#X.contains(document.activeElement)}],[["Escape"],e.unselectAll],[["ArrowLeft"],e.translateSelectedEditors,{args:[-s,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:t}],[["ArrowRight"],e.translateSelectedEditors,{args:[s,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:t}],[["ArrowUp"],e.translateSelectedEditors,{args:[0,-s],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:t}],[["ArrowDown"],e.translateSelectedEditors,{args:[0,s],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:t}]]))}constructor(e,t,n,s,i,r,o,l,c,h,d,m,p,b,v,k){let A=this._signal=this.#e.signal;this.#X=e,this.#ee=t,this.#te=n,this.#o=s,this.#h=i,this.#U=r,this.#W=l,this._eventBus=o;let T={signal:A,...Hb};o.on("editingaction",this.onEditingAction.bind(this),T),o.on("pagechanging",this.onPageChanging.bind(this),T),o.on("scalechanging",this.onScaleChanging.bind(this),T),o.on("rotationchanging",this.onRotationChanging.bind(this),T),o.on("setpreference",this.onSetPreference.bind(this),T),o.on("switchannotationeditorparams",(E)=>this.updateParams(E.type,E.value),T),window.addEventListener("pointerdown",()=>{this.#q=!0},{capture:!0,signal:A}),window.addEventListener("pointerup",()=>{this.#q=!1},{capture:!0,signal:A}),window.addEventListener("beforeunload",this.endCurrentEditing.bind(this),{capture:!0,signal:A}),this.#le(),this.#me(),this.#se(),this.#l=l.annotationStorage,this.#k=l.filterFactory,this.#V=c,this.#I=h||null,this.#y=d,this.#v=m,this.#x=p,this.#H=b||null,this.viewParameters={realScale:nc.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=v||null,this._supportsPinchToZoom=k!==!1,i?.setSidebarUiManager(this)}destroy(){this.#N?.resolve(),this.#N=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#i.values())e.destroy();if(this.#i.clear(),this.#s.clear(),this.#w.clear(),this.#O?.clear(),this.#t=null,this.#S.clear(),this.#u.destroy(),this.#o?.destroy(),this.#h?.destroy(),this.#U?.destroy(),this.#C?.hide(),this.#C=null,this.#G?.destroy(),this.#G=null,this.#n=null,this.#A)clearTimeout(this.#A),this.#A=null;if(this.#$)clearTimeout(this.#$),this.#$=null;this._editorUndoBar?.destroy(),this.#W=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#H}get useNewAltTextFlow(){return this.#v}get useNewAltTextWhenAddingImage(){return this.#x}get hcmFilter(){return Mt(this,"hcmFilter",this.#V?this.#k.addHCMFilter(this.#V.foreground,this.#V.background):"none")}get direction(){return Mt(this,"direction",getComputedStyle(this.#X).direction)}get _highlightColors(){return Mt(this,"_highlightColors",this.#I?new Map(this.#I.split(",").map((e)=>(e=e.split("=").map((t)=>t.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return Mt(this,"highlightColors",null);let t=new Map,n=!!this.#V;for(let[s,i]of e){let r=s.endsWith("_HCM");if(n&&r){t.set(s.replace("_HCM",""),i);continue}if(!n&&!r)t.set(s,i)}return Mt(this,"highlightColors",t)}get highlightColorNames(){return Mt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(e)=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){if(e)this.unselectAll(),this.disableUserSelect(!0);else this.disableUserSelect(!1);this.#p=e}setMainHighlightColorPicker(e){this.#G=e}editAltText(e,t=!1){this.#o?.editAltText(this,e,t)}hasCommentManager(){return!!this.#h}editComment(e,t,n,s){this.#h?.showDialog(this,e,t,n,s)}selectComment(e,t){this.#i.get(e)?.getEditorByUID(t)?.toggleComment(!0,!0)}updateComment(e){this.#h?.updateComment(e.getData())}updatePopupColor(e){this.#h?.updatePopupColor(e)}removeComment(e){this.#h?.removeComments([e.uid])}deleteComment(e,t){let n=()=>{e.comment=t},s=()=>{this._editorUndoBar?.show(n,"comment"),this.toggleComment(null),e.comment=null};this.addCommands({cmd:s,undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){this.#h?.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){return e&&this.#h?.makeCommentColor(e,t)||null}getCommentDialogElement(){return this.#h?.dialogElement||null}async waitForEditorsRendered(e){if(this.#i.has(e-1))return;let{resolve:t,promise:n}=Promise.withResolvers(),s=(i)=>{if(i.pageNumber===e)this._eventBus.off("editorsrendered",s),t()};this._eventBus.on("editorsrendered",s,Hb),await n}getSignature(e){this.#U?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#U}switchToMode(e,t){this._eventBus.on("annotationeditormodechanged",t,{once:!0,signal:this._signal,...Hb}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch("setpreference",{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case"enableNewAltTextWhenAddingImage":this.#x=t;break}}onPageChanging({pageNumber:e}){this.#g=e-1}deletePage(e){for(let t of this.getEditors(e))t.remove();if(this.#i.delete(e),this.#g===e)this.#g=0}focusMainContainer(){this.#X.focus()}findParent(e,t){for(let n of this.#i.values()){let{x:s,y:i,width:r,height:o}=n.div.getBoundingClientRect();if(e>=s&&e<=s+r&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#ee.classList.toggle("noUserSelect",e)}addShouldRescale(e){this.#w.add(e)}removeShouldRescale(e){this.#w.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*nc.PDF_TO_CSS_UNITS;for(let t of this.#w)t.onScaleChanging();this.#p?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#Z({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#ne(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let n of this.#i.values())if(n.hasTextLayer(e))return n;return null}highlightSelection(e="",t=!1){let n=document.getSelection();if(!n||n.isCollapsed)return;let{anchorNode:s,anchorOffset:i,focusNode:r,focusOffset:o}=n,l=n.toString(),h=this.#Z(n).closest(".textLayer"),d=this.getSelectionBoxes(h);if(!d)return;n.empty();let m=this.#ne(h),p=this.#E===Jt.NONE,b=()=>{let v=m?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:d,anchorNode:s,anchorOffset:i,focusNode:r,focusOffset:o,text:l});if(p)this.showAllEditors("highlight",!0,!0);if(t)v?.editComment()};if(p){this.switchToMode(Jt.HIGHLIGHT,b);return}b()}commentSelection(e=""){this.highlightSelection(e,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#ae(){let e=document.getSelection();if(!e||e.isCollapsed)return;let n=this.#Z(e).closest(".textLayer"),s=this.getSelectionBoxes(n);if(!s)return;this.#C||=new j7(this),this.#C.show(n,s,this.direction==="ltr")}getAndRemoveDataFromAnnotationStorage(e){if(!this.#l)return null;let t=`pdfjs_internal_editor_${e}`,n=this.#l.getRawValue(t);if(n)this.#l.remove(t);return n}addToAnnotationStorage(e){if(!e.isEmpty()&&this.#l&&!this.#l.has(e.id))this.#l.setValue(e.id,e)}a11yAlert(e,t=null){let n=this.#te;if(!n)return;if(n.setAttribute("data-l10n-id",e),t)n.setAttribute("data-l10n-args",JSON.stringify(t));else n.removeAttribute("data-l10n-args")}#oe(){let e=document.getSelection();if(!e||e.isCollapsed){if(this.#P)this.#C?.hide(),this.#P=null,this.#_({hasSelectedText:!1});return}let{anchorNode:t}=e;if(t===this.#P)return;let s=this.#Z(e).closest(".textLayer");if(!s){if(this.#P)this.#C?.hide(),this.#P=null,this.#_({hasSelectedText:!1});return}if(this.#C?.hide(),this.#P=t,this.#_({hasSelectedText:!0}),this.#E!==Jt.HIGHLIGHT&&this.#E!==Jt.NONE)return;if(this.#E===Jt.HIGHLIGHT)this.showAllEditors("highlight",!0,!0);if(this.#j=this.isShiftKeyDown,!this.isShiftKeyDown){let i=this.#E===Jt.HIGHLIGHT?this.#ne(s):null;if(i?.toggleDrawing(),this.#q){let r=new AbortController,o=this.combinedSignal(r),l=(c)=>{if(c.type==="pointerup"&&c.button!==0)return;if(r.abort(),i?.toggleDrawing(!0),c.type==="pointerup")this.#Q("main_toolbar")};window.addEventListener("pointerup",l,{signal:o}),window.addEventListener("blur",l,{signal:o})}else i?.toggleDrawing(!0),this.#Q("main_toolbar")}}#Q(e=""){if(this.#E===Jt.HIGHLIGHT)this.highlightSelection(e);else if(this.#y)this.#ae()}#le(){document.addEventListener("selectionchange",this.#oe.bind(this),{signal:this._signal})}#ce(){if(this.#T)return;this.#T=new AbortController;let e=this.combinedSignal(this.#T);window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})}#fe(){this.#T?.abort(),this.#T=null}blur(){if(this.isShiftKeyDown=!1,this.#j)this.#j=!1,this.#Q("main_toolbar");if(!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#S)if(t.div.contains(e)){this.#L=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#L)return;let[e,t]=this.#L;this.#L=null,t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#se(){if(this.#M)return;this.#M=new AbortController;let e=this.combinedSignal(this.#M);window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})}#he(){this.#M?.abort(),this.#M=null}#ue(){if(this.#d)return;this.#d=new AbortController;let e=this.combinedSignal(this.#d);document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})}#de(){this.#d?.abort(),this.#d=null}#me(){let e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})}addEditListeners(){this.#se(),this.setEditingState(!0)}removeEditListeners(){this.#he(),this.setEditingState(!1)}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#b)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#b)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let n of this.#S){let s=n.serialize(!0);if(s)t.push(s)}if(t.length===0)return;e.clipboardData.setData("application/pdfjs",JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let i of t.items)for(let r of this.#b)if(r.isHandlingMimeForPasting(i.type)){r.paste(i,this.currentLayer);return}let n=t.getData("application/pdfjs");if(!n)return;try{n=JSON.parse(n)}catch(i){on(`paste: "${i.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let s=this.currentLayer;try{let i=[];for(let l of n){let c=await s.deserialize(l);if(!c)return;i.push(c)}let r=()=>{for(let l of i)this.#ie(l);this.#re(i)},o=()=>{for(let l of i)l.remove()};this.addCommands({cmd:r,undo:o,mustExec:!0})}catch(i){on(`paste: "${i.message}".`)}}keydown(e){if(!this.isShiftKeyDown&&e.key==="Shift")this.isShiftKeyDown=!0;if(this.#E!==Jt.NONE&&!this.isEditorHandlingKeyboard)dl._keyboardManager.exec(this,e)}keyup(e){if(this.isShiftKeyDown&&e.key==="Shift"){if(this.isShiftKeyDown=!1,this.#j)this.#j=!1,this.#Q("main_toolbar")}}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}updatePageIndex(e,t){for(let s of this.#r.get(e)||[])s.pageIndex=t;let n=this.#a.get(e);if(n)if(n.pageIndex=t,this.#i.set(t,n),this.#R)n.enable();else n.disable()}startUpdatePages(){this.#a=new Map(this.#i),this.#i.clear();let e=this.#r=new Map,t=(n)=>{e.getOrInsertComputed(n.pageIndex,wf).push(n)};for(let n of this.#s.values())t(n);for(let[n,s]of this.#l)if(n.startsWith("pdfjs_internal_editor_")&&!this.#s.has(n)&&Number.isInteger(s?.pageIndex))t(s)}endUpdatePages(){this.#a=null,this.#r=null}clonePage(e,t){for(let n of this.getEditors(e)){let s=n.serialize(n.mode!==Jt.HIGHLIGHT);if(!s)continue;s.pageIndex=t,s.id=this.getId(),s.isClone=!0,delete s.popupRef,this.#l.setValue(s.id,s)}}findClonesForPage(e){let t=[],{pageIndex:n}=e;for(let[s,i]of this.#l)if(i.pageIndex===n&&i.isClone)this.#l.remove(s),t.push(e.deserialize(i).then((r)=>{if(r)r.isClone=!0,e.addOrRebuild(r)}));return Promise.all(t)}#_(e){if(Object.entries(e).some(([n,s])=>this.#K[n]!==s)){if(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(this.#K,e)}),this.#E===Jt.HIGHLIGHT&&e.hasSelectedEditor===!1)this.#z([[Tn.HIGHLIGHT_FREE,!0]])}}#z(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})}setEditingState(e){if(e)this.#ce(),this.#ue(),this.#_({isEditing:this.#E!==Jt.NONE,isEmpty:this.#J(),hasSomethingToUndo:this.#u.hasSomethingToUndo(),hasSomethingToRedo:this.#u.hasSomethingToRedo(),hasSelectedEditor:!1});else this.#fe(),this.#de(),this.#_({isEditing:!1}),this.disableUserSelect(!1)}registerEditorTypes(e){if(this.#b)return;this.#b=e;for(let t of this.#b)this.#z(t.defaultPropertiesToUpdate)}getId(){return this.#D.id}get currentLayer(){return this.#i.get(this.#g)}getLayer(e){return this.#i.get(e)}get currentPageIndex(){return this.#g}addLayer(e){if(this.#i.set(e.pageIndex,e),this.#R)e.enable();else e.disable()}removeLayer(e){this.#i.delete(e.pageIndex)}async updateMode(e,t=null,n=!1,s=!1,i=!1,r=!1){if(this.#E===e)return;if(this.#N){if(await this.#N.promise,!this.#N)return}if(this.#N=Promise.withResolvers(),this.#p?.commitOrRemove(),this.#E===Jt.POPUP)this.#h?.hideSidebar();if(this.#h?.destroyPopup(),this.#E=e,e===Jt.NONE){this.setEditingState(!1),this.#ge();for(let o of this.#s.values())o.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#N.resolve();return}for(let o of this.#s.values())o.addStandaloneCommentButton();if(e===Jt.SIGNATURE)await this.#U?.loadSignatures();if(n)zn.clearPointerType();this.setEditingState(!0),await this.#pe(),this.unselectAll();for(let o of this.#i.values())o.updateMode(e);if(e===Jt.POPUP){this.#n||=await this.#W.getAnnotationsByType(new Set(this.#b.map((c)=>c._editorType)));let o=new Set,l=[];for(let c of this.#s.values()){let{annotationElementId:h,hasComment:d,deleted:m}=c;if(h)o.add(h);if(d&&!m)l.push(c.getData())}for(let c of this.#n){let{id:h,popupRef:d,contentsObj:m}=c;if(d&&m?.str&&!o.has(h)&&!this.#f.has(h))l.push(c)}this.#h?.showSidebar(l)}if(!t){if(s)this.addNewEditorFromKeyboard();this.#N.resolve();return}for(let o of this.#s.values())if(o.uid===t)if(this.setSelected(o),r)o.editComment();else if(i)o.enterInEditMode();else o.focus();else o.unselect();this.#N.resolve()}addNewEditorFromKeyboard(){if(this.currentLayer.canCreateNewEmptyEditor())this.currentLayer.addNewEditor()}updateToolbar(e){if(e.mode===this.#E)return;this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,t){if(!this.#b)return;switch(e){case Tn.CREATE:this.currentLayer.addNewEditor(t);return;case Tn.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#Y||=new Map).set(e,t),this.showAllEditors("highlight",t);break}if(this.hasSelection)for(let n of this.#S)n.updateParams(e,t);else for(let n of this.#b)n.updateDefaultParams(e,t)}showAllEditors(e,t,n=!1){for(let i of this.#s.values())if(i.editorType===e)i.show(t);if((this.#Y?.get(Tn.HIGHLIGHT_SHOW_ALL)??!0)!==t)this.#z([[Tn.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#B===e)return;this.#B=e;for(let t of this.#i.values()){if(e)t.disableClick();else t.enableClick();t.div.classList.toggle("waiting",e)}}async#pe(){if(!this.#R){this.#R=!0;let e=[];for(let t of this.#i.values())e.push(t.enable());await Promise.all(e);for(let t of this.#s.values())t.enable()}}#ge(){if(this.unselectAll(),this.#R){this.#R=!1;for(let e of this.#i.values())e.disable();for(let e of this.#s.values())e.disable()}}*getEditors(e){for(let t of this.#s.values())if(t.pageIndex===e)yield t}getEditor(e){return this.#s.get(e)}addEditor(e){this.#s.set(e.id,e)}removeEditor(e){if(e.div.contains(document.activeElement)){if(this.#A)clearTimeout(this.#A);this.#A=setTimeout(()=>{this.focusMainContainer(),this.#A=null},0)}if(this.#s.delete(e.id),e.annotationElementId)this.#O?.delete(e.annotationElementId);if(this.unselect(e),!e.annotationElementId||!this.#f.has(e.annotationElementId))this.#l?.remove(e.id)}addDeletedAnnotationElement(e){this.#f.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#f.has(e)}removeDeletedAnnotationElement(e){this.#f.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#ie(e){let t=this.#i.get(e.pageIndex);if(t)t.addOrRebuild(e);else this.addEditor(e),this.addToAnnotationStorage(e)}setActiveEditor(e){if(this.#t===e)return;if(this.#t=e,e)this.#z(e.propertiesToUpdate)}get#be(){let e=null;for(e of this.#S);return e}updateUI(e){if(this.#be===e)this.#z(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#z(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#S.has(e)){this.#S.delete(e),e.unselect(),this.#_({hasSelectedEditor:this.hasSelection});return}this.#S.add(e),e.select(),this.#z(e.propertiesToUpdate),this.#_({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.uid}),this.#p?.commitOrRemove();for(let t of this.#S)if(t!==e)t.unselect();this.#h?.destroyPopup(),this.#S.clear(),this.#S.add(e),e.select(),this.#z(e.propertiesToUpdate),this.#_({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#S.values().next().value}unselect(e){e.unselect(),this.#S.delete(e),this.#_({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#S.size!==0}get isEnterHandled(){return this.#S.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#u.undo(),this.#_({hasSomethingToUndo:this.#u.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#J()}),this._editorUndoBar?.hide()}redo(){this.#u.redo(),this.#_({hasSomethingToUndo:!0,hasSomethingToRedo:this.#u.hasSomethingToRedo(),isEmpty:this.#J()})}addCommands(e){this.#u.add(e),this.#_({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#J()})}cleanUndoStack(e){this.#u.cleanType(e)}#J(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(let e of this.#s.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#S],n=()=>{this._editorUndoBar?.show(s,t.length===1?t[0].editorType:t.length);for(let i of t)i.remove()},s=()=>{for(let i of t)this.#ie(i)};this.addCommands({cmd:n,undo:s,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#re(e){for(let t of this.#S)t.unselect();this.#S.clear();for(let t of e){if(t.isEmpty())continue;this.#S.add(t),t.select()}this.#_({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#S)e.commit();this.#re(this.#s.values())}unselectAll(){if(this.#t){if(this.#t.commitOrRemove(),this.#E!==Jt.NONE)return}if(this.#p?.commitOrRemove())return;if(this.#h?.destroyPopup(),!this.hasSelection)return;for(let e of this.#S)e.unselect();this.#S.clear(),this.#_({hasSelectedEditor:!1})}translateSelectedEditors(e,t,n=!1){if(!n)this.commitOrRemove();if(!this.hasSelection)return;this.#F[0]+=e,this.#F[1]+=t;let[s,i]=this.#F,r=[...this.#S],o=1000;if(this.#$)clearTimeout(this.#$);this.#$=setTimeout(()=>{this.#$=null,this.#F[0]=this.#F[1]=0,this.addCommands({cmd:()=>{for(let l of r)if(this.#s.has(l.id))l.translateInPage(s,i),l.translationDone()},undo:()=>{for(let l of r)if(this.#s.has(l.id))l.translateInPage(-s,-i),l.translationDone()},mustExec:!1})},o);for(let l of r)l.translateInPage(e,t),l.translationDone()}setUpDragSession(){if(!this.hasSelection)return;this.disableUserSelect(!0),this.#m=new Map;for(let e of this.#S)this.#m.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}endDragSession(){if(!this.#m)return!1;this.disableUserSelect(!1);let e=this.#m;this.#m=null;let t=!1;for(let[{x:s,y:i,pageIndex:r},o]of e)o.newX=s,o.newY=i,o.newPageIndex=r,t||=s!==o.savedX||i!==o.savedY||r!==o.savedPageIndex;if(!t)return!1;let n=(s,i,r,o)=>{if(this.#s.has(s.id)){let l=this.#i.get(o);if(l)s._setParentAndPosition(l,i,r);else s.pageIndex=o,s.x=i,s.y=r}};return this.addCommands({cmd:()=>{for(let[s,{newX:i,newY:r,newPageIndex:o}]of e)n(s,i,r,o)},undo:()=>{for(let[s,{savedX:i,savedY:r,savedPageIndex:o}]of e)n(s,i,r,o)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(!this.#m)return;for(let n of this.#m.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);if(t)t.changeParent(e),t.addOrRebuild(e);else this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild()}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#S.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#E}isEditingMode(){return this.#E!==Jt.NONE}get imageManager(){return Mt(this,"imageManager",new o2)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let c=0,h=t.rangeCount;c<h;c++)if(!e.contains(t.getRangeAt(c).commonAncestorContainer))return null;let{x:n,y:s,width:i,height:r}=e.getBoundingClientRect(),o;switch(e.getAttribute("data-main-rotation")){case"90":o=(c,h,d,m)=>({x:(h-s)/r,y:1-(c+d-n)/i,width:m/r,height:d/i});break;case"180":o=(c,h,d,m)=>({x:1-(c+d-n)/i,y:1-(h+m-s)/r,width:d/i,height:m/r});break;case"270":o=(c,h,d,m)=>({x:1-(h+m-s)/r,y:(c-n)/i,width:m/r,height:d/i});break;default:o=(c,h,d,m)=>({x:(c-n)/i,y:(h-s)/r,width:d/i,height:m/r});break}let l=[];for(let c=0,h=t.rangeCount;c<h;c++){let d=t.getRangeAt(c);if(d.collapsed)continue;for(let{x:m,y:p,width:b,height:v}of d.getClientRects()){if(b===0||v===0)continue;l.push(o(m,p,b,v))}}return l.length===0?null:l}addChangedExistingAnnotation({annotationElementId:e,id:t}){(this.#c||=new Map).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){this.#c?.delete(e)}renderAnnotationElement(e){let t=this.#c?.get(e.data.id);if(!t)return;let n=this.#l.getRawValue(t);if(!n)return;if(this.#E===Jt.NONE&&!n.hasBeenModified)return;n.renderAnnotationElement(e)}setMissingCanvas(e,t,n){let s=this.#O?.get(e);if(!s)return;s.setCanvas(t,n),this.#O.delete(e)}addMissingCanvas(e,t){(this.#O||=new Map).set(e,t)}}class Ga{#e=null;#t=!1;#n=null;#s=null;#i=null;#a=null;#r=!1;#o=null;#l=null;#c=null;#u=null;#h=!1;static#d=null;static _l10n=null;constructor(e){this.#l=e,this.#h=e._uiManager.useNewAltTextFlow,Ga.#d||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(e){Ga._l10n??=e}async render(){let e=this.#n=document.createElement("button");e.className="altText",e.tabIndex="0";let t=this.#s=document.createElement("span");if(e.append(t),this.#h)e.classList.add("new"),e.setAttribute("data-l10n-id",Ga.#d.missing),t.setAttribute("data-l10n-id",Ga.#d["missing-label"]);else e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label");let n=this.#l._uiManager._signal;e.addEventListener("contextmenu",ca,{signal:n}),e.addEventListener("pointerdown",(i)=>i.stopPropagation(),{signal:n});let s=(i)=>{if(i.preventDefault(),this.#l._uiManager.editAltText(this.#l),this.#h)this.#l._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#p}})};return e.addEventListener("click",s,{capture:!0,signal:n}),e.addEventListener("keydown",(i)=>{if(i.target===e&&i.key==="Enter")this.#r=!0,s(i)},{signal:n}),await this.#g(),e}get#p(){return this.#e&&"added"||this.#e===null&&this.guessedText&&"review"||"missing"}finish(){if(!this.#n)return;this.#n.focus({focusVisible:this.#r}),this.#r=!1}isEmpty(){return this.#h?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#h?this.#e!==null||!!this.#c:this.isEmpty()}get guessedText(){return this.#c}async setGuessedText(e){if(this.#e!==null)return;this.#c=e,this.#u=await Ga._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e}),this.#g()}toggleAltTextBadge(e=!1){if(!this.#h||this.#e){this.#o?.remove(),this.#o=null;return}if(!this.#o){let t=this.#o=document.createElement("div");t.className="noAltTextBadge",this.#l.div.append(t)}this.#o.classList.toggle("hidden",!e)}serialize(e){let t=this.#e;if(!e&&this.#c===t)t=this.#u;return{altText:t,decorative:this.#t,guessedText:this.#c,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:s,cancel:i=!1}){if(n)this.#c=n,this.#u=s;if(this.#e===e&&this.#t===t)return;if(!i)this.#e=e,this.#t=t;this.#g()}toggle(e=!1){if(!this.#n)return;if(!e&&this.#a)clearTimeout(this.#a),this.#a=null;this.#n.disabled=!e}shown(){this.#l._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#s=null,this.#i=null,this.#o?.remove(),this.#o=null}async#g(){let e=this.#n;if(!e)return;if(this.#h){if(e.classList.toggle("done",!!this.#e),e.setAttribute("data-l10n-id",Ga.#d[this.#p]),this.#s?.setAttribute("data-l10n-id",Ga.#d[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){e.classList.remove("done"),this.#i?.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=this.#i;if(!t){this.#i=t=document.createElement("span"),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${this.#l.id}`;let s=100,i=this.#l._uiManager._signal;i.addEventListener("abort",()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),e.addEventListener("mouseenter",()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add("show"),this.#l._reportTelemetry({action:"alt_text_tooltip"})},s)},{signal:i}),e.addEventListener("mouseleave",()=>{if(this.#a)clearTimeout(this.#a),this.#a=null;this.#i?.classList.remove("show")},{signal:i})}if(this.#t)t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else t.removeAttribute("data-l10n-id"),t.textContent=this.#e;if(!t.parentNode)e.append(t);this.#l.getElementForAltText()?.setAttribute("aria-describedby",t.id)}}class Zh{#e=null;#t=null;#n=!1;#s=null;#i=null;#a=null;#r=null;#o=null;#l=!1;#c=null;constructor(e){this.#s=e}renderForToolbar(){let e=this.#t=document.createElement("button");return e.className="comment",this.#u(e,!1)}renderForStandalone(){let e=this.#e=document.createElement("button");e.className="annotationCommentButton";let t=this.#s.commentButtonPosition;if(t){let{style:n}=e;n.insetInlineEnd=`calc(${100*(this.#s._uiManager.direction==="ltr"?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;let s=this.#s.commentButtonColor;if(s)n.backgroundColor=s}return this.#u(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#s.commentButtonColor;if(e)this.#e.style.backgroundColor=e;this.#s._uiManager.updatePopupColor(this.#s)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#s.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#c)return this.#c;if(!this.#e)return null;let{x:e,y:t,height:n}=this.#e.getBoundingClientRect(),{x:s,y:i,width:r,height:o}=this.#s.parent.boundingClientRect;return[(e-s)/r,(t+n-i)/o]}set commentPopupPositionInLayer(e){this.#c=e}hasDefaultPopupPosition(){return this.#c===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:t}){if(!this.#e)return;this.#e.classList.toggle("selected",e),this.#e.ariaExpanded=t}#u(e,t){if(!this.#s._uiManager.hasCommentManager())return null;if(e.tabIndex="0",e.ariaHasPopup="dialog",t)e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button");else e.ariaControlsElements=[this.#s._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button");let n=this.#s._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;if(e.addEventListener("contextmenu",ca,{signal:n}),t)e.addEventListener("focusin",(i)=>{this.#s._focusEventsAllowed=!1,si(i)},{capture:!0,signal:n}),e.addEventListener("focusout",(i)=>{this.#s._focusEventsAllowed=!0,si(i)},{capture:!0,signal:n});e.addEventListener("pointerdown",(i)=>i.stopPropagation(),{signal:n});let s=(i)=>{if(i.preventDefault(),e===this.#t)this.edit();else this.#s.toggleComment(!0)};return e.addEventListener("click",s,{capture:!0,signal:n}),e.addEventListener("keydown",(i)=>{if(i.target===e&&i.key==="Enter")this.#n=!0,s(i)},{signal:n}),e.addEventListener("pointerenter",()=>{this.#s.toggleComment(!1,!0)},{signal:n}),e.addEventListener("pointerleave",()=>{this.#s.toggleComment(!1,!1)},{signal:n}),e}edit(e){let t=this.commentPopupPositionInLayer,n,s;if(t)[n,s]=t;else{[n,s]=this.#s.commentButtonPosition;let{width:h,height:d,x:m,y:p}=this.#s;n=m+n*h,s=p+s*d}let i=this.#s.parent.boundingClientRect,{x:r,y:o,width:l,height:c}=i;this.#s._uiManager.editComment(this.#s,r+n*l,o+s*c,{...e,parentDimensions:i})}finish(){if(!this.#t)return;this.#t.focus({focusVisible:this.#n}),this.#n=!1}isDeleted(){return this.#l||this.#r===""}isEmpty(){return this.#r===null}hasBeenEdited(){return this.isDeleted()||this.#r!==this.#i}serialize(){return this.data}get data(){return{text:this.#r,richText:this.#a,date:this.#o,deleted:this.isDeleted()}}set data(e){if(e!==this.#r)this.#a=null;if(e===null){this.#r="",this.#l=!0;return}this.#r=e,this.#o=new Date,this.#l=!1}restoreData({text:e,richText:t,date:n}){this.#r=e,this.#a=t,this.#o=n,this.#l=!1}setInitialText(e,t=null){this.#i=e,this.data=e,this.#o=null,this.#a=t}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#r="",this.#a=null,this.#o=null,this.#s=null,this.#n=!1,this.#l=!1}}function Q8(e){e.preventDefault()}var J8=0.0001;function Ub(e){if(e.cancelable)return si(e),!0;return e.stopPropagation(),!1}class c2{#e;#t=!1;#n=null;#s;#i;#a;#r;#o;#l=!1;#c=null;#u;#h=new Set;#d=null;#p;#g=null;#f=0;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:s=null,onPinching:i=null,onPinchEnd:r=null,onPanning:o=null,signal:l}){this.#e=e,this.#n=n,this.#s=t,this.#i=s,this.#a=i,this.#r=r,this.#o=o,this.#p=new AbortController,this.#u=AbortSignal.any([l,this.#p.signal]),e.addEventListener("touchstart",this.#m.bind(this),{passive:!1,signal:this.#u})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/fa.pixelRatio}get MIN_TOUCH_DISTANCE_TO_SCALE(){return 4/fa.pixelRatio}#m(e){if(this.#s?.())return;this.#w(e);let t=this.#h;for(let{identifier:n}of e.changedTouches)t.add(n);if(t.size===1){this.#b();return}if(!this.#g){this.#g=new AbortController;let n=AbortSignal.any([this.#u,this.#g.signal]),s=this.#e,i={signal:n,capture:!1,passive:!1};s.addEventListener("touchmove",this.#x.bind(this),i);let r=this.#k.bind(this);s.addEventListener("touchend",r,i),s.addEventListener("touchcancel",r,i),i.capture=!0,s.addEventListener("pointerdown",si,i),s.addEventListener("pointermove",si,i),s.addEventListener("pointercancel",Q8,i),s.addEventListener("pointerup",Q8,i),this.#i?.()}this.#l=Ub(e),this.#v(e)}#b(){if(this.#c)return;let e=this.#c=new AbortController,t=AbortSignal.any([this.#u,e.signal]),n=this.#e,s={capture:!0,signal:t,passive:!1},i=(r)=>{if(r.pointerType==="touch")this.#c?.abort(),this.#c=null};n.addEventListener("pointerdown",(r)=>{if(r.pointerType==="touch")si(r),i(r)},s),n.addEventListener("pointerup",i,s),n.addEventListener("pointercancel",i,s)}#w(e){let t=this.#h;if(t.size===0)return;let n=this.#h=new Set;for(let{identifier:s}of e.touches)if(t.has(s))n.add(s)}#y(e){let t=this.#h,n=[];for(let s of e.touches)if(t.has(s.identifier))n.push(s);return n}#v(e){let t=this.#y(e);if(t.length!==2||this.#n?.()){this.#d=null;return}let[n,s]=t;this.#d={touch0X:n.screenX,touch0Y:n.screenY,touch1X:s.screenX,touch1Y:s.screenY,panX:(n.clientX+s.clientX)/2,panY:(n.clientY+s.clientY)/2,screenPanX:(n.screenX+s.screenX)/2,screenPanY:(n.screenY+s.screenY)/2}}#x(e){if(!this.#d)return;let t=this.#y(e);if(t.length!==2)return;let n=this.#l;if(this.#l=Ub(e),!this.#l)return;if(!n){this.#v(e);return}let[s,i]=t,{screenX:r,screenY:o}=s,{screenX:l,screenY:c}=i,h=this.#d,{touch0X:d,touch0Y:m,touch1X:p,touch1Y:b,panX:v,panY:k}=h,A=p-d,T=b-m,E=l-r,I=c-o,_=(s.clientX+i.clientX)/2,q=(s.clientY+i.clientY)/2;h.panX=_,h.panY=q;let P=_-v,N=q-k,H=(r+l)/2,V=(o+c)/2,U=Math.hypot(H-h.screenPanX,V-h.screenPanY);h.screenPanX=H,h.screenPanY=V;let W=Math.hypot(E,I),ce=Math.hypot(A,T),ue=this.#t?this.MIN_TOUCH_DISTANCE_TO_SCALE:this.MIN_TOUCH_DISTANCE_TO_PINCH+2*U;if(W<J8||ce<J8||Math.abs(ce-W)<=ue){if(P||N)this.#o?.(P,N);return}h.touch0X=r,h.touch0Y=o,h.touch1X=l,h.touch1Y=c;let oe=Math.sign(W-ce);if(!this.#t){if(this.#t=!0,this.#f=oe,P||N)this.#o?.(P,N);return}if(this.#f){let ae=this.#f;if(this.#f=0,oe!==ae&&Math.abs(W-ce)<=2*U){if(this.#t=!1,P||N)this.#o?.(P,N);return}}this.#a?.([v,k],ce,W,P,N)}#k(e){if(this.#w(e),this.#h.size>=2){this.#v(e);return}let t=!!this.#d;if(this.#A(),this.#h.size===1)this.#b();if(t)Ub(e)}#A(){if(this.#d=null,this.#t=!1,this.#f=0,this.#l=!1,this.#g)this.#g.abort(),this.#g=null,this.#r?.()}destroy(){this.#A(),this.#h.clear(),this.#p?.abort(),this.#p=null,this.#c?.abort(),this.#c=null}}class _t{#e=null;#t=null;#n=null;#s=null;#i=null;#a=!1;#r=null;#o="";#l=null;#c=null;#u=null;#h=null;#d=null;#p="";#g=!1;#f=null;#m=!1;#b=!1;#w=!1;#y=null;#v=0;#x=0;#k=null;#A=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#T=!1;#I=_t._zIndex++;static _borderLineWidth=-1;static _colorManager=new l2;static _zIndex=1;static _telemetryTimeout=1000;static get _resizerKeyboardManager(){let e=_t.prototype._resizeWithKeyboard,{TRANSLATE_SMALL:t,TRANSLATE_BIG:n}=dl;return Mt(this,"_resizerKeyboardManager",new kr([[["ArrowLeft"],e,{args:[-t,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-n,0]}],[["ArrowRight"],e,{args:[t,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[n,0]}],[["ArrowUp"],e,{args:[0,-t]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-n]}],[["ArrowDown"],e,{args:[0,t]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,n]}],[["Escape"],_t.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;let{rotation:t,rawDims:{pageWidth:n,pageHeight:s,pageX:i,pageY:r}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,s],this.pageTranslation=[i,r];let[o,l]=this.parentDimensions;this.x=e.x/o,this.y=e.y/l,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Mt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){let t=new D7({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(e,t){if(_t._l10n??=e,_t._l10nAlert??=Object.freeze({highlight:"pdfjs-editor-highlight-added-alert",freetext:"pdfjs-editor-freetext-added-alert",ink:"pdfjs-editor-ink-added-alert",stamp:"pdfjs-editor-stamp-added-alert",signature:"pdfjs-editor-signature-added-alert"}),_t._l10nResizer??=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),_t._borderLineWidth!==-1)return;let n=getComputedStyle(document.documentElement);_t._borderLineWidth=parseFloat(n.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){Dn("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#T}set _isDraggable(e){this.#T=e,this.div?.classList.toggle("draggable",e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#I}setParent(e){if(e!==null)this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions;else this.#F(),this.#h?.remove(),this.#h=null;this.parent=e}focusin(e){if(!this._focusEventsAllowed)return;if(!this.#g)this.parent.setSelected(this);else this.#g=!1}focusout(e){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;if(e.relatedTarget?.closest(`#${this.id}`))return;if(e.preventDefault(),!this.parent?.isMultipleSelection)this.commitOrRemove()}commitOrRemove(){if(this.isEmpty())this.remove();else this.commit()}commit(){if(!this.isInEditMode())return;this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,s){let[i,r]=this.parentDimensions;[n,s]=this.screenToPageTranslation(n,s),this.x=(e+n)/i,this.y=(t+s)/r,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}let[n,s]=this.parentDimensions;this.setAt(e*n,t*s,this.width*n,this.height*s),this._onTranslated()}#j([e,t],n,s){[n,s]=this.screenToPageTranslation(n,s),this.x+=n/e,this.y+=s/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#j(this.parentDimensions,e,t)}translateInPage(e,t){this.#f||=[this.x,this.y,this.width,this.height],this.#j(this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){this.#f||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[s,i]}=this;if(this.x+=e/s,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:d,y:m}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,d,m))this.x-=Math.floor(this.x),this.y-=Math.floor(this.y)}let{x:r,y:o}=this,[l,c]=this.getBaseTranslation();r+=l,o+=c;let{style:h}=n;h.left=`${(100*r).toFixed(2)}%`,h.top=`${(100*o).toFixed(2)}%`,this._onTranslating(r,o)}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#f&&(this.#f[0]!==this.x||this.#f[1]!==this.y)}get _hasBeenResized(){return!!this.#f&&(this.#f[2]!==this.width||this.#f[3]!==this.height)}getBaseTranslation(){let[e,t]=this.parentDimensions,{_borderLineWidth:n}=_t,s=n/e,i=n/t;switch(this.rotation){case 90:return[-s,i];case 180:return[s,i];case 270:return[s,-i];default:return[-s,-i]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,s]}=this,{x:i,y:r,width:o,height:l}=this;if(o*=n,l*=s,i*=n,r*=s,this._mustFixPosition)switch(e){case 0:i=bs(i,0,n-o),r=bs(r,0,s-l);break;case 90:i=bs(i,0,n-l),r=bs(r,o,s);break;case 180:i=bs(i,o,n),r=bs(r,l,s);break;case 270:i=bs(i,l,n),r=bs(r,0,s-o);break}this.x=i/=n,this.y=r/=s;let[c,h]=this.getBaseTranslation();i+=c,r+=h,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#C(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(e,t){return _t.#C(e,t,this.parentRotation)}pageTranslationToScreen(e,t){return _t.#C(e,t,360-this.parentRotation)}#D(e){switch(e){case 90:{let[t,n]=this.pageDimensions;return[0,-t/n,n/t,0]}case 180:return[-1,0,0,-1];case 270:{let[t,n]=this.pageDimensions;return[0,t/n,-n/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){let{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#R(){if(this.#l)return;this.#l=document.createElement("div"),this.#l.classList.add("resizers");let e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],t=this._uiManager._signal;for(let n of e){let s=document.createElement("div");this.#l.append(s),s.classList.add("resizer",n),s.setAttribute("data-resizer-name",n),s.addEventListener("pointerdown",this.#q.bind(this,n),{signal:t}),s.addEventListener("contextmenu",ca,{signal:t}),s.tabIndex=-1}this.div.prepend(this.#l)}#q(e,t){t.preventDefault();let{isMac:n}=Wn.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let s=this._isDraggable;this._isDraggable=!1,this.#c=[t.screenX,t.screenY];let i=new AbortController,r=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#L.bind(this,e),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",si,{passive:!1,signal:r}),window.addEventListener("contextmenu",ca,{signal:r}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,l=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=s,this.parent.div.style.cursor=o,this.div.style.cursor=l,this.#M()};window.addEventListener("pointerup",c,{signal:r}),window.addEventListener("blur",c,{signal:r})}#B(e,t,n,s){this.width=n,this.height=s,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#M(){if(!this.#u)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:s}=this.#u;this.#u=null;let i=this.x,r=this.y,o=this.width,l=this.height;if(i===e&&r===t&&o===n&&l===s)return;this.addCommands({cmd:this.#B.bind(this,i,r,o,l),undo:this.#B.bind(this,e,t,n,s),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#L(e,t){let[n,s]=this.parentDimensions,i=this.x,r=this.y,o=this.width,l=this.height,c=_t.MIN_SIZE/n,h=_t.MIN_SIZE/s,d=this.#D(this.rotation),m=(ae,te)=>[d[0]*ae+d[2]*te,d[1]*ae+d[3]*te],p=this.#D(360-this.rotation),b=(ae,te)=>[p[0]*ae+p[2]*te,p[1]*ae+p[3]*te],v,k,A=!1,T=!1;switch(e){case"topLeft":A=!0,v=(ae,te)=>[0,0],k=(ae,te)=>[ae,te];break;case"topMiddle":v=(ae,te)=>[ae/2,0],k=(ae,te)=>[ae/2,te];break;case"topRight":A=!0,v=(ae,te)=>[ae,0],k=(ae,te)=>[0,te];break;case"middleRight":T=!0,v=(ae,te)=>[ae,te/2],k=(ae,te)=>[0,te/2];break;case"bottomRight":A=!0,v=(ae,te)=>[ae,te],k=(ae,te)=>[0,0];break;case"bottomMiddle":v=(ae,te)=>[ae/2,te],k=(ae,te)=>[ae/2,0];break;case"bottomLeft":A=!0,v=(ae,te)=>[0,te],k=(ae,te)=>[ae,0];break;case"middleLeft":T=!0,v=(ae,te)=>[0,te/2],k=(ae,te)=>[ae,te/2];break}let E=v(o,l),I=k(o,l),_=m(...I),q=_t._round(i+_[0]),P=_t._round(r+_[1]),N=1,H=1,V,U;if(!t.fromKeyboard){let{screenX:ae,screenY:te}=t,[me,he]=this.#c;[V,U]=this.screenToPageTranslation(ae-me,te-he),this.#c[0]=ae,this.#c[1]=te}else({deltaX:V,deltaY:U}=t);if([V,U]=b(V/n,U/s),A){let ae=Math.hypot(o,l);N=H=Math.max(Math.min(Math.hypot(I[0]-E[0]-V,I[1]-E[1]-U)/ae,1/o,1/l),c/o,h/l)}else if(T)N=bs(Math.abs(I[0]-E[0]-V),c,1)/o;else H=bs(Math.abs(I[1]-E[1]-U),h,1)/l;let W=_t._round(o*N),ce=_t._round(l*H);_=m(...k(W,ce));let ue=q-_[0],oe=P-_[1];this.#f||=[this.x,this.y,this.width,this.height],this.width=W,this.height=ce,this.x=ue,this.y=oe,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#b)return this._editToolbar;this._editToolbar=new nu(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[t,n]of e)await this._editToolbar.addButton(t,n);if(!this.hasComment)this._editToolbar.addButton("comment",this.addCommentButton());return this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton("comment")}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#n?.destroy()}addContainer(e){let t=this._editToolbar?.div;if(t)t.before(e);else this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){if(!this.#n){if(Ga.initialize(_t._l10n),this.#n=new Ga(this),this.#e)this.#n.data=this.#e,this.#e=null}return this.#n}get altTextData(){return this.#n?.data}set altTextData(e){if(!this.#n)return;this.#n.data=e}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}focusCommentButton(){this.#s?.focusButton()}addCommentButton(){return this.canAddComment?this.#s||=new Zh(this):null}addStandaloneCommentButton(){if(!this._uiManager.hasCommentManager())return;if(this.#i){if(this._uiManager.isEditingMode())this.#i.classList.remove("hidden");return}if(!this.hasComment)return;this.#i=this.#s.renderForStandalone(),this.div.append(this.#i)}removeStandaloneCommentButton(){this.#s.removeStandaloneCommentButton(),this.#i=null}hideStandaloneCommentButton(){this.#i?.classList.add("hidden")}get comment(){if(!this.#s)return null;let{data:{richText:e,text:t,date:n,deleted:s}}=this.#s;return{text:t,richText:e,date:n,deleted:s,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){if(this.#s||=new Zh(this),typeof e==="object"&&e!==null)this.#s.restoreData(e);else this.#s.data=e;if(this.hasComment)this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this);else this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this)}setCommentData({comment:e,popupRef:t,richText:n}){if(!t)return;if(this.#s||=new Zh(this),this.#s.setInitialText(e,n),!this.annotationElementId)return;let s=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);if(s)this.updateFromAnnotationLayer(s)}get hasEditedComment(){return this.#s?.hasBeenEdited()}get hasDeletedComment(){return this.#s?.isDeleted()}get hasComment(){return!!this.#s&&!this.#s.isEmpty()&&!this.#s.isDeleted()}async editComment(e){this.#s||=new Zh(this),this.#s.edit(e)}toggleComment(e,t=void 0){if(this.hasComment)this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){this.#s.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,s]=e.rect,[i]=this.pageDimensions,[r]=this.pageTranslation,o=r+i+1,l=s-100,c=o+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[o,l,c,s]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){this.#s.data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement("div");if(e.setAttribute("data-editor-rotation",(360-this.rotation)%360),e.className=this.name,e.setAttribute("id",this.id),e.tabIndex=this.#a?-1:0,e.setAttribute("role","application"),this.defaultL10nId)e.setAttribute("data-l10n-id",this.defaultL10nId);if(!this._isVisible)e.classList.add("hidden");this.setInForeground(),this.#P();let[t,n]=this.parentDimensions;if(this.parentRotation%180!==0)e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`;let[s,i]=this.getInitialTranslation();return this.translate(s,i),_7(this,e,["keydown","pointerdown","dblclick"]),this.#U(),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#G(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#O(e,t,n){let i=0.7*(n/t)+1-0.7;if(i===1)return;let r=this.#D(this.rotation),o=(q,P)=>[r[0]*q+r[2]*P,r[1]*q+r[3]*P],[l,c]=this.parentDimensions,h=this.x,d=this.y,m=this.width,p=this.height,b=_t.MIN_SIZE/l,v=_t.MIN_SIZE/c;i=Math.max(Math.min(i,1/m,1/p),b/m,v/p);let k=_t._round(m*i),A=_t._round(p*i);if(k===m&&A===p)return;this.#f||=[h,d,m,p];let T=o(m/2,p/2),E=_t._round(h+T[0]),I=_t._round(d+T[1]),_=o(k/2,A/2);this.x=E-_[0],this.y=I-_[1],this.width=k,this.height=A,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#H(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#M()}pointerdown(e){let{isMac:t}=Wn.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#g=!0,this._isDraggable){this.#S(e);return}this.#E(e)}#E(e){let{isMac:t}=Wn.platform;if(e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t)this.parent.toggleSelected(this);else this.parent.setSelected(this)}#S(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,s=new AbortController,i=this._uiManager.combinedSignal(s),r={capture:!0,passive:!1,signal:i},o=(c)=>{if(s.abort(),this.#r=null,this.#g=!1,!this._uiManager.endDragSession())this.#E(c);if(n)this._onStopDragging()};if(t)this.#v=e.clientX,this.#x=e.clientY,this.#r=e.pointerId,this.#o=e.pointerType,window.addEventListener("pointermove",(c)=>{if(!n)n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging();let{clientX:h,clientY:d,pointerId:m}=c;if(m!==this.#r){si(c);return}let[p,b]=this.screenToPageTranslation(h-this.#v,d-this.#x);this.#v=h,this.#x=d,this._uiManager.dragSelectedEditors(p,b),this.div.scrollIntoView({block:"nearest"})},r),window.addEventListener("touchmove",si,r),window.addEventListener("pointerdown",(c)=>{if(c.pointerType===this.#o){if(this.#A||c.isPrimary)o(c)}si(c)},r);let l=(c)=>{if(!this.#r||this.#r===c.pointerId){o(c);return}si(c)};window.addEventListener("pointerup",l,{signal:i}),window.addEventListener("blur",l,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){if(this.#y)clearTimeout(this.#y);this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let s=this.parentScale,[i,r]=this.pageDimensions,[o,l]=this.pageTranslation,c=e/s,h=t/s,d=this.x*i,m=this.y*r,p=this.width*i,b=this.height*r;switch(n){case 0:return[d+c+o,r-m-h-b+l,d+c+p+o,r-m-h+l];case 90:return[d+h+o,r-m+c+l,d+h+b+o,r-m+c+p+l];case 180:return[d-c-p+o,r-m+h+l,d-c+o,r-m+h+b+l];case 270:return[d-h-b+o,r-m-c-p+l,d-h+o,r-m-c+l];default:throw Error("Invalid rotation")}}getRectInCurrentCoords(e,t){let[n,s,i,r]=e,o=i-n,l=r-s;switch(this.rotation){case 0:return[n,t-r,o,l];case 90:return[n,t-s,l,o];case 180:return[i,t-s,o,l];case 270:return[i,t-r,l,o];default:throw Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&_t._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#s?.onUpdatedColor()}getData(){let{comment:{text:e,color:t,date:n,opacity:s,deleted:i,richText:r},uid:o,pageIndex:l,creationDate:c,modificationDate:h}=this;return{id:o,pageIndex:l,rect:this.getPDFRect(),richText:r,contentsObj:{str:e},creationDate:c,modificationDate:n||h,popupRef:!i,color:t,opacity:s}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){if(this.isInEditMode())return!1;return this.parent.setEditingState(!1),this.#b=!0,!0}disableEditMode(){if(!this.isInEditMode())return!1;return this.parent.setEditingState(!0),this.#b=!1,!0}isInEditMode(){return this.#b}shouldGetKeyboardEvents(){return this.#w}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:s}=this.getClientDimensions(),{innerHeight:i,innerWidth:r}=window;return t<r&&s>0&&e<i&&n>0}#P(){if(this.#d||!this.div)return;this.#d=new AbortController;let e=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})}#U(){if(this.#A||!this.div||!this.isResizable||!this._uiManager._supportsPinchToZoom)return;this.#A=new c2({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#G.bind(this),onPinching:this.#O.bind(this),onPinchEnd:this.#H.bind(this),signal:this._uiManager._signal})}rebuild(){this.#P(),this.#U()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(e=!1,t=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||""}}static async deserialize(e,t,n){let s=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});s.rotation=e.rotation,s.#e=e.accessibilityData,s._isCopy=e.isCopy||!1;let[i,r]=s.pageDimensions,[o,l,c,h]=s.getRectInCurrentCoords(e.rect,r);return s.x=o/i,s.y=l/r,s.width=c/i,s.height=h/r,s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,!this.isEmpty())this.commit();if(this.#A?.destroy(),this.#A=null,this.parent)this.parent.remove(this);else this._uiManager.removeEditor(this);if(this.hideCommentPopup(),this.#y)clearTimeout(this.#y),this.#y=null;if(this.#F(),this.removeEditToolbar(),this.#k){for(let e of this.#k.values())clearTimeout(e);this.#k=null}this.parent=null,this.#h?.remove(),this.#h=null}get isResizable(){return!1}makeResizable(){if(this.isResizable)this.#R(),this.#l.classList.remove("hidden")}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[e,t]}=this,[n,s,i,r]=this.getPDFRect();return[_t._round(n+(i-n)*e),_t._round(s+(r-s)*(1-t))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#s.commentPopupPositionInLayer}set commentPopupPosition(e){this.#s.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#s.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#s.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#s?.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let t=this.#l.children;if(!this.#t){this.#t=Array.from(t);let r=this.#V.bind(this),o=this.#Y.bind(this),l=this._uiManager._signal;for(let c of this.#t){let h=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",r,{signal:l}),c.addEventListener("blur",o,{signal:l}),c.addEventListener("focus",this.#W.bind(this,h),{signal:l}),c.setAttribute("data-l10n-id",_t._l10nResizer[h])}}let n=this.#t[0],s=0;for(let r of t){if(r===n)break;s++}let i=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(i!==s){if(i<s)for(let o=0;o<s-i;o++)this.#l.append(this.#l.firstElementChild);else if(i>s)for(let o=0;o<i-s;o++)this.#l.firstElementChild.before(this.#l.lastElementChild);let r=0;for(let o of t){let c=this.#t[r++].getAttribute("data-resizer-name");o.setAttribute("data-l10n-id",_t._l10nResizer[c])}}this.#K(0),this.#w=!0,this.#l.firstElementChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}#V(e){_t._resizerKeyboardManager.exec(this,e)}#Y(e){if(this.#w&&e.relatedTarget?.parentNode!==this.#l)this.#F()}#W(e){this.#p=this.#w?e:""}#K(e){if(!this.#t)return;for(let t of this.#t)t.tabIndex=e}_resizeWithKeyboard(e,t){if(!this.#w)return;this.#L(this.#p,{deltaX:e,deltaY:t,fromKeyboard:!0})}#F(){this.#w=!1,this.#K(-1),this.#M()}_stopResizingWithKeyboard(){this.#F(),this.div.focus()}select(){if(this.isSelected&&this._editToolbar){this._editToolbar.show();return}if(this.isSelected=!0,this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{if(this.div?.classList.contains("selectedEditor"))this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}focus(){if(this.div&&!this.div.contains(document.activeElement))setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){if(!this.isSelected)return;if(this.isSelected=!1,this.#l?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement))this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0),this.hideCommentPopup()}hideCommentPopup(){if(this.hasComment)this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){if(!this.canChangeContent)return;this.enableEditMode(),this.div.focus()}dblclick(e){if(e.target.nodeName==="BUTTON")return;this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid})}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#m}set isEditing(e){if(this.#m=e,!this.parent)return;if(e)this.parent.setSelected(this),this.parent.setActiveEditor(this);else this.parent.setActiveEditor(null)}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,t=!1){if(t){this.#k||=new Map;let{action:n}=e,s=this.#k.get(n);if(s)clearTimeout(s);s=setTimeout(()=>{if(this._reportTelemetry(e),this.#k.delete(n),this.#k.size===0)this.#k=null},_t._telemetryTimeout),this.#k.set(n,s);return}e.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){if(this.div)this.div.tabIndex=0;this.#a=!1}disable(){if(this.div)this.div.tabIndex=-1;this.#a=!0}updateFakeAnnotationElement(e){if(!this.#h&&!this.deleted){this.#h=e.addFakeAnnotation(this);return}if(this.deleted){this.#h.remove(),this.#h=null;return}if(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)this.#h.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(".annotationContent");if(!t)t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),e.container.prepend(t);else if(t.nodeName==="CANVAS"){let n=t;t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),n.before(t)}return t}resetAnnotationElement(e){let{firstElementChild:t}=e.container;if(t?.nodeName==="DIV"&&t.classList.contains("annotationContent"))t.remove()}}class D7 extends _t{constructor(e){super(e);this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}var Z8=3285377520,Br=4294901760,Ha=65535;class cm{constructor(e){this.h1=e?e&4294967295:Z8,this.h2=e?e&4294967295:Z8}update(e){let t,n;if(typeof e==="string"){t=new Uint8Array(e.length*2),n=0;for(let v=0,k=e.length;v<k;v++){let A=e.charCodeAt(v);if(A<=255)t[n++]=A;else t[n++]=A>>>8,t[n++]=A&255}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error("Invalid data format, must be a string or TypedArray.");let s=n>>2,i=n-s*4,r=new Uint32Array(t.buffer,0,s),o=0,l=0,c=this.h1,h=this.h2,d=3432918353,m=461845907,p=d&Ha,b=m&Ha;for(let v=0;v<s;v++)if(v&1)o=r[v],o=o*d&Br|o*p&Ha,o=o<<15|o>>>17,o=o*m&Br|o*b&Ha,c^=o,c=c<<13|c>>>19,c=c*5+3864292196;else l=r[v],l=l*d&Br|l*p&Ha,l=l<<15|l>>>17,l=l*m&Br|l*b&Ha,h^=l,h=h<<13|h>>>19,h=h*5+3864292196;switch(o=0,i){case 3:o^=t[s*4+2]<<16;case 2:o^=t[s*4+1]<<8;case 1:if(o^=t[s*4],o=o*d&Br|o*p&Ha,o=o<<15|o>>>17,o=o*m&Br|o*b&Ha,s&1)c^=o;else h^=o}this.h1=c,this.h2=h}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&Br|e*36045&Ha,t=t*4283543511&Br|((t<<16|e>>>16)*2950163797&Br)>>>16,e^=t>>>1,e=e*444984403&Br|e*60499&Ha,t=t*3301882366&Br|((t<<16|e>>>16)*3120437893&Br)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}var au=Object.freeze({map:null,hash:"",transfer:void 0});class km{#e=!1;#t=null;#n=null;#s=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(e,t){let n=this.#s.get(e);if(n===void 0)return t;return Object.assign(t,n)}getRawValue(e){return this.#s.get(e)}remove(e){let t=this.#s.get(e);if(t===void 0)return;if(t instanceof _t)this.#n.delete(t.annotationElementId);if(this.#s.delete(e),this.#s.size===0)this.resetModified();if(this.#s.values().some((n)=>n instanceof _t))return;this.onAnnotationEditor?.(null)}setValue(e,t){let n=this.#s.get(e),s=!1;if(n!==void 0){for(let[i,r]of Object.entries(t))if(n[i]!==r)s=!0,n[i]=r}else s=!0,this.#s.set(e,t);if(s)this.#i();if(t instanceof _t)(this.#n||=new Map).set(t.annotationElementId,t),this.onAnnotationEditor?.(t.constructor._type)}has(e){return this.#s.has(e)}get size(){return this.#s.size}#i(){if(!this.#e)this.#e=!0,this.onSetModified?.()}resetModified(){if(this.#e)this.#e=!1,this.onResetModified?.()}get print(){return new f2(this)}get serializable(){if(this.#s.size===0)return au;let e=new Map,t=new cm,n=[],s=Object.create(null),i=!1;for(let[r,o]of this.#s){let l=o instanceof _t?o.serialize(!1,s):o;if(o.page)o.pageIndex=o.page._pageIndex,delete o.page;if(l)e.set(r,l),t.update(`${r}:${JSON.stringify(l)}`),i||=!!l.bitmap}if(i){for(let r of e.values())if(r.bitmap)n.push(r.bitmap)}return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:au}get editorStats(){let e=null,t=new Map,n=0,s=0;for(let i of this.#s.values()){if(!(i instanceof _t)){if(i.popup)if(i.popup.deleted)s+=1;else n+=1;continue}if(i.isCommentDeleted)s+=1;else if(i.hasEditedComment)n+=1;let r=i.telemetryFinalData;if(!r)continue;let{type:o}=r;t.getOrInsertComputed(o,()=>Object.getPrototypeOf(i).constructor),e||=Object.create(null);let l=e[o]||=new Map;for(let[c,h]of Object.entries(r)){if(c==="type")continue;let d=l.getOrInsertComputed(c,s2);d.set(h,(d.get(h)??0)+1)}}if(s>0||n>0)e||=Object.create(null),e.comments={deleted:s,edited:n};if(!e)return null;for(let[i,r]of t)e[i]=r.computeTelemetryFinalData(e[i]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,t){let n=this.#n?.get(e);if(n)return n.updateFromAnnotationLayer(t),!0;return!1}getEditor(e){return this.#n?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#n)for(let n of this.#n.values()){if(!n.serialize())continue;e.push(n.annotationElementId)}let t="";if(e.length){let n=new cm;n.update(e.join(",")),t=n.hexdigest()}return this.#t={ids:new Set(e),hash:t}}[Symbol.iterator](){return this.#s.entries()}}class f2 extends km{#e=au;constructor(e){super();let{serializable:t}=e;if(t===au)return;let{map:n,hash:s,transfer:i}=t,r=structuredClone(n,i?{transfer:i}:null);this.#e={map:r,hash:s,transfer:[]}}get print(){Dn("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#e}get modifiedIds(){return Mt(this,"modifiedIds",{ids:new Set,hash:""})}}var df="__forcedDependency",{floor:e7,ceil:t7}=Math;function n7(e,t,n,s,i,r){e[t*4+0]=Math.min(e[t*4+0],n),e[t*4+1]=Math.min(e[t*4+1],s),e[t*4+2]=Math.max(e[t*4+2],i),e[t*4+3]=Math.max(e[t*4+3],r)}function hM(e,t,n,s,i){let r;if(e){if(e<0)r=i[0],i[0]=i[2],i[2]=r;if(i[0]*=e,i[2]*=e,t<0)r=i[1],i[1]=i[3],i[3]=r;i[1]*=t,i[3]*=t}else i.fill(0);i[0]+=n,i[1]+=s,i[2]+=n,i[3]+=s}var Jb=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];class q7{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===Jb}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}}var s7=(e,t)=>e?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1}));class M7{#e=[[1,0,0,1,0,0]];#t=[-1/0,-1/0,1/0,1/0];#n=new Float64Array(ko);_pendingBBoxIdx=-1;#s;#i;#a;#r;_savesStack=[];_markedContentStack=[];constructor(e,t){this.#s=e.width,this.#i=e.height,this.#o(t)}growOperationsCount(e){if(e>=this.#r.length)this.#o(e,this.#r)}#o(e,t){let n=new ArrayBuffer(e*4);if(this.#a=new Uint8ClampedArray(n),this.#r=new Uint32Array(n),t&&t.length>0)this.#r.set(t),this.#r.fill(Jb,t.length);else this.#r.fill(Jb)}get clipBox(){return this.#t}save(e){return this.#t={__proto__:this.#t},this._savesStack.push(e),this}restore(e,t){let n=Object.getPrototypeOf(this.#t);if(n===null)return this;this.#t=n;let s=this._savesStack.pop();if(s!==void 0)t?.(s,e),this.#r[e]=this.#r[s];return this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){let n=this._savesStack.pop();if(n!==void 0)t?.(n,e),this.#r[e]=this.#r[n];return this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){let n=this._markedContentStack.pop();if(n!==void 0)t?.(n,e),this.#r[e]=this.#r[n];return this}pushBaseTransform(e){return this.#e.push(ct.multiplyByDOMMatrix(this.#e.at(-1),e.getTransform())),this}popBaseTransform(){if(this.#e.length>1)this.#e.pop();return this}resetBBox(e){if(this._pendingBBoxIdx!==e)this._pendingBBoxIdx=e,this.#n.set(ko,0);return this}recordClipBox(e,t,n,s,i,r){let o=ct.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform()),l=ko.slice();ct.axialAlignedBoundingBox([n,i,s,r],o,l);let c=ct.intersect(this.#t,l);if(c)this.#t[0]=c[0],this.#t[1]=c[1],this.#t[2]=c[2],this.#t[3]=c[3];else this.#t[0]=this.#t[1]=1/0,this.#t[2]=this.#t[3]=-1/0;return this}recordBBox(e,t,n,s,i,r){let o=this.#t;if(o[0]===1/0)return this;let l=ct.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform());if(o[0]===-1/0)return ct.axialAlignedBoundingBox([n,i,s,r],l,this.#n),this;let c=ko.slice();return ct.axialAlignedBoundingBox([n,i,s,r],l,c),this.#n[0]=bs(c[0],o[0],this.#n[0]),this.#n[1]=bs(c[1],o[1],this.#n[1]),this.#n[2]=bs(c[2],this.#n[2],o[2]),this.#n[3]=bs(c[3],this.#n[3],o[3]),this}recordFullPageBBox(e){return this.#n[0]=Math.max(0,this.#t[0]),this.#n[1]=Math.max(0,this.#t[1]),this.#n[2]=Math.min(this.#s,this.#t[2]),this.#n[3]=Math.min(this.#i,this.#t[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;let s=e7(this.#n[0]*256/this.#s),i=e7(this.#n[1]*256/this.#i),r=t7(this.#n[2]*256/this.#s),o=t7(this.#n[3]*256/this.#i);if(n7(this.#a,e,s,i,r,o),n){for(let l of n)for(let c of l)if(c!==e)n7(this.#a,c,s,i,r,o)}if(!t)this._pendingBBoxIdx=-1;return this}bboxToClipBoxDropOperation(e){if(this._pendingBBoxIdx===e)this._pendingBBoxIdx=-1,this.#t[0]=Math.max(this.#t[0],this.#n[0]),this.#t[1]=Math.max(this.#t[1],this.#n[1]),this.#t[2]=Math.min(this.#t[2],this.#n[2]),this.#t[3]=Math.min(this.#t[3],this.#n[3]);return this}take(){return new q7(this.#r,this.#a)}takeDebugMetadata(){throw Error("Unreachable")}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,s=1,i=0,r=0,o){return this}getSimpleIndex(e){return}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}}class F7{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[df]:[]};#n=new Map;#s=new Set;#i=new Map;#a;#r;#o;constructor(e,t=!1){if(this.#o=e,t)this.#a=new Map,this.#r=(n,s)=>{s7(this.#a,s).dependencies.add(n)}}get clipBox(){return this.#o.clipBox}growOperationsCount(e){this.#o.growOperationsCount(e)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[df]:{__proto__:this.#t[df]}},this.#o.save(e),this}restore(e){this.#o.restore(e,this.#r);let t=Object.getPrototypeOf(this.#e);if(t===null)return this;return this.#e=t,this.#t=Object.getPrototypeOf(this.#t),this}recordOpenMarker(e){return this.#o.recordOpenMarker(e,this.#r),this}getOpenMarker(){return this.#o.getOpenMarker()}recordCloseMarker(e){return this.#o.recordCloseMarker(e,this.#r),this}beginMarkedContent(e){return this.#o.beginMarkedContent(e),this}endMarkedContent(e){return this.#o.endMarkedContent(e,this.#r),this}pushBaseTransform(e){return this.#o.pushBaseTransform(e),this}popBaseTransform(){return this.#o.popBaseTransform(),this}recordSimpleData(e,t){return this.#e[e]=t,this}recordIncrementalData(e,t){return this.#t[e].push(t),this}resetIncrementalData(e,t){return this.#t[e].length=0,this}recordNamedData(e,t){return this.#n.set(e,t),this}recordSimpleDataFromNamed(e,t,n){this.#e[e]=this.#n.get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(df,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let t of e)if(t in this.#e)this.recordFutureForcedDependency(t,this.#e[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#s)this.recordFutureForcedDependency(df,e);return this}resetBBox(e){return this.#o.resetBBox(e),this}recordClipBox(e,t,n,s,i,r){return this.#o.recordClipBox(e,t,n,s,i,r),this}recordBBox(e,t,n,s,i,r){return this.#o.recordBBox(e,t,n,s,i,r),this}recordCharacterBBox(e,t,n,s=1,i=0,r=0,o){let l=n.bbox,c,h;if(l){if(c=l[2]!==l[0]&&l[3]!==l[1]&&this.#i.get(n),c!==!1){if(h=[0,0,0,0],ct.axialAlignedBoundingBox(l,n.fontMatrix,h),s!==1||i!==0||r!==0)hM(s,-s,i,r,h);if(c)return this.recordBBox(e,t,h[0],h[2],h[1],h[3])}}if(!o)return this.recordFullPageBBox(e);let d=o();if(l&&h&&c===void 0){if(c=h[0]<=i-d.actualBoundingBoxLeft&&h[2]>=i+d.actualBoundingBoxRight&&h[1]<=r-d.actualBoundingBoxAscent&&h[3]>=r+d.actualBoundingBoxDescent,this.#i.set(n,c),c)return this.recordBBox(e,t,h[0],h[2],h[1],h[3])}return this.recordBBox(e,t,i-d.actualBoundingBoxLeft,i+d.actualBoundingBoxRight,r-d.actualBoundingBoxAscent,r+d.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#o.recordFullPageBBox(e),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,t){let n=this.#s,s=this.#e,i=this.#t;for(let r of t)if(r in this.#e)n.add(s[r]);else if(r in i)i[r].forEach(n.add,n);return this}recordNamedDependency(e,t){if(this.#n.has(t))this.#s.add(this.#n.get(t));return this}recordOperation(e,t=!1){if(this.recordDependencies(e,[df]),this.#a){let s=s7(this.#a,e),{dependencies:i}=s;this.#s.forEach(i.add,i),this.#o._savesStack.forEach(i.add,i),this.#o._markedContentStack.forEach(i.add,i),i.delete(e),s.isRenderingOperation=!0}let n=!t&&e===this.#o._pendingBBoxIdx;if(this.#o.recordOperation(e,t,[this.#s,this.#o._savesStack,this.#o._markedContentStack]),n)this.#s.clear();return this}recordShowTextOperation(e,t=!1){let n=Array.from(this.#s);this.recordOperation(e,t),this.recordIncrementalData("sameLineText",e);for(let s of n)this.recordIncrementalData("sameLineText",s);return this}bboxToClipBoxDropOperation(e,t=!1){let n=!t&&e===this.#o._pendingBBoxIdx;if(this.#o.bboxToClipBoxDropOperation(e),n)this.#s.clear();return this}take(){return this.#i.clear(),this.#o.take()}takeDebugMetadata(){return this.#a}}class ou{#e;#t;#n;#s=0;#i=0;constructor(e,t,n){if(e instanceof ou&&e.#n===!!n)return e;this.#e=e,this.#t=t,this.#n=!!n}get clipBox(){return this.#e.clipBox}growOperationsCount(){throw Error("Unreachable")}save(e){return this.#i++,this.#e.save(this.#t),this}restore(e){if(this.#i>0)this.#e.restore(this.#t),this.#i--;return this}recordOpenMarker(e){return this.#s++,this}getOpenMarker(){return this.#s>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#s--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,t){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,t){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,t){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this.#e.recordSimpleDataFromNamed(e,t,this.#t),this}recordFutureForcedDependency(e,t){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){if(!this.#n)this.#e.resetBBox(this.#t);return this}recordClipBox(e,t,n,s,i,r){if(!this.#n)this.#e.recordClipBox(this.#t,t,n,s,i,r);return this}recordBBox(e,t,n,s,i,r){if(!this.#n)this.#e.recordBBox(this.#t,t,n,s,i,r);return this}recordCharacterBBox(e,t,n,s,i,r,o){if(!this.#n)this.#e.recordCharacterBBox(this.#t,t,n,s,i,r,o);return this}recordFullPageBBox(e){if(!this.#n)this.#e.recordFullPageBBox(this.#t);return this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,t){return this.#e.recordDependencies(this.#t,t),this}recordNamedDependency(e,t){return this.#e.recordNamedDependency(this.#t,t),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){if(!this.#n)this.#e.bboxToClipBoxDropOperation(this.#t,!0);return this}take(){throw Error("Unreachable")}takeDebugMetadata(){throw Error("Unreachable")}}var Hr={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]};class fm{#e;#t;#n=4;#s=0;#i=new fm.#a(this.#n*6);static#a=Wn.isFloat16ArraySupported?Float16Array:Float32Array;constructor(e){this.#e=e.width,this.#t=e.height}record(e,t,n,s){if(this.#s===this.#n){this.#n*=2;let o=new fm.#a(this.#n*6);o.set(this.#i),this.#i=o}let i=ds(e),r;if(s[0]!==1/0){let o=ko.slice();ct.axialAlignedBoundingBox([0,-n,t,0],i,o);let l=ct.intersect(s,o);if(!l)return;let[c,h,d,m]=l;if(c!==o[0]||h!==o[1]||d!==o[2]||m!==o[3]){let p=Math.atan2(i[1],i[0]),b=Math.abs(Math.sin(p)),v=Math.abs(Math.cos(p));if(b<0.000001||v<0.000001||Math.abs(b-v)<0.000001)r=[c,h,c,m,d,h];else{let k=d-c,A=m-h,T=b*b,E=v*v,I=v*b,_=E-T,q=(A*E-k*I)/_,P=(A*I-k*T)/_;r=[c+P,h,c,h+q,d,m-q]}}}if(!r)r=[0,-n,0,0,t,-n],ct.applyTransform(r,i,0),ct.applyTransform(r,i,2),ct.applyTransform(r,i,4);r[0]/=this.#e,r[1]/=this.#t,r[2]/=this.#e,r[3]/=this.#t,r[4]/=this.#e,r[5]/=this.#t,this.#i.set(r,this.#s*6),this.#s++}take(){return this.#i.subarray(0,this.#s*6)}}var i7=/\p{Cc}/u;function uM(e){let t=e[0];if(e.length<2||t!=='"'&&t!=="'"||e.at(-1)!==t)return!1;let n=e.length-1;for(let s=1;s<n;s++){let i=e[s];if(i===t||i7.test(i))return!1;if(i==="\\"){if(++s>=n||i7.test(e[s]))return!1}}return!0}function r7(e){if(uM(e))return e;return`"${e.replaceAll(/["\\\p{Cc}]/gu,(n)=>n==='"'||n==="\\"?`\\${n}`:`\\${n.codePointAt(0).toString(16)} `)}"`}class L7{#e=new Set;#t=null;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){let t=this.#n();t.insertRule(e,t.cssRules.length)}#n(){if(this.#t)return this.#t;let e=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&e){let{adoptedStyleSheets:t}=this._document;if(t){let n=new e;return t.push(n),this.#t=n}}if(!this.styleElement)this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement);return this.#t=this.styleElement.sheet}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);if(this.nativeFontFaces.clear(),this.#e.clear(),this.#t){let{adoptedStyleSheets:e}=this._document;if(e?.includes(this.#t))this._document.adoptedStyleSheets=e.filter((t)=>t!==this.#t);this.#t=null}if(this.styleElement)this.styleElement.remove(),this.styleElement=null}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!e||this.#e.has(e.loadedName))return;if(Rs(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:s,src:i,style:r}=e,o=new FontFace(s,i,r);this.addNativeFontFace(o);try{await o.load(),this.#e.add(s),n?.(e)}catch{on(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(o)}return}Dn("Not implemented: loadSystemFont without the Font Loading API.")}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let n=e.createNativeFontFace();if(n){this.addNativeFontFace(n);try{await n.loaded}catch(s){throw on(`Failed to load font '${n.family}': '${s}'.`),e.disableFontFace=!0,s}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise((n)=>{let s=this._queueLoadingCallback(n);this._prepareFontLoadEvent(e,s)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return Mt(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Mt(this,"isSyncFontLoadingSupported",Sr||Wn.platform.isFirefox)}_queueLoadingCallback(e){function t(){Rs(!s.done,"completeRequest() cannot be called twice."),s.done=!0;while(n.length>0&&n[0].done){let i=n.shift();setTimeout(i.callback,0)}}let{loadingRequests:n}=this,s={done:!1,complete:t,callback:e};return n.push(s),s}get _loadTestFont(){let e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Mt(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function n(_,q){return _.charCodeAt(q)<<24|_.charCodeAt(q+1)<<16|_.charCodeAt(q+2)<<8|_.charCodeAt(q+3)&255}function s(_){return String.fromCharCode(_>>24&255,_>>16&255,_>>8&255,_&255)}function i(_,q,P,N){let H=_.substring(0,q),V=_.substring(q+P);return H+N+V}let r,o,l=this._document.createElement("canvas");l.width=1,l.height=1;let c=l.getContext("2d"),h=0;function d(_,q){if(++h>30){on("Load test font never loaded."),q();return}if(c.font="30px "+_,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){q();return}setTimeout(d.bind(null,_,q))}let m=`lt${Date.now()}${this.loadTestFontId++}`,p=this._loadTestFont;p=i(p,976,m.length,m);let v=16,k=1482184792,A=n(p,v);for(r=0,o=m.length-3;r<o;r+=4)A=A-k+n(m,r)|0;if(r<m.length)A=A-k+n(m+"XXX",r)|0;p=i(p,v,4,s(A));let T=`url(data:font/opentype;base64,${btoa(p)});`,E=`@font-face {font-family:"${m}";src:${T}}`;this.insertRule(E);let I=this._document.createElement("div");I.style.visibility="hidden",I.style.width=I.style.height="10px",I.style.position="absolute",I.style.top=I.style.left="0px";for(let _ of[e.loadedName,m]){let q=this._document.createElement("span");q.textContent="Hi",q.style.fontFamily=_,I.append(q)}this._document.body.append(I),d(m,()=>{I.remove(),t.complete()})}}class O7{compiledGlyphs=Object.create(null);#e;constructor(e,t=null,n,s){if(this.#e=e,this._inspectFont=t,n)this.charProcOperatorList=n;if(s)Object.assign(this,s)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};if(this.cssFontInfo.italicAngle)t.style=`oblique ${this.cssFontInfo.italicAngle}deg`;e=new FontFace(r7(this.cssFontInfo.fontFamily),this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;if(this.cssFontInfo.italicAngle)n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;t=`@font-face {font-family:${r7(this.cssFontInfo.fontFamily)};${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+"_path_"+t,s;try{s=e.get(n)}catch(r){on(`getPathGenerator - ignoring character: "${r}".`)}let i=C7(s?.path);if(!this.fontExtraProperties)e.delete(n);return this.compiledGlyphs[t]=i}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace}set disableFontFace(e){Mt(this,"disableFontFace",!!e)}get fontExtraProperties(){return this.#e.fontExtraProperties}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}}class P7{static strings=["fontFamily","fontWeight","italicAngle"]}class N7{static strings=["css","loadedName","baseFontName","src"]}class Ur{static bools=["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"];static numbers=["ascent","defaultWidth","descent"];static strings=["fallbackName","loadedName","mimetype","name"];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6}class fl{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16}class lu{static get decoder(){return Mt(this,"decoder",new TextDecoder)}static get encoder(){return Mt(this,"encoder",new TextEncoder)}}class B7{#e;#t;constructor(e){this.#e=e,this.#t=new DataView(e)}#n(e){Rs(e<P7.strings.length,"Invalid string index");let{decoder:t}=lu,n=0;for(let i=0;i<e;i++)n+=this.#t.getUint32(n)+4;let s=this.#t.getUint32(n);return t.decode(new Uint8Array(this.#e,n+4,s))}get fontFamily(){return this.#n(0)}get fontWeight(){return this.#n(1)}get italicAngle(){return this.#n(2)}}class H7{#e;#t;constructor(e){this.#e=e,this.#t=new DataView(e)}get guessFallback(){return this.#t.getUint8(0)!==0}#n(e){Rs(e<N7.strings.length,"Invalid string index");let{decoder:t}=lu,n=5;for(let i=0;i<e;i++)n+=this.#t.getUint32(n)+4;let s=this.#t.getUint32(n);return t.decode(new Uint8Array(this.#e,n+4,s))}get css(){return this.#n(0)}get loadedName(){return this.#n(1)}get baseFontName(){return this.#n(2)}get src(){return this.#n(3)}get style(){let{decoder:e}=lu,t=1;t+=4+this.#t.getUint32(t);let n=this.#t.getUint32(t),s=e.decode(new Uint8Array(this.#e,t+4,n));t+=4+n;let i=this.#t.getUint32(t),r=e.decode(new Uint8Array(this.#e,t+4,i));return{style:s,weight:r}}}class U7{#e;#t;constructor({buffer:e,extra:t}){if(this.#e=e,this.#t=new DataView(e),t)Object.assign(this,t)}#n(e){Rs(e<Ur.bools.length,"Invalid boolean index");let t=Math.floor(e/4),n=e*2%8,s=this.#t.getUint8(t)>>n&3;return s===0?void 0:s===2}get black(){return this.#n(0)}get bold(){return this.#n(1)}get disableFontFace(){return this.#n(2)}get fontExtraProperties(){return this.#n(3)}get isInvalidPDFjsFont(){return this.#n(4)}get isType3Font(){return this.#n(5)}get italic(){return this.#n(6)}get missingFile(){return this.#n(7)}get remeasure(){return this.#n(8)}get vertical(){return this.#n(9)}#s(e){return Rs(e<Ur.numbers.length,"Invalid number index"),this.#t.getFloat64(Ur.OFFSET_NUMBERS+e*8)}get ascent(){return this.#s(0)}get defaultWidth(){return this.#s(1)}get descent(){return this.#s(2)}#i(e,t,n,s){let i=this.#t.getUint8(e);if(i===0)return;Rs(i===t,"Invalid array length."),e+=1;let r=Array(i);for(let o=0;o<i;o++)r[o]=this.#t[n](e,!0),e+=s;return r}get bbox(){return this.#i(Ur.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return this.#i(Ur.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return this.#i(Ur.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}#a(e){Rs(e<Ur.strings.length,"Invalid string index");let{decoder:t}=lu,n=Ur.OFFSET_STRINGS+4;for(let i=0;i<e;i++)n+=this.#t.getUint32(n)+4;let s=this.#t.getUint32(n);return t.decode(new Uint8Array(this.#e,n+4,s))}get fallbackName(){return this.#a(0)}get loadedName(){return this.#a(1)}get mimetype(){return this.#a(2)}get name(){return this.#a(3)}#r(){let e=Ur.OFFSET_STRINGS,t=this.#t.getUint32(e);e+=4+t;let n=this.#t.getUint32(e);e+=4+n;let s=this.#t.getUint32(e);e+=4+s;let i=this.#t.getUint32(e);return{offset:e,length:i}}get data(){let{offset:e,length:t}=this.#r();return t===0?void 0:new Uint8Array(this.#e,e+4,t)}clearData(){let{offset:e,length:t}=this.#r();if(t===0)return;this.#t.setUint32(e,0),this.#e=new Uint8Array(this.#e,0,e+4).slice().buffer,this.#t=new DataView(this.#e)}get cssFontInfo(){let e=Ur.OFFSET_STRINGS,t=this.#t.getUint32(e);e+=4+t;let n=this.#t.getUint32(e);e+=4+n;let s=this.#t.getUint32(e);if(s===0)return null;let i=new Uint8Array(s);return i.set(new Uint8Array(this.#e,e+4,s)),new B7(i.buffer)}get systemFontInfo(){let e=Ur.OFFSET_STRINGS,t=this.#t.getUint32(e);e+=4+t;let n=this.#t.getUint32(e);if(n===0)return null;let s=new Uint8Array(n);return s.set(new Uint8Array(this.#e,e+4,n)),new H7(s.buffer)}}class z7{constructor(e){this.buffer=e,this.view=new DataView(e),this.data=new Uint8Array(e)}getIR(){let e=this.view,t=this.data[fl.KIND],n=!!this.data[fl.HAS_BBOX],s=!!this.data[fl.HAS_BACKGROUND],i=e.getUint32(fl.N_COORD,!0),r=e.getUint32(fl.N_COLOR,!0),o=e.getUint32(fl.N_STOP,!0),l=20,c=new Float32Array(this.buffer,l,i*2);l+=i*8;let h=new Uint8Array(this.buffer,l,r*4);l+=r*4;let d=[];for(let b=0;b<o;++b){let v=e.getFloat32(l,!0);l+=4;let k=e.getUint32(l,!0);l+=4,d.push([v,`#${k.toString(16).padStart(6,"0")}`])}let m=null;if(n){m=[];for(let b=0;b<4;++b)m.push(e.getFloat32(l,!0)),l+=4}let p=null;if(s)p=new Uint8Array(this.buffer,l,3),l+=3;if(t===1)return["RadialAxial","axial",m,d,Array.from(c.slice(0,2)),Array.from(c.slice(2,4)),null,null];if(t===2)return["RadialAxial","radial",m,d,[c[0],c[1]],[c[3],c[4]],c[2],c[5]];if(t===3){let b=this.data[fl.SHADING_TYPE],v=null;if(c.length>0){v=ko.slice();for(let k=0,A=c.length;k<A;k+=2)ct.pointBoundingBox(c[k],c[k+1],v)}return["Mesh",b,c,h,i,v,m,p]}throw Error(`Unsupported pattern kind: ${t}`)}}class G7{#e;constructor(e){this.#e=e}get path(){if(Wn.isFloat16ArraySupported)return new Float16Array(this.#e);return new Float32Array(this.#e)}}function dM(e){if(e instanceof URL)return e;if(typeof e==="string"){if(Sr){if(/^[a-z][a-z0-9\-+.]+:/i.test(e))return new URL(e);let n=process.getBuiltinModule("url");return new URL(n.pathToFileURL(e))}let t=URL.parse(e,window.location);if(t)return t}throw Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function mM(e){if(Sr&&typeof Buffer<"u"&&e instanceof Buffer)throw Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if(typeof e==="string")return ym(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==="object"&&!isNaN(e?.length))return new Uint8Array(e);throw Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function X0(e){if(typeof e!=="string")return null;if(e.endsWith("/"))return e;throw Error(`Invalid factory url: "${e}" must include trailing slash.`)}var Zb=(e)=>typeof e==="object"&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0,pM=(e)=>typeof e==="object"&&typeof e?.name==="string",gM=eM.bind(null,Zb,pM);class V7{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[s]of this.#e)s.call(this,n)})}addEventListener(e,t,n=null){let s=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){on("LoopbackPort - cannot use an `aborted` signal.");return}let r=()=>this.removeEventListener(e,t);s=()=>i.removeEventListener("abort",r),i.addEventListener("abort",r)}this.#e.set(t,s)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}}var W0={DATA:1,ERROR:2},Qs={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function a7(){}function er(e){if(e instanceof Ao||e instanceof om||e instanceof am||e instanceof iu||e instanceof sm)return e;if(!(e instanceof Error||typeof e==="object"&&e!==null))Dn('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new Ao(e.message);case"InvalidPDFException":return new om(e.message);case"PasswordException":return new am(e.message,e.code);case"ResponseException":return new iu(e.message,e.status,e.missing);case"UnknownErrorException":return new sm(e.message,e.details)}return new sm(e.message,e.toString())}class gf{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener("message",this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#s(e);return}if(e.callback){let n=e.callbackId,s=this.callbackCapabilities[n];if(!s)throw Error(`Cannot resolve callback ${n}`);if(delete this.callbackCapabilities[n],e.callback===W0.DATA)s.resolve(e.data);else if(e.callback===W0.ERROR)s.reject(er(e.reason));else throw Error("Unexpected callback case");return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,s=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(r){i.postMessage({sourceName:n,targetName:s,callback:W0.DATA,callbackId:e.callbackId,data:r})},function(r){i.postMessage({sourceName:n,targetName:s,callback:W0.ERROR,callbackId:e.callbackId,reason:er(r)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let s=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[s]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:s,data:t},n)}catch(r){i.reject(r)}return i.promise}sendWithStream(e,t,n,s){let i=this.streamId++,r=this.sourceName,o=this.targetName,l=this.comObj;return new ReadableStream({start:(c)=>{let h=Promise.withResolvers();return this.streamControllers[i]={controller:c,startCall:h,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:r,targetName:o,action:e,streamId:i,data:t,desiredSize:c.desiredSize},s),h.promise},pull:(c)=>{let h=Promise.withResolvers();return this.streamControllers[i].pullCall=h,l.postMessage({sourceName:r,targetName:o,stream:Qs.PULL,streamId:i,desiredSize:c.desiredSize}),h.promise},cancel:(c)=>{Rs(c instanceof Error,"cancel must have a valid reason");let h=Promise.withResolvers();return this.streamControllers[i].cancelCall=h,this.streamControllers[i].isClosed=!0,l.postMessage({sourceName:r,targetName:o,stream:Qs.CANCEL,streamId:i,reason:er(c)}),h.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,s=e.sourceName,i=this.comObj,r=this,o=this.actionHandler[e.action],l={enqueue(c,h=1,d){if(this.isCancelled)return;let m=this.desiredSize;if(this.desiredSize-=h,m>0&&this.desiredSize<=0)this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise;i.postMessage({sourceName:n,targetName:s,stream:Qs.ENQUEUE,streamId:t,chunk:c},d)},close(){if(this.isCancelled)return;this.isCancelled=!0,i.postMessage({sourceName:n,targetName:s,stream:Qs.CLOSE,streamId:t}),delete r.streamSinks[t]},error(c){if(Rs(c instanceof Error,"error must have a valid reason"),this.isCancelled)return;this.isCancelled=!0,i.postMessage({sourceName:n,targetName:s,stream:Qs.ERROR,streamId:t,reason:er(c)})},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[t]=l,Promise.try(o,e.data,l).then(function(){i.postMessage({sourceName:n,targetName:s,stream:Qs.START_COMPLETE,streamId:t,success:!0})},function(c){i.postMessage({sourceName:n,targetName:s,stream:Qs.START_COMPLETE,streamId:t,reason:er(c)})})}#s(e){let t=e.streamId,n=this.sourceName,s=e.sourceName,i=this.comObj,r=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case Qs.START_COMPLETE:if(e.success)r.startCall.resolve();else r.startCall.reject(er(e.reason));break;case Qs.PULL_COMPLETE:if(e.success)r.pullCall.resolve();else r.pullCall.reject(er(e.reason));break;case Qs.PULL:if(!o){i.postMessage({sourceName:n,targetName:s,stream:Qs.PULL_COMPLETE,streamId:t,success:!0});break}if(o.desiredSize<=0&&e.desiredSize>0)o.sinkCapability.resolve();o.desiredSize=e.desiredSize,Promise.try(o.onPull||a7).then(function(){i.postMessage({sourceName:n,targetName:s,stream:Qs.PULL_COMPLETE,streamId:t,success:!0})},function(c){i.postMessage({sourceName:n,targetName:s,stream:Qs.PULL_COMPLETE,streamId:t,reason:er(c)})});break;case Qs.ENQUEUE:if(Rs(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(e.chunk);break;case Qs.CLOSE:if(Rs(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#i(r,t);break;case Qs.ERROR:Rs(r,"error should have stream controller"),r.controller.error(er(e.reason)),this.#i(r,t);break;case Qs.CANCEL_COMPLETE:if(e.success)r.cancelCall.resolve();else r.cancelCall.reject(er(e.reason));this.#i(r,t);break;case Qs.CANCEL:if(!o)break;let l=er(e.reason);Promise.try(o.onCancel||a7,l).then(function(){i.postMessage({sourceName:n,targetName:s,stream:Qs.CANCEL_COMPLETE,streamId:t,success:!0})},function(c){i.postMessage({sourceName:n,targetName:s,stream:Qs.CANCEL_COMPLETE,streamId:t,reason:er(c)})}),o.sinkCapability.reject(l),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error("Unexpected stream case")}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}}class h2{#e=Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"});constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Dn(`Not implemented: ${e}`)}let n=this[e];if(!n)throw Error(`Ensure that the \`${e}\` API parameter is provided.`);let s=`${n}${t}`;return this._fetch(s,e).catch((i)=>{throw Error(`Unable to load ${this.#e[e]} data at: ${s}`)})}async _fetch(e,t){Dn("Abstract method `_fetch` called.")}}class e2 extends h2{async _fetch(e,t){let n=t==="cMapUrl"&&!e.endsWith(".bcmap")?"text":"bytes",s=await r2(e,n);return s instanceof Uint8Array?s:ym(s)}}class u2{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error("Invalid canvas size");let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext("2d",{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error("Canvas is not specified");if(t<=0||n<=0)throw Error("Invalid canvas size");e.width=t,e.height=n}destroy(e){let{canvas:t}=e;if(!t)throw Error("Canvas is not specified");t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){Dn("Abstract method `_createCanvas` called.")}}class $7 extends u2{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t});this._document=e}_createCanvas(e,t){let n=this._document.createElement("canvas");return n.width=e,n.height=t,n}}class d2{addFilter(e){return"none"}addHCMFilter(e,t){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addKnockoutFilter(e=0){return"none"}addHighlightHCMFilter(e,t,n,s,i){return"none"}addSelectionHCMFilter(e,t){return"none"}addSelectionFilter(){return"none"}createSelectionStyle(e=null){return null}destroy(e=!1){}}class X7 extends d2{#e;#t;#n;#s;#i;#a;#r=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super();this.#s=e,this.#i=t}get#o(){return this.#t||=new Map}get#l(){return this.#a||=new Map}get#c(){if(!this.#n){let e=this.#i.createElement("div"),{style:t}=e;t.colorScheme="only light",t.visibility="hidden",t.contain="strict",t.width=t.height=0,t.position="absolute",t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("width",0),n.setAttribute("height",0),this.#n=this.#i.createElementNS("http://www.w3.org/2000/svg","defs"),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let l=e[0],c=Array(256);for(let d=0;d<256;d++)c[d]=l[d]/255;let h=c.join(",");return[h,h,h]}let[t,n,s]=e,i=Array(256),r=Array(256),o=Array(256);for(let l=0;l<256;l++)i[l]=t[l]/255,r[l]=n[l]/255,o[l]=s[l]/255;return[i.join(","),r.join(","),o.join(",")]}#h(e){if(this.#e===void 0){this.#e="";let t=this.#i.URL;if(t!==this.#i.baseURI)if(Sm(t))on('#createUrl: ignore "data:"-URL for performance reasons.');else this.#e=S7(t,"")}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return"none";let t=this.#o.get(e);if(t)return t;let[n,s,i]=this.#u(e),r=e.length===1?n:`${n}${s}${i}`;if(t=this.#o.get(r),t)return this.#o.set(e,t),t;let o=`g_${this.#s}_transfer_map_${this.#r++}`,l=this.#h(o);this.#o.set(e,l),this.#o.set(r,l);let c=this.#g(o);return this.#m(n,s,i,c),l}addHCMFilter(e,t){let n=`${e}-${t}`,s="base",i=this.#l.get("base");if(i?.key===n)return i.url;if(i)i.filter?.remove(),i.key=n,i.url="none",i.filter=null;else i={key:n,url:"none",filter:null},this.#l.set("base",i);if(!e||!t)return i.url;let r=this.#w(e);e=ct.makeHexColor(...r);let o=this.#w(t);if(t=ct.makeHexColor(...o),this.#v(),e==="#000000"&&t==="#ffffff"||e===t)return i.url;let c=Array.from({length:256},(p,b)=>Qb(b/255)).join(","),h=`g_${this.#s}_hcm_filter`,d=i.filter=this.#g(h);this.#m(c,c,c,d),this.#p(d);let m=(p,b)=>{let v=r[p]/255,k=o[p]/255,A=Array(b+1);for(let T=0;T<=b;T++)A[T]=v+T/b*(k-v);return A.join(",")};return this.#m(m(0,5),m(1,5),m(2,5),d),i.url=this.#h(h),i.url}addSelectionHCMFilter(e,t){return this.addHighlightHCMFilter("selection",e,t,"HighlightText","Highlight")}addSelectionFilter(){return this.addHighlightHCMFilter("selection_default","black","white","HighlightText","Highlight")}createSelectionStyle(e=null){let t=e?this.addSelectionHCMFilter(e.foreground,e.background):this.addSelectionFilter();if(t==="none"||!Wn.platform.isFirefox)return null;return{"backdrop-filter":t,"background-color":"transparent"}}addAlphaFilter(e){let t=this.#o.get(e);if(t)return t;let[n]=this.#u([e]),s=`alpha_${n}`;if(t=this.#o.get(s),t)return this.#o.set(e,t),t;let i=`g_${this.#s}_alpha_map_${this.#r++}`,r=this.#h(i);this.#o.set(e,r),this.#o.set(s,r);let o=this.#g(i);return this.#b(n,o),r}addLuminosityFilter(e){let t=this.#o.get(e||"luminosity");if(t)return t;let n,s;if(e)[n]=this.#u([e]),s=`luminosity_${n}`;else s="luminosity";if(t=this.#o.get(s),t)return this.#o.set(e,t),t;let i=`g_${this.#s}_luminosity_map_${this.#r++}`,r=this.#h(i);this.#o.set(e,r),this.#o.set(s,r);let o=this.#g(i);if(this.#d(o),e)this.#b(n,o);return r}addKnockoutFilter(e=0){let t=e>0?Math.min(1/e,1e6):1e6,n=`knockout_${t}`,s=this.#o.get(n);if(s)return s;let i=`g_${this.#s}_knockout_filter_${this.#r++}`,r=this.#h(i);this.#o.set(n,r);let o=this.#g(i),l=this.#i.createElementNS("http://www.w3.org/2000/svg","feComponentTransfer");o.append(l);let c=this.#i.createElementNS("http://www.w3.org/2000/svg","feFuncA");return c.setAttribute("type","linear"),c.setAttribute("slope",`${t}`),c.setAttribute("intercept","0"),l.append(c),r}addHighlightHCMFilter(e,t,n,s,i){let r=`${t}-${n}-${s}-${i}`,o=this.#l.get(e);if(o?.key===r)return o.url;if(o)o.filter?.remove(),o.key=r,o.url="none",o.filter=null;else o={key:r,url:"none",filter:null},this.#l.set(e,o);if(!t||!n)return o.url;let[l,c]=[t,n].map(this.#w.bind(this)),h=Math.round(0.2126*l[0]+0.7152*l[1]+0.0722*l[2]),d=Math.round(0.2126*c[0]+0.7152*c[1]+0.0722*c[2]),[m,p]=[s,i].map(this.#x.bind(this));if(d<h)[h,d,m,p]=[d,h,p,m];this.#v();let b=(A,T,E)=>{let I=Array(256),_=(d-h)/E,q=A/255,P=(T-A)/(255*E),N=0;for(let H=0;H<=E;H++){let V=Math.round(h+H*_),U=q+H*P;for(let W=N;W<=V;W++)I[W]=U;N=V+1}for(let H=N;H<256;H++)I[H]=I[N-1];return I.join(",")},v=`g_${this.#s}_hcm_${e}_filter`,k=o.filter=this.#g(v);return this.#p(k),this.#m(b(m[0],p[0],5),b(m[1],p[1],5),b(m[2],p[2],5),k),o.url=this.#h(v),o.url}destroy(e=!1){if(e&&this.#a?.size)return;this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#r=0}#d(e){let t=this.#i.createElementNS("http://www.w3.org/2000/svg","feColorMatrix");t.setAttribute("type","matrix"),t.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),e.append(t)}#p(e){let t=this.#i.createElementNS("http://www.w3.org/2000/svg","feColorMatrix");t.setAttribute("type","matrix"),t.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),e.append(t)}#g(e){let t=this.#i.createElementNS("http://www.w3.org/2000/svg","filter");return t.setAttribute("color-interpolation-filters","sRGB"),t.setAttribute("id",e),this.#c.append(t),t}#f(e,t,n){let s=this.#i.createElementNS("http://www.w3.org/2000/svg",t);s.setAttribute("type","discrete"),s.setAttribute("tableValues",n),e.append(s)}#m(e,t,n,s){let i=this.#i.createElementNS("http://www.w3.org/2000/svg","feComponentTransfer");s.append(i),this.#f(i,"feFuncR",e),this.#f(i,"feFuncG",t),this.#f(i,"feFuncB",n)}#b(e,t){let n=this.#i.createElementNS("http://www.w3.org/2000/svg","feComponentTransfer");t.append(n),this.#f(n,"feFuncA",e)}#w(e){return this.#c.style.color="CanvasText",this.#c.style.backgroundColor=e,du(getComputedStyle(this.#c).getPropertyValue("background-color"))}#y(e){return this.#c.style.color="CanvasText",this.#c.style.backgroundColor=e,uu(getComputedStyle(this.#c).getPropertyValue("background-color"))}#v(){this.#c.style.color="",this.#c.style.backgroundColor=""}#x(e){let[t,n,s,i]=this.#y(e);if(i===1)return[t,n,s];let[r,o,l]=this.#w("Canvas");return[zb(t,r,i),zb(n,o,i),zb(s,l,i)]}}function zb(e,t,n){return Math.round(n*e+(1-n)*t)}if(Sr)on("Please use the `legacy` build in Node.js environments.");async function bM(e){let n=await process.getBuiltinModule("fs/promises").readFile(e);return new Uint8Array(n)}class W7 extends d2{}class K7 extends u2{_createCanvas(e,t){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(e,t)}}class Y7 extends h2{async _fetch(e,t){return bM(e)}}function Q7({src:e,srcPos:t=0,dest:n,width:s,height:i,nonBlackColor:r=4294967295,inverseDecode:o=!1}){let l=Wn.isLittleEndian?4278190080:255,[c,h]=o?[r,l]:[l,r],d=s>>3,m=s&7,p=c^h,b=e.length;n=new Uint32Array(n.buffer);let v=0;for(let k=0;k<i;++k){for(let T=t+d;t<T;++t,v+=8){let E=e[t];n[v]=c^-(E>>7&1)&p,n[v+1]=c^-(E>>6&1)&p,n[v+2]=c^-(E>>5&1)&p,n[v+3]=c^-(E>>4&1)&p,n[v+4]=c^-(E>>3&1)&p,n[v+5]=c^-(E>>2&1)&p,n[v+6]=c^-(E>>1&1)&p,n[v+7]=c^-(E&1)&p}if(m===0)continue;let A=t<b?e[t++]:255;for(let T=0;T<m;++T,++v)n[v]=c^-(A>>7-T&1)&p}return{srcPos:t,destPos:v}}function wM({src:e,srcPos:t=0,dest:n,destPos:s=0,width:i,height:r}){let o=0,l=i*r*3,c=l>>2,h=new Uint32Array(e.buffer,t,c),d=Wn.isLittleEndian?4278190080:255;if(Wn.isLittleEndian){for(;o<c-2;o+=3,s+=4){let m=h[o],p=h[o+1],b=h[o+2];n[s]=m|d,n[s+1]=m>>>24|p<<8|d,n[s+2]=p>>>16|b<<16|d,n[s+3]=b>>>8|d}for(let m=o*4,p=t+l;m<p;m+=3)n[s++]=e[m]|e[m+1]<<8|e[m+2]<<16|d}else{for(;o<c-2;o+=3,s+=4){let m=h[o],p=h[o+1],b=h[o+2];n[s]=m|d,n[s+1]=m<<24|p>>>8|d,n[s+2]=p<<16|b>>>16|d,n[s+3]=b<<8|d}for(let m=o*4,p=t+l;m<p;m+=3)n[s++]=e[m]<<24|e[m+1]<<16|e[m+2]<<8|d}return{srcPos:t+l,destPos:s}}var yM=`
76
- struct Uniforms {
77
- offsetX : f32,
78
- offsetY : f32,
79
- scaleX : f32,
80
- scaleY : f32,
81
- paddedWidth : f32,
82
- paddedHeight : f32,
83
- borderSize : f32,
84
- _pad : f32,
85
- };
86
-
87
- @group(0) @binding(0) var<uniform> u : Uniforms;
88
-
89
- struct VertexInput {
90
- @location(0) position : vec2<f32>,
91
- @location(1) color : vec4<f32>,
92
- };
93
-
94
- struct VertexOutput {
95
- @builtin(position) position : vec4<f32>,
96
- @location(0) color : vec3<f32>,
97
- };
98
-
99
- @vertex
100
- fn vs_main(in : VertexInput) -> VertexOutput {
101
- var out : VertexOutput;
102
- let cx = (in.position.x + u.offsetX) * u.scaleX;
103
- let cy = (in.position.y + u.offsetY) * u.scaleY;
104
- out.position = vec4<f32>(
105
- ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0,
106
- 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0,
107
- 0.0,
108
- 1.0
109
- );
110
- out.color = in.color.rgb;
111
- return out;
112
- }
113
-
114
- @fragment
115
- fn fs_main(in : VertexOutput) -> @location(0) vec4<f32> {
116
- return vec4<f32>(in.color, 1.0);
117
- }
118
- `;class J7{#e=null;#t=null;#n=null;#s=null;async#i(){if(!globalThis.navigator?.gpu)return!1;try{let e=await navigator.gpu.requestAdapter();if(!e)return!1;return this.#s=navigator.gpu.getPreferredCanvasFormat(),this.#t=await e.requestDevice(),!0}catch{return!1}}init(){return this.#e||=this.#i()}get isReady(){return this.#t!==null}loadMeshShader(){if(!this.#t||this.#n)return;let e=this.#t.createShaderModule({code:yM});this.#n=this.#t.createRenderPipeline({layout:"auto",vertex:{module:e,entryPoint:"vs_main",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:e,entryPoint:"fs_main",targets:[{format:this.#s}]},primitive:{topology:"triangle-list"}})}draw(e,t,n,s,i,r,o,l){this.loadMeshShader();let c=this.#t,{offsetX:h,offsetY:d,scaleX:m,scaleY:p}=s,b=c.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});if(e.byteLength>0)c.queue.writeBuffer(b,0,e);let v=c.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});if(t.byteLength>0)c.queue.writeBuffer(v,0,t);let k=c.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});c.queue.writeBuffer(k,0,new Float32Array([h,d,m,p,r,o,l,0]));let A=c.createBindGroup({layout:this.#n.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:k}}]}),T=new OffscreenCanvas(r,o),E=T.getContext("webgpu");E.configure({device:c,format:this.#s,alphaMode:i?"opaque":"premultiplied"});let I=i?{r:i[0]/255,g:i[1]/255,b:i[2]/255,a:1}:{r:0,g:0,b:0,a:0},_=c.createCommandEncoder(),q=_.beginRenderPass({colorAttachments:[{view:E.getCurrentTexture().createView(),clearValue:I,loadOp:"clear",storeOp:"store"}]});if(n>0)q.setPipeline(this.#n),q.setBindGroup(0,A),q.setVertexBuffer(0,b),q.setVertexBuffer(1,v),q.draw(n);return q.end(),c.queue.submit([_.finish()]),b.destroy(),v.destroy(),k.destroy(),T.transferToImageBitmap()}}var xm=new J7;function vM(){return xm.init()}function SM(){return xm.isReady}function kM(){xm.loadMeshShader()}function xM(e,t,n,s,i,r,o,l){return xm.draw(e,t,n,s,i,r,o,l)}var qi={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function im(e,t){if(!t)return;let n=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,s),e.clip(i)}class Am{matrix=null;isModifyingCurrentTransform(){return!1}getPattern(){Dn("Abstract method `getPattern` called.")}}class Z7 extends Am{constructor(e){super();this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7]}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type==="radial"}areConic(){if(!this.isRadial())return!1;let e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let n,s=this._p0,i=this._p1;if(t)s=s.slice(),i=i.slice(),ct.applyTransform(s,t),ct.applyTransform(i,t);if(this._type==="axial")n=e.createLinearGradient(s[0],s[1],i[0],i[1]);else if(this._type==="radial"){let r=this._r0,o=this._r1;if(t){let l=new Float32Array(2);ct.singularValueDecompose2dScale(t,l),r*=l[0],o*=l[0]}n=e.createRadialGradient(s[0],s[1],r,i[0],i[1],o)}for(let r of this._colorStops)n.addColorStop(r[0],r[1]);return n}_createReversedGradient(e,t=null){let n=this._p1,s=this._p0;if(t)n=n.slice(),s=s.slice(),ct.applyTransform(n,t),ct.applyTransform(s,t);let i=this._r1,r=this._r0;if(t){let c=new Float32Array(2);ct.singularValueDecompose2dScale(t,c),i*=c[0],r*=c[0]}let o=e.createRadialGradient(n[0],n[1],i,s[0],s[1],r),l=this._colorStops.map(([c,h])=>[1-c,h]).reverse();for(let[c,h]of l)o.addColorStop(c,h);return o}getPattern(e,t,n,s){let i;if(s===qi.STROKE||s===qi.FILL){if(this.isOriginBased()){let m=ct.transform(n,t.baseTransform);if(this.matrix)m=ct.transform(m,this.matrix);let p=0.001,b=Math.hypot(m[0],m[1]),v=Math.hypot(m[2],m[3]),k=(m[0]*m[2]+m[1]*m[3])/(b*v);if(Math.abs(k)<p)if(this.isRadial()){if(Math.abs(b-v)<p)return this._createGradient(e,m)}else return this._createGradient(e,m)}let r=t.current.getClippedPathBoundingBox(s,ds(e))||[0,0,0,0],o=Math.ceil(r[2]-r[0])||1,l=Math.ceil(r[3]-r[1])||1,c=t.canvasFactory.create(o,l),h=c.context;if(h.clearRect(0,0,h.canvas.width,h.canvas.height),h.beginPath(),h.rect(0,0,h.canvas.width,h.canvas.height),h.translate(-r[0],-r[1]),n=ct.transform(n,[1,0,0,1,r[0],r[1]]),h.transform(...t.baseTransform),this.matrix)h.transform(...this.matrix);if(im(h,this._bbox),this.areConic())h.fillStyle=this._createReversedGradient(h),h.fill();h.fillStyle=this._createGradient(h),h.fill(),i=e.createPattern(c.canvas,"no-repeat"),t.canvasFactory.destroy(c);let d=new DOMMatrix(n);i.setTransform(d)}else{if(this.areConic())e.save(),im(e,this._bbox),e.fillStyle=this._createReversedGradient(e),e.fillRect(-10000000000,-10000000000,20000000000,20000000000),e.restore();im(e,this._bbox),i=this._createGradient(e)}return i}}function AM(e,t,n,s,i,r,o,l){let{coords:c,colors:h}=t,d=e.data,m=e.width*4,p;if(c[n*2+1]>c[s*2+1])p=n,n=s,s=p,p=r,r=o,o=p;if(c[s*2+1]>c[i*2+1])p=s,s=i,i=p,p=o,o=l,l=p;if(c[n*2+1]>c[s*2+1])p=n,n=s,s=p,p=r,r=o,o=p;let b=(c[n*2]+t.offsetX)*t.scaleX,v=(c[n*2+1]+t.offsetY)*t.scaleY,k=(c[s*2]+t.offsetX)*t.scaleX,A=(c[s*2+1]+t.offsetY)*t.scaleY,T=(c[i*2]+t.offsetX)*t.scaleX,E=(c[i*2+1]+t.offsetY)*t.scaleY;if(v>=E)return;let I=h[r*4],_=h[r*4+1],q=h[r*4+2],P=h[o*4],N=h[o*4+1],H=h[o*4+2],V=h[l*4],U=h[l*4+1],W=h[l*4+2],ce=Math.round(v),ue=Math.round(E),oe,ae,te,me,he,we,be,ye;for(let Te=ce;Te<=ue;Te++){if(Te<A){let xt=Te<v?0:(v-Te)/(v-A);oe=b-(b-k)*xt,ae=I-(I-P)*xt,te=_-(_-N)*xt,me=q-(q-H)*xt}else{let xt;if(Te>E)xt=1;else if(A===E)xt=0;else xt=(A-Te)/(A-E);oe=k-(k-T)*xt,ae=P-(P-V)*xt,te=N-(N-U)*xt,me=H-(H-W)*xt}let Oe;if(Te<v)Oe=0;else if(Te>E)Oe=1;else Oe=(v-Te)/(v-E);he=b-(b-T)*Oe,we=I-(I-V)*Oe,be=_-(_-U)*Oe,ye=q-(q-W)*Oe;let st=Math.round(Math.min(oe,he)),We=Math.round(Math.max(oe,he)),wt=m*Te+st*4;for(let xt=st;xt<=We;xt++){if(Oe=(oe-xt)/(oe-he),Oe<0)Oe=0;else if(Oe>1)Oe=1;d[wt++]=ae-(ae-we)*Oe|0,d[wt++]=te-(te-be)*Oe|0,d[wt++]=me-(me-ye)*Oe|0,d[wt++]=255}}}class eS extends Am{constructor(e){super();this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],kM()}_createMeshCanvas(e,t,n){let o=Math.floor(this._bounds[0]),l=Math.floor(this._bounds[1]),c=Math.ceil(this._bounds[2])-o,h=Math.ceil(this._bounds[3])-l,d=Math.min(Math.ceil(Math.abs(c*e[0]*1.1)),3000)||1,m=Math.min(Math.ceil(Math.abs(h*e[1]*1.1)),3000)||1,p=c?c/d:1,b=h?h/m:1,v={coords:this._posData,colors:this._colData,offsetX:-o,offsetY:-l,scaleX:1/p,scaleY:1/b},k=d+4,A=m+4,T=n.create(k,A);if(SM()&&this._vertexCount>48)T.context.drawImage(xM(this._posData,this._colData,this._vertexCount,v,t,k,A,2),0,0);else{let E=T.context.createImageData(d,m);if(t){let I=E.data;for(let _=0,q=I.length;_<q;_+=4)I[_]=t[0],I[_+1]=t[1],I[_+2]=t[2],I[_+3]=255}for(let I=0,_=this._vertexCount;I<_;I+=3)AM(E,v,I,I+1,I+2,I,I+1,I+2);T.context.putImageData(E,2,2)}return{canvas:T.canvas,offsetX:o-2*p,offsetY:l-2*b,scaleX:p,scaleY:b}}isModifyingCurrentTransform(){return!0}getPattern(e,t,n,s){im(e,this._bbox);let i=new Float32Array(2);if(s===qi.SHADING)ct.singularValueDecompose2dScale(ds(e),i);else if(this.matrix){ct.singularValueDecompose2dScale(this.matrix,i);let[l,c]=i;ct.singularValueDecompose2dScale(t.baseTransform,i),i[0]*=l,i[1]*=c}else ct.singularValueDecompose2dScale(t.baseTransform,i);let r=this._createMeshCanvas(i,s===qi.SHADING?null:this._background,t.canvasFactory);if(s!==qi.SHADING){if(e.setTransform(...t.baseTransform),this.matrix)e.transform(...this.matrix)}e.translate(r.offsetX,r.offsetY),e.scale(r.scaleX,r.scaleY);let o=e.createPattern(r.canvas,"no-repeat");return t.canvasFactory.destroy(r),o}}class tS extends Am{getPattern(){return"hotpink"}}function TM(e){switch(e[0]){case"RadialAxial":return new Z7(e);case"Mesh":return new eS(e);case"Dummy":return new tS}throw Error(`Unknown IR type: ${e[0]}`)}var o7={COLORED:1,UNCOLORED:2};class su{static MAX_PATTERN_SIZE=3000;constructor(e,t,n,s){this.color=e[1],this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.needsIsolation=e[9]??!0,this.ctx=t,this.canvasGraphicsFactory=n,this.baseTransform=s,this.patternBaseMatrix=this.matrix?ct.transform(s,this.matrix):s}canSkipPatternCanvas([e,t,n,s]){let[i,r,o,l]=this.bbox,c=Math.abs(this.xstep),h=Math.abs(this.ystep);if(e>c+0.000001||t>h+0.000001)return null;let d=Math.floor((n-o)/c)+1,m=Math.ceil((n+e-i)/c)-1,p=Math.floor((s-l)/h)+1,b=Math.ceil((s+t-r)/h)-1;return m<=d&&b<=p?[d,p]:null}updatePatternDims(e,t){let n=ct.inverseTransform(this.patternBaseMatrix),s=[e[0],e[1]],i=[e[2],e[3]];ct.applyTransform(s,n),ct.applyTransform(i,n),t[0]=Math.abs(i[0]-s[0]),t[1]=Math.abs(i[1]-s[1]),t[2]=Math.min(s[0],i[0]),t[3]=Math.min(s[1],i[1])}_renderTileCanvas(e,t,n,s){let[i,r,o,l]=this.bbox,c=e.canvasFactory.create(n.size,s.size),h=c.context,d=this.canvasGraphicsFactory.createCanvasGraphics(h,t);return d.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(d,this.paintType,this.color),h.translate(-n.scale*i,-s.scale*r),d.transform(0,n.scale,0,0,s.scale,0,0),h.save(),d.dependencyTracker?.save(),this.clipBbox(d,i,r,o,l),d.baseTransform=ds(d.ctx),d.executeOperatorList(this.operatorList),d.endDrawing(),d.dependencyTracker?.restore(),h.restore(),c}_getCombinedScales(){let e=new Float32Array(2);ct.singularValueDecompose2dScale(this.matrix,e);let[t,n]=e;return ct.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],n*e[1]]}drawPattern(e,t,n=!1,[s,i],r){let[o,l,c,h]=this.bbox,d=e.dependencyTracker;if(d)e.dependencyTracker=new ou(d,r);if(e.save(),n)e.ctx.clip(t,"evenodd");else e.ctx.clip(t);if(e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(s*this.xstep,i*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!=="source-over"||e.inSMaskMode){let m=c-o,p=h-l,[b,v]=this._getCombinedScales(),k=this.getSizeAndScale(m,this.ctx.canvas.width,b),A=this.getSizeAndScale(p,this.ctx.canvas.height,v),T=this._renderTileCanvas(e,r,k,A);e.ctx.drawImage(T.canvas,o,l,m,p),e.canvasFactory.destroy(T)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,o,l,c,h),e.baseTransformStack.push(e.baseTransform),e.baseTransform=ds(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();if(e.restore(),d)e.dependencyTracker=d}createPatternCanvas(e,t){let[n,s,i,r]=this.bbox,o=i-n,l=r-s,{xstep:c,ystep:h}=this;c=Math.abs(c),h=Math.abs(h),wm("TilingType: "+this.tilingType);let[d,m]=this._getCombinedScales(),p=o,b=l,v=!1,k=!1;if(Math.ceil(c*d)>=Math.ceil(o*d))p=c;else v=!0;if(Math.ceil(h*m)>=Math.ceil(l*m))b=h;else k=!0;let A=this.getSizeAndScale(p,this.ctx.canvas.width,d),T=this.getSizeAndScale(b,this.ctx.canvas.height,m),E=this._renderTileCanvas(e,t,A,T);if(v||k){let I=E.canvas;if(v)p=c;if(k)b=h;let _=this.getSizeAndScale(p,this.ctx.canvas.width,d),q=this.getSizeAndScale(b,this.ctx.canvas.height,m),P=_.size,N=q.size,H=e.canvasFactory.create(P,N),V=H.context,U=v?Math.floor(o/c):0,W=k?Math.floor(l/h):0;for(let ce=0;ce<=U;ce++)for(let ue=0;ue<=W;ue++)V.drawImage(I,P*ce,N*ue,P,N,0,0,P,N);return e.canvasFactory.destroy(E),{canvas:H.canvas,canvasEntry:H,scaleX:_.scale,scaleY:q.scale,offsetX:n,offsetY:s}}return{canvas:E.canvas,canvasEntry:E,scaleX:A.scale,scaleY:T.scale,offsetX:n,offsetY:s}}getSizeAndScale(e,t,n){let s=Math.max(su.MAX_PATTERN_SIZE,t),i=Math.ceil(e*n);if(i>=s)i=s;else n=i/e;return{scale:n,size:i}}clipBbox(e,t,n,s,i){let r=s-t,o=i-n,l=new Path2D;l.rect(t,n,r,o),ct.axialAlignedBoundingBox([t,n,s,i],ds(e.ctx),e.current.minMax),e.ctx.clip(l),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,n){let{ctx:s,current:i}=e;switch(i.patternFill=i.patternStroke=!1,t){case o7.COLORED:let{fillStyle:r,strokeStyle:o}=this.ctx;s.fillStyle=i.fillColor=r,s.strokeStyle=i.strokeColor=o;break;case o7.UNCOLORED:s.fillStyle=s.strokeStyle=n,i.fillColor=i.strokeColor=n;break;default:throw new k7(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,n,s,i){let r=s!==qi.SHADING?ct.transform(n,this.patternBaseMatrix):n,o=this.createPatternCanvas(t,i),l=new DOMMatrix(r);l=l.translate(o.offsetX,o.offsetY),l=l.scale(1/o.scaleX,1/o.scaleY);let c=e.createPattern(o.canvas,"repeat");return t.canvasFactory.destroy(o.canvasEntry),c.setTransform(l),c}}var EM=16,CM=100,jM=15,l7=10,tr=16,xr=new Float32Array(2);function c7(e,t){if(e._removeMirroring)throw Error("Context is already forwarding operations.");let n=new Map;for(let s of["save","restore","rotate","scale","translate","transform","setTransform","resetTransform","clip","moveTo","lineTo","bezierCurveTo","quadraticCurveTo","arc","arcTo","ellipse","rect","roundRect","closePath","beginPath"]){let i=e[s];if(typeof i!=="function"||typeof t[s]!=="function")continue;n.set(s,i),e[s]=function(...r){return t[s](...r),i.apply(this,r)}}e._removeMirroring=()=>{for(let[s,i]of n)e[s]=i;delete e._removeMirroring}}function K0(e,t,n,s,i,r,o,l,c,h){let[d,m,p,b,v,k]=ds(e);if(m===0&&p===0){let E=o*d+v,I=Math.round(E),_=l*b+k,q=Math.round(_),P=(o+c)*d+v,N=Math.abs(Math.round(P)-I)||1,H=(l+h)*b+k,V=Math.abs(Math.round(H)-q)||1;return e.setTransform(Math.sign(d),0,0,Math.sign(b),I,q),e.drawImage(t,n,s,i,r,0,0,N,V),e.setTransform(d,m,p,b,v,k),[N,V]}if(d===0&&b===0){let E=l*p+v,I=Math.round(E),_=o*m+k,q=Math.round(_),P=(l+h)*p+v,N=Math.abs(Math.round(P)-I)||1,H=(o+c)*m+k,V=Math.abs(Math.round(H)-q)||1;return e.setTransform(0,Math.sign(m),Math.sign(p),0,I,q),e.drawImage(t,n,s,i,r,0,0,V,N),e.setTransform(d,m,p,b,v,k),[V,N]}e.drawImage(t,n,s,i,r,o,l,c,h);let A=Math.hypot(d,m),T=Math.hypot(p,b);return[A*c,T*h]}class t2{alphaIsShape=!1;fontSize=0;fontSizeScale=1;textMatrix=null;textMatrixScale=1;fontMatrix=Vb;leading=0;x=0;y=0;lineX=0;lineY=0;charSpacing=0;wordSpacing=0;textHScale=1;textRenderingMode=ni.FILL;textRise=0;fillColor="#000000";strokeColor="#000000";tilingPatternDims=null;patternFill=!1;patternStroke=!1;fillAlpha=1;strokeAlpha=1;lineWidth=1;activeSMask=null;transferMaps="none";minMax=Yl.slice();constructor(e,t){this.clipBox=new Float32Array([0,0,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=this.tilingPatternDims?.slice(),e}getPathBoundingBox(e=qi.FILL,t=null){let n=this.minMax.slice();if(e===qi.STROKE){if(!t)Dn("Stroke bounding box must include transform.");ct.singularValueDecompose2dScale(t,xr);let s=xr[0]*this.lineWidth/2,i=xr[1]*this.lineWidth/2;n[0]-=s,n[1]-=i,n[2]+=s,n[3]+=i}return n}updateClipFromPath(){let e=ct.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(Yl,0)}getClippedPathBoundingBox(e=qi.FILL,t=null){return ct.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function f7(e,t){let{width:n,height:s,kind:i}=t,r=s%tr,o=(s-r)/tr,l=r===0?o:o+1,c=e.createImageData(n,tr),h=0,d=t.data,m=c.data,p;if(i===nm.GRAYSCALE_1BPP)for(p=0;p<l;p++)({srcPos:h}=Q7({src:d,srcPos:h,dest:m,width:n,height:p<o?tr:r})),e.putImageData(c,0,p*tr);else if(i===nm.RGBA_32BPP){let b=0,v=n*tr*4;for(p=0;p<o;p++)m.set(d.subarray(h,h+v)),h+=v,e.putImageData(c,0,b),b+=tr;if(p<l)v=n*r*4,m.set(d.subarray(h,h+v)),e.putImageData(c,0,b)}else if(i===nm.RGB_24BPP)for(p=0;p<l;p++)({srcPos:h}=wM({src:d,srcPos:h,dest:new Uint32Array(m.buffer),width:n,height:p<o?tr:r})),e.putImageData(c,0,p*tr);else throw Error(`bad image kind: ${i}`)}function h7(e,t){if(t.bitmap){e.drawImage(t.bitmap,0,0);return}let{width:n,height:s}=t,i=s%tr,r=(s-i)/tr,o=i===0?r:r+1,l=e.createImageData(n,tr),c=0,h=t.data,d=l.data;for(let m=0;m<o;m++)({srcPos:c}=Q7({src:h,srcPos:c,dest:d,width:n,height:m<r?tr:i,nonBlackColor:0})),e.putImageData(l,0,m*tr)}function Xl(e,t){let n=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let s of n)if(e[s]!==void 0)t[s]=e[s];if(e.setLineDash!==void 0)t.setLineDash(e.getLineDash()),t.lineDashOffset=e.lineDashOffset}function Q0(e){if(e.strokeStyle=e.fillStyle="#000000",e.fillRule="nonzero",e.globalAlpha=1,e.lineWidth=1,e.lineCap="butt",e.lineJoin="miter",e.miterLimit=10,e.globalCompositeOperation="source-over",e.font="10px sans-serif",e.setLineDash!==void 0)e.setLineDash([]),e.lineDashOffset=0;let{filter:t}=e;if(t!=="none"&&t!=="")e.filter="none"}function u7(e,t){if(t)return!0;ct.singularValueDecompose2dScale(e,xr);let n=Math.fround(fa.pixelRatio*nc.PDF_TO_CSS_UNITS);return xr[0]<=n&&xr[1]<=n}var _M=["butt","round","square"],IM=["miter","round","bevel"],RM={},d7={};class Jl{static#e=null;#t=0;#n=0;#s=null;#i=null;#a=null;#r=null;#o=1;#l;#c=null;#u=[];constructor(e,t,n,s,i,{optionalContentConfig:r,markedContentStack:o=null},l,c,h,d){this.ctx=e,this.current=new t2(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=t,this.objs=n,this.canvasFactory=s,this.filterFactory=i,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=r,this.cachedPatterns=new Map,this.annotationCanvasMap=l,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=h??null,this.imagesTracker=d??null}getObject(e,t,n=null){if(typeof t==="string")return this.dependencyTracker?.recordNamedDependency(e,t),t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t);return n}beginDrawing({transform:e,viewport:t,transparency:n=!1,background:s=null}){let i=this.ctx.canvas.width,r=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=s||"#ffffff",this.ctx.fillRect(0,0,i,r),this.ctx.fillStyle=o,n){let l=this.transparentCanvasEntry=this.canvasFactory.create(i,r);this.compositeCtx=this.ctx,{canvas:this.transparentCanvas,context:this.ctx}=l,this.ctx.save(),this.ctx.transform(...ds(this.compositeCtx))}if(this.ctx.save(),Q0(this.ctx),e)this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[3];this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=ds(this.ctx)}executeOperatorList(e,t,n,s,i){let{argsArray:r,fnArray:o}=e,l=t||0,c=r.length;if(c===l)return l;let h=c-l>l7&&typeof n==="function",d=h?Date.now()+jM:0,m=0,p=this.commonObjs,b=this.objs,v,k;while(!0){if(s!==void 0){if(l===s.nextBreakPoint)return s.breakIt(l,n),l;if(s.shouldSkip(l)){if(++l===c)return l;continue}}if(!i||i(l))if(v=o[l],k=r[l]??null,v!==za.dependency)if(k===null)this[v](l);else this[v](l,...k);else for(let A of k){this.dependencyTracker?.recordNamedData(A,l);let T=A.startsWith("g_")?p:b;if(!T.has(A))return T.get(A,n),l}if(l++,l===c)return l;if(h&&++m>l7){if(Date.now()>d)return n(),l;m=0}}}#h(){while(this.stateStack.length||this.inSMaskMode)this.restore();if(this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas)this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null}endDrawing(){this.#h();for(let e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0;for(let e of this.#u)this.#v(e);this.#u.length=0,this.#s=null,this.#i=null,this.#a=null,this.#r=null,this.#o=1,this.#c=null,this.#n=0,this.#t=0,this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)t.width=t.height=0;e.clear()}this._cachedBitmapsMap.clear(),this.#d()}#d(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,s=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),r=Math.max(Math.hypot(t[2],t[3]),1),o=[],l=i,c=r,h=n,d=s;while(l>2&&h>1||c>2&&d>1){let A=h,T=d;if(l>2&&h>1)A=Math.ceil(h/2),l/=h/A;if(c>2&&d>1)T=Math.ceil(d/2),c/=d/T;o.push({newWidth:A,newHeight:T}),h=A,d=T}if(o.length===0)return{img:e,paintWidth:n,paintHeight:s,tmpCanvas:null};if(o.length===1){let{newWidth:A,newHeight:T}=o[0],E=this.canvasFactory.create(A,T);return E.context.drawImage(e,0,0,n,s,0,0,A,T),{img:E.canvas,paintWidth:A,paintHeight:T,tmpCanvas:E}}let m=this.canvasFactory.create(1,1),p=this.canvasFactory.create(1,1),b=n,v=s,k=e;for(let{newWidth:A,newHeight:T}of o)this.canvasFactory.reset(p,A,T),p.context.drawImage(k,0,0,b,v,0,0,A,T),[m,p]=[p,m],k=m.canvas,b=A,v=T;return this.canvasFactory.destroy(p),{img:m.canvas,paintWidth:b,paintHeight:v,tmpCanvas:m}}_createMaskCanvas(e,t){let n=this.ctx,{width:s,height:i}=t,r=this.current.fillColor,o=this.current.patternFill,l=ds(n),c,h,d,m;if((t.bitmap||t.data)&&t.count>1){let U=t.bitmap||t.data.buffer;h=JSON.stringify(o?l:[l.slice(0,4),r]),c=this._cachedBitmapsMap.getOrInsertComputed(U,s2);let W=c.get(h);if(W&&!o){let ce=Math.round(Math.min(l[0],l[2])+l[4]),ue=Math.round(Math.min(l[1],l[3])+l[5]);return this.dependencyTracker?.recordDependencies(e,Hr.transformAndFill),{canvas:W,offsetX:ce,offsetY:ue}}d=W}if(!d)m=this.canvasFactory.create(s,i),h7(m.context,t);let p=ct.transform(l,[1/s,0,0,-1/i,0,0]);p=ct.transform(p,[1,0,0,1,0,-i]);let b=Yl.slice();ct.axialAlignedBoundingBox([0,0,s,i],p,b);let[v,k,A,T]=b,E=Math.round(A-v)||1,I=Math.round(T-k)||1,_=this.canvasFactory.create(E,I),q=_.context,P=v,N=k;q.translate(-P,-N),q.transform(...p);let H=null;if(!d){let U=this._scaleImage(m.canvas,Ba(q));if(d=U.img,H=U.tmpCanvas,d!==m.canvas)this.canvasFactory.destroy(m),m=null;if(c&&o)c.set(h,d),H=null,m=null}if(q.imageSmoothingEnabled=u7(ds(q),t.interpolate),K0(q,d,0,0,d.width,d.height,0,0,s,i),H)this.canvasFactory.destroy(H);if(m)this.canvasFactory.destroy(m);q.globalCompositeOperation="source-in";let V=ct.transform(Ba(q),[1,0,0,1,-P,-N]);if(q.fillStyle=o?r.getPattern(n,this,V,qi.FILL,e):r,q.fillRect(0,0,s,i),c&&!o)c.set(h,_.canvas);return this.dependencyTracker?.recordDependencies(e,Hr.transformAndFill),{canvas:_.canvas,canvasEntry:c&&!o?null:_,offsetX:Math.round(P),offsetY:Math.round(N)}}setLineWidth(e,t){if(this.dependencyTracker?.recordSimpleData("lineWidth",e),t!==this.current.lineWidth)this._cachedScaleForStroking[0]=-1;this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){this.dependencyTracker?.recordSimpleData("lineCap",e),this.ctx.lineCap=_M[t]}setLineJoin(e,t){this.dependencyTracker?.recordSimpleData("lineJoin",e),this.ctx.lineJoin=IM[t]}setMiterLimit(e,t){this.dependencyTracker?.recordSimpleData("miterLimit",e),this.ctx.miterLimit=t}setDash(e,t,n){this.dependencyTracker?.recordSimpleData("dash",e);let s=this.ctx;if(s.setLineDash!==void 0)s.setLineDash(t),s.lineDashOffset=n}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){for(let[n,s]of t)switch(n){case"LW":this.setLineWidth(e,s);break;case"LC":this.setLineCap(e,s);break;case"LJ":this.setLineJoin(e,s);break;case"ML":this.setMiterLimit(e,s);break;case"D":this.setDash(e,s[0],s[1]);break;case"RI":this.setRenderingIntent(e,s);break;case"FL":this.setFlatness(e,s);break;case"Font":this.setFont(e,s[0],s[1]);break;case"CA":this.dependencyTracker?.recordSimpleData("strokeAlpha",e),this.current.strokeAlpha=s;break;case"ca":this.dependencyTracker?.recordSimpleData("fillAlpha",e),this.ctx.globalAlpha=this.current.fillAlpha=s;break;case"BM":this.dependencyTracker?.recordSimpleData("globalCompositeOperation",e),this.ctx.globalCompositeOperation=s;break;case"SMask":if(this.dependencyTracker?.recordSimpleData("SMask",e),this.current.activeSMask=s?this.tempSMask:null,this.current.activeSMask)this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation;this.tempSMask=null,this.checkSMaskState(e);break;case"TR":this.dependencyTracker?.recordSimpleData("filter",e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){if(this.smaskPreparedEntry)this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null;this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.smaskPreparedOOBAlpha=null}_ensurePreparedSMask(e){if(e===this.smaskPreparedFor)return;this._clearPreparedSMask(),this._prepareSMaskCanvas(e)}checkSMaskState(e){let t=this.inSMaskMode;if(this.current.activeSMask&&!t)this.beginSMaskMode(e);else if(!this.current.activeSMask&&t)this.endSMaskMode();else if(this.current.activeSMask&&t)this._ensurePreparedSMask(this.current.activeSMask)}_prepareSMaskCanvas(e){let{canvas:t,subtype:n,backdrop:s,transferMap:i}=e,r=n==="Luminosity"||n==="Alpha"&&i;if(!r&&!(n==="Luminosity"&&s)){this.smaskPreparedFor=e;return}let o;if(n==="Luminosity"&&s){let[T,E,I]=uu(s),_=Math.round(0.3*T+0.59*E+0.11*I);o=i?.[_]??_}else o=i?.[0]??0;let l=4,{width:c,height:h}=this.ctx.canvas,d=t.width*t.height,m=c*h<l*d,p=r?{url:n==="Alpha"?this.filterFactory.addAlphaFilter(i):this.filterFactory.addLuminosityFilter(i),subtype:n,transferMap:i}:null,b=n==="Luminosity"?s:null,v,k,A;if(m)v=this._bakeSMaskCanvas(t,e.offsetX,e.offsetY,c,h,b,p),k=0,A=0;else v=this._bakeSMaskCanvas(t,0,0,t.width,t.height,b,p),k=e.offsetX,A=e.offsetY;this.smaskPreparedEntry=v,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=k,this.smaskPreparedOffsetY=A,this.smaskPreparedOOBAlpha=!m&&o!==0?o:null}_bakeSMaskCanvas(e,t,n,s,i,r,o){if(!r&&!o)Dn("_bakeSMaskCanvas with neither backdrop nor filter");let l=this.canvasFactory.create(s,i),c=l.context;if(c.drawImage(e,t,n),r)c.globalCompositeOperation="destination-atop",c.fillStyle=r,c.fillRect(0,0,s,i);if(!o)return l;let h=this.canvasFactory.create(s,i),d=h.context;d.filter=o.url;let m=Wn.isCanvasFilterSupported&&d.filter!=="none"&&d.filter!=="";if(d.drawImage(l.canvas,0,0),Wn.isCanvasFilterSupported)d.filter="none";if(!m){let p=d.getImageData(0,0,s,i),{data:b}=p,{transferMap:v}=o;if(o.subtype==="Luminosity")for(let k=0,A=b.length;k<A;k+=4){let T=0.3*b[k]+0.59*b[k+1]+0.11*b[k+2]+0.5|0;b[k]=b[k+1]=b[k+2]=0,b[k+3]=v?.[T]??T}else for(let k=3,A=b.length;k<A;k+=4)b[k]=v[b[k]];d.putImageData(p,0,0)}return this.canvasFactory.destroy(l),h}beginSMaskMode(e){if(this.inSMaskMode)throw Error("beginSMaskMode called while already in smask mode");let{width:t,height:n}=this.ctx.canvas,s=this.canvasFactory.create(t,n);this.smaskScratchCanvas=s,this.suspendedCtx=this.ctx;let i=this.ctx=s.context;i.setTransform(this.suspendedCtx.getTransform()),Xl(this.suspendedCtx,i),c7(i,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask),this.setGState(e,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),Xl(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}#p(e,t=null,n=1){let{width:s,height:i}=e,r=t??this.canvasFactory.create(s,i),o=r.context;n=Math.round(n*255)/255;let l=n<1;if(l&&this.#l===void 0)this.#l=Wn.isCanvasFilterSupported?new Map:"none";let c="none";if(l&&this.#l instanceof Map)c=this.#l.getOrInsertComputed(n,()=>this.filterFactory.addKnockoutFilter(n));if(!l||c!=="none"){if(t)o.save(),o.setTransform(1,0,0,1,0,0),o.clearRect(0,0,s,i),o.restore();return o.filter=c,o.drawImage(e,0,0),o.filter="none",r}let h=e.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,s,i),d=o.createImageData(s,i),m=h.data,p=d.data,b=n>0?1/n:1e6;for(let v=3,k=m.length;v<k;v+=4)p[v]=Math.min(Math.round(m[v]*b),255);return o.putImageData(d,0,0),r}#g(e,t,n,s){let i=e?.[t]??null;if(i&&(i.canvas.width!==n||i.canvas.height!==s))this.canvasFactory.destroy(i),i=null;if(!i){if(i=this.canvasFactory.create(n,s),e)e[t]=i;return i}let r=i.context;return r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,n,s),r.restore(),i}#f(e,t,n={}){let{backdropCanvas:s=null,destTransform:i=[1,0,0,1,0,0],backdropOffset:r=[0,0],reuseMaskEntry:o=null,poolMeta:l=null,sourceAlpha:c=1,sourceFilter:h="none",knockoutAlpha:d=1}=n,{width:m,height:p}=t,b=this.#p(t,o,d),v=e.globalCompositeOperation;if(e.save(),e.setTransform(...i),e.globalAlpha=1,Wn.isCanvasFilterSupported)e.filter="none";if(e.globalCompositeOperation="destination-out",e.drawImage(b.canvas,0,0),s){let[k,A]=r,T=this.#g(l,"knockoutBackdropEntry",m,p),E=T.context;if(E.drawImage(s,k,A,m,p,0,0,m,p),E.globalCompositeOperation="destination-in",E.drawImage(b.canvas,0,0),E.globalCompositeOperation="source-over",e.globalCompositeOperation="destination-over",e.drawImage(T.canvas,0,0),!l)this.canvasFactory.destroy(T)}if(e.globalCompositeOperation=v,e.globalAlpha=c,Wn.isCanvasFilterSupported)e.filter=h??"none";if(e.drawImage(t,0,0),e.restore(),!o)this.canvasFactory.destroy(b)}#m(e=1){if(this.#t===0||this.#n>0||!this.contentVisible)return!1;this.#n++,this.#o=e;let t=this.#u.at(-1),{canvas:n}=this.ctx,s=this.#g(t,"knockoutTempEntry",n.width,n.height);this.#s=s;let i=s.context;if(i.save(),i.setTransform(this.ctx.getTransform()),Xl(this.ctx,i),this.#r=i.globalCompositeOperation,i.globalCompositeOperation="source-over",c7(i,this.ctx),this.#c=t,this.#i=this.ctx,this.#a=this.suspendedCtx,this.ctx=i,this.inSMaskMode)this.suspendedCtx=i;return!0}#b(e){if(!e)return;let t=this.#s,n=this.#i,s=this.#a,i=t.context;if(this.#s=null,this.#i=null,this.#a=null,this.inSMaskMode&&this.suspendedCtx===i&&this.ctx!==i)this.endSMaskMode();if(this.inSMaskMode)this.suspendedCtx=s;this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=this.#r,this.#r=null,Xl(this.ctx,n),this.ctx=n;let r=this.#c;this.#c=null;let o=this.#o;this.#o=1;try{this.#f(s??n,t.canvas,{backdropCanvas:r?.backdropCtx?.canvas??null,backdropOffset:r?.backdropCtx?[r.offsetX,r.offsetY]:[0,0],reuseMaskEntry:r?.knockoutMaskEntry??null,poolMeta:r,knockoutAlpha:o})}finally{if(i.restore(),this.#n--,!r)this.canvasFactory.destroy(t)}}compose(e){if(!this.current.activeSMask)return;e=e?[Math.floor(e[0]),Math.floor(e[1]),Math.ceil(e[2]),Math.ceil(e[3])]:[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx,s=this.#n>0&&n===this.ctx;if(this.composeSMask(s?null:n,t,this.ctx,e),s)return;this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(e,t,n,s){let i=s[0],r=s[1],o=s[2]-i,l=s[3]-r;if(o===0||l===0)return;let c=this.smaskPreparedEntry;if(c){let h=i,d=r,m=o,p=l,b=this.smaskPreparedOOBAlpha,v=b!==null;if(v){h=Math.max(i,t.offsetX),d=Math.max(r,t.offsetY);let k=Math.min(i+o,t.offsetX+t.canvas.width),A=Math.min(r+l,t.offsetY+t.canvas.height);m=k-h,p=A-d}if(m>0&&p>0){let k=h-this.smaskPreparedOffsetX,A=d-this.smaskPreparedOffsetY;n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0);let T=new Path2D;T.rect(h,d,m,p),n.clip(T),n.globalCompositeOperation="destination-in",n.drawImage(c.canvas,k,A,m,p,h,d,m,p),n.restore()}if(v&&b<255)this._applySMaskOOBAlpha(n,i,r,o,l,h,d,h+m,d+p,b)}else this.genericComposeSMask(t,n,o,l,i,r);if(!e)return;e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||"source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,i,r,o,l,i,r,o,l),e.restore()}_applySMaskOOBAlpha(e,t,n,s,i,r,o,l,c,h){let d=r<l&&o<c;if(d&&r===t&&o===n&&l===t+s&&c===n+i)return;let m=new Path2D;if(m.rect(t,n,s,i),d)m.rect(r,o,l-r,c-o);e.save(),e.globalAlpha=h/255,e.setTransform(1,0,0,1,0,0),e.clip(m,"evenodd"),e.globalCompositeOperation="destination-in",e.fillStyle="#000000",e.fillRect(t,n,s,i),e.restore()}genericComposeSMask(e,t,n,s,i,r){let{context:o,offsetX:l,offsetY:c}=e;t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);let h=new Path2D;h.rect(i,r,n,s),t.clip(h),t.globalCompositeOperation="destination-in",t.drawImage(o.canvas,i-l,r-c,n,s,i,r,n,s),t.restore()}save(e){if(this.inSMaskMode)Xl(this.ctx,this.suspendedCtx);this.ctx.save();let t=this.current;this.stateStack.push(t),this.current=t.clone(),this.dependencyTracker?.save(e)}restore(e){if(this.dependencyTracker?.restore(e),this.stateStack.length===0){if(this.inSMaskMode)this.endSMaskMode();return}if(this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode)Xl(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform());this.checkSMaskState(e),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(e,t,n,s,i,r,o){this.dependencyTracker?.recordIncrementalData("transform",e),this.ctx.transform(t,n,s,i,r,o),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,n,s){let[i]=n;if(!s){if(i||=n[0]=new Path2D,t!==za.stroke&&t!==za.closeStroke)this.current.tilingPatternDims=null;this[t](e,i);return}if(this.dependencyTracker!==null){let o=t===za.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(e).recordBBox(e,this.ctx,s[0]-o,s[2]+o,s[1]-o,s[3]+o).recordDependencies(e,["transform"])}if(!(i instanceof Path2D))i=n[0]=C7(i);ct.axialAlignedBoundingBox(s,ds(this.ctx),this.current.minMax);let r=this.current.tilingPatternDims;if(r&&t!==za.stroke&&t!==za.closeStroke&&this.current.fillColor instanceof su){let o=ct.intersect(this.current.clipBox,this.current.minMax);if(!o)this.current.tilingPatternDims=null;else this.current.fillColor.updatePatternDims(o,r)}this[t](e,i),this._pathStartIdx=e}closePath(e){this.ctx.closePath()}stroke(e,t,n=!0){let s=n&&this.#m(this.current.strokeAlpha),i=this.ctx,r=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof r==="object"&&r?.getPattern){let o=r.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=r.getPattern(i,this,Ba(i),qi.STROKE,e),o){let l=new Path2D;l.addPath(t,i.getTransform().invertSelf().multiplySelf(o)),t=l}this.rescaleAndStroke(t,!1),i.restore()}else this.rescaleAndStroke(t,!0);if(this.dependencyTracker?.recordDependencies(e,Hr.stroke),n)this.consumePath(e,t,this.current.getClippedPathBoundingBox(qi.STROKE,ds(this.ctx)));i.globalAlpha=this.current.fillAlpha,this.#b(s)}closeStroke(e,t){this.stroke(e,t)}fill(e,t,n=!0){let s=n&&this.#m(this.current.fillAlpha),i=this.ctx,r=this.current.fillColor,o=this.current.patternFill,l=!1,c=this.current.getClippedPathBoundingBox();if(this.dependencyTracker?.recordDependencies(e,Hr.fill),o){let h=this.current.tilingPatternDims,d=h&&r.canSkipPatternCanvas(h);if(d){if(r.drawPattern(this,t,this.pendingEOFill,d,e),this.pendingEOFill=!1,n)this.consumePath(e,t,c);this.current.tilingPatternDims=null,this.#b(s);return}let m=r.isModifyingCurrentTransform()?i.getTransform():null;if(this.dependencyTracker?.save(e),i.save(),i.fillStyle=r.getPattern(i,this,Ba(i),qi.FILL,e),m){let p=new Path2D;p.addPath(t,i.getTransform().invertSelf().multiplySelf(m)),t=p}l=!0}if(this.contentVisible&&c!==null)if(this.pendingEOFill)i.fill(t,"evenodd"),this.pendingEOFill=!1;else i.fill(t);if(l)i.restore(),this.dependencyTracker?.restore(e);if(n)this.consumePath(e,t,c);this.#b(s)}eoFill(e,t){this.pendingEOFill=!0,this.fill(e,t)}fillStroke(e,t){let n=this.#m(Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(e,t,!1),this.stroke(e,t,!1),this.consumePath(e,t),this.#b(n)}eoFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}closeFillStroke(e,t){this.fillStroke(e,t)}closeEOFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}endPath(e,t){this.consumePath(e,t)}rawFillPath(e,t){let n=this.#m(this.current.fillAlpha);this.ctx.fill(t),this.dependencyTracker?.recordDependencies(e,Hr.rawFillPath).recordOperation(e),this.#b(n)}clip(e){this.dependencyTracker?.recordFutureForcedDependency("clipMode",e),this.pendingClip=RM}eoClip(e){this.dependencyTracker?.recordFutureForcedDependency("clipMode",e),this.pendingClip=d7}beginText(e){this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.dependencyTracker?.recordOpenMarker(e).resetIncrementalData("sameLineText").resetIncrementalData("moveText",e)}endText(e){let t=this.pendingTextPaths,n=this.ctx;if(this.dependencyTracker){let{dependencyTracker:s}=this;if(t!==void 0)s.recordFutureForcedDependency("textClip",s.getOpenMarker()).recordFutureForcedDependency("textClip",e);s.recordCloseMarker(e)}if(t!==void 0){let s=new Path2D,i=n.getTransform().invertSelf();for(let{transform:r,x:o,y:l,fontSize:c,path:h}of t){if(!h)continue;s.addPath(h,new DOMMatrix(r).preMultiplySelf(i).translate(o,l).scale(c,-c))}n.clip(s)}delete this.pendingTextPaths}setCharSpacing(e,t){this.dependencyTracker?.recordSimpleData("charSpacing",e),this.current.charSpacing=t}setWordSpacing(e,t){this.dependencyTracker?.recordSimpleData("wordSpacing",e),this.current.wordSpacing=t}setHScale(e,t){this.dependencyTracker?.recordSimpleData("hScale",e),this.current.textHScale=t/100}setLeading(e,t){this.dependencyTracker?.recordSimpleData("leading",e),this.current.leading=-t}setFont(e,t,n){this.dependencyTracker?.recordSimpleData("font",e).recordSimpleDataFromNamed("fontObj",t,e);let s=this.commonObjs.get(t),i=this.current;if(!s)throw Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Vb,i.fontMatrix[0]===0||i.fontMatrix[3]===0)on("Invalid font matrix for font "+t);if(n<0)n=-n,i.fontDirection=-1;else i.fontDirection=1;if(this.current.font=s,this.current.fontSize=n,s.isType3Font)return;let r=s.loadedName||"sans-serif",o=s.systemFontInfo?.css||`"${r}", ${s.fallbackName}`,l="normal";if(s.black)l="900";else if(s.bold)l="bold";let c=s.italic?"italic":"normal",h=bs(n,EM,CM);this.current.fontSizeScale=n/h,this.ctx.font=`${c} ${l} ${h}px ${o}`}setTextRenderingMode(e,t){this.dependencyTracker?.recordSimpleData("textRenderingMode",e),this.current.textRenderingMode=t}setTextRise(e,t){this.dependencyTracker?.recordSimpleData("textRise",e),this.current.textRise=t}moveText(e,t,n){this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText",e),this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(e,t,n){this.setLeading(e,-n),this.moveText(e,t,n)}setTextMatrix(e,t){this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",e);let{current:n}=this;n.textMatrix=t,n.textMatrixScale=Math.hypot(t[0],t[1]),n.x=n.lineX=0,n.y=n.lineY=0}nextLine(e){this.moveText(e,0,this.current.leading),this.dependencyTracker?.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??e)}#w(e,t,n){let s=new Path2D;return s.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),s}paintChar(e,t,n,s,i,r){let o=this.ctx,l=this.current,{font:c,textRenderingMode:h}=l,d=l.fontSize/l.fontSizeScale,m=h&ni.FILL_STROKE_MASK,p=!!(h&ni.ADD_TO_PATH_FLAG),b=l.patternFill&&!c.missingFile,v=l.patternStroke&&!c.missingFile,k;if((c.disableFontFace||p||b||v)&&!c.missingFile)k=c.getPathGenerator(this.commonObjs,t);if(k&&(c.disableFontFace||b||v)){o.save(),o.translate(n,s),o.scale(d,-d),this.dependencyTracker?.recordCharacterBBox(e,o,c);let A;if(m===ni.FILL||m===ni.FILL_STROKE)if(i){A=o.getTransform(),o.setTransform(...i);let T=this.#w(k,A,i);o.fill(T)}else o.fill(k);if(m===ni.STROKE||m===ni.FILL_STROKE)if(r){A||=o.getTransform(),o.setTransform(...r);let{a:T,b:E,c:I,d:_}=A,q=ct.inverseTransform(r),P=ct.transform([T,E,I,_,0,0],q);ct.singularValueDecompose2dScale(P,xr),o.lineWidth*=Math.max(xr[0],xr[1])/d,o.stroke(this.#w(k,A,r))}else o.lineWidth/=d,o.stroke(k);o.restore()}else{if(m===ni.FILL||m===ni.FILL_STROKE)o.fillText(t,n,s),this.dependencyTracker?.recordCharacterBBox(e,o,c,d,n,s,()=>o.measureText(t));if(m===ni.STROKE||m===ni.FILL_STROKE){if(this.dependencyTracker)this.dependencyTracker?.recordCharacterBBox(e,o,c,d,n,s,()=>o.measureText(t)).recordDependencies(e,Hr.stroke);o.strokeText(t,n,s)}}if(p)(this.pendingTextPaths||=[]).push({transform:ds(o),x:n,y:s,fontSize:d,path:k}),this.dependencyTracker?.recordCharacterBBox(e,o,c,d,n,s)}get isFontSubpixelAAEnabled(){let e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText("I",0,10);let n=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let s=!1;for(let i=3;i<n.length;i+=4)if(n[i]>0&&n[i]<255){s=!0;break}return Mt(this,"isFontSubpixelAAEnabled",s)}showText(e,t){if(this.dependencyTracker){if(this.dependencyTracker.recordDependencies(e,Hr.showText).resetBBox(e),this.current.textRenderingMode&ni.ADD_TO_PATH_FLAG)this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies()}let n=this.current,s=n.font;if(s.isType3Font){let W=this.#m(n.fillAlpha);this.showType3Text(e,t),this.dependencyTracker?.recordShowTextOperation(e),this.#b(W);return}let i=n.fontSize;if(i===0){this.dependencyTracker?.recordOperation(e);return}let r=this.#m(n.fillAlpha),o=this.ctx,{fontSizeScale:l,charSpacing:c,wordSpacing:h,fontDirection:d}=n,m=n.textHScale*d,p=t.length,b=s.vertical,v=b?1:-1,k=s.defaultVMetrics,A=i*n.fontMatrix[0],T=n.textRenderingMode===ni.FILL&&!s.disableFontFace&&!n.patternFill;if(o.save(),n.textMatrix)o.transform(...n.textMatrix);if(o.translate(n.x,n.y+n.textRise),d>0)o.scale(m,-1);else o.scale(m,1);let E,I,_=n.textRenderingMode&ni.FILL_STROKE_MASK,q=_===ni.FILL||_===ni.FILL_STROKE,P=_===ni.STROKE||_===ni.FILL_STROKE,{lineWidth:N,textMatrixScale:H}=n;if(H===0||N===0){if(P)N=this.getSinglePixelWidth()}else N/=H;if(l!==1)o.scale(l,l),N/=l;if(o.lineWidth=N,q&&n.patternFill){o.save();let W=n.fillColor.getPattern(o,this,Ba(o),qi.FILL,e);E=ds(o),o.restore(),o.fillStyle=W}if(P&&n.patternStroke){o.save();let W=n.strokeColor.getPattern(o,this,Ba(o),qi.STROKE,e);I=ds(o),o.restore(),o.strokeStyle=W}if(s.isInvalidPDFjsFont){let W=[],ce=0;for(let oe of t)W.push(oe.unicode),ce+=oe.width;let ue=W.join("");if(o.fillText(ue,0,0),this.dependencyTracker!==null){let oe=o.measureText(ue);this.dependencyTracker.recordBBox(e,this.ctx,-oe.actualBoundingBoxLeft,oe.actualBoundingBoxRight,-oe.actualBoundingBoxAscent,oe.actualBoundingBoxDescent).recordShowTextOperation(e)}n.x+=ce*A*m,o.restore(),this.compose(),this.#b(r);return}let V=0,U;for(U=0;U<p;++U){let W=t[U];if(typeof W==="number"){V+=v*W*i/1000;continue}let ce=!1,ue=(W.isSpace?h:0)+c,{fontChar:oe,accent:ae}=W,te,me,he=W.width;if(b){let ye=W.vmetric||k,Te=-(W.vmetric?ye[1]:he*0.5)*A,Oe=ye[2]*A;he=ye?-ye[0]:he,te=Te/l,me=(V+Oe)/l}else te=V/l,me=0;let we;if(s.remeasure&&he>0){we=o.measureText(oe);let ye=we.width*1000/i*l;if(he<ye&&this.isFontSubpixelAAEnabled){let Te=he/ye;ce=!0,o.save(),o.scale(Te,1),te/=Te}else if(he!==ye)te+=(he-ye)/2000*i/l}if(this.contentVisible&&(W.isInFont||s.missingFile)){if(T&&!ae)o.fillText(oe,te,me),this.dependencyTracker?.recordCharacterBBox(e,o,we?{bbox:null}:s,i/l,te,me,()=>we??o.measureText(oe));else if(this.paintChar(e,oe,te,me,E,I),ae){let ye=te+i*ae.offset.x/l,Te=me-i*ae.offset.y/l;this.paintChar(e,ae.fontChar,ye,Te,E,I)}}let be=b?he*A-ue*d:he*A+ue*d;if(V+=be,ce)o.restore()}if(b)n.y-=V;else n.x+=V*m;o.restore(),this.compose(),this.dependencyTracker?.recordShowTextOperation(e),this.#b(r)}showType3Text(e,t){let n=this.ctx,s=this.current,{font:i,fontSize:r,fontDirection:o}=s,l=i.vertical?1:-1,{charSpacing:c,wordSpacing:h}=s,d=s.textHScale*o,m=s.fontMatrix||Vb,p=t.length,b=s.textRenderingMode===ni.INVISIBLE,v,k,A,T;if(b||r===0)return;if(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,n.save(),s.textMatrix)n.transform(...s.textMatrix);n.translate(s.x,s.y+s.textRise),n.scale(d,o);let E=this.dependencyTracker;this.dependencyTracker=E?new ou(E,e):null;for(v=0;v<p;++v){if(k=t[v],typeof k==="number"){T=l*k*r/1000,this.ctx.translate(T,0),s.x+=T*d;continue}let I=(k.isSpace?h:0)+c,_=i.charProcOperatorList.get(k.operatorListId);if(!_)on(`Type3 character "${k.operatorListId}" is not available.`);else if(this.contentVisible){if(this.save(),_.fnArray[0]===za.setCharWidth)s.fillAlpha=s.strokeAlpha=1,n.globalAlpha=1;n.scale(r,r),n.transform(...m),this.executeOperatorList(_),this.restore()}let q=[k.width,0];ct.applyTransform(q,m),A=q[0]*r+I,n.translate(A,0),s.x+=A*d}if(n.restore(),E)this.dependencyTracker=E}setCharWidth(e,t,n){}setCharWidthAndBounds(e,t,n,s,i,r,o){let l=new Path2D;l.rect(s,i,r-s,o-i),this.ctx.clip(l),this.dependencyTracker?.recordBBox(e,this.ctx,s,r,i,o).recordClipBox(e,this.ctx,s,r,i,o),this.endPath(e)}getColorN_Pattern(e,t){let n;if(t[0]==="TilingPattern"){let s=this.baseTransform||ds(this.ctx),i={createCanvasGraphics:(r,o)=>new Jl(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new ou(this.dependencyTracker,o,!0):null)};n=new su(t,this.ctx,i,s)}else n=this._getPattern(e,t[1],t[2]);return n}setStrokeColorN(e,...t){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){this.dependencyTracker?.recordSimpleData("fillColor",e);let n=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=n instanceof su?[0,0,0,0]:null}setStrokeRGBColor(e,t){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){this.dependencyTracker?.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(e,t){this.dependencyTracker?.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){this.dependencyTracker?.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,n=null){let s=this.cachedPatterns.getOrInsertComputed(t,()=>TM(this.getObject(e,t)));if(n)s.matrix=n;return s}shadingFill(e,t){if(!this.contentVisible)return;let n=this.#m(this.current.fillAlpha),s=this.ctx;this.save(e);let i=this._getPattern(e,t);s.fillStyle=i.getPattern(s,this,Ba(s),qi.SHADING,e);let r=Ba(s);if(r){let{width:o,height:l}=s.canvas,c=Yl.slice();ct.axialAlignedBoundingBox([0,0,o,l],r,c);let[h,d,m,p]=c;this.ctx.fillRect(h,d,m-h,p-d)}else this.ctx.fillRect(-10000000000,-10000000000,20000000000,20000000000);this.dependencyTracker?.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,Hr.transform).recordDependencies(e,Hr.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e),this.#b(n)}beginInlineImage(){Dn("Should not call beginInlineImage")}beginImageData(){Dn("Should not call beginImageData")}paintFormXObjectBegin(e,t,n){if(!this.contentVisible)return;if(this.save(e),this.baseTransformStack.push(this.baseTransform),t)this.transform(e,...t);if(this.baseTransform=ds(this.ctx),n){ct.axialAlignedBoundingBox(n,this.baseTransform,this.current.minMax);let[s,i,r,o]=n,l=new Path2D;l.rect(s,i,r-s,o-i),this.ctx.clip(l),this.dependencyTracker?.recordClipBox(e,this.ctx,s,r,i,o),this.endPath(e)}}paintFormXObjectEnd(e){if(!this.contentVisible)return;this.restore(e),this.baseTransform=this.baseTransformStack.pop()}beginGroup(e,t){if(!this.contentVisible)return;this.save(e);let{inSMaskMode:n}=this;if(n)this.endSMaskMode(),this.current.activeSMask=null;let s=this.ctx;if((!t.needsIsolation||!t.isolated&&!t.hasSoftMask)&&!t.knockout&&!t.isGray&&this.#t===0&&s.globalAlpha===1&&s.globalCompositeOperation==="source-over"&&!n){if(t.bbox){let I=new Path2D,[_,q,P,N]=t.bbox;if(I.rect(_,q,P-_,N-q),t.matrix){let H=new Path2D;H.addPath(I,new DOMMatrix(t.matrix)),I=H}s.clip(I)}this.groupStack.push(null),this.#u.push(null),this.groupLevel++;return}if(!t.isolated&&!t.knockout&&this.#t===0)wm("TODO: Fully support non-isolated non-knockout groups.");let i=ds(s);if(t.matrix)s.transform(...t.matrix);let r=[0,0,s.canvas.width,s.canvas.height],o;if(t.bbox)o=Yl.slice(),ct.axialAlignedBoundingBox(t.bbox,ds(s),o),o=ct.intersect(o,r)||[0,0,0,0];else o=r;let l=Math.floor(o[0]),c=Math.floor(o[1]),h=Math.max(Math.ceil(o[2])-l,1),d=Math.max(Math.ceil(o[3])-c,1);this.current.startNewPathAndClipBox([0,0,h,d]);let m=this.canvasFactory.create(h,d);if(t.smask)this.smaskGroupCanvases.push(m);let p=m.context,b=t.knockout&&!t.isolated?s:null,v=!t.isolated&&!t.knockout&&!t.smask&&t.needsIsolation&&this.#t>0,k=t.knockout?this.canvasFactory.create(h,d):null,A=this.#t;if(t.knockout)this.#t++;else this.#t=0;p.translate(-l,-c),p.transform(...i);let T=!t.isolated&&!t.smask&&t.needsIsolation,E=T&&!n&&A===0&&!t.knockout&&!t.isGray&&t.hasSoftMask&&s.globalAlpha===1&&s.globalCompositeOperation==="source-over"&&this.current.transferMaps==="none";if(T&&(n||E))p.save(),p.setTransform(1,0,0,1,0,0),p.drawImage(s.canvas,-l,-c),p.restore();if(t.bbox){let I=new Path2D,[_,q,P,N]=t.bbox;if(I.rect(_,q,P-_,N-q),t.matrix){let H=new Path2D;H.addPath(I,new DOMMatrix(t.matrix)),I=H}p.clip(I)}if(t.smask)this.smaskStack.push({canvas:m.canvas,context:p,offsetX:l,offsetY:c,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null});if(!t.smask||this.dependencyTracker)s.setTransform(1,0,0,1,0,0),s.translate(l,c),s.save();Xl(s,p),this.ctx=p,this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(s),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(s),this.#u.push({backdropCtx:b,savedKnockoutLevel:A,offsetX:l,offsetY:c,hasInnerBackdrop:v,replaceBackdrop:E,knockoutMaskEntry:k,knockoutTempEntry:null,knockoutBackdropEntry:null}),this.groupLevel++}endGroup(e,t){if(!this.contentVisible)return;this.groupLevel--;let n=this.ctx,s=this.groupStack.pop(),i=this.#u.pop();if(i)this.#t=i.savedKnockoutLevel;if(s===null){this.restore(e);return}if(t.isGray)this.#y(n);if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.dependencyTracker?.popBaseTransform(),t.smask){if(this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker){if(this.ctx.restore(),this.inSMaskMode)this.ctx.setTransform(this.suspendedCtx.getTransform())}this.#v(i)}else{this.ctx.restore();let r=ds(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...r);let o=Yl.slice();ct.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],r,o);let l=this.#u.at(-1);if(this.#t>0)if(i.hasInnerBackdrop){let{width:c,height:h}=n.canvas,d=this.canvasFactory.create(c,h),m=d.context;m.drawImage(s.canvas,i.offsetX,i.offsetY,c,h,0,0,c,h),m.globalCompositeOperation="source-over",m.drawImage(n.canvas,0,0);let p=this.#p(n.canvas);m.globalCompositeOperation="destination-in",m.drawImage(p.canvas,0,0);let b=this.ctx.globalCompositeOperation,v=this.ctx.globalAlpha,k=this.ctx.filter;if(this.ctx.save(),this.ctx.setTransform(...r),this.ctx.globalAlpha=1,Wn.isCanvasFilterSupported)this.ctx.filter="none";if(this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(p.canvas,0,0),this.ctx.globalCompositeOperation=b,this.ctx.globalAlpha=v,Wn.isCanvasFilterSupported)this.ctx.filter=k??"none";this.ctx.drawImage(d.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(p),this.canvasFactory.destroy(d)}else{let c=l?.backdropCtx??null;this.#f(this.ctx,n.canvas,{backdropCanvas:c?.canvas??null,destTransform:r,backdropOffset:c?[l.offsetX+i.offsetX,l.offsetY+i.offsetY]:[0,0],sourceAlpha:this.ctx.globalAlpha,sourceFilter:this.ctx.filter})}else{if(i.replaceBackdrop){let c=new Path2D;c.rect(0,0,n.canvas.width,n.canvas.height),this.ctx.clip(c),this.ctx.globalCompositeOperation="copy"}this.ctx.drawImage(n.canvas,0,0)}this.ctx.restore(),this.canvasFactory.destroy({canvas:n.canvas,context:n}),this.#v(i),this.compose(o)}}#y(e){let{canvas:t}=e,{width:n,height:s}=t;if(Wn.isCanvasFilterSupported){e.save(),e.setTransform(1,0,0,1,0,0),e.filter="grayscale(1)",e.globalAlpha=1,e.globalCompositeOperation="copy",e.drawImage(t,0,0),e.restore();return}let i=e.getImageData(0,0,n,s),{data:r}=i;for(let o=0,l=r.length;o<l;o+=4){let c=r[o]*0.2126+r[o+1]*0.7152+r[o+2]*0.0722+0.5|0;r[o]=r[o+1]=r[o+2]=c}e.putImageData(i,0,0)}#v(e){if(!e)return;if(e.knockoutMaskEntry)this.canvasFactory.destroy(e.knockoutMaskEntry),e.knockoutMaskEntry=null;if(e.knockoutTempEntry)this.canvasFactory.destroy(e.knockoutTempEntry),e.knockoutTempEntry=null;if(e.knockoutBackdropEntry)this.canvasFactory.destroy(e.knockoutBackdropEntry),e.knockoutBackdropEntry=null}beginAnnotation(e,t,n,s,i,r,o){if(this.#h(),Q0(this.ctx),this.ctx.save(),this.save(e),this.baseTransform)this.ctx.setTransform(...this.baseTransform);if(n){let l=n[2]-n[0],c=n[3]-n[1];if(r&&this.annotationCanvasMap){s=s.slice(),s[4]-=n[0],s[5]-=n[1],ct.singularValueDecompose2dScale(ds(this.ctx),xr);let{viewportScale:h}=this,d=Math.ceil(l*this.outputScaleX*h),m=Math.ceil(c*this.outputScaleY*h);this.annotationCanvas=this.canvasFactory.create(d,m);let{canvas:p,context:b}=this.annotationCanvas;if(o){let v=this.annotationCanvasMap.getOrInsertComputed(t,wf);p.setAttribute("data-canvas-name",o);let k=v.findIndex((A)=>A.getAttribute("data-canvas-name")===o);if(k===-1)v.push(p);else v[k]=p}else this.annotationCanvasMap.set(t,p);this.annotationCanvas.savedCtx=this.ctx,this.ctx=b,this.ctx.save(),this.ctx.setTransform(xr[0],0,0,-xr[1],0,c*xr[1]),Q0(this.ctx)}else{Q0(this.ctx),this.endPath(e);let h=new Path2D;h.rect(n[0],n[1],l,c),this.ctx.clip(h)}}this.current=new t2(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...s),this.transform(e,...i),this.baseTransform=ds(this.ctx)}endAnnotation(e){if(this.annotationCanvas)this.ctx.restore(),this.#d(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas;this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){if(!this.contentVisible)return;let n=t.count;t=this.getObject(e,t.data,t),t.count=n;let s=this.#m(this.current.fillAlpha),i=this.ctx,r=this._createMaskCanvas(e,t),o=r.canvas;if(i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(o,r.offsetX,r.offsetY),this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,r.offsetX,r.offsetX+o.width,r.offsetY,r.offsetY+o.height).recordOperation(e),i.restore(),r.canvasEntry)this.canvasFactory.destroy(r.canvasEntry);this.compose(),this.#b(s)}paintImageMaskXObjectRepeat(e,t,n,s=0,i=0,r,o){if(!this.contentVisible)return;t=this.getObject(e,t.data,t);let l=this.#m(this.current.fillAlpha),c=this.ctx;c.save();let h=ds(c);c.transform(n,s,i,r,0,0);let d=this._createMaskCanvas(e,t);c.setTransform(1,0,0,1,d.offsetX-h[4],d.offsetY-h[5]),this.dependencyTracker?.resetBBox(e);for(let m=0,p=o.length;m<p;m+=2){let b=ct.transform(h,[n,s,i,r,o[m],o[m+1]]);c.drawImage(d.canvas,b[4],b[5]),this.dependencyTracker?.recordBBox(e,this.ctx,b[4],b[4]+d.canvas.width,b[5],b[5]+d.canvas.height)}if(c.restore(),d.canvasEntry)this.canvasFactory.destroy(d.canvasEntry);this.compose(),this.dependencyTracker?.recordOperation(e),this.#b(l)}paintImageMaskXObjectGroup(e,t){if(!this.contentVisible)return;let n=this.#m(this.current.fillAlpha),s=this.ctx,i=this.current.fillColor,r=this.current.patternFill;this.dependencyTracker?.resetBBox(e).recordDependencies(e,Hr.transformAndFill);for(let o of t){let{data:l,width:c,height:h,transform:d}=o,m=this.canvasFactory.create(c,h),p=m.context;p.save();let b=this.getObject(e,l,o);h7(p,b),p.globalCompositeOperation="source-in",p.fillStyle=r?i.getPattern(p,this,Ba(s),qi.FILL,e):i,p.fillRect(0,0,c,h),p.restore(),s.save(),s.transform(...d),s.scale(1,-1),K0(s,m.canvas,0,0,c,h,0,-1,1,1),this.canvasFactory.destroy(m),this.dependencyTracker?.recordBBox(e,s,0,c,0,h),s.restore()}this.compose(),this.dependencyTracker?.recordOperation(e),this.#b(n)}paintImageXObject(e,t){if(!this.contentVisible)return;let n=this.getObject(e,t);if(!n){on("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e,n)}paintImageXObjectRepeat(e,t,n,s,i){if(!this.contentVisible)return;let r=this.getObject(e,t);if(!r){on("Dependent image isn't ready yet");return}let{width:o,height:l}=r,c=[];for(let h=0,d=i.length;h<d;h+=2)c.push({transform:[n,0,0,s,i[h],i[h+1]],x:0,y:0,w:o,h:l});this.paintInlineImageXObjectGroup(e,r,c)}applyTransferMapsToCanvas(e){if(this.current.transferMaps!=="none")e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter="none";return e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps==="none")return{img:e.bitmap,canvasEntry:null};let{bitmap:t,width:n,height:s}=e,i=this.canvasFactory.create(n,s),r=i.context;return r.filter=this.current.transferMaps,r.drawImage(t,0,0),r.filter="none",{img:i.canvas,canvasEntry:i}}paintInlineImageXObject(e,t){if(!this.contentVisible)return;let{width:n,height:s}=t,i=this.#m(this.current.fillAlpha),r=this.ctx;this.save(e);let{filter:o}=r;if(o!=="none"&&o!=="")r.filter="none";r.scale(1/n,-1/s);let l,c=null;if(t.bitmap){let d=this.applyTransferMapsToBitmap(t);l=d.img,c=d.canvasEntry}else{let d=this.canvasFactory.create(n,s);f7(d.context,t),l=this.applyTransferMapsToCanvas(d.context),c=d}let h=this._scaleImage(l,Ba(r));if(r.imageSmoothingEnabled=u7(ds(r),t.interpolate),this.dependencyTracker)this.dependencyTracker.resetBBox(e).recordBBox(e,r,0,n,-s,0).recordDependencies(e,Hr.imageXObject).recordOperation(e),this.imagesTracker?.record(r,n,s,this.dependencyTracker.clipBox);if(K0(r,h.img,0,0,h.paintWidth,h.paintHeight,0,-s,n,s),h.tmpCanvas)this.canvasFactory.destroy(h.tmpCanvas);if(c)this.canvasFactory.destroy(c);this.compose(),this.restore(e),this.#b(i)}paintInlineImageXObjectGroup(e,t,n){if(!this.contentVisible)return;let s=this.#m(this.current.fillAlpha),i=this.ctx,r,o=null;if(t.bitmap)r=t.bitmap;else{let{width:l,height:c}=t,h=this.canvasFactory.create(l,c);f7(h.context,t),r=this.applyTransferMapsToCanvas(h.context),o=h}this.dependencyTracker?.resetBBox(e);for(let l of n)i.save(),i.transform(...l.transform),i.scale(1,-1),K0(i,r,l.x,l.y,l.w,l.h,0,-1,1,1),this.dependencyTracker?.recordBBox(e,i,0,1,-1,0),i.restore();if(o)this.canvasFactory.destroy(o);this.dependencyTracker?.recordOperation(e),this.compose(),this.#b(s)}paintSolidColorImageMask(e){if(!this.contentVisible)return;let t=this.#m(this.current.fillAlpha);this.dependencyTracker?.resetBBox(e).recordBBox(e,this.ctx,0,1,0,1).recordDependencies(e,Hr.fill).recordOperation(e),this.ctx.fillRect(0,0,1,1),this.compose(),this.#b(t)}markPoint(e,t){}markPointProps(e,t,n){}beginMarkedContent(e,t){this.dependencyTracker?.beginMarkedContent(e),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t,n){if(this.dependencyTracker?.beginMarkedContent(e),t==="OC")this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(n)});else this.markedContentStack.push({visible:!0});this.contentVisible=this.isContentVisible()}endMarkedContent(e){this.dependencyTracker?.endMarkedContent(e),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(e){}endCompat(e){}consumePath(e,t,n){let s=this.current.isEmptyClip();if(this.pendingClip)this.current.updateClipFromPath();if(!this.pendingClip)this.compose(n);let i=this.ctx;if(this.pendingClip){if(!s)if(this.pendingClip===d7)i.clip(t,"evenodd");else i.clip(t);this.pendingClip=null,this.dependencyTracker?.bboxToClipBoxDropOperation(e).recordFutureForcedDependency("clipPath",e)}else this.dependencyTracker?.recordOperation(e);this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let e=ds(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{let t=Math.abs(e[0]*e[3]-e[2]*e[1]),n=Math.hypot(e[0],e[2]),s=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(n,s)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:e}=this.current,{a:t,b:n,c:s,d:i}=this.ctx.getTransform(),r,o;if(n===0&&s===0){let l=Math.abs(t),c=Math.abs(i);if(l===c)if(e===0)r=o=1/l;else{let h=l*e;r=o=h<1?1/h:1}else if(e===0)r=1/l,o=1/c;else{let h=l*e,d=c*e;r=h<1?1/h:1,o=d<1?1/d:1}}else{let l=Math.abs(t*i-n*s),c=Math.hypot(t,n),h=Math.hypot(s,i);if(e===0)r=h/l,o=c/l;else{let d=e*l;r=h>d?h/d:1,o=c>d?c/d:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(e,t){let{ctx:n,current:{lineWidth:s}}=this,[i,r]=this.getScaleForStroking();if(i===r){n.lineWidth=(s||1)*i,n.stroke(e);return}let o=Jl.#e??=new DOMMatrix,l=n.getLineDash();if(t)n.save();n.scale(i,r),o.a=1/i,o.d=1/r;let c=new Path2D;if(c.addPath(e,o),l.length>0){let h=Math.max(i,r);n.setLineDash(l.map((d)=>d/h)),n.lineDashOffset/=h}if(n.lineWidth=s||1,n.stroke(c),t)n.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}}for(let e in za)if(Jl.prototype[e]!==void 0)Jl.prototype[za[e]]=Jl.prototype[e];class mu{#e=null;#t=null;_fullReader=null;_rangeReaders=new Set;_source=null;constructor(e,t,n){this._source=e,this.#e=t,this.#t=n}get _progressiveDataLength(){return this._fullReader?._loaded??0}getFullReader(){return Rs(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new this.#e(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new this.#t(this,e,t);return this._rangeReaders.add(n),n}cancelAllRequests(e){this._fullReader?.cancel(e);for(let t of new Set(this._rangeReaders))t.cancel(e)}}class pu{onProgress=null;_contentLength=0;_filename=null;_headersCapability=Promise.withResolvers();_isRangeSupported=!1;_isStreamingSupported=!1;_loaded=0;_stream=null;constructor(e){this._stream=e}_callOnProgress(){this.onProgress?.({loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){Dn("Abstract method `read` called")}cancel(e){Dn("Abstract method `cancel` called")}}class bu{_stream=null;constructor(e,t,n){this._stream=e}async read(){Dn("Abstract method `read` called")}cancel(e){Dn("Abstract method `cancel` called")}}function DM(e){let t=!0,n=s("filename\\*","i").exec(e);if(n){n=n[1];let d=l(n);return d=unescape(d),d=c(d),d=h(d),r(d)}if(n=o(e),n){let d=h(n);return r(d)}if(n=s("filename","i").exec(e),n){n=n[1];let d=l(n);return d=h(d),r(d)}function s(d,m){return new RegExp("(?:^|;)\\s*"+d+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',m)}function i(d,m){if(d){if(!/^[\x00-\xFF]+$/.test(m))return m;try{let p=new TextDecoder(d,{fatal:!0}),b=ym(m);m=p.decode(b),t=!1}catch{}}return m}function r(d){if(t&&/[\x80-\xff]/.test(d)){if(d=i("utf-8",d),t)d=i("iso-8859-1",d)}return d}function o(d){let m=[],p,b=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");while((p=b.exec(d))!==null){let[,k,A,T]=p;if(k=parseInt(k,10),k in m){if(k===0)break;continue}m[k]=[A,T]}let v=[];for(let k=0;k<m.length;++k){if(!(k in m))break;let[A,T]=m[k];if(T=l(T),A){if(T=unescape(T),k===0)T=c(T)}v.push(T)}return v.join("")}function l(d){if(d.startsWith('"')){let m=d.slice(1).split("\\\"");for(let p=0;p<m.length;++p){let b=m[p].indexOf('"');if(b!==-1)m[p]=m[p].slice(0,b),m.length=p+1;m[p]=m[p].replaceAll(/\\(.)/g,"$1")}d=m.join('"')}return d}function c(d){let m=d.indexOf("'");if(m===-1)return d;let p=d.slice(0,m),v=d.slice(m+1).replace(/^[^']*'/,"");return i(p,v)}function h(d){if(!d.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(d))return d;return d.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(m,p,b,v){if(b==="q"||b==="Q")return v=v.replaceAll("_"," "),v=v.replaceAll(/=([0-9a-f]{2})/gi,function(k,A){return String.fromCharCode(parseInt(A,16))}),i(p,v);try{v=atob(v)}catch{}return i(p,v)})}return""}function nS(e,t){let n=new Headers;if(!e||!t||typeof t!=="object")return n;for(let s in t){let i=t[s];if(i!==void 0)n.append(s,i)}return n}function qM(e){let t=e.length;while(t>0&&e[t-1]!==" "&&/\s/.test(e[t-1]))t--;return e.slice(0,t)}function Tm(e){return URL.parse(e)?.origin??null}function sS({responseHeaders:e,isHttp:t,rangeChunkSize:n,disableRange:s}){let i={contentLength:0,isRangeSupported:!1},r=parseInt(e.get("Content-Length"),10);if(!Number.isInteger(r))return i;if(i.contentLength=r,r<=2*n)return i;if(s||!t)return i;if(e.get("Accept-Ranges")!=="bytes")return i;if((e.get("Content-Encoding")||"identity")==="identity")i.isRangeSupported=!0;return i}function iS(e){let t=e.get("Content-Disposition");if(t){let n=DM(t);if(n.includes("%"))try{n=decodeURIComponent(n)}catch{}if(a2(n))return n}return null}function Em(e,t){return new iu(`Unexpected server response (${e}) while retrieving PDF "${t.href}".`,e,e===404||e===0&&t.protocol==="file:")}function rS(e,t){if(e!==t)throw Error(`Expected range response-origin "${e}" to match "${t}".`)}function aS(e,t,n,s){return fetch(e,{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:n?"include":"same-origin",redirect:"follow"})}function oS(e,t){if(e!==200&&e!==206)throw Em(e,t)}function Cm(e){if(e instanceof Uint8Array)return e.buffer;if(e instanceof ArrayBuffer)return e;throw Error(`getArrayBuffer - unexpected data: ${e}`)}class lS extends mu{_responseOrigin=null;constructor(e){super(e,cS,fS);let{httpHeaders:t,url:n}=e;Rs(/https?:/.test(n.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=nS(!0,t)}}class cS extends pu{_abortController=new AbortController;_reader=null;constructor(e){super(e);let{disableRange:t,disableStream:n,rangeChunkSize:s,url:i,withCredentials:r}=e._source;this._isStreamingSupported=!n;let o=new Headers(e.headers);aS(i,o,r,this._abortController).then((l)=>{e._responseOrigin=Tm(l.url),oS(l.status,i),this._reader=l.body.getReader();let c=l.headers,{contentLength:h,isRangeSupported:d}=sS({responseHeaders:c,isHttp:!0,rangeChunkSize:s,disableRange:t});if(this._contentLength=h,this._isRangeSupported=d,this._filename=iS(c),!this._isStreamingSupported&&this._isRangeSupported)this.cancel(new Ao("Streaming is disabled."));this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();if(t)return{value:e,done:t};return this._loaded+=e.byteLength,this._callOnProgress(),{value:Cm(e),done:!1}}cancel(e){this._reader?.cancel(e),this._abortController.abort()}}class fS extends bu{_abortController=new AbortController;_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:s,withCredentials:i}=e._source,r=new Headers(e.headers);r.append("Range",`bytes=${t}-${n-1}`),aS(s,r,i,this._abortController).then((o)=>{let l=Tm(o.url);rS(l,e._responseOrigin),oS(o.status,s),this._reader=o.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();if(t)return{value:e,done:t};return{value:Cm(e),done:!1}}cancel(e){this._reader?.cancel(e),this._abortController.abort()}}function m7(e){return e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function jm(){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}class hS extends mu{_progressiveDone=!1;_queuedChunks=[];constructor(e){super(e,uS,dS);let{pdfDataRangeTransport:t}=e,{initialData:n,progressiveDone:s}=t;if(n?.length>0){let r=m7(n);this._queuedChunks.push(r)}this._progressiveDone=s;let i=(r)=>{switch(r.type){case"range":case"progressiveRead":this.#e(r.begin,r.chunk);break;case"progressiveDone":this._fullReader?.progressiveDone(),this._progressiveDone=!0;break}};t.transportReady(i)}#e(e,t){let n=m7(t);if(e===void 0)if(this._fullReader)this._fullReader._enqueue(n);else this._queuedChunks.push(n);else{let s=this._rangeReaders.keys().find((i)=>i._begin===e);Rs(s,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),s._enqueue(n)}}getFullReader(){let e=super.getFullReader();return this._queuedChunks=null,e}getRangeReader(e,t){let n=super.getRangeReader(e,t);if(n)n.onDone=()=>this._rangeReaders.delete(n),this._source.pdfDataRangeTransport.requestDataRange(e,t);return n}cancelAllRequests(e){super.cancelAllRequests(e),this._source.pdfDataRangeTransport.abort()}}class uS extends pu{#e=jm.bind(this);_done=!1;_queuedChunks=null;_requests=[];constructor(e){super(e);let{pdfDataRangeTransport:t,disableRange:n,disableStream:s}=e._source,{length:i,contentDispositionFilename:r}=t;this._queuedChunks=e._queuedChunks||[];for(let l of this._queuedChunks)this._loaded+=l.byteLength;if(this._done=e._progressiveDone,this._contentLength=i,this._isStreamingSupported=!s,this._isRangeSupported=!n,a2(r))this._filename=r;this._headersCapability.resolve();let o=this._loaded;Promise.resolve().then(()=>{if(o>0&&this._loaded===o)this._callOnProgress()})}_enqueue(e){if(this._done)return;if(this._requests.length>0)this._requests.shift().resolve({value:e,done:!1});else this._queuedChunks.push(e);this._loaded+=e.byteLength,this._callOnProgress()}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e()}progressiveDone(){if(this._done||=!0,this._queuedChunks.length===0)this.#e()}}class dS extends bu{#e=jm.bind(this);onDone=null;_begin=-1;_done=!1;_queuedChunk=null;_requests=[];constructor(e,t,n){super(e,t,n);this._begin=t}_enqueue(e){if(this._done)return;if(this._requests.length===0)this._queuedChunk=e;else this._requests.shift().resolve({value:e,done:!1}),this.#e();this._done=!0,this.onDone?.()}async read(){if(this._queuedChunk){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this.onDone?.()}}var Gb=200,p7=206;function MM(e){return typeof e!=="string"?e:ym(e).buffer}class mS extends mu{#e=new WeakMap;_responseOrigin=null;constructor(e){super(e,pS,gS);let{httpHeaders:t,url:n}=e;this.url=n,this.isHttp=/https?:/.test(n.protocol),this.headers=nS(this.isHttp,t)}_request(e){let t=new XMLHttpRequest,n={validateStatus:null,onHeadersReceived:e.onHeadersReceived,onDone:e.onDone,onError:e.onError,onProgress:e.onProgress};this.#e.set(t,n),t.open("GET",this.url),t.withCredentials=this._source.withCredentials;for(let[s,i]of this.headers)t.setRequestHeader(s,i);if(this.isHttp&&"begin"in e&&"end"in e)t.setRequestHeader("Range",`bytes=${e.begin}-${e.end-1}`),n.validateStatus=(s)=>s===p7||s===Gb;else n.validateStatus=(s)=>s===Gb;return t.responseType="arraybuffer",Rs(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>e.onError(t.status),t.onreadystatechange=this.#n.bind(this,t),t.onprogress=this.#t.bind(this,t),t.send(null),t}#t(e,t){this.#e.get(e)?.onProgress?.(t)}#n(e,t){let n=this.#e.get(e);if(!n)return;if(e.readyState>=2&&n.onHeadersReceived)n.onHeadersReceived(),delete n.onHeadersReceived;if(e.readyState!==4)return;if(!this.#e.has(e))return;if(this.#e.delete(e),e.status===0&&this.isHttp){n.onError(e.status);return}let s=e.status||Gb;if(!n.validateStatus(s)){n.onError(e.status);return}let i=MM(e.response);if(s===p7){let r=e.getResponseHeader("Content-Range");if(/bytes \d+-\d+\/\d+/.test(r))n.onDone(i);else on('Missing or invalid "Content-Range" header.'),n.onError(0)}else if(i)n.onDone(i);else n.onError(e.status)}_abortRequest(e){if(this.#e.has(e))this.#e.delete(e),e.abort()}getRangeReader(e,t){let n=super.getRangeReader(e,t);if(n)n.onClosed=()=>this._rangeReaders.delete(n);return n}}class pS extends pu{#e=jm.bind(this);_cachedChunks=[];_done=!1;_requests=[];_storedError=null;constructor(e){super(e);this._fullRequestXhr=e._request({onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#s.bind(this),onProgress:this.#i.bind(this)})}#t(){let e=this._stream,{disableRange:t,rangeChunkSize:n}=e._source,s=this._fullRequestXhr;e._responseOrigin=Tm(s.responseURL);let i=s.getAllResponseHeaders(),r=new Headers(i?qM(i.trimStart()).split(/[\r\n]+/).map((c)=>{let[h,...d]=c.split(": ");return[h,d.join(": ")]}):[]),{contentLength:o,isRangeSupported:l}=sS({responseHeaders:r,isHttp:e.isHttp,rangeChunkSize:n,disableRange:t});if(this._contentLength=o,this._isRangeSupported=l,this._filename=iS(r),this._isRangeSupported)e._abortRequest(s);this._headersCapability.resolve()}#n(e){if(this._requests.length>0)this._requests.shift().resolve({value:e,done:!1});else this._cachedChunks.push(e);if(this._done=!0,this._cachedChunks.length===0)this.#e()}#s(e){this._storedError=Em(e,this._stream.url),this._headersCapability.reject(this._storedError);for(let t of this._requests)t.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}#i(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e),this.#e(),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}class gS extends bu{#e=jm.bind(this);onClosed=null;_done=!1;_queuedChunk=null;_requests=[];_storedError=null;constructor(e,t,n){super(e,t,n);this._requestXhr=e._request({begin:t,end:n,onHeadersReceived:this.#t.bind(this),onDone:this.#n.bind(this),onError:this.#s.bind(this),onProgress:null})}#t(){let e=Tm(this._requestXhr?.responseURL);try{rS(e,this._stream._responseOrigin)}catch(t){this._storedError=t,this.#s(0)}}#n(e){if(this._requests.length>0)this._requests.shift().resolve({value:e,done:!1});else this._queuedChunk=e;this._done=!0,this.#e(),this.onClosed?.()}#s(e){this._storedError??=Em(e,this._stream.url);for(let t of this._requests)t.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let t=this._queuedChunk;return this._queuedChunk=null,{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this.#e(),this._stream._abortRequest(this._requestXhr),this.onClosed?.()}}function bS(e,t=null){let n=process.getBuiltinModule("fs"),{Readable:s}=process.getBuiltinModule("stream"),i=n.createReadStream(e,t);return s.toWeb(i)}class wS extends mu{constructor(e){super(e,yS,vS);let{url:t}=e;Rs(t.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class yS extends pu{_reader=null;constructor(e){super(e);let{disableRange:t,disableStream:n,rangeChunkSize:s,url:i}=e._source;this._isStreamingSupported=!n,process.getBuiltinModule("fs/promises").lstat(i).then((o)=>{let l=bS(i);this._reader=l.getReader();let{size:c}=o;if(this._contentLength=c,this._isRangeSupported=!t&&c>2*s,!this._isStreamingSupported&&this._isRangeSupported)this.cancel(new Ao("Streaming is disabled."));this._headersCapability.resolve()}).catch((o)=>{if(o.code==="ENOENT")o=Em(0,i);this._headersCapability.reject(o)})}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();if(t)return{value:e,done:t};return this._loaded+=e.byteLength,this._callOnProgress(),{value:Cm(e),done:!1}}cancel(e){this._reader?.cancel(e)}}class vS extends bu{_readCapability=Promise.withResolvers();_reader=null;constructor(e,t,n){super(e,t,n);let{url:s}=e._source;try{let i=bS(s,{start:t,end:n-1});this._reader=i.getReader(),this._readCapability.resolve()}catch(i){this._readCapability.reject(i)}}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();if(t)return{value:e,done:t};return{value:Cm(e),done:!1}}cancel(e){this._reader?.cancel(e)}}function FM(e){return tu(e)?lS:Sr?wS:mS}class xo{static#e=null;static#t="";static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=="string")throw Error("Invalid `workerSrc` type.");this.#t=e}}class SS{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}[Symbol.iterator](){return this.#e.entries()}}var Wl=Symbol("INTERNAL");class kS{#e=!1;#t=!1;#n=!1;#s=!0;constructor(e,{name:t,intent:n,usage:s,rbGroups:i}){this.#e=!!(e&vr.DISPLAY),this.#t=!!(e&vr.PRINT),this.name=t,this.intent=n,this.usage=s,this.rbGroups=i}get visible(){if(this.#n)return this.#s;if(!this.#s)return!1;let{print:e,view:t}=this.usage;if(this.#e)return t?.viewState!=="OFF";else if(this.#t)return e?.printState!=="OFF";return!0}_setVisible(e,t,n=!1){if(e!==Wl)Dn("Internal method `_setVisible` called.");this.#n=n,this.#s=t}get serializable(){return{userSet:this.#n,visible:this.#s}}}class m2{#e=null;#t=new Map;#n=null;#s=null;#i;creator=null;name=null;constructor(e,t=vr.DISPLAY,n=null){if(this.#i=e,this.renderingIntent=t,e===null)return;this.name=e.name,this.creator=e.creator,this.#s=e.order;for(let s of e.groups)this.#t.set(s.id,new kS(t,s));if(n){if(n.size!==this.#t.size)Dn("Incorrect serialized groupState.");for(let[s,i]of n)this.#t.get(s)._setVisible(Wl,i.visible,i.userSet)}else{if(e.baseState==="OFF")for(let s of this.#t.values())s._setVisible(Wl,!1);for(let s of e.on)this.#t.get(s)._setVisible(Wl,!0);for(let s of e.off)this.#t.get(s)._setVisible(Wl,!1)}this.#n=this.getHash()}#a(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let s=1;s<t;s++){let i=e[s],r;if(Array.isArray(i))r=this.#a(i);else if(this.#t.has(i))r=this.#t.get(i).visible;else return on(`Optional content group not found: ${i}`),!0;switch(n){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return n==="And"}isVisible(e){if(this.#t.size===0)return!0;if(!e)return wm("Optional content group not defined."),!0;if(e.type==="OCG"){if(!this.#t.has(e.id))return on(`Optional content group not found: ${e.id}`),!0;return this.#t.get(e.id).visible}else if(e.type==="OCMD"){if(e.expression)return this.#a(e.expression);if(!e.policy||e.policy==="AnyOn"){for(let t of e.ids){if(!this.#t.has(t))return on(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(let t of e.ids){if(!this.#t.has(t))return on(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(let t of e.ids){if(!this.#t.has(t))return on(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(let t of e.ids){if(!this.#t.has(t))return on(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!1}return!0}return on(`Unknown optional content policy ${e.policy}.`),!0}return on(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){let s=this.#t.get(e);if(!s){on(`Optional content group not found: ${e}`);return}if(n&&t&&s.rbGroups.length){for(let i of s.rbGroups)for(let r of i)if(r!==e)this.#t.get(r)?._setVisible(Wl,!1,!0)}s._setVisible(Wl,!!t,!0),this.#e=null}setOCGState({state:e,preserveRB:t}){let n;for(let s of e){switch(s){case"ON":case"OFF":case"Toggle":n=s;continue}let i=this.#t.get(s);if(!i)continue;switch(n){case"ON":this.setVisibility(s,!0,t);break;case"OFF":this.setVisibility(s,!1,t);break;case"Toggle":this.setVisibility(s,!i.visible,t);break}}this.#e=null}get hasInitialVisibility(){return this.#n===null||this.getHash()===this.#n}getOrder(){if(!this.#t.size)return null;if(this.#s)return this.#s.slice();return[...this.#t.keys()]}getGroup(e){return this.#t.get(e)||null}getHash(){if(this.#e!==null)return this.#e;let e=new cm;for(let[t,n]of this.#t)e.update(`${t}:${n.visible}`);return this.#e=e.hexdigest()}[Symbol.iterator](){return this.#t.entries()}get serializable(){let e=new Map;for(let[t,n]of this.#t)e.set(t,n.serializable);return{data:this.#i,renderingIntent:this.renderingIntent,groupState:e}}static fromSerializable({data:e,renderingIntent:t,groupState:n}){return new m2(e,t,n)}}class xS{#e=null;#t=null;#n=0;#s=null;#i=null;get pagesNumber(){return this.#n}set pagesNumber(e){if(this.#n===e)return;this.#n=e,this.#e=null,this.#t=null}#a(){if(this.#e)return;let e=this.#n,t=this.#e=new Uint32Array(e);for(let n=0;n<e;n++)t[n]=n+1;this.#t=new Int32Array(t)}#r(){let e=new Map,t=this.#e;for(let n=0,s=this.#n;n<s;n++){let i=t[n],r=e.get(i);if(r)r.push(n+1);else e.set(i,[n+1])}return e}movePages(e,t,n){this.#a();let s=this.#e,i=t.length,r=new Uint32Array(i),o=0;for(let m=0;m<i;m++){let p=t[m]-1;if(r[m]=s[p],p<n)o++}let l=this.#n,c=l-i,h=new Int32Array(l),d=bs(n-o,0,c);for(let m=0,p=0;m<l;m++)if(!e.has(m+1))s[p]=s[m],h[p++]=m+1;if(s.copyWithin(d+i,d,c),s.set(r,d),h.copyWithin(d+i,d,c),h.set(t,d),this.#t=h,s.every((m,p)=>m===p+1))this.#e=null}deletePages(e){this.#a();let t=this.#e,n=this.#r();this.#i={pageNumberToId:t.slice(),pagesNumber:this.#n,prevPageNumbers:this.#t.slice()};let s=this.#n-e.length;this.#n=s;let i=this.#e=new Uint32Array(s);this.#t=new Int32Array(s);let r=0,o=0;for(let l of e){let c=l-1;if(c!==r)i.set(t.subarray(r,c),o),o+=c-r;r=c+1}if(r<t.length)i.set(t.subarray(r),o);this.#o(n,new Set(e))}cancelDelete(){if(this.#i)this.#e=this.#i.pageNumberToId,this.#n=this.#i.pagesNumber,this.#t=this.#i.prevPageNumbers,this.#i=null}cleanSavedData(){this.#i=null}copyPages(e){this.#a(),this.#s={pageNumbers:e,pageIds:e.map((t)=>this.#e[t-1])}}cancelCopy(){this.#s=null}pastePages(e){this.#a();let t=this.#e,n=this.#r(),{pageNumbers:s,pageIds:i}=this.#s,r=this.#n+s.length;this.#n=r;let o=this.#e=new Uint32Array(r);this.#t=new Int32Array(r),o.set(t.subarray(0,e),0),o.set(i,e),o.set(t.subarray(e),e+s.length),this.#o(n,null,e,s),this.#s=null}#o(e,t=null,n=-1,s=null){let i=this.#t,r=this.#e,o=n+(s?.length??0),l=new Map;for(let c=0,h=this.#n;c<h;c++){if(c>=n&&c<o){i[c]=-s[c-n];continue}let d=r[c],m=e.get(d),p=l.get(d)||0;if(t&&m)while(p<m.length&&t.has(m[p]))p++;i[c]=m?.[p],l.set(d,p+1)}}hasBeenAltered(){return this.#e!==null}#l(e=null){if(!this.#e)return null;let t=new Int32Array(this.#n).fill(-1),n=new Map;if(e)for(let s of e){let i=this.getPageId(s),r=n.get(i)??0;n.set(i,r+1),t[s-1]=r}else for(let s=0,i=this.#n;s<i;s++){let r=this.#e[s],o=n.get(r)??0;n.set(r,o+1),t[s]=o}return t}getPageMappingForSaving(e=null,t=this.#l()){e??=this.#r();let n=0;for(let i of e.values())n=Math.max(n,i.length);let s=Array(n);for(let i=0;i<n;i++)s[i]={document:null,pageIndices:[],includePages:[]};for(let[i,r]of e)for(let o=0,l=r.length;o<l;o++)s[o].includePages.push([i-1,r[o]-1]);for(let{includePages:i,pageIndices:r}of s){i.sort((o,l)=>o[0]-l[0]);for(let o=0,l=i.length;o<l;o++)r.push(i[o][1]),i[o]=i[o][0]}return{pageInfos:s,copyLevels:t}}extractPages(e){e=Array.from(e).sort((n,s)=>n-s);let t=new Map;for(let n=0,s=e.length;n<s;n++){let i=this.getPageId(e[n]);t.getOrInsertComputed(i,wf).push(n+1)}return this.getPageMappingForSaving(t,this.#l(e))}getPrevPageNumber(e){return this.#t?.[e-1]??0}getPageNumber(e){if(!this.#e)return e;let t=this.#e;for(let n=0,s=this.#n;n<s;n++)if(t[n]===e)return n+1;return 0}getPageId(e){return this.#e?.[e-1]??e}getMapping(){return this.#e?.subarray(0,this.pagesNumber)}}var pf=Symbol("INITIAL_DATA"),g7=()=>({...Promise.withResolvers(),data:pf});class p2{#e=new Map;get(e,t=null){if(t){let s=this.#e.getOrInsertComputed(e,g7);return s.promise.then(()=>t(s.data)),null}let n=this.#e.get(e);if(!n||n.data===pf)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e.get(e);return!!t&&t.data!==pf}delete(e){let t=this.#e.get(e);if(!t||t.data===pf)return!1;return this.#e.delete(e),!0}resolve(e,t=null){let n=this.#e.getOrInsertComputed(e,g7);if(n.data!==pf)throw Error(`Object already resolved ${e}.`);n.data=t,n.resolve()}clear(){for(let{data:e}of this.#e.values())e?.bitmap?.close();this.#e.clear()}*[Symbol.iterator](){for(let[e,{data:t}]of this.#e)if(t!==pf)yield[e,t]}}var LM=1e5,b7=30;class Vi{#e=Promise.withResolvers();#t=null;#n=!1;#s=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#r=null;#o=0;#l=0;#c=null;#u=null;#h=0;#d=0;#p=Object.create(null);#g=[];#f=null;#m=[];#b=new WeakMap;#w=null;static#y=new Map;static#v=new Map;static#x=new WeakMap;static#k=null;static#A=new Set;constructor({textContentSource:e,images:t,container:n,viewport:s}){if(e instanceof ReadableStream)this.#f=e;else if(typeof e==="object")this.#f=new ReadableStream({start(c){c.enqueue(e),c.close()}});else throw Error('No "textContentSource" parameter specified.');this.#t=this.#u=n,this.#i=t,this.#d=s.scale*fa.pixelRatio,this.#h=s.rotation,this.#r={div:null,properties:null,ctx:null};let{pageWidth:i,pageHeight:r,pageX:o,pageY:l}=s.rawDims;this.#w=[1,0,0,-1,-o,l+r],this.#l=i,this.#o=r,Vi.#R(),n.style.setProperty("--min-font-size",Vi.#k),sc(n,s),this.#e.promise.finally(()=>{Vi.#A.delete(this),this.#r=null,this.#p=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=Wn.platform;return Mt(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){if(this.#i)this.#t.append(this.#i.render());let e=()=>{this.#c.read().then(({value:t,done:n})=>{if(n){this.#e.resolve();return}this.#a??=t.lang,Object.assign(this.#p,t.styles),this.#T(t.items),e()},this.#e.reject)};return this.#c=this.#f.getReader(),Vi.#A.add(this),e(),this.#e.promise}update({viewport:e,onBefore:t=null}){let n=e.scale*fa.pixelRatio,s=e.rotation;if(s!==this.#h)t?.(),this.#h=s,sc(this.#u,{rotation:s});if(n!==this.#d){t?.(),this.#d=n;let i={div:null,properties:null,ctx:Vi.#C(this.#a)};for(let r of this.#m)i.properties=this.#b.get(r),i.div=r,this.#j(i)}}cancel(){let e=new Ao("TextLayer task cancelled.");this.#c?.cancel(e).catch(()=>{}),this.#c=null,this.#e.reject(e)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#g}#T(e){if(this.#n)return;this.#r.ctx??=Vi.#C(this.#a);let t=this.#m,n=this.#g;for(let s of e){if(t.length>LM){on("Ignoring additional textDivs for performance reasons."),this.#n=!0;return}if(s.str===void 0){if(s.type==="beginMarkedContentProps"||s.type==="beginMarkedContent"){let i=this.#t;if(this.#t=document.createElement("span"),this.#t.classList.add("markedContent"),s.id)this.#t.setAttribute("id",s.id);if(s.tag==="Artifact")this.#t.ariaHidden=!0;i.append(this.#t)}else if(s.type==="endMarkedContent")this.#t=this.#t.parentNode;continue}n.push(s.str),this.#I(s)}}#I(e){let t=document.createElement("span"),n={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};this.#m.push(t);let s=ct.transform(this.#w,e.transform),i=Math.atan2(s[1],s[0]),r=this.#p[e.fontName];if(r.vertical)i+=Math.PI/2;let o=this.#s&&r.fontSubstitution||r.fontFamily;o=Vi.fontFamilyMap.get(o)||o;let l=Math.hypot(s[2],s[3]),c=l*Vi.#q(o,r,this.#a),h,d;if(i===0)h=s[4],d=s[5]-c;else h=s[4]+c*Math.sin(i),d=s[5]-c*Math.cos(i);let m=t.style;if(m.left=`${(100*h/this.#l).toFixed(2)}%`,m.top=`${(100*d/this.#o).toFixed(2)}%`,m.setProperty("--font-height",`${l.toFixed(2)}px`),m.fontFamily=o,n.fontSize=l,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,this.#s)t.dataset.fontName=r.fontSubstitutionLoadedName||e.fontName;if(i!==0)n.angle=i*(180/Math.PI);let p=!1;if(e.str.length>1)p=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){let b=Math.abs(e.transform[0]),v=Math.abs(e.transform[3]);if(b!==v&&Math.max(b,v)/Math.min(b,v)>1.5)p=!0}if(p)n.canvasWidth=r.vertical?e.height:e.width;if(this.#b.set(t,n),this.#r.div=t,this.#r.properties=n,this.#j(this.#r),n.hasText)this.#t.append(t);if(n.hasEOL){let b=document.createElement("br");b.setAttribute("role","presentation"),this.#t.append(b)}}#j(e){let{div:t,properties:n,ctx:s}=e,{style:i}=t;if(n.canvasWidth!==0&&n.hasText){let{fontFamily:r}=i,{canvasWidth:o,fontSize:l}=n;Vi.#D(s,l*this.#d,r);let{width:c}=s.measureText(t.textContent);if(c>0)i.setProperty("--scale-x",o*this.#d/c)}if(n.angle!==0)i.setProperty("--rotate",`${n.angle}deg`)}static cleanup(){if(this.#A.size>0)return;this.#y.clear();for(let{canvas:e}of this.#v.values())e.remove();this.#v.clear()}static#C(e=null){let t=this.#v.get(e||="");if(!t){let n=document.createElement("canvas");n.style.cssText="position:absolute;top:0;left:0;width:0;height:0;display:none;letter-spacing:normal;word-spacing:normal",n.lang=e,document.body.append(n),t=n.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#v.set(e,t),this.#x.set(t,{size:0,family:""})}return t}static#D(e,t,n){let s=this.#x.get(e);if(t===s.size&&n===s.family)return;e.font=`${t}px ${n}`,s.size=t,s.family=n}static#R(){if(this.#k!==null)return;let e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),this.#k=e.getBoundingClientRect().height,e.remove()}static#q(e,t,n){let s=this.#y.get(e);if(s)return s;let i=this.#C(n);i.canvas.width=i.canvas.height=b7,this.#D(i,b7,e);let r=i.measureText(""),o=r.fontBoundingBoxAscent,l=Math.abs(r.fontBoundingBoxDescent);i.canvas.width=i.canvas.height=0;let c=0.8;if(o)c=o/(o+l);else{if(Wn.platform.isFirefox)on("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering.");if(t.ascent)c=t.ascent;else if(t.descent)c=1+t.descent}return this.#y.set(e,c),c}}var OM=100;function g2(e={}){let t=new b2,{docId:n}=t,s=e.url?dM(e.url):null,i=e.data?mM(e.data):null,r=e.httpHeaders||null,o=e.withCredentials===!0,l=e.password??null,c=e.range instanceof w2?e.range:null,h=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:65536,d=e.worker instanceof Di?e.worker:null,m=e.verbosity,p=typeof e.docBaseUrl==="string"&&!Sm(e.docBaseUrl)?e.docBaseUrl:null,b=X0(e.cMapUrl),v=e.cMapPacked!==!1,k=X0(e.iccUrl),A=X0(e.standardFontDataUrl),T=X0(e.wasmUrl),E=e.stopAtErrors!==!0,I=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,_=typeof e.isOffscreenCanvasSupported==="boolean"?e.isOffscreenCanvasSupported:!Sr,q=typeof e.isImageDecoderSupported==="boolean"?e.isImageDecoderSupported:!Sr,P=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,N=typeof e.disableFontFace==="boolean"?e.disableFontFace:Sr,H=e.fontExtraProperties===!0,V=e.enableXfa===!0,U=e.ownerDocument||globalThis.document,W=e.disableRange===!0,ce=e.disableStream===!0,ue=e.disableAutoFetch===!0,oe=e.pdfBug===!0,ae=e.CanvasFactory||(Sr?K7:$7),te=e.FilterFactory||(Sr?W7:X7),me=e.BinaryDataFactory||(Sr?Y7:e2),he=e.enableHWA===!0,be=e.enableWebGPU===!0?vM():Promise.resolve(!1),ye=e.useWasm!==!1,Te=e.pagesMapper||new xS,Oe=typeof e.useSystemFonts==="boolean"?e.useSystemFonts:!Sr&&!N,st=typeof e.useWorkerFetch==="boolean"?e.useWorkerFetch:!!(me===e2&&b&&v&&A&&T&&tu(b,document.baseURI)&&tu(A,document.baseURI)&&tu(T,document.baseURI)),We=null;Wq(m);let wt={canvasFactory:new ae({ownerDocument:U,enableHWA:he}),filterFactory:new te({docId:n,ownerDocument:U}),binaryDataFactory:st?null:new me({cMapUrl:b,standardFontDataUrl:A,wasmUrl:T})};if(!d)d=Di.create({verbosity:m,port:xo.workerPort}),t._worker=d;let xt={docId:n,apiVersion:"6.3.289",data:i,password:l,disableAutoFetch:ue,rangeChunkSize:h,docBaseUrl:p,enableXfa:V,evaluatorOptions:{maxImageSize:I,disableFontFace:N,ignoreErrors:E,isOffscreenCanvasSupported:_,isImageDecoderSupported:q,canvasMaxAreaInBytes:P,fontExtraProperties:H,useSystemFonts:Oe,useWasm:ye,useWorkerFetch:st,cMapUrl:b,cMapPacked:v,iccUrl:k,standardFontDataUrl:A,wasmUrl:T,hasGPU:!1}},ft={ownerDocument:U,pdfBug:oe,styleElement:We,enableHWA:he,loadingParams:{disableAutoFetch:ue,enableXfa:V}};return Promise.all([d.promise,be]).then(function([,It]){if(d.destroyed)throw Error("Worker was destroyed");xt.evaluatorOptions.hasGPU=It;let Wt=d.messageHandler.sendWithPromise("GetDocRequest",xt,i?[i.buffer]:null),hn;if(i);else if(c)hn=new hS({pdfDataRangeTransport:c,disableRange:W,disableStream:ce});else if(s)hn=new(FM(s))({url:s,httpHeaders:r,withCredentials:o,rangeChunkSize:h,disableRange:W,disableStream:ce});else throw Error("getDocument - expected either `data`, `range`, or `url` parameter.");return Wt.then((zt)=>{if(d.destroyed)throw Error("Worker was destroyed");let tn=new gf(n,zt,d.port),Kn=new TS(tn,t,hn,ft,wt,Te);if(t._transport=Kn,t.destroyed)throw Error("Loading aborted");tn.send("Ready",null)})}).catch(t._capability.reject).finally(t._setupCapability.resolve),t}class b2{static#e=0;_capability=Promise.withResolvers();_setupCapability=Promise.withResolvers();_transport=null;_worker=null;docId=`d${b2.#e++}`;destroyed=!1;onPassword=null;onProgress=null;get promise(){return this._capability.promise}async destroy(){this.destroyed=!0,this._capability.promise.catch(()=>{});try{if(this._worker?.port)this._worker._pendingDestroy=!0;await this._setupCapability.promise,await this._transport?.destroy()}catch(e){if(this._worker?.port)delete this._worker._pendingDestroy;throw e}this._transport=null,this._worker?.destroy(),this._worker=null}async getData(){return this._transport.getData()}}class w2{#e=Promise.withResolvers();#t=null;constructor(e,t,n=!1,s=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=s}onDataRange(e,t){this.#t({type:"range",begin:e,chunk:t})}onDataProgressiveRead(e){this.#e.promise.then(()=>{this.#t({type:"progressiveRead",chunk:e})})}onDataProgressiveDone(){this.#e.promise.then(()=>{this.#t({type:"progressiveDone"})})}transportReady(e){this.#t=e,this.#e.resolve()}requestDataRange(e,t){Dn("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class AS{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Mt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAttachmentContent(e){return this._transport.getAttachmentContent(e)}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e="display"}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e,t=null){return this._transport.extractPages(e,t)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}getSignatures(){return this._transport.getSignatures()}getSignatureData(e){return this._transport.getSignatureData(e)}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class y2{#e=!1;#t=null;constructor(e,t,n,s,i=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=i?new Wb:null,this._pdfBug=i,this.commonObjs=n.commonObjs,this.objs=new p2,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,this.#t=s,this.imageCoordinates=null}clone(e){let t=new y2(e,this._pageInfo,this._transport,this.#t,this._pdfBug);return t.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(t),t}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:s=0,dontFlip:i=!1}={}){return new hu({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:s,dontFlip:i})}getAnnotations({intent:e="display"}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Mt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,canvas:t=e.canvas,viewport:n,intent:s="display",annotationMode:i=hl.ENABLE,transform:r=null,background:o=null,optionalContentConfigPromise:l=null,annotationCanvasMap:c=null,pageColors:h=null,printAnnotationStorage:d=null,isEditing:m=!1,recordImages:p=!1,recordOperations:b=!1,operationsFilter:v=null}){this._stats?.time("Overall");let k=this._transport.getRenderingIntent(s,i,d,m),{renderingIntent:A,cacheKey:T}=k;this.#e=!1,l||=this._transport.getOptionalContentConfig(A);let E=this._intentStates.getOrInsertComputed(T,Xb);if(E.streamReaderCancelTimeout)clearTimeout(E.streamReaderCancelTimeout),E.streamReaderCancelTimeout=null;let I=!!(A&vr.PRINT);if(!E.displayReadyCapability)E.displayReadyCapability=Promise.withResolvers(),E.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(k);let _=!!(this._pdfBug&&globalThis.StepperManager?.enabled),q=!!t&&!this.recordedBBoxes&&(b||_),P=!!t&&!this.imageCoordinates&&p,N=(ce)=>{if(E.renderTasks.delete(U),q){let ue=U.gfx?.dependencyTracker.take();if(ue){if(U.stepper?.setOperatorBBoxes(ue,U.gfx.dependencyTracker.takeDebugMetadata()),b)this.recordedBBoxes=ue}}if(P&&!ce)this.imageCoordinates=U.gfx?.imagesTracker.take();if(I)this.#e=!0;if(this.#n(),ce)U.capability.reject(ce),this._abortOperatorList({intentState:E,reason:ce instanceof Error?ce:Error(ce)});else U.capability.resolve();if(this._stats){if(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled)globalThis.Stats.add(this.pageNumber,this._stats)}},H=null,V=null;if(q||P)V=new M7(t,E.operatorList.length);if(q)H=new F7(V,_);let U=new bf({callback:N,params:{canvas:t,canvasContext:e,dependencyTracker:H??V,imagesTracker:P?new fm(t):null,viewport:n,transform:r,background:o},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:E.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!I,pdfBug:this._pdfBug,pageColors:h,enableHWA:this._transport.enableHWA,operationsFilter:v});(E.renderTasks||=new Set).add(U);let W=U.task;return Promise.all([E.displayReadyCapability.promise,l]).then(([ce,ue])=>{if(this.destroyed){N();return}if(this._stats?.time("Rendering"),!(ue.renderingIntent&A))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");U.initializeGraphics({transparency:ce,optionalContentConfig:ue}),U.operatorListChanged()}).catch(N),W}getOperatorList({intent:e="display",annotationMode:t=hl.ENABLE,printAnnotationStorage:n=null,isEditing:s=!1}={}){function i(){if(o.operatorList.lastChunk)o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(l)}let r=this._transport.getRenderingIntent(e,t,n,s,!0),o=this._intentStates.getOrInsertComputed(r.cacheKey,Xb),l;if(!o.opListReadCapability)l=Object.create(null),l.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(l),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r);return o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:this.#t.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(s){return s.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then((s)=>ru.textContent(s));let t=this.streamTextContent(e),n={items:[],styles:Object.create(null),lang:null};for await(let s of t)n.lang??=s.lang,Object.assign(n.styles,s.styles),n.items.push(...s.items);return n}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values()){if(this._abortOperatorList({intentState:t,reason:Error("Page was destroyed."),force:!0}),t.opListReadCapability)continue;for(let n of t.renderTasks)e.push(n.completed),n.cancel()}return this.objs.clear(),this.#e=!1,Promise.all(e)}cleanup(e=!1){this.#e=!0;let t=this.#n();if(e&&t)this._stats&&=new Wb;return t}#n(){if(!this.#e||this.destroyed)return!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}_startRenderPage(e,t){let n=this._intentStates.get(t);if(!n)return;this._stats?.timeEnd("Page Request"),n.displayReadyCapability?.resolve(e)}_renderPageChunk(e,t){for(let n=0,s=e.length;n<s;n++)t.operatorList.fnArray.push(e.fnArray[n]),t.operatorList.argsArray.push(e.argsArray[n]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(let n of t.renderTasks)n.operatorListChanged();if(e.lastChunk)this.#n()}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:n,modifiedIds:s}){let{map:i,transfer:r}=n,l=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:this.#t.getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:i,modifiedIds:s},void 0,r).getReader(),c=this._intentStates.get(t);c.streamReader=l;let h=()=>{l.read().then(({value:d,done:m})=>{if(m){c.streamReader=null;return}if(this._transport.destroyed)return;this._renderPageChunk(d,c),h()},(d)=>{if(c.streamReader=null,this._transport.destroyed)return;if(c.operatorList){c.operatorList.lastChunk=!0;for(let m of c.renderTasks)m.operatorListChanged();this.#n()}if(c.displayReadyCapability)c.displayReadyCapability.reject(d);else if(c.opListReadCapability)c.opListReadCapability.reject(d);else throw d})};h()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(!e.streamReader)return;if(e.streamReaderCancelTimeout)clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null;if(!n){if(e.renderTasks.size>0)return;if(t instanceof vm){let s=OM;if(t.extraDelay>0&&t.extraDelay<1000)s+=t.extraDelay;e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},s);return}}if(e.streamReader.cancel(new Ao(t.message)).catch(()=>{}),e.streamReader=null,this._transport.destroyed)return;for(let[s,i]of this._intentStates)if(i===e){this._intentStates.delete(s);break}this.cleanup()}get stats(){return this._stats}}class Di{#e=Promise.withResolvers();#t=null;#n=null;#s=null;static#i=0;static#a=!1;static#r=new WeakMap;static{if(Sr)this.#a=!0,xo.workerSrc||="./pdf.worker.mjs";this._isSameOrigin=(e,t)=>{let n=URL.parse(e);if(!n?.origin||n.origin==="null")return!1;let s=new URL(t,n);return n.origin===s.origin},this._createCDNWrapper=(e)=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))}}constructor({name:e=null,port:t=null,verbosity:n=Kq()}={}){if(this.name=e,this.destroyed=!1,this.verbosity=n,t){if(Di.#r.has(t))throw Error("Cannot use more than one PDFWorker per port.");Di.#r.set(t,this),this.#l(t)}else this.#c()}get promise(){return this.#e.promise}#o(){this.#e.resolve(),this.#t.send("configure",{verbosity:this.verbosity})}get port(){return this.#n}get messageHandler(){return this.#t}#l(e){this.#n=e,this.#t=new gf("main","worker",e),this.#t.on("ready",()=>{}),this.#o()}#c(){if(Di.#a||Di.#h){this.#u();return}let{workerSrc:e}=Di;try{if(!Di._isSameOrigin(window.location,e))e=Di._createCDNWrapper(new URL(e,window.location).href);let t=new Worker(e,{type:"module"}),n=new gf("main","worker",t),s=()=>{if(i.abort(),n.destroy(),t.terminate(),this.destroyed)this.#e.reject(Error("Worker was destroyed"));else this.#u()},i=new AbortController;t.addEventListener("error",()=>{if(!this.#s)s()},{signal:i.signal}),n.on("test",(o)=>{if(i.abort(),this.destroyed||!o){s();return}this.#t=n,this.#n=t,this.#s=t,this.#o()}),n.on("ready",(o)=>{if(i.abort(),this.destroyed){s();return}try{r()}catch{this.#u()}});let r=()=>{let o=new Uint8Array;n.send("test",o,[o.buffer])};r();return}catch{wm("The worker has been disabled.")}this.#u()}#u(){if(!Di.#a)on("Setting up fake worker."),Di.#a=!0;Di._setupFakeWorkerGlobal.then((e)=>{if(this.destroyed){this.#e.reject(Error("Worker was destroyed"));return}let t=new V7;this.#n=t;let n=`fake${Di.#i++}`,s=new gf(n+"_worker",n,t);e.setup(s,t),this.#t=new gf(n,n+"_worker",t),this.#o()}).catch((e)=>{this.#e.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this.#s?.terminate(),this.#s=null,Di.#r.delete(this.#n),this.#n=null,this.#t?.destroy(),this.#t=null}static create(e){let t=this.#r.get(e?.port);if(t){if(t._pendingDestroy)throw Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new Di(e)}static get workerSrc(){if(xo.workerSrc)return xo.workerSrc;throw Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#h(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Mt(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#h)return this.#h;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class TS{downloadInfoCapability=Promise.withResolvers();#e=null;#t=new Map;#n=null;#s=new Map;#i=new Map;#a=new Map;#r=null;constructor(e,t,n,s,i,r){this.messageHandler=e,this.loadingTask=t,this.#n=n,this.commonObjs=new p2,this.fontLoader=new L7({ownerDocument:s.ownerDocument,styleElement:s.styleElement}),this.enableHWA=s.enableHWA,this.loadingParams=s.loadingParams,this._params=s,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.binaryDataFactory=i.binaryDataFactory,this.pagesMapper=r,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){let{_pageIndex:t}=e;this.#s.set(t,e),this.#i.set(t,Promise.resolve(e))}#o(e,t=null){return this.#t.getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))}#l({loaded:e,total:t}){this.loadingTask.onProgress?.({loaded:e,total:t,percent:t?bs(Math.round(e/t*100),0,100):NaN})}get annotationStorage(){return Mt(this,"annotationStorage",new km)}getRenderingIntent(e,t=hl.ENABLE,n=null,s=!1,i=!1){let r=vr.DISPLAY,o=au;switch(e){case"any":r=vr.ANY;break;case"display":break;case"print":r=vr.PRINT;break;default:on(`getRenderingIntent - invalid intent: ${e}`)}let l=r&vr.PRINT&&n instanceof f2?n:this.annotationStorage;switch(t){case hl.DISABLE:r+=vr.ANNOTATIONS_DISABLE;break;case hl.ENABLE:break;case hl.ENABLE_FORMS:r+=vr.ANNOTATIONS_FORMS;break;case hl.ENABLE_STORAGE:r+=vr.ANNOTATIONS_STORAGE,o=l.serializable;break;default:on(`getRenderingIntent - invalid annotationMode: ${t}`)}if(s)r+=vr.IS_EDITING;if(i)r+=vr.OPLIST;let{ids:c,hash:h}=l.modifiedIds,d=[r,o.hash,h];return{renderingIntent:r,cacheKey:d.join("_"),annotationStorageSerializable:o,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(Error("Worker was destroyed during onPassword callback"));let e=[];for(let n of this.#s.values())e.push(n._destroy());if(this.#s.clear(),this.#i.clear(),this.#a.clear(),Object.hasOwn(this,"annotationStorage"))this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise("Terminate",null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Vi.cleanup(),this.#n?.cancelAllRequests(new Ao("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on("GetReader",(n,s)=>{Rs(this.#n,"GetReader - no `BasePDFStream` instance available."),this.#e=this.#n.getFullReader(),this.#e.onProgress=(i)=>this.#l(i),s.onPull=()=>{this.#e.read().then(function({value:i,done:r}){if(r){s.close();return}Rs(i instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),s.enqueue(new Uint8Array(i),1,[i])}).catch((i)=>{s.error(i)})},s.onCancel=(i)=>{this.#e.cancel(i),s.ready.catch((r)=>{if(this.destroyed)return;throw r})}}),e.on("ReaderHeadersReady",async(n)=>{await this.#e.headersReady;let{isStreamingSupported:s,isRangeSupported:i,contentLength:r}=this.#e;if(s&&i)this.#e.onProgress=null;return{isStreamingSupported:s,isRangeSupported:i,contentLength:r}}),e.on("GetRangeReader",(n,s)=>{Rs(this.#n,"GetRangeReader - no `BasePDFStream` instance available.");let i=this.#n.getRangeReader(n.begin,n.end);if(!i){s.close();return}s.onPull=()=>{i.read().then(function({value:r,done:o}){if(o){s.close();return}Rs(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),s.enqueue(new Uint8Array(r),1,[r])}).catch((r)=>{s.error(r)})},s.onCancel=(r)=>{i.cancel(r),s.ready.catch((o)=>{if(this.destroyed)return;throw o})}}),e.on("GetDoc",({pdfInfo:n})=>{this.pagesMapper.pagesNumber=n.numPages,this._numPages=n.numPages,this._htmlForXfa=n.htmlForXfa,delete n.htmlForXfa,t._capability.resolve(new AS(n,this))}),e.on("DocException",(n)=>{t._capability.reject(er(n))}),e.on("PasswordRequest",(n)=>{this.#r=Promise.withResolvers();try{if(!t.onPassword)throw er(n);let s=(i)=>{if(i instanceof Error)this.#r.reject(i);else this.#r.resolve({password:i})};t.onPassword(s,n.code)}catch(s){this.#r.reject(s)}return this.#r.promise}),e.on("DataLoaded",(n)=>{this.#l({loaded:n.length,total:n.length}),this.downloadInfoCapability.resolve(n)}),e.on("StartRenderPage",(n)=>{if(this.destroyed)return;this.#s.get(n.pageIndex)._startRenderPage(n.transparency,n.cacheKey)}),e.on("commonobj",([n,s,i])=>{if(this.destroyed)return null;if(this.commonObjs.has(n))return null;switch(s){case"Font":if("error"in i){let d=i.error;on(`Error during font loading: ${d}`),this.commonObjs.resolve(n,d);break}let r=new U7(i),o=this._params.pdfBug&&globalThis.FontInspector?.enabled?(d,m)=>globalThis.FontInspector.fontAdded(d,m):null,l=new O7(r,o,i.charProcOperatorList,i.extra);this.fontLoader.bind(l).catch(()=>e.sendWithPromise("FontFallback",{id:n})).finally(()=>{if(!l.fontExtraProperties)l.clearData();this.commonObjs.resolve(n,l)});break;case"CopyLocalImage":let{imageRef:c}=i;Rs(c,"The imageRef must be defined.");for(let d of this.#s.values())for(let[,m]of d.objs){if(m?.ref!==c)continue;if(!m.dataLen)return null;let p=structuredClone(m);return this.commonObjs.resolve(n,p),m.dataLen}break;case"FontPath":this.commonObjs.resolve(n,new G7(i));break;case"Image":this.commonObjs.resolve(n,i);break;case"Pattern":let h=new z7(i);this.commonObjs.resolve(n,h.getIR());break;default:throw Error(`Got unknown common object type ${s}`)}return null}),e.on("obj",([n,s,i,r])=>{if(this.destroyed)return;let o=this.#s.get(s);if(o.objs.has(n))return;if(o._intentStates.size===0){r?.bitmap?.close();return}switch(i){case"Image":case"Pattern":o.objs.resolve(n,r);break;default:throw Error(`Got unknown object type ${i}`)}}),e.on("DocProgress",(n)=>{if(this.destroyed)return;this.#l(n)}),e.on("FetchBinaryData",async(n)=>{if(this.destroyed)throw Error("Worker was destroyed.");if(!this.binaryDataFactory)throw Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(n)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){if(this.annotationStorage.size<=0)on("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this.#e?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e,t=null){let n={pageInfos:e},s,i=globalThis.ImageBitmap;if(typeof i==="function"){let r=Array.isArray(e)?e:[e];for(let o of r)if(o?.image instanceof i)(s||=[]).push(o.image)}if(this.annotationStorage.size>0){let r=this.annotationStorage.serializable,{map:o}=r;if(r.transfer?.length)if(s)s.push(...r.transfer);else s=r.transfer;let l=this.pagesMapper.getMapping();if(l){let c=new Map;for(let[h,d]of o){if(d?.pageIndex!==void 0&&d.pageIndex>=0&&d.pageIndex<l.length){let m=t?.[d.pageIndex]??0,p=l[d.pageIndex]-1;if(p!==d.pageIndex||m!==0){c.set(h,{...d,pageIndex:p,copyLevel:m});continue}}c.set(h,d)}o=c}n.annotationStorage=o}return this.messageHandler.sendWithPromise("ExtractPages",n,s).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(Error("Invalid page request."));let t=e-1,n=this.pagesMapper.getPageId(e)-1,s=this.#i.get(t);if(s)return s;let i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then((r)=>{if(this.destroyed)throw Error("Transport destroyed");if(r.refStr)this.#a.set(r.refStr,n);let o=new y2(t,r,this,this.pagesMapper,this._params.pdfBug);return this.#s.set(t,o),o});return this.#i.set(t,i),i}async getPageIndex(e){if(!Zb(e))throw Error("Invalid pageIndex request.");let t=await this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}),n=this.pagesMapper.getPageNumber(t+1);if(n===0)throw Error("GetPageIndex: page has been removed.");return n-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return this.#o("GetFieldObjects")}getSignatures(){return this.#o("GetSignatures")}getSignatureData(e){return this.messageHandler.sendWithPromise("GetSignatureData",e)}hasJSActions(){return this.#o("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){if(typeof e!=="string")return Promise.reject(Error("Invalid destination request."));return this.messageHandler.sendWithPromise("GetDestination",{id:e})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAttachmentContent(e){return this.messageHandler.sendWithPromise("GetAttachmentContent",e)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:e,pageIndexesToSkip:t})}getDocJSActions(){return this.#o("GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return this.#o("GetOptionalContentConfig").then((t)=>new m2(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){return this.#t.getOrInsertComputed("GetMetadata",()=>this.messageHandler.sendWithPromise("GetMetadata",null).then((t)=>({info:t[0],metadata:t[1]?new SS(t[1]):null,contentDispositionFilename:this.#e?.filename??null,contentLength:this.#e?.contentLength??null,hasStructTree:t[2]})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(e=!1){if(this.destroyed)return;await this.messageHandler.sendWithPromise("Cleanup",null);for(let t of this.#s.values())if(!t.cleanup())throw Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);if(this.commonObjs.clear(),!e)this.fontLoader.clear();this.#t.clear(),this.filterFactory.destroy(!0),Vi.cleanup()}cachedPageNumber(e){if(!Zb(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,n=this.#a.get(t);if(n>=0){let s=this.pagesMapper.getPageNumber(n+1);if(s!==0)return s}return null}}class ES{_internalRenderTask=null;onContinue=null;onError=null;constructor(e){this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&t?.size>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}class bf{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:s,annotationCanvasMap:i,operatorList:r,pageIndex:o,canvasFactory:l,filterFactory:c,useRequestAnimationFrame:h=!1,pdfBug:d=!1,pageColors:m=null,enableHWA:p=!1,operationsFilter:b=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=s,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=o,this.canvasFactory=l,this.filterFactory=c,this._pdfBug=d,this.pageColors=m,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=h===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new ES(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=p,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=b}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:t}){if(this.cancelled)return;if(this._canvas){if(bf.#t.has(this._canvas))throw Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");bf.#t.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled)this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint();let{viewport:n,transform:s,background:i,dependencyTracker:r,imagesTracker:o}=this.params,l=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new Jl(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:t},this.annotationCanvasMap,this.pageColors,r,o),this.gfx.beginDrawing({transform:s,viewport:n,transparency:e,background:i}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(e=null,t=0){if(this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e)window.cancelAnimationFrame(this.#e),this.#e=null;bf.#t.delete(this._canvas),e||=new vm(`Rendering cancelled, page ${this._pageIndex+1}`,t),this.callback(e),this.task.onError?.(e)}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}if(this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length),this.stepper?.updateOperatorList(this.operatorList),this.running)return;this._continue()}_continue(){if(this.running=!0,this.cancelled)return;if(this.task.onContinue)this.task.onContinue(this._scheduleNextBound);else this._scheduleNext()}_scheduleNext(){if(this._useRequestAnimationFrame)this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)});else Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(this.cancelled)return;if(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length){if(this.running=!1,this.operatorList.lastChunk)this.gfx.endDrawing(),bf.#t.delete(this._canvas),this.callback()}}}var PM="6.3.289",NM="1c8020a7d";class zr{#e=null;#t=null;#n;#s=null;#i=!1;#a=!1;#r=null;#o;#l=null;#c=null;static#u=null;static get _keyboardManager(){return Mt(this,"_keyboardManager",new kr([[["Escape"],zr.prototype._hideDropdownFromKeyboard],[["Space"],zr.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight"],zr.prototype._moveToNext],[["ArrowUp","ArrowLeft"],zr.prototype._moveToPrevious],[["Home"],zr.prototype._moveToBeginning],[["End"],zr.prototype._moveToEnd]]))}constructor({editor:e=null,uiManager:t=null}){if(e)this.#a=!1,this.#r=e;else this.#a=!0;this.#c=e?._uiManager||t,this.#o=this.#c._eventBus,this.#n=e?.color?.toUpperCase()||this.#c?.highlightColors.values().next().value||"#FFFF98",zr.#u||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){let e=this.#e=document.createElement("button");if(e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",this.#r)e.ariaControls=`${this.#r.id}_colorpicker_dropdown`;let t=this.#c._signal;e.addEventListener("click",this.#g.bind(this),{signal:t}),e.addEventListener("keydown",this.#p.bind(this),{signal:t});let n=this.#t=document.createElement("span");return n.className="swatch",n.ariaHidden="true",n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#s=this.#h();return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}#h(){let e=document.createElement("div"),t=this.#c._signal;if(e.addEventListener("contextmenu",ca,{signal:t}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),this.#r)e.id=`${this.#r.id}_colorpicker_dropdown`;for(let[n,s]of this.#c.highlightColors){let i=document.createElement("button");i.tabIndex="0",i.role="option",i.setAttribute("data-color",s),i.title=n,i.setAttribute("data-l10n-id",zr.#u[n]);let r=document.createElement("span");i.append(r),r.className="swatch",r.style.backgroundColor=s,i.ariaSelected=s===this.#n,i.addEventListener("click",this.#d.bind(this,s),{signal:t}),e.append(i)}return e.addEventListener("keydown",this.#p.bind(this),{signal:t}),e}#d(e,t){t.stopPropagation(),this.#o.dispatch("switchannotationeditorparams",{source:this,type:Tn.HIGHLIGHT_COLOR,value:e}),this.update(e)}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#g(e);return}let t=e.target.getAttribute("data-color");if(!t)return;this.#d(t,e)}_moveToNext(e){if(!this.#m){this.#g(e);return}if(e.target===this.#e){this.#s.firstElementChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#s?.firstElementChild||e.target===this.#e){if(this.#m)this._hideDropdownFromKeyboard();return}if(!this.#m)this.#g(e);e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#m){this.#g(e);return}this.#s.firstElementChild?.focus()}_moveToEnd(e){if(!this.#m){this.#g(e);return}this.#s.lastElementChild?.focus()}#p(e){zr._keyboardManager.exec(this,e)}#g(e){if(this.#m){this.hideDropdown();return}if(this.#i=e.detail===0,!this.#l)this.#l=new AbortController,window.addEventListener("pointerdown",this.#f.bind(this),{signal:this.#c.combinedSignal(this.#l)});if(this.#e.ariaExpanded="true",this.#s){this.#s.classList.remove("hidden");return}let t=this.#s=this.#h();this.#e.append(t)}#f(e){if(this.#s?.contains(e.target))return;this.hideDropdown()}hideDropdown(){this.#s?.classList.add("hidden"),this.#e.ariaExpanded="false",this.#l?.abort(),this.#l=null}get#m(){return this.#s&&!this.#s.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(this.#a)return;if(!this.#m){this.#r?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}update(e){if(this.#t)this.#t.style.backgroundColor=e;if(!this.#s)return;let t=this.#c.highlightColors.values();for(let n of this.#s.children)n.ariaSelected=t.next().value===e.toUpperCase()}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#s?.remove(),this.#s=null}}class cu{#e=null;#t=!1;#n=null;#s=null;static#i=null;constructor(e){this.#n=e,this.#s=e._uiManager,cu.#i||=Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"})}renderButton(){if(this.#e)return this.#e;let{editorType:e,colorType:t,colorAndOpacityType:n,opacityType:s,color:i,opacity:r}=this.#n,o=this.#t=Wn.isAlphaColorInputSupported&&s!==void 0,l=this.#e=document.createElement("input");if(l.type="color",o){l.setAttribute("alpha","");let c=ct.hexNums[Math.round((r??1)*255)];l.value=(i||"#000000")+c}else l.value=i||"#000000";return l.className="basicColorPicker",l.tabIndex=0,l.setAttribute("data-l10n-id",cu.#i[e]),l.addEventListener("input",()=>{if(o){let c=uu(l.value);if(!c)return;let[h,d,m,p]=c,b=ct.makeHexColor(h,d,m);if(n!==void 0)this.#s.updateParams(n,{color:b,opacity:p});else this.#s.updateParams(t,b),this.#s.updateParams(s,p)}else this.#s.updateParams(t,l.value)},{signal:this.#s._signal}),l}update(e){if(!this.#e)return;if(this.#t){let t=ct.hexNums[Math.round(this.#n.opacity*255)];this.#e.value=e+t}else this.#e.value=e}updateOpacity(e){if(!this.#e||!this.#t)return;let t=ct.hexNums[Math.round(e*255)];this.#e.value=this.#n.color+t}destroy(){this.#e?.remove(),this.#e=null}hideDropdown(){}}function w7(e){return Math.floor(bs(e,0,1)*255).toString(16).padStart(2,"0")}function Qh(e){return bs(e,0,1)*255}class n2{static CMYK_G([e,t,n,s]){return["G",1-Math.min(1,0.3*e+0.59*n+0.11*t+s)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=Qh(e),[e,e,e]}static G_HTML([e]){let t=w7(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return["G",0.3*e+0.59*t+0.11*n]}static RGB_rgb(e){return e.map(Qh)}static RGB_HTML(e){return`#${e.map(w7).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,s]){return["RGB",1-Math.min(1,e+s),1-Math.min(1,n+s),1-Math.min(1,t+s)]}static CMYK_rgb([e,t,n,s]){return[Qh(1-Math.min(1,e+s)),Qh(1-Math.min(1,n+s)),Qh(1-Math.min(1,t+s))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let s=1-e,i=1-t,r=1-n,o=Math.min(s,i,r);return["CMYK",s,i,r,o]}}class CS{create(e,t,n=!1){if(e<=0||t<=0)throw Error("Invalid SVG dimensions");let s=this._createSVG("svg:svg");if(s.setAttribute("version","1.1"),!n)s.setAttribute("width",`${e}px`),s.setAttribute("height",`${t}px`);return s.setAttribute("preserveAspectRatio","none"),s.setAttribute("viewBox",`0 0 ${e} ${t}`),s}createElement(e){if(typeof e!=="string")throw Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){Dn("Abstract method `_createSVG` called.")}}class fu extends CS{_createSVG(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}}var BM=9,ic=new WeakSet,HM=new Date().getTimezoneOffset()*60*1000;class rm{static create(e){switch(e.data.annotationType){case Is.LINK:return new _m(e);case Is.TEXT:return new _S(e);case Is.WIDGET:switch(e.data.fieldType){case"Tx":return new IS(e);case"Btn":if(e.data.radioButton)return new MS(e);else if(e.data.checkBox)return new qS(e);return new FS(e);case"Ch":return new LS(e);case"Sig":return new RS(e)}return new ml(e);case Is.POPUP:return new hm(e);case Is.FREETEXT:return new v2(e);case Is.LINE:return new PS(e);case Is.SQUARE:return new NS(e);case Is.CIRCLE:return new BS(e);case Is.POLYLINE:return new S2(e);case Is.CARET:return new US(e);case Is.INK:return new Im(e);case Is.POLYGON:return new HS(e);case Is.HIGHLIGHT:return new k2(e);case Is.UNDERLINE:return new zS(e);case Is.SQUIGGLY:return new GS(e);case Is.STRIKEOUT:return new VS(e);case Is.STAMP:return new x2(e);case Is.FILEATTACHMENT:return new $S(e);case Is.RICHMEDIA:case Is.SCREEN:case Is.SOUND:return new A2(e);default:return new ks(e)}}}class ks{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:s=!1}={}){if(this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t)this.contentElement=this.container=this._createContainer(n);if(s)this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e?.str||t?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return ks._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){let{data:e}=this,t=this.annotationStorage?.getEditor(e.id);if(t)return t.getData();return e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){let e=this.annotationStorage?.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;let{quadPoints:t,inkLists:n,rect:s}=this.data,i=-1/0,r=-1/0;if(t?.length>=8){for(let o=0;o<t.length;o+=8)if(t[o+1]>r)r=t[o+1],i=t[o+2];else if(t[o+1]===r)i=Math.max(i,t[o+2]);return[i,r]}if(n?.length>=1){for(let o of n)for(let l=0,c=o.length;l<c;l+=2)if(o[l+1]>r)r=o[l+1],i=o[l];else if(o[l+1]===r)i=Math.max(i,o[l]);if(i!==1/0)return[i,r]}if(s)return[s[2],s[3]];return null}_normalizePoint(e){let{page:{view:t},viewport:{rawDims:{pageWidth:n,pageHeight:s,pageX:i,pageY:r}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-i)/n,e[1]=100*(e[1]-r)/s,e}get commentText(){let{data:e}=this;return this.annotationStorage.getRawValue(`pdfjs_internal_editor_${e.id}`)?.popup?.contents||e.contentsObj?.str||""}set commentText(e){let{data:t}=this,n={deleted:!e,contents:e||""};if(!this.annotationStorage.updateEditor(t.id,{popup:n}))this.annotationStorage.setValue(`pdfjs_internal_editor_${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:n,popupRef:t.popupRef,modificationDate:new Date});if(!e)this.removePopup()}removePopup(){(this.#n?.popup||this.popup)?.remove(),this.#n=this.popup=null}updateEdited(e){if(!this.container)return;if(e.rect)this.#e||={rect:this.data.rect.slice(0)};let{rect:t,popup:n}=e;if(t)this.#s(t);let s=this.#n?.popup||this.popup;if(!s&&n?.text)this._createPopup(n),s=this.#n.popup;if(!s)return;if(s.updateEdited(e),n?.deleted)s.remove(),this.#n=null,this.popup=null}resetEdited(){if(!this.#e)return;this.#s(this.#e.rect),this.#n?.popup.resetEdited(),this.#e=null}#s(e){let{container:{style:t},data:{rect:n,rotation:s},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:r,pageX:o,pageY:l}}}}=this;if(n?.splice(0,4,...e),t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(r-e[3]+l)/r}%`,s===0)t.width=`${100*(e[2]-e[0])/i}%`,t.height=`${100*(e[3]-e[1])/r}%`;else this.setRotation(s)}_createContainer(e){let{data:t,parent:{page:n,viewport:s}}=this,i=document.createElement("section");if(i.setAttribute("data-annotation-id",t.id),!(this instanceof ml)&&!(this instanceof _m)&&!(this instanceof A2))i.tabIndex=0;let{style:r}=i;if(r.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText)i.title=t.alternativeText;if(t.noRotate)i.classList.add("norotate");if(!t.rect||this instanceof hm){let{rotation:v}=t;if(!t.hasOwnCanvas&&v!==0)this.setRotation(v,i);return i}let{width:o,height:l}=this;if(!e&&t.borderStyle.width>0){r.borderWidth=`${t.borderStyle.width}px`;let v=t.borderStyle.horizontalCornerRadius,k=t.borderStyle.verticalCornerRadius;if(v>0||k>0){let T=`calc(${v}px * var(--total-scale-factor)) / calc(${k}px * var(--total-scale-factor))`;r.borderRadius=T}switch(t.borderStyle.style){case mf.SOLID:r.borderStyle="solid";break;case mf.DASHED:r.borderStyle="dashed";break;case mf.BEVELED:on("Unimplemented border style: beveled");break;case mf.INSET:on("Unimplemented border style: inset");break;case mf.UNDERLINE:r.borderBottomStyle="solid";break;default:break}let A=t.borderColor||null;if(A)this.#t=!0,r.borderColor=ct.makeHexColor(...A);else r.borderWidth=0}let c=ct.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:h,pageHeight:d,pageX:m,pageY:p}=s.rawDims;r.left=`${100*(c[0]-m)/h}%`,r.top=`${100*(c[1]-p)/d}%`;let{rotation:b}=t;if(t.hasOwnCanvas||b===0)r.width=`${100*o/h}%`,r.height=`${100*l/d}%`;else this.setRotation(b,i);return i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:s}=this.parent.viewport.rawDims,{width:i,height:r}=this;if(e%180!==0)[i,r]=[r,i];t.style.width=`${100*i/n}%`,t.style.height=`${100*r/s}%`,t.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){let e=(t,n,s)=>{let i=s.detail[t],r=i[0],o=i.slice(1);s.target.style[n]=n2[`${r}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[n]:n2[`${r}_rgb`](o)})};return Mt(this,"_commonActions",{display:(t)=>{let{display:n}=t.detail,s=n%2===1;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:s,noPrint:n===1||n===2})},print:(t)=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:(t)=>{let{hidden:n}=t.detail;this.container.style.visibility=n?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:n,noView:n})},focus:(t)=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:(t)=>{t.target.title=t.detail.userName},readonly:(t)=>{t.target.disabled=t.detail.readonly},required:(t)=>{this._setRequired(t.target,t.detail.required)},bgColor:(t)=>{e("bgColor","backgroundColor",t)},fillColor:(t)=>{e("fillColor","backgroundColor",t)},fgColor:(t)=>{e("fgColor","color",t)},textColor:(t)=>{e("textColor","color",t)},borderColor:(t)=>{e("borderColor","borderColor",t)},strokeColor:(t)=>{e("strokeColor","borderColor",t)},rotation:(t)=>{let n=t.detail.rotation;this.setRotation(n),this.annotationStorage.setValue(this.data.id,{rotation:n})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let s of Object.keys(t.detail))(e[s]||n[s])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[s,i]of Object.entries(t)){let r=n[s];if(r){let o={detail:{[s]:i},target:e};r(o),delete t[s]}}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,s,i]=this.data.rect.map(Math.fround);if(e.length===8){let[v,k,A,T]=e.subarray(2,6);if(s===v&&i===k&&t===A&&n===T)return}let{style:r}=this.container,o;if(this.#t){let{borderColor:v,borderWidth:k}=r;r.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${v}" stroke-width="${k}">`],this.container.classList.add("hasBorder")}let l=s-t,c=i-n,{svgFactory:h}=this,d=h.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";let m=h.createElement("defs");d.append(m);let p=h.createElement("clipPath"),b=`clippath_${this.data.id}`;p.setAttribute("id",b),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let v=2,k=e.length;v<k;v+=8){let A=e[v],T=e[v+1],E=e[v+2],I=e[v+3],_=h.createElement("rect"),q=(E-t)/l,P=(i-T)/c,N=(A-E)/l,H=(T-I)/c;_.setAttribute("x",q),_.setAttribute("y",P),_.setAttribute("width",N),_.setAttribute("height",H),p.append(_),o?.push(`<rect vector-effect="non-scaling-stroke" x="${q}" y="${P}" width="${N}" height="${H}"/>`)}if(this.#t)o.push("</g></svg>')"),r.backgroundImage=o.join("");this.container.append(d),this.container.style.clipPath=`url(#${b})`}_createPopup(e=null){let{data:t}=this,n,s;if(e)n={str:e.text},s=e.date;else n=t.contentsObj,s=t.modificationDate;this.#n=new hm({data:{color:t.color,titleObj:t.titleObj,modificationDate:s,contentsObj:n,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]})}get hasPopupElement(){return!!(this.#n||this.popup||this.data.popupRef)}get extraPopupElement(){return this.#n}render(){Dn("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let s=this._fieldObjects.get(e)||[];for(let{page:i,id:r,exportValues:o}of s){if(i===-1)continue;if(r===t)continue;let l=typeof o==="string"?o:null,c=document.querySelector(`[data-element-id="${r}"]`);if(c&&!ic.has(c)){on(`_getElementsByName - element not allowed: ${r}`);continue}n.push({id:r,exportValue:l,domElement:c})}return n}for(let s of document.getElementsByName(e)){let{exportValue:i}=s,r=s.getAttribute("data-element-id");if(r===t)continue;if(!ic.has(s))continue;n.push({id:r,exportValue:i,domElement:s})}return n}show(){if(this.container)this.container.hidden=!1;this.popup?.maybeShow()}hide(){if(this.container)this.container.hidden=!0;this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}updateOC(e){if(!this.data.oc||!e)return;if(e.isVisible(this.data.oc))this.show();else this.hide()}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?"transparent":ct.makeHexColor(...t)}}class jS extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});this.editor=e.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){let{editor:e}=this;if(!e.hasComment)return;this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){if(this.editor.comment=e,!e)this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}class _m extends ks{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement("a");n.setAttribute("data-element-id",e.id);let s=!1;if(e.url)t.addLinkAttributes(n,e.url,e.newWindow),s=!0;else if(e.action)this._bindNamedAction(n,e.action,e.overlaidText),s=!0;else if(e.attachment)this.#t(n,e.attachmentId,e.attachment,e.overlaidText,e.attachmentDest),s=!0;else if(e.setOCGState)this.#n(n,e.setOCGState,e.overlaidText),s=!0;else if(e.dest)this._bindLink(n,e.dest,e.overlaidText),s=!0;else{if(e.actions&&(e.actions.has("Action")||e.actions.has("Mouse Up")||e.actions.has("Mouse Down"))&&this.enableScripting&&this.hasJSActions)this._bindJSAction(n,e),s=!0;if(e.resetForm)this._bindResetFormAction(n,e.resetForm),s=!0;else if(this.isTooltipOnly&&!s)this._bindLink(n,""),s=!0}if(this.container.classList.add("linkAnnotation"),s)this.contentElement=n,this.container.append(n);return this.container}#e(){this.container.setAttribute("data-internal-link","")}_bindLink(e,t,n=""){if(e.href=this.linkService.getDestinationHash(t),e.onclick=()=>{if(t)this.linkService.goToDestination(t);return!1},t||t==="")this.#e();if(n)e.title=n}_bindNamedAction(e,t,n=""){if(e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),n)e.title=n;this.#e()}#t(e,t,n,s="",i=null){if(e.href=this.linkService.getAnchorUrl(""),n.description)e.title=n.description;else if(s)e.title=s;let r=async()=>{let o=await this.linkService.getAttachmentContent(t);if(o)this.downloadManager?.openOrDownloadData(o,n.filename,i)};e.onclick=()=>(r(),!1),this.#e()}#n(e,t,n=""){if(e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),n)e.title=n;this.#e()}_bindJSAction(e,{actions:t,id:n,overlaidText:s}){e.href=this.linkService.getAnchorUrl("");let i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let r of t.keys()){let o=i.get(r);if(!o)continue;e[o]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:r}}),!1)}if(s)e.title=s;e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(!n)e.href=this.linkService.getAnchorUrl("");if(this.#e(),!this._fieldObjects){if(on('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),!n)e.onclick=()=>!1;return}e.onclick=()=>{n?.();let{fields:s,refs:i,include:r}=t,o=[];if(s.length!==0||i.length!==0){let h=new Set(i);for(let d of s){let m=this._fieldObjects.get(d)||[];for(let{id:p}of m)h.add(p)}for(let d of this._fieldObjects.values())for(let m of d)if(h.has(m.id)===r)o.push(m)}else for(let h of this._fieldObjects.values())o.push(...h);let l=this.annotationStorage,c=[];for(let h of o){let{id:d}=h;switch(c.push(d),h.type){case"text":{let p=h.defaultValue||"";l.setValue(d,{value:p});break}case"checkbox":case"radiobutton":{let p=h.defaultValue===h.exportValues;l.setValue(d,{value:p});break}case"combobox":case"listbox":{let p=h.defaultValue||"";l.setValue(d,{value:p});break}default:continue}let m=document.querySelector(`[data-element-id="${d}"]`);if(!m)continue;else if(!ic.has(m)){on(`_bindResetFormAction - element not allowed: ${d}`);continue}m.dispatchEvent(new Event("resetform"))}if(this.enableScripting)this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:c,name:"ResetForm"}});return!1}}}class _S extends ks{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");let e=document.createElement("img");if(e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container.append(e),this.container}}class ml extends ks{render(){return this.container}_getKeyModifier(e){return Wn.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,s,i){if(n.includes("mouse"))e.addEventListener(n,(r)=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:i(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})});else e.addEventListener(n,(r)=>{if(n==="blur"){if(!t.focused||!r.relatedTarget)return;t.focused=!1}else if(n==="focus"){if(t.focused)return;t.focused=!0}if(!i)return;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:i(r)}})})}_setEventListeners(e,t,n,s){let{actions:i}=this.data;for(let[r,o]of n)if(o==="Action"||i?.has(o)){if(o==="Focus"||o==="Blur")t||={focused:!1};if(this._setEventListener(e,t,r,o,s),o==="Focus"&&!i?.has("Blur"))this._setEventListener(e,t,"blur","Blur",null);else if(o==="Blur"&&!i?.has("Focus"))this._setEventListener(e,t,"focus","Focus",null)}}_setTextStyle(e){let t=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||BM,i=e.style,r,o=2,l=(c)=>Math.round(10*c)/10;if(this.data.multiLine){let c=Math.abs(this.data.rect[3]-this.data.rect[1]-2),h=Math.round(c/(1.35*s))||1,d=c/h;r=Math.min(s,l(d/1.35))}else{let c=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(s,l(c/1.35))}if(i.fontSize=`calc(${r}px * var(--total-scale-factor))`,i.color=ct.makeHexColor(...n),this.data.textAlignment!==null&&!this.data.comb)i.textAlign=t[this.data.textAlignment]}_setRequired(e,t){if(t)e.setAttribute("required",!0);else e.removeAttribute("required");e.setAttribute("aria-required",t)}}class IS extends ml{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,s){let i=this.annotationStorage;for(let r of this._getElementsByName(e.name,e.id)){if(r.domElement)r.domElement[t]=n;i.setValue(r.id,{[s]:n})}}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add("textWidgetAnnotation");let n=null;if(this.renderForms){let s=e.getValue(t,{value:this.data.fieldValue}),i=s.value||"",r=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;if(r&&i.length>r)i=i.slice(0,r);let o=s.formattedValue||this.data.textContent?.join(`
119
- `)||null;if(o&&this.data.comb)o=o.replaceAll(/\s+/g,"");let l={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){if(n=document.createElement("textarea"),n.textContent=o??i,this.data.doNotScroll)n.style.overflowY="hidden"}else if(n=document.createElement("input"),n.type=this.data.password?"password":"text",n.setAttribute("value",o??i),this.data.doNotScroll)n.style.overflowX="hidden";if(this.data.hasOwnCanvas){if(this.container.classList.add("hasOwnCanvas"),e.has(t))this.container.classList.add("sandboxModified")}ic.add(n),this.contentElement=n,n.setAttribute("data-element-id",t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=0;let{datetimeFormat:c,datetimeType:h,timeStep:d}=this.data,m=!!h&&this.enableScripting;if(c)n.title=c;if(this._setRequired(n,this.data.required),r)n.maxLength=r;n.addEventListener("input",(b)=>{e.setValue(t,{value:b.target.value}),this.setPropertyOnSiblings(n,"value",b.target.value,"value"),l.formattedValue=null}),n.addEventListener("resetform",(b)=>{let v=this.data.defaultFieldValue??"";n.value=l.userValue=v,l.formattedValue=null});let p=(b)=>{let{formattedValue:v}=l;if(v!==null&&v!==void 0)b.target.value=v;b.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener("focus",(v)=>{if(l.focused)return;let{target:k}=v;if(m){if(k.type=h,d)k.step=d}if(l.userValue){let A=l.userValue;if(m)if(h==="time"){let T=new Date(A),E=[T.getHours(),T.getMinutes(),T.getSeconds()];k.value=E.map((I)=>I.toString().padStart(2,"0")).join(":")}else k.value=new Date(A-HM).toISOString().split(h==="date"?"T":".",1)[0];else k.value=A}if(l.lastCommittedValue=k.value,l.commitKey=1,!this.data.actions?.has("Focus"))l.focused=!0}),n.addEventListener("updatefromsandbox",(v)=>{this.container.classList.add("sandboxModified");let k={value(A){if(l.userValue=A.detail.value??"",!m)e.setValue(t,{value:l.userValue.toString()});A.target.value=l.userValue},formattedValue(A){let{formattedValue:T}=A.detail;if(l.formattedValue=T,T!==null&&T!==void 0&&A.target!==document.activeElement)A.target.value=T;let E={formattedValue:T};if(m)E.value=T;e.setValue(t,E)},selRange(A){A.target.setSelectionRange(...A.detail.selRange)},charLimit:(A)=>{let{charLimit:T}=A.detail,{target:E}=A;if(T===0){E.removeAttribute("maxLength");return}E.setAttribute("maxLength",T);let I=l.userValue;if(!I||I.length<=T)return;I=I.slice(0,T),E.value=l.userValue=I,e.setValue(t,{value:I}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:I,willCommit:!0,commitKey:1,selStart:E.selectionStart,selEnd:E.selectionEnd}})}};this._dispatchEventFromSandbox(k,v)}),n.addEventListener("keydown",(v)=>{l.commitKey=1;let k=-1;if(v.key==="Escape")k=0;else if(v.key==="Enter"&&!this.data.multiLine)k=2;else if(v.key==="Tab")l.commitKey=3;if(k===-1)return;let{value:A}=v.target;if(l.lastCommittedValue===A)return;l.lastCommittedValue=A,l.userValue=A,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:A,willCommit:!0,commitKey:k,selStart:v.target.selectionStart,selEnd:v.target.selectionEnd}})});let b=p;if(p=null,n.addEventListener("blur",(v)=>{if(!l.focused||!v.relatedTarget)return;if(!this.data.actions?.has("Blur"))l.focused=!1;let{target:k}=v,{value:A}=k;if(m){if(A&&h==="time"){let T=A.split(":").map((E)=>parseInt(E,10));A=new Date(2000,0,1,T[0],T[1],T[2]||0).valueOf(),k.step=""}else{if(!A.includes("T"))A=`${A}T00:00`;A=new Date(A).valueOf()}k.type="text"}if(l.userValue=A,l.lastCommittedValue!==A)this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:A,willCommit:!0,commitKey:l.commitKey,selStart:v.target.selectionStart,selEnd:v.target.selectionEnd}});b(v)}),this.data.actions?.has("Keystroke"))n.addEventListener("beforeinput",(v)=>{l.lastCommittedValue=null;let{data:k,target:A}=v,{value:T,selectionStart:E,selectionEnd:I}=A,_=E,q=I;switch(v.inputType){case"deleteWordBackward":{let P=/\w/;while(_>0&&!P.test(T[_-1]))_--;while(_>0&&P.test(T[_-1]))_--;break}case"deleteWordForward":{let P=T.substring(E).match(/^\W*\w*/);if(P)q+=P[0].length;break}case"deleteContentBackward":if(E===I)_-=1;break;case"deleteContentForward":if(E===I)q+=1;break}v.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:T,change:k||"",willCommit:!1,selStart:_,selEnd:q}})});this._setEventListeners(n,l,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(v)=>v.target.value)}if(p)n.addEventListener("blur",p);if(this.data.comb){let v=(this.data.rect[2]-this.data.rect[0])/r;n.classList.add("comb"),n.style.setProperty("--comb-width",`calc(${v}px * var(--total-scale-factor))`);let k=this.data.textAlignment;if(k===1||k===2){let A=()=>{let T=r-n.value.length;n.style.setProperty("--comb-offset",`${k===1?T>>1:T}`)};A();for(let T of["input","blur","resetform","updatefromsandbox"])n.addEventListener(T,A)}}}else if(n=document.createElement("div"),n.textContent=this.data.fieldValue,n.style.verticalAlign="middle",n.style.display="table-cell",this.data.hasOwnCanvas)n.hidden=!0;return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class RS extends ml{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class qS extends ml{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,s=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;if(typeof s==="string")s=s!=="Off",e.setValue(n,{value:s});this.container.classList.add("buttonWidgetAnnotation","checkBox");let i=document.createElement("input");if(ic.add(i),i.setAttribute("data-element-id",n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type="checkbox",i.name=t.fieldName,s)i.setAttribute("checked",!0);if(i.setAttribute("exportValue",t.exportValue),i.tabIndex=0,i.addEventListener("change",(r)=>{let{name:o,checked:l}=r.target;for(let c of this._getElementsByName(o,n)){let h=l&&c.exportValue===t.exportValue;if(c.domElement)c.domElement.checked=h;e.setValue(c.id,{value:h})}e.setValue(n,{value:l})}),i.addEventListener("resetform",(r)=>{let o=t.defaultFieldValue||"Off";r.target.checked=o===t.exportValue}),this.enableScripting&&this.hasJSActions)i.addEventListener("updatefromsandbox",(r)=>{let o={value(l){l.target.checked=l.detail.value!=="Off",e.setValue(n,{value:l.target.checked})}};this._dispatchEventFromSandbox(o,r)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(r)=>r.target.checked);return this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class MS extends ml{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let e=this.annotationStorage,t=this.data,n=t.id,s=e.getValue(n,{value:t.buttonValue!==null&&t.fieldValue===t.buttonValue}).value;if(typeof s==="string")s=s!==t.buttonValue,e.setValue(n,{value:s});if(s)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement("input");if(ic.add(i),i.setAttribute("data-element-id",n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type="radio",i.name=t.fieldName,s)i.setAttribute("checked",!0);if(i.tabIndex=0,i.addEventListener("change",(r)=>{let{name:o,checked:l}=r.target;for(let c of this._getElementsByName(o,n))e.setValue(c.id,{value:!1});e.setValue(n,{value:l})}),i.addEventListener("resetform",(r)=>{let o=t.defaultFieldValue;r.target.checked=o!==null&&o!==void 0&&o===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener("updatefromsandbox",(o)=>{let l={value:(c)=>{let h=r===c.detail.value;for(let d of this._getElementsByName(c.target.name)){let m=h&&d.id===n;if(d.domElement)d.domElement.checked=m;e.setValue(d.id,{value:m})}}};this._dispatchEventFromSandbox(l,o)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(o)=>o.target.checked)}return this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class FS extends _m{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");let t=e.lastChild;if(this.enableScripting&&this.hasJSActions&&t)this._setDefaultPropertiesFromJS(t),t.addEventListener("updatefromsandbox",(n)=>{this._dispatchEventFromSandbox({},n)});return e}}class LS extends ml{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),s=document.createElement("select");ic.add(s),s.setAttribute("data-element-id",t),s.disabled=this.data.readOnly,this._setRequired(s,this.data.required),s.name=this.data.fieldName,s.tabIndex=0;let i=this.data.combo&&this.data.options.length>0;if(!this.data.combo){if(s.size=this.data.options.length,this.data.multiSelect)s.multiple=!0}s.addEventListener("resetform",(d)=>{let m=this.data.defaultFieldValue;for(let p of s.options)p.selected=p.value===m});let r=(d,m)=>{let p=m.replaceAll(" "," ");if(d.textContent=p,p!==m)d.setAttribute("display-value",m)};for(let d of this.data.options){let m=document.createElement("option");if(r(m,d.displayValue),m.value=d.exportValue,n.value.includes(d.exportValue))m.setAttribute("selected",!0),i=!1;s.append(m)}let o=null;if(i){let d=document.createElement("option");d.value=" ",d.setAttribute("hidden",!0),d.setAttribute("selected",!0),s.prepend(d),o=()=>{d.remove(),s.removeEventListener("input",o),o=null},s.addEventListener("input",o)}let l=(d)=>{let m=d?"value":"textContent",{options:p,multiple:b}=s;if(!b)return p.selectedIndex===-1?null:p[p.selectedIndex][m];return Array.prototype.filter.call(p,(v)=>v.selected).map((v)=>v[m])},c=l(!1),h=(d)=>{let m=d.target.options;return Array.prototype.map.call(m,(p)=>({displayValue:p.getAttribute("display-value")||p.textContent,exportValue:p.value}))};if(this.enableScripting&&this.hasJSActions)s.addEventListener("updatefromsandbox",(d)=>{let m={value(p){o?.();let b=p.detail.value,v=new Set(Array.isArray(b)?b:[b]);for(let k of s.options)k.selected=v.has(k.value);e.setValue(t,{value:l(!0)}),c=l(!1)},multipleSelection(p){s.multiple=!0},remove(p){let b=s.options,v=p.detail.remove;if(b[v].selected=!1,s.remove(v),b.length>0){if(Array.prototype.findIndex.call(b,(A)=>A.selected)===-1)b[0].selected=!0}e.setValue(t,{value:l(!0),items:h(p)}),c=l(!1)},clear(p){while(s.length!==0)s.remove(0);e.setValue(t,{value:null,items:[]}),c=l(!1)},insert(p){let{index:b,displayValue:v,exportValue:k}=p.detail.insert,A=s.children[b],T=document.createElement("option");if(r(T,v),T.value=k,A)A.before(T);else s.append(T);e.setValue(t,{value:l(!0),items:h(p)}),c=l(!1)},items(p){let{items:b}=p.detail;while(s.length!==0)s.remove(0);for(let v of b){let{displayValue:k,exportValue:A}=v,T=document.createElement("option");r(T,k),T.value=A,s.append(T)}if(s.options.length>0)s.options[0].selected=!0;e.setValue(t,{value:l(!0),items:h(p)}),c=l(!1)},indices(p){let b=new Set(p.detail.indices);for(let v of p.target.options)v.selected=b.has(v.index);e.setValue(t,{value:l(!0)}),c=l(!1)},editable(p){p.target.disabled=!p.detail.editable}};this._dispatchEventFromSandbox(m,d)}),s.addEventListener("input",(d)=>{let m=l(!0),p=l(!1);e.setValue(t,{value:m}),d.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:c,change:p,changeEx:m,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(d)=>d.target.value);else s.addEventListener("input",function(d){e.setValue(t,{value:l(!0)})});if(this.data.combo)this._setTextStyle(s);return this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class hm extends ks{constructor(e){let{data:t,elements:n,parent:s}=e,i=!!s._commentManager;super(e,{isRenderable:!i&&ks._hasPopupData(t)});if(this.elements=n,i&&ks._hasPopupData(t)){let r=this.popup=this.#e();for(let o of n)o.popup=r}else this.popup=null}#e(){return new OS({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})}render(){let{container:e}=this;e.classList.add("popupAnnotation"),e.role="comment";let t=this.popup=this.#e(),n=[];for(let s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",n.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",n.map((s)=>`pdfjs_internal_id_${s}`).join(",")),this.container}}class OS{#e=null;#t=this.#G.bind(this);#n=this.#S.bind(this);#s=this.#E.bind(this);#i=this.#H.bind(this);#a=null;#r=null;#o=null;#l=null;#c=null;#u=null;#h=null;#d=!1;#p=null;#g=null;#f=null;#m=null;#b=null;#w=null;#y=null;#v=null;#x=null;#k=null;#A=!1;#T=null;#I=null;constructor({container:e,color:t,elements:n,titleObj:s,modificationDate:i,contentsObj:r,richText:o,parent:l,rect:c,parentRect:h,open:d,commentManager:m=null}){if(this.#r=e,this.#x=s,this.#o=r,this.#v=o,this.#u=l,this.#a=t,this.#y=c,this.#h=h,this.#c=n,this.#e=m,this.#T=n[0],this.#l=lm.toDateObject(i),this.trigger=n.flatMap((p)=>p.getElementsToTriggerPopup()),!m){if(this.#j(),this.#r.hidden=!0,d)this.#H()}}#j(){if(this.#g)return;this.#g=new AbortController;let{signal:e}=this.#g;for(let t of this.trigger)t.addEventListener("click",this.#i,{signal:e}),t.addEventListener("pointerenter",this.#s,{signal:e}),t.addEventListener("pointerleave",this.#n,{signal:e}),t.classList.add("popupTriggerArea");for(let t of this.#c)t.container?.addEventListener("keydown",this.#t,{signal:e})}#C(){let e=this.#c.find((t)=>t.hasCommentButton);if(!e)return;this.#b=e._normalizePoint(e.commentButtonPosition)}renderCommentButton(){if(this.#m){if(!this.#m.parentNode)this.#T.container.after(this.#m);return}if(!this.#b)this.#C();if(!this.#b)return;let{signal:e}=this.#g=new AbortController,t=this.#T.hasOwnCommentButton,n=()=>{this.#e.toggleCommentPopup(this,!0,void 0,!t)},s=()=>{this.#e.toggleCommentPopup(this,!1,!0,!t)},i=()=>{this.#e.toggleCommentPopup(this,!1,!1)};if(!t){let r=this.#m=document.createElement("button");r.className="annotationCommentButton";let o=this.#T.container;r.style.zIndex=parseInt(o.style.zIndex,10)+1,r.tabIndex=0,r.ariaHasPopup="dialog",r.ariaControls="commentPopup",r.setAttribute("data-l10n-id","pdfjs-show-comment-button"),this.#R(),this.#D(),r.addEventListener("keydown",this.#t,{signal:e}),r.addEventListener("click",n,{signal:e}),r.addEventListener("pointerenter",s,{signal:e}),r.addEventListener("pointerleave",i,{signal:e}),o.after(r)}else{this.#m=this.#T.container;for(let r of this.trigger)r.ariaHasPopup="dialog",r.ariaControls="commentPopup",r.addEventListener("keydown",this.#t,{signal:e}),r.addEventListener("click",n,{signal:e}),r.addEventListener("pointerenter",s,{signal:e}),r.addEventListener("pointerleave",i,{signal:e}),r.classList.add("popupTriggerArea")}}#D(){if(this.#T.extraPopupElement&&!this.#T.editor)return;if(!this.#m)this.renderCommentButton();let[e,t]=this.#b,{style:n}=this.#m;n.left=`calc(${e}%)`,n.top=`calc(${t}% - var(--comment-button-dim))`}#R(){if(this.#T.extraPopupElement)return;if(!this.#m)this.renderCommentButton();this.#m.style.backgroundColor=this.commentButtonColor||""}get commentButtonColor(){let{color:e,opacity:t}=this.#T.commentData;if(!e)return null;return this.#u._commentManager.makeCommentColor(e,t)}focusCommentButton(){setTimeout(()=>{this.#m?.focus()},0)}getData(){let{richText:e,color:t,opacity:n,creationDate:s,modificationDate:i}=this.#T.commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:n,creationDate:s,modificationDate:i}}get elementBeforePopup(){return this.#m}get comment(){return this.#I||=this.#T.commentText,this.#I}set comment(e){if(e===this.comment)return;this.#T.commentText=this.#I=e}focus(){this.#T.container?.focus()}get parentBoundingClientRect(){return this.#T.layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){if(!this.#m)return;this.#m.classList.toggle("selected",e),this.#m.ariaExpanded=t}setSelectedCommentButton(e){this.#m.classList.toggle("selected",e)}get commentPopupPosition(){if(this.#w)return this.#w;let{x:e,y:t,height:n}=this.#m.getBoundingClientRect(),{x:s,y:i,width:r,height:o}=this.#T.layer.getBoundingClientRect();return[(e-s)/r,(t+n-i)/o]}set commentPopupPosition(e){this.#w=e}hasDefaultPopupPosition(){return this.#w===null}get commentButtonPosition(){return this.#b}get commentButtonWidth(){return this.#m.getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){let[t,n]=this.#w||this.commentButtonPosition.map((c)=>c/100),s=this.parentBoundingClientRect,{x:i,y:r,width:o,height:l}=s;this.#e.showDialog(null,this,i+t*o,r+n*l,{...e,parentDimensions:s})}render(){if(this.#p)return;let e=this.#p=document.createElement("div");if(e.className="popup",this.#a){let n=e.style.outlineColor=ct.makeHexColor(...this.#a);e.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`}let t=document.createElement("span");if(t.className="header",this.#x?.str){let n=document.createElement("span");n.className="title",t.append(n),{dir:n.dir,str:n.textContent}=this.#x}if(e.append(t),this.#l){let n=document.createElement("time");n.className="popupDate",n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#l.valueOf()})),n.dateTime=this.#l.toISOString(),t.append(n)}E7({html:this.#q||this.#o.str,dir:this.#o?.dir,className:"popupContent"},e),this.#r.append(e)}get#q(){let e=this.#v,t=this.#o;if(e?.str&&(!t?.str||t.str===e.str))return this.#v.html||null;return null}get#B(){return this.#q?.attributes?.style?.fontSize||0}get#M(){return this.#q?.attributes?.style?.color||null}#L(e){let t=[],n={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:t}]}},s={style:{color:this.#M,fontSize:this.#B?`calc(${this.#B}px * var(--total-scale-factor))`:""}};for(let i of e.split(`
120
- `))t.push({name:"span",value:i,attributes:s});return n}#G(e){if(e.altKey||e.shiftKey||e.ctrlKey||e.metaKey)return;if(e.key==="Enter"||e.key==="Escape"&&this.#d)this.#H()}updateEdited({rect:e,popup:t,deleted:n}){if(this.#e){if(n)this.remove(),this.#I=null;else if(t)if(t.deleted)this.remove();else this.#R(),this.#I=t.text;if(e)this.#b=null,this.#C(),this.#D();return}if(n||t?.deleted){this.remove();return}if(this.#j(),this.#k||={contentsObj:this.#o,richText:this.#v},e)this.#f=null;if(t&&t.text)this.#v=this.#L(t.text),this.#l=lm.toDateObject(t.date),this.#o=null;this.#p?.remove(),this.#p=null}resetEdited(){if(!this.#k)return;({contentsObj:this.#o,richText:this.#v}=this.#k),this.#k=null,this.#p?.remove(),this.#p=null,this.#f=null}remove(){if(this.#g?.abort(),this.#g=null,this.#p?.remove(),this.#p=null,this.#A=!1,this.#d=!1,this.#m?.remove(),this.#m=null,this.trigger)for(let e of this.trigger)e.classList.remove("popupTriggerArea")}#O(){if(this.#f!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:s,pageY:i}}}=this.#u,r=!!this.#h,o=r?this.#h:this.#y;for(let b of this.#c)if(!o||ct.intersect(b.data.rect,o)!==null){o=b.data.rect,r=!0;break}let l=ct.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=5,h=r?o[2]-o[0]+c:0,d=l[0]+h,m=l[1];this.#f=[100*(d-s)/t,100*(m-i)/n];let{style:p}=this.#r;p.left=`${this.#f[0]}%`,p.top=`${this.#f[1]}%`}#H(){if(this.#e){this.#e.toggleCommentPopup(this,!1);return}if(this.#d=!this.#d,this.#d)this.#E(),this.#r.addEventListener("click",this.#i),this.#r.addEventListener("keydown",this.#t);else this.#S(),this.#r.removeEventListener("click",this.#i),this.#r.removeEventListener("keydown",this.#t)}#E(){if(!this.#p)this.render();if(!this.isVisible)this.#O(),this.#r.hidden=!1,this.#r.style.zIndex=parseInt(this.#r.style.zIndex,10)+1000;else if(this.#d)this.#r.classList.add("focused")}#S(){if(this.#r.classList.remove("focused"),this.#d||!this.isVisible)return;this.#r.hidden=!0,this.#r.style.zIndex=parseInt(this.#r.style.zIndex,10)-1000}forceHide(){if(this.#A=this.isVisible,!this.#A)return;this.#r.hidden=!0}maybeShow(){if(this.#e)return;if(this.#j(),!this.#A)return;if(!this.#p)this.#E();this.#A=!1,this.#r.hidden=!1}get isVisible(){return!this.#e&&this.#r.hidden===!1}}class v2 extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=Jt.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){let e=this.contentElement=document.createElement("div");e.classList.add("annotationTextContent"),e.setAttribute("role","comment");for(let t of this.textContent){let n=document.createElement("span");n.textContent=t,e.append(n)}this.container.append(e)}if(!this.data.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this._editOnDoubleClick(),this.container}}class PS extends ks{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let{data:e,width:t,height:n}=this,s=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement("svg:line");if(i.setAttribute("x1",e.rect[2]-e.lineCoordinates[0]),i.setAttribute("y1",e.rect[3]-e.lineCoordinates[1]),i.setAttribute("x2",e.rect[2]-e.lineCoordinates[2]),i.setAttribute("y2",e.rect[3]-e.lineCoordinates[3]),i.setAttribute("stroke-width",e.borderStyle.width||1),i.setAttribute("stroke","transparent"),i.setAttribute("fill","transparent"),s.append(i),this.container.append(s),!e.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class NS extends ks{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let{data:e,width:t,height:n}=this,s=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,r=this.#e=this.svgFactory.createElement("svg:rect");if(r.setAttribute("x",i/2),r.setAttribute("y",i/2),r.setAttribute("width",t-i),r.setAttribute("height",n-i),r.setAttribute("stroke-width",i||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),s.append(r),this.container.append(s),!e.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class BS extends ks{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let{data:e,width:t,height:n}=this,s=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,r=this.#e=this.svgFactory.createElement("svg:ellipse");if(r.setAttribute("cx",t/2),r.setAttribute("cy",n/2),r.setAttribute("rx",t/2-i/2),r.setAttribute("ry",n/2-i/2),r.setAttribute("stroke-width",i||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),s.append(r),this.container.append(s),!e.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class S2 extends ks{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:s},width:i,height:r}=this;if(!t)return this.container;let o=this.svgFactory.create(i,r,!0),l=[];for(let h=0,d=t.length;h<d;h+=2){let m=t[h]-e[0],p=e[3]-t[h+1];l.push(`${m},${p}`)}l=l.join(" ");let c=this.#e=this.svgFactory.createElement(this.svgElementName);if(c.setAttribute("points",l),c.setAttribute("stroke-width",n.width||1),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),o.append(c),this.container.append(o),!s&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class HS extends S2{constructor(e){super(e);this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class US extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){if(this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container}}class Im extends ks{#e=null;#t=[];constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Jt.HIGHLIGHT:Jt.INK}#n(e,t){switch(e){case 90:return{transform:`rotate(90) translate(${-t[0]},${t[1]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};case 180:return{transform:`rotate(180) translate(${-t[2]},${t[1]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]};case 270:return{transform:`rotate(270) translate(${-t[2]},${t[3]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};default:return{transform:`translate(${-t[0]},${t[3]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,rotation:t,inkLists:n,borderStyle:s,popupRef:i}}=this,{transform:r,width:o,height:l}=this.#n(t,e),c=this.svgFactory.create(o,l,!0),h=this.#e=this.svgFactory.createElement("svg:g");c.append(h),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke-linecap","round"),h.setAttribute("stroke-linejoin","round"),h.setAttribute("stroke-miterlimit",10),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),h.setAttribute("transform",r);for(let d of n){let m=this.svgFactory.createElement(this.svgElementName);this.#t.push(m),m.setAttribute("points",d.join(",")),h.append(m)}if(!i&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this.container.append(c),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);let{thickness:t,points:n,rect:s}=e,i=this.#e;if(t>=0)i.setAttribute("stroke-width",t||1);if(n)for(let r=0,o=this.#t.length;r<o;r++)this.#t[r].setAttribute("points",n[r].join(","));if(s){let{transform:r,width:o,height:l}=this.#n(this.data.rotation,s);i.parentElement.setAttribute("viewBox",`0 0 ${o} ${l}`),i.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class k2 extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0});this.annotationEditorType=Jt.HIGHLIGHT}render(){let{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();if(this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),e){let n=document.createElement("mark");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class zS extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();if(this.container.classList.add("underlineAnnotation"),e){let n=document.createElement("u");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class GS extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();if(this.container.classList.add("squigglyAnnotation"),e){let n=document.createElement("u");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class VS extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){let{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();if(this.container.classList.add("strikeoutAnnotation"),e){let n=document.createElement("s");n.classList.add("overlaidText"),n.textContent=e,this.container.append(n)}return this.container}}class x2 extends ks{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});this.annotationEditorType=Jt.STAMP}render(){if(this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();return this._editOnDoubleClick(),this.container}}class $S extends ks{#e=null;constructor(e){super(e,{isRenderable:!0});let{fileId:t,file:n}=this.data;this.filename=n.filename,this.content=n.content,this.fileId=t,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,attachmentId:this.fileId,...n})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:e,data:t}=this,n;if(t.hasAppearance||t.fillAlpha===0)n=document.createElement("div");else if(n=document.createElement("img"),n.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(t.name)?"paperclip":"pushpin"}.svg`,t.fillAlpha&&t.fillAlpha<1)n.style=`filter: opacity(${Math.round(t.fillAlpha*100)}%);`;n.addEventListener("dblclick",this.#t.bind(this)),this.#e=n;let{isMac:s}=Wn.platform;if(e.addEventListener("keydown",(i)=>{if(i.key==="Enter"&&(s?i.metaKey:i.ctrlKey))this.#t()}),!t.popupRef&&this.hasPopupData)this.hasOwnCommentButton=!0,this._createPopup();else n.classList.add("popupTriggerArea");return e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}async#t(){let{fileId:e,filename:t,content:n}=this,s=await this.linkService.getAttachmentContent(e)||n;if(s)this.downloadManager?.openOrDownloadData(s,t)}}class A2 extends ks{#e=new AbortController;#t=null;#n=null;constructor(e){super(e,{isRenderable:!!e.data.richMedia})}render(){this.container.classList.add("mediaAnnotation");let{filename:e}=this.data.richMedia,t=document.createElement("button");return t.className="mediaPlayButton",t.type="button",t.title=t.ariaLabel=e,t.addEventListener("click",()=>this.#s(t),{signal:this.#e.signal}),this.container.append(t),this.container}async#s(e){let{fileId:t,filename:n,contentType:s}=this.data.richMedia;e.disabled=!0;let i;try{i=await this.linkService.getAttachmentContent(t)}catch{return}finally{e.disabled=!1}if(!i||!e.isConnected)return;let{signal:r}=this.#e,o=URL.createObjectURL(new Blob([i],{type:s}));this.#t=o;let l=s.startsWith("audio/"),c=document.createElement(l?"audio":"video");if(this.#n=c,c.className="mediaContent",this._setBackgroundColor(c),c.src=o,c.title=n,c.controls=!0,c.autoplay=!0,c.tabIndex=0,l){let h=!1,d=!1,m=()=>{c.controls=h||d};this.container.addEventListener("pointerenter",()=>{h=!0,m()},{signal:r}),this.container.addEventListener("pointerleave",()=>{h=!1,m()},{signal:r}),this.container.addEventListener("focusin",()=>{d=!0,m()},{signal:r}),this.container.addEventListener("focusout",()=>{d=!1,m()},{signal:r})}c.addEventListener("emptied",()=>this.#i(o),{once:!0,signal:r}),e.replaceWith(c),c.play().catch(()=>{})}#i(e=this.#t){if(e&&e===this.#t)URL.revokeObjectURL(e),this.#t=null}destroy(){if(this.#e.abort(),this.#n)this.#n.pause(),this.#n.removeAttribute("src"),this.#n.load(),this.#n=null;this.#i()}}class T2{#e=null;#t=null;#n=null;#s=new Map;#i=null;#a=null;#r=[];#o=!1;zIndex=0;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:s,page:i,viewport:r,structTreeLayer:o,commentManager:l,linkService:c,annotationStorage:h}){this.div=e,this.#e=t,this.#t=n,this.#i=o||null,this.#a=c||null,this.#n=h||new km,this.page=i,this.viewport=r,this._annotationEditorUIManager=s,this._commentManager=l||null}hasEditableAnnotations(){return this.#s.size>0}async render(e){let{annotations:t,optionalContentConfig:n}=e,s=this.div;sc(s,this.viewport);let i=new Map,r=[],o={data:null,layer:s,linkService:this.#a,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new fu,annotationStorage:this.#n,enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let l of t){if(l.noHTML)continue;let c=l.annotationType===Is.POPUP;if(!c){if(l.rect[2]===l.rect[0]||l.rect[3]===l.rect[1])continue}else{let m=i.get(l.id);if(!m)continue;if(!this._commentManager){r.push(l);continue}o.elements=m}o.data=l;let h=rm.create(o);if(!h.isRenderable)continue;if(!c){if(this.#r.push(h),l.popupRef)i.getOrInsertComputed(l.popupRef,wf).push(h)}let d=h.render();if(l.hidden)d.style.visibility="hidden";if(h.updateOC(n),h._isEditable)this.#s.set(h.data.id,h),this._annotationEditorUIManager?.renderAnnotationElement(h)}await this.#l();for(let l of r){let c=o.elements=i.get(l.id);o.data=l;let h=rm.create(o);if(!h.isRenderable)continue;let d=h.render();if(h.contentElement.id=`pdfjs_internal_id_${l.id}`,l.hidden)d.style.visibility="hidden";c.at(-1).container.after(d)}this.#c()}async#l(){if(this.#r.length===0)return;this.div.replaceChildren();let e=[];if(!this.#o){this.#o=!0;for(let{contentElement:n,data:{hidden:s,id:i,oc:r}}of this.#r){let o=n.id=`pdfjs_internal_id_${i}`,l=n.localName==="a"&&!s&&!r;e.push(this.#i?.getAriaAttributes(o,{enableLinkOwnership:l}).then((c)=>{if(c)for(let[h,d]of c)n.setAttribute(h,d)}))}}this.#r.sort(({data:{rect:[n,s,i,r]}},{data:{rect:[o,l,c,h]}})=>{if(n===i&&s===r)return 1;if(o===c&&l===h)return-1;let d=r,m=s,p=(s+r)/2,b=h,v=l,k=(l+h)/2;if(p>=b&&k<=m)return-1;if(k>=d&&p<=v)return 1;let A=(n+i)/2,T=(o+c)/2;return A-T});let t=document.createDocumentFragment();for(let n of this.#r)if(t.append(n.container),this._commentManager)(n.extraPopupElement?.popup||n.popup)?.renderCommentButton();else if(n.extraPopupElement)t.append(n.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),this.#e){let n=await this.#i?.getAnnotationIds();for(let{contentElement:s}of this.#r){if(n?.has(s.id))continue;this.#e.addPointerInTextLayer(s,!1)}}}async addLinkAnnotations(e){let t={data:null,layer:this.div,linkService:this.#a,svgFactory:new fu,parent:this};for(let n of e){n.borderStyle||=T2._defaultBorderStyle,t.data=n;let s=rm.create(t);if(!s.isRenderable)continue;s.render(),s.contentElement.id=`pdfjs_internal_id_${n.id}`,this.#r.push(s)}await this.#l()}update({viewport:e,optionalContentConfig:t}){let n=this.div;this.viewport=e,sc(n,{rotation:e.rotation});for(let s of this.#r)s.updateOC(t);this.#c(),n.hidden=!1}destroy(){for(let e of this.#r)e.destroy?.(),this.#e?.removePointerInTextLayer(e.contentElement);this.#r.length=0,this.#s.clear(),this.div.replaceChildren()}#c(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let s=e.querySelector(`[data-annotation-id="${t}"]`);if(!s)continue;if(Array.isArray(n))for(let c of n)c.className="annotationContent",c.ariaHidden=!0;else n.className="annotationContent",n.ariaHidden=!0;let i=[];for(let c of s.children)if(c.nodeName==="CANVAS")i.push(c);for(let c of i)c.remove();let r=Array.isArray(n)?n[0]:n,{firstChild:o}=s;if(!o)s.append(r);else if(!o.classList.contains("annotationContent"))o.before(r);else o.after(r);if(Array.isArray(n)){let c=r;for(let h=1,d=n.length;h<d;h++)c.after(n[h]),c=n[h]}this.#t.delete(t);let l=this.#s.get(t);if(!l)continue;if(l._hasNoCanvas)this._annotationEditorUIManager?.setMissingCanvas(t,s.id,n),l._hasNoCanvas=!1;else l.canvas=n}}refreshCanvases(){this.#c()}getEditableAnnotations(){return this.#s.values()}getEditableAnnotation(e){return this.#s.get(e)}addFakeAnnotation(e){let{div:t}=this,{id:n,rotation:s}=e,i=new jS({data:{id:n,rect:e.getPDFRect(),rotation:s},editor:e,layer:t,parent:this,enableComment:!!this._commentManager,linkService:this.#a,annotationStorage:this.#n});return i.render(),i.contentElement.id=`pdfjs_internal_id_${n}`,i.createOrUpdatePopup(),this.#r.push(i),i}removeAnnotation(e){let t=this.#r.findIndex((s)=>s.data.id===e);if(t<0)return;let[n]=this.#r.splice(t,1);this.#e?.removePointerInTextLayer(n.contentElement)}updateFakeAnnotations(e){if(e.length===0)return;for(let t of e)t.updateFakeAnnotationElement(this);this.#l()}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}static get _defaultBorderStyle(){return Mt(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:mf.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}}var J0=/\r\n?|\n/g;class wi extends _t{#e="";#t=`${this.id}-editor`;#n=null;#s;_colorPicker=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let e=wi.prototype,t=(i)=>i.isEmpty(),{TRANSLATE_SMALL:n,TRANSLATE_BIG:s}=dl;return Mt(this,"_keyboardManager",new kr([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter"],e.commitOrRemove],[["Escape"],e.commitOrRemove],[["ArrowLeft"],e._translateEmpty,{args:[-n,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-s,0],checker:t}],[["ArrowRight"],e._translateEmpty,{args:[n,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[s,0],checker:t}],[["ArrowUp"],e._translateEmpty,{args:[0,-n],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-s],checker:t}],[["ArrowDown"],e._translateEmpty,{args:[0,n],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,s],checker:t}]]))}static _type="freetext";static _editorType=Jt.FREETEXT;constructor(e){super({...e,name:"freeTextEditor"});if(this.color=e.color||wi._defaultColor||_t._defaultLineColor,this.#s=e.fontSize||wi._defaultFontSize,!this.annotationElementId)this._uiManager.a11yAlert(_t._l10nAlert.freetext);this.canAddComment=!1}static initialize(e,t){_t.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,t){switch(e){case Tn.FREETEXT_SIZE:wi._defaultFontSize=t;break;case Tn.FREETEXT_COLOR:wi._defaultColor=t;break}}updateParams(e,t){switch(e){case Tn.FREETEXT_SIZE:this.#i(t);break;case Tn.FREETEXT_COLOR:this.#a(t);break}}static get defaultPropertiesToUpdate(){return[[Tn.FREETEXT_SIZE,wi._defaultFontSize],[Tn.FREETEXT_COLOR,wi._defaultColor||_t._defaultLineColor]]}get propertiesToUpdate(){return[[Tn.FREETEXT_SIZE,this.#s],[Tn.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||=new cu(this),[["colorPicker",this._colorPicker]]}get colorType(){return Tn.FREETEXT_COLOR}#i(e){let t=(s)=>{this.editorDiv.style.fontSize=`calc(${s}px * var(--total-scale-factor))`,this.translate(0,-(s-this.#s)*this.parentScale),this.#s=s,this.#o()},n=this.#s;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Tn.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}onUpdatedColor(){this.editorDiv.style.color=this.color,this._colorPicker?.update(this.color),super.onUpdatedColor()}#a(e){let t=(s)=>{this.color=s,this.onUpdatedColor()},n=this.color;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Tn.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let e=this.parentScale;return[-wi._internalPadding*e,-(wi._internalPadding+this.#s)*e]}rebuild(){if(!this.parent)return;if(super.rebuild(),this.div===null)return;if(!this.isAttachedToDOM)this.parent.add(this)}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#n=new AbortController;let e=this._uiManager.combinedSignal(this.#n);return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e}),!0}disableEditMode(){if(!super.disableEditMode())return!1;return this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#t),this._isDraggable=!0,this.#n?.abort(),this.#n=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0}focusin(e){if(!this._focusEventsAllowed)return;if(super.focusin(e),e.target!==this.editorDiv)this.editorDiv.focus()}onceAdded(e){if(this.width)return;if(this.enableEditMode(),e)this.editorDiv.focus();if(this._initialOptions?.isCentered)this.center();this._initialOptions=null}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){if(this.isEditing=!1,this.parent)this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing");super.remove()}#r(){let e=[];this.editorDiv.normalize();let t=null;for(let n of this.editorDiv.childNodes){if(t?.nodeType===Node.TEXT_NODE&&n.nodeName==="BR")continue;e.push(wi.#l(n)),t=n}return e.join(`
121
- `)}#o(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:s,div:i}=this,r=i.style.display,o=i.classList.contains("hidden");i.classList.remove("hidden"),i.style.display="hidden",s.div.append(this.div),n=i.getBoundingClientRect(),i.remove(),i.style.display=r,i.classList.toggle("hidden",o)}if(this.rotation%180===this.parentRotation%180)this.width=n.width/e,this.height=n.height/t;else this.width=n.height/e,this.height=n.width/t;this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#e,t=this.#e=this.#r().trimEnd();if(e===t)return;let n=(s)=>{if(this.#e=s,!s){this.remove();return}this.#c(),this._uiManager.rebuild(this),this.#o()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#o()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(e){if(e.target===this.div&&e.key==="Enter")this.enterInEditMode(),e.preventDefault()}editorDivKeydown(e){wi._keyboardManager.exec(this,e)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let e,t;if(this._isCopy||this.annotationElementId)e=this.x,t=this.y;super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#t),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#s}px * var(--total-scale-factor))`,n.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){let[s,i]=this.parentDimensions;if(this.annotationElementId){let{position:r}=this._initialData,[o,l]=this.getInitialTranslation();[o,l]=this.pageTranslationToScreen(o,l);let[c,h]=this.pageDimensions,[d,m]=this.pageTranslation,p,b;switch(this.rotation){case 0:p=e+(r[0]-d)/c,b=t+this.height-(r[1]-m)/h;break;case 90:p=e+(r[0]-d)/c,b=t-(r[1]-m)/h,[o,l]=[l,-o];break;case 180:p=e-this.width+(r[0]-d)/c,b=t-(r[1]-m)/h,[o,l]=[-o,-l];break;case 270:p=e+(r[0]-d-this.height*h)/c,b=t+(r[1]-m-this.width*c)/h,[o,l]=[-l,o];break}this.setAt(p*s,b*i,o,l)}else this._moveAfterPaste(e,t);this.#c(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(J0,"")}editorDivPaste(e){let t=e.clipboardData||window.clipboardData,{types:n}=t;if(n.length===1&&n[0]==="text/plain")return;e.preventDefault();let s=wi.#h(t.getData("text")||"").replaceAll(J0,`
122
- `);if(!s)return;let i=window.getSelection();if(!i.rangeCount)return;this.editorDiv.normalize(),i.deleteFromDocument();let r=i.getRangeAt(0);if(!s.includes(`
123
- `)){r.insertNode(document.createTextNode(s)),this.editorDiv.normalize(),i.collapseToStart();return}let{startContainer:o,startOffset:l}=r,c=[],h=[];if(o.nodeType===Node.TEXT_NODE){let p=o.parentElement;if(h.push(o.nodeValue.slice(l).replaceAll(J0,"")),p!==this.editorDiv){let b=c;for(let v of this.editorDiv.childNodes){if(v===p){b=h;continue}b.push(wi.#l(v))}}c.push(o.nodeValue.slice(0,l).replaceAll(J0,""))}else if(o===this.editorDiv){let p=c,b=0;for(let v of this.editorDiv.childNodes){if(b++===l)p=h;p.push(wi.#l(v))}}this.#e=`${c.join(`
124
- `)}${s}${h.join(`
125
- `)}`,this.#c();let d=new Range,m=Math.sumPrecise(c.map((p)=>p.length));for(let{firstChild:p}of this.editorDiv.childNodes)if(p.nodeType===Node.TEXT_NODE){let b=p.nodeValue.length;if(m<=b){d.setStart(p,m),d.setEnd(p,m);break}m-=b}i.removeAllRanges(),i.addRange(d)}#c(){if(this.editorDiv.replaceChildren(),!this.#e)return;for(let e of this.#e.split(`
126
- `)){let t=document.createElement("div");t.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(t)}}#u(){return this.#e.replaceAll(" "," ")}static#h(e){return e.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}getPDFRect(){let e=wi._internalPadding*this.parentScale;return this.getRect(e,e)}static async deserialize(e,t,n){let s=null;if(e instanceof v2){let{data:{defaultAppearanceData:{fontSize:r,fontColor:o},rect:l,rotation:c,id:h,popupRef:d,richText:m,contentsObj:p,creationDate:b,modificationDate:v},textContent:k,textPosition:A,parent:{page:{pageNumber:T}}}=e;if(!k?.length)return null;s=e={annotationType:Jt.FREETEXT,color:Array.from(o),fontSize:r,value:k.join(`
127
- `),position:A,pageIndex:T-1,rect:l.slice(0),rotation:c,annotationElementId:h,id:h,deleted:!1,popupRef:d,comment:p?.str||null,richText:m,creationDate:b,modificationDate:v}}let i=await super.deserialize(e,t,n);if(i.#s=e.fontSize,i.color=ct.makeHexColor(...e.color),i.#e=wi.#h(e.value),i._initialData=s,e.comment)i.setCommentData(e);return i}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let t=_t._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),n=Object.assign(super.serialize(e),{color:t,fontSize:this.#s,value:this.#u()});if(this.addComment(n),e)return n.isCopy=!0,n;if(this.annotationElementId&&!this.#d(n))return null;return n.id=this.annotationElementId,n}#d(e){let{value:t,fontSize:n,color:s,pageIndex:i}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||e.value!==t||e.fontSize!==n||e.color.some((r,o)=>r!==s[o])||e.pageIndex!==i}renderAnnotationElement(e){let t=super.renderAnnotationElement(e);if(!t)return null;let{style:n}=t;n.fontSize=`calc(${this.#s}px * var(--total-scale-factor))`,n.color=this.color,t.replaceChildren();for(let s of this.#e.split(`
128
- `)){let i=document.createElement("div");i.append(s?document.createTextNode(s):document.createElement("br")),t.append(i)}return e.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:this.#e}}),t}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}}class Rm{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(!e)return;for(let[t,n]of Object.entries(e))if(!t.startsWith("_"))this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){Dn("Not implemented")}}class kn extends _t{#e=null;#t;_clipPathId=null;_colorPicker=null;_drawId=null;_drawOutlines=null;_focusDrawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#s=null;static#i=null;static#a=null;static _INNER_MARGIN=3;constructor(e){super(e);this.#t=e.mustBeCommitted||!1,this._addOutlines(e)}onUpdatedColor(){this._colorPicker?.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){this._colorPicker?.updateOpacity?.(this.opacity)}_addOutlines(e){if(e.drawOutlines)this.#r(e),this.#g()}#r({drawOutlines:e,drawId:t,drawingOptions:n,clipPathId:s}){if(this._drawOutlines=e,this._drawingOptions||=n,!this.annotationElementId)this._uiManager.a11yAlert(_t._l10nAlert[this.editorType]);if(t>=0)this._drawId=t,this._clipPathId=s??null,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties),this.#l(this.parent);else this._drawId=this.#o(e,this.parent);this.#b(e.box)}#o(e,t){let{id:n,clipPathId:s}=t.drawLayer.draw(kn._mergeSVGProperties(this._drawingOptions.toSVGProperties(),e.defaultSVGProperties),!1,this.constructor._hasClipPath);if(this.constructor._hasClipPath)this._clipPathId=s;return this.#l(t),n}#l(e){let t=this._drawOutlines.getFocusSVGProperties(this.#d);if(t)this._focusDrawId=e.drawLayer.drawOutline(t,this._drawOutlines.focusMustRemoveSelfIntersections)}#c(e=this.#d){if(this._focusDrawId===null)return;this.parent?.drawLayer.updateProperties(this._focusDrawId,this._drawOutlines.getFocusSVGProperties(e))}#u(e){if(this._focusDrawId!==null)this.parent?.drawLayer.updateProperties(this._focusDrawId,{rootClass:e})}#h(){let{parent:e,_drawId:t,_focusDrawId:n,_isVisible:s}=this;if(!e||t===null)return;let i={hidden:!s};if(e.drawLayer.updateProperties(t,{rootClass:i}),n!==null)e.drawLayer.updateProperties(n,{rootClass:i})}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[s,i]of Object.entries(t))if(n.has(s))Object.assign(e[s],i);else e[s]=i;return e}static getDefaultDrawingOptions(e){Dn("Not implemented")}static get typesMap(){Dn("Not implemented")}static get isDrawer(){return!0}static get _hasClipPath(){return!1}static get _hasDrawClass(){return!0}static get supportMultipleDrawings(){return!1}get _drawRotation(){return this.rotation}get _opacityName(){return this.constructor.typesMap.get(this.opacityType)}get#d(){return(this.parentRotation-this._drawRotation+360)%360}static updateDefaultParams(e,t){let n=this.typesMap.get(e);if(n)this._defaultDrawingOptions.updateProperty(n,t);if(this._currentParent)kn.#n.updateProperty(n,t),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}updateParams(e,t){let n=this.constructor.typesMap.get(e);if(n)this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,s]of this.typesMap)e.push([n,t[s]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,s]of this.constructor.typesMap)e.push([n,t[s]]);return e}_updateProperty(e,t,n){let s=this._drawingOptions,i=s[t],r=(o)=>{s.updateProperty(t,o);let l=this._drawOutlines.updateProperty(t,o);if(l)this.#b(l);if(this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties()),e===this.colorType)this.onUpdatedColor();else if(e===this.opacityType)this.onUpdatedOpacity()};this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(e,t,n=this.colorAndOpacityType){let s=this.constructor.typesMap.get(this.colorType),i=this._opacityName,r=this._drawingOptions,o=r[s],l=r[i],c=(h,d)=>{r.updateProperty(s,h),r.updateProperty(i,d),this._drawOutlines.updateProperty(s,h),this._drawOutlines.updateProperty(i,d),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:c.bind(this,e,t),undo:c.bind(this,o,l),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:n,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,kn._mergeSVGProperties(this._drawOutlines.getPathResizingSVGProperties(this.#m()),{bbox:this.#w()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,kn._mergeSVGProperties(this._drawOutlines.getPathResizedSVGProperties(this.#m()),{bbox:this.#w()})),this.#c()}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#w()})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,kn._mergeSVGProperties(this._drawOutlines.getPathTranslatedSVGProperties(this.#m(),this.parentDimensions),{bbox:this.#w()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}get _mustBeDisabledOnCommit(){return!0}commit(){if(super.commit(),this._mustBeDisabledOnCommit)this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){if(!this.annotationElementId)this.parent.addUndoableEditor(this);if(this._isDraggable=!0,this.#t){if(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen)this.div.focus()}}remove(){this._uiManager.removeShouldRescale(this),this.#p(),super.remove()}rebuild(){if(!this.parent)return;if(super.rebuild(),this.div===null)return;if(this.#g(),this.#b(this._drawOutlines.box),!this.isAttachedToDOM)this.parent.add(this)}setParent(e){let t=!1;if(this.parent&&!e)this._uiManager.removeShouldRescale(this),this.#p();else if(e)this._uiManager.addShouldRescale(this),this.#g(e),t=!this.parent&&this.div?.classList.contains("selectedEditor");if(super.setParent(e),this.#h(),t)this.select()}#p(){if(this._drawId===null||!this.parent)return;let{drawLayer:e}=this.parent;if(e.remove(this._drawId),this._drawId=null,this._focusDrawId!==null)e.remove(this._focusDrawId),this._focusDrawId=null;this._drawingOptions.reset()}#g(e=this.parent){if(this._drawId!==null&&this.parent===e)return;if(this._drawId!==null){let{drawLayer:t}=this.parent;if(t.updateParent(this._drawId,e.drawLayer),this._focusDrawId!==null)t.updateParent(this._focusDrawId,e.drawLayer);return}if(this._drawingOptions.updateAll(),this._drawId=this.#o(this._drawOutlines,e),this._clipPathId&&this.#e)this.#e.style.clipPath=this._clipPathId}#f([e,t,n,s]){let{parentDimensions:[i,r],_drawRotation:o}=this;switch(o){case 90:return[t,1-e,n*(r/i),s*(i/r)];case 180:return[1-e,1-t,n,s];case 270:return[1-t,e,n*(r/i),s*(i/r)];default:return[e,t,n,s]}}#m(){let{x:e,y:t,width:n,height:s,parentDimensions:[i,r],_drawRotation:o}=this;switch(o){case 90:return[1-t,e,n*(i/r),s*(r/i)];case 180:return[1-e,1-t,n,s];case 270:return[t,1-e,n*(i/r),s*(r/i)];default:return[e,t,n,s]}}#b(e){if([this.x,this.y,this.width,this.height]=this.#f(e),this.div)this.fixAndSetPosition(),this.setDims();this._onResized()}#w(e=this.parentRotation){let{x:t,y:n,width:s,height:i,_drawRotation:r,parentDimensions:[o,l]}=this;switch((r*4+e)/90){case 1:return[1-n-i,t,i,s];case 2:return[1-t-s,1-n-i,s,i];case 3:return[n,1-t-s,i,s];case 4:return[t,n-s*(o/l),i*(l/o),s*(o/l)];case 5:return[1-n,t,s*(o/l),i*(l/o)];case 6:return[1-t-i*(l/o),1-n,i*(l/o),s*(o/l)];case 7:return[n-s*(o/l),1-t-i*(l/o),s*(o/l),i*(l/o)];case 8:return[t-s,n-i,s,i];case 9:return[1-n,t-s,i,s];case 10:return[1-t,1-n,s,i];case 11:return[n-i,1-t,i,s];case 12:return[t-i*(l/o),n,i*(l/o),s*(o/l)];case 13:return[1-n-s*(o/l),t-i*(l/o),s*(o/l),i*(l/o)];case 14:return[1-t,1-n-s*(o/l),i*(l/o),s*(o/l)];case 15:return[n,1-t,s*(o/l),i*(l/o)];default:return[t,n,s,i]}}rotate(e=this.parentRotation){if(!this.parent||this._drawId===null)return;let t=(e-this._drawRotation+360)%360;this.parent.drawLayer.updateProperties(this._drawId,kn._mergeSVGProperties({bbox:this.#w(e)},this._drawOutlines.updateRotation(t))),this.#c(t)}show(e=this._isVisible){super.show(e),this.#h()}select(){super.select(),this.#u({hovered:!1,selected:!0})}unselect(){super.unselect(),this.#u({selected:!1})}pointerover(){if(!this.isSelected)this.#u({hovered:!0})}pointerleave(){if(!this.isSelected)this.#u({hovered:!1})}onScaleChanging(){if(!this.parent)return;let e=this._drawOutlines.updateParentDimensions(this.parentDimensions,this.parent.scale);if(e)this.#b(e)}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e,t;if(this._isCopy)e=this.x,t=this.y;let n=super.render();if(this.constructor._hasDrawClass)n.classList.add("draw");let s=this.#e=document.createElement("div");if(n.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",this._clipPathId)s.style.clipPath=this._clipPathId;if(_7(this,s,["pointerover","pointerleave"]),this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy)this._moveAfterPaste(e,t);return n}static createDrawerInstance(e){Dn("Not implemented")}static _getDrawingTarget(e,{target:t}){return t}static _getPointerCoords({offsetX:e,offsetY:t,clientX:n,clientY:s},i=null){if(!i)return[e,t];let r=n-i.clientX,o=s-i.clientY;switch(this._currentParent.viewport.rotation){case 90:[r,o]=[o,-r];break;case 180:[r,o]=[-r,-o];break;case 270:[r,o]=[-o,r];break}return[i.offsetX+r,i.offsetY+o]}static _addDrawingListeners(e,t){}static _endDrawingSession(e=!1){return this._currentParent.endDrawingSession(e)}static startDrawing(e,t,n,s){let{pointerId:i,pointerType:r}=s;if(zn.isInitializedAndDifferentPointerType(r))return;let o=this._getDrawingTarget(e,s),[l,c]=this._getPointerCoords(s),{viewport:{rotation:h}}=e,{x:d,y:m,width:p,height:b}=o.getBoundingClientRect(),v=kn.#s=new AbortController,k=e.combinedSignal(v);if(zn.setPointer(r,i),window.addEventListener("pointerup",(E)=>{if(zn.isSamePointerIdOrRemove(E.pointerId))this._endDraw(E)},{signal:k}),window.addEventListener("pointercancel",(E)=>{if(zn.isSamePointerIdOrRemove(E.pointerId))this._endDrawingSession()},{signal:k}),window.addEventListener("pointerdown",(E)=>{if(!zn.isSamePointerType(E.pointerType))return;if(zn.initializeAndAddPointerId(E.pointerId),kn.#n.isCancellable())if(kn.#n.removeLastElement(),kn.#n.isEmpty())this._endDrawingSession(!0);else this._endDraw(null)},{capture:!0,passive:!1,signal:k}),window.addEventListener("contextmenu",ca,{signal:k}),o.addEventListener("pointermove",this._drawMove.bind(this),{signal:k}),o.addEventListener("touchmove",(E)=>{if(zn.isSameTimeStamp(E.timeStamp))si(E)},{signal:k}),this._addDrawingListeners(o,k),e.toggleDrawing(),t._editorUndoBar?.hide(),kn.#n){e.drawLayer.updateProperties(this._currentDrawId,kn.#n.startNew(l,c,p,b,h));return}t.updateUIForDefaultProperties(this),kn.#n=this.createDrawerInstance({x:l,y:c,box:[d,m,p,b],rotation:h,parent:e,isLTR:n}),kn.#i=this.getDefaultDrawingOptions(),this._currentParent=e;let{id:A,clipPathId:T}=e.drawLayer.draw(this._mergeSVGProperties(kn.#i.toSVGProperties(),kn.#n.defaultSVGProperties),!0,this._hasClipPath);this._currentDrawId=A,kn.#a=this._hasClipPath?T:null}static _drawMove(e){if(zn.isSameTimeStamp(e.timeStamp),!kn.#n)return;if(!zn.isSamePointerId(e.pointerId))return;if(zn.isUsingMultiplePointers()){this._endDraw(e);return}let t,n=e.getCoalescedEvents?.();if(n?.length){let s=[];for(let i of n)s.push(...this._getPointerCoords(i,e));t=kn.#n.addPoints(s)}else t=kn.#n.add(...this._getPointerCoords(e));this._currentParent.drawLayer.updateProperties(this._currentDrawId,t),zn.setTimeStamp(e.timeStamp),si(e)}static _cleanup(e){if(e)this._currentDrawId=-1,this._currentParent=null,kn.#n=null,kn.#i=null,kn.#a=null,zn.clearTimeStamp();if(kn.#s)kn.#s.abort(),kn.#s=null,zn.clearPointerIds()}static _endDraw(e){let t=this._currentParent;if(!t)return;if(t.toggleDrawing(!0),this._cleanup(!1),t.drawLayer.updateProperties(this._currentDrawId,e?.target===t.div?kn.#n.end(...this._getPointerCoords(e)):kn.#n.end()),this.supportMultipleDrawings){let n=kn.#n,s=this._currentDrawId,i=n.getLastElement();t.addCommands({cmd:()=>{t.drawLayer.updateProperties(s,n.setLastElement(i))},undo:()=>{t.drawLayer.updateProperties(s,n.removeLastElement())},mustExec:!1,type:Tn.DRAW_STEP});return}this.endDrawing(!1)}static endDrawing(e){let t=this._currentParent;if(!t)return null;if(t.toggleDrawing(!0),t.cleanUndoStack(Tn.DRAW_STEP),!kn.#n.isEmpty()){let{pageDimensions:[n,s],scale:i}=t,r=t.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,clipPathId:kn.#a,drawOutlines:kn.#n.getOutlines(n*i,s*i,i,this._INNER_MARGIN),drawingOptions:kn.#i,mustBeCommitted:!e});return this._cleanup(!0),r}return t.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,s,i,r,o){Dn("Not implemented")}static async deserialize(e,t,n){let{rawDims:{pageWidth:s,pageHeight:i,pageX:r,pageY:o}}=t.viewport,l=this.deserializeDraw(r,o,s,i,this._INNER_MARGIN,e,n),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#r({drawOutlines:l}),c.#g(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[s,i]=this.pageDimensions;return this._drawOutlines.serialize([t,n,s,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}}class vt{static PRECISION=0.0001;focusOutline=null;toSVGPath(){Dn("Abstract method `toSVGPath` must be implemented.")}get box(){Dn("Abstract getter `box` must be implemented.")}serialize(e,t){Dn("Abstract method `serialize` must be implemented.")}get defaultSVGProperties(){Dn("Abstract getter `defaultSVGProperties` must be implemented.")}get defaultProperties(){return this.defaultSVGProperties}getFocusSVGProperties(e){return null}get focusMustRemoveSelfIntersections(){return!1}updateProperty(e,t){return null}updateParentDimensions(e,t){return null}serializeQuadPoints(e,t){return null}updateRotation(e){return{}}getPathResizingSVGProperties(e){return{}}getPathResizedSVGProperties(e){return{}}getPathTranslatedSVGProperties(e,t){return{}}static _rotateBox([e,t,n,s],i){switch(i){case 90:return[1-t-s,e,s,n];case 180:return[1-e-n,1-t-s,n,s];case 270:return[t,1-e-n,s,n]}return[e,t,n,s]}static _rescale(e,t,n,s,i,r){r||=new Float32Array(e.length);for(let o=0,l=e.length;o<l;o+=2)r[o]=t+e[o]*s,r[o+1]=n+e[o+1]*i;return r}static _rescaleAndSwap(e,t,n,s,i,r){r||=new Float32Array(e.length);for(let o=0,l=e.length;o<l;o+=2)r[o]=t+e[o+1]*s,r[o+1]=n+e[o]*i;return r}static _translate(e,t,n,s){s||=new Float32Array(e.length);for(let i=0,r=e.length;i<r;i+=2)s[i]=t+e[i],s[i+1]=n+e[i+1];return s}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,n,s,i){switch(i){case 90:return[1-t/n,e/s];case 180:return[1-e/n,1-t/s];case 270:return[t/n,1-e/s];default:return[e/n,t/s]}}static createBezierPoints(e,t,n,s,i,r){return[(e+5*n)/6,(t+5*s)/6,(5*n+i)/6,(5*s+r)/6,(n+i)/2,(s+r)/2]}}class Ql{#e;#t=[];#n;#s;#i=[];#a=new Float32Array(18);#r;#o;#l;#c;#u;#h;#d=[];static#p=8;static#g=2;static#f=Ql.#p+Ql.#g;constructor(e,t,n,s,i,r,o=0){this.#e=n,this.#h=i*s,this.#s=r,this.#a.set([NaN,NaN,NaN,NaN,e,t],6),this.#n=o,this.#c=Ql.#p*s,this.#l=Ql.#f*s,this.#u=s,this.#d.push(e,t)}isEmpty(){return isNaN(this.#a[8])}isCancellable(){return this.#d.length<=10}removeLastElement(){return this.#a.fill(NaN),this.#i.length=this.#t.length=this.#d.length=0,{path:{d:""}}}#m(){let e=this.#a.subarray(4,6),t=this.#a.subarray(16,18),[n,s,i,r]=this.#e;return[(this.#r+(e[0]-t[0])/2-n)/i,(this.#o+(e[1]-t[1])/2-s)/r,(this.#r+(t[0]-e[0])/2-n)/i,(this.#o+(t[1]-e[1])/2-s)/r]}add(e,t){this.#r=e,this.#o=t;let[n,s,i,r]=this.#e,[o,l,c,h]=this.#a.subarray(8,12),d=e-c,m=t-h,p=Math.hypot(d,m);if(p<this.#l)return!1;let b=p-this.#c,v=b/p,k=v*d,A=v*m,T=o,E=l;o=c,l=h,c+=k,h+=A,this.#d?.push(e,t);let I=-A/b,_=k/b,q=I*this.#h,P=_*this.#h;if(this.#a.set(this.#a.subarray(2,8),0),this.#a.set([c+q,h+P],4),this.#a.set(this.#a.subarray(14,18),12),this.#a.set([c-q,h-P],16),isNaN(this.#a[6])){if(this.#i.length===0)this.#a.set([o+q,l+P],2),this.#i.push(NaN,NaN,NaN,NaN,(o+q-n)/i,(l+P-s)/r),this.#a.set([o-q,l-P],14),this.#t.push(NaN,NaN,NaN,NaN,(o-q-n)/i,(l-P-s)/r);return this.#a.set([T,E,o,l,c,h],6),!this.isEmpty()}if(this.#a.set([T,E,o,l,c,h],6),Math.abs(Math.atan2(E-l,T-o)-Math.atan2(A,k))<Math.PI/2)return[o,l,c,h]=this.#a.subarray(2,6),this.#i.push(NaN,NaN,NaN,NaN,((o+c)/2-n)/i,((l+h)/2-s)/r),[o,l,T,E]=this.#a.subarray(14,18),this.#t.push(NaN,NaN,NaN,NaN,((T+o)/2-n)/i,((E+l)/2-s)/r),!0;return[T,E,o,l,c,h]=this.#a.subarray(0,6),this.#i.push(((T+5*o)/6-n)/i,((E+5*l)/6-s)/r,((5*o+c)/6-n)/i,((5*l+h)/6-s)/r,((o+c)/2-n)/i,((l+h)/2-s)/r),[c,h,o,l,T,E]=this.#a.subarray(12,18),this.#t.push(((T+5*o)/6-n)/i,((E+5*l)/6-s)/r,((5*o+c)/6-n)/i,((5*l+h)/6-s)/r,((o+c)/2-n)/i,((l+h)/2-s)/r),!0}toSVGPath(){if(this.isEmpty())return"";let e=this.#i,t=this.#t;if(isNaN(this.#a[6])&&!this.isEmpty())return this.#b();let n=[];n.push(`M${e[4]} ${e[5]}`);for(let s=6;s<e.length;s+=6)if(isNaN(e[s]))n.push(`L${e[s+4]} ${e[s+5]}`);else n.push(`C${e[s]} ${e[s+1]} ${e[s+2]} ${e[s+3]} ${e[s+4]} ${e[s+5]}`);this.#y(n);for(let s=t.length-6;s>=6;s-=6)if(isNaN(t[s]))n.push(`L${t[s+4]} ${t[s+5]}`);else n.push(`C${t[s]} ${t[s+1]} ${t[s+2]} ${t[s+3]} ${t[s+4]} ${t[s+5]}`);return this.#w(n),n.join(" ")}#b(){let[e,t,n,s]=this.#e,[i,r,o,l]=this.#m();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/s} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/s} L${i} ${r} L${o} ${l} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/s} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/s} Z`}#w(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,s,i]=this.#e,r=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[l,c,h,d]=this.#m();e.push(`L${(r[0]-t)/s} ${(r[1]-n)/i} L${l} ${c} L${h} ${d} L${(o[0]-t)/s} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,s,i,r){return new E2(e,t,n,s,i,r)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[s,i,r,o]=this.#e,l=new Float32Array((this.#d?.length??0)+2);for(let d=0,m=l.length-2;d<m;d+=2)l[d]=(this.#d[d]-s)/r,l[d+1]=(this.#d[d+1]-i)/o;if(l[l.length-2]=(this.#r-s)/r,l[l.length-1]=(this.#o-i)/o,isNaN(n[6])&&!this.isEmpty())return this.#v(l);let c=new Float32Array(this.#i.length+24+this.#t.length),h=e.length;for(let d=0;d<h;d+=2){if(isNaN(e[d])){c[d]=c[d+1]=NaN;continue}c[d]=e[d],c[d+1]=e[d+1]}h=this.#k(c,h);for(let d=t.length-6;d>=6;d-=6)for(let m=0;m<6;m+=2){if(isNaN(t[d+m])){c[h]=c[h+1]=NaN,h+=2;continue}c[h]=t[d+m],c[h+1]=t[d+m+1],h+=2}return this.#x(c,h),this.newFreeDrawOutline(c,l,this.#e,this.#u,this.#n,this.#s)}#v(e){let t=this.#a,[n,s,i,r]=this.#e,[o,l,c,h]=this.#m(),d=new Float32Array(36);return d.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-s)/r,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-s)/r,NaN,NaN,NaN,NaN,o,l,NaN,NaN,NaN,NaN,c,h,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-s)/r,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-s)/r],0),this.newFreeDrawOutline(d,e,this.#e,this.#u,this.#n,this.#s)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#k(e,t){let n=this.#a.subarray(4,6),s=this.#a.subarray(16,18),[i,r,o,l]=this.#e,[c,h,d,m]=this.#m();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-r)/l,NaN,NaN,NaN,NaN,c,h,NaN,NaN,NaN,NaN,d,m,NaN,NaN,NaN,NaN,(s[0]-i)/o,(s[1]-r)/l],t),t+=24}}class E2 extends vt{#e;#t=new Float32Array(4);#n;#s;#i;#a;#r;constructor(e,t,n,s,i,r){super();this.#r=e,this.#i=t,this.#e=n,this.#a=s,this.#n=i,this.#s=r,this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],this.#o(r);let[o,l,c,h]=this.#t;for(let d=0,m=e.length;d<m;d+=2)e[d]=(e[d]-o)/c,e[d+1]=(e[d+1]-l)/h;for(let d=0,m=t.length;d<m;d+=2)t[d]=(t[d]-o)/c,t[d+1]=(t[d+1]-l)/h}toSVGPath(){let e=[`M${this.#r[4]} ${this.#r[5]}`];for(let t=6,n=this.#r.length;t<n;t+=6){if(isNaN(this.#r[t])){e.push(`L${this.#r[t+4]} ${this.#r[t+5]}`);continue}e.push(`C${this.#r[t]} ${this.#r[t+1]} ${this.#r[t+2]} ${this.#r[t+3]} ${this.#r[t+4]} ${this.#r[t+5]}`)}return e.push("Z"),e.join(" ")}serialize([e,t,n,s],i){let r=n-e,o=s-t,l,c;switch(i){case 0:l=vt._rescale(this.#r,e,s,r,-o),c=vt._rescale(this.#i,e,s,r,-o);break;case 90:l=vt._rescaleAndSwap(this.#r,e,t,r,o),c=vt._rescaleAndSwap(this.#i,e,t,r,o);break;case 180:l=vt._rescale(this.#r,n,t,-r,o),c=vt._rescale(this.#i,n,t,-r,o);break;case 270:l=vt._rescaleAndSwap(this.#r,n,s,-r,-o),c=vt._rescaleAndSwap(this.#i,n,s,-r,-o);break}return{outline:Array.from(l),points:[Array.from(c)]}}#o(e){let t=this.#r,n=t[4],s=t[5],i=[n,s,n,s],r=n,o=s,l=n,c=s,h=e?Math.max:Math.min,d=new Float32Array(4);for(let p=6,b=t.length;p<b;p+=6){let v=t[p+4],k=t[p+5];if(isNaN(t[p])){if(ct.pointBoundingBox(v,k,i),o>k)r=v,o=k;else if(o===k)r=h(r,v);if(c<k)l=v,c=k;else if(c===k)l=h(l,v)}else{if(d.set(ko,0),ct.bezierBoundingBox(n,s,...t.slice(p,p+6),d),ct.rectBoundingBox(...d,i),o>d[1])r=d[0],o=d[1];else if(o===d[1])r=h(r,d[0]);if(c<d[3])l=d[2],c=d[3];else if(c===d[3])l=h(l,d[2])}n=v,s=k}let m=this.#t;m[0]=i[0]-this.#n,m[1]=i[1]-this.#n,m[2]=i[2]-i[0]+2*this.#n,m[3]=i[3]-i[1]+2*this.#n,this.firstPoint=[r,o],this.lastPoint=[l,c]}get box(){return this.#t}newOutliner(e,t,n,s,i,r,o=0){return new Ql(e,t,n,s,i,r,o)}updateThickness(e){let t=this.getNewOutline(e);return this.#r=t.#r,this.#i=t.#i,this.#t.set(t.#t),this.firstPoint=t.firstPoint,this.lastPoint=t.lastPoint,this.#t}getNewOutline(e,t){let[n,s,i,r]=this.#t,[o,l,c,h]=this.#e,d=i*c,m=r*h,p=n*c+o,b=s*h+l,v=this.#i,k=this.newOutliner(v[0]*d+p,v[1]*m+b,this.#e,this.#a,e,this.#s,t??this.#n);for(let A=2,T=v.length;A<T;A+=2)k.add(v[A]*d+p,v[A+1]*m+b);return k.getOutlines()}}function XS(e){return{bbox:e.box,root:{viewBox:"0 0 1 1"},rootClass:{highlight:!0,free:e.isFree},path:{d:e.toSVGPath()}}}function WS(e,t){let{focusOutline:n}=e;return{bbox:vt._rotateBox(n.box,t),root:{"data-main-rotation":t},rootClass:{highlightOutline:!0,free:e.isFree},path:{d:n.toSVGPath()}}}class um{#e;#t;#n;#s=[];#i=[];constructor(e,t=0,n=0,s=!0){let i=ko.slice(),r=4,o=0.0001;for(let{x:k,y:A,width:T,height:E}of e){let I=Math.floor((k-t)/0.0001)*0.0001,_=Math.ceil((k+T+t)/0.0001)*0.0001,q=Math.floor((A-t)/0.0001)*0.0001,P=Math.ceil((A+E+t)/0.0001)*0.0001,N=[I,q,P,!0],H=[_,q,P,!1];this.#s.push(N,H),ct.rectBoundingBox(I,q,_,P,i)}let l=i[2]-i[0]+2*n,c=i[3]-i[1]+2*n,h=i[0]-n,d=i[1]-n,m=s?-1/0:1/0,p=1/0,b=this.#s.at(s?-1:-2),v=[b[0],b[2]];for(let k of this.#s){let[A,T,E,I]=k;if(!I&&s){if(T<p)p=T,m=A;else if(T===p)m=Math.max(m,A)}else if(I&&!s){if(T<p)p=T,m=A;else if(T===p)m=Math.min(m,A)}k[0]=(A-h)/l,k[1]=(T-d)/c,k[2]=(E-d)/c}this.#e=new Float32Array([h,d,l,c]),this.#t=[m,p],this.#n=v}getOutlines(){this.#s.sort((t,n)=>t[0]-n[0]||t[1]-n[1]||t[2]-n[2]);let e=[];for(let t of this.#s)if(t[3])e.push(...this.#c(t)),this.#o(t);else this.#l(t),e.push(...this.#c(t));return this.#a(e)}#a(e){let t=[],n=new Set;for(let r of e){let[o,l,c]=r;t.push([o,l,r],[o,c,r])}t.sort((r,o)=>r[1]-o[1]||r[0]-o[0]);for(let r=0,o=t.length;r<o;r+=2){let l=t[r][2],c=t[r+1][2];l.push(c),c.push(l),n.add(l),n.add(c)}let s=[],i;while(n.size>0){let r=n.values().next().value,[o,l,c,h,d]=r;n.delete(r);let m=o,p=l;i=[o,c],s.push(i);while(!0){let b;if(n.has(h))b=h;else if(n.has(d))b=d;else break;if(n.delete(b),[o,l,c,h,d]=b,m!==o)i.push(m,p,o,p===l?l:c),m=o;p=p===l?c:l}i.push(m,p)}return new dm(s,this.#e,this.#t,this.#n)}#r(e){let t=this.#i,n=0,s=t.length-1;while(n<=s){let i=n+s>>1,r=t[i][0];if(r===e)return i;if(r<e)n=i+1;else s=i-1}return s+1}#o([,e,t]){let n=this.#r(e);this.#i.splice(n,0,[e,t])}#l([,e,t]){let n=this.#r(e);for(let s=n;s<this.#i.length;s++){let[i,r]=this.#i[s];if(i!==e)break;if(i===e&&r===t){this.#i.splice(s,1);return}}for(let s=n-1;s>=0;s--){let[i,r]=this.#i[s];if(i!==e)break;if(i===e&&r===t){this.#i.splice(s,1);return}}}#c(e){let[t,n,s]=e,i=[[t,n,s]],r=this.#r(s);for(let o=0;o<r;o++){let[l,c]=this.#i[o];for(let h=0,d=i.length;h<d;h++){let[,m,p]=i[h];if(c<=m||p<=l)continue;if(m>=l){if(p>c)i[h][1]=c;else{if(d===1)return[];i.splice(h,1),h--,d--}continue}if(i[h][2]=l,p>c)i.push([t,c,p])}}return i}}class dm extends vt{#e;#t=null;#n;constructor(e,t,n,s){super();this.#n=e,this.#e=t,this.firstPoint=n,this.lastPoint=s}static build(e,t){let n=new um(e,0.001).getOutlines();return n.#t=e,n.focusOutline=new um(e,0.0025,0.001,t).getOutlines(),n}get isFree(){return!1}get defaultSVGProperties(){return XS(this)}getFocusSVGProperties(e){return WS(this,e)}updateRotation(e){return{root:{"data-main-rotation":e}}}serializeQuadPoints([e,t],[n,s]){let i=this.#t,r=new Float32Array(i.length*8),o=0;for(let{x:l,y:c,width:h,height:d}of i){let m=l*n+e,p=(1-c)*s+t;r[o]=r[o+4]=m,r[o+1]=r[o+3]=p,r[o+2]=r[o+6]=m+h*n,r[o+5]=r[o+7]=p-d*s,o+=8}return r}toSVGPath(){let e=[];for(let t of this.#n){let[n,s]=t;e.push(`M${n} ${s}`);for(let i=2;i<t.length;i+=2){let r=t[i],o=t[i+1];if(r===n)e.push(`V${o}`),s=o;else if(o===s)e.push(`H${r}`),n=r}e.push("Z")}return e.join(" ")}serialize([e,t,n,s],i){let r=[],o=n-e,l=s-t;for(let c of this.#n){let h=Array(c.length);for(let d=0;d<c.length;d+=2)h[d]=e+c[d]*o,h[d+1]=s-c[d+1]*l;r.push(h)}return r}get box(){return this.#e}}class Dm extends Ql{newFreeDrawOutline(e,t,n,s,i,r){return new C2(e,t,n,s,i,r)}}class KS{#e;#t;constructor(e,t,n,s,i,r,o){this.#e=new Dm(e,t,n,s,i,r,o),this.#t=i}add(e,t){return this.#e.add(e,t)?{path:{d:this.#e.toSVGPath()}}:null}addPoints(e){let t=!1;for(let n=0,s=e.length;n<s;n+=2)t=this.#e.add(e[n],e[n+1])||t;return t?{path:{d:this.#e.toSVGPath()}}:null}end(e,t){return e===void 0?null:this.add(e,t)}isEmpty(){return this.#e.isEmpty()}isCancellable(){return this.#e.isCancellable()}removeLastElement(){return this.#e.removeLastElement()}updateProperty(e,t){return null}getOutlines(){let e=this.#e.getOutlines();return e.buildFocusOutline(2*this.#t),e}get defaultSVGProperties(){return{bbox:[0,0,1,1],root:{viewBox:"0 0 1 1"},rootClass:{highlight:!0,free:!0},path:{d:this.#e.toSVGPath()}}}}class C2 extends E2{static#e=1.5;newOutliner(e,t,n,s,i,r,o=0){return new Dm(e,t,n,s,i,r,o)}get isFree(){return!0}buildFocusOutline(e){this.focusOutline=this.getNewOutline(e/2+C2.#e,0.0025)}get defaultSVGProperties(){return XS(this)}getFocusSVGProperties(e){return WS(this,e)}get focusMustRemoveSelfIntersections(){return!0}updateRotation(e){return{root:{"data-main-rotation":e}}}updateProperty(e,t){if(e!=="thickness")return null;let n=this.updateThickness(t/2);return this.buildFocusOutline(t),n}getPathResizedSVGProperties(){return{path:{d:this.toSVGPath()}}}}class j2 extends Rm{constructor(e=null){super();super.updateProperties(e)}updateSVGProperty(e,t){if(e!=="thickness")super.updateSVGProperty(e,t)}clone(){let e=new j2;return e.updateAll(this),e}}class la extends kn{#e=null;#t=0;#n=null;#s=0;#i="";#a="";static _DEFAULT_OPACITY=1;static _DEFAULT_THICKNESS=12;static _defaultDrawingOptions=null;static _type="highlight";static _editorType=Jt.HIGHLIGHT;static get _keyboardManager(){let e=la.prototype;return Mt(this,"_keyboardManager",new kr([[["ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown"],e._moveCaret,{args:[3]}]]))}constructor(e){super({...e,name:"highlightEditor"});this.#e=e.anchorNode||null,this.#t=e.anchorOffset||0,this.#n=e.focusNode||null,this.#s=e.focusOffset||0,this.#i=e.methodOfCreation||(this._drawOutlines?.isFree?"main_toolbar":""),this.#a=e.text||"",this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",this.rotate()}static initialize(e,t){_t.initialize(e,t),this._defaultDrawingOptions||=new j2({fill:t.highlightColors?.values().next().value||"#fff066","fill-opacity":la._DEFAULT_OPACITY,thickness:la._DEFAULT_THICKNESS})}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get typesMap(){return Mt(this,"typesMap",new Map([[Tn.HIGHLIGHT_COLOR,"fill"],[Tn.HIGHLIGHT_THICKNESS,"thickness"]]))}static get isDrawer(){return!1}static get _hasClipPath(){return!0}static get _hasDrawClass(){return!1}_addOutlines(e){let{boxes:t,drawOutlines:n}=e;if(!t&&!n)return;if(this._drawingOptions||=e.drawingOptions||la.getDefaultDrawingOptions(),t)e={...e,drawOutlines:dm.build(t,this._uiManager.direction==="ltr")};super._addOutlines(e)}get colorType(){return Tn.HIGHLIGHT_COLOR}get color(){return this._drawingOptions.fill}get opacity(){return this._drawingOptions["fill-opacity"]}get _opacityName(){return"fill-opacity"}get _drawRotation(){return this._drawOutlines?.isFree?this.rotation:0}get isResizable(){return!1}get _mustBeDisabledOnCommit(){return!1}get _mustFixPosition(){return!this._drawOutlines?.isFree}get telemetryInitialData(){return{action:"added",type:this._drawOutlines.isFree?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:this._drawingOptions.thickness,methodOfCreation:this.#i}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get("color").size}}translateInPage(e,t){}get toolbarPosition(){return this.#r(this._drawOutlines.focusOutline.lastPoint)}get commentButtonPosition(){return this.#r(this._drawOutlines.firstPoint)}#r([e,t]){let[n,s,i,r]=this._drawOutlines.box;return[(e-n)/i,(t-s)/r]}updateParams(e,t){switch(e){case Tn.HIGHLIGHT_COLOR:this._updateColorAndOpacity(t,la._DEFAULT_OPACITY,e),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0);break;case Tn.HIGHLIGHT_THICKNESS:super.updateParams(e,t),this._reportTelemetry({action:"thickness_changed",thickness:t},!0);break}}get propertiesToUpdate(){let e=super.propertiesToUpdate;return e.push([Tn.HIGHLIGHT_FREE,this._drawOutlines.isFree]),e}get toolbarButtons(){if(this._uiManager.highlightColors)return this._colorPicker=new zr({editor:this}),[["colorPicker",this._colorPicker]];return super.toolbarButtons}fixAndSetPosition(){return super.fixAndSetPosition(this._drawRotation)}getRect(e,t){return super.getRect(e,t,this._drawRotation)}onceAdded(e){if(!this.annotationElementId)this.parent.addUndoableEditor(this);if(e)this.div.focus()}remove(){this._reportTelemetry({action:"deleted"}),super.remove()}render(){if(this.div)return this.div;let e=super.render();if(this.#a)e.setAttribute("aria-label",this.#a),e.setAttribute("role","mark");if(this._drawOutlines.isFree)e.classList.add("free");else e.addEventListener("keydown",this.#o.bind(this),{signal:this._uiManager._signal});return this.enableEditing(),e}#o(e){la._keyboardManager.exec(this,e)}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:this.#l(!0);break;case 1:case 3:this.#l(!1);break}}#l(e){if(!this.#e)return;let t=window.getSelection();if(e)t.setPosition(this.#e,this.#t);else t.setPosition(this.#n,this.#s)}unselect(){if(super.unselect(),!this._drawOutlines.isFree)this.#l(!1)}static createDrawerInstance({x:e,y:t,box:n,parent:s,isLTR:i}){return new KS(e,t,n,s.scale,this._defaultDrawingOptions.thickness/2,i,0.001)}static _getDrawingTarget(e,{target:t}){return t.closest(".textLayer")}static _getPointerCoords({x:e,y:t}){return[e,t]}static _addDrawingListeners(e,t){e.classList.add("free"),t.addEventListener("abort",()=>e.classList.remove("free"),{once:!0}),window.addEventListener("blur",()=>this._endDraw(null),{signal:t}),window.addEventListener("pointerdown",si,{capture:!0,passive:!1,signal:t})}static _endDrawingSession(e=!1){return this.endDrawing(e)}createDrawingOptions({color:e,opacity:t,thickness:n}){let{_defaultDrawingOptions:s,_DEFAULT_OPACITY:i}=la;this._drawingOptions=la.getDefaultDrawingOptions({fill:ct.makeHexColor(...e),"fill-opacity":t||i,thickness:n||s.thickness})}static deserializeDraw(e,t,n,s,i,r,o){let{quadPoints:l}=r;if(l){let p=[];for(let b=0,v=l.length;b<v;b+=8)p.push({x:(l[b]-e)/n,y:1-(l[b+1]-t)/s,width:(l[b+2]-l[b])/n,height:(l[b+1]-l[b+5])/s});return dm.build(p,o.direction==="ltr")}let c=r.thickness||this._defaultDrawingOptions.thickness,h=(r.inkLists||r.outlines.points)[0],d=new Dm(h[0]-e,s-(h[1]-t),[0,0,n,s],1,c/2,!0,0.001);for(let p=0,b=h.length;p<b;p+=2)d.add(h[p]-e,s-(h[p+1]-t));let m=d.getOutlines();return m.buildFocusOutline(c),m}static async deserialize(e,t,n){let s=null;if(e instanceof k2){let{data:{quadPoints:r,rect:o,rotation:l,id:c,color:h,opacity:d,popupRef:m,richText:p,contentsObj:b,creationDate:v,modificationDate:k},parent:{page:{pageNumber:A}}}=e;s=e={annotationType:Jt.HIGHLIGHT,color:Array.from(h),opacity:d,quadPoints:r,pageIndex:A-1,rect:o.slice(0),rotation:l,annotationElementId:c,id:c,deleted:!1,popupRef:m,richText:p,comment:b?.str||null,creationDate:v,modificationDate:k}}else if(e instanceof Im){let{data:{inkLists:r,rect:o,rotation:l,id:c,color:h,borderStyle:{rawWidth:d},popupRef:m,richText:p,contentsObj:b,creationDate:v,modificationDate:k},parent:{page:{pageNumber:A}}}=e;s=e={annotationType:Jt.HIGHLIGHT,color:Array.from(h),thickness:d,inkLists:r,pageIndex:A-1,rect:o.slice(0),rotation:l,annotationElementId:c,id:c,deleted:!1,popupRef:m,richText:p,comment:b?.str||null,creationDate:v,modificationDate:k}}let i=await super.deserialize(e,t,n);if(i._initialData=s,e.comment)i.setCommentData(e);return i}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();let t=super.serialize(e);if(Object.assign(t,{color:_t._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),opacity:this.opacity,thickness:this._drawingOptions.thickness,quadPoints:this._drawOutlines.serializeQuadPoints(this.pageTranslation,this.pageDimensions),outlines:this._drawOutlines.serialize(t.rect,this._drawRotation)}),this.addComment(t),this.annotationElementId&&!this.#c(t))return null;return t.id=this.annotationElementId,t}#c(e){let{color:t}=this._initialData;return this.hasEditedComment||e.color.some((n,s)=>n!==t[s])}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;return e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null}}class YS{#e=new Float64Array(6);#t=new Float64Array(2);#n;#s;#i;#a;#r;#o="";#l=0;#c=new yf;#u;#h;constructor(e,t,n,s,i,r){this.#u=n,this.#h=s,this.#i=i,this.#a=r,[e,t]=this.#d(e,t);let o=this.#n=[NaN,NaN,NaN,NaN,e,t];this.#r=[e,t],this.#s=[{line:o,points:this.#r}],this.#e.set(o,0),this.#t.set([e,t],0)}updateProperty(e,t){if(e==="stroke-width")this.#a=t}#d(e,t){return vt._normalizePoint(e,t,this.#u,this.#h,this.#i)}isEmpty(){return!this.#s?.length}isCancellable(){return this.#r.length<=10}add(e,t){if(this.#p(e,t))this.toSVGPath();return{path:{d:this.#g()}}}addPoints(e){let t=!1;for(let n=0,s=e.length;n<s;n+=2){if(!this.#p(e[n],e[n+1]))continue;if(t=!0,this.#r.length<=6)this.toSVGPath(),t=!1}if(t)this.toSVGPath();return{path:{d:this.#g()}}}#p(e,t){[e,t]=this.#d(e,t),this.#t.set([e,t],0);let[n,s,i,r]=this.#e.subarray(2,6),o=e-i,l=t-r;if(Math.hypot(this.#u*o,this.#h*l)<=2)return!1;if(this.#r.push(e,t),isNaN(n))return this.#e.set([i,r,e,t],2),this.#n.push(NaN,NaN,NaN,NaN,e,t),!0;if(isNaN(this.#e[0]))this.#n.splice(6,6);return this.#e.set([n,s,i,r,e,t],0),this.#n.push(...vt.createBezierPoints(n,s,i,r,e,t)),!0}end(e,t){if(e!==void 0&&this.#p(e,t))return{path:{d:this.toSVGPath()}};if(this.#r.length===2)return{path:{d:this.toSVGPath()}};return{path:{d:this.#o}}}startNew(e,t,n,s,i){this.#u=n,this.#h=s,this.#i=i,[e,t]=this.#d(e,t);let r=this.#n=[NaN,NaN,NaN,NaN,e,t];this.#r=[e,t],this.#t.set([e,t],0);let o=this.#s.at(-1);if(o)o.line=new Float32Array(o.line),o.points=new Float32Array(o.points);return this.#s.push({line:r,points:this.#r}),this.#e.set(r,0),this.#l=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(e){if(!this.#s)return this.#c.setLastElement(e);return this.#s.push(e),this.#n=e.line,this.#r=e.points,this.#l=0,{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#o="";for(let e=0,t=this.#s.length;e<t;e++){let{line:n,points:s}=this.#s[e];this.#n=n,this.#r=s,this.#l=0,this.toSVGPath()}return{path:{d:this.#o}}}#g(){let e=vt.svgRound(this.#t[0]),t=vt.svgRound(this.#t[1]);if(this.#r.length===2){let n=vt.svgRound(this.#n[4]),s=vt.svgRound(this.#n[5]);return`${this.#o} M ${n} ${s} L ${e} ${t}`}return`${this.#o} L ${e} ${t}`}toSVGPath(){let e=vt.svgRound(this.#n[4]),t=vt.svgRound(this.#n[5]);if(this.#r.length===2)return this.#o=`${this.#o} M ${e} ${t} Z`,this.#o;if(this.#r.length<=6){let s=this.#o.lastIndexOf("M");this.#o=`${this.#o.slice(0,s)} M ${e} ${t}`,this.#l=6}if(this.#r.length===4){let s=vt.svgRound(this.#n[10]),i=vt.svgRound(this.#n[11]);return this.#o=`${this.#o} L ${s} ${i}`,this.#l=12,this.#o}let n=[];if(this.#l===0)n.push(`M ${e} ${t}`),this.#l=6;for(let s=this.#l,i=this.#n.length;s<i;s+=6){let[r,o,l,c,h,d]=this.#n.slice(s,s+6).map(vt.svgRound);n.push(`C${r} ${o} ${l} ${c} ${h} ${d}`)}return this.#o+=n.join(" "),this.#l=this.#n.length,this.#o}getOutlines(e,t,n,s){let i=this.#s.at(-1);return i.line=new Float32Array(i.line),i.points=new Float32Array(i.points),this.#c.build(this.#s,e,t,n,this.#i,this.#a,s),this.#e=null,this.#n=null,this.#s=null,this.#o=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class yf extends vt{#e;#t=0;#n;#s;#i;#a;#r;#o;#l;build(e,t,n,s,i,r,o){this.#i=t,this.#a=n,this.#r=s,this.#o=i,this.#l=r,this.#n=o??0,this.#s=e,this.#h()}get thickness(){return this.#l}setLastElement(e){return this.#s.push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#s.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){let e=[];for(let{line:t}of this.#s){if(e.push(`M${vt.svgRound(t[4])} ${vt.svgRound(t[5])}`),t.length===6){e.push("Z");continue}if(t.length===12&&isNaN(t[6])){e.push(`L${vt.svgRound(t[10])} ${vt.svgRound(t[11])}`);continue}for(let n=6,s=t.length;n<s;n+=6){let[i,r,o,l,c,h]=t.subarray(n,n+6).map(vt.svgRound);e.push(`C${i} ${r} ${o} ${l} ${c} ${h}`)}}return e.join("")}serialize([e,t,n,s],i){let r=[],o=[],[l,c,h,d]=this.#u(),m,p,b,v,k,A,T,E,I;switch(this.#o){case 0:I=vt._rescale,m=e,p=t+s,b=n,v=-s,k=e+l*n,A=t+(1-c-d)*s,T=e+(l+h)*n,E=t+(1-c)*s;break;case 90:I=vt._rescaleAndSwap,m=e,p=t,b=n,v=s,k=e+c*n,A=t+l*s,T=e+(c+d)*n,E=t+(l+h)*s;break;case 180:I=vt._rescale,m=e+n,p=t,b=-n,v=s,k=e+(1-l-h)*n,A=t+c*s,T=e+(1-l)*n,E=t+(c+d)*s;break;case 270:I=vt._rescaleAndSwap,m=e+n,p=t+s,b=-n,v=-s,k=e+(1-c-d)*n,A=t+(1-l-h)*s,T=e+(1-c)*n,E=t+(1-l)*s;break}for(let{line:_,points:q}of this.#s)r.push(I(_,m,p,b,v,i?Array(_.length):null)),o.push(I(q,m,p,b,v,i?Array(q.length):null));return{lines:r,points:o,rect:[k,A,T,E]}}static deserialize(e,t,n,s,i,{paths:{lines:r,points:o},rotation:l,thickness:c}){let h=[],d,m,p,b,v;switch(l){case 0:v=vt._rescale,d=-e/n,m=t/s+1,p=1/n,b=-1/s;break;case 90:v=vt._rescaleAndSwap,d=-t/s,m=-e/n,p=1/s,b=1/n;break;case 180:v=vt._rescale,d=e/n+1,m=-t/s,p=-1/n,b=1/s;break;case 270:v=vt._rescaleAndSwap,d=t/s+1,m=e/n+1,p=-1/s,b=-1/n;break}if(!r){r=[];for(let A of o){let T=A.length;if(T===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,A[0],A[1]]));continue}if(T===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,A[0],A[1],NaN,NaN,NaN,NaN,A[2],A[3]]));continue}let E=new Float32Array(3*(T-2));r.push(E);let[I,_,q,P]=A.subarray(0,4);E.set([NaN,NaN,NaN,NaN,I,_],0);for(let N=4;N<T;N+=2){let H=A[N],V=A[N+1];E.set(vt.createBezierPoints(I,_,q,P,H,V),(N-2)*3),[I,_,q,P]=[q,P,H,V]}}}for(let A=0,T=r.length;A<T;A++)h.push({line:v(r[A].map((E)=>E??NaN),d,m,p,b),points:v(o[A].map((E)=>E??NaN),d,m,p,b)});let k=new this.prototype.constructor;return k.build(h,n,s,1,l,c,i),k}#c(e=this.#l){let t=this.#n+e/2*this.#r;return this.#o%180===0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,s]=this.#e,[i,r]=this.#c(0);return[e+i,t+r,n-2*i,s-2*r]}#h(){let e=this.#e=Yl.slice();for(let{line:s}of this.#s){if(s.length<=12){for(let o=4,l=s.length;o<l;o+=6)ct.pointBoundingBox(s[o],s[o+1],e);continue}let i=s[4],r=s[5];for(let o=6,l=s.length;o<l;o+=6){let[c,h,d,m,p,b]=s.subarray(o,o+6);ct.bezierBoundingBox(i,r,c,h,d,m,p,b,e),i=p,r=b}}let[t,n]=this.#c();e[0]=bs(e[0]-t,0,1),e[1]=bs(e[1]-n,0,1),e[2]=bs(e[2]+t,0,1),e[3]=bs(e[3]+n,0,1),e[2]-=e[0],e[3]-=e[1]}get box(){return this.#e}updateProperty(e,t){return e==="stroke-width"?this.#d(t):null}#d(e){let[t,n]=this.#c();this.#l=e;let[s,i]=this.#c(),[r,o]=[s-t,i-n],l=this.#e;return l[0]-=r,l[1]-=o,l[2]+=2*r,l[3]+=2*o,l}updateParentDimensions([e,t],n){let[s,i]=this.#c();this.#i=e,this.#a=t,this.#r=n;let[r,o]=this.#c(),l=r-s,c=o-i,h=this.#e;return h[0]-=l,h[1]-=c,h[2]+=2*l,h[3]+=2*c,h}updateRotation(e){return this.#t=e,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#e.map(vt.svgRound).join(" ")}get defaultProperties(){let[e,t]=this.#e;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${vt.svgRound(e)} ${vt.svgRound(t)}`}}}get rotationTransform(){let[,,e,t]=this.#e,n=0,s=0,i=0,r=0,o=0,l=0;switch(this.#t){case 90:s=t/e,i=-e/t,o=e;break;case 180:n=-1,r=-1,o=e,l=t;break;case 270:s=-t/e,i=e/t,l=t;break;default:return""}return`matrix(${n} ${s} ${i} ${r} ${vt.svgRound(o)} ${vt.svgRound(l)})`}getPathResizingSVGProperties([e,t,n,s]){let[i,r]=this.#c(),[o,l,c,h]=this.#e;if(Math.abs(c-i)<=vt.PRECISION||Math.abs(h-r)<=vt.PRECISION){let v=e+n/2-(o+c/2),k=t+s/2-(l+h/2);return{path:{"transform-origin":`${vt.svgRound(e)} ${vt.svgRound(t)}`,transform:`${this.rotationTransform} translate(${v} ${k})`}}}let d=(n-2*i)/(c-2*i),m=(s-2*r)/(h-2*r),p=c/n,b=h/s;return{path:{"transform-origin":`${vt.svgRound(o)} ${vt.svgRound(l)}`,transform:`${this.rotationTransform} scale(${p} ${b}) translate(${vt.svgRound(i)} ${vt.svgRound(r)}) scale(${d} ${m}) translate(${vt.svgRound(-i)} ${vt.svgRound(-r)})`}}}getPathResizedSVGProperties([e,t,n,s]){let[i,r]=this.#c(),o=this.#e,[l,c,h,d]=o;if(o[0]=e,o[1]=t,o[2]=n,o[3]=s,Math.abs(h-i)<=vt.PRECISION||Math.abs(d-r)<=vt.PRECISION){let k=e+n/2-(l+h/2),A=t+s/2-(c+d/2);for(let{line:T,points:E}of this.#s)vt._translate(T,k,A,T),vt._translate(E,k,A,E);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${vt.svgRound(e)} ${vt.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}let m=(n-2*i)/(h-2*i),p=(s-2*r)/(d-2*r),b=-m*(l+i)+e+i,v=-p*(c+r)+t+r;if(m!==1||p!==1||b!==0||v!==0)for(let{line:k,points:A}of this.#s)vt._rescale(k,b,v,m,p,k),vt._rescale(A,b,v,m,p,A);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${vt.svgRound(e)} ${vt.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,t],n){let[s,i]=n,r=this.#e,o=e-r[0],l=t-r[1];if(this.#i===s&&this.#a===i)for(let{line:c,points:h}of this.#s)vt._translate(c,o,l,c),vt._translate(h,o,l,h);else{let c=this.#i/s,h=this.#a/i;this.#i=s,this.#a=i;for(let{line:d,points:m}of this.#s)vt._rescale(d,o,l,c,h,d),vt._rescale(m,o,l,c,h,m);r[2]*=c,r[3]*=h}return r[0]=e,r[1]=t,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${vt.svgRound(e)} ${vt.svgRound(t)}`}}}get defaultSVGProperties(){let e=this.#e;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${vt.svgRound(e[0])} ${vt.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}}class qm extends Rm{constructor(e){super();this._viewParameters=e,super.updateProperties({fill:"none",stroke:_t._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(e,t){if(e==="stroke-width")t??=this["stroke-width"],t*=this._viewParameters.realScale;super.updateSVGProperty(e,t)}clone(){let e=new qm(this._viewParameters);return e.updateAll(this),e}}class _2 extends kn{static _type="ink";static _editorType=Jt.INK;static _defaultDrawingOptions=null;constructor(e){super({...e,name:"inkEditor"});this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(e,t){_t.initialize(e,t),this._defaultDrawingOptions=new qm(t.viewParameters)}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get supportMultipleDrawings(){return!0}static get typesMap(){return Mt(this,"typesMap",new Map([[Tn.INK_THICKNESS,"stroke-width"],[Tn.INK_COLOR,"stroke"],[Tn.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance({x:e,y:t,box:[,,n,s],rotation:i}){return new YS(e,t,n,s,i,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(e,t,n,s,i,r){return yf.deserialize(e,t,n,s,i,r)}static async deserialize(e,t,n){let s=null;if(e instanceof Im){let{data:{inkLists:r,rect:o,rotation:l,id:c,color:h,opacity:d,borderStyle:{rawWidth:m},popupRef:p,richText:b,contentsObj:v,creationDate:k,modificationDate:A},parent:{page:{pageNumber:T}}}=e;s=e={annotationType:Jt.INK,color:Array.from(h),thickness:m,opacity:d,paths:{points:r},boxes:null,pageIndex:T-1,rect:o.slice(0),rotation:l,annotationElementId:c,id:c,deleted:!1,popupRef:p,richText:b,comment:v?.str||null,creationDate:k,modificationDate:A}}let i=await super.deserialize(e,t,n);if(i._initialData=s,e.comment)i.setCommentData(e);return i}get toolbarButtons(){return this._colorPicker||=new cu(this),[["colorPicker",this._colorPicker]]}get colorType(){return Tn.INK_COLOR}get colorAndOpacityType(){return Tn.INK_COLOR_AND_OPACITY}get opacityType(){return Tn.INK_OPACITY}updateParams(e,t){if(e===Tn.INK_COLOR_AND_OPACITY){this._updateColorAndOpacity(t.color,t.opacity);return}super.updateParams(e,t)}static updateDefaultParams(e,t){if(e===Tn.INK_COLOR_AND_OPACITY){super.updateDefaultParams(Tn.INK_COLOR,t.color),super.updateDefaultParams(Tn.INK_OPACITY,t.opacity);return}super.updateDefaultParams(e,t)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();let{_drawId:e,_drawingOptions:t,parent:n}=this;t.updateSVGProperty("stroke-width"),n.drawLayer.updateProperties(e,t.toSVGProperties())}static onScaleChangingWhenDrawing(){let e=this._currentParent;if(!e)return;super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}createDrawingOptions({color:e,thickness:t,opacity:n}){this._drawingOptions=_2.getDefaultDrawingOptions({stroke:ct.makeHexColor(...e),"stroke-width":t,"stroke-opacity":n})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let{lines:t,points:n}=this.serializeDraw(e),{_drawingOptions:{stroke:s,"stroke-opacity":i,"stroke-width":r}}=this,o=Object.assign(super.serialize(e),{color:_t._colorManager.convert(s),opacity:i,thickness:r,paths:{lines:t,points:n}});if(this.addComment(o),e)return o.isCopy=!0,o;if(this.annotationElementId&&!this.#e(o))return null;return o.id=this.annotationElementId,o}#e(e){let{color:t,thickness:n,opacity:s,pageIndex:i}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||e.color.some((r,o)=>r!==t[o])||e.thickness!==n||e.opacity!==s||e.pageIndex!==i}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions["stroke-width"],points:t,popup:this.comment}),null}}class mm extends yf{toSVGPath(){let e=super.toSVGPath();if(!e.endsWith("Z"))e+="Z";return e}}var Z0=8,Jh=3;class Kl{static#e={maxDim:512,sigmaSFactor:0.02,sigmaR:25,kernelSize:16};static#t(e,t,n,s){if(n-=e,s-=t,n===0)return s>0?0:4;if(n===1)return s+6;return 2-s}static#n=new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]);static#s(e,t,n,s,i,r,o){let l=this.#t(n,s,i,r);for(let c=0;c<8;c++){let h=(-c+l-o+16)%8,d=this.#n[2*h],m=this.#n[2*h+1];if(e[(n+d)*t+(s+m)]!==0)return h}return-1}static#i(e,t,n,s,i,r,o){let l=this.#t(n,s,i,r);for(let c=0;c<8;c++){let h=(c+l+o+16)%8,d=this.#n[2*h],m=this.#n[2*h+1];if(e[(n+d)*t+(s+m)]!==0)return h}return-1}static#a(e,t,n,s){let i=e.length,r=new Int32Array(i);for(let h=0;h<i;h++)r[h]=e[h]<=s?1:0;for(let h=1;h<n-1;h++)r[h*t]=r[h*t+t-1]=0;for(let h=0;h<t;h++)r[h]=r[t*n-1-h]=0;let o=1,l,c=[];for(let h=1;h<n-1;h++){l=1;for(let d=1;d<t-1;d++){let m=h*t+d,p=r[m];if(p===0)continue;let b=h,v=d;if(p===1&&r[m-1]===0)o+=1,v-=1;else if(p>=1&&r[m+1]===0){if(o+=1,v+=1,p>1)l=p}else{if(p!==1)l=Math.abs(p);continue}let k=[d,h],A=v===d+1,T={isHole:A,points:k,id:o,parent:0};c.push(T);let E;for(let U of c)if(U.id===l){E=U;break}if(!E)T.parent=A?l:0;else if(E.isHole)T.parent=A?E.parent:l;else T.parent=A?l:E.parent;let I=this.#s(r,t,h,d,b,v,0);if(I===-1){if(r[m]=-o,r[m]!==1)l=Math.abs(r[m]);continue}let _=this.#n[2*I],q=this.#n[2*I+1],P=h+_,N=d+q;b=P,v=N;let H=h,V=d;while(!0){let U=this.#i(r,t,H,V,b,v,1);_=this.#n[2*U],q=this.#n[2*U+1];let W=H+_,ce=V+q;k.push(ce,W);let ue=H*t+V;if(r[ue+1]===0)r[ue]=-o;else if(r[ue]===1)r[ue]=o;if(W===h&&ce===d&&H===P&&V===N){if(r[m]!==1)l=Math.abs(r[m]);break}else b=H,v=V,H=W,V=ce}}}return c}static#r(e,t,n,s){if(n-t<=4){for(let P=t;P<n-2;P+=2)s.push(e[P],e[P+1]);return}let i=e[t],r=e[t+1],o=e[n-4]-i,l=e[n-3]-r,c=Math.hypot(o,l),h=o/c,d=l/c,m=h*r-d*i,p=l/o,b=1/c,v=Math.atan(p),k=Math.cos(v),A=Math.sin(v),T=b*(Math.abs(k)+Math.abs(A)),E=b*(1-T+T**2),I=Math.max(Math.atan(Math.abs(A+k)*E),Math.atan(Math.abs(A-k)*E)),_=0,q=t;for(let P=t+2;P<n-2;P+=2){let N=Math.abs(m-h*e[P+1]+d*e[P]);if(N>_)q=P,_=N}if(_>(c*I)**2)this.#r(e,t,q+2,s),this.#r(e,q,n,s);else s.push(i,r)}static#o(e){let t=[],n=e.length;return this.#r(e,0,n,t),t.push(e[n-2],e[n-1]),t.length<=4?null:t}static#l(e,t,n,s,i,r){let o=new Float32Array(r**2),l=-2*s**2,c=r>>1;for(let v=0;v<r;v++){let k=(v-c)**2;for(let A=0;A<r;A++)o[v*r+A]=Math.exp((k+(A-c)**2)/l)}let h=new Float32Array(256),d=-2*i**2;for(let v=0;v<256;v++)h[v]=Math.exp(v**2/d);let m=e.length,p=new Uint8Array(m),b=new Uint32Array(256);for(let v=0;v<n;v++)for(let k=0;k<t;k++){let A=v*t+k,T=e[A],E=0,I=0;for(let q=0;q<r;q++){let P=v+q-c;if(P<0||P>=n)continue;for(let N=0;N<r;N++){let H=k+N-c;if(H<0||H>=t)continue;let V=e[P*t+H],U=o[q*r+N]*h[Math.abs(V-T)];E+=V*U,I+=U}}let _=p[A]=Math.round(E/I);b[_]++}return[p,b]}static#c(e){let t=new Uint32Array(256);for(let n of e)t[n]++;return t}static#u(e){let t=e.length,n=new Uint8ClampedArray(t>>2),s=-1/0,i=1/0;for(let o=0,l=n.length;o<l;o++){let c=n[o]=e[o<<2];s=Math.max(s,c),i=Math.min(i,c)}let r=255/(s-i);for(let o=0,l=n.length;o<l;o++)n[o]=(n[o]-i)*r;return n}static#h(e){let t,n=-1/0,s=-1/0,i=e.findIndex((l)=>l!==0),r=i,o=i;for(t=i;t<256;t++){let l=e[t];if(l>n){if(t-r>s)s=t-r,o=t-1;n=l,r=t}}for(t=o-1;t>=0;t--)if(e[t]>e[t+1])break;return t}static#d(e){let t=e,{width:n,height:s}=e,{maxDim:i}=this.#e,r=n,o=s;if(n>i||s>i){let m=n,p=s,b=Math.log2(Math.max(n,s)/i),v=Math.floor(b);b=b===v?v-1:v;for(let A=0;A<b;A++){r=Math.ceil(m/2),o=Math.ceil(p/2);let T=new OffscreenCanvas(r,o);if(T.getContext("2d").drawImage(e,0,0,m,p,0,0,r,o),m=r,p=o,e!==t)e.close();e=T.transferToImageBitmap()}let k=Math.min(i/r,i/o);r=Math.round(r*k),o=Math.round(o*k)}let c=new OffscreenCanvas(r,o).getContext("2d",{willReadFrequently:!0});c.fillStyle="white",c.fillRect(0,0,r,o),c.filter="grayscale(1)",c.drawImage(e,0,0,e.width,e.height,0,0,r,o);let h=c.getImageData(0,0,r,o).data;return[this.#u(h),r,o]}static extractContoursFromText(e,{fontFamily:t,fontStyle:n,fontWeight:s},i,r,o,l){let c=new OffscreenCanvas(1,1),h=c.getContext("2d",{alpha:!1}),d=200,m=h.font=`${n} ${s} ${d}px ${t}`,{actualBoundingBoxLeft:p,actualBoundingBoxRight:b,actualBoundingBoxAscent:v,actualBoundingBoxDescent:k,fontBoundingBoxAscent:A,fontBoundingBoxDescent:T,width:E}=h.measureText(e),I=1.5,_=Math.ceil(Math.max(Math.abs(p)+Math.abs(b)||0,E)*I),q=Math.ceil(Math.max(Math.abs(v)+Math.abs(k)||d,Math.abs(A)+Math.abs(T)||d)*I);c=new OffscreenCanvas(_,q),h=c.getContext("2d",{alpha:!0,willReadFrequently:!0}),h.font=m,h.filter="grayscale(1)",h.fillStyle="white",h.fillRect(0,0,_,q),h.fillStyle="black",h.fillText(e,_*(I-1)/2,q*(3-I)/2);let P=this.#u(h.getImageData(0,0,_,q).data),N=this.#c(P),H=this.#h(N),V=this.#a(P,_,q,H);return this.processDrawnLines({lines:{curves:V,width:_,height:q},pageWidth:i,pageHeight:r,rotation:o,innerMargin:l,mustSmooth:!0,areContours:!0})}static process(e,t,n,s,i){let[r,o,l]=this.#d(e),[c,h]=this.#l(r,o,l,Math.hypot(o,l)*this.#e.sigmaSFactor,this.#e.sigmaR,this.#e.kernelSize),d=this.#h(h),m=this.#a(c,o,l,d);return this.processDrawnLines({lines:{curves:m,width:o,height:l},pageWidth:t,pageHeight:n,rotation:s,innerMargin:i,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:e,pageWidth:t,pageHeight:n,rotation:s,innerMargin:i,mustSmooth:r,areContours:o}){if(s%180!==0)[t,n]=[n,t];let{curves:l,width:c,height:h}=e,d=e.thickness??0,m=[],p=Math.min(t/c,n/h),b=p/t,v=p/n,k=[];for(let{points:T}of l){let E=r?this.#o(T):T;if(!E)continue;k.push(E);let I=E.length,_=new Float32Array(I),q=new Float32Array(3*(I===2?2:I-2));if(m.push({line:q,points:_}),I===2){_[0]=E[0]*b,_[1]=E[1]*v,q.set([NaN,NaN,NaN,NaN,_[0],_[1]],0);continue}let[P,N,H,V]=E;P*=b,N*=v,H*=b,V*=v,_.set([P,N,H,V],0),q.set([NaN,NaN,NaN,NaN,P,N],0);for(let U=4;U<I;U+=2){let W=_[U]=E[U]*b,ce=_[U+1]=E[U+1]*v;q.set(vt.createBezierPoints(P,N,H,V,W,ce),(U-2)*3),[P,N,H,V]=[H,V,W,ce]}}if(m.length===0)return null;let A=o?new mm:new yf;return A.build(m,t,n,1,s,o?0:d,i),{outline:A,newCurves:k,areContours:o,thickness:d,width:c,height:h}}static async compressSignature({outlines:e,areContours:t,thickness:n,width:s,height:i}){let r=1/0,o=-1/0,l=0;for(let T of e){l+=T.length;for(let E=2,I=T.length;E<I;E++){let _=T[E]-T[E-2];r=Math.min(r,_),o=Math.max(o,_)}}let c;if(r>=-128&&o<=127)c=Int8Array;else if(r>=-32768&&o<=32767)c=Int16Array;else c=Int32Array;let h=e.length,d=Z0+Jh*h,m=new Uint32Array(d),p=0;m[p++]=d*Uint32Array.BYTES_PER_ELEMENT+(l-2*h)*c.BYTES_PER_ELEMENT,m[p++]=0,m[p++]=s,m[p++]=i,m[p++]=t?0:1,m[p++]=Math.max(0,Math.floor(n??0)),m[p++]=h,m[p++]=c.BYTES_PER_ELEMENT;for(let T of e)m[p++]=T.length-2,m[p++]=T[0],m[p++]=T[1];let b=new CompressionStream("deflate-raw"),v=b.writable.getWriter();await v.ready,v.write(m);let k=c.prototype.constructor;for(let T of e){let E=new k(T.length-2);for(let I=2,_=T.length;I<_;I++)E[I-2]=T[I]-T[I-2];v.write(E)}return v.close(),(await new Response(b.readable).bytes()).toBase64()}static async decompressSignature(e){try{let t=Uint8Array.fromBase64(e),{readable:n,writable:s}=new DecompressionStream("deflate-raw"),i=s.getWriter();await i.ready,i.write(t).then(async()=>{await i.ready,await i.close()}).catch(()=>{});let r=null,o=0;for await(let E of n)r||=new Uint8Array(new Uint32Array(E.buffer,0,4)[0]),r.set(E,o),o+=E.length;let l=new Uint32Array(r.buffer,0,r.length>>2),c=l[1];if(c!==0)throw Error(`Invalid version: ${c}`);let h=l[2],d=l[3],m=l[4]===0,p=l[5],b=l[6],v=l[7],k=[],A=(Z0+Jh*b)*Uint32Array.BYTES_PER_ELEMENT,T;switch(v){case Int8Array.BYTES_PER_ELEMENT:T=new Int8Array(r.buffer,A);break;case Int16Array.BYTES_PER_ELEMENT:T=new Int16Array(r.buffer,A);break;case Int32Array.BYTES_PER_ELEMENT:T=new Int32Array(r.buffer,A);break}o=0;for(let E=0;E<b;E++){let I=l[Jh*E+Z0],_=new Float32Array(I+2);k.push(_);for(let q=0;q<Jh-1;q++)_[q]=l[Jh*E+Z0+q+1];for(let q=0;q<I;q++)_[q+2]=_[q]+T[o++]}return{areContours:m,thickness:p,outlines:k,width:h,height:d}}catch(t){return on(`decompressSignature: ${t}`),null}}}class I2 extends Rm{constructor(){super();super.updateProperties({fill:_t._defaultLineColor,"stroke-width":0})}clone(){let e=new I2;return e.updateAll(this),e}}class R2 extends qm{constructor(e){super(e);super.updateProperties({stroke:_t._defaultLineColor,"stroke-width":1})}clone(){let e=new R2(this._viewParameters);return e.updateAll(this),e}}class Ua extends kn{#e=!1;#t=null;#n=null;#s=null;static _type="signature";static _editorType=Jt.SIGNATURE;static _defaultDrawingOptions=null;constructor(e){super({...e,mustBeCommitted:!0,name:"signatureEditor"});this._willKeepAspectRatio=!0,this.#n=e.signatureData||null,this.#t=null,this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(e,t){_t.initialize(e,t),this._defaultDrawingOptions=new I2,this._defaultDrawnSignatureOptions=new R2(t.viewParameters)}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get supportMultipleDrawings(){return!1}static get typesMap(){return Mt(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!this.#t}}static computeTelemetryFinalData(e){let t=e.get("hasDescription");return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){if(this._drawId===null)return;super.onScaleChanging()}render(){if(this.div)return this.div;let e,t,{_isCopy:n}=this;if(n)this._isCopy=!1,e=this.x,t=this.y;if(super.render(),this._drawId===null)if(this.#n){let{lines:s,mustSmooth:i,areContours:r,description:o,uuid:l,heightInPage:c}=this.#n,{rawDims:{pageWidth:h,pageHeight:d},rotation:m}=this.parent.viewport,p=Kl.processDrawnLines({lines:s,pageWidth:h,pageHeight:d,rotation:m,innerMargin:Ua._INNER_MARGIN,mustSmooth:i,areContours:r});this.addSignature(p,c,o,l)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:this.#t||""}));if(n)this._isCopy=!0,this._moveAfterPaste(e,t);return this.div}setUuid(e){this.#s=e,this.addEditToolbar()}getUuid(){return this.#s}get description(){return this.#t}set description(e){if(this.#t=e,!this.div)return;this.div.setAttribute("data-l10n-args",JSON.stringify({description:e})),super.addEditToolbar().then((t)=>{t?.updateEditSignatureButton(e)})}getSignaturePreview(){let{newCurves:e,areContours:t,thickness:n,width:s,height:i}=this.#n,r=Math.max(s,i),o=Kl.processDrawnLines({lines:{curves:e.map((l)=>({points:l})),thickness:n,width:s,height:i},pageWidth:r,pageHeight:r,rotation:0,innerMargin:0,mustSmooth:!1,areContours:t});return{areContours:t,outline:o.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(e,t,n,s){let{x:i,y:r}=this,{outline:o}=this.#n=e;this.#e=o instanceof mm,this.description=n;let l;if(this.#e)l=Ua.getDefaultDrawingOptions();else l=Ua._defaultDrawnSignatureOptions.clone(),l.updateProperties({"stroke-width":o.thickness});this._addOutlines({drawOutlines:o,drawingOptions:l});let[,c]=this.pageDimensions,h=t/c;if(h=h>=1?0.5:h,this.width*=h/this.height,this.width>=1)h*=0.9/this.width,this.width=0.9;this.height=h,this.setDims(),this.x=i,this.y=r,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(s),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!s,hasDescription:!!n}}),this.div.hidden=!1}getFromImage(e){let{rawDims:{pageWidth:t,pageHeight:n},rotation:s}=this.parent.viewport;return Kl.process(e,t,n,s,Ua._INNER_MARGIN)}getFromText(e,t){let{rawDims:{pageWidth:n,pageHeight:s},rotation:i}=this.parent.viewport;return Kl.extractContoursFromText(e,t,n,s,i,Ua._INNER_MARGIN)}getDrawnSignature(e){let{rawDims:{pageWidth:t,pageHeight:n},rotation:s}=this.parent.viewport;return Kl.processDrawnLines({lines:e,pageWidth:t,pageHeight:n,rotation:s,innerMargin:Ua._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:e,thickness:t}){if(e)this._drawingOptions=Ua.getDefaultDrawingOptions();else this._drawingOptions=Ua._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":t})}serialize(e=!1){if(this.isEmpty())return null;let{lines:t,points:n}=this.serializeDraw(e),{_drawingOptions:{"stroke-width":s}}=this,i=Object.assign(super.serialize(e),{isSignature:!0,areContours:this.#e,color:[0,0,0],thickness:this.#e?0:s});if(this.addComment(i),e)i.paths={lines:t,points:n},i.uuid=this.#s,i.isCopy=!0;else i.lines=t;if(this.#t)i.accessibilityData={type:"Figure",alt:this.#t};return i}static deserializeDraw(e,t,n,s,i,r){if(r.areContours)return mm.deserialize(e,t,n,s,i,r);return yf.deserialize(e,t,n,s,i,r)}static async deserialize(e,t,n){let s=await super.deserialize(e,t,n);return s.#e=e.areContours,s.description=e.accessibilityData?.alt||"",s.#s=e.uuid,s}}class QS extends _t{#e=null;#t=null;#n=null;#s=null;#i=null;#a="";#r=null;#o=!1;#l=null;#c=!1;#u=!1;static _type="stamp";static _editorType=Jt.STAMP;constructor(e){super({...e,name:"stampEditor"});this.#s=e.bitmapUrl,this.#i=e.bitmapFile,this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(e,t){_t.initialize(e,t)}static isHandlingMimeForPasting(e){return Kb.includes(e)}static paste(e,t){t.pasteEditor({mode:Jt.STAMP},{bitmapFile:e.getAsFile()})}altTextFinish(){if(this._uiManager.useNewAltTextFlow)this.div.hidden=!1;super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get("hasAltText");return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#h(e,t=!1){if(!e){this.remove();return}if(this.#e=e.bitmap,!t)this.#t=e.id,this.#c=e.isSvg;if(e.file)this.#a=e.file.name;this.#g()}#d(){if(this.#n=null,this._uiManager.enableWaiting(!1),!this.#r)return;if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}async mlGuessAltText(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error("No ML.");if(!await n.isEnabledFor("altText"))throw Error("ML isn't enabled for alt text.");let{data:s,width:i,height:r}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:"altText",request:{data:s,width:i,height:r,channels:s.length/(i*r)}});if(!o)throw Error("No response from the AI service.");if(o.error)throw Error("Error from the AI service.");if(o.cancel)return null;if(!o.output)throw Error("No valid response from the AI service.");let l=o.output;if(await this.setGuessedAltText(l),t&&!this.hasAltTextData())this.altTextData={alt:l,decorative:!1};return l}#p(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then((n)=>this.#h(n,!0)).finally(()=>this.#d());return}if(this.#s){let n=this.#s;this.#s=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(n).then((s)=>this.#h(s)).finally(()=>this.#d());return}if(this.#i){let n=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(n).then((s)=>this.#h(s)).finally(()=>this.#d());return}let e=document.createElement("input");e.type="file",e.accept=Kb.join(",");let t=this._uiManager._signal;this.#n=new Promise((n)=>{e.addEventListener("change",async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let s=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#h(s)}n()},{signal:t}),e.addEventListener("cancel",()=>{this.remove(),n()},{signal:t})}).finally(()=>this.#d()),e.click()}remove(){if(this.#t){if(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#r?.remove(),this.#r=null,this.#l)clearTimeout(this.#l),this.#l=null}super.remove()}rebuild(){if(!this.parent){if(this.#t)this.#p();return}if(super.rebuild(),this.div===null)return;if(this.#t&&this.#r===null)this.#p();if(!this.isAttachedToDOM)this.parent.add(this)}onceAdded(e){if(this._isDraggable=!0,e)this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#s||this.#i||this.#t||this.#o)}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;if(this._isCopy)e=this.x,t=this.y;if(super.render(),this.div.hidden=!0,this.createAltText(),!this.#o)if(this.#e)this.#g();else this.#p();if(this._isCopy)this._moveAfterPaste(e,t);return this._uiManager.addShouldRescale(this),this.div}setCanvas(e,t){let{id:n,bitmap:s}=this._uiManager.imageManager.getFromCanvas(e,t);if(t.remove(),n&&this._uiManager.imageManager.isValidId(n)){if(this.#t=n,s)this.#e=s;this.#o=!1,this.#g()}}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;if(this.#l!==null)clearTimeout(this.#l);let e=200;this.#l=setTimeout(()=>{this.#l=null,this.#m()},e)}#g(){let{div:e}=this,{width:t,height:n}=this.#e,[s,i]=this.pageDimensions,r=0.75;if(this.width)t=this.width*s,n=this.height*i;else if(t>0.75*s||n>0.75*i){let l=Math.min(0.75*s/t,0.75*i/n);t*=l,n*=l}this._uiManager.enableWaiting(!1);let o=this.#r=document.createElement("canvas");if(o.setAttribute("role","img"),this.addContainer(o),this.width=t/s,this.height=n/i,this.setDims(),this._initialOptions?.isCentered)this.center();else this.fixAndSetPosition();if(this._initialOptions=null,!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)e.hidden=!1;if(this.#m(),!this.#u)this.parent.addUndoableEditor(this),this.#u=!0;if(this._reportTelemetry({action:"inserted_image"}),this.#a)this.div.setAttribute("aria-description",this.#a);if(!this.annotationElementId)this._uiManager.a11yAlert(_t._l10nAlert.stamp)}copyCanvas(e,t,n=!1){e||=224;let{width:s,height:i}=this.#e,r=new fa,o=this.#e,l=s,c=i,h=null;if(t){if(s>t||i>t){let q=Math.min(t/s,t/i);l=Math.floor(s*q),c=Math.floor(i*q)}h=document.createElement("canvas");let m=h.width=Math.ceil(l*r.sx),p=h.height=Math.ceil(c*r.sy);if(!this.#c)o=this.#f(m,p);let b=h.getContext("2d");b.filter=this._uiManager.hcmFilter;let v="white",k="#cfcfd8";if(this._uiManager.hcmFilter!=="none")k="black";else if(A7.isDarkMode)v="#8f8f9d",k="#42414d";let A=15,T=A*r.sx,E=A*r.sy,I=new OffscreenCanvas(T*2,E*2),_=I.getContext("2d");_.fillStyle=v,_.fillRect(0,0,T*2,E*2),_.fillStyle=k,_.fillRect(0,0,T,E),_.fillRect(T,E,T,E),b.fillStyle=b.createPattern(I,"repeat"),b.fillRect(0,0,m,p),b.drawImage(o,0,0,o.width,o.height,0,0,m,p)}let d=null;if(n){let m,p;if(r.symmetric&&o.width<e&&o.height<e)m=o.width,p=o.height;else if(o=this.#e,s>e||i>e){let k=Math.min(e/s,e/i);if(m=Math.floor(s*k),p=Math.floor(i*k),!this.#c)o=this.#f(m,p)}let v=new OffscreenCanvas(m,p).getContext("2d",{willReadFrequently:!0});v.drawImage(o,0,0,o.width,o.height,0,0,m,p),d={width:m,height:p,data:v.getImageData(0,0,m,p).data}}return{canvas:h,width:l,height:c,imageData:d}}#f(e,t){let{width:n,height:s}=this.#e,i=n,r=s,o=this.#e;while(i>2*e||r>2*t){let l=i,c=r;if(i>2*e)i=Math.ceil(i/2);if(r>2*t)r=Math.ceil(r/2);let h=new OffscreenCanvas(i,r);h.getContext("2d").drawImage(o,0,0,l,c,0,0,i,r),o=h.transferToImageBitmap()}return o}#m(){let[e,t]=this.parentDimensions,{width:n,height:s}=this,i=new fa,r=Math.ceil(n*e*i.sx),o=Math.ceil(s*t*i.sy),l=this.#r;if(!l||l.width===r&&l.height===o)return;l.width=r,l.height=o;let c=this.#c?this.#e:this.#f(r,o),h=l.getContext("2d");h.filter=this._uiManager.hcmFilter,h.drawImage(c,0,0,c.width,c.height,0,0,r,o)}#b(e){if(e){if(this.#c){let s=this._uiManager.imageManager.getSvgUrl(this.#t);if(s)return s}let t=document.createElement("canvas");return{width:t.width,height:t.height}=this.#e,t.getContext("2d").drawImage(this.#e,0,0),t.toDataURL()}if(this.#c){let[t,n]=this.pageDimensions,s=Math.round(this.width*t*nc.PDF_TO_CSS_UNITS),i=Math.round(this.height*n*nc.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(s,i);return r.getContext("2d").drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,s,i),r.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let s=null,i=!1;if(e instanceof x2){let{data:{rect:v,rotation:k,id:A,structParent:T,popupRef:E,richText:I,contentsObj:_,creationDate:q,modificationDate:P},container:N,parent:{page:{pageNumber:H}},canvas:V}=e,U,W;if(V)delete e.canvas,{id:U,bitmap:W}=n.imageManager.getFromCanvas(N.id,V),V.remove();else i=!0,e._hasNoCanvas=!0;let ce=(await t._structTree.getAriaAttributes(`pdfjs_internal_id_${A}`))?.get("aria-label")||"";s=e={annotationType:Jt.STAMP,bitmapId:U,bitmap:W,pageIndex:H-1,rect:v.slice(0),rotation:k,annotationElementId:A,id:A,deleted:!1,accessibilityData:{decorative:!1,altText:ce},isSvg:!1,structParent:T,popupRef:E,richText:I,comment:_?.str||null,creationDate:q,modificationDate:P}}let r=await super.deserialize(e,t,n),{rect:o,bitmap:l,bitmapUrl:c,bitmapId:h,isSvg:d,accessibilityData:m}=e;if(i)n.addMissingCanvas(e.id,r),r.#o=!0;else if(h&&n.imageManager.isValidId(h)){if(r.#t=h,l)r.#e=l}else r.#s=c;r.#c=d;let[p,b]=r.pageDimensions;if(r.width=(o[2]-o[0])/p,r.height=(o[3]-o[1])/b,m)r.altTextData=m;if(r._initialData=s,e.comment)r.setCommentData(e);return r.#u=!!s,r}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=Object.assign(super.serialize(e),{bitmapId:this.#t,isSvg:this.#c});if(this.addComment(n),e)return n.bitmapUrl=this.#b(!0),n.accessibilityData=this.serializeAltText(!0),n.isCopy=!0,n;let{decorative:s,altText:i}=this.serializeAltText(!1);if(!s&&i)n.accessibilityData={type:"Figure",alt:i};if(this.annotationElementId){let o=this.#w(n);if(o.isSame)return null;if(o.isSameAltText)delete n.accessibilityData;else n.accessibilityData.structParent=this._initialData.structParent??-1;return n.id=this.annotationElementId,delete n.bitmapId,n}if(t===null)return n;t.stamps||=new Map;let r=this.#c?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:r,serialized:n}),n.bitmap=this.#b(!1);else if(this.#c){let o=t.stamps.get(this.#t);if(r>o.area)o.area=r,o.serialized.bitmap.close(),o.serialized.bitmap=this.#b(!1)}return n}#w(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,s=e.pageIndex===t,i=(e.accessibilityData?.alt||"")===n;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&s&&i,isSameAltText:i}}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;return e.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null}}class So{#e;#t=!1;#n=null;#s=null;#i=null;#a=new Map;#r=!1;#o=!1;#l=!1;#c=null;#u=null;#h=null;#d=null;#p=null;#g=-1;#f;static _initialized=!1;static#m=new Map([wi,_2,QS,la,Ua].map((e)=>[e._editorType,e]));constructor({uiManager:e,pageIndex:t,div:n,structTreeLayer:s,accessibilityManager:i,annotationLayer:r,drawLayer:o,textLayer:l,viewport:c,l10n:h}){let d=[...So.#m.values()];if(!So._initialized){So._initialized=!0;for(let m of d)m.initialize(h,e)}e.registerEditorTypes(d),this.#f=e,this.pageIndex=t,this.div=n,this.#e=i,this.#n=r,this.viewport=c,this.#h=l,this.drawLayer=o,this._structTree=s,this.#f.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#f.getMode()===Jt.NONE}updateToolbar(e){this.#f.updateToolbar(e)}updateMode(e=this.#f.getMode()){switch(this.#k(),e){case Jt.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Jt.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case Jt.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:t}=this.div;if(t.toggle("nonEditing",!1),e===Jt.POPUP)t.toggle("commentEditing",!0);else{t.toggle("commentEditing",!1);for(let n of So.#m.values())t.toggle(`${n._type}Editing`,e===n._editorType)}this.div.hidden=!1}hasTextLayer(e){return e===this.#h?.div}setEditingState(e){this.#f.setEditingState(e)}addCommands(e){this.#f.addCommands(e)}cleanUndoStack(e){this.#f.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle("drawing",!e)}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.togglePointerEvents(e)}get#b(){return this.#a.size!==0?this.#a.values():this.#f.getEditors(this.pageIndex)}async enable(){this.#l=!0,this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),this.#p?.abort(),this.#p=null;let e=new Set;for(let n of this.#b)if(n.enableEditing(),n.show(!0),n.annotationElementId)this.#f.removeChangedExistingAnnotation(n),e.add(n.annotationElementId);let t=this.#n;if(t)for(let n of t.getEditableAnnotations()){if(n.hide(),this.#f.isDeletedAnnotationElement(n.data.id))continue;if(e.has(n.data.id))continue;let s=await this.deserialize(n);if(!s)continue;this.addOrRebuild(s),s.enableEditing()}this.#l=!1,this.#f._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){if(this.#o=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),this.#h&&!this.#p){this.#p=new AbortController;let s=this.#f.combinedSignal(this.#p);this.#h.div.addEventListener("pointerdown",(i)=>{let{clientX:o,clientY:l,timeStamp:c}=i,h=this.#g;if(c-h>500){this.#g=c;return}this.#g=-1;let{classList:d}=this.div;d.toggle("getElements",!0);let m=document.elementsFromPoint(o,l);if(d.toggle("getElements",!1),!this.div.contains(m[0]))return;let p,b=new RegExp("^pdfjs_internal_editor_[0-9]+$");for(let k of m)if(b.test(k.id)){p=k.id;break}if(!p)return;let v=this.#a.get(p);if(v?.annotationElementId===null)si(i),v.dblclick(i)},{signal:s,capture:!0})}let e=this.#n,t=[];if(e){let s=new Map,i=new Map;for(let r of this.#b){if(r.disableEditing(),!r.annotationElementId){t.push(r);continue}if(r.serialize()!==null){s.set(r.annotationElementId,r);continue}else i.set(r.annotationElementId,r);this.getEditableAnnotation(r.annotationElementId)?.show(),r.remove()}for(let r of e.getEditableAnnotations()){let{id:o}=r.data;if(this.#f.isDeletedAnnotationElement(o)){r.updateEdited({deleted:!0});continue}let l=i.get(o);if(l){l.resetAnnotationElement(r),l.show(!1),r.show();continue}if(l=s.get(o),l){if(this.#f.addChangedExistingAnnotation(l),l.renderAnnotationElement(r))l.show(!1)}r.show()}}if(this.#k(),this.isEmpty)this.div.hidden=!0;let{classList:n}=this.div;for(let s of So.#m.values())n.remove(`${s._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e?.updateFakeAnnotations(t),this.#o=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){if(this.#f.getActive()===e)return;this.#f.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#h?.div&&!this.#d){this.#d=new AbortController;let e=this.#f.combinedSignal(this.#d);this.#h.div.addEventListener("pointerdown",this.#w.bind(this),{signal:e}),this.#h.div.classList.add("highlighting")}}disableTextSelection(){if(this.div.tabIndex=0,this.#h?.div&&this.#d)this.#d.abort(),this.#d=null,this.#h.div.classList.remove("highlighting")}#w(e){this.#f.unselectAll();let{target:t}=e;if(t===this.#h.div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent")||t.classList.contains("textLayerImages")||t.classList.contains("textLayerImagePlaceholder"))&&this.#h.div.contains(t)){let{isMac:n}=Wn.platform;if(e.button!==0||e.ctrlKey&&n)return;this.#f.showAllEditors("highlight",!0,!0),la.startDrawing(this,this.#f,this.#f.direction==="ltr",e),e.preventDefault()}}enableClick(){if(this.#s)return;this.#s=new AbortController;let e=this.#f.combinedSignal(this.#s);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener("pointerup",t,{signal:e}),this.div.addEventListener("pointercancel",t,{signal:e})}disableClick(){this.#s?.abort(),this.#s=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;if(t&&this.#f.isDeletedAnnotationElement(t))this.#f.removeDeletedAnnotationElement(e)}detach(e){if(this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#o&&e.annotationElementId)this.#f.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#f.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){if(e.parent===this)return;if(e.parent&&e.annotationElementId)this.#f.addDeletedAnnotationElement(e),_t.deleteAnnotationElement(e),e.annotationElementId=null;if(this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM)e.div.remove(),this.div.append(e.div)}add(e){if(e.parent===this&&e.isAttachedToDOM)return;if(this.changeParent(e),this.#f.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#l),this.#f.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;if(e.div.contains(t)&&!this.#i)e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{if(this.#i=null,!e.div.contains(document.activeElement))e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#f._signal}),t.focus();else e._focusEventsAllowed=!0},0);e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){if(e.needsToBeRebuilt())e.parent||=this,e.rebuild(),e.show();else this.add(e)}addUndoableEditor(e){let t=()=>e._uiManager.rebuild(e),n=()=>{e.remove()};this.addCommands({cmd:t,undo:n,mustExec:!1})}getEditorByUID(e){for(let t of this.#a.values())if(t.uid===e)return t;return null}get#y(){return So.#m.get(this.#f.getMode())}combinedSignal(e){return this.#f.combinedSignal(e)}#v(e){let t=this.#y;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#y?.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await this.#f.updateMode(e.mode);let{offsetX:n,offsetY:s}=this.#x(),i=this.#f.getId(),r=this.#v({parent:this,id:i,x:n,y:s,uiManager:this.#f,isCentered:!0,...t});if(r)this.add(r)}async deserialize(e){return await So.#m.get(e.annotationType??e.annotationEditorType)?.deserialize(e,this,this.#f)||null}createAndAddNewEditor(e,t,n={}){let s=this.#f.getId(),i=this.#v({parent:this,id:s,x:e.offsetX,y:e.offsetY,uiManager:this.#f,isCentered:t,...n});if(i)this.add(i);return i}get boundingClientRect(){return this.div.getBoundingClientRect()}#x(){let{x:e,y:t,width:n,height:s}=this.boundingClientRect,i=Math.max(0,e),r=Math.max(0,t),o=Math.min(window.innerWidth,e+n),l=Math.min(window.innerHeight,t+s),c=(i+o)/2-e,h=(r+l)/2-t,[d,m]=this.viewport.rotation%180===0?[c,h]:[h,c];return{offsetX:d,offsetY:m}}addNewEditor(e={}){this.createAndAddNewEditor(this.#x(),!0,e)}setSelected(e){this.#f.setSelected(e)}toggleSelected(e){this.#f.toggleSelected(e)}unselect(e){this.#f.unselect(e)}pointerup(e){let{isMac:t}=Wn.platform;if(e.button!==0||e.ctrlKey&&t)return;if(e.target!==this.div)return;if(!this.#r)return;if(this.#r=!1,this.#y?.isDrawer&&this.#y.supportMultipleDrawings)return;if(!this.#t){this.#t=!0;return}let n=this.#f.getMode();if(n===Jt.STAMP||n===Jt.POPUP||n===Jt.SIGNATURE){this.#f.unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){if(this.#f.getMode()===Jt.HIGHLIGHT)this.enableTextSelection();if(this.#r){this.#r=!1;return}let{isMac:t}=Wn.platform;if(e.button!==0||e.ctrlKey&&t)return;if(e.target!==this.div)return;if(this.#r=!0,this.#y?.isDrawer){this.startDrawingSession(e);return}let n=this.#f.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),this.#c){this.#y.startDrawing(this,this.#f,!1,e);return}this.#f.setCurrentDrawingSession(this),this.#c=new AbortController;let t=this.#f.combinedSignal(this.#c);this.div.addEventListener("blur",({relatedTarget:n})=>{if(n&&!this.div.contains(n))this.#u=null,this.commitOrRemove()},{signal:t}),this.#y.startDrawing(this,this.#f,!1,e)}pause(e){if(e){let{activeElement:t}=document;if(this.div.contains(t))this.#u=t;return}if(this.#u)setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){if(!this.#c)return null;return this.#f.setCurrentDrawingSession(null),this.#c.abort(),this.#c=null,this.#u=null,this.#y.endDrawing(e)}findNewParent(e,t,n){let s=this.#f.findParent(t,n);if(s===null||s===this)return!1;return s.changeParent(e),!0}commitOrRemove(){if(this.#c)return this.endDrawingSession(),!0;return!1}onScaleChanging(){if(!this.#c)return;this.#y.onScaleChangingWhenDrawing(this)}destroy(){if(this.commitOrRemove(),this.#f.getActive()?.parent===this)this.#f.commitOrRemove(),this.#f.setActiveEditor(null);if(this.#i)clearTimeout(this.#i),this.#i=null;for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#f.removeLayer(this)}#k(){for(let e of this.#a.values())if(e.isEmpty())e.remove()}async render({viewport:e}){this.viewport=e,sc(this.div,e);for(let t of this.#f.getEditors(this.pageIndex))this.add(t),t.rebuild();await this.#f.findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){this.#f.commitOrRemove(),this.#k();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,sc(this.div,{rotation:n}),t!==n)for(let s of this.#a.values())s.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#f.viewParameters.realScale}}function UM(e,t){if(e===t)return 0;return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function em(e){if(!e)return null;if(e.nodeType===Node.ELEMENT_NODE)return e.closest(".textLayer");return e.parentElement?.closest(".textLayer")||null}function zM(e,t,n,s){if(e===n)return t<=s;let i=e.compareDocumentPosition(n);if(i&Node.DOCUMENT_POSITION_FOLLOWING)return!0;if(i&Node.DOCUMENT_POSITION_PRECEDING)return!1;return null}function y7(e,t,n){if(e.nodeType!==Node.ELEMENT_NODE||!e.classList.contains("textLayer")||t!==e.childNodes.length)return{container:e,offset:t};let s=e.lastChild;if(s?.nodeType===Node.ELEMENT_NODE&&s.classList.contains("endOfContent"))s=s.previousSibling;if(!s||!n.contains(s))return null;if(s.nodeType===Node.TEXT_NODE)return{container:s,offset:s.textContent.length};return{container:s,offset:s.childNodes.length}}class Kt{#e=null;#t=new Map;#n=null;#s=null;#i=null;#a=null;#r=new Map;static#o=0;static#l=0;static#c=null;static#u=new Set;static#h=!1;static#d=new Set;static#p=new WeakMap;constructor({filterFactory:e=null,pageColors:t=null,pageIndex:n,textLayer:s=null}){if(this.pageIndex=n,this.#s=e,this.#i=t,s){let i=Kt.#p.get(s);if(i?.selectionDiv)i.selectionDiv.remove(),Kt.#u.delete(i.selectionDiv);if(Kt.#p.set(s,{drawLayer:this}),Kt.#d.add(s),this.#n=s,this.#a=new MutationObserver((r)=>{if(!this.#e||!this.#n?.isConnected||!Kt.#f())return;for(let{addedNodes:o}of r)for(let l of o)if(l.nodeType===Node.ELEMENT_NODE&&l.classList.contains("endOfContent")){Kt.#b();return}}),this.#a.observe(s,{childList:!0}),Kt.#c===null){Kt.#c=new AbortController;let{signal:r}=Kt.#c;document.addEventListener("selectionchange",Kt.#b.bind(Kt),{signal:r}),document.addEventListener("pointerdown",()=>{Kt.#h=!0},{signal:r}),document.addEventListener("pointerup",()=>{Kt.#h=!1},{signal:r}),window.addEventListener("blur",()=>{Kt.#h=!1},{signal:r})}}}setParent(e){if(!this.#e){if(this.#e=e,this.#n?.isConnected&&Kt.#f())Kt.#b();return}if(this.#e!==e){if(this.#t.size>0)for(let t of this.#t.values())t.remove(),e.append(t);this.#e=e}}static#g(e){let t=this.#p.get(e);if(!t?.selectionDiv)return;t.selectionDiv.remove(),this.#u.delete(t.selectionDiv),t.selectionDiv=null,t.path=null}static#f(){let e=document.getSelection();return!!e&&!e.isCollapsed}static#m(){return this.#d.keys().filter((e)=>e.isConnected).toArray().sort(UM)}static#b(){let e=document.getSelection();if(!e||e.isCollapsed){for(let r of this.#u)r.remove();this.#u.clear();return}let t=new WeakMap,n=this.#m(),s=[];for(let r=0,o=e.rangeCount;r<o;r++){let l=e.getRangeAt(r);if(l.collapsed)continue;let{startContainer:c,startOffset:h,endContainer:d,endOffset:m}=l,p=em(c),b=em(d),v=p===null,k=b===null;if(this.#h&&v!==k)return;if(e.rangeCount===1){let{anchorNode:E,anchorOffset:I,focusNode:_,focusOffset:q}=e,P=em(E),N=em(_),H=zM(E,I,_,q);if(P&&N&&H!==null)if(H)c=E,h=I,p=P,d=_,m=q,b=N;else c=_,h=q,p=N,d=E,m=I,b=P}let A=n.filter((E)=>l.intersectsNode(E));if(A.length===0)continue;let T=!1;if(!p)p=A[0],c=p,h=0,T=!0;if(!b)b=A.at(-1),d=b,m=b.childNodes.length,T=!0;if(d.nodeType===Node.ELEMENT_NODE){if(d.classList.contains("endOfContent")){let E=d.previousSibling;if(!E)continue;d=E,m=E.nodeType===Node.TEXT_NODE?E.textContent.length:E.childNodes.length}else if(d.classList.contains("textLayer")&&d.childNodes.length===m){let E=y7(d,m,b);if(!E)continue;d=E.container,m=E.offset}}if(c.nodeType===Node.ELEMENT_NODE){let E=y7(c,h,p);if(!E)continue;c=E.container,h=E.offset}if(p===b&&!T&&A.includes(p)){s.push([l,p]);continue}for(let E of A){let I=E.firstChild;if(!I)continue;let _=document.createRange();if(E===p)_.setStart(c,h);else _.setStartBefore(I);if(E===b)_.setEnd(d,m);else{let q=E.lastChild;if(!q)continue;if(q.nodeType===Node.ELEMENT_NODE&&q.classList.contains("endOfContent")){let P=q.previousSibling;if(!P)continue;_.setEndAfter(P)}else _.setEndAfter(q)}if(!_.collapsed)s.push([_,E])}}let i=new Set(s.map((r)=>r[1]));for(let r of this.#d)if(!i.has(r))this.#g(r);for(let[r,o]of s){let l=Kt.#p.get(o);if(!l)continue;let c=t.get(o);if(!c){let b=o.getBoundingClientRect();c=(v,k,A,T)=>({x:(v-b.x)/b.width,y:(k-b.y)/b.height,width:A/b.width,height:T/b.height}),t.set(o,c)}let h=[];for(let{x:b,y:v,width:k,height:A}of r.getClientRects()){if(k===0||A===0)continue;if({x:b,y:v,width:k,height:A}=c(b,v,k,A),k===1&&A===1)continue;h.push(`M${b} ${v} h${k} v${A} h-${k} Z`)}if(h.length===0)continue;let{drawLayer:d,selectionDiv:m,path:p}=l;if(!m){let b=`clip_selection_${Kt.#l++}`;m=document.createElement("div"),m.className="selection",m.style.clipPath=`url(#${b})`;let v=d.#s?.createSelectionStyle(d.#i);if(v)for(let[T,E]of Object.entries(v))m.style.setProperty(T,E);let k=Kt._svgFactory.create(1,1,!0);k.setAttribute("aria-hidden","true"),k.setAttribute("width","100%"),k.setAttribute("height","100%");let A=Kt._svgFactory.createElement("clipPath");A.setAttribute("id",b),A.setAttribute("clipPathUnits","objectBoundingBox"),p=Kt._svgFactory.createElement("path"),A.append(p),k.append(A),m.append(k),l.path=p,l.selectionDiv=m}if(d.#e&&m.parentNode!==d.#e)d.#e.append(m),this.#u.add(m);p.setAttribute("d",h.join(" "))}}static get _svgFactory(){return Mt(this,"_svgFactory",new fu)}static#w(e,[t,n,s,i]){let{style:r}=e;r.top=`${100*n}%`,r.left=`${100*t}%`,r.width=`${100*s}%`,r.height=`${100*i}%`}#y(){let e=Kt._svgFactory.create(1,1,!0);return this.#e.append(e),e.setAttribute("aria-hidden","true"),e}#v(e,t){let n=Kt._svgFactory.createElement("clipPath");e.append(n);let s=`clip_${t}`;n.setAttribute("id",s),n.setAttribute("clipPathUnits","objectBoundingBox");let i=Kt._svgFactory.createElement("use");return n.append(i),i.setAttribute("href",`#${t}`),i.classList.add("clip"),s}#x(e,t){for(let[n,s]of Object.entries(t))if(s===null)e.removeAttribute(n);else e.setAttribute(n,s)}draw(e,t=!1,n=!1){let s=Kt.#o++,i=this.#y(),r=Kt._svgFactory.createElement("defs");i.append(r);let o=Kt._svgFactory.createElement("path");r.append(o);let l=`path_${s}`;if(o.setAttribute("id",l),o.setAttribute("vector-effect","non-scaling-stroke"),t)this.#r.set(s,o);let c=n?this.#v(r,l):null,h=Kt._svgFactory.createElement("use");return i.append(h),h.setAttribute("href",`#${l}`),this.updateProperties(i,e),this.#t.set(s,i),{id:s,clipPathId:`url(#${c})`}}drawOutline(e,t){let n=Kt.#o++,s=this.#y(),i=Kt._svgFactory.createElement("defs");s.append(i);let r=Kt._svgFactory.createElement("path");i.append(r);let o=`path_${n}`;r.setAttribute("id",o),r.setAttribute("vector-effect","non-scaling-stroke");let l;if(t){let d=Kt._svgFactory.createElement("mask");i.append(d),l=`mask_${n}`,d.setAttribute("id",l),d.setAttribute("maskUnits","objectBoundingBox");let m=Kt._svgFactory.createElement("rect");d.append(m),m.setAttribute("width","1"),m.setAttribute("height","1"),m.setAttribute("fill","white");let p=Kt._svgFactory.createElement("use");d.append(p),p.setAttribute("href",`#${o}`),p.setAttribute("stroke","none"),p.setAttribute("fill","black"),p.setAttribute("fill-rule","nonzero"),p.classList.add("mask")}let c=Kt._svgFactory.createElement("use");if(s.append(c),c.setAttribute("href",`#${o}`),l)c.setAttribute("mask",`url(#${l})`);let h=c.cloneNode();return s.append(h),c.classList.add("mainOutline"),h.classList.add("secondaryOutline"),this.updateProperties(s,e),this.#t.set(n,s),n}finalizeDraw(e,t){this.#r.delete(e),this.updateProperties(e,t)}updateProperties(e,t){if(!t)return;let{root:n,bbox:s,rootClass:i,path:r}=t,o=typeof e==="number"?this.#t.get(e):e;if(!o)return;if(n)this.#x(o,n);if(s)Kt.#w(o,s);if(i){let{classList:l}=o;for(let[c,h]of Object.entries(i))l.toggle(c,h)}if(r){let c=o.firstElementChild.firstElementChild;this.#x(c,r)}}updateParent(e,t){if(t===this)return;let n=this.#t.get(e);if(!n)return;t.#e.append(n),this.#t.delete(e),t.#t.set(e,n)}remove(e){if(this.#r.delete(e),this.#e===null)return;this.#t.get(e).remove(),this.#t.delete(e)}destroy(){this.#e=null;for(let e of this.#t.values())e.remove();if(this.#t.clear(),this.#r.clear(),this.#a?.disconnect(),this.#a=null,this.#n){if(Kt.#p.get(this.#n)?.drawLayer===this){if(Kt.#g(this.#n),Kt.#p.delete(this.#n),Kt.#d.delete(this.#n),Kt.#d.size===0)Kt.#c?.abort(),Kt.#c=null,Kt.#h=!1}this.#n=null}}}function tm(e){return`${(e*100).toFixed(2)}%`}class pm{#e=[];#t=new Map;#n=null;#s=0;#i=0;#a=0;static#r=null;constructor(e,t,n,s){this.#s=e,this.#e=t,this.#i=n.rawDims.pageWidth,this.#a=n.rawDims.pageHeight,this.#n=s}render(){let e=document.createElement("div");e.className="textLayerImages";for(let t=0;t<this.#e.length;t+=6){let n=this.#o(this.#e.subarray(t,t+6));if(n)e.append(n)}return e.addEventListener("contextmenu",(t)=>{if(!(t.target instanceof HTMLCanvasElement))return;let n=t.target,s=this.#t.get(n);if(!s)return;let i=pm.#r?.deref();if(i===n)return;if(i)i.width=0,i.height=0;pm.#r=new WeakRef(n);let{inverseTransform:r,x1:o,y1:l,width:c,height:h}=s,d=this.#n(),m=Math.ceil(o*d.width),p=Math.ceil(l*d.height),b=Math.floor((o+c/this.#i)*d.width),v=Math.floor((l+h/this.#a)*d.height);n.width=b-m,n.height=v-p;let k=n.getContext("2d");k.setTransform(...r),k.translate(-m,-p),k.drawImage(d,0,0)}),e}#o([e,t,n,s,i,r]){let o=Math.hypot((i-e)*this.#i,(r-t)*this.#a),l=Math.hypot((n-e)*this.#i,(s-t)*this.#a);if(o<this.#s||l<this.#s)return null;let c=[(i-e)*this.#i/o,(r-t)*this.#a/o,(n-e)*this.#i/l,(s-t)*this.#a/l,0,0],h=ct.inverseTransform(c),d=document.createElement("canvas");return d.className="textLayerImagePlaceholder",d.width=0,d.height=0,Object.assign(d.style,{opacity:0,position:"absolute",left:tm(e),top:tm(t),width:tm(o/this.#i),height:tm(l/this.#a),transformOrigin:"0% 0%",transform:`matrix(${c.join(",")})`}),this.#t.set(d,{inverseTransform:h,width:o,height:l,x1:e,y1:t}),d}}globalThis._pdfjsTestingUtils={HighlightOutliner:um};globalThis.pdfjsLib={AbortException:Ao,AnnotationEditorLayer:So,AnnotationEditorParamsType:Tn,AnnotationEditorType:Jt,AnnotationEditorUIManager:dl,AnnotationLayer:T2,AnnotationMode:hl,AnnotationType:Is,applyOpacity:lM,build:NM,ColorPicker:zr,createValidAbsoluteUrl:v7,CSSConstants:T7,DOMSVGFactory:fu,DrawLayer:Kt,FeatureTest:Wn,fetchData:r2,findContrastColor:cM,getDocument:g2,getFilenameFromUrl:iM,getPdfFilenameFromUrl:aM,getRGB:du,getRGBA:uu,getUuid:x7,GlobalWorkerOptions:xo,ImageKind:nm,InvalidPDFException:om,isDataScheme:Sm,isPdfFile:a2,isValidExplicitDest:gM,makeArr:wf,makeMap:s2,makeObj:Xb,makeSet:tM,MathClamp:bs,noContextMenu:ca,normalizeUnicode:Zq,OPS:za,OutputScale:fa,PasswordException:am,PasswordResponses:Xq,PDFDataRangeTransport:w2,PDFDateString:lm,PDFWorker:Di,PermissionFlag:$q,PixelsPerInch:nc,RenderingCancelledException:vm,renderRichText:E7,ResponseException:iu,setLayerDimensions:sc,shadow:Mt,SignatureExtractor:Kl,stopEvent:si,SupportedImageMimeTypes:Kb,TextLayer:Vi,TextLayerImages:pm,TouchManager:c2,updateUrlHash:S7,Util:ct,VerbosityLevel:gm,version:PM,XfaLayer:i2};Z();function JS({currentPage:e,totalPages:t,onPageChange:n,zoom:s,onZoomIn:i,onZoomOut:r,onFit:o,onDownload:l,canDownload:c,allowDownload:h=!0}){return g("div",{className:"relative px-2 py-2 sm:px-4 sm:py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-between gap-1.5 sm:gap-2 transition-colors duration-200 shrink-0",children:[g("div",{className:"flex items-center gap-1 sm:gap-1.5 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 shrink-0",children:[a("button",{onClick:()=>n(Math.max(1,e-1)),disabled:e<=1,className:"p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40",title:Lh(),children:a(Mn,{size:16})}),g("span",{className:"px-1 sm:px-2 text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none whitespace-nowrap",children:[a("span",{className:"hidden sm:inline",children:XT({current:e,total:t||1})}),g("span",{className:"inline sm:hidden",children:[e,"/",t||1]})]}),a("button",{onClick:()=>n(Math.min(t,e+1)),disabled:e>=t,className:"p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors disabled:opacity-40",title:JI(),children:a(jt,{size:16})})]}),g("div",{className:"flex items-center gap-1 sm:gap-2 shrink-0",children:[g("div",{className:"flex items-center gap-0.5 sm:gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5",children:[a("button",{onClick:r,className:"p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors",title:yg(),children:a(ss,{size:16})}),g("span",{className:"w-10 sm:w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none",children:[Math.round(s*100),"%"]}),a("button",{onClick:i,className:"p-1 sm:p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors",title:_g(),children:a(Re,{size:16})})]}),a("button",{onClick:o,className:"text-xs font-medium px-2 py-1 sm:px-3 sm:py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent",children:fh()}),h&&g("button",{onClick:l,disabled:!c,className:"flex items-center gap-1 text-xs font-medium px-2 py-1 sm:px-3 sm:py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50",title:JE(),children:[a(Bt,{size:14}),a("span",{className:"hidden sm:inline",children:Dr()})]})]})]})}var vf="./pdf.worker.min-vf48er29.mjs";var $M=32000000,ZS=16;if(typeof window<"u"&&xo)try{let e=typeof vf==="string"?vf.startsWith("/")?vf:"/"+vf.replace(/^\.\//,""):vf;if(typeof e==="string")xo.workerSrc=e}catch{}var XM=J(({file:e,annotations:t,shareId:n,children:s,onPlay:i,onPause:r,onTimeUpdate:o,startTime:l,allowDownload:c},h)=>{let{isDrawing:d,currentTool:m,currentColor:p,addAnnotation:b,annotations:v}=un(),[k,A]=w(null),[T,E]=w(()=>l&&!isNaN(l)?Math.max(1,Math.round(l)):1),[I,_]=w(1),[q,P]=w(null),[N,H]=w({width:800,height:1000}),[V,U]=w(2),W=M(null),[ce,ue]=w(!0),[oe,ae]=w(null);bn(h,()=>({play:()=>{i?.()},pause:()=>{r?.()},seekTo:(Le)=>{if(Le&&!isNaN(Le)){let Je=Math.max(1,Math.min(I,Math.round(Le)));E(Je)}}}),[I,i,r]),S(()=>{o?.(T)},[T,o]),S(()=>{let Le=(Je)=>{let bt=document.activeElement;if(bt&&(bt.tagName==="INPUT"||bt.tagName==="TEXTAREA"||bt instanceof HTMLElement&&bt.isContentEditable))return;if(Je.key==="ArrowRight"||Je.key==="ArrowDown"||Je.key==="PageDown")Je.preventDefault(),E((ut)=>{let Ft=Math.min(I,ut+1);if(Ft!==ut)i?.();return Ft});else if(Je.key==="ArrowLeft"||Je.key==="ArrowUp"||Je.key==="PageUp")Je.preventDefault(),E((ut)=>{let Ft=Math.max(1,ut-1);if(Ft!==ut)i?.();return Ft});else if(Je.key==="Home")Je.preventDefault(),E(1),i?.();else if(Je.key==="End")Je.preventDefault(),E(I),i?.()};return window.addEventListener("keydown",Le),()=>{window.removeEventListener("keydown",Le)}},[I,i]);let[te,me]=w({width:0,height:0}),[he,we]=w(1),[be,ye]=w({x:0,y:0}),[Te,Oe]=w(!1);S(()=>{Oe(!1)},[e.id]);let st=M(null);S(()=>{let Le=st.current;if(!Le)return;let Je=new ResizeObserver((bt)=>{let ut=bt[0];if(ut)me({width:ut.contentRect.width,height:ut.contentRect.height})});return Je.observe(Le),()=>Je.disconnect()},[]);let We=e.media?.pdfTranscode?.url;S(()=>{if(!We){ae("No PDF URL available"),ue(!1);return}let Le=!0;ue(!0),ae(null);let Je=g2({url:We});return Je.promise.then((bt)=>{if(!Le)return;A(bt),_(bt.numPages),E((ut)=>l&&!isNaN(l)?Math.max(1,Math.min(bt.numPages,Math.round(l))):ut),ue(!1)}).catch((bt)=>{if(!Le)return;console.error("Failed to load PDF:",bt),ae("Failed to load PDF document"),ue(!1)}),()=>{Le=!1,Je.destroy().catch(()=>{})}},[We,l]),S(()=>{if(!k)return;let Le=!0,Je=null;return k.getPage(T).then((bt)=>{if(!Le)return;let ut=bt.getViewport({scale:1}),Ft=bt.getViewport({scale:V}),nn=document.createElement("canvas");nn.width=Ft.width,nn.height=Ft.height;let mn=nn.getContext("2d");if(!mn)return;if(Je=bt.render({canvasContext:mn,viewport:Ft,canvas:nn}),!Le){Je.cancel();return}Je.promise.then(()=>{if(!Le)return;P(nn),H({width:ut.width,height:ut.height})}).catch((Vt)=>{if(!Le||Vt&&typeof Vt==="object"&&"name"in Vt&&Vt.name==="RenderingCancelledException")return;console.error("Failed to render page:",Vt)})}).catch((bt)=>{if(!Le)return;console.error("Failed to get page:",bt)}),()=>{if(Le=!1,Je)Je.cancel()}},[k,T,V]),S(()=>{let Le=window.setTimeout(()=>{let Je=typeof window<"u"?window.devicePixelRatio||1:1,bt=N.width*N.height,ut=bt>0?Math.sqrt($M/bt):ZS,Ft=Math.min(Math.max(0.5,he*Je),ut,ZS);U(Ft)},150);return()=>window.clearTimeout(Le)},[he,N]),S(()=>{let Le=W.current;if(!k||!Le)return;let Je=!0,bt=null;return Le.innerHTML="",k.getPage(T).then((ut)=>{if(!Je)return;bt=new Vi({textContentSource:ut.streamTextContent(),container:Le,viewport:ut.getViewport({scale:1})}),bt.render().catch(()=>{})}).catch((ut)=>{if(!Je)return;console.error("Failed to build text layer:",ut)}),()=>{Je=!1,bt?.cancel()}},[k,T]),S(()=>{let Le=W.current;if(!Le)return;Le.style.transform=`translate(${be.x}px, ${be.y}px) scale(${he})`},[be,he]);let{width:wt,height:xt}=te,{width:ft,height:It}=N,Wt=Na(wt,xt,ft,It);S(()=>{if(wt<=0||xt<=0||ft<=0||It<=0)return;if(Te)return;we(Wt),ye(Pr(wt,xt,ft,It,Wt))},[wt,xt,Wt,ft,It,Te]);let hn=(Le)=>{Oe(!0);let Je=oa(he,be,Le,wt/2,xt/2);we(Je.zoom),ye(Je.pan)},zt=()=>{Oe(!1),we(Wt),ye(Pr(wt,xt,ft,It,Wt))};ll({containerRef:st,zoom:he,pan:be,baseScale:Wt,onZoomChange:(Le)=>{Oe(!0),we(Le.zoom),ye(Le.pan)},onPanChange:ye});let tn=async()=>{let Le=e.media?.original?.key;if(!Le||!e.id)return;try{let Je=n?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:n,fileId:e.id},json:{key:Le}}):await R.api.files["download-url"].$post({json:{key:Le,assetId:e.id}});if(!Je.ok)return;let{url:bt}=await Je.json(),ut=document.createElement("a");ut.href=bt,ut.download=e.name||"document.pdf",document.body.appendChild(ut),ut.click(),document.body.removeChild(ut)}catch{}},Kn=[...t||[],...v];return g("div",{className:"flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative",children:[g("div",{className:"flex-1 flex flex-col-reverse md:flex-row min-h-0 relative",children:[s,g("div",{ref:st,className:"flex-1 relative overflow-hidden touch-none",children:[ce?a("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 z-20",children:a("div",{className:"w-8 h-8 border-4 border-white/30 border-t-white rounded-full animate-spin"})}):oe?a("div",{className:"absolute inset-0 flex items-center justify-center text-gray-500 text-sm",children:oe}):a(Or,{width:wt,height:xt,mediaDimensions:N,canvasElement:q,annotations:Kn,scale:he,offset:be,className:"absolute inset-0 z-0",isDrawing:d,currentTool:m,currentColor:p,onAddAnnotation:b}),a("div",{ref:W,className:"pdf-text-layer",onMouseDown:(Le)=>{if(Le.target instanceof HTMLElement&&Le.target.tagName!=="SPAN")window.getSelection()?.removeAllRanges()},style:{transform:`translate(${be.x}px, ${be.y}px) scale(${he})`,transformOrigin:"0 0",pointerEvents:d?"none":"auto"}})]})]}),a(JS,{currentPage:T,totalPages:I,onPageChange:(Le)=>{E(Le),i?.()},zoom:he,onZoomIn:()=>hn(1.2),onZoomOut:()=>hn(0.8),onFit:zt,onDownload:tn,canDownload:!!e.media?.original?.key,allowDownload:c})]})}),ek=XM;var tk={id:"pdf",name:"PDF",match:(e)=>e.proxyType==="pdf",viewer:ek,commentsConfig:{hasTimestamp:!0,hasAnnotations:!0,formatTimestamp:(e)=>`P${Math.round(e)}`}};Z();Z();var Oi=15,KM=20,nk=KM/Oi,sk=240,ik=({currentDegree:e,onChange:t,className:n,disabled:s=!1})=>{let i=M(null),[r,o]=w(!1),[l,c]=w(null),h=M({clientX:0,startDegree:0}),d=(Math.round(e/Oi)*Oi%360+360)%360,m=r&&l!==null?l:d,p=(Math.round(m/Oi)*Oi%360+360)%360,b=Q((q)=>{if(s)return;let P=((d+q)%360+360)%360;t(P)},[s,d,t]),v=Q((q)=>{if(s||q.button!==0)return;q.preventDefault(),q.stopPropagation();let P=i.current;if(!P)return;P.setPointerCapture(q.pointerId),h.current={clientX:q.clientX,startDegree:e},o(!0),c(e)},[s,e]),k=Q((q)=>{if(!r||s)return;let P=q.clientX-h.current.clientX,N=h.current.startDegree-P/nk,H=(Math.round(N/Oi)*Oi%360+360)%360;c(N),t(H)},[r,s,t]),A=Q((q)=>{if(!r)return;if(o(!1),l!==null){let P=(Math.round(l/Oi)*Oi%360+360)%360;t(P)}c(null);try{i.current?.releasePointerCapture(q.pointerId)}catch{}},[r,l,t]),T=Q((q)=>{if(s)return;if(q.key==="ArrowLeft"||q.key==="ArrowDown")q.preventDefault(),q.stopPropagation(),b(-Oi);else if(q.key==="ArrowRight"||q.key==="ArrowUp")q.preventDefault(),q.stopPropagation(),b(Oi);else if(q.key==="Home")q.preventDefault(),q.stopPropagation(),t(0);else if(q.key==="End")q.preventDefault(),q.stopPropagation(),t(345)},[s,b,t]),E=Math.floor((m-sk)/Oi),I=Math.ceil((m+sk)/Oi),_=[];for(let q=E;q<=I;q++)_.push(q*Oi);return g("div",{className:B("relative select-none flex items-center gap-1 sm:gap-2.5 w-full min-w-0 sm:min-w-[140px]",s&&"opacity-50",n),children:[a("button",{type:"button",onClick:()=>b(-Oi),disabled:s,title:"Decrease 15°","aria-label":"Decrease 15°","data-testid":"ruler-step-minus",className:"p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:a(ss,{className:"w-3.5 h-3.5"})}),g("div",{className:"relative flex-1 min-w-0",children:[r&&g("div",{"data-testid":"ruler-slider-tooltip",className:"absolute -top-7 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-mono font-medium shadow-md whitespace-nowrap pointer-events-none z-30 animate-in fade-in zoom-in-95 duration-100",children:[p,"°"]}),g("div",{ref:i,role:"slider","aria-label":"Turntable angle","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":p,"aria-valuetext":`${p}°`,tabIndex:s?-1:0,onPointerDown:v,onPointerMove:k,onPointerUp:A,onPointerCancel:A,onKeyDown:T,className:B("relative w-full h-7 rounded-full bg-muted border border-border overflow-hidden cursor-ew-resize touch-none select-none group focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",s&&"cursor-not-allowed"),children:[a("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:_.map((q)=>{let P=(q-m)*nk,N=(q%360+360)%360,H=N%60===0;return a("div",{"data-testid":`tick-${N}`,"data-major":H,className:B("absolute top-1/2 -translate-y-1/2 -translate-x-1/2 transition-colors pointer-events-none rounded-[0.5px]",H?"w-0.5 h-2.5 bg-foreground/75":"w-px h-1.5 bg-muted-foreground/45 group-hover:bg-muted-foreground/65"),style:{left:`calc(50% + ${P}px)`}},`tick-${q}`)})}),a("div",{"data-testid":"ruler-center-indicator",className:"absolute inset-y-0 left-1/2 -translate-x-1/2 w-0.5 flex items-center justify-center pointer-events-none z-20",children:a("div",{className:"w-full h-full bg-[#ea3349] rounded-full"})})]})]}),a("button",{type:"button",onClick:()=>b(Oi),disabled:s,title:"Increase 15°","aria-label":"Increase 15°","data-testid":"ruler-step-plus",className:"p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:a(Re,{className:"w-3.5 h-3.5"})})]})};var rk=({isPlaying:e,currentDegree:t,zoom:n,isFullScreen:s,allowDownload:i=!0,onDownload:r,togglePlay:o,onSeekDegree:l,onZoomChange:c,onZoomReset:h,toggleFullScreen:d})=>a("div",{className:B("transition-all duration-300 ease-in-out z-20 text-foreground",s?"absolute bottom-0 left-0 right-0 px-2 py-2 sm:px-4 sm:py-2.5 bg-card/90 backdrop-blur-md border-t border-border":"relative w-full bg-card border-t border-border px-2 py-2 sm:px-4 sm:py-2.5 z-10 transition-colors duration-200"),children:g("div",{className:"flex items-center justify-between text-foreground gap-1.5 sm:gap-3 md:gap-4",children:[g("div",{className:"flex items-center gap-1.5 sm:gap-3 justify-start min-w-0 flex-1",children:[a("button",{type:"button",onClick:o,"aria-label":e?"Pause":"Play",className:"hover:text-primary transition-colors shrink-0 p-0.5 sm:p-1","data-testid":"play-toggle","data-playing":e,children:e?a(Mc,{className:"w-4 h-4 sm:w-5 sm:h-5 fill-current"}):a(ya,{className:"w-4 h-4 sm:w-5 sm:h-5 fill-current"})}),a("div",{className:"flex items-center text-xs sm:text-sm font-medium tabular-nums select-none shrink-0","data-testid":"degree-readout",children:g("span",{className:"text-muted-foreground font-mono",children:[t,"° / 360°"]})})]}),a("div",{className:"flex items-center w-full max-w-[130px] sm:max-w-[220px] md:max-w-[320px] justify-center mx-auto shrink min-w-0",children:a(ik,{currentDegree:t,onChange:l,className:"w-full"})}),g("div",{className:"flex items-center gap-1 sm:gap-2 justify-end min-w-0 flex-1",children:[g("div",{className:"flex items-center gap-0.5 sm:gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40 shrink-0",children:[a("button",{type:"button",onClick:()=>c(Math.max(0.2,n-0.2)),"aria-label":"Zoom out",className:"p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors",children:a(ss,{className:"w-3.5 h-3.5"})}),g("button",{type:"button",onClick:h,"aria-label":"Reset zoom",className:"px-1 sm:px-1.5 py-0.5 text-[10px] sm:text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors",children:[Math.round(n*100),"%"]}),a("button",{type:"button",onClick:()=>c(Math.min(5,n+0.2)),"aria-label":"Zoom in",className:"p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors",children:a(Re,{className:"w-3.5 h-3.5"})})]}),i&&r&&a("button",{type:"button",onClick:r,title:"Download asset","aria-label":"Download asset",className:"p-1 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0",children:a(Bt,{className:"w-4 h-4"})}),a("button",{type:"button",onClick:d,title:s?"Exit fullscreen":"Fullscreen","aria-label":s?"Exit fullscreen":"Fullscreen",className:"p-1 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0",children:s?a(li,{className:"w-4 h-4"}):a(ai,{className:"w-4 h-4"})})]})]})});var Sf=24;var ak=0.16666666666666666;function ok(e){let t=(e%24+24)%24;if(t===23)return t*0.16666666666666666+0.041666666666666664;return(t+0.5)*0.16666666666666666}function kf(e){return Math.min(Math.max(0,Math.floor(e*6+0.0001)),23)}function wu(e){return kf(e)*15%360}var lk=J(({file:e,onPlay:t,onPause:n,onTimeUpdate:s,onSeek:i,annotations:r,startTime:o,shareId:l,children:c,allowDownload:h=!0,autoPlay:d=!1},m)=>{let p=M(null),b=M(null),v=M(null),[k,A]=w({width:0,height:0}),[T,E]=w(!1),[I,_]=w(o||0),[q,P]=w(!0),[N,H]=w(null),[V,U]=w(!1),[W,ce]=w(1),[ue,oe]=w({x:0,y:0}),[ae,te]=w(!1);S(()=>{te(!1)},[e.id]);let[me,he]=w(!1),we=M({clientX:0,frame:0}),be=M(!1),ye=e.media?.videoTranscodes?.[0]?.url||e.media?.videoPreview?.url||"",Te=async()=>{let St=e.media?.original?.key;if(!St||!e.id)return;try{let it=l?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:l,fileId:e.id},json:{key:St}}):await R.api.files["download-url"].$post({json:{key:St,assetId:e.id}});if(!it.ok)return;let{url:sn}=await it.json(),Lt=document.createElement("a");Lt.href=sn,Lt.download=e.name||"model.glb",document.body.appendChild(Lt),Lt.click(),document.body.removeChild(Lt)}catch{}},{isDrawing:Oe,currentTool:st,currentColor:We,addAnnotation:wt,annotations:xt}=un(),ft=[...r||[],...xt],It=Oe,Wt=e.media?.metadata?.originalWidth||1080,hn=e.media?.metadata?.originalHeight||1080,zt=Na(k.width,k.height,Wt,hn);S(()=>{if(!v.current)return;let St=new ResizeObserver((it)=>{let sn=it[0];if(sn)A({width:sn.contentRect.width,height:sn.contentRect.height})});return St.observe(v.current),()=>St.disconnect()},[]),S(()=>{if(k.width>0&&k.height>0&&!ae)ce(zt),oe(Pr(k.width,k.height,Wt,hn,zt))},[k,Wt,hn,zt,ae]),ll({containerRef:v,zoom:W,pan:ue,baseScale:zt,onZoomChange:(St)=>{te(!0),ce(St.zoom),oe(St.pan)},onPanChange:oe});let tn=wu(I),Kn=M(s);S(()=>{Kn.current=s},[s]);let Le=M(i);S(()=>{Le.current=i},[i]),S(()=>{if(!T)return;let St=b.current;if(!St)return;let it=null,sn=null,Lt=!1,Ln=St,is=typeof Ln.requestVideoFrameCallback==="function",xs=(Ls)=>{if(!me)_(Ls),Kn.current?.(Ls)};if(is){let Ls=(ha,Pi)=>{if(Lt)return;xs(Pi.mediaTime),sn=Ln.requestVideoFrameCallback(Ls)};sn=Ln.requestVideoFrameCallback(Ls)}else{let Ls=()=>{if(Lt)return;if(b.current)xs(b.current.currentTime);it=requestAnimationFrame(Ls)};it=requestAnimationFrame(Ls)}return()=>{if(Lt=!0,sn!==null&&typeof Ln.cancelVideoFrameCallback==="function")Ln.cancelVideoFrameCallback(sn);if(it!==null)cancelAnimationFrame(it)}},[T,me]);let Je=Q((St)=>{let it=(St%Sf+Sf)%Sf,sn=it*ak,Lt=ok(it);if(b.current)b.current.currentTime=Lt;_(sn),s?.(sn)},[s]),bt=Q((St)=>{Le.current?.(),b.current?.pause();let it=Math.round((St%360+360)%360/15)%Sf;Je(it)},[Je]),ut=Q(()=>{let St=b.current;if(!St)return;if(St.paused||St.ended)St.play().catch(()=>{});else St.pause()},[]);bn(m,()=>({play:()=>{b.current?.play().catch(()=>{})},pause:()=>{b.current?.pause()},seekTo:(St)=>{Je(kf(St))},getCurrentTime:()=>b.current?.currentTime||0,getDuration:()=>4}),[Je]),S(()=>{let St=(it)=>{let sn=document.activeElement;if(sn&&(sn.tagName==="INPUT"||sn.tagName==="TEXTAREA"||sn instanceof HTMLElement&&sn.isContentEditable))return;if(it.key===" ")it.preventDefault(),ut();else if(it.key==="ArrowLeft"){it.preventDefault(),Le.current?.();let Lt=kf(I);Je(Lt-1)}else if(it.key==="ArrowRight"){it.preventDefault(),Le.current?.();let Lt=kf(I);Je(Lt+1)}};return window.addEventListener("keydown",St),()=>window.removeEventListener("keydown",St)},[I,Je,ut]);let Ft=(St)=>{if(It||St.button!==0)return;St.currentTarget.setPointerCapture(St.pointerId),b.current?.pause();let sn=Math.round(tn/15)%Sf;we.current={clientX:St.clientX,frame:sn},be.current=!1,he(!0)},nn=(St)=>{if(!me)return;let it=St.clientX-we.current.clientX,sn=Math.round(it/12);if(sn!==0&&!be.current)be.current=!0,Le.current?.();let Lt=we.current.frame-sn;Je(Lt)},mn=(St)=>{if(!me)return;be.current=!1,he(!1);try{St.currentTarget.releasePointerCapture(St.pointerId)}catch{}},Vt=()=>{if(!p.current)return;if(!document.fullscreenElement)p.current.requestFullscreen().catch(()=>{});else document.exitFullscreen().catch(()=>{})};S(()=>{let St=()=>{U(Boolean(document.fullscreenElement))};return document.addEventListener("fullscreenchange",St),()=>document.removeEventListener("fullscreenchange",St)},[]);let Fn=(St)=>{te(!0);let it=oa(W,ue,St/W,k.width/2,k.height/2);ce(it.zoom),oe(it.pan)},ns=()=>{if(te(!1),k.width>0&&k.height>0)ce(zt),oe(Pr(k.width,k.height,Wt,hn,zt))};return g("div",{ref:p,"data-testid":"model-viewer-container",className:B("group shadow-2xl font-sans select-none flex flex-col mx-auto relative",V?"h-full w-full rounded-none bg-black":"w-full h-full"),children:[g("div",{className:"flex-1 flex flex-col-reverse md:flex-row min-h-0 relative",children:[!V&&c,g("div",{ref:v,"data-testid":"model-viewer-surface",onPointerDown:Ft,onPointerMove:nn,onPointerUp:mn,onPointerCancel:mn,className:B("flex-1 bg-black relative flex items-center justify-center overflow-hidden min-h-0 touch-none",It?"cursor-crosshair":me?"cursor-grabbing":"cursor-grab"),children:[a("div",{className:"absolute pointer-events-none",style:{left:0,top:0,width:Wt,height:hn,transform:`translate(${ue.x}px, ${ue.y}px) scale(${W})`,transformOrigin:"0 0"},children:ye&&a("video",{ref:b,src:ye,playsInline:!0,loop:T,muted:!0,autoPlay:d,preload:"auto",onLoadedData:()=>{if(P(!1),o&&o>0)Je(kf(o))},onPlay:()=>{E(!0),t?.()},onPause:()=>{E(!1),n?.()},onEnded:()=>{E(!1)},onError:()=>{P(!1),H("Failed to load turntable video")},className:"w-full h-full block object-contain pointer-events-none"})}),k.width>0&&k.height>0&&a(Or,{width:k.width,height:k.height,mediaDimensions:{width:Wt,height:hn},annotations:ft,scale:W,offset:ue,className:"absolute inset-0 pointer-events-none",isDrawing:Oe,currentTool:st,currentColor:We,onAddAnnotation:wt}),q&&!N&&a("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10",children:a("div",{className:"w-14 h-14 bg-background/80 backdrop-blur-md rounded-full flex items-center justify-center border border-border shadow-lg",children:a(K,{className:"w-7 h-7 text-primary animate-spin"})})}),N&&g("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-destructive z-10 bg-background/90 p-4 text-center",children:[a(_r,{className:"w-10 h-10"}),a("p",{className:"text-sm font-medium",children:N})]})]})]}),a(rk,{isPlaying:T,currentDegree:tn,zoom:W,isFullScreen:V,allowDownload:h,onDownload:e.media?.original?.key?Te:void 0,togglePlay:ut,onSeekDegree:bt,onZoomChange:Fn,onZoomReset:ns,toggleFullScreen:Vt})]})});lk.displayName="ModelViewer";var ck=lk;var fk={id:"3d",name:"3D Model",match:(e)=>e.proxyType==="3d",viewer:ck,commentsConfig:{hasTimestamp:!0,hasAnnotations:!0,formatTimestamp:(e)=>`${wu(e)}°`}};Z();var YM=J(({file:e,shareId:t,children:n,allowDownload:s=!0},i)=>{bn(i,()=>({play:()=>{},pause:()=>{},seekTo:()=>{}}));let r=async()=>{let c=e.media?.original?.key;if(!c||!e.id)return;try{let h=t?await R.api.shares[":shareId"].files[":fileId"]["download-url"].$post({param:{shareId:t,fileId:e.id},json:{key:c}}):await R.api.files["download-url"].$post({json:{key:c,assetId:e.id}});if(!h.ok)return;let{url:d}=await h.json(),m=document.createElement("a");m.href=d,m.download="",document.body.appendChild(m),m.click(),document.body.removeChild(m)}catch{}},o=e.status==="failed",l=e.media?.error;return g("div",{className:"flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative",children:[g("div",{className:"flex-1 flex flex-col-reverse md:flex-row min-h-0 relative",children:[n,a("div",{className:"flex-1 flex items-center justify-center p-6 text-center",children:o?g("div",{"data-testid":"default-viewer-failed-state",className:"flex flex-col items-center justify-center gap-3 max-w-md",children:[a(_r,{className:"h-12 w-12 text-destructive/80"}),g("div",{className:"space-y-1",children:[a("h3",{className:"text-base font-semibold text-foreground",children:J_()}),a("p",{className:"text-sm text-muted-foreground",children:Y_()}),l&&a("div",{title:l,className:"mt-3 rounded-lg border border-destructive/20 bg-destructive/10 p-3 text-xs text-destructive text-left line-clamp-3 break-words",children:l})]})]}):a("p",{className:"text-muted-foreground",children:"Preview unavailable"})})]}),a("div",{className:"relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200",children:s&&g("button",{onClick:r,disabled:!e.media?.original?.key,className:"flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200",title:"Download original file",children:[a(Bt,{size:14}),"Download"]})})]})}),hk=YM;var D2={id:"default",name:"Default",match:()=>!0,viewer:hk,commentsConfig:{hasTimestamp:!1,hasAnnotations:!1}};var QM=[fk,tk,z8,$8];function Ds(e){if(!e)return D2;return QM.find((n)=>n.match(e))||D2}function Ns({file:e,mediaControllerRef:t,onPlay:n,onPause:s,onTimeUpdate:i,onSeek:r,annotations:o,startTime:l,shareId:c,allowDownload:h,autoPlay:d,children:m}){let p=Ds(e),b=p.viewer;return a(b,{ref:t,file:e,onPlay:n,onPause:s,onTimeUpdate:i,onSeek:r,annotations:o,startTime:l,shareId:c,allowDownload:h,autoPlay:d,children:m},p.id)}function JM(e){let t=e.lastIndexOf(".");if(t>0)return[0,t];return[0,e.length]}function ci(e){e.focus();let[t,n]=JM(e.value);if(typeof e.setSelectionRange==="function")e.setSelectionRange(t,n);else e.select()}Z();var ZM=({value:e,config:t,onSave:n,readOnly:s})=>{let i=t?.date,[r,o]=w(!1),l=e?new Date(e):new Date,c=el(l)?l:new Date,[h,d]=w(c);S(()=>{if(r&&e){let P=new Date(e);if(el(P))d(P)}},[r,e]);let m=()=>{if(!s)o(!0)},p=(P)=>{if(s)return;o(P)},b=(P)=>{if(!P)return"";let N=new Date(P);if(!el(N))return"Invalid Date";let H="PPP";if(i?.displayFormat==="usa")H="MM/dd/yyyy";else if(i?.displayFormat==="euro")H="dd/MM/yyyy";else if(i?.displayFormat==="iso")H="yyyy-MM-dd";if(i?.includeTime)if(i?.timeFormat==="twenty_four_hour")H+=" HH:mm";else H+=" p";let V=Nr(N,H);if(i?.displayTimezone)V+=` (${Intl.DateTimeFormat().resolvedOptions().timeZone})`;return V},v=new Date(h.getFullYear(),h.getMonth(),1),k=Hp(h),A=E5({start:v,end:k}),T=C5(v),E=(P)=>{let N=new Date(P);if(i?.includeTime)N.setHours(bg(c)),N.setMinutes(wg(c));let H=N.toISOString();if(n(H),!i?.includeTime)o(!1)},I=(P,N)=>{let H=e?new Date(e):new Date;if(!el(H))H.setTime(new Date().getTime());if(P==="hour")H.setHours(N);if(P==="minute")H.setMinutes(N);let V=H.toISOString();n(V)},_=Array.from({length:24},(P,N)=>N),q=Array.from({length:12},(P,N)=>N*5);return a("div",{className:"relative w-full",onClick:(P)=>P.stopPropagation(),children:g(pt,{open:!s&&r,onOpenChange:p,children:[a(mt,{asChild:!0,children:a("div",{onClick:m,className:`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border transition-colors ${r?"border-ring bg-background shadow-sm":"border-transparent"} ${!s?"cursor-pointer hover:bg-accent hover:border-border":""}`,children:e?b(e):a("span",{className:"text-muted-foreground italic",children:"Empty"})})}),g(ht,{side:"bottom",align:"start",sideOffset:4,className:"p-0 w-auto bg-popover border border-border rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden",onClick:(P)=>P.stopPropagation(),children:[g("div",{className:"p-4 w-64",children:[g("div",{className:"flex justify-between items-center mb-4",children:[a("button",{type:"button",onClick:()=>d(ql(h,-1)),className:"p-1 hover:bg-accent rounded",children:a(Mn,{className:"w-4 h-4"})}),a("span",{className:"font-semibold text-sm",children:Nr(h,"MMMM yyyy")}),a("button",{type:"button",onClick:()=>d(ql(h,1)),className:"p-1 hover:bg-accent rounded",children:a(jt,{className:"w-4 h-4"})})]}),a("div",{className:"grid grid-cols-7 gap-1 text-center text-xs mb-2 text-muted-foreground",children:["Su","Mo","Tu","We","Th","Fr","Sa"].map((P)=>a("div",{children:P},P))}),g("div",{className:"grid grid-cols-7 gap-1 text-center text-sm",children:[Array.from({length:T}).map((P,N)=>a("div",{},`empty-${N}`)),A.map((P)=>{let N=e?new Date(e):null,H=N&&el(N)&&pd(N)===pd(P)&&Od(N)===Od(P)&&Pd(N)===Pd(P);return a("button",{type:"button",onClick:()=>E(P),className:`w-8 h-8 rounded-full flex items-center justify-center hover:bg-accent transition-colors ${H?"bg-primary text-primary-foreground hover:bg-primary/90":"text-foreground"}`,children:pd(P)},P.toString())})]})]}),i?.includeTime&&g("div",{className:"border-l border-border bg-muted w-32 flex flex-col",children:[g("div",{className:"p-2 border-b border-border text-xs font-semibold text-muted-foreground flex items-center justify-center gap-1",children:[a(cr,{className:"w-3 h-3"})," Time"]}),g("div",{className:"flex flex-1 h-64",children:[a("div",{className:"flex-1 overflow-y-auto scrollbar-hide border-r border-border",children:_.map((P)=>a("div",{"data-testid":`hour-${P}`,onClick:()=>I("hour",P),className:`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${bg(c)===P?"bg-primary/10 font-medium text-primary":""}`,children:P.toString().padStart(2,"0")},P))}),a("div",{className:"flex-1 overflow-y-auto scrollbar-hide",children:q.map((P)=>a("div",{"data-testid":`minute-${P}`,onClick:()=>I("minute",P),className:`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${wg(c)===P?"bg-primary/10 font-medium text-primary":""}`,children:P.toString().padStart(2,"0")},P))})]})]})]})]})})},uk=ZM;Z();var eF=({value:e,onSave:t,readOnly:n})=>{let[s,i]=w(!1),[r,o]=w(e||""),l=M(null),c=M(null),h=M(null),[d,m]=w(!1),[p,b]=w(null);S(()=>{o(e||"")},[e]);let v=()=>{if(c.current){let _=c.current.getBoundingClientRect();b({top:_.top,left:_.left,width:_.width,height:_.height})}};nt(()=>{if(d||s)v()},[d,s]);let k=()=>{if(l.current){l.current.style.height="auto";let _=Math.max(80,p?.height||0),q=Math.min(240,Math.max(_,l.current.scrollHeight));l.current.style.height=`${q}px`}};nt(()=>{if(s)k()},[s,r]),S(()=>{if(s&&l.current){l.current.focus();let _=l.current.value.length;l.current.setSelectionRange(_,_)}},[s]),S(()=>{let _=(N)=>{let H=N.target;if(c.current&&!c.current.contains(H)&&h.current&&!h.current.contains(H))if(s)A();else m(!1)},q=(N)=>{if(N.key==="Escape")if(s)i(!1),o(e||"");else m(!1)},P=(N)=>{if(h.current&&h.current.contains(N.target))return;v()};if(d||s)document.addEventListener("mousedown",_),document.addEventListener("keydown",q),window.addEventListener("scroll",P,!0),window.addEventListener("resize",P);return()=>{document.removeEventListener("mousedown",_),document.removeEventListener("keydown",q),window.removeEventListener("scroll",P,!0),window.removeEventListener("resize",P)}},[d,s,r,e]);let A=()=>{if(i(!1),m(!1),r!==(e||""))t(r)};return g("div",{ref:c,className:"relative w-full text-sm",onClick:(_)=>_.stopPropagation(),children:[a("div",{"data-testid":"long-text-placeholder",onClick:(_)=>{if(_.stopPropagation(),v(),!n)i(!0);else m(!0)},className:`w-full text-foreground rounded border border-transparent transition-all px-2 py-1 h-[48px] line-clamp-2 whitespace-pre-wrap overflow-hidden ${d||s?"invisible pointer-events-none select-none":""} ${!n?"cursor-pointer hover:bg-accent hover:border-border":"cursor-pointer"}`,title:!d&&!s?!n?"Click to edit":"Click to expand":void 0,children:e?e:a("span",{className:"text-muted-foreground italic",children:"Empty"})}),(d||s)&&p&&typeof document<"u"&&Js(s?a("textarea",{ref:(_)=>{l.current=_,h.current=_},"data-testid":"long-text-editing-overlay",value:r,onChange:(_)=>{o(_.target.value),k()},onBlur:A,onKeyDown:(_)=>{if((_.metaKey||_.ctrlKey)&&_.key==="Enter")_.currentTarget.blur()},style:{position:"fixed",top:p.top,left:p.left,width:p.width>0?p.width:"auto",minWidth:p.width>0?p.width:200,minHeight:Math.max(80,p.height),maxHeight:240,zIndex:50},className:"bg-background border border-ring rounded shadow-lg px-2 py-1 text-sm outline-none resize-none overflow-y-auto"}):a("div",{ref:(_)=>{h.current=_},"data-testid":"long-text-expanded-overlay",style:{position:"fixed",top:p.top,left:p.left,width:p.width>0?p.width:"auto",minWidth:p.width>0?p.width:200,minHeight:Math.max(80,p.height),maxHeight:240,zIndex:50},className:"min-h-[80px] bg-background border border-ring rounded shadow-lg px-2 py-1 whitespace-pre-wrap overflow-y-auto text-sm cursor-pointer",children:e?e:a("span",{className:"text-muted-foreground italic",children:"Empty"})}),document.body)]})},dk=eF;Z();var tF=({value:e,config:t,onSave:n,readOnly:s})=>{let i=t?.number,[r,o]=w(!1),[l,c]=w(""),h=M(null);S(()=>{c(e!==void 0&&e!==null?e.toString():"")},[e]),S(()=>{if(r&&h.current)h.current.focus()},[r]);let d=(v)=>{if(v.stopPropagation(),!s)o(!0)},m=()=>{if(o(!1),l==="")n(void 0);else{let v=parseFloat(l);n(isNaN(v)?void 0:v)}},p=(v)=>{if(v.key==="Enter")v.stopPropagation(),h.current?.blur();if(v.key==="Escape")v.stopPropagation(),o(!1),c(e!==void 0&&e!==null?e.toString():"")};return a("div",{className:"relative w-full",onClick:(v)=>v.stopPropagation(),onDoubleClick:(v)=>v.stopPropagation(),children:r?a("input",{ref:h,type:"number",step:1/Math.pow(10,i?.scale||0),value:l,onChange:(v)=>c(v.target.value),onBlur:m,onKeyDown:p,onClick:(v)=>v.stopPropagation(),className:"w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm text-left font-mono"}):a("div",{onClick:d,className:`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors text-left font-mono ${!s?"cursor-pointer hover:bg-accent hover:border-border":""}`,children:e!==void 0&&e!==null?((v)=>{if(v===void 0||v===null||isNaN(v))return"";return v.toFixed(i?.scale)})(e):a("span",{className:"text-muted-foreground italic font-sans text-left block",children:"Empty"})})})},mk=tF;Z();var nF=({value:e,config:t,onSave:n,readOnly:s})=>{let i=t?.rating,r=Math.max(2,Math.min(6,i?.maxValue||5)),[o,l]=w(null),c=(d,m)=>{if(d.stopPropagation(),s)return;let p;if(e===m)p=0;else p=m;n(p)},h=Array.from({length:r},(d,m)=>m+1);return a("div",{className:"flex items-center gap-1 h-[28px]",onClick:(d)=>d.stopPropagation(),onMouseLeave:()=>!s&&l(null),onDoubleClick:(d)=>d.stopPropagation(),children:h.map((d)=>{let m=o!==null?d<=o:d<=(e||0);return a("button",{onClick:(p)=>c(p,d),onMouseEnter:()=>!s&&l(d),className:`focus:outline-none transition-transform ${!s?"cursor-pointer hover:scale-110":"cursor-default"}`,type:"button",disabled:s,children:a(fd,{className:`w-5 h-5 transition-colors ${m?"fill-yellow-400 text-yellow-400":"fill-muted text-muted-foreground/30"}`})},d)})})},Qd=nF;Z();Z();Z();function Au(){let[e,t]=w(!1);return g(Se,{open:e,onOpenChange:t,children:[a(Oy,{asChild:!0,children:g(F,{type:"button",variant:"ghost",size:"icon",className:"h-4 w-4 p-0 hover:bg-transparent text-muted-foreground hover:text-foreground inline-flex items-center justify-center shrink-0 ml-1",title:Gm(),children:[a(gg,{className:"h-3.5 w-3.5"}),a("span",{className:"sr-only",children:Gm()})]})}),g(xe,{className:"sm:max-w-[500px]",children:[g(ke,{children:[g(Ce,{className:"flex items-center gap-2",children:[a(gg,{className:"h-5 w-5 text-muted-foreground"}),Gm()]}),a(Ot,{children:sw()})]}),g("div",{className:"space-y-4 py-2",children:[g("div",{className:"rounded-lg border p-3.5 space-y-1.5 bg-muted/30",children:[g("div",{className:"flex items-center gap-2 font-medium text-sm",children:[a(k5,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{children:gd()})]}),a("p",{className:"text-xs text-muted-foreground leading-relaxed",children:iw()}),a("p",{className:"text-xs italic text-muted-foreground/80",children:aw()})]}),g("div",{className:"rounded-lg border p-3.5 space-y-1.5 bg-muted/30",children:[g("div",{className:"flex items-center gap-2 font-medium text-sm",children:[a(qn,{className:"h-4 w-4 text-amber-500 shrink-0"}),a("span",{children:md()})]}),a("p",{className:"text-xs text-muted-foreground leading-relaxed",children:tw()}),a("p",{className:"text-xs italic text-muted-foreground/80",children:rw()})]}),g("div",{className:"rounded-lg border p-3.5 space-y-1.5 bg-muted/30",children:[g("div",{className:"flex items-center gap-2 font-medium text-sm",children:[a($t,{className:"h-4 w-4 text-blue-500 shrink-0"}),a("span",{children:hd()})]}),a("p",{className:"text-xs text-muted-foreground leading-relaxed",children:nw()}),a("p",{className:"text-xs italic text-muted-foreground/80",children:ow()})]})]})]})]})}var cl=["red","orange","yellow","green","blue","purple","gray"],Ca={red:{bg:"rgba(239, 68, 68, 0.15)",text:"#ef4444",hex:"#ef4444"},orange:{bg:"rgba(249, 115, 22, 0.15)",text:"#f97316",hex:"#f97316"},yellow:{bg:"rgba(234, 179, 8, 0.15)",text:"#ca8a04",hex:"#eab308"},green:{bg:"rgba(34, 197, 94, 0.15)",text:"#16a34a",hex:"#22c55e"},blue:{bg:"rgba(59, 130, 246, 0.15)",text:"#2563eb",hex:"#3b82f6"},purple:{bg:"rgba(168, 85, 247, 0.15)",text:"#9333ea",hex:"#a855f7"},gray:{bg:"rgba(128, 128, 128, 0.15)",text:"#4b5563",hex:"#808080"},system:{bg:"rgba(128, 128, 128, 0.1)",text:"#6b7280",hex:"#808080"}};function ui(e){if(!e)return{backgroundColor:"rgba(128, 128, 128, 0.1)",color:"#6b7280"};let t=e.toLowerCase(),n=Ca[t];if(n)return{backgroundColor:n.bg,color:n.text};if(e.startsWith("#"))return{backgroundColor:`${e}33`,color:e};return{backgroundColor:"rgba(128, 128, 128, 0.1)",color:e}}function Sa(e=[]){let t=new Set(e.map((s)=>s.color?.toLowerCase()).filter(Boolean)),n=cl.filter((s)=>!t.has(s.toLowerCase()));if(n.length>0)return n[Math.floor(Math.random()*n.length)];return cl[Math.floor(Math.random()*cl.length)]}var ul={[rn.text]:ec,[rn.longText]:S5,[rn.select]:ps,[rn.selectMulti]:A5,[rn.rating]:fd,[rn.number]:x5,[rn.toggle]:T5,[rn.date]:yo,[rn.user]:jn,[rn.userMulti]:Uo};function sF({field:e,index:t,onVisibilityChange:n}){let{ref:s,handleRef:i}=Gl({id:e.id,index:t}),r=e.config?.type?ul[e.config.type]:null;return g("div",{ref:s,className:"flex items-center justify-between p-2 rounded-md hover:bg-muted",children:[g("div",{className:"flex items-center gap-2",children:[a("div",{ref:i,className:"cursor-grab",children:a(ki,{className:"h-4 w-4 text-muted-foreground"})}),r&&a(r,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.config?.autofillSource===Kr.CONTENT&&a(qn,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.config?.autofillSource===Kr.CREATION_CONTEXT&&a($t,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"text-sm truncate",children:e.config?.name})]}),a(Ve,{checked:e.visible,onCheckedChange:(o)=>n(e.id,o)})]})}function Dg({projectId:e,onManageFields:t,onSave:n}){let{fields:s,updateFields:i}=cn(),[r,o]=w(""),[l,c]=w("list"),[h,d]=w(""),[m,p]=w(""),[b,v]=w(Kr.NONE),[k,A]=w(""),[T,E]=w([]),I=ie();S(()=>{I.invalidateQueries({queryKey:["fields",e]})},[e,I]);let _=R.api.projects[":projectId"].fields.order.$patch,{mutate:q}=ee({mutationFn:async(ue)=>{if(!(await _(ue)).ok)throw Error(ah());return null}}),P=R.api.projects[":projectId"].fields.$post,{mutate:N}=ee({mutationFn:async(ue)=>{let oe=await P(ue);if(!oe.ok)throw Error(sh());return await oe.json()},onSuccess:(ue)=>{let oe={...ue,visible:!0},ae=[...s,oe];i(ae),d(""),E([]),q({param:{projectId:e},json:ae.map((te)=>({fieldId:te.id,visible:te.visible||!1}))}),n?.()}}),H=G(()=>s.filter((ue)=>ue.config?.name?.toLowerCase().includes(r.toLowerCase())),[s,r]),V=(ue)=>{if(ue.canceled)return;let{source:oe}=ue.operation;if(!Lo(oe))return;let{initialIndex:ae,index:te}=oe;if(ae===te)return;let me=qd(s,H,ae,te);i(me),q({param:{projectId:e},json:me.map((he)=>({fieldId:he.id,visible:he.visible||!1}))})},U=(ue,oe)=>{let ae=s.map((te)=>te.id===ue?{...te,visible:oe}:te);i(ae),q({param:{projectId:e},json:ae.map((te)=>({fieldId:te.id,visible:te.visible||!1}))})},W=()=>{if(!h||!m)return;let ue=m===rn.select?{select:{options:T}}:m===rn.selectMulti?{selectMulti:{options:T}}:{};N({param:{projectId:e},json:{config:{name:h,type:m,autofillSource:b,...ue},label:h,description:k}})},ce=s.filter((ue)=>ue.visible).length;if(l==="create")return a("div",{className:"w-80 p-4",children:g("div",{className:"space-y-4",children:[g("div",{className:"space-y-2",children:[a(fe,{htmlFor:"field-name",children:ch()}),a(re,{id:"field-name",placeholder:GI(),value:h,onChange:(ue)=>d(ue.target.value),autoFocus:!0})]}),g("div",{className:"space-y-2",children:[a(fe,{children:uh()}),g(De,{children:[a(Ne,{asChild:!0,children:g(F,{variant:"outline",className:"w-full justify-between font-normal",children:[m?a("span",{className:"capitalize",children:m.replace(/_/g," ")}):a("span",{className:"text-muted-foreground border-dashed",children:rR()}),a(Be,{className:"ml-2 h-4 w-4 opacity-50"})]})}),a(Fe,{className:"w-[--radix-dropdown-menu-trigger-width]",children:Object.values(rn).map((ue)=>a(de,{onClick:()=>{p(ue),E([])},className:"capitalize",children:ue.replace(/_/g," ")},ue))})]})]}),g("div",{className:"space-y-2",children:[a(fe,{htmlFor:"field-desc",children:Uc()}),a(re,{id:"field-desc",placeholder:up(),value:k,onChange:(ue)=>A(ue.target.value)})]}),g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center gap-1",children:[a(fe,{children:ap()}),a(Au,{})]}),g(os,{type:"single",value:b,onValueChange:(ue)=>{if(ue)v(ue)},className:"w-full grid grid-cols-3 border rounded-md p-1 gap-1",children:[a(Lr,{value:Kr.NONE,className:"text-[11px] leading-tight py-1 px-1 h-auto min-h-[32px] w-full text-center justify-center whitespace-normal font-medium",children:gd()}),a(Lr,{value:Kr.CONTENT,className:"text-[11px] leading-tight py-1 px-1 h-auto min-h-[32px] w-full text-center justify-center whitespace-normal font-medium",children:md()}),a(Lr,{value:Kr.CREATION_CONTEXT,className:"text-[11px] leading-tight py-1 px-1 h-auto min-h-[32px] w-full text-center justify-center whitespace-normal font-medium",children:hd()})]})]}),(m===rn.select||m===rn.selectMulti)&&g("div",{className:"space-y-2",children:[g("div",{className:"flex items-center justify-between",children:[a(fe,{className:"text-sm font-medium",children:Sp()}),g(F,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:()=>{let ue={id:As(),displayName:Ep(),color:Sa(T)};E([...T,ue])},children:[a(Re,{className:"h-4 w-4 mr-1"})," ",np()]})]}),a("div",{className:"space-y-2 max-h-40 overflow-y-auto pr-1",children:T.map((ue,oe)=>g("div",{className:"flex items-center gap-2",children:[a(re,{value:ue.displayName,onChange:(ae)=>{let te=[...T];te[oe]={...ue,displayName:ae.target.value},E(te)},placeholder:Ph(),className:"h-8 flex-1"}),g(pt,{children:[a(mt,{asChild:!0,children:a("button",{type:"button",className:"w-6 h-6 rounded-full border shrink-0 cursor-pointer focus:outline-none hover:scale-105 transition-transform",style:{backgroundColor:Ca[ue.color||""]?.hex||ue.color||"#808080"}})}),a(ht,{className:"p-2 w-auto",align:"end",children:a("div",{className:"flex gap-1",children:cl.map((ae)=>a("button",{type:"button",className:"w-5 h-5 rounded-full border cursor-pointer hover:scale-110 transition-transform",style:{backgroundColor:Ca[ae]?.hex||ae},onClick:()=>{let te=[...T];te[oe]={...ue,color:ae},E(te)}},ae))})})]}),a(F,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{E(T.filter((ae,te)=>te!==oe))},children:a(Ge,{className:"h-4 w-4"})})]},ue.id))})]}),g("div",{className:"flex gap-2 pt-2",children:[a(F,{variant:"secondary",className:"flex-1",onClick:()=>{c("list"),d(""),p(""),v(Kr.NONE),A(""),E([])},children:Ke()}),a(F,{className:"flex-1",onClick:W,disabled:!h||!m,children:wo()})]})]})});return g("div",{className:"w-80 p-4",children:[a("div",{className:"flex items-center justify-between mb-4",children:g("h3",{className:"font-semibold",children:[Ll()," ",a("span",{className:"text-muted-foreground text-sm font-normal",children:UO({count:ce})})]})}),g("div",{className:"relative mb-4",children:[a(rr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(re,{placeholder:Gk(),value:r,onChange:(ue)=>o(ue.target.value),className:"pl-8"})]}),a("div",{className:"max-h-60 overflow-y-auto pr-2",children:a(Eo,{sensors:[Yn.configure({activationConstraints:[new an.Distance({value:8})]}),Os],onDragEnd:V,children:H.map((ue,oe)=>a(sF,{field:ue,index:oe,onVisibilityChange:U},ue.id))})}),t&&g("div",{className:"mt-4 space-y-2",children:[g(F,{variant:"secondary",className:"w-full",onClick:t,children:[a(xa,{className:"h-4 w-4 mr-2"}),Ah()]}),g(F,{className:"w-full",onClick:()=>c("create"),children:[a(Re,{className:"h-4 w-4 mr-2"}),QI()]})]})]})}var iF=({value:e,config:t,onSave:n,readOnly:s,fieldId:i})=>{let r=t?.select,o=r?.options||[],[l,c]=w(!1),[h,d]=w(""),m=o.find((_)=>_.id===e),p=h.trim(),b=o.filter((_)=>_.displayName.toLowerCase().includes(p.toLowerCase())),v=o.some((_)=>_.displayName.trim().toLowerCase()===p.toLowerCase()||_.id.toLowerCase()===p.toLowerCase()),k=()=>{if(!s)c(!0)},A=(_)=>{n(_),c(!1),d("")},T=(_)=>{if(s)return;if(c(_),!_)d("")},E=async()=>{if(!p)return;let _={id:p.toLowerCase().replace(/\s+/g,"-"),displayName:p,color:Sa(o)},q=[...o,_],P={...t,select:{...r,options:q}};if(i)try{let N=await R.api.fields[":fieldId"].$put({param:{fieldId:i},json:{config:P}});if(!N.ok){j.error(jc());return}let H=await N.json(),U=cn.getState().fields.map((W)=>W.id===H.id?{...W,...H,visible:W.visible}:W);cn.getState().updateFields(U)}catch{j.error(jc());return}n(_.id),d(""),c(!1)};return a("div",{className:"relative w-full",onClick:(_)=>_.stopPropagation(),children:g(pt,{open:!s&&l,onOpenChange:T,children:[a(mt,{asChild:!0,children:g("div",{onClick:k,className:`flex items-center justify-between w-full h-[28px] px-2 rounded border border-transparent transition-colors ${!s?"cursor-pointer hover:bg-accent hover:border-border group":""}`,children:[((_)=>{if(!_)return a("span",{className:"text-muted-foreground italic text-sm",children:"Select an option"});return a("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium h-[22px]",style:ui(_.color),children:_.displayName})})(m),!s&&a(Be,{className:"w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100"})]})}),g(ht,{side:"bottom",align:"start",sideOffset:4,className:"p-1.5 w-64 max-h-72 flex flex-col bg-popover border border-border rounded-lg shadow-lg",children:[g("div",{className:"relative pb-1.5 border-b border-border mb-1",onClick:(_)=>_.stopPropagation(),children:[a(rr,{className:"w-3.5 h-3.5 absolute left-2 top-2 text-muted-foreground"}),a("input",{type:"text",className:"w-full pl-7 pr-2 py-1 text-xs bg-muted/50 border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-ring text-foreground",placeholder:Y0(),value:h,onChange:(_)=>d(_.target.value),autoFocus:!0})]}),g("div",{className:"overflow-y-auto max-h-48 min-h-[120px] space-y-0.5",children:[h===""&&g("div",{onClick:()=>A(""),className:"px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded cursor-pointer flex items-center gap-2",children:[a(Ge,{className:"w-3.5 h-3.5"})," Clear"]}),b.map((_)=>a("div",{onClick:()=>A(_.id),className:`px-2.5 py-1.5 text-xs hover:bg-accent rounded cursor-pointer flex items-center justify-between ${e===_.id?"bg-accent/50 font-medium":""}`,children:a("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",style:ui(_.color),children:_.displayName})},_.id)),b.length===0&&!p&&a("div",{className:"px-2.5 py-2 text-xs text-muted-foreground italic text-center",children:p0()}),p!==""&&!v&&g("div",{onClick:E,className:"px-2.5 py-1.5 text-xs text-primary hover:bg-accent rounded cursor-pointer flex items-center gap-1.5 font-medium border-t border-border mt-1 pt-1.5",children:[a(Re,{className:"w-3.5 h-3.5 shrink-0"}),a("span",{className:"truncate",children:bA({name:p})})]})]})]})]})})},pk=iF;Z();var rF=({value:e=[],config:t,onSave:n,readOnly:s,fieldId:i})=>{let r=t?.selectMulti,o=r?.options||[],l=M(null),[c,h]=w(!1),[d,m]=w(e.length),[p,b]=w(""),v=o.filter((N)=>(e||[]).includes(N.id))||[],k=p.trim(),A=o.filter((N)=>N.displayName.toLowerCase().includes(k.toLowerCase())),T=o.some((N)=>N.displayName.trim().toLowerCase()===k.toLowerCase()||N.id.toLowerCase()===k.toLowerCase());nt(()=>{if(c){m(v.length);return}if(l.current){let N=l.current.clientWidth-8,V=document.createElement("canvas").getContext("2d");if(V&&N>0){V.font="500 12px ui-sans-serif, system-ui, sans-serif";let U=4,W=v.map((me)=>Math.ceil(V.measureText(me.displayName).width)+18);if(W.reduce((me,he)=>me+he,0)+Math.max(0,W.length-1)*U<=N){m(v.length);return}let oe=N-32-U,ae=0,te=0;for(let me=0;me<W.length;me++){let he=te>0?ae+U+W[me]:W[me];if(he>oe)break;ae=he,te++}m(te)}}},[v,c,e]);let E=(N)=>{let H=e||[],V;if(H.includes(N))V=H.filter((U)=>U!==N);else V=[...H,N];n(V)},I=async()=>{if(!k)return;let N={id:k.toLowerCase().replace(/\s+/g,"-"),displayName:k,color:Sa(o)},H=[...o,N],V={...t,selectMulti:{...r,options:H}};if(i)try{let U=await R.api.fields[":fieldId"].$put({param:{fieldId:i},json:{config:V}});if(!U.ok){j.error(jc());return}let W=await U.json(),ue=cn.getState().fields.map((oe)=>oe.id===W.id?{...oe,...W,visible:oe.visible}:oe);cn.getState().updateFields(ue)}catch{j.error(jc());return}n([...e||[],N.id]),b("")},_=(N)=>{if(N.stopPropagation(),!s)h(!0)},q=v.length-d;return a("div",{className:"relative w-full",onClick:(N)=>N.stopPropagation(),children:g(pt,{open:!s&&c,onOpenChange:(N)=>{if(s)return;if(h(N),!N)b("")},children:[a(mt,{asChild:!0,children:g("div",{ref:l,onClick:_,className:`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${!s||q>0?"cursor-pointer hover:bg-accent hover:border-border":""}`,children:[v.length===0&&a("span",{className:"text-muted-foreground text-sm italic px-1 pt-0.5",children:"Empty"}),v.slice(0,d).map((N)=>a("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]",style:ui(N.color),children:N.displayName},N.id)),q>0&&g("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground h-[22px]",children:["+",q]})]})}),g(ht,{side:"bottom",align:"start",sideOffset:4,className:"p-1.5 w-64 max-h-72 flex flex-col bg-popover border border-border rounded-lg shadow-lg",children:[g("div",{className:"relative pb-1.5 border-b border-border mb-1",onClick:(N)=>N.stopPropagation(),children:[a(rr,{className:"w-3.5 h-3.5 absolute left-2 top-2 text-muted-foreground"}),a("input",{type:"text",className:"w-full pl-7 pr-2 py-1 text-xs bg-muted/50 border border-input rounded-md focus:outline-none focus:ring-1 focus:ring-ring text-foreground",placeholder:Y0(),value:p,onChange:(N)=>b(N.target.value),autoFocus:!0})]}),g("div",{className:"overflow-y-auto max-h-48 min-h-[120px] space-y-0.5",children:[A.map((N)=>{let H=(e||[]).includes(N.id);return g("div",{onClick:()=>E(N.id),className:`px-2.5 py-1.5 hover:bg-accent rounded cursor-pointer flex items-center justify-between text-xs ${H?"bg-accent/30 font-medium":""}`,children:[a("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",style:ui(N.color),children:N.displayName}),H&&a(qe,{className:"w-3.5 h-3.5 text-primary"})]},N.id)}),A.length===0&&!k&&a("div",{className:"px-2.5 py-2 text-xs text-muted-foreground italic text-center",children:p0()}),k!==""&&!T&&g("div",{onClick:I,className:"px-2.5 py-1.5 text-xs text-primary hover:bg-accent rounded cursor-pointer flex items-center gap-1.5 font-medium border-t border-border mt-1 pt-1.5",children:[a(Re,{className:"w-3.5 h-3.5 shrink-0"}),a("span",{className:"truncate",children:bA({name:k})})]})]})]})]})})},gk=rF;Z();var aF=({value:e,onSave:t,readOnly:n})=>{let[s,i]=w(!1),[r,o]=w(e||""),l=M(null);return S(()=>{o(e||"")},[e]),S(()=>{if(s&&l.current)l.current.focus()},[s]),a("div",{className:"relative w-full",onClick:(m)=>m.stopPropagation(),onDoubleClick:(m)=>m.stopPropagation(),children:s?a("input",{ref:l,type:"text",value:r,onChange:(m)=>o(m.target.value),onBlur:()=>{if(i(!1),r!==(e||""))t(r)},onKeyDown:(m)=>{if(m.key==="Enter")l.current?.blur();if(m.key==="Escape")i(!1),o(e||"")},onClick:(m)=>m.stopPropagation(),className:"w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm"}):a("div",{"data-testid":"text-field-display",onClick:(m)=>{if(m.stopPropagation(),!n)i(!0)},className:`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border border-transparent transition-colors ${!n?"cursor-pointer hover:bg-accent hover:border-border":""}`,children:e||a("span",{className:"text-muted-foreground italic",children:"Empty"})})})},bk=aF;var oF=({value:e,onSave:t,readOnly:n})=>a("div",{className:"flex items-center h-[28px] w-full",onClick:(i)=>i.stopPropagation(),children:a(Ve,{checked:e,onCheckedChange:(i)=>{if(!n)t(i)},disabled:n,className:"cursor-pointer"})}),wk=oF;Z();var lF=({value:e,onSave:t,readOnly:n})=>{let s=ri(),{members:i,fetchMembers:r}=An(),[o,l]=w(!1);S(()=>{if(s)r(s)},[s,r]);let c=i.find((v)=>v.id===e),h=()=>{if(!n)l(!0)},d=(v)=>{t(v),l(!1)},m=(v)=>{if(n)return;l(v)},p=(v)=>v.split(" ").map((k)=>k[0]).slice(0,2).join("").toUpperCase();return a("div",{className:"relative w-full",onClick:(v)=>v.stopPropagation(),children:g(pt,{open:!n&&o,onOpenChange:m,children:[a(mt,{asChild:!0,children:g("div",{onClick:h,className:`flex items-center justify-between w-full h-[28px] px-2 rounded border border-transparent transition-colors ${!n?"cursor-pointer hover:bg-accent hover:border-border group":""}`,children:[((v)=>{if(!v)return a("span",{className:"text-muted-foreground italic text-sm",children:"Select user"});return g("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-muted text-foreground border h-[22px]",children:[g($e,{className:"w-4 h-4",children:[a(He,{src:v.image,alt:v.name,className:"object-cover"}),a(Qe,{className:"text-[8px] bg-rose-400 text-black font-semibold",children:p(v.name)})]}),a("span",{className:"truncate max-w-[120px]",children:v.name})]})})(c),!n&&a(Be,{className:"w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100"})]})}),g(ht,{className:"p-1 w-[--radix-popover-trigger-width] min-w-[200px] max-h-60 overflow-auto bg-popover border border-border rounded-lg shadow-lg",align:"start",children:[g("div",{onClick:()=>d(""),className:"px-3 py-2 text-sm text-muted-foreground hover:bg-accent cursor-pointer flex items-center gap-2 rounded-sm",children:[a(Ge,{className:"w-3 h-3"})," Clear"]}),i.map((v)=>g("div",{onClick:()=>d(v.id),className:"px-3 py-2 hover:bg-accent cursor-pointer flex items-center gap-2 rounded-sm",children:[g($e,{className:"w-5 h-5",children:[a(He,{src:v.image,alt:v.name,className:"object-cover"}),a(Qe,{className:"text-[10px] bg-rose-400 text-black font-semibold",children:p(v.name)})]}),a("span",{className:"text-sm font-medium text-foreground",children:v.name})]},v.id))]})]})})},yk=lF;Z();var cF=({value:e=[],onSave:t,readOnly:n})=>{let s=ri(),{members:i,fetchMembers:r}=An(),o=M(null),[l,c]=w(!1),[h,d]=w(e.length);S(()=>{if(s)r(s)},[s,r]);let m=i.filter((E)=>(e||[]).includes(E.id)),p=(E)=>E.split(" ").map((I)=>I[0]).slice(0,2).join("").toUpperCase();nt(()=>{if(l){d(m.length);return}if(o.current){let E=o.current.clientWidth-8,_=document.createElement("canvas").getContext("2d");if(_&&E>0){_.font="500 12px ui-sans-serif, system-ui, sans-serif";let q=4,P=m.map((ce)=>Math.min(100,Math.ceil(_.measureText(ce.name).width))+40);if(P.reduce((ce,ue)=>ce+ue,0)+Math.max(0,P.length-1)*q<=E){d(m.length);return}let V=E-32-q,U=0,W=0;for(let ce=0;ce<P.length;ce++){let ue=W>0?U+q+P[ce]:P[ce];if(ue>V)break;U=ue,W++}d(W)}}},[m,l,e]);let b=(E)=>{let I=e||[],_;if(I.includes(E))_=I.filter((q)=>q!==E);else _=[...I,E];t(_)},v=(E)=>{if(E.stopPropagation(),!n)c(!0)},k=m.length-h,A=(E)=>{if(n)return;c(E)},T=(E)=>g("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-muted text-foreground border whitespace-nowrap h-[22px]",children:[g($e,{className:"w-4 h-4",children:[a(He,{src:E.image,alt:E.name,className:"object-cover"}),a(Qe,{className:"text-[8px] bg-rose-400 text-black font-semibold",children:p(E.name)})]}),a("span",{className:"truncate max-w-[100px]",children:E.name})]},E.id);return a("div",{className:"relative w-full",onClick:(E)=>E.stopPropagation(),children:g(pt,{open:!n&&l,onOpenChange:A,children:[a(mt,{asChild:!0,children:g("div",{ref:o,onClick:v,className:`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${!n||k>0?"cursor-pointer hover:bg-accent hover:border-border":""}`,children:[m.length===0&&a("span",{className:"text-muted-foreground text-sm italic px-1 pt-0.5",children:"Empty"}),m.slice(0,h).map(T),k>0&&g("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground h-[22px]",children:["+",k]})]})}),a(ht,{className:"p-1 w-[--radix-popover-trigger-width] min-w-[200px] max-h-60 overflow-auto bg-popover border border-border rounded-lg shadow-lg",align:"start",children:i.map((E)=>{let I=(e||[]).includes(E.id);return g("div",{onClick:()=>b(E.id),className:"px-3 py-2 hover:bg-accent cursor-pointer flex items-center justify-between rounded-sm",children:[g("div",{className:"flex items-center gap-2",children:[g($e,{className:"w-5 h-5",children:[a(He,{src:E.image,alt:E.name,className:"object-cover"}),a(Qe,{className:"text-[10px] bg-rose-400 text-black font-semibold",children:p(E.name)})]}),a("span",{className:"text-sm font-medium text-foreground",children:E.name})]}),I&&a(qe,{className:"w-4 h-4 text-primary"})]},E.id)})})]})})},vk=cF;var fF=(e)=>{if(!e.config)return a("div",{children:"Unknown Field Type"});switch(e.config.type){case"text":return a(bk,{...e,value:e.value,onSave:e.onSave});case"longText":return a(dk,{...e,value:e.value,onSave:e.onSave});case"select":return a(pk,{...e,value:e.value,onSave:e.onSave});case"selectMulti":return a(gk,{...e,value:e.value,onSave:e.onSave});case"rating":return a(Qd,{...e,value:e.value,onSave:e.onSave});case"number":return a(mk,{...e,value:e.value,onSave:e.onSave});case"toggle":return a(wk,{...e,value:e.value,onSave:e.onSave});case"date":return a(uk,{...e,value:e.value,onSave:e.onSave});case"user":return a(yk,{...e,value:e.value,onSave:e.onSave});case"userMulti":return a(vk,{...e,value:e.value,onSave:e.onSave});default:return a("div",{children:"Unknown Field Type"})}},di=fF;
129
- export{Ps,ai,li,xa,ec,qd,tc,cn,As,$d,gu,Hd,Ds,Ns,ci,Qd,Au,cl,Ca,ui,Sa,ul,Dg,di};