@makefully/fancifully 0.2.0 → 0.3.0

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 (43) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +30 -35
  3. package/dist/Storybook.d.ts +69 -34
  4. package/dist/Storybook.d.ts.map +1 -1
  5. package/dist/fancifully.css +1 -1
  6. package/dist/fancifully.iife.js +4 -4
  7. package/dist/fancifully.js +3139 -2967
  8. package/dist/index.d.ts +9 -7
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/interop/fabricLike.d.ts +124 -0
  11. package/dist/interop/fabricLike.d.ts.map +1 -0
  12. package/dist/{editor → layout}/layoutUnits.d.ts +4 -0
  13. package/dist/{editor → layout}/layoutUnits.d.ts.map +1 -1
  14. package/dist/load/fanciFile.d.ts +6 -0
  15. package/dist/load/fanciFile.d.ts.map +1 -0
  16. package/dist/load/loadEpub.d.ts.map +1 -1
  17. package/dist/nav/Pager.d.ts +10 -3
  18. package/dist/nav/Pager.d.ts.map +1 -1
  19. package/dist/nav/hardback.d.ts +3 -0
  20. package/dist/nav/hardback.d.ts.map +1 -1
  21. package/dist/nav/layoutMode.d.ts +10 -3
  22. package/dist/nav/layoutMode.d.ts.map +1 -1
  23. package/dist/pack/packFanci.d.ts.map +1 -0
  24. package/dist/render/SpreadView.d.ts +20 -2
  25. package/dist/render/SpreadView.d.ts.map +1 -1
  26. package/dist/render/blocks/TextBlock.d.ts.map +1 -1
  27. package/dist/schema/story.d.ts +138 -19
  28. package/dist/schema/story.d.ts.map +1 -1
  29. package/dist/ui/iconifyIcon.d.ts +21 -0
  30. package/dist/ui/iconifyIcon.d.ts.map +1 -0
  31. package/package.json +4 -3
  32. package/dist/editor/EditorChrome.d.ts +0 -33
  33. package/dist/editor/EditorChrome.d.ts.map +0 -1
  34. package/dist/editor/PageCanvas.d.ts +0 -50
  35. package/dist/editor/PageCanvas.d.ts.map +0 -1
  36. package/dist/editor/dropImport.d.ts +0 -16
  37. package/dist/editor/dropImport.d.ts.map +0 -1
  38. package/dist/editor/index.d.ts +0 -7
  39. package/dist/editor/index.d.ts.map +0 -1
  40. package/dist/editor/packFanci.d.ts.map +0 -1
  41. package/dist/editor/storyFabricMap.d.ts +0 -29
  42. package/dist/editor/storyFabricMap.d.ts.map +0 -1
  43. /package/dist/{editor → pack}/packFanci.d.ts +0 -0
@@ -1,4 +1,4 @@
1
- var Fancifully=(function(_){"use strict";var zn=Object.defineProperty;var Zn=(_,me,_e)=>me in _?zn(_,me,{enumerable:!0,configurable:!0,writable:!0,value:_e}):_[me]=_e;var f=(_,me,_e)=>Zn(_,typeof me!="symbol"?me+"":me,_e);class me{constructor(){f(this,"volumes",{sound:1,vo:1,sfx:1,music:1});f(this,"elements",new Set);f(this,"paused",!1)}setVolume(e,t){this.volumes[e]=_e(t),this.applyAll()}getVolume(e){return _e(this.volumes.sound)*_e(this.volumes[e])}setPaused(e){this.paused=e;for(const t of this.elements)e&&t.pause()}get isPaused(){return this.paused}register(e,t){this.elements.add(e),e.volume=this.getVolume(t),e.dataset.fcChannel=t}unregister(e){this.elements.delete(e)}applyTo(e,t){e.volume=this.getVolume(t)}applyAll(){for(const e of this.elements){const t=e.dataset.fcChannel||"vo";e.volume=this.getVolume(t)}}}function _e(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}class Ls{constructor(e=[]){f(this,"cues");f(this,"root",null);f(this,"lastActiveId",null);f(this,"readIds",new Set);this.cues=[...e].sort((t,i)=>t.start-i.start)}setCues(e){this.cues=[...e].sort((t,i)=>t.start-i.start),this.reset()}attach(e){this.root=e,this.resetHighlight()}reset(){this.lastActiveId=null,this.readIds.clear(),this.resetHighlight()}update(e){const t=this.cues.find(i=>e>=i.start&&e<i.end)??null;return this.root&&(t?(this.readIds.add(t.id),t.id!==this.lastActiveId&&(this.applyHighlight(t.id),this.lastActiveId=t.id)):this.lastActiveId&&(this.clearActive(),this.lastActiveId=null)),t}applyHighlight(e){if(!this.root)return;this.root.querySelectorAll(".fc-cue.is-active").forEach(i=>i.classList.remove("is-active"));const t=this.root.querySelector(`#${$s(e)}, [data-cue-id="${Rs(e)}"]`);t&&t.classList.add("fc-cue","is-active","is-read");for(const i of this.readIds){if(i===e)continue;const r=this.root.querySelector(`#${$s(i)}, [data-cue-id="${Rs(i)}"]`);r==null||r.classList.add("fc-cue","is-read")}}clearActive(){var e;(e=this.root)==null||e.querySelectorAll(".fc-cue.is-active").forEach(t=>t.classList.remove("is-active"))}resetHighlight(){var e;(e=this.root)==null||e.querySelectorAll(".fc-cue").forEach(t=>{t.classList.remove("is-active","is-read")})}}function $s(s){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function Rs(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}class Ui{constructor(e){f(this,"bus");f(this,"audio");f(this,"timeline",new Ls);f(this,"queue",[]);f(this,"raf",0);f(this,"captionsMuted",!1);f(this,"onCaptionLine",null);f(this,"playing",!1);this.bus=e,this.audio=new Audio,this.audio.preload="auto",this.bus.register(this.audio,"vo"),this.audio.addEventListener("ended",()=>this.playNext())}setCaptionsMuted(e){var t;this.captionsMuted=e,e&&((t=this.onCaptionLine)==null||t.call(this,null))}onCaption(e){this.onCaptionLine=e}async playSequence(e){this.stop(),this.queue=e.filter(t=>!!t.url),this.queue.length!==0&&(this.playing=!0,await this.playNext())}pause(){this.audio.pause(),this.cancelTick()}resume(){!this.playing||this.bus.isPaused||(this.audio.play().catch(()=>{}),this.startTick())}stop(){var e;this.playing=!1,this.queue=[],this.audio.pause(),this.audio.removeAttribute("src"),this.audio.load(),this.timeline.reset(),this.cancelTick(),(e=this.onCaptionLine)==null||e.call(this,null)}destroy(){this.stop(),this.bus.unregister(this.audio)}async playNext(){var t;this.cancelTick();const e=this.queue.shift();if(!e){this.playing=!1,this.timeline.reset(),(t=this.onCaptionLine)==null||t.call(this,null);return}this.timeline.setCues(e.cues),this.timeline.attach(e.root),this.bus.register(this.audio,e.channel),this.audio.src=e.url,this.bus.applyTo(this.audio,e.channel);try{await this.audio.play(),this.startTick()}catch{this.startTick()}}startTick(){this.cancelTick();const e=()=>{var t;if(this.playing){if(!this.bus.isPaused&&!this.audio.paused){const i=this.timeline.update(this.audio.currentTime);this.captionsMuted||(t=this.onCaptionLine)==null||t.call(this,(i==null?void 0:i.text)??(i==null?void 0:i.id)??null)}this.raf=requestAnimationFrame(e)}};this.raf=requestAnimationFrame(e)}cancelTick(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=0)}}class Di{constructor(e){f(this,"element");f(this,"toggleBtn");f(this,"toolbar");f(this,"frontCoverInput");f(this,"backCoverInput");f(this,"hardbackInput");f(this,"removeBtn");f(this,"handlers");this.handlers=e,this.element=document.createElement("div"),this.element.className="fc-editor-chrome",this.toggleBtn=document.createElement("button"),this.toggleBtn.type="button",this.toggleBtn.className="fc-editor-toggle",this.toggleBtn.textContent="Edit",this.toggleBtn.setAttribute("aria-pressed","false"),this.toggleBtn.addEventListener("click",()=>this.handlers.onToggleEdit()),this.toolbar=document.createElement("div"),this.toolbar.className="fc-editor-toolbar",this.toolbar.hidden=!0;const t=document.createElement("button");t.type="button",t.className="fc-editor-btn",t.textContent="Add page",t.addEventListener("click",()=>this.handlers.onAddPage()),this.removeBtn=document.createElement("button"),this.removeBtn.type="button",this.removeBtn.className="fc-editor-btn",this.removeBtn.textContent="Remove page",this.removeBtn.addEventListener("click",()=>this.handlers.onRemovePage());const i=document.createElement("label");i.className="fc-editor-check",this.frontCoverInput=document.createElement("input"),this.frontCoverInput.type="checkbox",this.frontCoverInput.addEventListener("change",()=>{this.handlers.onFrontCoverChange(this.frontCoverInput.checked)}),i.append(this.frontCoverInput,document.createTextNode(" Front cover"));const r=document.createElement("label");r.className="fc-editor-check",this.backCoverInput=document.createElement("input"),this.backCoverInput.type="checkbox",this.backCoverInput.addEventListener("change",()=>{this.handlers.onBackCoverChange(this.backCoverInput.checked)}),r.append(this.backCoverInput,document.createTextNode(" Back cover"));const n=document.createElement("label");n.className="fc-editor-check",this.hardbackInput=document.createElement("input"),this.hardbackInput.type="checkbox",this.hardbackInput.addEventListener("change",()=>{this.handlers.onHardbackChange(this.hardbackInput.checked)}),n.append(this.hardbackInput,document.createTextNode(" Hardback"));const a=document.createElement("button");a.type="button",a.className="fc-editor-btn fc-editor-btn-download",a.textContent="Download book",a.addEventListener("click",()=>this.handlers.onDownload()),this.toolbar.append(t,this.removeBtn,i,r,n,a),this.element.append(this.toggleBtn,this.toolbar)}setState(e){this.toggleBtn.textContent=e.editing?"Preview":"Edit",this.toggleBtn.setAttribute("aria-pressed",String(e.editing)),this.toggleBtn.classList.toggle("is-active",e.editing),this.toolbar.hidden=!e.editing,this.frontCoverInput.checked=e.frontCover,this.backCoverInput.checked=e.backCover,this.hardbackInput.checked=e.hardback,this.removeBtn.disabled=!e.canRemovePage}destroy(){this.element.remove()}}var D=Uint8Array,te=Uint16Array,Ot=Int32Array,ut=new D([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ft=new D([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),jt=new D([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Fs=function(s,e){for(var t=new te(31),i=0;i<31;++i)t[i]=e+=1<<s[i-1];for(var r=new Ot(t[30]),i=1;i<30;++i)for(var n=t[i];n<t[i+1];++n)r[n]=n-t[i]<<5|i;return{b:t,r}},Bs=Fs(ut,2),Os=Bs.b,Vt=Bs.r;Os[28]=258,Vt[258]=28;for(var js=Fs(ft,0),Hi=js.b,Vs=js.r,zt=new te(32768),F=0;F<32768;++F){var Se=(F&43690)>>1|(F&21845)<<1;Se=(Se&52428)>>2|(Se&13107)<<2,Se=(Se&61680)>>4|(Se&3855)<<4,zt[F]=((Se&65280)>>8|(Se&255)<<8)>>1}for(var ce=(function(s,e,t){for(var i=s.length,r=0,n=new te(e);r<i;++r)s[r]&&++n[s[r]-1];var a=new te(e);for(r=1;r<e;++r)a[r]=a[r-1]+n[r-1]<<1;var o;if(t){o=new te(1<<e);var l=15-e;for(r=0;r<i;++r)if(s[r])for(var c=r<<4|s[r],d=e-s[r],h=a[s[r]-1]++<<d,u=h|(1<<d)-1;h<=u;++h)o[zt[h]>>l]=c}else for(o=new te(i),r=0;r<i;++r)s[r]&&(o[r]=zt[a[s[r]-1]++]>>15-s[r]);return o}),Ce=new D(288),F=0;F<144;++F)Ce[F]=8;for(var F=144;F<256;++F)Ce[F]=9;for(var F=256;F<280;++F)Ce[F]=7;for(var F=280;F<288;++F)Ce[F]=8;for(var Xe=new D(32),F=0;F<32;++F)Xe[F]=5;var Wi=ce(Ce,9,0),qi=ce(Ce,9,1),Xi=ce(Xe,5,0),Yi=ce(Xe,5,1),Zt=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},le=function(s,e,t){var i=e/8|0;return(s[i]|s[i+1]<<8)>>(e&7)&t},Ut=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},Dt=function(s){return(s+7)/8|0},Ye=function(s,e,t){return(e==null||e<0)&&(e=0),(t==null||t>s.length)&&(t=s.length),new D(s.subarray(e,t))},Ji=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Q=function(s,e,t){var i=new Error(e||Ji[s]);if(i.code=s,Error.captureStackTrace&&Error.captureStackTrace(i,Q),!t)throw i;return i},Gi=function(s,e,t,i){var r=s.length,n=i?i.length:0;if(!r||e.f&&!e.l)return t||new D(0);var a=!t,o=a||e.i!=2,l=e.i;a&&(t=new D(r*3));var c=function(dt){var ht=t.length;if(dt>ht){var qe=new D(Math.max(ht*2,dt));qe.set(t),t=qe}},d=e.f||0,h=e.p||0,u=e.b||0,k=e.l,x=e.d,p=e.m,y=e.n,m=r*8;do{if(!k){d=le(s,h,1);var S=le(s,h+1,3);if(h+=3,S)if(S==1)k=qi,x=Yi,p=9,y=5;else if(S==2){var z=le(s,h,31)+257,j=le(s,h+10,15)+4,N=z+le(s,h+5,31)+1;h+=14;for(var T=new D(N),Y=new D(19),Z=0;Z<j;++Z)Y[jt[Z]]=le(s,h+Z*3,7);h+=j*3;for(var X=Zt(Y),ae=(1<<X)-1,R=ce(Y,X,1),Z=0;Z<N;){var V=R[le(s,h,ae)];h+=V&15;var C=V>>4;if(C<16)T[Z++]=C;else{var H=0,B=0;for(C==16?(B=3+le(s,h,3),h+=2,H=T[Z-1]):C==17?(B=3+le(s,h,7),h+=3):C==18&&(B=11+le(s,h,127),h+=7);B--;)T[Z++]=H}}var G=T.subarray(0,z),K=T.subarray(z);p=Zt(G),y=Zt(K),k=ce(G,p,1),x=ce(K,y,1)}else Q(1);else{var C=Dt(h)+4,$=s[C-4]|s[C-3]<<8,O=C+$;if(O>r){l&&Q(0);break}o&&c(u+$),t.set(s.subarray(C,O),u),e.b=u+=$,e.p=h=O*8,e.f=d;continue}if(h>m){l&&Q(0);break}}o&&c(u+131072);for(var ct=(1<<p)-1,oe=(1<<y)-1,xe=h;;xe=h){var H=k[Ut(s,h)&ct],se=H>>4;if(h+=H&15,h>m){l&&Q(0);break}if(H||Q(2),se<256)t[u++]=se;else if(se==256){xe=h,k=null;break}else{var ie=se-254;if(se>264){var Z=se-257,U=ut[Z];ie=le(s,h,(1<<U)-1)+Os[Z],h+=U}var ge=x[Ut(s,h)&oe],He=ge>>4;ge||Q(3),h+=ge&15;var K=Hi[He];if(He>3){var U=ft[He];K+=Ut(s,h)&(1<<U)-1,h+=U}if(h>m){l&&Q(0);break}o&&c(u+131072);var We=u+ie;if(u<K){var Ft=n-K,Bt=Math.min(K,We);for(Ft+u<0&&Q(3);u<Bt;++u)t[u]=i[Ft+u]}for(;u<We;++u)t[u]=t[u-K]}}e.l=k,e.p=xe,e.b=u,e.f=d,k&&(d=1,e.m=p,e.d=x,e.n=y)}while(!d);return u!=t.length&&a?Ye(t,0,u):t.subarray(0,u)},ye=function(s,e,t){t<<=e&7;var i=e/8|0;s[i]|=t,s[i+1]|=t>>8},Je=function(s,e,t){t<<=e&7;var i=e/8|0;s[i]|=t,s[i+1]|=t>>8,s[i+2]|=t>>16},Ht=function(s,e){for(var t=[],i=0;i<s.length;++i)s[i]&&t.push({s:i,f:s[i]});var r=t.length,n=t.slice();if(!r)return{t:Ds,l:0};if(r==1){var a=new D(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(O,z){return O.f-z.f}),t.push({s:-1,f:25001});var o=t[0],l=t[1],c=0,d=1,h=2;for(t[0]={s:-1,f:o.f+l.f,l:o,r:l};d!=r-1;)o=t[t[c].f<t[h].f?c++:h++],l=t[c!=d&&t[c].f<t[h].f?c++:h++],t[d++]={s:-1,f:o.f+l.f,l:o,r:l};for(var u=n[0].s,i=1;i<r;++i)n[i].s>u&&(u=n[i].s);var k=new te(u+1),x=Wt(t[d-1],k,0);if(x>e){var i=0,p=0,y=x-e,m=1<<y;for(n.sort(function(z,j){return k[j.s]-k[z.s]||z.f-j.f});i<r;++i){var S=n[i].s;if(k[S]>e)p+=m-(1<<x-k[S]),k[S]=e;else break}for(p>>=y;p>0;){var C=n[i].s;k[C]<e?p-=1<<e-k[C]++-1:++i}for(;i>=0&&p;--i){var $=n[i].s;k[$]==e&&(--k[$],++p)}x=e}return{t:new D(k),l:x}},Wt=function(s,e,t){return s.s==-1?Math.max(Wt(s.l,e,t+1),Wt(s.r,e,t+1)):e[s.s]=t},zs=function(s){for(var e=s.length;e&&!s[--e];);for(var t=new te(++e),i=0,r=s[0],n=1,a=function(l){t[i++]=l},o=1;o<=e;++o)if(s[o]==r&&o!=e)++n;else{if(!r&&n>2){for(;n>138;n-=138)a(32754);n>2&&(a(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(a(r),--n;n>6;n-=6)a(8304);n>2&&(a(n-3<<5|8208),n=0)}for(;n--;)a(r);n=1,r=s[o]}return{c:t.subarray(0,i),n:e}},Ge=function(s,e){for(var t=0,i=0;i<e.length;++i)t+=s[i]*e[i];return t},Zs=function(s,e,t){var i=t.length,r=Dt(e+2);s[r]=i&255,s[r+1]=i>>8,s[r+2]=s[r]^255,s[r+3]=s[r+1]^255;for(var n=0;n<i;++n)s[r+n+4]=t[n];return(r+4+i)*8},Us=function(s,e,t,i,r,n,a,o,l,c,d){ye(e,d++,t),++r[256];for(var h=Ht(r,15),u=h.t,k=h.l,x=Ht(n,15),p=x.t,y=x.l,m=zs(u),S=m.c,C=m.n,$=zs(p),O=$.c,z=$.n,j=new te(19),N=0;N<S.length;++N)++j[S[N]&31];for(var N=0;N<O.length;++N)++j[O[N]&31];for(var T=Ht(j,7),Y=T.t,Z=T.l,X=19;X>4&&!Y[jt[X-1]];--X);var ae=c+5<<3,R=Ge(r,Ce)+Ge(n,Xe)+a,V=Ge(r,u)+Ge(n,p)+a+14+3*X+Ge(j,Y)+2*j[16]+3*j[17]+7*j[18];if(l>=0&&ae<=R&&ae<=V)return Zs(e,d,s.subarray(l,l+c));var H,B,G,K;if(ye(e,d,1+(V<R)),d+=2,V<R){H=ce(u,k,0),B=u,G=ce(p,y,0),K=p;var ct=ce(Y,Z,0);ye(e,d,C-257),ye(e,d+5,z-1),ye(e,d+10,X-4),d+=14;for(var N=0;N<X;++N)ye(e,d+3*N,Y[jt[N]]);d+=3*X;for(var oe=[S,O],xe=0;xe<2;++xe)for(var se=oe[xe],N=0;N<se.length;++N){var ie=se[N]&31;ye(e,d,ct[ie]),d+=Y[ie],ie>15&&(ye(e,d,se[N]>>5&127),d+=se[N]>>12)}}else H=Wi,B=Ce,G=Xi,K=Xe;for(var N=0;N<o;++N){var U=i[N];if(U>255){var ie=U>>18&31;Je(e,d,H[ie+257]),d+=B[ie+257],ie>7&&(ye(e,d,U>>23&31),d+=ut[ie]);var ge=U&31;Je(e,d,G[ge]),d+=K[ge],ge>3&&(Je(e,d,U>>5&8191),d+=ft[ge])}else Je(e,d,H[U]),d+=B[U]}return Je(e,d,H[256]),d+B[256]},Ki=new Ot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ds=new D(0),Qi=function(s,e,t,i,r,n){var a=n.z||s.length,o=new D(i+a+5*(1+Math.ceil(a/7e3))+r),l=o.subarray(i,o.length-r),c=n.l,d=(n.r||0)&7;if(e){d&&(l[0]=n.r>>3);for(var h=Ki[e-1],u=h>>13,k=h&8191,x=(1<<t)-1,p=n.p||new te(32768),y=n.h||new te(x+1),m=Math.ceil(t/3),S=2*m,C=function(Ms){return(s[Ms]^s[Ms+1]<<m^s[Ms+2]<<S)&x},$=new Ot(25e3),O=new te(288),z=new te(32),j=0,N=0,T=n.i||0,Y=0,Z=n.w||0,X=0;T+2<a;++T){var ae=C(T),R=T&32767,V=y[ae];if(p[R]=V,y[ae]=R,Z<=T){var H=a-T;if((j>7e3||Y>24576)&&(H>423||!c)){d=Us(s,l,0,$,O,z,N,Y,X,T-X,d),Y=j=N=0,X=T;for(var B=0;B<286;++B)O[B]=0;for(var B=0;B<30;++B)z[B]=0}var G=2,K=0,ct=k,oe=R-V&32767;if(H>2&&ae==C(T-oe))for(var xe=Math.min(u,H)-1,se=Math.min(32767,T),ie=Math.min(258,H);oe<=se&&--ct&&R!=V;){if(s[T+G]==s[T+G-oe]){for(var U=0;U<ie&&s[T+U]==s[T+U-oe];++U);if(U>G){if(G=U,K=oe,U>xe)break;for(var ge=Math.min(oe,U-2),He=0,B=0;B<ge;++B){var We=T-oe+B&32767,Ft=p[We],Bt=We-Ft&32767;Bt>He&&(He=Bt,V=We)}}}R=V,V=p[R],oe+=R-V&32767}if(K){$[Y++]=268435456|Vt[G]<<18|Vs[K];var dt=Vt[G]&31,ht=Vs[K]&31;N+=ut[dt]+ft[ht],++O[257+dt],++z[ht],Z=T+G,++j}else $[Y++]=s[T],++O[s[T]]}}for(T=Math.max(T,Z);T<a;++T)$[Y++]=s[T],++O[s[T]];d=Us(s,l,c,$,O,z,N,Y,X,T-X,d),c||(n.r=d&7|l[d/8|0]<<3,d-=7,n.h=y,n.p=p,n.i=T,n.w=Z)}else{for(var T=n.w||0;T<a+c;T+=65535){var qe=T+65535;qe>=a&&(l[d/8|0]=c,qe=a),d=Zs(l,d+1,s.subarray(T,qe))}n.i=a}return Ye(o,0,i+Dt(d)+r)},er=(function(){for(var s=new Int32Array(256),e=0;e<256;++e){for(var t=e,i=9;--i;)t=(t&1&&-306674912)^t>>>1;s[e]=t}return s})(),tr=function(){var s=-1;return{p:function(e){for(var t=s,i=0;i<e.length;++i)t=er[t&255^e[i]]^t>>>8;s=t},d:function(){return~s}}},sr=function(s,e,t,i,r){if(!r&&(r={l:1},e.dictionary)){var n=e.dictionary.subarray(-32768),a=new D(n.length+s.length);a.set(n),a.set(s,n.length),s=a,r.w=n.length}return Qi(s,e.level==null?6:e.level,e.mem==null?r.l?Math.ceil(Math.max(8,Math.min(13,Math.log(s.length)))*1.5):20:12+e.mem,t,i,r)},Hs=function(s,e){var t={};for(var i in s)t[i]=s[i];for(var i in e)t[i]=e[i];return t},de=function(s,e){return s[e]|s[e+1]<<8},re=function(s,e){return(s[e]|s[e+1]<<8|s[e+2]<<16|s[e+3]<<24)>>>0},qt=function(s,e){return re(s,e)+re(s,e+4)*4294967296},J=function(s,e,t){for(;t;++e)s[e]=t,t>>>=8};function ir(s,e){return sr(s,e||{},0,0)}function rr(s,e){return Gi(s,{i:2},e&&e.out,e&&e.dictionary)}var Ws=function(s,e,t,i){for(var r in s){var n=s[r],a=e+r,o=i;Array.isArray(n)&&(o=Hs(i,n[1]),n=n[0]),ArrayBuffer.isView(n)?t[a]=[n,o]:(t[a+="/"]=[new D(0),o],Ws(n,a,t,i))}},qs=typeof TextEncoder<"u"&&new TextEncoder,Xt=typeof TextDecoder<"u"&&new TextDecoder,nr=0;try{Xt.decode(Ds,{stream:!0}),nr=1}catch{}var ar=function(s){for(var e="",t=0;;){var i=s[t++],r=(i>127)+(i>223)+(i>239);if(t+r>s.length)return{s:e,r:Ye(s,t-1)};r?r==3?(i=((i&15)<<18|(s[t++]&63)<<12|(s[t++]&63)<<6|s[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):r&1?e+=String.fromCharCode((i&31)<<6|s[t++]&63):e+=String.fromCharCode((i&15)<<12|(s[t++]&63)<<6|s[t++]&63):e+=String.fromCharCode(i)}};function Yt(s,e){var t;if(qs)return qs.encode(s);for(var i=s.length,r=new D(s.length+(s.length>>1)),n=0,a=function(c){r[n++]=c},t=0;t<i;++t){if(n+5>r.length){var o=new D(n+8+(i-t<<1));o.set(r),r=o}var l=s.charCodeAt(t);l<128||e?a(l):l<2048?(a(192|l>>6),a(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|s.charCodeAt(++t)&1023,a(240|l>>18),a(128|l>>12&63),a(128|l>>6&63),a(128|l&63)):(a(224|l>>12),a(128|l>>6&63),a(128|l&63))}return Ye(r,0,n)}function Xs(s,e){if(e){for(var t="",i=0;i<s.length;i+=16384)t+=String.fromCharCode.apply(null,s.subarray(i,i+16384));return t}else{if(Xt)return Xt.decode(s);var r=ar(s),n=r.s,t=r.r;return t.length&&Q(8),n}}var or=function(s,e){return e+30+de(s,e+26)+de(s,e+28)},lr=function(s,e,t){var i=de(s,e+28),r=de(s,e+30),n=Xs(s.subarray(e+46,e+46+i),!(de(s,e+8)&2048)),a=e+46+i,o=cr(s,a,r,t,re(s,e+20),re(s,e+24),re(s,e+42)),l=o[0],c=o[1],d=o[2];return[de(s,e+10),l,c,n,a+r+de(s,e+32),d]},cr=function(s,e,t,i,r,n,a){var o=r==4294967295,l=n==4294967295,c=a==4294967295,d=e+t,h=o+l+c;if(i&&h){for(;e+4<d;e+=4+de(s,e+2))if(de(s,e)==1)return[o?qt(s,e+4+8*l):r,l?qt(s,e+4):n,c?qt(s,e+4+8*(l+o)):a,1];i<2&&Q(13)}return[r,n,a,0]},Jt=function(s){var e=0;if(s)for(var t in s){var i=s[t].length;i>65535&&Q(9),e+=i+4}return e},Ys=function(s,e,t,i,r,n,a,o){var l=i.length,c=t.extra,d=o&&o.length,h=Jt(c);J(s,e,a!=null?33639248:67324752),e+=4,a!=null&&(s[e++]=20,s[e++]=t.os),s[e]=20,e+=2,s[e++]=t.flag<<1|(n<0&&8),s[e++]=r&&8,s[e++]=t.compression&255,s[e++]=t.compression>>8;var u=new Date(t.mtime==null?Date.now():t.mtime),k=u.getFullYear()-1980;if((k<0||k>119)&&Q(10),J(s,e,k<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,n!=-1&&(J(s,e,t.crc),J(s,e+4,n<0?-n-2:n),J(s,e+8,t.size)),J(s,e+12,l),J(s,e+14,h),e+=16,a!=null&&(J(s,e,d),J(s,e+6,t.attrs),J(s,e+10,a),e+=14),s.set(i,e),e+=l,h)for(var x in c){var p=c[x],y=p.length;J(s,e,+x),J(s,e+2,y),s.set(p,e+4),e+=4+y}return d&&(s.set(o,e),e+=d),e},dr=function(s,e,t,i,r){J(s,e,101010256),J(s,e+8,t),J(s,e+10,t),J(s,e+12,i),J(s,e+16,r)};function hr(s,e){e||(e={});var t={},i=[];Ws(s,"",t,e);var r=0,n=0;for(var a in t){var o=t[a],l=o[0],c=o[1],d=c.level==0?0:8,h=Yt(a),u=h.length,k=c.comment,x=k&&Yt(k),p=x&&x.length,y=Jt(c.extra);u>65535&&Q(11);var m=d?ir(l,c):l,S=m.length,C=tr();C.p(l),i.push(Hs(c,{size:l.length,crc:C.d(),c:m,f:h,m:x,u:u!=a.length||x&&k.length!=p,o:r,compression:d})),r+=30+u+y+S,n+=76+2*(u+y)+(p||0)+S}for(var $=new D(n+22),O=r,z=n-r,j=0;j<i.length;++j){var h=i[j];Ys($,h.o,h,h.f,h.u,h.c.length);var N=30+h.f.length+Jt(h.extra);$.set(h.c,h.o+N),Ys($,r,h,h.f,h.u,h.c.length,h.o,h.m),r+=16+N+(h.m?h.m.length:0)}return dr($,r,i.length,z,O),$}function ur(s,e){for(var t={},i=s.length-22;re(s,i)!=101010256;--i)(!i||s.length-i>65558)&&Q(13);var r=de(s,i+8);if(!r)return{};var n=re(s,i+16),a=re(s,i-20)==117853008;if(a){var o=re(s,i-12);a=re(s,o)==101075792,a&&(r=re(s,o+32),n=re(s,o+48))}for(var l=0;l<r;++l){var c=lr(s,n,a),d=c[0],h=c[1],u=c[2],k=c[3],x=c[4],p=c[5],y=or(s,p);n=x,d?d==8?t[k]=rr(s.subarray(y,y+h),{out:new D(u)}):Q(14,"unknown compression type "+d):t[k]=Ye(s,y,y+h)}return t}function Fe(s,e){if(/^(?:[a-z]+:)?\/\//i.test(e)||e.startsWith("data:")||e.startsWith("blob:")||!s)return e;try{return new URL(e,Gt(s)).href}catch{return`${Gt(s)}${e.replace(/^\//,"")}`}}function Gt(s){return s.endsWith("/")||s.includes("?")?s.endsWith("/")?s:`${s}/`:/\.[a-z0-9]+$/i.test(s.split("/").pop()??"")?s.replace(/[^/]+$/,""):`${s}/`}function fr(s){try{const e=new URL(s,typeof location<"u"?location.href:"http://local/");e.hash="";const t=e.pathname;return e.pathname=t.replace(/[^/]+$/,""),e.href}catch{return Gt(s.replace(/[^/]+$/,""))}}function pt(s){return s.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function gt(s,e){var t;try{const r=(t=new URL(s,"http://local/").pathname.split(".").pop())==null?void 0:t.toLowerCase();if(r&&/^[a-z0-9]{1,8}$/.test(r))return r}catch{}return e}async function mt(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch asset ${s}: ${e.status}`);return new Uint8Array(await e.arrayBuffer())}async function Js(s,e={}){const t={...e.files??{}},i=structuredClone(s),r=e.baseUrl??"";for(const[a,o]of Object.entries(i.assets)){const l=o.src;if(/^(?:[a-z]+:)?\/\//i.test(l)||l.startsWith("blob:")||l.startsWith("data:")){const h=o.type==="image"?gt(l,"png"):o.type==="audio"?gt(l,"mp3"):o.type==="vtt"?"vtt":gt(l,"bin"),u=pt(`assets/${a}.${h}`);t[u]||(t[u]=await mt(l)),o.src=u;continue}const d=pt(l);if(!t[d]){const h=Fe(r,l);t[d]=await mt(h)}o.src=d}for(const a of i.fonts){const o=a.src;if(/^(?:[a-z]+:)?\/\//i.test(o)||o.startsWith("blob:")||o.startsWith("data:")){const c=pt(`fonts/${a.family.replace(/\s+/g,"-")}.${gt(o,"woff2")}`);t[c]||(t[c]=await mt(o)),a.src=c}else{const c=pt(o);t[c]||(t[c]=await mt(Fe(r,o))),a.src=c}}t["story.json"]=Yt(JSON.stringify(i,null,2));const n=hr(t,{level:6});return new Blob([n],{type:"application/zip"})}function Gs(s,e){const t=URL.createObjectURL(s),i=document.createElement("a");i.href=t,i.download=e,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(t)}const pr=new Set(["woff","woff2","ttf","otf"]),gr=new Set(["png","jpg","jpeg","gif","webp","svg","avif"]);function Kt(s){var t;const e=((t=s.split(".").pop())==null?void 0:t.toLowerCase())??"";return/^[a-z0-9]{1,8}$/.test(e)?e:""}function Ks(s){const e=Kt(s.name),t=(s.type||"").toLowerCase();return t.startsWith("font/")||t.includes("font")||pr.has(e)?"font":t.startsWith("image/")||gr.has(e)?"image":t.startsWith("text/")||e==="txt"||e==="md"?"text":"unknown"}function mr(s){return s.replace(/\.[^.]+$/,"").replace(/[_-]+/g," ").trim()||"Custom Font"}function yt(s){return`${s}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function yr(s,e){const t=new Set(e);if(!t.has(s))return s;let i=2;for(;t.has(`${s} ${i}`);)i+=1;return`${s} ${i}`}async function Qs(s){return new Uint8Array(await s.arrayBuffer())}async function vr(s){const e=new Image;return e.decoding="async",await new Promise((t,i)=>{e.onload=()=>t(),e.onerror=()=>i(new Error(`Failed to load image ${s}`)),e.src=s}),e}async function br(s,e,t){const r=await new FontFace(s,`url(${JSON.stringify(e)})`,{weight:"normal",style:"normal"}).load();return document.fonts.add(r),r}async function kr(s){var i,r;const e=(i=s.getData("text/plain"))==null?void 0:i.trim();if(e)return e;const t=(r=s.getData("text/html"))==null?void 0:r.trim();if(t&&typeof DOMParser<"u"){const a=(new DOMParser().parseFromString(t,"text/html").body.textContent??"").replace(/\u00a0/g," ").trim();if(a)return a}for(const n of Array.from(s.files??[]))if(Ks(n)==="text"){const a=(await n.text()).trim();if(a)return a}return null}function Be(s,e=0,t=0){if(s==null)return e;if(typeof s=="number")return Number.isFinite(s)?s:e;const i=s.trim();if(/^-?\d+(\.\d+)?$/.test(i)){const a=Number(i);return Number.isFinite(a)?a:e}const r=i.match(/^(-?\d+(?:\.\d+)?)%$/);if(r){const a=Number(r[1]);return!Number.isFinite(a)||!(t>0)?e:a/100*t}const n=i.match(/^(-?\d+(?:\.\d+)?)px$/i);if(n){const a=Number(n[1]);return Number.isFinite(a)?a:e}return e}function vt(s,e){const{width:t,height:i}=e;return{x:Math.round(Be(s==null?void 0:s.x,0,t)),y:Math.round(Be(s==null?void 0:s.y,0,i)),width:Math.round(Be(s==null?void 0:s.width,t,t)),height:Math.round(Be(s==null?void 0:s.height,i*.25,i))}}function bt(s){return typeof s=="string"&&/%$/.test(s.trim())}function Ke(s,e){if(!(e>0))return"0%";const t=s/e*100,i=Math.round(t*10)/10;return Number.isInteger(i)?`${i}%`:`${i}%`}function Qt(s,e,t,i,r,n,a={}){const o=vt(r,n),l=Math.abs(o.x-s)<=1&&Math.abs(o.y-e)<=1&&Math.abs(o.width-t)<=1,c=Math.abs(o.height-i)<=1;if(l&&(a.preserveHeight||c)&&r)return{...r};const d=bt(r==null?void 0:r.x)||bt(r==null?void 0:r.y)||bt(r==null?void 0:r.width)||bt(r==null?void 0:r.height),h=a.preserveHeight&&(r==null?void 0:r.height)!=null?r.height:i;return d?{...r,x:Ke(s,n.width),y:Ke(e,n.height),width:Ke(t,n.width),height:typeof h=="string"||typeof h=="number"?typeof h=="number"?Ke(h,n.height):h:Ke(i,n.height)}:{...r,x:s,y:e,width:t,height:typeof h=="number"?Math.round(h):h}}function wr(s,e,t=1.35){if(s==null)return t;if(typeof s=="number")return s>0?s:t;const i=s.trim();if(/^-?\d+(\.\d+)?$/.test(i)){const a=Number(i);return a>0?a:t}const r=i.match(/^(-?\d+(?:\.\d+)?)%$/);if(r){const a=Number(r[1])/100;return a>0?a:t}const n=i.match(/^(-?\d+(?:\.\d+)?)px$/i);if(n&&e>0){const a=Number(n[1])/e;return a>0?a:t}return t}const xr=1;function es(s){return typeof DOMParser>"u"?s.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim():(new DOMParser().parseFromString(s,"text/html").body.textContent??"").replace(/\u00a0/g," ")}function ei(s){return`<p>${s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\n/g,"<br/>")}</p>`}function ti(s){return s.type==="text"||s.type==="image"}function ts(s){const e=s.scaleX??1,t=s.scaleY??1;e===1&&t===1||(s.set({width:Math.max(20,(s.width??0)*e),scaleX:1,scaleY:1}),s.setCoords())}function _r(s){s.on("scaling",()=>{ts(s)}),s.on("modified",()=>{ts(s)})}function si(s,e){const{Textbox:t}=s,i=e.fontSize??18,r=e.lineHeight??1.35,n=new t(e.text,{left:e.left,top:e.top,width:Math.max(20,e.width),originX:"left",originY:"top",padding:0,fontFamily:e.fontFamily??"Georgia, serif",fontSize:i,fill:e.fill??"#1f1a14",textAlign:e.textAlign??"left",lineHeight:r,editable:!0,lockScalingY:!0,lockScalingFlip:!0});return n._fontSizeMult=xr,n.initDimensions(),n.setCoords(),n.set({blockId:e.blockId,blockType:"text"}),n.setControlsVisibility({mt:!1,mb:!1,tl:!1,tr:!1,bl:!1,br:!1}),_r(n),n}async function ss(s,e,t,i){var l,c,d,h,u,k,x;const{Textbox:r,FabricImage:n,FabricObject:a}=i;if(a.customProperties=["blockId","blockType","assetId"],s.clear(),(l=e.background)!=null&&l.color?s.backgroundColor=e.background.color:s.backgroundColor="#faf6ef",(c=e.background)!=null&&c.asset){const p=t.images.get(e.background.asset);if(p!=null&&p.src)try{const y=await n.fromURL(p.src,{crossOrigin:"anonymous"});y.set({selectable:!1,evented:!1,excludeFromExport:!1});const m=s.getWidth()/(y.width||1),S=s.getHeight()/(y.height||1),C=Math.max(m,S);y.set({left:0,top:0,scaleX:C,scaleY:C,originX:"left",originY:"top"}),s.backgroundImage=y}catch{}}const o={width:s.getWidth(),height:s.getHeight()};for(const p of e.blocks)if(ti(p)){if(p.type==="text"){const y=p.html??t.html.get(`htmlSrc:${p.id}`)??(p.htmlSrc?t.html.get(p.htmlSrc):void 0)??"",m=vt(p.layout,o),S=Be((d=p.style)==null?void 0:d.fontSize,18)||18,C=wr((h=p.style)==null?void 0:h.lineHeight,S,1.35),$=si(i,{blockId:p.id,text:es(y),left:m.x,top:m.y,width:Math.max(20,m.width),fontFamily:((u=p.style)==null?void 0:u.fontFamily)??"Georgia, serif",fontSize:S,fill:((k=p.style)==null?void 0:k.color)??"#1f1a14",textAlign:((x=p.style)==null?void 0:x.textAlign)??"left",lineHeight:C});s.add($)}else if(p.type==="image"){const y=t.images.get(p.asset);if(!(y!=null&&y.src))continue;const m=vt(p.layout,o);try{const S=await n.fromURL(y.src,{crossOrigin:"anonymous"}),C=S.width||1,$=S.height||1;S.set({left:m.x,top:m.y,scaleX:m.width/C,scaleY:m.height/$,originX:"left",originY:"top",blockId:p.id,blockType:"image",assetId:p.asset}),s.add(S)}catch{}}}s.requestRenderAll()}function ii(s,e,t){const i=t??{width:s.getWidth(),height:s.getHeight()},r=e.blocks.filter(c=>c.type==="hotspot"),n=new Map;for(const c of e.blocks)c.type!=="hotspot"&&n.set(c.id,{...c});const a=[],o=s.getObjects();for(const c of o){const d=c.blockId,h=c.blockType;if(!d||!h)continue;const u=n.get(d),k=Math.round(c.left??0),x=Math.round(c.top??0);if(h==="text"){const p=c,y=Math.round(p.width??0),m=Math.round(p.height??0),S=p.text??"",C=u&&u.type==="text"?u:void 0,$=C?es(C.html??""):"",O=C&&$===S&&C.html?C.html:ei(S),z=C!=null&&C.style?{...C.style}:{fontFamily:p.fontFamily||void 0,fontSize:`${p.fontSize??18}px`,color:typeof p.fill=="string"?p.fill:void 0,textAlign:p.textAlign??void 0};a.push({id:d,type:"text",layout:Qt(k,x,y,m,C==null?void 0:C.layout,i,{preserveHeight:!0}),html:O,style:z,htmlSrc:C==null?void 0:C.htmlSrc})}else if(h==="image"){const p=Math.round((c.width??0)*(c.scaleX??1)),y=Math.round((c.height??0)*(c.scaleY??1)),m=c.assetId??(u&&u.type==="image"?u.asset:void 0);if(!m)continue;const S=u&&u.type==="image"?u:void 0;a.push({id:d,type:"image",asset:m,layout:Qt(k,x,p,y,S==null?void 0:S.layout,i),className:S==null?void 0:S.className})}}for(const c of e.blocks)ti(c)&&(a.some(d=>d.id===c.id)||a.push(c));let l=e.background?{...e.background}:void 0;return typeof s.backgroundColor=="string"&&s.backgroundColor&&(l={...l,color:s.backgroundColor}),{...e,background:l,blocks:[...a,...r]}}class is{constructor(e,t,i){f(this,"element");f(this,"canvasEl");f(this,"fabricCanvas",null);f(this,"page");f(this,"assets");f(this,"pageSize");f(this,"fabricMod",null);f(this,"dirty",!1);f(this,"host");this.page=e,this.assets=i.assets,this.pageSize=t,this.host=i,this.element=document.createElement("div"),this.element.className="fc-page-canvas",this.element.dataset.pageId=e.id,this.canvasEl=document.createElement("canvas"),this.canvasEl.width=t.width,this.canvasEl.height=t.height,this.element.appendChild(this.canvasEl)}static async create(e,t,i){const r=new is(e,t,i);return await r.mount(),r}async mount(){const e=await import("fabric");this.fabricMod=e;const{Canvas:t}=e;this.fabricCanvas=new t(this.canvasEl,{width:this.pageSize.width,height:this.pageSize.height,preserveObjectStacking:!0,selection:!0,uniformScaling:!1}),this.fabricCanvas.on("object:scaling",r=>{const n=r.target;(n==null?void 0:n.blockType)==="text"&&ts(n)});const i=()=>{this.dirty=!0};this.fabricCanvas.on("object:modified",i),this.fabricCanvas.on("text:changed",i),this.fabricCanvas.on("dragover",r=>{r.e.preventDefault()}),this.fabricCanvas.on("drop",r=>{r.e.preventDefault(),this.handleDrop(r)}),await ss(this.fabricCanvas,this.page,this.assets,e),this.dirty=!1}syncLayout(){this.fabricCanvas&&(this.fabricCanvas.setDimensions({width:this.pageSize.width,height:this.pageSize.height}),this.fabricCanvas.calcOffset(),this.fabricCanvas.requestRenderAll())}get isDirty(){return this.dirty}markDirty(){this.dirty=!0}applyFontToAllText(e){if(this.fabricCanvas){for(const t of this.fabricCanvas.getObjects())t.blockType==="text"&&t.set({fontFamily:e});this.fabricCanvas.requestRenderAll(),this.dirty=!0}}commit(){if(!this.fabricCanvas)return this.page;const e=ii(this.fabricCanvas,this.page,this.pageSize);return this.page=e,this.dirty=!1,e}get pageId(){return this.page.id}async reload(e){this.page=e,this.element.dataset.pageId=e.id,!(!this.fabricCanvas||!this.fabricMod)&&(await ss(this.fabricCanvas,this.page,this.assets,this.fabricMod),this.syncLayout(),this.dirty=!1)}destroy(){var e;(e=this.fabricCanvas)==null||e.dispose(),this.fabricCanvas=null,this.element.remove()}async handleDrop(e){if(!this.fabricCanvas||!this.fabricMod)return;const t=e.e,i=t.dataTransfer;if(!i)return;const r=this.fabricCanvas.getScenePoint(t),n=e.target,a=Array.from(i.files??[]);let o=!1;for(const l of a){const c=Ks(l);if(c==="font")await this.dropFont(l,n),o=!0;else if(c==="image")await this.dropImage(l,r.x,r.y),o=!0;else if(c==="text"){const d=(await l.text()).trim();d&&(this.dropText(d,r.x,r.y),o=!0)}}if(!o){const l=await kr(i);l&&this.dropText(l,r.x,r.y)}}async dropFont(e,t){var c;const i=Kt(e.name)||"woff2",r=mr(e.name),n=yr(r,this.host.story.fonts.map(d=>d.family)),a=await Qs(e),o=`fonts/${yt("font")}.${i}`,l=URL.createObjectURL(e);this.host.blobUrls.push(l),this.host.editorFiles[o]=a,await br(n,l),this.host.story.fonts.push({family:n,src:o}),(t==null?void 0:t.blockType)==="text"?(t.set({fontFamily:n}),(c=this.fabricCanvas)==null||c.requestRenderAll(),this.dirty=!0):(this.host.setDefaultFontFamily(n),this.host.applyFontToAllTextboxes(n))}async dropImage(e,t,i){if(!this.fabricCanvas||!this.fabricMod)return;const r=Kt(e.name)||"png",n=yt("img"),a=`assets/${n}.${r}`,o=await Qs(e),l=URL.createObjectURL(e);this.host.blobUrls.push(l),this.host.editorFiles[a]=o,this.host.story.assets[n]={type:"image",src:a};const c=await vr(l);this.host.assets.images.set(n,c);const{FabricImage:d}=this.fabricMod,h=await d.fromURL(l,{crossOrigin:"anonymous"}),u=this.pageSize.width*.5,k=this.pageSize.height*.5,x=h.width||1,p=h.height||1,y=Math.min(1,u/x,k/p),m=x*y,S=p*y;h.set({left:Math.max(0,Math.min(t-m/2,this.pageSize.width-m)),top:Math.max(0,Math.min(i-S/2,this.pageSize.height-S)),scaleX:y,scaleY:y,originX:"left",originY:"top",blockId:yt("block"),blockType:"image",assetId:n}),this.fabricCanvas.add(h),this.fabricCanvas.setActiveObject(h),this.fabricCanvas.requestRenderAll(),this.dirty=!0}dropText(e,t,i){if(!this.fabricCanvas||!this.fabricMod)return;const r=Math.min(280,this.pageSize.width*.7),n=this.host.getDefaultFontFamily()??"Georgia, serif",a=si(this.fabricMod,{blockId:yt("block"),text:e,left:Math.max(0,Math.min(t,this.pageSize.width-40)),top:Math.max(0,Math.min(i,this.pageSize.height-40)),width:r,fontFamily:n,fontSize:22,fill:"#2a2440",lineHeight:1.4});this.fabricCanvas.add(a),this.fabricCanvas.setActiveObject(a),this.fabricCanvas.requestRenderAll(),this.dirty=!0}}function Sr(s,e){let t=0,i=0,r=!1;const n=l=>{l.button!=null&&l.button!==0||(r=!0,t=l.clientX,i=l.clientY)},a=l=>{var h,u;if(!r)return;r=!1;const c=l.clientX-t,d=l.clientY-i;Math.abs(c)<50||Math.abs(c)<Math.abs(d)||(c<0?(h=e.onSwipeLeft)==null||h.call(e):(u=e.onSwipeRight)==null||u.call(e))},o=()=>{r=!1};return s.addEventListener("pointerdown",n),s.addEventListener("pointerup",a),s.addEventListener("pointercancel",o),()=>{s.removeEventListener("pointerdown",n),s.removeEventListener("pointerup",a),s.removeEventListener("pointercancel",o)}}var M;(function(s){s.assertEqual=r=>{};function e(r){}s.assertIs=e;function t(r){throw new Error}s.assertNever=t,s.arrayToEnum=r=>{const n={};for(const a of r)n[a]=a;return n},s.getValidEnumValues=r=>{const n=s.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of n)a[o]=r[o];return s.objectValues(a)},s.objectValues=r=>s.objectKeys(r).map(function(n){return r[n]}),s.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const n=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&n.push(a);return n},s.find=(r,n)=>{for(const a of r)if(n(a))return a},s.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,n=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(n)}s.joinValues=i,s.jsonStringifyReplacer=(r,n)=>typeof n=="bigint"?n.toString():n})(M||(M={}));var ri;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(ri||(ri={}));const b=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ee=s=>{switch(typeof s){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(s)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(s)?b.array:s===null?b.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?b.promise:typeof Map<"u"&&s instanceof Map?b.map:typeof Set<"u"&&s instanceof Set?b.set:typeof Date<"u"&&s instanceof Date?b.date:b.object;default:return b.unknown}},g=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ve extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(n){return n.message},i={_errors:[]},r=n=>{for(const a of n.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)i._errors.push(t(a));else{let o=i,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return r(this),i}static assert(e){if(!(e instanceof ve))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else i.push(e(r));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ve.create=s=>new ve(s);const rs=(s,e)=>{let t;switch(s.code){case g.invalid_type:s.received===b.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case g.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,M.jsonStringifyReplacer)}`;break;case g.unrecognized_keys:t=`Unrecognized key(s) in object: ${M.joinValues(s.keys,", ")}`;break;case g.invalid_union:t="Invalid input";break;case g.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${M.joinValues(s.options)}`;break;case g.invalid_enum_value:t=`Invalid enum value. Expected ${M.joinValues(s.options)}, received '${s.received}'`;break;case g.invalid_arguments:t="Invalid function arguments";break;case g.invalid_return_type:t="Invalid function return type";break;case g.invalid_date:t="Invalid date";break;case g.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:M.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case g.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case g.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case g.custom:t="Invalid input";break;case g.invalid_intersection_types:t="Intersection results could not be merged";break;case g.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case g.not_finite:t="Number must be finite";break;default:t=e.defaultError,M.assertNever(s)}return{message:t}};let Cr=rs;function Er(){return Cr}const Ar=s=>{const{data:e,path:t,errorMaps:i,issueData:r}=s,n=[...t,...r.path||[]],a={...r,path:n};if(r.message!==void 0)return{...r,path:n,message:r.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:e,defaultError:o}).message;return{...r,path:n,message:o}};function v(s,e){const t=Er(),i=Ar({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===rs?void 0:rs].filter(r=>!!r)});s.common.issues.push(i)}class ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const r of t){if(r.status==="aborted")return E;r.status==="dirty"&&e.dirty(),i.push(r.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const r of t){const n=await r.key,a=await r.value;i.push({key:n,value:a})}return ee.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const r of t){const{key:n,value:a}=r;if(n.status==="aborted"||a.status==="aborted")return E;n.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(i[n.value]=a.value)}return{status:e.value,value:i}}}const E=Object.freeze({status:"aborted"}),Qe=s=>({status:"dirty",value:s}),ne=s=>({status:"valid",value:s}),ni=s=>s.status==="aborted",ai=s=>s.status==="dirty",Oe=s=>s.status==="valid",kt=s=>typeof Promise<"u"&&s instanceof Promise;var w;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(w||(w={}));class he{constructor(e,t,i,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const oi=(s,e)=>{if(Oe(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ve(s.common.issues);return this._error=t,this._error}}};function I(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:r}=s;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(a,o)=>{const{message:l}=s;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??i??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:r}}class P{get description(){return this._def.description}_getType(e){return Ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ee,ctx:{common:e.parent.common,data:e.data,parsedType:Ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(kt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ee(e)},r=this._parseSync({data:e,path:i.path,parent:i});return oi(i,r)}"~validate"(e){var i,r;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ee(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Oe(n)?{value:n.value}:{issues:t.common.issues}}catch(n){(r=(i=n==null?void 0:n.message)==null?void 0:i.toLowerCase())!=null&&r.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>Oe(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ee(e)},r=this._parse({data:e,path:i.path,parent:i}),n=await(kt(r)?r:Promise.resolve(r));return oi(i,n)}refine(e,t){const i=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,n)=>{const a=e(r),o=()=>n.addIssue({code:g.custom,...i(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,r)=>e(i)?!0:(r.addIssue(typeof t=="function"?t(i,r):t),!1))}_refinement(e){return new Me({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return we.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ue.create(this)}promise(){return Et.create(this,this._def)}or(e){return xt.create([this,e],this._def)}and(e){return _t.create(this,e,this._def)}transform(e){return new Me({...I(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new At({...I(this._def),innerType:this,defaultValue:t,typeName:A.ZodDefault})}brand(){return new yi({typeName:A.ZodBranded,type:this,...I(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Tt({...I(this._def),innerType:this,catchValue:t,typeName:A.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fs.create(this,e)}readonly(){return It.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Tr=/^c[^\s-]{8,}$/i,Ir=/^[0-9a-z]+$/,Pr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Mr=/^[a-z0-9_-]{21}$/i,Lr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$r=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Rr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ns;const Br=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Or=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,jr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Vr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,li="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ur=new RegExp(`^${li}$`);function ci(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Dr(s){return new RegExp(`^${ci(s)}$`)}function Hr(s){let e=`${li}T${ci(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Wr(s,e){return!!((e==="v4"||!e)&&Br.test(s)||(e==="v6"||!e)&&jr.test(s))}function qr(s,e){if(!Lr.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(i));return!(typeof r!="object"||r===null||"typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Xr(s,e){return!!((e==="v4"||!e)&&Or.test(s)||(e==="v6"||!e)&&Vr.test(s))}class be extends P{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){const n=this._getOrReturnCtx(e);return v(n,{code:g.invalid_type,expected:b.string,received:n.parsedType}),E}const i=new ee;let r;for(const n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),v(r,{code:g.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),v(r,{code:g.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const a=e.data.length>n.value,o=e.data.length<n.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?v(r,{code:g.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&v(r,{code:g.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")Rr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"email",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")ns||(ns=new RegExp(Fr,"u")),ns.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"emoji",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")Nr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"uuid",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")Mr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"nanoid",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Tr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"cuid",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")Ir.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"cuid2",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Pr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"ulid",code:g.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),v(r,{validation:"url",code:g.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"regex",code:g.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?Hr(n).test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?Ur.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?Dr(n).test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{code:g.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?$r.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"duration",code:g.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Wr(e.data,n.version)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"ip",code:g.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?qr(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"jwt",code:g.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?Xr(e.data,n.version)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"cidr",code:g.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?zr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"base64",code:g.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?Zr.test(e.data)||(r=this._getOrReturnCtx(e,r),v(r,{validation:"base64url",code:g.invalid_string,message:n.message}),i.dirty()):M.assertNever(n);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(r=>e.test(r),{validation:t,code:g.invalid_string,...w.errToObj(i)})}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...w.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...w.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...w.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...w.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...w.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...w.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...w.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...w.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...w.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...w.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...w.errToObj(t)})}nonempty(e){return this.min(1,w.errToObj(e))}trim(){return new be({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new be({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new be({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}be.create=s=>new be({checks:[],typeName:A.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...I(s)});function Yr(s,e){const t=(s.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,r=t>i?t:i,n=Number.parseInt(s.toFixed(r).replace(".","")),a=Number.parseInt(e.toFixed(r).replace(".",""));return n%a/10**r}class je extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==b.number){const n=this._getOrReturnCtx(e);return v(n,{code:g.invalid_type,expected:b.number,received:n.parsedType}),E}let i;const r=new ee;for(const n of this._def.checks)n.kind==="int"?M.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),v(i,{code:g.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="multipleOf"?Yr(e.data,n.value)!==0&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),v(i,{code:g.not_finite,message:n.message}),r.dirty()):M.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,i,r){return new je({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:w.toString(r)}]})}_addCheck(e){return new je({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&M.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}je.create=s=>new je({checks:[],typeName:A.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...I(s)});class et extends P{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==b.bigint)return this._getInvalidInput(e);let i;const r=new ee;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),v(i,{code:g.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):M.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return v(t,{code:g.invalid_type,expected:b.bigint,received:t.parsedType}),E}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,i,r){return new et({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:w.toString(r)}]})}_addCheck(e){return new et({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}et.create=s=>new et({checks:[],typeName:A.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...I(s)});class as extends P{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==b.boolean){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.boolean,received:i.parsedType}),E}return ne(e.data)}}as.create=s=>new as({typeName:A.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...I(s)});class wt extends P{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){const n=this._getOrReturnCtx(e);return v(n,{code:g.invalid_type,expected:b.date,received:n.parsedType}),E}if(Number.isNaN(e.data.getTime())){const n=this._getOrReturnCtx(e);return v(n,{code:g.invalid_date}),E}const i=new ee;let r;for(const n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),v(r,{code:g.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),v(r,{code:g.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):M.assertNever(n);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new wt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:w.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}wt.create=s=>new wt({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:A.ZodDate,...I(s)});class di extends P{_parse(e){if(this._getType(e)!==b.symbol){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.symbol,received:i.parsedType}),E}return ne(e.data)}}di.create=s=>new di({typeName:A.ZodSymbol,...I(s)});class os extends P{_parse(e){if(this._getType(e)!==b.undefined){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.undefined,received:i.parsedType}),E}return ne(e.data)}}os.create=s=>new os({typeName:A.ZodUndefined,...I(s)});class ls extends P{_parse(e){if(this._getType(e)!==b.null){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.null,received:i.parsedType}),E}return ne(e.data)}}ls.create=s=>new ls({typeName:A.ZodNull,...I(s)});class hi extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}}hi.create=s=>new hi({typeName:A.ZodAny,...I(s)});class ui extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}}ui.create=s=>new ui({typeName:A.ZodUnknown,...I(s)});class Ae extends P{_parse(e){const t=this._getOrReturnCtx(e);return v(t,{code:g.invalid_type,expected:b.never,received:t.parsedType}),E}}Ae.create=s=>new Ae({typeName:A.ZodNever,...I(s)});class fi extends P{_parse(e){if(this._getType(e)!==b.undefined){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.void,received:i.parsedType}),E}return ne(e.data)}}fi.create=s=>new fi({typeName:A.ZodVoid,...I(s)});class ue extends P{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),r=this._def;if(t.parsedType!==b.array)return v(t,{code:g.invalid_type,expected:b.array,received:t.parsedType}),E;if(r.exactLength!==null){const a=t.data.length>r.exactLength.value,o=t.data.length<r.exactLength.value;(a||o)&&(v(t,{code:a?g.too_big:g.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(v(t,{code:g.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(v(t,{code:g.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>r.type._parseAsync(new he(t,a,t.path,o)))).then(a=>ee.mergeArray(i,a));const n=[...t.data].map((a,o)=>r.type._parseSync(new he(t,a,t.path,o)));return ee.mergeArray(i,n)}get element(){return this._def.type}min(e,t){return new ue({...this._def,minLength:{value:e,message:w.toString(t)}})}max(e,t){return new ue({...this._def,maxLength:{value:e,message:w.toString(t)}})}length(e,t){return new ue({...this._def,exactLength:{value:e,message:w.toString(t)}})}nonempty(e){return this.min(1,e)}}ue.create=(s,e)=>new ue({type:s,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...I(e)});function Ve(s){if(s instanceof W){const e={};for(const t in s.shape){const i=s.shape[t];e[t]=we.create(Ve(i))}return new W({...s._def,shape:()=>e})}else return s instanceof ue?new ue({...s._def,type:Ve(s.element)}):s instanceof we?we.create(Ve(s.unwrap())):s instanceof Le?Le.create(Ve(s.unwrap())):s instanceof Pe?Pe.create(s.items.map(e=>Ve(e))):s}class W extends P{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=M.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==b.object){const c=this._getOrReturnCtx(e);return v(c,{code:g.invalid_type,expected:b.object,received:c.parsedType}),E}const{status:i,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ae&&this._def.unknownKeys==="strip"))for(const c in r.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const d=n[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new he(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Ae){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")o.length>0&&(v(r,{code:g.unrecognized_keys,keys:o}),i.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of o){const h=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new he(r,h,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const h=await d.key,u=await d.value;c.push({key:h,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>ee.mergeObjectSync(i,c)):ee.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new W({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var n,a;const r=((a=(n=this._def).errorMap)==null?void 0:a.call(n,t,i).message)??i.defaultError;return t.code==="unrecognized_keys"?{message:w.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new W({...this._def,unknownKeys:"strip"})}passthrough(){return new W({...this._def,unknownKeys:"passthrough"})}extend(e){return new W({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new W({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:A.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new W({...this._def,catchall:e})}pick(e){const t={};for(const i of M.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new W({...this._def,shape:()=>t})}omit(e){const t={};for(const i of M.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new W({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){const t={};for(const i of M.objectKeys(this.shape)){const r=this.shape[i];e&&!e[i]?t[i]=r:t[i]=r.optional()}return new W({...this._def,shape:()=>t})}required(e){const t={};for(const i of M.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof we;)n=n._def.innerType;t[i]=n}return new W({...this._def,shape:()=>t})}keyof(){return gi(M.objectKeys(this.shape))}}W.create=(s,e)=>new W({shape:()=>s,unknownKeys:"strip",catchall:Ae.create(),typeName:A.ZodObject,...I(e)}),W.strictCreate=(s,e)=>new W({shape:()=>s,unknownKeys:"strict",catchall:Ae.create(),typeName:A.ZodObject,...I(e)}),W.lazycreate=(s,e)=>new W({shape:s,unknownKeys:"strip",catchall:Ae.create(),typeName:A.ZodObject,...I(e)});class xt extends P{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function r(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=n.map(o=>new ve(o.ctx.common.issues));return v(t,{code:g.invalid_union,unionErrors:a}),E}if(t.common.async)return Promise.all(i.map(async n=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let n;const a=[];for(const l of i){const c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!n&&(n={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;const o=a.map(l=>new ve(l));return v(t,{code:g.invalid_union,unionErrors:o}),E}}get options(){return this._def.options}}xt.create=(s,e)=>new xt({options:s,typeName:A.ZodUnion,...I(e)});const ke=s=>s instanceof hs?ke(s.schema):s instanceof Me?ke(s.innerType()):s instanceof Ct?[s.value]:s instanceof Ne?s.options:s instanceof us?M.objectValues(s.enum):s instanceof At?ke(s._def.innerType):s instanceof os?[void 0]:s instanceof ls?[null]:s instanceof we?[void 0,...ke(s.unwrap())]:s instanceof Le?[null,...ke(s.unwrap())]:s instanceof yi||s instanceof It?ke(s.unwrap()):s instanceof Tt?ke(s._def.innerType):[];class cs extends P{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.object)return v(t,{code:g.invalid_type,expected:b.object,received:t.parsedType}),E;const i=this.discriminator,r=t.data[i],n=this.optionsMap.get(r);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(v(t,{code:g.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const r=new Map;for(const n of t){const a=ke(n.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(r.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);r.set(o,n)}}return new cs({typeName:A.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...I(i)})}}function ds(s,e){const t=Ee(s),i=Ee(e);if(s===e)return{valid:!0,data:s};if(t===b.object&&i===b.object){const r=M.objectKeys(e),n=M.objectKeys(s).filter(o=>r.indexOf(o)!==-1),a={...s,...e};for(const o of n){const l=ds(s[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===b.array&&i===b.array){if(s.length!==e.length)return{valid:!1};const r=[];for(let n=0;n<s.length;n++){const a=s[n],o=e[n],l=ds(a,o);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===b.date&&i===b.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class _t extends P{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),r=(n,a)=>{if(ni(n)||ni(a))return E;const o=ds(n.value,a.value);return o.valid?((ai(n)||ai(a))&&t.dirty(),{status:t.value,value:o.data}):(v(i,{code:g.invalid_intersection_types}),E)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([n,a])=>r(n,a)):r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}_t.create=(s,e,t)=>new _t({left:s,right:e,typeName:A.ZodIntersection,...I(t)});class Pe extends P{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==b.array)return v(i,{code:g.invalid_type,expected:b.array,received:i.parsedType}),E;if(i.data.length<this._def.items.length)return v(i,{code:g.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&i.data.length>this._def.items.length&&(v(i,{code:g.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new he(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(n).then(a=>ee.mergeArray(t,a)):ee.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new Pe({...this._def,rest:e})}}Pe.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Pe({items:s,typeName:A.ZodTuple,rest:null,...I(e)})};class St extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==b.object)return v(i,{code:g.invalid_type,expected:b.object,received:i.parsedType}),E;const r=[],n=this._def.keyType,a=this._def.valueType;for(const o in i.data)r.push({key:n._parse(new he(i,o,i.path,o)),value:a._parse(new he(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?ee.mergeObjectAsync(t,r):ee.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof P?new St({keyType:e,valueType:t,typeName:A.ZodRecord,...I(i)}):new St({keyType:be.create(),valueType:e,typeName:A.ZodRecord,...I(t)})}}class pi extends P{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==b.map)return v(i,{code:g.invalid_type,expected:b.map,received:i.parsedType}),E;const r=this._def.keyType,n=this._def.valueType,a=[...i.data.entries()].map(([o,l],c)=>({key:r._parse(new he(i,o,i.path,[c,"key"])),value:n._parse(new he(i,l,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return E;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return E;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}}}}pi.create=(s,e,t)=>new pi({valueType:e,keyType:s,typeName:A.ZodMap,...I(t)});class tt extends P{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==b.set)return v(i,{code:g.invalid_type,expected:b.set,received:i.parsedType}),E;const r=this._def;r.minSize!==null&&i.data.size<r.minSize.value&&(v(i,{code:g.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&i.data.size>r.maxSize.value&&(v(i,{code:g.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const n=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return E;d.status==="dirty"&&t.dirty(),c.add(d.value)}return{status:t.value,value:c}}const o=[...i.data.values()].map((l,c)=>n._parse(new he(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new tt({...this._def,minSize:{value:e,message:w.toString(t)}})}max(e,t){return new tt({...this._def,maxSize:{value:e,message:w.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}tt.create=(s,e)=>new tt({valueType:s,minSize:null,maxSize:null,typeName:A.ZodSet,...I(e)});class hs extends P{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}hs.create=(s,e)=>new hs({getter:s,typeName:A.ZodLazy,...I(e)});class Ct extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return v(t,{received:t.data,code:g.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ct.create=(s,e)=>new Ct({value:s,typeName:A.ZodLiteral,...I(e)});function gi(s,e){return new Ne({values:s,typeName:A.ZodEnum,...I(e)})}class Ne extends P{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return v(t,{expected:M.joinValues(i),received:t.parsedType,code:g.invalid_type}),E}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return v(t,{received:t.data,code:g.invalid_enum_value,options:i}),E}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ne.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ne.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}Ne.create=gi;class us extends P{_parse(e){const t=M.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==b.string&&i.parsedType!==b.number){const r=M.objectValues(t);return v(i,{expected:M.joinValues(r),received:i.parsedType,code:g.invalid_type}),E}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=M.objectValues(t);return v(i,{received:i.data,code:g.invalid_enum_value,options:r}),E}return ne(e.data)}get enum(){return this._def.values}}us.create=(s,e)=>new us({values:s,typeName:A.ZodNativeEnum,...I(e)});class Et extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.promise&&t.common.async===!1)return v(t,{code:g.invalid_type,expected:b.promise,received:t.parsedType}),E;const i=t.parsedType===b.promise?t.data:Promise.resolve(t.data);return ne(i.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Et.create=(s,e)=>new Et({type:s,typeName:A.ZodPromise,...I(e)});class Me extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:a=>{v(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),r.type==="preprocess"){const a=r.transform(i.data,n);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return E;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?E:l.status==="dirty"||t.value==="dirty"?Qe(l.value):l});{if(t.value==="aborted")return E;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?E:o.status==="dirty"||t.value==="dirty"?Qe(o.value):o}}if(r.type==="refinement"){const a=o=>{const l=r.refinement(o,n);if(i.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?E:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?E:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(r.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Oe(a))return E;const o=r.transform(a.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Oe(a)?Promise.resolve(r.transform(a.value,n)).then(o=>({status:t.value,value:o})):E);M.assertNever(r)}}Me.create=(s,e,t)=>new Me({schema:s,typeName:A.ZodEffects,effect:e,...I(t)}),Me.createWithPreprocess=(s,e,t)=>new Me({schema:e,effect:{type:"preprocess",transform:s},typeName:A.ZodEffects,...I(t)});class we extends P{_parse(e){return this._getType(e)===b.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(s,e)=>new we({innerType:s,typeName:A.ZodOptional,...I(e)});class Le extends P{_parse(e){return this._getType(e)===b.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(s,e)=>new Le({innerType:s,typeName:A.ZodNullable,...I(e)});class At extends P{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===b.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}At.create=(s,e)=>new At({innerType:s,typeName:A.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...I(e)});class Tt extends P{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return kt(r)?r.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ve(i.common.issues)},input:i.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ve(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Tt.create=(s,e)=>new Tt({innerType:s,typeName:A.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...I(e)});class mi extends P{_parse(e){if(this._getType(e)!==b.nan){const i=this._getOrReturnCtx(e);return v(i,{code:g.invalid_type,expected:b.nan,received:i.parsedType}),E}return{status:"valid",value:e.data}}}mi.create=s=>new mi({typeName:A.ZodNaN,...I(s)});class yi extends P{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class fs extends P{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?E:n.status==="dirty"?(t.dirty(),Qe(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?E:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(e,t){return new fs({in:e,out:t,typeName:A.ZodPipeline})}}class It extends P{_parse(e){const t=this._def.innerType._parse(e),i=r=>(Oe(r)&&(r.value=Object.freeze(r.value)),r);return kt(t)?t.then(r=>i(r)):i(t)}unwrap(){return this._def.innerType}}It.create=(s,e)=>new It({innerType:s,typeName:A.ZodReadonly,...I(e)});var A;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(A||(A={}));const L=be.create,Te=je.create,ps=as.create;Ae.create;const st=ue.create,q=W.create,it=xt.create,vi=cs.create;_t.create,Pe.create;const Jr=St.create,$e=Ct.create,ze=Ne.create;Et.create,we.create,Le.create;const Pt=it([Te(),L()]),gs=q({x:Pt.optional().default(0),y:Pt.optional().default(0),width:Pt.optional(),height:Pt.optional(),fit:ze(["contain","cover","fill","none"]).optional(),horizontalAlign:ze(["left","center","right"]).optional(),verticalAlign:ze(["top","center","bottom"]).optional()}),Gr=q({id:L(),start:Te(),end:Te(),text:L().optional()}),Kr=vi("type",[q({type:$e("image"),src:L()}),q({type:$e("audio"),src:L(),channel:ze(["vo","sfx","music"]).optional().default("vo")}),q({type:$e("vtt"),src:L()}),q({type:$e("html"),src:L()})]),Qr=it([q({play:L()}),q({toggleClass:q({target:L(),className:L()})})]),en=q({id:L(),type:$e("text"),layout:gs.optional().default({}),html:L().optional(),htmlSrc:L().optional(),style:q({fontFamily:L().optional(),fontSize:L().optional(),color:L().optional(),textAlign:ze(["left","center","right"]).optional(),lineHeight:it([L(),Te()]).optional()}).optional()}),tn=q({id:L(),type:$e("image"),asset:L(),layout:gs.optional().default({}),className:L().optional()}),sn=q({id:L(),type:$e("hotspot"),layout:gs.optional().default({}),onTap:st(Qr).optional().default([]),ariaLabel:L().optional()}),rn=vi("type",[en,tn,sn]),nn=q({id:L(),background:q({asset:L().optional(),color:L().optional()}).optional(),readAloud:q({audio:L(),cues:it([L(),st(Gr)]).optional()}).optional(),blocks:st(rn).optional().default([])}),bi=q({id:L(),title:L().optional(),pageSize:q({width:Te().positive(),height:Te().positive()}),frontCover:ps().optional().default(!1),backCover:ps().optional().default(!1),hardback:ps().optional().default(!1),layout:q({mode:ze(["single","two-page","responsive","auto"]).default("auto"),singleBreakpoint:Te().positive().default(900)}).default({mode:"auto",singleBreakpoint:900}),fonts:st(q({family:L(),src:L(),weight:it([L(),Te()]).optional(),style:L().optional()})).optional().default([]),assets:Jr(Kr).optional().default({}),pages:st(nn).min(1)});function Ze(s){return bi.parse(s)}function ms(s){const e=s.replace(/^\uFEFF/,"").replace(/\r\n/g,`
2
- `).trim();if(!e.startsWith("WEBVTT"))throw new Error("Invalid WebVTT: missing WEBVTT header");const i=e.slice(e.indexOf(`
3
- `)+1).split(/\n\n+/),r=[];let n=0;for(const a of i){const o=a.split(`
4
- `).map(m=>m.trim()).filter(m=>m.length>0&&!m.startsWith("NOTE"));if(o.length===0)continue;const l=o.findIndex(m=>m.includes("-->"));if(l===-1)continue;const c=l>0?o[0]:void 0,d=o[l],h=o.slice(l+1),u=d.split("-->").map(m=>m.trim().split(/\s+/)[0]);if(u.length<2)continue;const k=ki(u[0]),x=ki(u[1]),p=h.join(" ").trim(),y=c||p||`cue-${n++}`;r.push({id:y,start:k,end:x,text:p||void 0})}return r}function ki(s){const e=s.trim().split(":");if(e.length===3){const[t,i,r]=e;return Number(t)*3600+Number(i)*60+Number(r)}if(e.length===2){const[t,i]=e;return Number(t)*60+Number(i)}return Number(s)}async function rt(s,e){typeof document>"u"||!("fonts"in document)||await Promise.all(s.fonts.map(async t=>{const i=Fe(e,t.src),n=await new FontFace(t.family,`url(${JSON.stringify(i)})`,{weight:t.weight!=null?String(t.weight):"normal",style:t.style??"normal"}).load();document.fonts.add(n)}))}const wi=[80,75];function ys(s){return s.length>=2&&s[0]===wi[0]&&s[1]===wi[1]}function vs(s){const e=s instanceof Uint8Array?s:new Uint8Array(s);if(!ys(e))throw new Error("Not a ZIP archive");const t=ur(e),i=new Map;for(const[r,n]of Object.entries(t))!n||r.endsWith("/")||i.set(fe(r),n);return i}function fe(s){return s.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function nt(s,e){const t=Nt(s,e);if(!t)throw new Error(`Missing zip entry: ${e}`);return Xs(t)}function Nt(s,e){const t=fe(e);if(s.has(t))return s.get(t);const i=t.toLowerCase();for(const[r,n]of s)if(r.toLowerCase()===i)return n}function an(s){return[...s.keys()]}function on(s){var t;switch(((t=s.split(".").pop())==null?void 0:t.toLowerCase())??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"ogg":return"audio/ogg";case"m4a":return"audio/mp4";case"webm":return"audio/webm";case"vtt":return"text/vtt";case"html":case"xhtml":case"htm":return"application/xhtml+xml";case"css":return"text/css";case"json":return"application/json";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";default:return"application/octet-stream"}}function xi(s,e){const t=new Uint8Array(s.byteLength);t.set(s);const i=new Blob([t.buffer],{type:on(e)});return URL.createObjectURL(i)}async function ln(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch ${s}: ${e.status}`);return e.arrayBuffer()}function cn(s){return bs(vs(s))}function bs(s){const e=nt(s,"META-INF/container.xml"),t=pe(e,/full-path\s*=\s*"([^"]+)"/i);if(!t)throw new Error("Invalid EPUB: missing rootfile in container.xml");const i=fe(t),r=i.includes("/")?i.replace(/\/[^/]+$/,"/"):"",n=nt(s,i),a=Ci(n,"dc:title")||Ci(n,"title")||"EPUB Story",o=fn(n)??{width:768,height:1024},l=hn(n,r),c=un(n),d=[],h=new Map,u=y=>{const m=fe(y);if(h.has(m))return h.get(m);const S=Nt(s,m);if(!S)throw new Error(`EPUB missing file: ${m}`);const C=xi(S,m);return d.push(C),h.set(m,C),C},k={},x=[];if(c.forEach((y,m)=>{const S=l.get(y);if(!S||!/html|xml/i.test(S.mediaType)&&!S.href.match(/\.x?html?$/i))return;const C=S.href,$=nt(s,C),O=C.includes("/")?C.replace(/\/[^/]+$/,"/"):"",z=`page-${m+1}`,j=gn($),{html:N,imageHrefs:T}=mn(j,O,R=>{const V=fe(R.includes(":")?R:`${O}${R}`);try{return u(V)}catch{return R}}),Y=[{id:`${z}-text`,type:"text",layout:{x:"5%",y:"5%",width:"90%",height:"90%"},html:N}],Z=T[0];let X;if(Z){const R=`img-${m}-0`;k[R]={type:"image",src:u(Z)},X={asset:R,color:"#ffffff"}}else X={color:"#ffffff"};let ae;if(S.mediaOverlay){const R=l.get(S.mediaOverlay);if(R){const V=pn(nt(s,R.href),R.href);if(V.audioHref){const H=`vo-${m}`,B=fe(V.audioHref.includes("/")||V.audioHref.startsWith(".")?Si(R.href,V.audioHref):`${r}${V.audioHref}`);k[H]={type:"audio",src:u(B),channel:"vo"};const G=V.cues;G.length?ae={audio:H,cues:G}:ae={audio:H}}}}x.push({id:z,background:X,readAloud:ae,blocks:Y})}),x.length===0)throw new Error("Invalid EPUB: no spine HTML documents found");return{story:Ze({id:`epub-${yn(a)}`,title:a,pageSize:o,layout:{mode:"auto",singleBreakpoint:900},fonts:[],assets:k,pages:x}),blobUrls:d}}function dn(s){return!!Nt(s,"META-INF/container.xml")}function hn(s,e){const t=new Map,i=/<item\b[^>]*>/gi;let r;for(;r=i.exec(s);){const n=r[0],a=pe(n,/\bid\s*=\s*"([^"]+)"/i),o=pe(n,/\bhref\s*=\s*"([^"]+)"/i),l=pe(n,/\bmedia-type\s*=\s*"([^"]+)"/i)??"",c=pe(n,/\bmedia-overlay\s*=\s*"([^"]+)"/i)??void 0,d=pe(n,/\bproperties\s*=\s*"([^"]+)"/i)??void 0;!a||!o||t.set(a,{id:a,href:fe(`${e}${o}`),mediaType:l,mediaOverlay:c,properties:d})}return t}function un(s){const e=s.match(/<spine\b[^>]*>([\s\S]*?)<\/spine>/i);if(!e)return[];const t=[],i=/<itemref\b[^>]*\bidref\s*=\s*"([^"]+)"[^>]*>/gi;let r;for(;r=i.exec(e[1]);)t.push(r[1]);return t}function fn(s){const e=s.match(/<meta\b[^>]*name\s*=\s*"viewport"[^>]*content\s*=\s*"([^"]+)"[^>]*>/i)||s.match(/<meta\b[^>]*content\s*=\s*"([^"]+)"[^>]*name\s*=\s*"viewport"[^>]*>/i);if(!e)return null;const t=e[1],i=t.match(/width\s*=\s*(\d+)/i),r=t.match(/height\s*=\s*(\d+)/i);return!i||!r?null:{width:Number(i[1]),height:Number(r[1])}}function pn(s,e){const t=[];let i;const r=pe(s,/<audio\b[^>]*\bsrc\s*=\s*"([^"]+)"/i);r&&(i=Si(e,r));const n=/<par\b[^>]*>([\s\S]*?)<\/par>/gi;let a,o=0;for(;a=n.exec(s);){const l=a[1],c=pe(l,/<text\b[^>]*\bsrc\s*=\s*"([^"]+)"/i),d=pe(l,/\bclipBegin\s*=\s*"([^"]+)"/i),h=pe(l,/\bclipEnd\s*=\s*"([^"]+)"/i),u=c!=null&&c.includes("#")?c.split("#")[1]:`cue-${o}`;d==null||h==null||(t.push({id:u||`cue-${o}`,start:_i(d),end:_i(h)}),o+=1)}return{audioHref:i,cues:t}}function _i(s){const e=s.replace(/^npt=/i,"").trim();if(/^\d+(\.\d+)?$/.test(e))return Number(e);const t=e.split(":").map(Number);return t.length===3?t[0]*3600+t[1]*60+t[2]:t.length===2?t[0]*60+t[1]:0}function gn(s){const e=s.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);return e?e[1].trim():s}function mn(s,e,t){const i=[];return{html:s.replace(/\b(src|href)\s*=\s*["']([^"']+)["']/gi,(n,a,o)=>{if(/^(?:[a-z]+:|#|data:)/i.test(o))return n;const l=fe(`${e}${o}`);/\.(png|jpe?g|gif|webp|svg)$/i.test(o)&&i.push(l);const c=t(o);return`${a}="${c}"`}),imageHrefs:i}}function Si(s,e){if(/^(?:[a-z]+:)/i.test(e))return e;const i=((s.includes("/")?s.replace(/\/[^/]+$/,"/"):"")+e).split("/"),r=[];for(const n of i)!n||n==="."||(n===".."?r.pop():r.push(n));return r.join("/")}function pe(s,e){const t=s.match(e);return t?t[1]:null}function Ci(s,e){const t=new RegExp(`<${e.replace(":",":")}[^>]*>([^<]*)</${e.replace(":",":")}>`,"i"),i=s.match(t);return i?i[1].trim():null}function yn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"book"}function ks(s){const e=an(s),t=e.find(r=>r==="story.json"||r.toLowerCase()==="story.json");if(t)return t;const i=e.filter(r=>r.toLowerCase().endsWith("/story.json")||r.toLowerCase()==="story.json").sort((r,n)=>r.length-n.length);if(i[0])return i[0];throw new Error("Invalid .fanci package: missing story.json")}function ws(s){const e=ks(s),t=e.includes("/")?e.replace(/\/[^/]+$/,"/"):"",i=Ze(JSON.parse(nt(s,e))),r=new Map,n=[];for(const[a,o]of s){if(a===e)continue;const l=xi(o,a);n.push(l),r.set(a,l),t&&a.startsWith(t)&&r.set(a.slice(t.length),l)}return kn(i,a=>bn(r,t,a)),{story:i,pathUrls:r,blobUrls:n,storyDir:t}}function vn(s){return ws(vs(s))}function bn(s,e,t){const i=fe(t);if(s.has(i))return s.get(i);const r=fe(`${e}${i}`);if(s.has(r))return s.get(r);const n=i.toLowerCase();for(const[a,o]of s)if(a.toLowerCase()===n||a.toLowerCase().endsWith(`/${n}`))return o}function kn(s,e){for(const t of s.fonts){const i=e(t.src);i&&(t.src=i)}for(const t of Object.values(s.assets)){const i=e(t.src);i&&(t.src=i)}for(const t of s.pages)for(const i of t.blocks)if(i.type==="text"&&i.htmlSrc){const r=e(i.htmlSrc);r&&(i.htmlSrc=r)}}function wn(s){if(Nt(s,"META-INF/container.xml"))return!1;try{return ks(s),!0}catch{return!1}}const Mt=".fanci";function xs(s){const e=s.split("?")[0].split("#")[0],t=e.split("/").pop()??e,i=t.lastIndexOf(".");return i>=0?t.slice(i).toLowerCase():""}function xn(s,e){if(typeof s=="object"&&s!==null&&!(s instanceof Blob)&&!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)&&!ArrayBuffer.isView(s)&&("story"in s||"id"in s&&"pages"in s))return"object";const t=e??(typeof s=="string"?s:s instanceof File?s.name:""),i=xs(t);return i===Mt||i===".fanci.zip"?"fanci":i===".epub"?"epub":"json"}async function _n(s){return s instanceof ArrayBuffer?s:s instanceof Uint8Array?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s.arrayBuffer()}async function _s(s,e){const t=typeof e=="string"?{baseUrl:e}:e??{},i=t.onProgress??(()=>{});if(Cn(s)){i({stage:"parse",progress:.1,detail:"story object"});const r=Ze(s),n=t.baseUrl??(typeof location<"u"?location.href:"");i({stage:"assets",progress:.2,detail:"fonts"}),await rt(r,n);const a=await at(r,n,i,.25,1);return i({stage:"complete",progress:1}),{story:r,baseUrl:n,assets:a,blobUrls:[],kind:"object"}}if(typeof s=="object"&&s!==null&&"story"in s&&!Ei(s)){const r=s;return _s(r.story,{baseUrl:t.baseUrl??r.baseUrl,name:t.name,onProgress:t.onProgress})}if(typeof s=="string")return Sn(s,t,i);if(Ei(s)){i({stage:"fetch",progress:.05,detail:"bytes"});const r=await _n(s),n=t.name??(s instanceof File?s.name:void 0)??"";return Ss(r,n,t.baseUrl,i)}throw new Error("Unsupported story source")}async function Sn(s,e,t){const i=xs(s),r=xn(s,e.name??s);if(t({stage:"fetch",progress:.02,detail:s}),i===Mt||i===".epub"||r==="fanci"||r==="epub"){const u=await ln(s);return t({stage:"fetch",progress:.15,detail:"package downloaded"}),Ss(u,e.name??s,e.baseUrl,t)}const n=await fetch(s);if(!n.ok)throw new Error(`Failed to load story: ${n.status} ${n.statusText}`);const a=await n.arrayBuffer(),o=new Uint8Array(a);if(ys(o))return t({stage:"fetch",progress:.15,detail:"zip downloaded"}),Ss(a,e.name??s,e.baseUrl,t);t({stage:"parse",progress:.2,detail:"json"});const l=new TextDecoder().decode(o),c=Ze(JSON.parse(l)),d=e.baseUrl??fr(new URL(s,location.href).href);await rt(c,d);const h=await at(c,d,t,.3,1);return t({stage:"complete",progress:1}),{story:c,baseUrl:d,assets:h,blobUrls:[],kind:"json"}}async function Ss(s,e,t,i){const r=new Uint8Array(s),n=xs(e);if(ys(r)){i({stage:"unpack",progress:.2,detail:"unzip"});const c=vs(r);if(i({stage:"unpack",progress:.35,detail:`${c.size} entries`}),n===".epub"||dn(c)){i({stage:"parse",progress:.4,detail:"epub"});const{story:d,blobUrls:h}=bs(c);await rt(d,t??"");const u=await at(d,t??"",i,.5,1);return i({stage:"complete",progress:1}),{story:d,baseUrl:t??"",assets:u,blobUrls:h,kind:"epub"}}if(n===Mt||wn(c)){i({stage:"parse",progress:.4,detail:"fanci"});const{story:d,blobUrls:h}=ws(c);await rt(d,t??"");const u=await at(d,t??"",i,.5,1);return i({stage:"complete",progress:1}),{story:d,baseUrl:t??"",assets:u,blobUrls:h,kind:"fanci"}}throw new Error("ZIP archive is neither a .fanci package (story.json) nor an EPUB (META-INF/container.xml)")}i({stage:"parse",progress:.25,detail:"json bytes"});const a=Ze(JSON.parse(new TextDecoder().decode(r))),o=t??(typeof location<"u"?location.href:"");await rt(a,o);const l=await at(a,o,i,.35,1);return i({stage:"complete",progress:1}),{story:a,baseUrl:o,assets:l,blobUrls:[],kind:"json"}}function Cn(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Blob)&&!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)&&"id"in s&&"pages"in s&&"pageSize"in s}function Ei(s){return s instanceof ArrayBuffer||s instanceof Uint8Array||s instanceof Blob||typeof File<"u"&&s instanceof File}async function at(s,e,t,i,r){var x;const n=new Map,a=new Map,o=new Map,l=new Map,c=Object.entries(s.assets),d=[];for(const p of s.pages)for(const y of p.blocks)if(y.type==="text"&&y.htmlSrc&&!y.html&&d.push(async()=>{const m=Fe(e,y.htmlSrc);l.set(`htmlSrc:${y.id}`,await Lt(m))}),(x=p.readAloud)!=null&&x.cues&&typeof p.readAloud.cues=="string"){const m=p.readAloud.cues;s.assets[m]||d.push(async()=>{const S=Fe(e,m);try{o.set(m,ms(await Lt(S)))}catch{}})}const h=c.length+d.length||1;let u=0;const k=p=>{u+=1;const y=u/h,m=i+(r-i)*Math.min(1,y);t({stage:"assets",progress:m,count:u,total:h,detail:p})};return await Promise.all(c.map(async([p,y])=>{const m=Fe(e,y.src);y.type==="image"?n.set(p,await En(m)):y.type==="audio"?a.set(p,{url:m,channel:y.channel??"vo"}):y.type==="vtt"?o.set(p,ms(await Lt(m))):y.type==="html"&&l.set(p,await Lt(m)),k(p)})),await Promise.all(d.map(async p=>{await p(),k("fragment")})),c.length===0&&d.length===0&&t({stage:"assets",progress:r,count:0,total:0,detail:"none"}),{images:n,audioUrls:a,cues:o,html:l}}function En(s){return new Promise((e,t)=>{const i=new Image;i.decoding="async",i.onload=()=>e(i),i.onerror=()=>t(new Error(`Failed to load image: ${s}`)),i.src=s})}async function Lt(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to load ${s}: ${e.status}`);return e.text()}function Ai(s){for(const e of s.blobUrls)try{URL.revokeObjectURL(e)}catch{}s.blobUrls.length=0}function Ti(s,e,t,i){return s==="responsive"?e>=t?"two-page":"single":s==="auto"?e>=i?"two-page":"single":s}function Re(s,e){return{kind:"page",pageIndex:e,pageId:s[e].id}}const Ie={kind:"blank"};function Ii(s){return{index:-1,left:Ie,right:Re(s,0)}}function Pi(s){const e=s.length-1;return{index:-2,left:Ie,right:Re(s,e)}}function Ni(s,e={}){if(s.length===0)return[];const t=!!e.frontCover,i=!!e.backCover,r=[];let n=t?1:0;const a=i?Math.max(n,s.length-1):s.length;for(!t&&n<a&&(r.push({index:0,left:Ie,right:Re(s,0)}),n=1);n<a;){if(n+1<a){r.push({index:r.length,left:Re(s,n),right:Re(s,n+1)}),n+=2;continue}r.push({index:r.length,left:Re(s,n),right:Ie}),n+=1}return r}function Mi(s,e={}){if(s.length===0)return[];const t=!!e.frontCover,i=!!e.backCover,r=s.length-1;return s.map((n,a)=>{const o=Re(s,a);return t&&a===0?{index:a,left:o,right:Ie}:i&&a===r?{index:a,left:Ie,right:o}:a%2===0?{index:a,left:Ie,right:o}:{index:a,left:o,right:Ie}})}function $t(s,e="two-page",t={}){return e==="single"?Mi(s,t):Ni(s,t)}function Li(s){const e=[];return s.left.kind==="page"&&e.push(s.left.pageId),s.right.kind==="page"&&e.push(s.right.pageId),e}function $i(s){return s?s.left.kind==="page"?s.left.pageId:s.right.kind==="page"?s.right.pageId:null:null}function Ue(s,e){const t=s.findIndex(i=>i.left.kind==="page"&&i.left.pageId===e||i.right.kind==="page"&&i.right.pageId===e);return t<0?0:t}class An{constructor(e,t){f(this,"story");f(this,"spreadView");f(this,"spreads");f(this,"spreadIndex",0);f(this,"preferredMode");f(this,"resolvedMode","two-page");f(this,"breakpoint");f(this,"listeners",new Map);f(this,"busy",!1);f(this,"hasResolvedLayout",!1);f(this,"bookState");f(this,"covers");f(this,"frontCoverSpread",null);f(this,"backCoverSpread",null);this.story=e,this.spreadView=t,this.preferredMode=e.layout.mode,this.breakpoint=e.layout.singleBreakpoint,this.covers={frontCover:!!e.frontCover,backCover:!!e.backCover},this.bookState=this.covers.frontCover?"closed-front":"open",this.rebuildCoverSpreads(),this.spreads=$t(e.pages,"two-page",this.covers)}get layoutMode(){return this.resolvedMode}get currentBookState(){return this.bookState}get currentSpread(){return this.bookState==="closed-front"&&this.frontCoverSpread?this.frontCoverSpread:this.bookState==="closed-back"&&this.backCoverSpread?this.backCoverSpread:this.spreads[this.spreadIndex]??this.spreads[0]}get currentPageIds(){var e,t;if(this.bookState==="closed-front"){const i=(e=this.story.pages[0])==null?void 0:e.id;return i?[i]:[]}if(this.bookState==="closed-back"){const i=(t=this.story.pages[this.story.pages.length-1])==null?void 0:t.id;return i?[i]:[]}return Li(this.currentSpread)}get canPrev(){return this.bookState==="closed-front"?!1:this.bookState==="closed-back"||this.spreadIndex>0?!0:!!this.covers.frontCover&&this.resolvedMode==="two-page"}get canNext(){return this.bookState==="closed-back"?!1:this.bookState==="closed-front"?this.spreads.length>0||!!this.covers.backCover:this.spreadIndex<this.spreads.length-1?!0:!!this.covers.backCover&&this.resolvedMode==="two-page"}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var i;return(i=this.listeners.get(e))==null?void 0:i.delete(t)}}setLayoutMode(e,t,i){this.preferredMode=e,this.updateLayout(t,i,!1)}updateLayout(e,t,i=!0){var l,c,d,h,u;const r=Ti(this.preferredMode,e,t,this.breakpoint);if(!(!this.hasResolvedLayout||r!==this.resolvedMode)){this.spreadView.setLayoutMode(r);return}const a=this.currentPageIds[0]??$i(this.spreads[this.spreadIndex])??((l=this.story.pages[0])==null?void 0:l.id)??null;this.resolvedMode=r,this.hasResolvedLayout=!0,this.rebuildCoverSpreads(),this.spreads=$t(this.story.pages,r,this.covers);const o=this.covers.frontCover&&a===((c=this.story.pages[0])==null?void 0:c.id)||this.covers.backCover&&a===((d=this.story.pages[this.story.pages.length-1])==null?void 0:d.id);r==="single"?(this.bookState="open",this.spreadIndex=a?Ue(this.spreads,a):0):this.covers.frontCover&&(this.bookState==="closed-front"||o&&a===((h=this.story.pages[0])==null?void 0:h.id))?(this.bookState="closed-front",this.spreadIndex=0):this.covers.backCover&&(this.bookState==="closed-back"||o&&a===((u=this.story.pages[this.story.pages.length-1])==null?void 0:u.id))?(this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1)):(this.bookState="open",this.spreadIndex=a?Ue(this.spreads,a):0),this.spreadIndex>=this.spreads.length&&(this.spreadIndex=Math.max(0,this.spreads.length-1)),this.busy=!1,this.spreadView.setLayoutMode(r),this.spreadView.setBookState(this.bookState),this.spreadView.showSpread(this.currentSpread,"none"),i&&(this.emit("layoutchange",{layoutMode:r}),this.emitPageChange())}async showInitial(){this.covers.frontCover&&this.resolvedMode==="two-page"?(this.bookState="closed-front",this.spreadIndex=0):this.bookState="open",await this.spreadView.showSpread(this.currentSpread,"none"),this.spreadView.setBookState(this.bookState),this.emitPageChange()}async next(){if(!(this.busy||!this.canNext)){if(this.busy=!0,this.bookState==="closed-front"){this.spreads.length===0&&this.covers.backCover&&this.backCoverSpread?(this.bookState="closed-back",await this.spreadView.showSpread(this.backCoverSpread,"next"),this.spreadView.setBookState("closed-back")):(this.bookState="open",this.spreadIndex=0,await this.spreadView.showSpread(this.currentSpread,"next"),this.spreadView.setBookState("open")),this.emitPageChange(),this.busy=!1;return}if(this.bookState==="open"&&this.covers.backCover&&this.backCoverSpread&&this.resolvedMode==="two-page"&&this.spreadIndex>=this.spreads.length-1){this.bookState="closed-back",await this.spreadView.showSpread(this.backCoverSpread,"next"),this.spreadView.setBookState("closed-back"),this.emitPageChange(),this.busy=!1;return}this.spreadIndex+=1,await this.spreadView.showSpread(this.currentSpread,"next"),this.emitPageChange(),this.busy=!1}}async prev(){if(!(this.busy||!this.canPrev)){if(this.busy=!0,this.bookState==="closed-back"){this.spreads.length===0&&this.covers.frontCover&&this.frontCoverSpread?(this.bookState="closed-front",await this.spreadView.showSpread(this.frontCoverSpread,"prev"),this.spreadView.setBookState("closed-front")):(this.bookState="open",this.spreadIndex=Math.max(0,this.spreads.length-1),await this.spreadView.showSpread(this.currentSpread,"prev"),this.spreadView.setBookState("open")),this.emitPageChange(),this.busy=!1;return}if(this.bookState==="open"&&this.covers.frontCover&&this.frontCoverSpread&&this.resolvedMode==="two-page"&&this.spreadIndex<=0){this.bookState="closed-front",await this.spreadView.showSpread(this.frontCoverSpread,"prev"),this.spreadView.setBookState("closed-front"),this.emitPageChange(),this.busy=!1;return}this.spreadIndex-=1,await this.spreadView.showSpread(this.currentSpread,"prev"),this.emitPageChange(),this.busy=!1}}rebuildFromStory(e){var i,r,n;this.covers={frontCover:!!this.story.frontCover,backCover:!!this.story.backCover},this.rebuildCoverSpreads(),this.spreads=$t(this.story.pages,this.resolvedMode,this.covers);const t=e??this.currentPageIds[0]??((i=this.story.pages[0])==null?void 0:i.id)??null;this.resolvedMode==="single"?(this.bookState="open",this.spreadIndex=t?Ue(this.spreads,t):0):this.covers.frontCover&&t===((r=this.story.pages[0])==null?void 0:r.id)&&this.bookState==="closed-front"?(this.bookState="closed-front",this.spreadIndex=0):this.covers.backCover&&t===((n=this.story.pages[this.story.pages.length-1])==null?void 0:n.id)&&this.bookState==="closed-back"?(this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1)):(this.bookState="open",this.spreadIndex=t?Ue(this.spreads,t):0,this.spreadIndex<0&&(this.spreadIndex=0)),this.spreads.length===0?(this.spreadIndex=0,this.covers.frontCover?this.bookState="closed-front":this.covers.backCover&&(this.bookState="closed-back")):this.spreadIndex>=this.spreads.length&&(this.spreadIndex=Math.max(0,this.spreads.length-1)),this.busy=!1,this.spreadView.setLayoutMode(this.resolvedMode),this.spreadView.setBookState(this.bookState),this.spreadView.showSpread(this.currentSpread,"none"),this.emitPageChange()}async goTo(e){var a,o;const t=this.covers.frontCover&&((a=this.story.pages[0])==null?void 0:a.id)===e,i=this.covers.backCover&&((o=this.story.pages[this.story.pages.length-1])==null?void 0:o.id)===e;if(this.busy=!0,t&&this.resolvedMode==="two-page"&&this.frontCoverSpread){this.bookState="closed-front",this.spreadIndex=0,await this.spreadView.showSpread(this.frontCoverSpread,"none"),this.spreadView.setBookState("closed-front"),this.emitPageChange(),this.busy=!1;return}if(i&&this.resolvedMode==="two-page"&&this.backCoverSpread){this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1),await this.spreadView.showSpread(this.backCoverSpread,"none"),this.spreadView.setBookState("closed-back"),this.emitPageChange(),this.busy=!1;return}const r=Ue(this.spreads,e);if(r===this.spreadIndex&&this.bookState==="open"){this.busy=!1;return}const n=r>this.spreadIndex?"next":"prev";this.bookState="open",this.spreadIndex=r,this.spreadView.setBookState("open"),await this.spreadView.showSpread(this.currentSpread,n),this.emitPageChange(),this.busy=!1}rebuildCoverSpreads(){this.frontCoverSpread=this.covers.frontCover?Ii(this.story.pages):null,this.backCoverSpread=this.covers.backCover?Pi(this.story.pages):null}emitPageChange(){this.emit("pagechange",{pageIds:this.currentPageIds,index:this.spreadIndex,layoutMode:this.resolvedMode,bookState:this.bookState})}emit(e,t){const i=this.listeners.get(e);if(i)for(const r of i)r(t)}}class ot{cancel(e){}}f(ot,"id","base");const lt=new Map;function Ri(s,e){lt.set(s,e)}function Tn(s){return lt.get(s)}function Fi(){return[...lt.keys()]}function In(s){return typeof s=="function"&&s.prototype instanceof ot}function Cs(s){if(s==null||s===""){const e=lt.get("default");if(!e)throw new Error('FlipStyle "default" is not registered');return new e}if(typeof s=="string"){const e=lt.get(s);if(!e){const t=Fi().join(", ")||"(none)";throw new Error(`Unknown flipStyle "${s}". Registered: ${t}`)}return new e}if(s instanceof ot)return s;if(In(s))return new s;throw new Error("flipStyle must be a string id, FlipStyle instance, or FlipStyle subclass")}const Bi=400;function Es(s){return s==null||!Number.isFinite(s)||s<=0?Bi:s}class Rt extends ot{play(e){const{bookEl:t,direction:i,durationMs:r}=e,n=i==="next"?"fc-turn-next":"fc-turn-prev";return t.style.setProperty("--fc-flip-duration",`${r}ms`),t.classList.remove("fc-turn-next","fc-turn-prev"),t.offsetWidth,t.classList.add(n),new Promise(a=>{const o=()=>{t.removeEventListener("animationend",l),t.classList.remove("fc-turn-next","fc-turn-prev"),a()},l=c=>{c.target!==e.rightLeaf&&c.target!==e.leftLeaf||o()};t.addEventListener("animationend",l),window.setTimeout(o,r+50)})}cancel(e){e.bookEl.classList.remove("fc-turn-next","fc-turn-prev")}}f(Rt,"id","default"),Ri(Rt.id,Rt);const As=.035;function Oi(s){return{x:Math.max(1,Math.round(s.width*As)),y:Math.max(1,Math.round(s.height*As))}}function Ts(s){return!!(s.hardback&&(s.frontCover||s.backCover))}function Pn(s){const e=s??{},t={left:De(e.x??0),top:De(e.y??0)};return e.width!=null&&(t.width=De(e.width)),e.height!=null&&(t.height=De(e.height)),t}function Is(s,e){const t=Pn(e);s.style.left=t.left,s.style.top=t.top,t.width&&(s.style.width=t.width),t.height&&(s.style.height=t.height),(e==null?void 0:e.horizontalAlign)==="right"?(s.style.left="auto",s.style.right=De(e.x??0)):(e==null?void 0:e.horizontalAlign)==="center"&&(s.style.left="50%",s.style.transform=`${s.style.transform||""} translateX(-50%)`.trim()),(e==null?void 0:e.verticalAlign)==="bottom"?(s.style.top="auto",s.style.bottom=De(e.y??0)):(e==null?void 0:e.verticalAlign)==="center"&&(s.style.top="50%",s.style.transform=`${s.style.transform||""} translateY(-50%)`.trim())}function De(s){return typeof s=="number"?`${s}px`:/^-?\d+(\.\d+)?$/.test(s)?`${s}px`:s}function Nn(s,e){const t=document.createElement("button");return t.type="button",t.className="fc-block fc-block-hotspot",t.dataset.blockId=s.id,t.setAttribute("aria-label",s.ariaLabel??s.id),Is(t,s.layout),t.addEventListener("click",i=>{i.stopPropagation(),e(s.onTap??[])}),t}function Mn(s,e){var n;const t=document.createElement("div");t.className=`fc-block fc-block-image${s.className?` ${s.className}`:""}`,t.dataset.blockId=s.id,Is(t,s.layout);const i=document.createElement("img");i.alt="",i.draggable=!1,e&&(i.src=e.src);const r=((n=s.layout)==null?void 0:n.fit)??"contain";return i.style.objectFit=r,t.appendChild(i),t}function Ln(s,e){const t=document.createElement("div");return t.className="fc-block fc-block-text",t.dataset.blockId=s.id,Is(t,s.layout),t.innerHTML=e,t.querySelectorAll("[id]").forEach(i=>{i.classList.add("fc-cue")}),s.style&&(s.style.fontFamily&&(t.style.fontFamily=s.style.fontFamily),s.style.fontSize&&(t.style.fontSize=s.style.fontSize),s.style.color&&(t.style.color=s.style.color),s.style.textAlign&&(t.style.textAlign=s.style.textAlign),s.style.lineHeight!=null&&(t.style.lineHeight=String(s.style.lineHeight))),t}class Ps{constructor(e,t,i){f(this,"element");f(this,"page");f(this,"blank");var r,n;if(this.page=e,this.blank=!e,this.element=document.createElement("article"),this.element.className=`fc-page${this.blank?" fc-page-blank":""}`,this.element.setAttribute("role",this.blank?"presentation":"document"),!e){this.element.dataset.blank="true";return}if(this.element.dataset.pageId=e.id,(r=e.background)!=null&&r.color&&(this.element.style.backgroundColor=e.background.color),(n=e.background)!=null&&n.asset){const a=t.images.get(e.background.asset);a&&(this.element.style.backgroundImage=`url(${JSON.stringify(a.src)})`,this.element.style.backgroundSize="cover",this.element.style.backgroundPosition="center")}for(const a of e.blocks)if(a.type==="text"){const o=a.html??t.html.get(`htmlSrc:${a.id}`)??(a.htmlSrc?t.html.get(a.htmlSrc):void 0)??"";this.element.appendChild(Ln(a,o))}else a.type==="image"?this.element.appendChild(Mn(a,t.images.get(a.asset))):a.type==="hotspot"&&this.element.appendChild(Nn(a,o=>i.onTapActions(o,this.element)))}destroy(){this.element.remove()}}class $n{constructor(e,t,i,r={}){f(this,"element");f(this,"bookEl");f(this,"hardbackEl");f(this,"hardbackLeft");f(this,"hardbackRight");f(this,"hardbackLeftPage",null);f(this,"hardbackRightPage",null);f(this,"leftSlot");f(this,"rightSlot");f(this,"leftPage",null);f(this,"rightPage",null);f(this,"story");f(this,"assets");f(this,"onTapActions");f(this,"turning",!1);f(this,"bookState","open");f(this,"layoutMode","two-page");f(this,"lastSize",{width:0,height:0});f(this,"currentSpread",null);f(this,"flipStyle");f(this,"flipSpeedMs");this.story=e,this.assets=t,this.onTapActions=i,this.flipStyle=Cs(r.flipStyle),this.flipSpeedMs=Es(r.flipSpeed),this.element=document.createElement("div"),this.element.className="fc-spread-viewport",this.hardbackEl=document.createElement("div"),this.hardbackEl.className="fc-hardback",this.hardbackEl.setAttribute("aria-hidden","true"),this.hardbackLeft=document.createElement("div"),this.hardbackLeft.className="fc-hardback-board fc-hardback-board-left",this.hardbackRight=document.createElement("div"),this.hardbackRight.className="fc-hardback-board fc-hardback-board-right",this.hardbackEl.append(this.hardbackLeft,this.hardbackRight),this.bookEl=document.createElement("div"),this.bookEl.className="fc-spread",this.leftSlot=document.createElement("div"),this.leftSlot.className="fc-leaf fc-leaf-left",this.rightSlot=document.createElement("div"),this.rightSlot.className="fc-leaf fc-leaf-right",this.bookEl.append(this.leftSlot,this.rightSlot),this.element.append(this.hardbackEl,this.bookEl)}get currentBookState(){return this.bookState}setFlipStyle(e){this.flipStyle=Cs(e)}setFlipSpeed(e){this.flipSpeedMs=Es(e)}setLayoutMode(e){this.layoutMode=e,this.element.dataset.layoutMode=e,this.element.classList.toggle("fc-spread-viewport-single",e==="single"),this.element.classList.toggle("fc-spread-viewport-two",e==="two-page")}setBookState(e){this.bookState=e,this.element.dataset.bookState=e,this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}showSpread(e,t="none"){var i,r;return t==="none"||this.turning?((r=(i=this.flipStyle).cancel)==null||r.call(i,{bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot}),this.turning=!1,this.mountSpread(e),Promise.resolve()):(this.turning=!0,this.flipStyle.play({bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot,direction:t,durationMs:this.flipSpeedMs}).then(()=>{this.mountSpread(e),this.turning=!1}).catch(()=>{this.mountSpread(e),this.turning=!1}))}getPageElement(e){var t,i,r,n;return((i=(t=this.leftPage)==null?void 0:t.page)==null?void 0:i.id)===e?this.leftPage.element:((n=(r=this.rightPage)==null?void 0:r.page)==null?void 0:n.id)===e?this.rightPage.element:null}getLeafSlots(){return{left:this.leftSlot,right:this.rightSlot}}getEditableLeaves(e,t){const i=[],r=(n,a,o)=>{a.kind==="page"&&i.push({side:n,pageIndex:a.pageIndex,slot:o})};return this.bookState==="closed-front"||this.bookState==="closed-back"?(r("right",t.right,this.rightSlot),i):e==="two-page"?(r("left",t.left,this.leftSlot),r("right",t.right,this.rightSlot),i):(t.left.kind==="blank"&&t.right.kind==="page"?r("right",t.right,this.rightSlot):t.right.kind==="blank"&&t.left.kind==="page"?r("left",t.left,this.leftSlot):t.left.kind==="page"?r("left",t.left,this.leftSlot):t.right.kind==="page"&&r("right",t.right,this.rightSlot),i)}setPageViewsHidden(e){this.leftPage&&(this.leftPage.element.hidden=e),this.rightPage&&(this.rightPage.element.hidden=e)}remountCurrent(){this.currentSpread&&this.mountSpread(this.currentSpread)}setStory(e){this.story=e,this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}getVisiblePageElements(e,t){if(this.bookState==="closed-front"||this.bookState==="closed-back")return this.rightPage&&t.right.kind==="page"?[this.rightPage.element]:[];const i=[];return e==="two-page"?(t.left.kind==="page"&&this.leftPage&&i.push(this.leftPage.element),t.right.kind==="page"&&this.rightPage&&i.push(this.rightPage.element)):t.left.kind==="blank"&&t.right.kind==="page"&&this.rightPage?i.push(this.rightPage.element):t.right.kind==="blank"&&t.left.kind==="page"&&this.leftPage?i.push(this.leftPage.element):t.left.kind==="page"&&this.leftPage?i.push(this.leftPage.element):t.right.kind==="page"&&this.rightPage&&i.push(this.rightPage.element),i}updateStageSize(e,t,i,r){this.layoutMode=i,this.lastSize={width:e,height:t},this.applyStageTransform(e,t,r)}destroy(){var e,t,i,r;(t=(e=this.flipStyle).cancel)==null||t.call(e,{bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot}),this.clearHardbackBoards(),(i=this.leftPage)==null||i.destroy(),(r=this.rightPage)==null||r.destroy(),this.element.remove()}applyStageTransform(e,t,i){if(e<=0||t<=0)return;const{width:r,height:n}=this.story.pageSize,a=this.layoutMode,o=this.bookState,l=Ts(this.story),c=l?Oi(this.story.pageSize):{x:0,y:0},d=a==="two-page"&&(o==="closed-front"||o==="closed-back"),h=l&&o==="open";this.element.classList.toggle("fc-hardback-active",l),this.element.classList.toggle("fc-hardback-open",h),this.element.classList.toggle("fc-hardback-closed",l&&d);let u,k,x,p=0,y=0,m=0;l&&d?(k=r+2*c.x,x=n+2*c.y,u=Math.min(e/k,t/x),this.bookEl.style.setProperty("--fc-page-width",`${k}px`),this.bookEl.style.setProperty("--fc-page-height",`${x}px`),this.bookEl.style.width=`${k*2}px`,this.bookEl.style.height=`${x}px`,p=-k*u,y=0,m=0,this.hardbackEl.hidden=!0):h?(k=(a==="single"?r:r*2)+2*c.x,x=n+2*c.y,u=Math.min(e/k,t/x),this.bookEl.style.setProperty("--fc-page-width",`${r}px`),this.bookEl.style.setProperty("--fc-page-height",`${n}px`),this.bookEl.style.width=`${r*2}px`,this.bookEl.style.height=`${n}px`,this.hardbackEl.hidden=!1,this.hardbackEl.style.width=`${k}px`,this.hardbackEl.style.height=`${x}px`,this.sizeHardbackBoards(a,r,n,c.x,c.y),y=c.x,m=c.y,a==="single"&&(i==null?void 0:i.left.kind)==="blank"?p=-r*u:p=0):(k=r*2,x=n,a==="single"||d?u=Math.min(e/r,t/n):u=Math.min(e/k,t/x),this.bookEl.style.setProperty("--fc-page-width",`${r}px`),this.bookEl.style.setProperty("--fc-page-height",`${n}px`),this.bookEl.style.width=`${k}px`,this.bookEl.style.height=`${x}px`,this.hardbackEl.hidden=!0,(d||a==="single"&&i&&i.left.kind==="blank")&&(p=-r*u)),this.element.style.setProperty("--fc-hardback-overhang-x",`${c.x}px`),this.element.style.setProperty("--fc-hardback-overhang-y",`${c.y}px`),this.hardbackEl.style.transform=`scale(${u})`,this.hardbackEl.style.transformOrigin="left top",this.bookEl.style.left=h?`${y*u}px`:"0",this.bookEl.style.top=h?`${m*u}px`:"0",this.bookEl.style.transform=`translateX(${p}px) scale(${u})`,this.bookEl.style.transformOrigin="left top";const S=l&&d?(r+2*c.x)*u:h?(a==="single"?r+2*c.x:r*2+2*c.x)*u:a==="single"||d?r*u:r*2*u,C=l&&(d||h)?(n+2*c.y)*u:n*u;this.element.style.width=`${S}px`,this.element.style.height=`${C}px`,this.leftSlot.classList.toggle("fc-leaf-dimmed",d),this.rightSlot.classList.remove("fc-leaf-dimmed")}sizeHardbackBoards(e,t,i,r,n){const a=i+2*n;if(e==="single"){this.hardbackLeft.style.display="none",this.hardbackRight.style.display="",this.hardbackRight.style.width=`${t+2*r}px`,this.hardbackRight.style.height=`${a}px`;return}this.hardbackLeft.style.display="",this.hardbackRight.style.display="",this.hardbackLeft.style.width=`${t+r}px`,this.hardbackLeft.style.height=`${a}px`,this.hardbackRight.style.width=`${t+r}px`,this.hardbackRight.style.height=`${a}px`}syncHardbackBoards(){if(!Ts(this.story)||this.bookState!=="open"){this.clearHardbackBoards();return}const e=this.story.pages,t=this.story.frontCover?e[0]:null,i=this.story.backCover?e[e.length-1]:null,r=t??i,n=i??t;this.mountHardbackBoard("left",r),this.mountHardbackBoard("right",n)}mountHardbackBoard(e,t){const i=e==="left"?this.hardbackLeft:this.hardbackRight,r=e==="left"?this.hardbackLeftPage:this.hardbackRightPage;if(r==null||r.destroy(),!t){i.replaceChildren(),e==="left"?this.hardbackLeftPage=null:this.hardbackRightPage=null;return}const n=new Ps(t,this.assets,{onTapActions:()=>{}});n.element.classList.add("fc-hardback-page"),i.replaceChildren(n.element),e==="left"?this.hardbackLeftPage=n:this.hardbackRightPage=n}clearHardbackBoards(){var e,t;(e=this.hardbackLeftPage)==null||e.destroy(),(t=this.hardbackRightPage)==null||t.destroy(),this.hardbackLeftPage=null,this.hardbackRightPage=null,this.hardbackLeft.replaceChildren(),this.hardbackRight.replaceChildren()}mountSpread(e){var t,i;this.currentSpread=e,(t=this.leftPage)==null||t.destroy(),(i=this.rightPage)==null||i.destroy(),this.leftSlot.replaceChildren(),this.rightSlot.replaceChildren(),this.leftPage=this.createLeaf(e.left),this.rightPage=this.createLeaf(e.right),this.leftSlot.appendChild(this.leftPage.element),this.rightSlot.appendChild(this.rightPage.element),this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,e)}createLeaf(e){if(e.kind==="blank")return new Ps(null,this.assets,{onTapActions:this.onTapActions});const t=this.story.pages[e.pageIndex];return new Ps(t,this.assets,{onTapActions:this.onTapActions})}}function ji(s,e){const t=s==null?void 0:s.container;if(!(t!=null&&t.send))return;const i=Bn(e.progress);t.send("progress",i),t.send("loading",{stage:e.stage,progress:i,count:e.count,total:e.total,detail:e.detail})}function Rn(s){var e,t;(t=(e=s==null?void 0:s.container)==null?void 0:e.send)==null||t.call(e,"loaded")}function Fn(){let s;return{promise:new Promise(t=>{s=t}),resolve:s}}function Bn(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}function Vi(s,e,t={}){const i=[];let r=!1;const n=(a,o)=>{if(!(a!=null&&a.subscribe))return;const l=a.subscribe(o);typeof l=="function"?i.push(l):l&&typeof l.unsubscribe=="function"&&i.push(()=>{var c;return(c=l.unsubscribe)==null?void 0:c.call(l)})};return s!=null&&s.state&&(n(s.state.pause,a=>{var l;const o=!!a;e.setPaused(o),(l=t.onPause)==null||l.call(t,o)}),n(s.state.soundVolume,a=>e.setVolume("sound",Number(a))),n(s.state.voVolume,a=>e.setVolume("vo",Number(a))),n(s.state.sfxVolume,a=>e.setVolume("sfx",Number(a))),n(s.state.musicVolume,a=>e.setVolume("music",Number(a))),n(s.state.captionsMuted,a=>{var o;r=!!a,(o=t.onCaptionsMuted)==null||o.call(t,r)})),{get captionsMuted(){return r},destroy(){for(const a of i)a()}}}async function zi(s){var e,t;try{const i=await import("springroll"),r=i.Application??((e=i.default)==null?void 0:e.Application),n=i.ApplicationPlugin??((t=i.default)==null?void 0:t.ApplicationPlugin);if(!r)return null;const a=Fn(),o=`fancifully-story-load-${Math.random().toString(36).slice(2,9)}`;if(n&&typeof r.uses=="function"){const c=new n({name:o});c.preload=()=>a.promise,r.uses(c)}else a.resolve();return{app:new r({features:s}),loadGate:a,owned:!0}}catch{return null}}function Zi(s){var e;return!((e=s==null?void 0:s.state)!=null&&e.ready)||s.state.ready.value===!0?Promise.resolve():new Promise(t=>{const i=s.state.ready.subscribe(r=>{r&&(typeof i=="function"&&i(),t())})})}const On={sound:!0,soundVolume:!0,vo:!0,voVolume:!0,sfx:!0,sfxVolume:!0,music:!0,musicVolume:!0,captions:!0};class Ns{constructor(e,t,i,r,n={},a,o,l=!1){f(this,"element");f(this,"root");f(this,"stage");f(this,"chrome");f(this,"captionsEl");f(this,"loaded");f(this,"spreadView");f(this,"pager");f(this,"bus",new me);f(this,"readAloud");f(this,"springroll");f(this,"bindings",null);f(this,"sfxAudio");f(this,"unbindSwipe",null);f(this,"resizeObserver",null);f(this,"listeners",new Map);f(this,"destroyed",!1);f(this,"btnPrev");f(this,"btnRead");f(this,"btnNext");f(this,"editorEnabled");f(this,"editing",!1);f(this,"chromeHiddenByOptions",!1);f(this,"editorChrome",null);f(this,"pageCanvases",new Map);f(this,"editorMounting",!1);f(this,"editorFiles",{});f(this,"editorDefaultFontFamily",null);var h,u,k,x,p,y;this.root=e,this.loaded=t,this.springroll=i,this.editorEnabled=l,this.chromeHiddenByOptions=!!n.hidden,this.element=document.createElement("div"),this.element.className="fc-root",this.element.tabIndex=0,this.stage=document.createElement("div"),this.stage.className="fc-stage",this.captionsEl=document.createElement("div"),this.captionsEl.className="fc-captions",this.captionsEl.setAttribute("aria-live","polite");const c={prev:((h=n.labels)==null?void 0:h.prev)??"Prev",read:((u=n.labels)==null?void 0:u.read)??"Read",next:((k=n.labels)==null?void 0:k.next)??"Next"},d={prev:((x=n.ariaLabels)==null?void 0:x.prev)??"Previous page",read:((p=n.ariaLabels)==null?void 0:p.read)??"Read aloud",next:((y=n.ariaLabels)==null?void 0:y.next)??"Next page"};this.chrome=document.createElement("div"),this.chrome.className=["fc-chrome",n.className].filter(Boolean).join(" "),this.chrome.hidden=!!n.hidden,this.btnPrev=document.createElement("button"),this.btnPrev.type="button",this.btnPrev.className="fc-btn fc-btn-prev",this.btnPrev.setAttribute("aria-label",d.prev),this.btnPrev.textContent=c.prev,this.btnRead=document.createElement("button"),this.btnRead.type="button",this.btnRead.className="fc-btn fc-btn-read",this.btnRead.setAttribute("aria-label",d.read),this.btnRead.textContent=c.read,this.btnNext=document.createElement("button"),this.btnNext.type="button",this.btnNext.className="fc-btn fc-btn-next",this.btnNext.setAttribute("aria-label",d.next),this.btnNext.textContent=c.next,this.chrome.append(this.btnPrev,this.btnRead,this.btnNext),this.spreadView=new $n(t.story,t.assets,(m,S)=>this.handleTapActions(m,S),{flipStyle:a??"default",flipSpeed:o}),this.pager=new An(t.story,this.spreadView),this.readAloud=new Ui(this.bus),this.sfxAudio=new Audio,this.bus.register(this.sfxAudio,"sfx"),this.stage.appendChild(this.spreadView.element),this.element.append(this.stage,this.captionsEl,this.chrome),this.root.appendChild(this.element),this.wireChrome(),this.wirePager(r),this.wireSpringroll(),this.wireResize(),this.unbindSwipe=Sr(this.stage,{onSwipeLeft:()=>{this.editing||this.next()},onSwipeRight:()=>{this.editing||this.prev()}}),this.element.addEventListener("keydown",m=>{this.editing||(m.key==="ArrowRight"?(m.preventDefault(),this.next()):m.key==="ArrowLeft"?(m.preventDefault(),this.prev()):m.key===" "&&(m.preventDefault(),this.playReadAloud()))}),this.readAloud.onCaption(m=>{this.captionsEl.textContent=m??"",this.captionsEl.hidden=!m}),this.editorEnabled&&this.mountEditorChrome()}static async create(e,t){const i={...On,...t.features};let r=t.springroll??null,n=null;if(!r){const d=await zi(i);d&&(r=d.app,n=d.loadGate,Vn(r))}const a=[];t.onProgress&&a.push(t.onProgress);const o=d=>{ji(r,d);for(const h of a)h(d)};o({stage:"fetch",progress:0,detail:"start"});const l=await _s(t.story,{baseUrl:t.baseUrl,name:t.storyName,onProgress:o});n==null||n.resolve(),await Zi(r);const c=new Ns(e,l,r,t.autoPlayReadAloud??!1,t.chrome??{},t.flipStyle,t.flipSpeed,!!t.editor);return c.pager.updateLayout(e.clientWidth||window.innerWidth,e.clientHeight||window.innerHeight,!1),c.layoutStage(),await c.pager.showInitial(),c.syncChromeNavState(),c.syncEditorChromeState(),c.emit("ready",{story:l.story}),c}get story(){return this.loaded.story}get layoutMode(){return this.pager.layoutMode}get pageIds(){return this.pager.currentPageIds}get spreadIndex(){return this.pager.currentSpread.index}get isEditing(){return this.editing}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var i;return(i=this.listeners.get(e))==null?void 0:i.delete(t)}}next(){return this.editing?Promise.resolve():this.navigate(()=>this.pager.next())}prev(){return this.editing?Promise.resolve():this.navigate(()=>this.pager.prev())}goTo(e){return this.editing?Promise.resolve():this.navigate(()=>this.pager.goTo(e))}setLayoutMode(e){this.editing&&this.commitEditorCanvases(),this.pager.setLayoutMode(e,this.root.clientWidth||window.innerWidth,this.root.clientHeight||window.innerHeight),this.layoutStage(),this.syncChromeNavState(),this.emit("layoutchange",{layoutMode:this.pager.layoutMode}),this.editing&&this.mountEditorCanvases()}setFlipStyle(e){this.spreadView.setFlipStyle(e)}setFlipSpeed(e){this.spreadView.setFlipSpeed(e)}playReadAloud(){if(this.editing)return Promise.resolve();const e=this.buildReadAloudClips();return this.readAloud.playSequence(e)}pause(){this.readAloud.pause(),this.bus.setPaused(!0)}resume(){this.bus.setPaused(!1),this.readAloud.resume()}async enterEditor(){!this.editorEnabled||this.editing||(this.readAloud.stop(),this.editing=!0,this.element.classList.add("fc-editing"),this.chrome.hidden=!0,await this.mountEditorCanvases(),this.syncEditorChromeState())}async exitEditor(){if(!this.editing)return;[...this.pageCanvases.values()].some(t=>t.isDirty)?(this.commitEditorCanvases(),this.destroyEditorCanvases(),this.spreadView.setPageViewsHidden(!1),this.spreadView.remountCurrent(),this.layoutStage()):(this.destroyEditorCanvases(),this.spreadView.setPageViewsHidden(!1)),this.editing=!1,this.element.classList.remove("fc-editing"),this.chrome.hidden=this.chromeHiddenByOptions,this.syncChromeNavState(),this.syncEditorChromeState()}async downloadFanci(e){this.editing&&this.commitEditorCanvases();const t=e??`${this.loaded.story.id||"story"}.fanci`,i=await Js(this.loaded.story,{baseUrl:this.loaded.baseUrl,files:{...this.editorFiles}});Gs(i,t.endsWith(".fanci")?t:`${t}.fanci`)}destroy(){var e,t,i,r;this.destroyed||(this.destroyed=!0,this.destroyEditorCanvases(),(e=this.editorChrome)==null||e.destroy(),this.editorChrome=null,this.readAloud.destroy(),this.bus.unregister(this.sfxAudio),(t=this.bindings)==null||t.destroy(),(i=this.unbindSwipe)==null||i.call(this),(r=this.resizeObserver)==null||r.disconnect(),this.spreadView.destroy(),this.element.remove(),this.listeners.clear(),Ai(this.loaded))}async navigate(e){this.readAloud.stop(),this.editing&&(this.commitEditorCanvases(),this.destroyEditorCanvases()),await e(),this.layoutStage(),this.editing&&await this.mountEditorCanvases()}mountEditorChrome(){this.editorChrome=new Di({onToggleEdit:()=>{this.editing?this.exitEditor():this.enterEditor()},onAddPage:()=>void this.editorAddPage(),onRemovePage:()=>void this.editorRemovePage(),onFrontCoverChange:e=>void this.editorSetFrontCover(e),onBackCoverChange:e=>void this.editorSetBackCover(e),onHardbackChange:e=>void this.editorSetHardback(e),onDownload:()=>void this.downloadFanci()}),this.element.appendChild(this.editorChrome.element),this.syncEditorChromeState()}syncEditorChromeState(){var e;(e=this.editorChrome)==null||e.setState({editing:this.editing,frontCover:!!this.loaded.story.frontCover,backCover:!!this.loaded.story.backCover,hardback:!!this.loaded.story.hardback,canRemovePage:this.loaded.story.pages.length>1})}editorHost(){return{story:this.loaded.story,assets:this.loaded.assets,editorFiles:this.editorFiles,blobUrls:this.loaded.blobUrls,getDefaultFontFamily:()=>this.editorDefaultFontFamily,setDefaultFontFamily:e=>{this.editorDefaultFontFamily=e},applyFontToAllTextboxes:e=>{this.editorDefaultFontFamily=e;for(const t of this.loaded.story.pages)for(const i of t.blocks)i.type==="text"&&(i.style={...i.style,fontFamily:e});for(const t of this.pageCanvases.values())t.applyFontToAllText(e)}}}async mountEditorCanvases(){if(!(!this.editing||this.editorMounting)){this.editorMounting=!0;try{this.destroyEditorCanvases(),this.spreadView.setPageViewsHidden(!0);const e=this.pager.currentSpread,t=this.spreadView.getEditableLeaves(this.pager.layoutMode,e),{width:i,height:r}=this.loaded.story.pageSize,n=this.editorHost();for(const a of t){const o=this.loaded.story.pages[a.pageIndex];if(!o)continue;const l=await is.create(o,{width:i,height:r},n);a.slot.appendChild(l.element),l.syncLayout(),this.pageCanvases.set(a.side,l)}}finally{this.editorMounting=!1}}}commitEditorCanvases(){for(const e of this.pageCanvases.values()){const t=e.commit(),i=this.loaded.story.pages.findIndex(r=>r.id===t.id);i>=0&&(this.loaded.story.pages[i]=t)}}destroyEditorCanvases(){for(const e of this.pageCanvases.values())e.destroy();this.pageCanvases.clear()}async editorAddPage(){if(!this.editing)return;this.commitEditorCanvases();const e=jn(this.loaded.story);this.loaded.story.pages.push(e),this.spreadView.setStory(this.loaded.story),this.destroyEditorCanvases(),this.pager.rebuildFromStory(e.id),this.layoutStage(),await this.mountEditorCanvases(),this.syncChromeNavState(),this.syncEditorChromeState()}async editorRemovePage(){var r,n;if(!this.editing||this.loaded.story.pages.length<=1)return;this.commitEditorCanvases();const e=this.pager.currentPageIds[0]??((r=this.loaded.story.pages[0])==null?void 0:r.id);if(!e)return;const t=this.loaded.story.pages.findIndex(a=>a.id===e);if(t<0)return;this.loaded.story.pages.splice(t,1);const i=((n=this.loaded.story.pages[Math.min(t,this.loaded.story.pages.length-1)])==null?void 0:n.id)??null;this.spreadView.setStory(this.loaded.story),this.destroyEditorCanvases(),this.pager.rebuildFromStory(i),this.layoutStage(),await this.mountEditorCanvases(),this.syncChromeNavState(),this.syncEditorChromeState()}async editorSetFrontCover(e){this.editing&&(this.commitEditorCanvases(),this.loaded.story.frontCover=e,this.spreadView.setStory(this.loaded.story),this.destroyEditorCanvases(),this.pager.rebuildFromStory(this.pager.currentPageIds[0]??null),this.layoutStage(),await this.mountEditorCanvases(),this.syncChromeNavState(),this.syncEditorChromeState())}async editorSetBackCover(e){this.editing&&(this.commitEditorCanvases(),this.loaded.story.backCover=e,this.spreadView.setStory(this.loaded.story),this.destroyEditorCanvases(),this.pager.rebuildFromStory(this.pager.currentPageIds[0]??null),this.layoutStage(),await this.mountEditorCanvases(),this.syncChromeNavState(),this.syncEditorChromeState())}async editorSetHardback(e){this.editing&&(this.commitEditorCanvases(),this.loaded.story.hardback=e,this.spreadView.setStory(this.loaded.story),this.destroyEditorCanvases(),this.layoutStage(),await this.mountEditorCanvases(),this.syncEditorChromeState())}wireChrome(){this.btnPrev.addEventListener("click",()=>void this.prev()),this.btnNext.addEventListener("click",()=>void this.next()),this.btnRead.addEventListener("click",()=>void this.playReadAloud())}syncChromeNavState(){const e=this.pager.canPrev,t=this.pager.canNext;this.btnPrev.disabled=!e,this.btnNext.disabled=!t,this.btnPrev.classList.toggle("is-disabled",!e),this.btnNext.classList.toggle("is-disabled",!t),this.btnPrev.setAttribute("aria-disabled",String(!e)),this.btnNext.setAttribute("aria-disabled",String(!t))}wirePager(e){this.pager.on("pagechange",t=>{this.syncChromeNavState(),this.emit("pagechange",t),e&&!this.editing&&this.playReadAloud()}),this.pager.on("layoutchange",t=>{this.readAloud.stop(),this.editing&&(this.commitEditorCanvases(),this.destroyEditorCanvases()),this.layoutStage(),this.syncChromeNavState(),this.emit("layoutchange",t),this.editing&&this.mountEditorCanvases()})}wireSpringroll(){this.bindings=Vi(this.springroll,this.bus,{onCaptionsMuted:e=>this.readAloud.setCaptionsMuted(e),onPause:e=>{e?this.readAloud.pause():this.readAloud.resume()}})}wireResize(){const e=()=>{this.pager.updateLayout(this.root.clientWidth||window.innerWidth,this.root.clientHeight||window.innerHeight),this.layoutStage()};typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.root)):window.addEventListener("resize",e)}layoutStage(){const e=this.stage.clientWidth||this.root.clientWidth||window.innerWidth,t=this.stage.clientHeight||Math.max(320,this.root.clientHeight-64);this.spreadView.updateStageSize(e,t,this.pager.layoutMode,this.pager.currentSpread)}buildReadAloudClips(){const e=this.pager.layoutMode,t=this.pager.currentSpread,i=this.pager.currentBookState;let r=[t.left,t.right];i==="closed-front"?r=[t.left]:i==="closed-back"?r=[t.right]:e==="single"&&(r=t.left.kind==="blank"?[t.right]:t.right.kind==="blank"?[t.left]:[t.left]);const n=[];for(const a of r){if(a.kind!=="page")continue;const o=this.loaded.story.pages[a.pageIndex];if(!o.readAloud)continue;const l=this.loaded.assets.audioUrls.get(o.readAloud.audio);if(!l)continue;const c=this.resolveCues(o.readAloud.cues),d=this.spreadView.getPageElement(o.id);n.push({url:l.url,channel:l.channel,cues:c,root:d})}return n}resolveCues(e){return e?Array.isArray(e)?e:this.loaded.assets.cues.get(e)??[]:[]}handleTapActions(e,t){if(!this.editing){for(const i of e)if("play"in i){const r=this.loaded.assets.audioUrls.get(i.play);if(!r)continue;this.sfxAudio.src=r.url,this.bus.applyTo(this.sfxAudio,r.channel),this.sfxAudio.play().catch(()=>{})}else if("toggleClass"in i){const r=t.querySelector(`[data-block-id="${i.toggleClass.target}"]`);r==null||r.classList.toggle(i.toggleClass.className)}}}emit(e,t){const i=this.listeners.get(e);if(i)for(const r of i)r(t)}}function jn(s){let e=s.pages.length+1,t=`page-${e}`;const i=new Set(s.pages.map(r=>r.id));for(;i.has(t);)e+=1,t=`page-${e}`;return{id:t,background:{color:"#faf6ef"},blocks:[]}}function Vn(s){var t,i,r,n,a,o;const e=s.state;e&&((t=e.pause)==null||t.subscribe(()=>{}),(i=e.soundVolume)==null||i.subscribe(()=>{}),(r=e.voVolume)==null||r.subscribe(()=>{}),(n=e.sfxVolume)==null||n.subscribe(()=>{}),(a=e.musicVolume)==null||a.subscribe(()=>{}),(o=e.captionsMuted)==null||o.subscribe(()=>{}))}return _.CueTimeline=Ls,_.DEFAULT_FLIP_SPEED_MS=Bi,_.DefaultFlipStyle=Rt,_.FANCI_EXTENSION=Mt,_.FlipStyle=ot,_.HARDBACK_EDGE_RATIO=As,_.Storybook=Ns,_.bindApplication=Vi,_.boxToPixels=vt,_.buildBackCoverSpread=Pi,_.buildFrontCoverSpread=Ii,_.buildSingleSpreads=Mi,_.buildSpreads=$t,_.buildTwoPageSpreads=Ni,_.contentPageIds=Li,_.createFlipStyle=Cs,_.createSpringrollApplication=zi,_.downloadBlob=Gs,_.fabricToStory=ii,_.findSpreadIndexForPage=Ue,_.findStoryJsonPath=ks,_.getRegisteredFlipStyle=Tn,_.hardbackEnabled=Ts,_.hardbackOverhang=Oi,_.htmlToPlainText=es,_.listRegisteredFlipStyles=Fi,_.loadEpubFromBytes=cn,_.loadEpubFromZip=bs,_.loadFanciFromBytes=vn,_.loadFanciFromZip=ws,_.loadStory=_s,_.packFanci=Js,_.parseStory=Ze,_.parseVtt=ms,_.plainTextToHtml=ei,_.primaryPageId=$i,_.registerFlipStyle=Ri,_.reportSpringrollLoaded=Rn,_.reportSpringrollProgress=ji,_.resolveFlipSpeedMs=Es,_.resolveLayoutMode=Ti,_.revokeLoadedStory=Ai,_.serializeLayoutBox=Qt,_.storySchema=bi,_.storyToFabric=ss,_.toPx=Be,_.waitForSpringrollReady=Zi,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"}),_})({});
1
+ var Fancifully=(function(S){"use strict";var aa=Object.defineProperty;var oa=(S,ye,xe)=>ye in S?aa(S,ye,{enumerable:!0,configurable:!0,writable:!0,value:xe}):S[ye]=xe;var y=(S,ye,xe)=>oa(S,typeof ye!="symbol"?ye+"":ye,xe);class ye{constructor(){y(this,"volumes",{sound:1,vo:1,sfx:1,music:1});y(this,"elements",new Set);y(this,"paused",!1)}setVolume(e,t){this.volumes[e]=xe(t),this.applyAll()}getVolume(e){return xe(this.volumes.sound)*xe(this.volumes[e])}setPaused(e){this.paused=e;for(const t of this.elements)e&&t.pause()}get isPaused(){return this.paused}register(e,t){this.elements.add(e),e.volume=this.getVolume(t),e.dataset.fcChannel=t}unregister(e){this.elements.delete(e)}applyTo(e,t){e.volume=this.getVolume(t)}applyAll(){for(const e of this.elements){const t=e.dataset.fcChannel||"vo";e.volume=this.getVolume(t)}}}function xe(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}class $s{constructor(e=[]){y(this,"cues");y(this,"root",null);y(this,"lastActiveId",null);y(this,"readIds",new Set);this.cues=[...e].sort((t,r)=>t.start-r.start)}setCues(e){this.cues=[...e].sort((t,r)=>t.start-r.start),this.reset()}attach(e){this.root=e,this.resetHighlight()}reset(){this.lastActiveId=null,this.readIds.clear(),this.resetHighlight()}update(e){const t=this.cues.find(r=>e>=r.start&&e<r.end)??null;return this.root&&(t?(this.readIds.add(t.id),t.id!==this.lastActiveId&&(this.applyHighlight(t.id),this.lastActiveId=t.id)):this.lastActiveId&&(this.clearActive(),this.lastActiveId=null)),t}applyHighlight(e){if(!this.root)return;this.root.querySelectorAll(".fc-cue.is-active").forEach(r=>r.classList.remove("is-active"));const t=this.root.querySelector(`#${Fs(e)}, [data-cue-id="${Rs(e)}"]`);t&&t.classList.add("fc-cue","is-active","is-read");for(const r of this.readIds){if(r===e)continue;const i=this.root.querySelector(`#${Fs(r)}, [data-cue-id="${Rs(r)}"]`);i==null||i.classList.add("fc-cue","is-read")}}clearActive(){var e;(e=this.root)==null||e.querySelectorAll(".fc-cue.is-active").forEach(t=>t.classList.remove("is-active"))}resetHighlight(){var e;(e=this.root)==null||e.querySelectorAll(".fc-cue").forEach(t=>{t.classList.remove("is-active","is-read")})}}function Fs(s){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function Rs(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}class Yr{constructor(e){y(this,"bus");y(this,"audio");y(this,"timeline",new $s);y(this,"queue",[]);y(this,"raf",0);y(this,"captionsMuted",!1);y(this,"onCaptionLine",null);y(this,"playing",!1);this.bus=e,this.audio=new Audio,this.audio.preload="auto",this.bus.register(this.audio,"vo"),this.audio.addEventListener("ended",()=>this.playNext())}setCaptionsMuted(e){var t;this.captionsMuted=e,e&&((t=this.onCaptionLine)==null||t.call(this,null))}onCaption(e){this.onCaptionLine=e}async playSequence(e){this.stop(),this.queue=e.filter(t=>!!t.url),this.queue.length!==0&&(this.playing=!0,await this.playNext())}pause(){this.audio.pause(),this.cancelTick()}resume(){!this.playing||this.bus.isPaused||(this.audio.play().catch(()=>{}),this.startTick())}stop(){var e;this.playing=!1,this.queue=[],this.audio.pause(),this.audio.removeAttribute("src"),this.audio.load(),this.timeline.reset(),this.cancelTick(),(e=this.onCaptionLine)==null||e.call(this,null)}destroy(){this.stop(),this.bus.unregister(this.audio)}async playNext(){var t;this.cancelTick();const e=this.queue.shift();if(!e){this.playing=!1,this.timeline.reset(),(t=this.onCaptionLine)==null||t.call(this,null);return}this.timeline.setCues(e.cues),this.timeline.attach(e.root),this.bus.register(this.audio,e.channel),this.audio.src=e.url,this.bus.applyTo(this.audio,e.channel);try{await this.audio.play(),this.startTick()}catch{this.startTick()}}startTick(){this.cancelTick();const e=()=>{var t;if(this.playing){if(!this.bus.isPaused&&!this.audio.paused){const r=this.timeline.update(this.audio.currentTime);this.captionsMuted||(t=this.onCaptionLine)==null||t.call(this,(r==null?void 0:r.text)??(r==null?void 0:r.id)??null)}this.raf=requestAnimationFrame(e)}};this.raf=requestAnimationFrame(e)}cancelTick(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=0)}}function Gr(s,e){let t=0,r=0,i=!1;const n=l=>{l.button!=null&&l.button!==0||(i=!0,t=l.clientX,r=l.clientY)},a=l=>{var h,u;if(!i)return;i=!1;const d=l.clientX-t,c=l.clientY-r;Math.abs(d)<50||Math.abs(d)<Math.abs(c)||(d<0?(h=e.onSwipeLeft)==null||h.call(e):(u=e.onSwipeRight)==null||u.call(e))},o=()=>{i=!1};return s.addEventListener("pointerdown",n),s.addEventListener("pointerup",a),s.addEventListener("pointercancel",o),()=>{s.removeEventListener("pointerdown",n),s.removeEventListener("pointerup",a),s.removeEventListener("pointercancel",o)}}function Os(s){var t;const e=((t=s.split(".").pop())==null?void 0:t.toLowerCase())??"";return/^[a-z0-9]{1,8}$/.test(e)?e:""}function jt(s){const e=Os(s.name),t=(s.type||"").toLowerCase();return e==="fanci"||t==="application/x-fanci"||t==="application/fanci"}function Jr(s){var e;if(!((e=s==null?void 0:s.files)!=null&&e.length))return null;for(const t of Array.from(s.files))if(jt(t))return t;return null}var F;(function(s){s.assertEqual=i=>{};function e(i){}s.assertIs=e;function t(i){throw new Error}s.assertNever=t,s.arrayToEnum=i=>{const n={};for(const a of i)n[a]=a;return n},s.getValidEnumValues=i=>{const n=s.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(const o of n)a[o]=i[o];return s.objectValues(a)},s.objectValues=i=>s.objectKeys(i).map(function(n){return i[n]}),s.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const n=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&n.push(a);return n},s.find=(i,n)=>{for(const a of i)if(n(a))return a},s.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,n=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(n)}s.joinValues=r,s.jsonStringifyReplacer=(i,n)=>typeof n=="bigint"?n.toString():n})(F||(F={}));var Vs;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Vs||(Vs={}));const w=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ce=s=>{switch(typeof s){case"undefined":return w.undefined;case"string":return w.string;case"number":return Number.isNaN(s)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":return Array.isArray(s)?w.array:s===null?w.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?w.promise:typeof Map<"u"&&s instanceof Map?w.map:typeof Set<"u"&&s instanceof Set?w.set:typeof Date<"u"&&s instanceof Date?w.date:w.object;default:return w.unknown}},p=F.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ve extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(n){return n.message},r={_errors:[]},i=n=>{for(const a of n.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let o=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(a))):o[d]=o[d]||{_errors:[]},o=o[d],l++}}};return i(this),r}static assert(e){if(!(e instanceof ve))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const i of this.issues)if(i.path.length>0){const n=i.path[0];t[n]=t[n]||[],t[n].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ve.create=s=>new ve(s);const Zt=(s,e)=>{let t;switch(s.code){case p.invalid_type:s.received===w.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case p.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,F.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:t=`Unrecognized key(s) in object: ${F.joinValues(s.keys,", ")}`;break;case p.invalid_union:t="Invalid input";break;case p.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${F.joinValues(s.options)}`;break;case p.invalid_enum_value:t=`Invalid enum value. Expected ${F.joinValues(s.options)}, received '${s.received}'`;break;case p.invalid_arguments:t="Invalid function arguments";break;case p.invalid_return_type:t="Invalid function return type";break;case p.invalid_date:t="Invalid date";break;case p.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:F.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case p.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case p.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case p.custom:t="Invalid input";break;case p.invalid_intersection_types:t="Intersection results could not be merged";break;case p.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case p.not_finite:t="Number must be finite";break;default:t=e.defaultError,F.assertNever(s)}return{message:t}};let Xr=Zt;function Kr(){return Xr}const Qr=s=>{const{data:e,path:t,errorMaps:r,issueData:i}=s,n=[...t,...i.path||[]],a={...i,path:n};if(i.message!==void 0)return{...i,path:n,message:i.message};let o="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)o=d(a,{data:e,defaultError:o}).message;return{...i,path:n,message:o}};function k(s,e){const t=Kr(),r=Qr({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Zt?void 0:Zt].filter(i=>!!i)});s.common.issues.push(r)}class ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const i of t){if(i.status==="aborted")return A;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const i of t){const n=await i.key,a=await i.value;r.push({key:n,value:a})}return ee.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const i of t){const{key:n,value:a}=i;if(n.status==="aborted"||a.status==="aborted")return A;n.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[n.value]=a.value)}return{status:e.value,value:r}}}const A=Object.freeze({status:"aborted"}),Ge=s=>({status:"dirty",value:s}),ne=s=>({status:"valid",value:s}),Bs=s=>s.status==="aborted",zs=s=>s.status==="dirty",Re=s=>s.status==="valid",pt=s=>typeof Promise<"u"&&s instanceof Promise;var C;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(C||(C={}));class de{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const js=(s,e)=>{if(Re(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ve(s.common.issues);return this._error=t,this._error}}};function P(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:i}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{const{message:l}=s;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:i}}class N{get description(){return this._def.description}_getType(e){return Ce(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ee,ctx:{common:e.parent.common,data:e.data,parsedType:Ce(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(pt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)},i=this._parseSync({data:e,path:r.path,parent:r});return js(r,i)}"~validate"(e){var r,i;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return Re(n)?{value:n.value}:{issues:t.common.issues}}catch(n){(i=(r=n==null?void 0:n.message)==null?void 0:r.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>Re(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ce(e)},i=this._parse({data:e,path:r.path,parent:r}),n=await(pt(i)?i:Promise.resolve(i));return js(r,n)}refine(e,t){const r=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,n)=>{const a=e(i),o=()=>n.addIssue({code:p.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof t=="function"?t(r,i):t),!1))}_refinement(e){return new Ie({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return we.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return he.create(this)}promise(){return kt.create(this,this._def)}or(e){return mt.create([this,e],this._def)}and(e){return yt.create(this,e,this._def)}transform(e){return new Ie({...P(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new wt({...P(this._def),innerType:this,defaultValue:t,typeName:T.ZodDefault})}brand(){return new Xs({typeName:T.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new St({...P(this._def),innerType:this,catchValue:t,typeName:T.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xt.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ei=/^c[^\s-]{8,}$/i,ti=/^[0-9a-z]+$/,si=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ri=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ii=/^[a-z0-9_-]{21}$/i,ni=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ai=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,oi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,li="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ut;const ci=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,di=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,hi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ui=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zs="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",gi=new RegExp(`^${Zs}$`);function Us(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function mi(s){return new RegExp(`^${Us(s)}$`)}function yi(s){let e=`${Zs}T${Us(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function vi(s,e){return!!((e==="v4"||!e)&&ci.test(s)||(e==="v6"||!e)&&hi.test(s))}function bi(s,e){if(!ni.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function ki(s,e){return!!((e==="v4"||!e)&&di.test(s)||(e==="v6"||!e)&&ui.test(s))}class be extends N{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==w.string){const n=this._getOrReturnCtx(e);return k(n,{code:p.invalid_type,expected:w.string,received:n.parsedType}),A}const r=new ee;let i;for(const n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(i=this._getOrReturnCtx(e,i),k(i,{code:p.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if(n.kind==="max")e.data.length>n.value&&(i=this._getOrReturnCtx(e,i),k(i,{code:p.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if(n.kind==="length"){const a=e.data.length>n.value,o=e.data.length<n.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?k(i,{code:p.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&k(i,{code:p.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),r.dirty())}else if(n.kind==="email")oi.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"email",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="emoji")Ut||(Ut=new RegExp(li,"u")),Ut.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"emoji",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="uuid")ri.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"uuid",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="nanoid")ii.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"nanoid",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="cuid")ei.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"cuid",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="cuid2")ti.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"cuid2",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="ulid")si.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"ulid",code:p.invalid_string,message:n.message}),r.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),k(i,{validation:"url",code:p.invalid_string,message:n.message}),r.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"regex",code:p.invalid_string,message:n.message}),r.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()):n.kind==="datetime"?yi(n).test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:"datetime",message:n.message}),r.dirty()):n.kind==="date"?gi.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:"date",message:n.message}),r.dirty()):n.kind==="time"?mi(n).test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:p.invalid_string,validation:"time",message:n.message}),r.dirty()):n.kind==="duration"?ai.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"duration",code:p.invalid_string,message:n.message}),r.dirty()):n.kind==="ip"?vi(e.data,n.version)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"ip",code:p.invalid_string,message:n.message}),r.dirty()):n.kind==="jwt"?bi(e.data,n.alg)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"jwt",code:p.invalid_string,message:n.message}),r.dirty()):n.kind==="cidr"?ki(e.data,n.version)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"cidr",code:p.invalid_string,message:n.message}),r.dirty()):n.kind==="base64"?fi.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"base64",code:p.invalid_string,message:n.message}),r.dirty()):n.kind==="base64url"?pi.test(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{validation:"base64url",code:p.invalid_string,message:n.message}),r.dirty()):F.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(i=>e.test(i),{validation:t,code:p.invalid_string,...C.errToObj(r)})}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...C.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...C.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...C.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...C.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...C.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...C.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...C.errToObj(t)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new be({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new be({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new be({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}be.create=s=>new be({checks:[],typeName:T.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...P(s)});function wi(s,e){const t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=t>r?t:r,n=Number.parseInt(s.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return n%a/10**i}class Oe extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==w.number){const n=this._getOrReturnCtx(e);return k(n,{code:p.invalid_type,expected:w.number,received:n.parsedType}),A}let r;const i=new ee;for(const n of this._def.checks)n.kind==="int"?F.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:p.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):n.kind==="multipleOf"?wi(e.data,n.value)!==0&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:p.not_finite,message:n.message}),i.dirty()):F.assertNever(n);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,r,i){return new Oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:C.toString(i)}]})}_addCheck(e){return new Oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&F.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Oe.create=s=>new Oe({checks:[],typeName:T.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...P(s)});class Je extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==w.bigint)return this._getInvalidInput(e);let r;const i=new ee;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),k(r,{code:p.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):F.assertNever(n);return{status:i.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return k(t,{code:p.invalid_type,expected:w.bigint,received:t.parsedType}),A}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,r,i){return new Je({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:C.toString(i)}]})}_addCheck(e){return new Je({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Je.create=s=>new Je({checks:[],typeName:T.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...P(s)});class Ht extends N{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==w.boolean){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.boolean,received:r.parsedType}),A}return ne(e.data)}}Ht.create=s=>new Ht({typeName:T.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...P(s)});class gt extends N{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==w.date){const n=this._getOrReturnCtx(e);return k(n,{code:p.invalid_type,expected:w.date,received:n.parsedType}),A}if(Number.isNaN(e.data.getTime())){const n=this._getOrReturnCtx(e);return k(n,{code:p.invalid_date}),A}const r=new ee;let i;for(const n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(i=this._getOrReturnCtx(e,i),k(i,{code:p.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(i=this._getOrReturnCtx(e,i),k(i,{code:p.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):F.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new gt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}gt.create=s=>new gt({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:T.ZodDate,...P(s)});class Hs extends N{_parse(e){if(this._getType(e)!==w.symbol){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.symbol,received:r.parsedType}),A}return ne(e.data)}}Hs.create=s=>new Hs({typeName:T.ZodSymbol,...P(s)});class Dt extends N{_parse(e){if(this._getType(e)!==w.undefined){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.undefined,received:r.parsedType}),A}return ne(e.data)}}Dt.create=s=>new Dt({typeName:T.ZodUndefined,...P(s)});class Wt extends N{_parse(e){if(this._getType(e)!==w.null){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.null,received:r.parsedType}),A}return ne(e.data)}}Wt.create=s=>new Wt({typeName:T.ZodNull,...P(s)});class Ds extends N{constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}}Ds.create=s=>new Ds({typeName:T.ZodAny,...P(s)});class Ws extends N{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}}Ws.create=s=>new Ws({typeName:T.ZodUnknown,...P(s)});class Ae extends N{_parse(e){const t=this._getOrReturnCtx(e);return k(t,{code:p.invalid_type,expected:w.never,received:t.parsedType}),A}}Ae.create=s=>new Ae({typeName:T.ZodNever,...P(s)});class qs extends N{_parse(e){if(this._getType(e)!==w.undefined){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.void,received:r.parsedType}),A}return ne(e.data)}}qs.create=s=>new qs({typeName:T.ZodVoid,...P(s)});class he extends N{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==w.array)return k(t,{code:p.invalid_type,expected:w.array,received:t.parsedType}),A;if(i.exactLength!==null){const a=t.data.length>i.exactLength.value,o=t.data.length<i.exactLength.value;(a||o)&&(k(t,{code:a?p.too_big:p.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(k(t,{code:p.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(k(t,{code:p.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>i.type._parseAsync(new de(t,a,t.path,o)))).then(a=>ee.mergeArray(r,a));const n=[...t.data].map((a,o)=>i.type._parseSync(new de(t,a,t.path,o)));return ee.mergeArray(r,n)}get element(){return this._def.type}min(e,t){return new he({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new he({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new he({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}he.create=(s,e)=>new he({type:s,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...P(e)});function Ve(s){if(s instanceof Y){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=we.create(Ve(r))}return new Y({...s._def,shape:()=>e})}else return s instanceof he?new he({...s._def,type:Ve(s.element)}):s instanceof we?we.create(Ve(s.unwrap())):s instanceof Ne?Ne.create(Ve(s.unwrap())):s instanceof Me?Me.create(s.items.map(e=>Ve(e))):s}class Y extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=F.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==w.object){const d=this._getOrReturnCtx(e);return k(d,{code:p.invalid_type,expected:w.object,received:d.parsedType}),A}const{status:r,ctx:i}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ae&&this._def.unknownKeys==="strip"))for(const d in i.data)a.includes(d)||o.push(d);const l=[];for(const d of a){const c=n[d],h=i.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new de(i,h,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof Ae){const d=this._def.unknownKeys;if(d==="passthrough")for(const c of o)l.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(d==="strict")o.length>0&&(k(i,{code:p.unrecognized_keys,keys:o}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const c of o){const h=i.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new de(i,h,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const d=[];for(const c of l){const h=await c.key,u=await c.value;d.push({key:h,value:u,alwaysSet:c.alwaysSet})}return d}).then(d=>ee.mergeObjectSync(r,d)):ee.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new Y({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var n,a;const i=((a=(n=this._def).errorMap)==null?void 0:a.call(n,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:C.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new Y({...this._def,unknownKeys:"strip"})}passthrough(){return new Y({...this._def,unknownKeys:"passthrough"})}extend(e){return new Y({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Y({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:T.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Y({...this._def,catchall:e})}pick(e){const t={};for(const r of F.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Y({...this._def,shape:()=>t})}omit(e){const t={};for(const r of F.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Y({...this._def,shape:()=>t})}deepPartial(){return Ve(this)}partial(e){const t={};for(const r of F.objectKeys(this.shape)){const i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new Y({...this._def,shape:()=>t})}required(e){const t={};for(const r of F.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let n=this.shape[r];for(;n instanceof we;)n=n._def.innerType;t[r]=n}return new Y({...this._def,shape:()=>t})}keyof(){return Gs(F.objectKeys(this.shape))}}Y.create=(s,e)=>new Y({shape:()=>s,unknownKeys:"strip",catchall:Ae.create(),typeName:T.ZodObject,...P(e)}),Y.strictCreate=(s,e)=>new Y({shape:()=>s,unknownKeys:"strict",catchall:Ae.create(),typeName:T.ZodObject,...P(e)}),Y.lazycreate=(s,e)=>new Y({shape:s,unknownKeys:"strip",catchall:Ae.create(),typeName:T.ZodObject,...P(e)});class mt extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function i(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=n.map(o=>new ve(o.ctx.common.issues));return k(t,{code:p.invalid_union,unionErrors:a}),A}if(t.common.async)return Promise.all(r.map(async n=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let n;const a=[];for(const l of r){const d={...t,common:{...t.common,issues:[]},parent:null},c=l._parseSync({data:t.data,path:t.path,parent:d});if(c.status==="valid")return c;c.status==="dirty"&&!n&&(n={result:c,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;const o=a.map(l=>new ve(l));return k(t,{code:p.invalid_union,unionErrors:o}),A}}get options(){return this._def.options}}mt.create=(s,e)=>new mt({options:s,typeName:T.ZodUnion,...P(e)});const ke=s=>s instanceof Gt?ke(s.schema):s instanceof Ie?ke(s.innerType()):s instanceof bt?[s.value]:s instanceof Pe?s.options:s instanceof Jt?F.objectValues(s.enum):s instanceof wt?ke(s._def.innerType):s instanceof Dt?[void 0]:s instanceof Wt?[null]:s instanceof we?[void 0,...ke(s.unwrap())]:s instanceof Ne?[null,...ke(s.unwrap())]:s instanceof Xs||s instanceof _t?ke(s.unwrap()):s instanceof St?ke(s._def.innerType):[];class qt extends N{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.object)return k(t,{code:p.invalid_type,expected:w.object,received:t.parsedType}),A;const r=this.discriminator,i=t.data[r],n=this.optionsMap.get(i);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(k(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),A)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const i=new Map;for(const n of t){const a=ke(n.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,n)}}return new qt({typeName:T.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...P(r)})}}function Yt(s,e){const t=Ce(s),r=Ce(e);if(s===e)return{valid:!0,data:s};if(t===w.object&&r===w.object){const i=F.objectKeys(e),n=F.objectKeys(s).filter(o=>i.indexOf(o)!==-1),a={...s,...e};for(const o of n){const l=Yt(s[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===w.array&&r===w.array){if(s.length!==e.length)return{valid:!1};const i=[];for(let n=0;n<s.length;n++){const a=s[n],o=e[n],l=Yt(a,o);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return t===w.date&&r===w.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class yt extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),i=(n,a)=>{if(Bs(n)||Bs(a))return A;const o=Yt(n.value,a.value);return o.valid?((zs(n)||zs(a))&&t.dirty(),{status:t.value,value:o.data}):(k(r,{code:p.invalid_intersection_types}),A)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([n,a])=>i(n,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}yt.create=(s,e,t)=>new yt({left:s,right:e,typeName:T.ZodIntersection,...P(t)});class Me extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.array)return k(r,{code:p.invalid_type,expected:w.array,received:r.parsedType}),A;if(r.data.length<this._def.items.length)return k(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&r.data.length>this._def.items.length&&(k(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new de(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(n).then(a=>ee.mergeArray(t,a)):ee.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new Me({...this._def,rest:e})}}Me.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Me({items:s,typeName:T.ZodTuple,rest:null,...P(e)})};class vt extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.object)return k(r,{code:p.invalid_type,expected:w.object,received:r.parsedType}),A;const i=[],n=this._def.keyType,a=this._def.valueType;for(const o in r.data)i.push({key:n._parse(new de(r,o,r.path,o)),value:a._parse(new de(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?ee.mergeObjectAsync(t,i):ee.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof N?new vt({keyType:e,valueType:t,typeName:T.ZodRecord,...P(r)}):new vt({keyType:be.create(),valueType:e,typeName:T.ZodRecord,...P(t)})}}class Ys extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.map)return k(r,{code:p.invalid_type,expected:w.map,received:r.parsedType}),A;const i=this._def.keyType,n=this._def.valueType,a=[...r.data.entries()].map(([o,l],d)=>({key:i._parse(new de(r,o,r.path,[d,"key"])),value:n._parse(new de(r,l,r.path,[d,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,c=await l.value;if(d.status==="aborted"||c.status==="aborted")return A;(d.status==="dirty"||c.status==="dirty")&&t.dirty(),o.set(d.value,c.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of a){const d=l.key,c=l.value;if(d.status==="aborted"||c.status==="aborted")return A;(d.status==="dirty"||c.status==="dirty")&&t.dirty(),o.set(d.value,c.value)}return{status:t.value,value:o}}}}Ys.create=(s,e,t)=>new Ys({valueType:e,keyType:s,typeName:T.ZodMap,...P(t)});class Xe extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==w.set)return k(r,{code:p.invalid_type,expected:w.set,received:r.parsedType}),A;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(k(r,{code:p.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(k(r,{code:p.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const n=this._def.valueType;function a(l){const d=new Set;for(const c of l){if(c.status==="aborted")return A;c.status==="dirty"&&t.dirty(),d.add(c.value)}return{status:t.value,value:d}}const o=[...r.data.values()].map((l,d)=>n._parse(new de(r,l,r.path,d)));return r.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new Xe({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new Xe({...this._def,maxSize:{value:e,message:C.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Xe.create=(s,e)=>new Xe({valueType:s,minSize:null,maxSize:null,typeName:T.ZodSet,...P(e)});class Gt extends N{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Gt.create=(s,e)=>new Gt({getter:s,typeName:T.ZodLazy,...P(e)});class bt extends N{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return k(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:e.data}}get value(){return this._def.value}}bt.create=(s,e)=>new bt({value:s,typeName:T.ZodLiteral,...P(e)});function Gs(s,e){return new Pe({values:s,typeName:T.ZodEnum,...P(e)})}class Pe extends N{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return k(t,{expected:F.joinValues(r),received:t.parsedType,code:p.invalid_type}),A}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return k(t,{received:t.data,code:p.invalid_enum_value,options:r}),A}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}Pe.create=Gs;class Jt extends N{_parse(e){const t=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==w.string&&r.parsedType!==w.number){const i=F.objectValues(t);return k(r,{expected:F.joinValues(i),received:r.parsedType,code:p.invalid_type}),A}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=F.objectValues(t);return k(r,{received:r.data,code:p.invalid_enum_value,options:i}),A}return ne(e.data)}get enum(){return this._def.values}}Jt.create=(s,e)=>new Jt({values:s,typeName:T.ZodNativeEnum,...P(e)});class kt extends N{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&t.common.async===!1)return k(t,{code:p.invalid_type,expected:w.promise,received:t.parsedType}),A;const r=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return ne(r.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}}kt.create=(s,e)=>new kt({type:s,typeName:T.ZodPromise,...P(e)});class Ie extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,n={addIssue:a=>{k(r,a),a.fatal?t.abort():t.dirty()},get path(){return r.path}};if(n.addIssue=n.addIssue.bind(n),i.type==="preprocess"){const a=i.transform(r.data,n);if(r.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return A;const l=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return l.status==="aborted"?A:l.status==="dirty"||t.value==="dirty"?Ge(l.value):l});{if(t.value==="aborted")return A;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?A:o.status==="dirty"||t.value==="dirty"?Ge(o.value):o}}if(i.type==="refinement"){const a=o=>{const l=i.refinement(o,n);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?A:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?A:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(i.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Re(a))return A;const o=i.transform(a.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Re(a)?Promise.resolve(i.transform(a.value,n)).then(o=>({status:t.value,value:o})):A);F.assertNever(i)}}Ie.create=(s,e,t)=>new Ie({schema:s,typeName:T.ZodEffects,effect:e,...P(t)}),Ie.createWithPreprocess=(s,e,t)=>new Ie({schema:e,effect:{type:"preprocess",transform:s},typeName:T.ZodEffects,...P(t)});class we extends N{_parse(e){return this._getType(e)===w.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}we.create=(s,e)=>new we({innerType:s,typeName:T.ZodOptional,...P(e)});class Ne extends N{_parse(e){return this._getType(e)===w.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ne.create=(s,e)=>new Ne({innerType:s,typeName:T.ZodNullable,...P(e)});class wt extends N{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===w.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}wt.create=(s,e)=>new wt({innerType:s,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class St extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return pt(i)?i.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}St.create=(s,e)=>new St({innerType:s,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class Js extends N{_parse(e){if(this._getType(e)!==w.nan){const r=this._getOrReturnCtx(e);return k(r,{code:p.invalid_type,expected:w.nan,received:r.parsedType}),A}return{status:"valid",value:e.data}}}Js.create=s=>new Js({typeName:T.ZodNaN,...P(s)});class Xs extends N{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Xt extends N{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?A:n.status==="dirty"?(t.dirty(),Ge(n.value)):this._def.out._parseAsync({data:n.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?A:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,t){return new Xt({in:e,out:t,typeName:T.ZodPipeline})}}class _t extends N{_parse(e){const t=this._def.innerType._parse(e),r=i=>(Re(i)&&(i.value=Object.freeze(i.value)),i);return pt(t)?t.then(i=>r(i)):r(t)}unwrap(){return this._def.innerType}}_t.create=(s,e)=>new _t({innerType:s,typeName:T.ZodReadonly,...P(e)});var T;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(T||(T={}));const $=be.create,te=Oe.create,Be=Ht.create;Ae.create;const Ke=he.create,H=Y.create,Qe=mt.create,Ks=qt.create;yt.create,Me.create;const Si=vt.create,$e=bt.create,et=Pe.create;kt.create,we.create,Ne.create;const xt=Qe([te(),$()]),Kt=H({x:xt.optional().default(0),y:xt.optional().default(0),width:xt.optional(),height:xt.optional(),fit:et(["contain","cover","fill","none"]).optional(),horizontalAlign:et(["left","center","right"]).optional(),verticalAlign:et(["top","center","bottom"]).optional()}),_i=H({id:$(),start:te(),end:te(),text:$().optional()}),xi=Ks("type",[H({type:$e("image"),src:$()}),H({type:$e("audio"),src:$(),channel:et(["vo","sfx","music"]).optional().default("vo")}),H({type:$e("vtt"),src:$()}),H({type:$e("html"),src:$()})]),Ci=Qe([H({play:$()}),H({toggleClass:H({target:$(),className:$()})})]),Ai=H({id:$(),type:$e("text"),layout:Kt.optional().default({}),html:$().optional(),htmlSrc:$().optional(),style:H({fontFamily:$().optional(),fontSize:$().optional(),color:$().optional(),textAlign:et(["left","center","right"]).optional(),lineHeight:Qe([$(),te()]).optional(),fontWeight:$().optional(),fontStyle:$().optional()}).optional()}),Ti=H({id:$(),type:$e("image"),asset:$(),layout:Kt.optional().default({}),className:$().optional()}),Ei=H({id:$(),type:$e("hotspot"),layout:Kt.optional().default({}),onTap:Ke(Ci).optional().default([]),ariaLabel:$().optional()}),Li=Ks("type",[Ai,Ti,Ei]),Mi=H({id:$(),background:H({asset:$().optional(),color:$().optional(),innerColor:$().optional()}).optional(),readAloud:H({audio:$(),cues:Qe([$(),Ke(_i)]).optional()}).optional(),blocks:Ke(Li).optional().default([])}),Qs=H({id:$(),title:$().optional(),pageSize:H({width:te().positive(),height:te().positive()}),frontCover:Be().optional().default(!1),backCover:Be().optional().default(!1),hardback:Be().optional().default(!1),coverSize:H({width:te().positive(),height:te().positive()}).optional(),guides:H({marginTop:te().nonnegative().default(48),marginRight:te().nonnegative().default(48),marginBottom:te().nonnegative().default(48),marginLeft:te().nonnegative().default(48),gutterBand:te().nonnegative().default(8),showGuides:Be().default(!0),snapGuides:Be().default(!0),snapObjects:Be().default(!0)}).optional(),fonts:Ke(H({family:$(),src:$(),weight:Qe([$(),te()]).optional(),style:$().optional()})).optional().default([]),assets:Si(xi).optional().default({}),pages:Ke(Mi).min(1)});function ze(s){return Qs.parse(s)}function Qt(s){const e=s.replace(/^\uFEFF/,"").replace(/\r\n/g,`
2
+ `).trim();if(!e.startsWith("WEBVTT"))throw new Error("Invalid WebVTT: missing WEBVTT header");const r=e.slice(e.indexOf(`
3
+ `)+1).split(/\n\n+/),i=[];let n=0;for(const a of r){const o=a.split(`
4
+ `).map(b=>b.trim()).filter(b=>b.length>0&&!b.startsWith("NOTE"));if(o.length===0)continue;const l=o.findIndex(b=>b.includes("-->"));if(l===-1)continue;const d=l>0?o[0]:void 0,c=o[l],h=o.slice(l+1),u=c.split("-->").map(b=>b.trim().split(/\s+/)[0]);if(u.length<2)continue;const g=er(u[0]),x=er(u[1]),v=h.join(" ").trim(),f=d||v||`cue-${n++}`;i.push({id:f,start:g,end:x,text:v||void 0})}return i}function er(s){const e=s.trim().split(":");if(e.length===3){const[t,r,i]=e;return Number(t)*3600+Number(r)*60+Number(i)}if(e.length===2){const[t,r]=e;return Number(t)*60+Number(r)}return Number(s)}function je(s,e){if(/^(?:[a-z]+:)?\/\//i.test(e)||e.startsWith("data:")||e.startsWith("blob:")||!s)return e;try{return new URL(e,es(s)).href}catch{return`${es(s)}${e.replace(/^\//,"")}`}}function es(s){return s.endsWith("/")||s.includes("?")?s.endsWith("/")?s:`${s}/`:/\.[a-z0-9]+$/i.test(s.split("/").pop()??"")?s.replace(/[^/]+$/,""):`${s}/`}function Pi(s){try{const e=new URL(s,typeof location<"u"?location.href:"http://local/");e.hash="";const t=e.pathname;return e.pathname=t.replace(/[^/]+$/,""),e.href}catch{return es(s.replace(/[^/]+$/,""))}}async function tt(s,e){typeof document>"u"||!("fonts"in document)||await Promise.all(s.fonts.map(async t=>{const r=je(e,t.src),n=await new FontFace(t.family,`url(${JSON.stringify(r)})`,{weight:t.weight!=null?String(t.weight):"normal",style:t.style??"normal"}).load();document.fonts.add(n)}))}var D=Uint8Array,se=Uint16Array,ts=Int32Array,Ct=new D([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),At=new D([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ss=new D([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tr=function(s,e){for(var t=new se(31),r=0;r<31;++r)t[r]=e+=1<<s[r-1];for(var i=new ts(t[30]),r=1;r<30;++r)for(var n=t[r];n<t[r+1];++n)i[n]=n-t[r]<<5|r;return{b:t,r:i}},sr=tr(Ct,2),rr=sr.b,rs=sr.r;rr[28]=258,rs[258]=28;for(var ir=tr(At,0),Ii=ir.b,nr=ir.r,is=new se(32768),B=0;B<32768;++B){var Te=(B&43690)>>1|(B&21845)<<1;Te=(Te&52428)>>2|(Te&13107)<<2,Te=(Te&61680)>>4|(Te&3855)<<4,is[B]=((Te&65280)>>8|(Te&255)<<8)>>1}for(var ue=(function(s,e,t){for(var r=s.length,i=0,n=new se(e);i<r;++i)s[i]&&++n[s[i]-1];var a=new se(e);for(i=1;i<e;++i)a[i]=a[i-1]+n[i-1]<<1;var o;if(t){o=new se(1<<e);var l=15-e;for(i=0;i<r;++i)if(s[i])for(var d=i<<4|s[i],c=e-s[i],h=a[s[i]-1]++<<c,u=h|(1<<c)-1;h<=u;++h)o[is[h]>>l]=d}else for(o=new se(r),i=0;i<r;++i)s[i]&&(o[i]=is[a[s[i]-1]++]>>15-s[i]);return o}),Ee=new D(288),B=0;B<144;++B)Ee[B]=8;for(var B=144;B<256;++B)Ee[B]=9;for(var B=256;B<280;++B)Ee[B]=7;for(var B=280;B<288;++B)Ee[B]=8;for(var st=new D(32),B=0;B<32;++B)st[B]=5;var Ni=ue(Ee,9,0),$i=ue(Ee,9,1),Fi=ue(st,5,0),Ri=ue(st,5,1),ns=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},ce=function(s,e,t){var r=e/8|0;return(s[r]|s[r+1]<<8)>>(e&7)&t},as=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},os=function(s){return(s+7)/8|0},rt=function(s,e,t){return(e==null||e<0)&&(e=0),(t==null||t>s.length)&&(t=s.length),new D(s.subarray(e,t))},Oi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Q=function(s,e,t){var r=new Error(e||Oi[s]);if(r.code=s,Error.captureStackTrace&&Error.captureStackTrace(r,Q),!t)throw r;return r},Vi=function(s,e,t,r){var i=s.length,n=r?r.length:0;if(!i||e.f&&!e.l)return t||new D(0);var a=!t,o=a||e.i!=2,l=e.i;a&&(t=new D(i*3));var d=function(ut){var ft=t.length;if(ut>ft){var Ye=new D(Math.max(ft*2,ut));Ye.set(t),t=Ye}},c=e.f||0,h=e.p||0,u=e.b||0,g=e.l,x=e.d,v=e.m,f=e.n,b=i*8;do{if(!g){c=ce(s,h,1);var _=ce(s,h+1,3);if(h+=3,_)if(_==1)g=$i,x=Ri,v=9,f=5;else if(_==2){var L=ce(s,h,31)+257,O=ce(s,h+10,15)+4,I=L+ce(s,h+5,31)+1;h+=14;for(var M=new D(I),W=new D(19),Z=0;Z<O;++Z)W[ss[Z]]=ce(s,h+Z*3,7);h+=O*3;for(var G=ns(W),oe=(1<<G)-1,V=ue(W,G,1),Z=0;Z<I;){var j=V[ce(s,h,oe)];h+=j&15;var m=j>>4;if(m<16)M[Z++]=m;else{var q=0,z=0;for(m==16?(z=3+ce(s,h,3),h+=2,q=M[Z-1]):m==17?(z=3+ce(s,h,7),h+=3):m==18&&(z=11+ce(s,h,127),h+=7);z--;)M[Z++]=q}}var X=M.subarray(0,L),K=M.subarray(L);v=ns(X),f=ns(K),g=ue(X,v,1),x=ue(K,f,1)}else Q(1);else{var m=os(h)+4,E=s[m-4]|s[m-3]<<8,R=m+E;if(R>i){l&&Q(0);break}o&&d(u+E),t.set(s.subarray(m,R),u),e.b=u+=E,e.p=h=R*8,e.f=c;continue}if(h>b){l&&Q(0);break}}o&&d(u+131072);for(var ht=(1<<v)-1,le=(1<<f)-1,_e=h;;_e=h){var q=g[as(s,h)&ht],re=q>>4;if(h+=q&15,h>b){l&&Q(0);break}if(q||Q(2),re<256)t[u++]=re;else if(re==256){_e=h,g=null;break}else{var ie=re-254;if(re>264){var Z=re-257,U=Ct[Z];ie=ce(s,h,(1<<U)-1)+rr[Z],h+=U}var me=x[as(s,h)&le],We=me>>4;me||Q(3),h+=me&15;var K=Ii[We];if(We>3){var U=At[We];K+=as(s,h)&(1<<U)-1,h+=U}if(h>b){l&&Q(0);break}o&&d(u+131072);var qe=u+ie;if(u<K){var Bt=n-K,zt=Math.min(K,qe);for(Bt+u<0&&Q(3);u<zt;++u)t[u]=r[Bt+u]}for(;u<qe;++u)t[u]=t[u-K]}}e.l=g,e.p=_e,e.b=u,e.f=c,g&&(c=1,e.m=v,e.d=x,e.n=f)}while(!c);return u!=t.length&&a?rt(t,0,u):t.subarray(0,u)},Se=function(s,e,t){t<<=e&7;var r=e/8|0;s[r]|=t,s[r+1]|=t>>8},it=function(s,e,t){t<<=e&7;var r=e/8|0;s[r]|=t,s[r+1]|=t>>8,s[r+2]|=t>>16},ls=function(s,e){for(var t=[],r=0;r<s.length;++r)s[r]&&t.push({s:r,f:s[r]});var i=t.length,n=t.slice();if(!i)return{t:cr,l:0};if(i==1){var a=new D(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(R,L){return R.f-L.f}),t.push({s:-1,f:25001});var o=t[0],l=t[1],d=0,c=1,h=2;for(t[0]={s:-1,f:o.f+l.f,l:o,r:l};c!=i-1;)o=t[t[d].f<t[h].f?d++:h++],l=t[d!=c&&t[d].f<t[h].f?d++:h++],t[c++]={s:-1,f:o.f+l.f,l:o,r:l};for(var u=n[0].s,r=1;r<i;++r)n[r].s>u&&(u=n[r].s);var g=new se(u+1),x=cs(t[c-1],g,0);if(x>e){var r=0,v=0,f=x-e,b=1<<f;for(n.sort(function(L,O){return g[O.s]-g[L.s]||L.f-O.f});r<i;++r){var _=n[r].s;if(g[_]>e)v+=b-(1<<x-g[_]),g[_]=e;else break}for(v>>=f;v>0;){var m=n[r].s;g[m]<e?v-=1<<e-g[m]++-1:++r}for(;r>=0&&v;--r){var E=n[r].s;g[E]==e&&(--g[E],++v)}x=e}return{t:new D(g),l:x}},cs=function(s,e,t){return s.s==-1?Math.max(cs(s.l,e,t+1),cs(s.r,e,t+1)):e[s.s]=t},ar=function(s){for(var e=s.length;e&&!s[--e];);for(var t=new se(++e),r=0,i=s[0],n=1,a=function(l){t[r++]=l},o=1;o<=e;++o)if(s[o]==i&&o!=e)++n;else{if(!i&&n>2){for(;n>138;n-=138)a(32754);n>2&&(a(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(a(i),--n;n>6;n-=6)a(8304);n>2&&(a(n-3<<5|8208),n=0)}for(;n--;)a(i);n=1,i=s[o]}return{c:t.subarray(0,r),n:e}},nt=function(s,e){for(var t=0,r=0;r<e.length;++r)t+=s[r]*e[r];return t},or=function(s,e,t){var r=t.length,i=os(e+2);s[i]=r&255,s[i+1]=r>>8,s[i+2]=s[i]^255,s[i+3]=s[i+1]^255;for(var n=0;n<r;++n)s[i+n+4]=t[n];return(i+4+r)*8},lr=function(s,e,t,r,i,n,a,o,l,d,c){Se(e,c++,t),++i[256];for(var h=ls(i,15),u=h.t,g=h.l,x=ls(n,15),v=x.t,f=x.l,b=ar(u),_=b.c,m=b.n,E=ar(v),R=E.c,L=E.n,O=new se(19),I=0;I<_.length;++I)++O[_[I]&31];for(var I=0;I<R.length;++I)++O[R[I]&31];for(var M=ls(O,7),W=M.t,Z=M.l,G=19;G>4&&!W[ss[G-1]];--G);var oe=d+5<<3,V=nt(i,Ee)+nt(n,st)+a,j=nt(i,u)+nt(n,v)+a+14+3*G+nt(O,W)+2*O[16]+3*O[17]+7*O[18];if(l>=0&&oe<=V&&oe<=j)return or(e,c,s.subarray(l,l+d));var q,z,X,K;if(Se(e,c,1+(j<V)),c+=2,j<V){q=ue(u,g,0),z=u,X=ue(v,f,0),K=v;var ht=ue(W,Z,0);Se(e,c,m-257),Se(e,c+5,L-1),Se(e,c+10,G-4),c+=14;for(var I=0;I<G;++I)Se(e,c+3*I,W[ss[I]]);c+=3*G;for(var le=[_,R],_e=0;_e<2;++_e)for(var re=le[_e],I=0;I<re.length;++I){var ie=re[I]&31;Se(e,c,ht[ie]),c+=W[ie],ie>15&&(Se(e,c,re[I]>>5&127),c+=re[I]>>12)}}else q=Ni,z=Ee,X=Fi,K=st;for(var I=0;I<o;++I){var U=r[I];if(U>255){var ie=U>>18&31;it(e,c,q[ie+257]),c+=z[ie+257],ie>7&&(Se(e,c,U>>23&31),c+=Ct[ie]);var me=U&31;it(e,c,X[me]),c+=K[me],me>3&&(it(e,c,U>>5&8191),c+=At[me])}else it(e,c,q[U]),c+=z[U]}return it(e,c,q[256]),c+z[256]},Bi=new ts([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cr=new D(0),zi=function(s,e,t,r,i,n){var a=n.z||s.length,o=new D(r+a+5*(1+Math.ceil(a/7e3))+i),l=o.subarray(r,o.length-i),d=n.l,c=(n.r||0)&7;if(e){c&&(l[0]=n.r>>3);for(var h=Bi[e-1],u=h>>13,g=h&8191,x=(1<<t)-1,v=n.p||new se(32768),f=n.h||new se(x+1),b=Math.ceil(t/3),_=2*b,m=function(Ns){return(s[Ns]^s[Ns+1]<<b^s[Ns+2]<<_)&x},E=new ts(25e3),R=new se(288),L=new se(32),O=0,I=0,M=n.i||0,W=0,Z=n.w||0,G=0;M+2<a;++M){var oe=m(M),V=M&32767,j=f[oe];if(v[V]=j,f[oe]=V,Z<=M){var q=a-M;if((O>7e3||W>24576)&&(q>423||!d)){c=lr(s,l,0,E,R,L,I,W,G,M-G,c),W=O=I=0,G=M;for(var z=0;z<286;++z)R[z]=0;for(var z=0;z<30;++z)L[z]=0}var X=2,K=0,ht=g,le=V-j&32767;if(q>2&&oe==m(M-le))for(var _e=Math.min(u,q)-1,re=Math.min(32767,M),ie=Math.min(258,q);le<=re&&--ht&&V!=j;){if(s[M+X]==s[M+X-le]){for(var U=0;U<ie&&s[M+U]==s[M+U-le];++U);if(U>X){if(X=U,K=le,U>_e)break;for(var me=Math.min(le,U-2),We=0,z=0;z<me;++z){var qe=M-le+z&32767,Bt=v[qe],zt=qe-Bt&32767;zt>We&&(We=zt,j=qe)}}}V=j,j=v[V],le+=V-j&32767}if(K){E[W++]=268435456|rs[X]<<18|nr[K];var ut=rs[X]&31,ft=nr[K]&31;I+=Ct[ut]+At[ft],++R[257+ut],++L[ft],Z=M+X,++O}else E[W++]=s[M],++R[s[M]]}}for(M=Math.max(M,Z);M<a;++M)E[W++]=s[M],++R[s[M]];c=lr(s,l,d,E,R,L,I,W,G,M-G,c),d||(n.r=c&7|l[c/8|0]<<3,c-=7,n.h=f,n.p=v,n.i=M,n.w=Z)}else{for(var M=n.w||0;M<a+d;M+=65535){var Ye=M+65535;Ye>=a&&(l[c/8|0]=d,Ye=a),c=or(l,c+1,s.subarray(M,Ye))}n.i=a}return rt(o,0,r+os(c)+i)},ji=(function(){for(var s=new Int32Array(256),e=0;e<256;++e){for(var t=e,r=9;--r;)t=(t&1&&-306674912)^t>>>1;s[e]=t}return s})(),Zi=function(){var s=-1;return{p:function(e){for(var t=s,r=0;r<e.length;++r)t=ji[t&255^e[r]]^t>>>8;s=t},d:function(){return~s}}},Ui=function(s,e,t,r,i){if(!i&&(i={l:1},e.dictionary)){var n=e.dictionary.subarray(-32768),a=new D(n.length+s.length);a.set(n),a.set(s,n.length),s=a,i.w=n.length}return zi(s,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(s.length)))*1.5):20:12+e.mem,t,r,i)},dr=function(s,e){var t={};for(var r in s)t[r]=s[r];for(var r in e)t[r]=e[r];return t},fe=function(s,e){return s[e]|s[e+1]<<8},ae=function(s,e){return(s[e]|s[e+1]<<8|s[e+2]<<16|s[e+3]<<24)>>>0},ds=function(s,e){return ae(s,e)+ae(s,e+4)*4294967296},J=function(s,e,t){for(;t;++e)s[e]=t,t>>>=8};function Hi(s,e){return Ui(s,e||{},0,0)}function Di(s,e){return Vi(s,{i:2},e&&e.out,e&&e.dictionary)}var hr=function(s,e,t,r){for(var i in s){var n=s[i],a=e+i,o=r;Array.isArray(n)&&(o=dr(r,n[1]),n=n[0]),ArrayBuffer.isView(n)?t[a]=[n,o]:(t[a+="/"]=[new D(0),o],hr(n,a,t,r))}},ur=typeof TextEncoder<"u"&&new TextEncoder,hs=typeof TextDecoder<"u"&&new TextDecoder,Wi=0;try{hs.decode(cr,{stream:!0}),Wi=1}catch{}var qi=function(s){for(var e="",t=0;;){var r=s[t++],i=(r>127)+(r>223)+(r>239);if(t+i>s.length)return{s:e,r:rt(s,t-1)};i?i==3?(r=((r&15)<<18|(s[t++]&63)<<12|(s[t++]&63)<<6|s[t++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?e+=String.fromCharCode((r&31)<<6|s[t++]&63):e+=String.fromCharCode((r&15)<<12|(s[t++]&63)<<6|s[t++]&63):e+=String.fromCharCode(r)}};function us(s,e){var t;if(ur)return ur.encode(s);for(var r=s.length,i=new D(s.length+(s.length>>1)),n=0,a=function(d){i[n++]=d},t=0;t<r;++t){if(n+5>i.length){var o=new D(n+8+(r-t<<1));o.set(i),i=o}var l=s.charCodeAt(t);l<128||e?a(l):l<2048?(a(192|l>>6),a(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|s.charCodeAt(++t)&1023,a(240|l>>18),a(128|l>>12&63),a(128|l>>6&63),a(128|l&63)):(a(224|l>>12),a(128|l>>6&63),a(128|l&63))}return rt(i,0,n)}function fr(s,e){if(e){for(var t="",r=0;r<s.length;r+=16384)t+=String.fromCharCode.apply(null,s.subarray(r,r+16384));return t}else{if(hs)return hs.decode(s);var i=qi(s),n=i.s,t=i.r;return t.length&&Q(8),n}}var Yi=function(s,e){return e+30+fe(s,e+26)+fe(s,e+28)},Gi=function(s,e,t){var r=fe(s,e+28),i=fe(s,e+30),n=fr(s.subarray(e+46,e+46+r),!(fe(s,e+8)&2048)),a=e+46+r,o=Ji(s,a,i,t,ae(s,e+20),ae(s,e+24),ae(s,e+42)),l=o[0],d=o[1],c=o[2];return[fe(s,e+10),l,d,n,a+i+fe(s,e+32),c]},Ji=function(s,e,t,r,i,n,a){var o=i==4294967295,l=n==4294967295,d=a==4294967295,c=e+t,h=o+l+d;if(r&&h){for(;e+4<c;e+=4+fe(s,e+2))if(fe(s,e)==1)return[o?ds(s,e+4+8*l):i,l?ds(s,e+4):n,d?ds(s,e+4+8*(l+o)):a,1];r<2&&Q(13)}return[i,n,a,0]},fs=function(s){var e=0;if(s)for(var t in s){var r=s[t].length;r>65535&&Q(9),e+=r+4}return e},pr=function(s,e,t,r,i,n,a,o){var l=r.length,d=t.extra,c=o&&o.length,h=fs(d);J(s,e,a!=null?33639248:67324752),e+=4,a!=null&&(s[e++]=20,s[e++]=t.os),s[e]=20,e+=2,s[e++]=t.flag<<1|(n<0&&8),s[e++]=i&&8,s[e++]=t.compression&255,s[e++]=t.compression>>8;var u=new Date(t.mtime==null?Date.now():t.mtime),g=u.getFullYear()-1980;if((g<0||g>119)&&Q(10),J(s,e,g<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,n!=-1&&(J(s,e,t.crc),J(s,e+4,n<0?-n-2:n),J(s,e+8,t.size)),J(s,e+12,l),J(s,e+14,h),e+=16,a!=null&&(J(s,e,c),J(s,e+6,t.attrs),J(s,e+10,a),e+=14),s.set(r,e),e+=l,h)for(var x in d){var v=d[x],f=v.length;J(s,e,+x),J(s,e+2,f),s.set(v,e+4),e+=4+f}return c&&(s.set(o,e),e+=c),e},Xi=function(s,e,t,r,i){J(s,e,101010256),J(s,e+8,t),J(s,e+10,t),J(s,e+12,r),J(s,e+16,i)};function Ki(s,e){e||(e={});var t={},r=[];hr(s,"",t,e);var i=0,n=0;for(var a in t){var o=t[a],l=o[0],d=o[1],c=d.level==0?0:8,h=us(a),u=h.length,g=d.comment,x=g&&us(g),v=x&&x.length,f=fs(d.extra);u>65535&&Q(11);var b=c?Hi(l,d):l,_=b.length,m=Zi();m.p(l),r.push(dr(d,{size:l.length,crc:m.d(),c:b,f:h,m:x,u:u!=a.length||x&&g.length!=v,o:i,compression:c})),i+=30+u+f+_,n+=76+2*(u+f)+(v||0)+_}for(var E=new D(n+22),R=i,L=n-i,O=0;O<r.length;++O){var h=r[O];pr(E,h.o,h,h.f,h.u,h.c.length);var I=30+h.f.length+fs(h.extra);E.set(h.c,h.o+I),pr(E,i,h,h.f,h.u,h.c.length,h.o,h.m),i+=16+I+(h.m?h.m.length:0)}return Xi(E,i,r.length,L,R),E}function Qi(s,e){for(var t={},r=s.length-22;ae(s,r)!=101010256;--r)(!r||s.length-r>65558)&&Q(13);var i=fe(s,r+8);if(!i)return{};var n=ae(s,r+16),a=ae(s,r-20)==117853008;if(a){var o=ae(s,r-12);a=ae(s,o)==101075792,a&&(i=ae(s,o+32),n=ae(s,o+48))}for(var l=0;l<i;++l){var d=Gi(s,n,a),c=d[0],h=d[1],u=d[2],g=d[3],x=d[4],v=d[5],f=Yi(s,v);n=x,c?c==8?t[g]=Di(s.subarray(f,f+h),{out:new D(u)}):Q(14,"unknown compression type "+c):t[g]=rt(s,f,f+h)}return t}const gr=[80,75];function ps(s){return s.length>=2&&s[0]===gr[0]&&s[1]===gr[1]}function gs(s){const e=s instanceof Uint8Array?s:new Uint8Array(s);if(!ps(e))throw new Error("Not a ZIP archive");const t=Qi(e),r=new Map;for(const[i,n]of Object.entries(t))!n||i.endsWith("/")||r.set(pe(i),n);return r}function pe(s){return s.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function at(s,e){const t=Tt(s,e);if(!t)throw new Error(`Missing zip entry: ${e}`);return fr(t)}function Tt(s,e){const t=pe(e);if(s.has(t))return s.get(t);const r=t.toLowerCase();for(const[i,n]of s)if(i.toLowerCase()===r)return n}function en(s){return[...s.keys()]}function tn(s){var t;switch(((t=s.split(".").pop())==null?void 0:t.toLowerCase())??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"ogg":return"audio/ogg";case"m4a":return"audio/mp4";case"webm":return"audio/webm";case"vtt":return"text/vtt";case"html":case"xhtml":case"htm":return"application/xhtml+xml";case"css":return"text/css";case"json":return"application/json";case"woff":return"font/woff";case"woff2":return"font/woff2";case"ttf":return"font/ttf";case"otf":return"font/otf";default:return"application/octet-stream"}}function mr(s,e){const t=new Uint8Array(s.byteLength);t.set(s);const r=new Blob([t.buffer],{type:tn(e)});return URL.createObjectURL(r)}async function sn(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch ${s}: ${e.status}`);return e.arrayBuffer()}function rn(s){return ms(gs(s))}function ms(s){const e=at(s,"META-INF/container.xml"),t=ge(e,/full-path\s*=\s*"([^"]+)"/i);if(!t)throw new Error("Invalid EPUB: missing rootfile in container.xml");const r=pe(t),i=r.includes("/")?r.replace(/\/[^/]+$/,"/"):"",n=at(s,r),a=br(n,"dc:title")||br(n,"title")||"EPUB Story",o=ln(n)??{width:768,height:1024},l=an(n,i),d=on(n),c=[],h=new Map,u=f=>{const b=pe(f);if(h.has(b))return h.get(b);const _=Tt(s,b);if(!_)throw new Error(`EPUB missing file: ${b}`);const m=mr(_,b);return c.push(m),h.set(b,m),m},g={},x=[];if(d.forEach((f,b)=>{const _=l.get(f);if(!_||!/html|xml/i.test(_.mediaType)&&!_.href.match(/\.x?html?$/i))return;const m=_.href,E=at(s,m),R=m.includes("/")?m.replace(/\/[^/]+$/,"/"):"",L=`page-${b+1}`,O=dn(E),{html:I,imageHrefs:M}=hn(O,R,V=>{const j=pe(V.includes(":")?V:`${R}${V}`);try{return u(j)}catch{return V}}),W=[{id:`${L}-text`,type:"text",layout:{x:"5%",y:"5%",width:"90%",height:"90%"},html:I}],Z=M[0];let G;if(Z){const V=`img-${b}-0`;g[V]={type:"image",src:u(Z)},G={asset:V,color:"#ffffff"}}else G={color:"#ffffff"};let oe;if(_.mediaOverlay){const V=l.get(_.mediaOverlay);if(V){const j=cn(at(s,V.href),V.href);if(j.audioHref){const q=`vo-${b}`,z=pe(j.audioHref.includes("/")||j.audioHref.startsWith(".")?vr(V.href,j.audioHref):`${i}${j.audioHref}`);g[q]={type:"audio",src:u(z),channel:"vo"};const X=j.cues;X.length?oe={audio:q,cues:X}:oe={audio:q}}}}x.push({id:L,background:G,readAloud:oe,blocks:W})}),x.length===0)throw new Error("Invalid EPUB: no spine HTML documents found");return{story:ze({id:`epub-${un(a)}`,title:a,pageSize:o,fonts:[],assets:g,pages:x}),blobUrls:c}}function nn(s){return!!Tt(s,"META-INF/container.xml")}function an(s,e){const t=new Map,r=/<item\b[^>]*>/gi;let i;for(;i=r.exec(s);){const n=i[0],a=ge(n,/\bid\s*=\s*"([^"]+)"/i),o=ge(n,/\bhref\s*=\s*"([^"]+)"/i),l=ge(n,/\bmedia-type\s*=\s*"([^"]+)"/i)??"",d=ge(n,/\bmedia-overlay\s*=\s*"([^"]+)"/i)??void 0,c=ge(n,/\bproperties\s*=\s*"([^"]+)"/i)??void 0;!a||!o||t.set(a,{id:a,href:pe(`${e}${o}`),mediaType:l,mediaOverlay:d,properties:c})}return t}function on(s){const e=s.match(/<spine\b[^>]*>([\s\S]*?)<\/spine>/i);if(!e)return[];const t=[],r=/<itemref\b[^>]*\bidref\s*=\s*"([^"]+)"[^>]*>/gi;let i;for(;i=r.exec(e[1]);)t.push(i[1]);return t}function ln(s){const e=s.match(/<meta\b[^>]*name\s*=\s*"viewport"[^>]*content\s*=\s*"([^"]+)"[^>]*>/i)||s.match(/<meta\b[^>]*content\s*=\s*"([^"]+)"[^>]*name\s*=\s*"viewport"[^>]*>/i);if(!e)return null;const t=e[1],r=t.match(/width\s*=\s*(\d+)/i),i=t.match(/height\s*=\s*(\d+)/i);return!r||!i?null:{width:Number(r[1]),height:Number(i[1])}}function cn(s,e){const t=[];let r;const i=ge(s,/<audio\b[^>]*\bsrc\s*=\s*"([^"]+)"/i);i&&(r=vr(e,i));const n=/<par\b[^>]*>([\s\S]*?)<\/par>/gi;let a,o=0;for(;a=n.exec(s);){const l=a[1],d=ge(l,/<text\b[^>]*\bsrc\s*=\s*"([^"]+)"/i),c=ge(l,/\bclipBegin\s*=\s*"([^"]+)"/i),h=ge(l,/\bclipEnd\s*=\s*"([^"]+)"/i),u=d!=null&&d.includes("#")?d.split("#")[1]:`cue-${o}`;c==null||h==null||(t.push({id:u||`cue-${o}`,start:yr(c),end:yr(h)}),o+=1)}return{audioHref:r,cues:t}}function yr(s){const e=s.replace(/^npt=/i,"").trim();if(/^\d+(\.\d+)?$/.test(e))return Number(e);const t=e.split(":").map(Number);return t.length===3?t[0]*3600+t[1]*60+t[2]:t.length===2?t[0]*60+t[1]:0}function dn(s){const e=s.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);return e?e[1].trim():s}function hn(s,e,t){const r=[];return{html:s.replace(/\b(src|href)\s*=\s*["']([^"']+)["']/gi,(n,a,o)=>{if(/^(?:[a-z]+:|#|data:)/i.test(o))return n;const l=pe(`${e}${o}`);/\.(png|jpe?g|gif|webp|svg)$/i.test(o)&&r.push(l);const d=t(o);return`${a}="${d}"`}),imageHrefs:r}}function vr(s,e){if(/^(?:[a-z]+:)/i.test(e))return e;const r=((s.includes("/")?s.replace(/\/[^/]+$/,"/"):"")+e).split("/"),i=[];for(const n of r)!n||n==="."||(n===".."?i.pop():i.push(n));return i.join("/")}function ge(s,e){const t=s.match(e);return t?t[1]:null}function br(s,e){const t=new RegExp(`<${e.replace(":",":")}[^>]*>([^<]*)</${e.replace(":",":")}>`,"i"),r=s.match(t);return r?r[1].trim():null}function un(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"book"}function ys(s){const e=en(s),t=e.find(i=>i==="story.json"||i.toLowerCase()==="story.json");if(t)return t;const r=e.filter(i=>i.toLowerCase().endsWith("/story.json")||i.toLowerCase()==="story.json").sort((i,n)=>i.length-n.length);if(r[0])return r[0];throw new Error("Invalid .fanci package: missing story.json")}function vs(s){const e=ys(s),t=e.includes("/")?e.replace(/\/[^/]+$/,"/"):"",r=ze(JSON.parse(at(s,e))),i=new Map,n=[];for(const[a,o]of s){if(a===e)continue;const l=mr(o,a);n.push(l),i.set(a,l),t&&a.startsWith(t)&&i.set(a.slice(t.length),l)}return gn(r,a=>pn(i,t,a)),{story:r,pathUrls:i,blobUrls:n,storyDir:t}}function fn(s){return vs(gs(s))}function pn(s,e,t){const r=pe(t);if(s.has(r))return s.get(r);const i=pe(`${e}${r}`);if(s.has(i))return s.get(i);const n=r.toLowerCase();for(const[a,o]of s)if(a.toLowerCase()===n||a.toLowerCase().endsWith(`/${n}`))return o}function gn(s,e){for(const t of s.fonts){const r=e(t.src);r&&(t.src=r)}for(const t of Object.values(s.assets)){const r=e(t.src);r&&(t.src=r)}for(const t of s.pages)for(const r of t.blocks)if(r.type==="text"&&r.htmlSrc){const i=e(r.htmlSrc);i&&(r.htmlSrc=i)}}function mn(s){if(Tt(s,"META-INF/container.xml"))return!1;try{return ys(s),!0}catch{return!1}}const Et=".fanci";function bs(s){const e=s.split("?")[0].split("#")[0],t=e.split("/").pop()??e,r=t.lastIndexOf(".");return r>=0?t.slice(r).toLowerCase():""}function yn(s,e){if(typeof s=="object"&&s!==null&&!(s instanceof Blob)&&!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)&&!ArrayBuffer.isView(s)&&("story"in s||"id"in s&&"pages"in s))return"object";const t=e??(typeof s=="string"?s:s instanceof File?s.name:""),r=bs(t);return r===Et||r===".fanci.zip"?"fanci":r===".epub"?"epub":"json"}async function vn(s){return s instanceof ArrayBuffer?s:s instanceof Uint8Array?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s.arrayBuffer()}async function Lt(s,e){const t=typeof e=="string"?{baseUrl:e}:e??{},r=t.onProgress??(()=>{});if(kn(s)){r({stage:"parse",progress:.1,detail:"story object"});const i=ze(s),n=t.baseUrl??(typeof location<"u"?location.href:"");r({stage:"assets",progress:.2,detail:"fonts"}),await tt(i,n);const a=await ot(i,n,r,.25,1);return r({stage:"complete",progress:1}),{story:i,baseUrl:n,assets:a,blobUrls:[],kind:"object"}}if(typeof s=="object"&&s!==null&&"story"in s&&!kr(s)){const i=s;return Lt(i.story,{baseUrl:t.baseUrl??i.baseUrl,name:t.name,onProgress:t.onProgress})}if(typeof s=="string")return bn(s,t,r);if(kr(s)){r({stage:"fetch",progress:.05,detail:"bytes"});const i=await vn(s),n=t.name??(s instanceof File?s.name:void 0)??"";return ks(i,n,t.baseUrl,r)}throw new Error("Unsupported story source")}async function bn(s,e,t){const r=bs(s),i=yn(s,e.name??s);if(t({stage:"fetch",progress:.02,detail:s}),r===Et||r===".epub"||i==="fanci"||i==="epub"){const u=await sn(s);return t({stage:"fetch",progress:.15,detail:"package downloaded"}),ks(u,e.name??s,e.baseUrl,t)}const n=await fetch(s);if(!n.ok)throw new Error(`Failed to load story: ${n.status} ${n.statusText}`);const a=await n.arrayBuffer(),o=new Uint8Array(a);if(ps(o))return t({stage:"fetch",progress:.15,detail:"zip downloaded"}),ks(a,e.name??s,e.baseUrl,t);t({stage:"parse",progress:.2,detail:"json"});const l=new TextDecoder().decode(o),d=ze(JSON.parse(l)),c=e.baseUrl??Pi(new URL(s,location.href).href);await tt(d,c);const h=await ot(d,c,t,.3,1);return t({stage:"complete",progress:1}),{story:d,baseUrl:c,assets:h,blobUrls:[],kind:"json"}}async function ks(s,e,t,r){const i=new Uint8Array(s),n=bs(e);if(ps(i)){r({stage:"unpack",progress:.2,detail:"unzip"});const d=gs(i);if(r({stage:"unpack",progress:.35,detail:`${d.size} entries`}),n===".epub"||nn(d)){r({stage:"parse",progress:.4,detail:"epub"});const{story:c,blobUrls:h}=ms(d);await tt(c,t??"");const u=await ot(c,t??"",r,.5,1);return r({stage:"complete",progress:1}),{story:c,baseUrl:t??"",assets:u,blobUrls:h,kind:"epub"}}if(n===Et||mn(d)){r({stage:"parse",progress:.4,detail:"fanci"});const{story:c,blobUrls:h}=vs(d);await tt(c,t??"");const u=await ot(c,t??"",r,.5,1);return r({stage:"complete",progress:1}),{story:c,baseUrl:t??"",assets:u,blobUrls:h,kind:"fanci"}}throw new Error("ZIP archive is neither a .fanci package (story.json) nor an EPUB (META-INF/container.xml)")}r({stage:"parse",progress:.25,detail:"json bytes"});const a=ze(JSON.parse(new TextDecoder().decode(i))),o=t??(typeof location<"u"?location.href:"");await tt(a,o);const l=await ot(a,o,r,.35,1);return r({stage:"complete",progress:1}),{story:a,baseUrl:o,assets:l,blobUrls:[],kind:"json"}}function kn(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Blob)&&!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)&&"id"in s&&"pages"in s&&"pageSize"in s}function kr(s){return s instanceof ArrayBuffer||s instanceof Uint8Array||s instanceof Blob||typeof File<"u"&&s instanceof File}async function ot(s,e,t,r,i){var x;const n=new Map,a=new Map,o=new Map,l=new Map,d=Object.entries(s.assets),c=[];for(const v of s.pages)for(const f of v.blocks)if(f.type==="text"&&f.htmlSrc&&!f.html&&c.push(async()=>{const b=je(e,f.htmlSrc);l.set(`htmlSrc:${f.id}`,await Mt(b))}),(x=v.readAloud)!=null&&x.cues&&typeof v.readAloud.cues=="string"){const b=v.readAloud.cues;s.assets[b]||c.push(async()=>{const _=je(e,b);try{o.set(b,Qt(await Mt(_)))}catch{}})}const h=d.length+c.length||1;let u=0;const g=v=>{u+=1;const f=u/h,b=r+(i-r)*Math.min(1,f);t({stage:"assets",progress:b,count:u,total:h,detail:v})};return await Promise.all(d.map(async([v,f])=>{const b=je(e,f.src);f.type==="image"?n.set(v,await wn(b)):f.type==="audio"?a.set(v,{url:b,channel:f.channel??"vo"}):f.type==="vtt"?o.set(v,Qt(await Mt(b))):f.type==="html"&&l.set(v,await Mt(b)),g(v)})),await Promise.all(c.map(async v=>{await v(),g("fragment")})),d.length===0&&c.length===0&&t({stage:"assets",progress:i,count:0,total:0,detail:"none"}),{images:n,audioUrls:a,cues:o,html:l}}function wn(s){return new Promise((e,t)=>{const r=new Image;r.decoding="async",r.onload=()=>e(r),r.onerror=()=>t(new Error(`Failed to load image: ${s}`)),r.src=s})}async function Mt(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to load ${s}: ${e.status}`);return e.text()}function ws(s){for(const e of s.blobUrls)try{URL.revokeObjectURL(e)}catch{}s.blobUrls.length=0}const wr="auto",Sr=900;function _r(s,e,t,r){return s==="responsive"?e>=t?"two-page":"single":s==="auto"?e>=r?"two-page":"single":s}function Fe(s,e){return{kind:"page",pageIndex:e,pageId:s[e].id}}const Le={kind:"blank"};function xr(s){return{index:-1,left:Le,right:Fe(s,0)}}function Cr(s){const e=s.length-1;return{index:-2,left:Le,right:Fe(s,e)}}function Ar(s,e={}){if(s.length===0)return[];const t=!!e.frontCover,r=!!e.backCover,i=[];let n=t?1:0;const a=r?Math.max(n,s.length-1):s.length;for(!t&&n<a&&(i.push({index:0,left:Le,right:Fe(s,0)}),n=1);n<a;){if(n+1<a){i.push({index:i.length,left:Fe(s,n),right:Fe(s,n+1)}),n+=2;continue}i.push({index:i.length,left:Fe(s,n),right:Le}),n+=1}return i}function Tr(s,e={}){if(s.length===0)return[];const t=!!e.frontCover,r=!!e.backCover,i=s.length-1;return s.map((n,a)=>{const o=Fe(s,a);return t&&a===0?{index:a,left:o,right:Le}:r&&a===i?{index:a,left:Le,right:o}:a%2===0?{index:a,left:Le,right:o}:{index:a,left:o,right:Le}})}function Pt(s,e="two-page",t={}){return e==="single"?Tr(s,t):Ar(s,t)}function Er(s){const e=[];return s.left.kind==="page"&&e.push(s.left.pageId),s.right.kind==="page"&&e.push(s.right.pageId),e}function Lr(s){return s?s.left.kind==="page"?s.left.pageId:s.right.kind==="page"?s.right.pageId:null:null}function Ze(s,e){const t=s.findIndex(r=>r.left.kind==="page"&&r.left.pageId===e||r.right.kind==="page"&&r.right.pageId===e);return t<0?0:t}class Sn{constructor(e,t,r={}){y(this,"story");y(this,"spreadView");y(this,"spreads");y(this,"spreadIndex",0);y(this,"preferredMode");y(this,"resolvedMode","two-page");y(this,"breakpoint");y(this,"listeners",new Map);y(this,"busy",!1);y(this,"hasResolvedLayout",!1);y(this,"bookState");y(this,"covers");y(this,"frontCoverSpread",null);y(this,"backCoverSpread",null);this.story=e,this.spreadView=t,this.preferredMode=r.mode??wr,this.breakpoint=r.singleBreakpoint??Sr,this.covers={frontCover:!!e.frontCover,backCover:!!e.backCover},this.bookState=this.covers.frontCover?"closed-front":"open",this.rebuildCoverSpreads(),this.spreads=Pt(e.pages,"two-page",this.covers)}get layoutMode(){return this.resolvedMode}get layoutPreference(){return this.preferredMode}get currentBookState(){return this.bookState}get currentSpread(){return this.bookState==="closed-front"&&this.frontCoverSpread?this.frontCoverSpread:this.bookState==="closed-back"&&this.backCoverSpread?this.backCoverSpread:this.spreads[this.spreadIndex]??this.spreads[0]}get currentPageIds(){var e,t;if(this.bookState==="closed-front"){const r=(e=this.story.pages[0])==null?void 0:e.id;return r?[r]:[]}if(this.bookState==="closed-back"){const r=(t=this.story.pages[this.story.pages.length-1])==null?void 0:t.id;return r?[r]:[]}return Er(this.currentSpread)}get canPrev(){return this.bookState==="closed-front"?!1:this.bookState==="closed-back"||this.spreadIndex>0?!0:!!this.covers.frontCover&&this.resolvedMode==="two-page"}get canNext(){return this.bookState==="closed-back"?!1:this.bookState==="closed-front"?this.spreads.length>0||!!this.covers.backCover:this.spreadIndex<this.spreads.length-1?!0:!!this.covers.backCover&&this.resolvedMode==="two-page"}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var r;return(r=this.listeners.get(e))==null?void 0:r.delete(t)}}setLayoutMode(e,t,r){this.preferredMode=e,this.updateLayout(t,r,!1)}updateLayout(e,t,r=!0){var l,d,c,h,u;const i=_r(this.preferredMode,e,t,this.breakpoint);if(!(!this.hasResolvedLayout||i!==this.resolvedMode)){this.spreadView.setLayoutMode(i);return}const a=this.currentPageIds[0]??Lr(this.spreads[this.spreadIndex])??((l=this.story.pages[0])==null?void 0:l.id)??null;this.resolvedMode=i,this.hasResolvedLayout=!0,this.rebuildCoverSpreads(),this.spreads=Pt(this.story.pages,i,this.covers);const o=this.covers.frontCover&&a===((d=this.story.pages[0])==null?void 0:d.id)||this.covers.backCover&&a===((c=this.story.pages[this.story.pages.length-1])==null?void 0:c.id);i==="single"?(this.bookState="open",this.spreadIndex=a?Ze(this.spreads,a):0):this.covers.frontCover&&(this.bookState==="closed-front"||o&&a===((h=this.story.pages[0])==null?void 0:h.id))?(this.bookState="closed-front",this.spreadIndex=0):this.covers.backCover&&(this.bookState==="closed-back"||o&&a===((u=this.story.pages[this.story.pages.length-1])==null?void 0:u.id))?(this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1)):(this.bookState="open",this.spreadIndex=a?Ze(this.spreads,a):0),this.spreadIndex>=this.spreads.length&&(this.spreadIndex=Math.max(0,this.spreads.length-1)),this.busy=!1,this.spreadView.setLayoutMode(i),this.spreadView.setBookState(this.bookState),this.spreadView.showSpread(this.currentSpread,"none"),r&&(this.emit("layoutchange",{layoutMode:i}),this.emitPageChange())}async showInitial(){this.covers.frontCover&&this.resolvedMode==="two-page"?(this.bookState="closed-front",this.spreadIndex=0):this.bookState="open",await this.spreadView.showSpread(this.currentSpread,"none"),this.spreadView.setBookState(this.bookState),this.emitPageChange()}async next(){if(!(this.busy||!this.canNext)){if(this.busy=!0,this.bookState==="closed-front"){this.spreads.length===0&&this.covers.backCover&&this.backCoverSpread?(this.bookState="closed-back",await this.spreadView.showSpread(this.backCoverSpread,"next"),this.spreadView.setBookState("closed-back")):(this.bookState="open",this.spreadIndex=0,await this.spreadView.showSpread(this.currentSpread,"next"),this.spreadView.setBookState("open")),this.emitPageChange(),this.busy=!1;return}if(this.bookState==="open"&&this.covers.backCover&&this.backCoverSpread&&this.resolvedMode==="two-page"&&this.spreadIndex>=this.spreads.length-1){this.bookState="closed-back",await this.spreadView.showSpread(this.backCoverSpread,"next"),this.spreadView.setBookState("closed-back"),this.emitPageChange(),this.busy=!1;return}this.spreadIndex+=1,await this.spreadView.showSpread(this.currentSpread,"next"),this.emitPageChange(),this.busy=!1}}async prev(){if(!(this.busy||!this.canPrev)){if(this.busy=!0,this.bookState==="closed-back"){this.spreads.length===0&&this.covers.frontCover&&this.frontCoverSpread?(this.bookState="closed-front",await this.spreadView.showSpread(this.frontCoverSpread,"prev"),this.spreadView.setBookState("closed-front")):(this.bookState="open",this.spreadIndex=Math.max(0,this.spreads.length-1),await this.spreadView.showSpread(this.currentSpread,"prev"),this.spreadView.setBookState("open")),this.emitPageChange(),this.busy=!1;return}if(this.bookState==="open"&&this.covers.frontCover&&this.frontCoverSpread&&this.resolvedMode==="two-page"&&this.spreadIndex<=0){this.bookState="closed-front",await this.spreadView.showSpread(this.frontCoverSpread,"prev"),this.spreadView.setBookState("closed-front"),this.emitPageChange(),this.busy=!1;return}this.spreadIndex-=1,await this.spreadView.showSpread(this.currentSpread,"prev"),this.emitPageChange(),this.busy=!1}}replaceStory(e,t){this.story=e,this.bookState=e.frontCover?"closed-front":"open",this.rebuildFromStory(t)}rebuildFromStory(e){var r,i,n;this.covers={frontCover:!!this.story.frontCover,backCover:!!this.story.backCover},this.rebuildCoverSpreads(),this.spreads=Pt(this.story.pages,this.resolvedMode,this.covers);const t=e??this.currentPageIds[0]??((r=this.story.pages[0])==null?void 0:r.id)??null;this.resolvedMode==="single"?(this.bookState="open",this.spreadIndex=t?Ze(this.spreads,t):0):this.covers.frontCover&&t===((i=this.story.pages[0])==null?void 0:i.id)&&this.bookState==="closed-front"?(this.bookState="closed-front",this.spreadIndex=0):this.covers.backCover&&t===((n=this.story.pages[this.story.pages.length-1])==null?void 0:n.id)&&this.bookState==="closed-back"?(this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1)):(this.bookState="open",this.spreadIndex=t?Ze(this.spreads,t):0,this.spreadIndex<0&&(this.spreadIndex=0)),this.spreads.length===0?(this.spreadIndex=0,this.covers.frontCover?this.bookState="closed-front":this.covers.backCover&&(this.bookState="closed-back")):this.spreadIndex>=this.spreads.length&&(this.spreadIndex=Math.max(0,this.spreads.length-1)),this.busy=!1,this.spreadView.setLayoutMode(this.resolvedMode),this.spreadView.setBookState(this.bookState),this.spreadView.showSpread(this.currentSpread,"none"),this.emitPageChange()}async goTo(e){var a,o;const t=this.covers.frontCover&&((a=this.story.pages[0])==null?void 0:a.id)===e,r=this.covers.backCover&&((o=this.story.pages[this.story.pages.length-1])==null?void 0:o.id)===e;if(this.busy=!0,t&&this.resolvedMode==="two-page"&&this.frontCoverSpread){this.bookState="closed-front",this.spreadIndex=0,await this.spreadView.showSpread(this.frontCoverSpread,"none"),this.spreadView.setBookState("closed-front"),this.emitPageChange(),this.busy=!1;return}if(r&&this.resolvedMode==="two-page"&&this.backCoverSpread){this.bookState="closed-back",this.spreadIndex=Math.max(0,this.spreads.length-1),await this.spreadView.showSpread(this.backCoverSpread,"none"),this.spreadView.setBookState("closed-back"),this.emitPageChange(),this.busy=!1;return}const i=Ze(this.spreads,e);if(i===this.spreadIndex&&this.bookState==="open"){this.busy=!1;return}const n=i>this.spreadIndex?"next":"prev";this.bookState="open",this.spreadIndex=i,this.spreadView.setBookState("open"),await this.spreadView.showSpread(this.currentSpread,n),this.emitPageChange(),this.busy=!1}rebuildCoverSpreads(){this.frontCoverSpread=this.covers.frontCover?xr(this.story.pages):null,this.backCoverSpread=this.covers.backCover?Cr(this.story.pages):null}emitPageChange(){this.emit("pagechange",{pageIds:this.currentPageIds,index:this.spreadIndex,layoutMode:this.resolvedMode,bookState:this.bookState})}emit(e,t){const r=this.listeners.get(e);if(r)for(const i of r)i(t)}}function It(s){return s.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Nt(s,e){var t;try{const i=(t=new URL(s,"http://local/").pathname.split(".").pop())==null?void 0:t.toLowerCase();if(i&&/^[a-z0-9]{1,8}$/.test(i))return i}catch{}return e}async function $t(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch asset ${s}: ${e.status}`);return new Uint8Array(await e.arrayBuffer())}async function Mr(s,e={}){const t={...e.files??{}},r=structuredClone(s),i=e.baseUrl??"";for(const[a,o]of Object.entries(r.assets)){const l=o.src;if(/^(?:[a-z]+:)?\/\//i.test(l)||l.startsWith("blob:")||l.startsWith("data:")){const h=o.type==="image"?Nt(l,"png"):o.type==="audio"?Nt(l,"mp3"):o.type==="vtt"?"vtt":Nt(l,"bin"),u=It(`assets/${a}.${h}`);t[u]||(t[u]=await $t(l)),o.src=u;continue}const c=It(l);if(!t[c]){const h=je(i,l);t[c]=await $t(h)}o.src=c}for(const a of r.fonts){const o=a.src;if(/^(?:[a-z]+:)?\/\//i.test(o)||o.startsWith("blob:")||o.startsWith("data:")){const d=It(`fonts/${a.family.replace(/\s+/g,"-")}.${Nt(o,"woff2")}`);t[d]||(t[d]=await $t(o)),a.src=d}else{const d=It(o);t[d]||(t[d]=await $t(je(i,o))),a.src=d}}t["story.json"]=us(JSON.stringify(r,null,2));const n=Ki(t,{level:6});return new Blob([n],{type:"application/zip"})}function Pr(s,e){const t=URL.createObjectURL(s),r=document.createElement("a");r.href=t,r.download=e,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(t)}class lt{cancel(e){}}y(lt,"id","base");const ct=new Map;function Ir(s,e){ct.set(s,e)}function _n(s){return ct.get(s)}function Nr(){return[...ct.keys()]}function xn(s){return typeof s=="function"&&s.prototype instanceof lt}function Ss(s){if(s==null||s===""){const e=ct.get("default");if(!e)throw new Error('FlipStyle "default" is not registered');return new e}if(typeof s=="string"){const e=ct.get(s);if(!e){const t=Nr().join(", ")||"(none)";throw new Error(`Unknown flipStyle "${s}". Registered: ${t}`)}return new e}if(s instanceof lt)return s;if(xn(s))return new s;throw new Error("flipStyle must be a string id, FlipStyle instance, or FlipStyle subclass")}const $r=400;function _s(s){return s==null||!Number.isFinite(s)||s<=0?$r:s}class Ft extends lt{play(e){const{bookEl:t,direction:r,durationMs:i}=e,n=r==="next"?"fc-turn-next":"fc-turn-prev";return t.style.setProperty("--fc-flip-duration",`${i}ms`),t.classList.remove("fc-turn-next","fc-turn-prev"),t.offsetWidth,t.classList.add(n),new Promise(a=>{const o=()=>{t.removeEventListener("animationend",l),t.classList.remove("fc-turn-next","fc-turn-prev"),a()},l=d=>{d.target!==e.rightLeaf&&d.target!==e.leftLeaf||o()};t.addEventListener("animationend",l),window.setTimeout(o,i+50)})}cancel(e){e.bookEl.classList.remove("fc-turn-next","fc-turn-prev")}}y(Ft,"id","default"),Ir(Ft.id,Ft);const xs=.035;function Fr(s,e){return e&&e.width>0&&e.height>0?{x:Math.max(0,Math.round((e.width-s.width)/2)),y:Math.max(0,Math.round((e.height-s.height)/2))}:{x:Math.max(1,Math.round(s.width*xs)),y:Math.max(1,Math.round(s.height*xs))}}function Cs(s){return!!(s.hardback&&(s.frontCover||s.backCover))}function Cn(s){const e=s??{},t={left:Ue(e.x??0),top:Ue(e.y??0)};return e.width!=null&&(t.width=Ue(e.width)),e.height!=null&&(t.height=Ue(e.height)),t}function As(s,e){const t=Cn(e);s.style.left=t.left,s.style.top=t.top,t.width&&(s.style.width=t.width),t.height&&(s.style.height=t.height),(e==null?void 0:e.horizontalAlign)==="right"?(s.style.left="auto",s.style.right=Ue(e.x??0)):(e==null?void 0:e.horizontalAlign)==="center"&&(s.style.left="50%",s.style.transform=`${s.style.transform||""} translateX(-50%)`.trim()),(e==null?void 0:e.verticalAlign)==="bottom"?(s.style.top="auto",s.style.bottom=Ue(e.y??0)):(e==null?void 0:e.verticalAlign)==="center"&&(s.style.top="50%",s.style.transform=`${s.style.transform||""} translateY(-50%)`.trim())}function Ue(s){return typeof s=="number"?`${s}px`:/^-?\d+(\.\d+)?$/.test(s)?`${s}px`:s}function An(s,e){const t=document.createElement("button");return t.type="button",t.className="fc-block fc-block-hotspot",t.dataset.blockId=s.id,t.setAttribute("aria-label",s.ariaLabel??s.id),As(t,s.layout),t.addEventListener("click",r=>{r.stopPropagation(),e(s.onTap??[])}),t}function Tn(s,e){var n;const t=document.createElement("div");t.className=`fc-block fc-block-image${s.className?` ${s.className}`:""}`,t.dataset.blockId=s.id,As(t,s.layout);const r=document.createElement("img");r.alt="",r.draggable=!1,e&&(r.src=e.src);const i=((n=s.layout)==null?void 0:n.fit)??"contain";return r.style.objectFit=i,t.appendChild(r),t}function En(s,e){const t=document.createElement("div");return t.className="fc-block fc-block-text",t.dataset.blockId=s.id,As(t,s.layout),t.innerHTML=e,t.querySelectorAll("[id]").forEach(r=>{r.classList.add("fc-cue")}),s.style&&(s.style.fontFamily&&(t.style.fontFamily=s.style.fontFamily),s.style.fontSize&&(t.style.fontSize=s.style.fontSize),s.style.color&&(t.style.color=s.style.color),s.style.textAlign&&(t.style.textAlign=s.style.textAlign),s.style.lineHeight!=null&&(t.style.lineHeight=String(s.style.lineHeight)),s.style.fontWeight&&(t.style.fontWeight=s.style.fontWeight),s.style.fontStyle&&(t.style.fontStyle=s.style.fontStyle)),t}class Ts{constructor(e,t,r){y(this,"element");y(this,"page");y(this,"blank");var i,n;if(this.page=e,this.blank=!e,this.element=document.createElement("article"),this.element.className=`fc-page${this.blank?" fc-page-blank":""}`,this.element.setAttribute("role",this.blank?"presentation":"document"),!e){this.element.dataset.blank="true";return}if(this.element.dataset.pageId=e.id,(i=e.background)!=null&&i.color&&(this.element.style.backgroundColor=e.background.color),(n=e.background)!=null&&n.asset){const a=t.images.get(e.background.asset);a&&(this.element.style.backgroundImage=`url(${JSON.stringify(a.src)})`,this.element.style.backgroundSize="cover",this.element.style.backgroundPosition="center")}for(const a of e.blocks)if(a.type==="text"){const o=a.html??t.html.get(`htmlSrc:${a.id}`)??(a.htmlSrc?t.html.get(a.htmlSrc):void 0)??"";this.element.appendChild(En(a,o))}else a.type==="image"?this.element.appendChild(Tn(a,t.images.get(a.asset))):a.type==="hotspot"&&this.element.appendChild(An(a,o=>r.onTapActions(o,this.element)))}destroy(){this.element.remove()}}class Ln{constructor(e,t,r,i={}){y(this,"element");y(this,"bookEl");y(this,"hardbackEl");y(this,"hardbackLeft");y(this,"hardbackRight");y(this,"hardbackLeftPage",null);y(this,"hardbackRightPage",null);y(this,"leftSlot");y(this,"rightSlot");y(this,"leftPage",null);y(this,"rightPage",null);y(this,"story");y(this,"assets");y(this,"onTapActions");y(this,"turning",!1);y(this,"bookState","open");y(this,"layoutMode","two-page");y(this,"lastSize",{width:0,height:0});y(this,"stageZoom",{mode:"fit-spread"});y(this,"currentSpread",null);y(this,"flipStyle");y(this,"flipSpeedMs");this.story=e,this.assets=t,this.onTapActions=r,this.flipStyle=Ss(i.flipStyle),this.flipSpeedMs=_s(i.flipSpeed),this.element=document.createElement("div"),this.element.className="fc-spread-viewport",this.hardbackEl=document.createElement("div"),this.hardbackEl.className="fc-hardback",this.hardbackEl.setAttribute("aria-hidden","true"),this.hardbackLeft=document.createElement("div"),this.hardbackLeft.className="fc-hardback-board fc-hardback-board-left",this.hardbackRight=document.createElement("div"),this.hardbackRight.className="fc-hardback-board fc-hardback-board-right",this.hardbackEl.append(this.hardbackLeft,this.hardbackRight),this.bookEl=document.createElement("div"),this.bookEl.className="fc-spread",this.leftSlot=document.createElement("div"),this.leftSlot.className="fc-leaf fc-leaf-left",this.rightSlot=document.createElement("div"),this.rightSlot.className="fc-leaf fc-leaf-right",this.bookEl.append(this.leftSlot,this.rightSlot),this.element.append(this.hardbackEl,this.bookEl)}get currentBookState(){return this.bookState}setFlipStyle(e){this.flipStyle=Ss(e)}setFlipSpeed(e){this.flipSpeedMs=_s(e)}setStageZoom(e){this.stageZoom=e,this.lastSize.width>0&&this.lastSize.height>0&&this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}setLayoutMode(e){this.layoutMode=e,this.element.dataset.layoutMode=e,this.element.classList.toggle("fc-spread-viewport-single",e==="single"),this.element.classList.toggle("fc-spread-viewport-two",e==="two-page")}setBookState(e){this.bookState=e,this.element.dataset.bookState=e,this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}showSpread(e,t="none"){var r,i;return t==="none"||this.turning?((i=(r=this.flipStyle).cancel)==null||i.call(r,{bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot}),this.turning=!1,this.mountSpread(e),Promise.resolve()):(this.turning=!0,this.flipStyle.play({bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot,direction:t,durationMs:this.flipSpeedMs}).then(()=>{this.mountSpread(e),this.turning=!1}).catch(()=>{this.mountSpread(e),this.turning=!1}))}getPageElement(e){var t,r,i,n;return((r=(t=this.leftPage)==null?void 0:t.page)==null?void 0:r.id)===e?this.leftPage.element:((n=(i=this.rightPage)==null?void 0:i.page)==null?void 0:n.id)===e?this.rightPage.element:null}getLeafSlots(){return{left:this.leftSlot,right:this.rightSlot}}getEditableLeaves(e,t){const r=[],i=(n,a,o)=>{a.kind==="page"&&r.push({side:n,pageIndex:a.pageIndex,slot:o})};return this.bookState==="closed-front"||this.bookState==="closed-back"?(i("right",t.right,this.rightSlot),r):e==="two-page"?(i("left",t.left,this.leftSlot),i("right",t.right,this.rightSlot),r):(t.left.kind==="blank"&&t.right.kind==="page"?i("right",t.right,this.rightSlot):t.right.kind==="blank"&&t.left.kind==="page"?i("left",t.left,this.leftSlot):t.left.kind==="page"?i("left",t.left,this.leftSlot):t.right.kind==="page"&&i("right",t.right,this.rightSlot),r)}setPageViewsHidden(e){this.leftPage&&(this.leftPage.element.hidden=e),this.rightPage&&(this.rightPage.element.hidden=e)}remountCurrent(){this.currentSpread&&this.mountSpread(this.currentSpread)}setStory(e){this.story=e,this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}setLoaded(e,t){this.story=e,this.assets=t,this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,this.currentSpread??void 0)}getVisiblePageElements(e,t){if(this.bookState==="closed-front"||this.bookState==="closed-back")return this.rightPage&&t.right.kind==="page"?[this.rightPage.element]:[];const r=[];return e==="two-page"?(t.left.kind==="page"&&this.leftPage&&r.push(this.leftPage.element),t.right.kind==="page"&&this.rightPage&&r.push(this.rightPage.element)):t.left.kind==="blank"&&t.right.kind==="page"&&this.rightPage?r.push(this.rightPage.element):t.right.kind==="blank"&&t.left.kind==="page"&&this.leftPage?r.push(this.leftPage.element):t.left.kind==="page"&&this.leftPage?r.push(this.leftPage.element):t.right.kind==="page"&&this.rightPage&&r.push(this.rightPage.element),r}updateStageSize(e,t,r,i){this.layoutMode=r,this.lastSize={width:e,height:t},this.applyStageTransform(e,t,i)}destroy(){var e,t,r,i;(t=(e=this.flipStyle).cancel)==null||t.call(e,{bookEl:this.bookEl,viewportEl:this.element,leftLeaf:this.leftSlot,rightLeaf:this.rightSlot}),this.clearHardbackBoards(),(r=this.leftPage)==null||r.destroy(),(i=this.rightPage)==null||i.destroy(),this.element.remove()}applyStageTransform(e,t,r){if(e<=0||t<=0)return;const{width:i,height:n}=this.story.pageSize,a=this.layoutMode,o=this.bookState,l=Cs(this.story),d=l?Fr(this.story.pageSize,this.story.coverSize):{x:0,y:0},c=a==="two-page"&&(o==="closed-front"||o==="closed-back"),h=l&&o==="open",u=this.isSoloCover();this.element.classList.toggle("fc-hardback-active",l),this.element.classList.toggle("fc-hardback-open",h),this.element.classList.toggle("fc-hardback-closed",l&&c);let g,x,v,f=0,b=0,_=0;if(l&&c)x=i+2*d.x,v=n+2*d.y,g=this.sizedScale(Math.min(e/x,t/v),i,n,e,t),this.bookEl.style.setProperty("--fc-page-width",`${x}px`),this.bookEl.style.setProperty("--fc-page-height",`${v}px`),this.bookEl.style.width=`${u?x:x*2}px`,this.bookEl.style.height=`${v}px`,f=u?0:-x*g,b=0,_=0,this.hardbackEl.hidden=!0;else if(h){x=(a==="single"?i:i*2)+2*d.x,v=n+2*d.y,g=this.sizedScale(Math.min(e/x,t/v),i,n,e,t),this.bookEl.style.setProperty("--fc-page-width",`${i}px`),this.bookEl.style.setProperty("--fc-page-height",`${n}px`),this.bookEl.style.width=`${i*2}px`,this.bookEl.style.height=`${n}px`,this.hardbackEl.hidden=!1,this.hardbackEl.style.width=`${x}px`,this.hardbackEl.style.height=`${v}px`;const W=a==="single"?(r==null?void 0:r.left.kind)==="blank"?"right":"left":"both";this.sizeHardbackBoards(W,i,n,d.x,d.y),b=d.x,_=d.y,a==="single"&&(r==null?void 0:r.left.kind)==="blank"?f=-i*g:f=0}else x=i*2,v=n,a==="single"||c?g=this.sizedScale(Math.min(e/i,t/n),i,n,e,t):g=this.sizedScale(Math.min(e/x,t/v),i,n,e,t),this.bookEl.style.setProperty("--fc-page-width",`${i}px`),this.bookEl.style.setProperty("--fc-page-height",`${n}px`),this.bookEl.style.width=`${u?i:x}px`,this.bookEl.style.height=`${v}px`,this.hardbackEl.hidden=!0,u?f=0:(c||a==="single"&&r&&r.left.kind==="blank")&&(f=-i*g);this.element.style.setProperty("--fc-hardback-overhang-x",`${d.x}px`),this.element.style.setProperty("--fc-hardback-overhang-y",`${d.y}px`),this.hardbackEl.style.transform=`scale(${g})`,this.hardbackEl.style.transformOrigin="left top",this.bookEl.style.transform=`translateX(${f}px) scale(${g})`,this.bookEl.style.transformOrigin="left top";let m=l&&c?(i+2*d.x)*g:h?(a==="single"?i+2*d.x:i*2+2*d.x)*g:a==="single"||c?i*g:i*2*g,E=l&&(c||h)?(n+2*d.y)*g:n*g,R=0,L=0;this.stageZoom.mode==="fit-page"&&(E>t&&(L=(E-t)/2,E=t),(a==="single"||c||u?i:i*2)*g<=e&&m>e&&(R=(m-e)/2,m=e));const O=(h?b*g:0)-R,I=(h?_*g:0)-L;this.hardbackEl.style.left=`${-R}px`,this.hardbackEl.style.top=`${-L}px`,this.bookEl.style.left=`${O}px`,this.bookEl.style.top=`${I}px`,this.element.style.width=`${m}px`,this.element.style.height=`${E}px`,this.leftSlot.classList.toggle("fc-leaf-dimmed",c&&!u),this.rightSlot.classList.remove("fc-leaf-dimmed"),this.applySoloCover(u)}sizedScale(e,t,r,i,n){return this.stageZoom.mode==="percent"?Math.max(.1,this.stageZoom.percent/100):this.stageZoom.mode==="fit-page"?Math.min(i/t,n/r):e}isSoloCover(){var l,d;if(this.bookState==="closed-front"||this.bookState==="closed-back")return!0;const e=this.currentSpread;if(!e)return!1;const t=e.left.kind==="page",r=e.right.kind==="page";if(t===r)return!1;const i=t&&e.left.kind==="page"?e.left.pageId:e.right.kind==="page"?e.right.pageId:null;if(!i)return!1;const n=this.story.pages,a=!!this.story.frontCover&&((l=n[0])==null?void 0:l.id)===i,o=!!this.story.backCover&&((d=n[n.length-1])==null?void 0:d.id)===i;return a||o}applySoloCover(e){if(this.bookEl.classList.toggle("is-solo-cover",e),!e||!this.currentSpread){this.leftSlot.classList.remove("is-cover-hidden"),this.rightSlot.classList.remove("is-cover-hidden");return}const t=this.currentSpread.left.kind==="page";this.leftSlot.classList.toggle("is-cover-hidden",!t),this.rightSlot.classList.toggle("is-cover-hidden",t)}sizeHardbackBoards(e,t,r,i,n){const a=r+2*n;if(e!=="both"){const o=e==="left";this.hardbackLeft.style.display=o?"":"none",this.hardbackRight.style.display=o?"none":"";const l=o?this.hardbackLeft:this.hardbackRight;l.style.width=`${t+2*i}px`,l.style.height=`${a}px`;return}this.hardbackLeft.style.display="",this.hardbackRight.style.display="",this.hardbackLeft.style.width=`${t+i}px`,this.hardbackLeft.style.height=`${a}px`,this.hardbackRight.style.width=`${t+i}px`,this.hardbackRight.style.height=`${a}px`}syncHardbackBoards(){if(!Cs(this.story)||this.bookState!=="open"){this.clearHardbackBoards();return}const e=this.story.pages,t=this.story.frontCover?e[0]:null,r=this.story.backCover?e[e.length-1]:null,i=t??r,n=r??t;this.mountHardbackBoard("left",i),this.mountHardbackBoard("right",n)}mountHardbackBoard(e,t){var o;const r=e==="left"?this.hardbackLeft:this.hardbackRight,i=e==="left"?this.hardbackLeftPage:this.hardbackRightPage;if(i==null||i.destroy(),!t){r.replaceChildren(),r.style.background="",e==="left"?this.hardbackLeftPage=null:this.hardbackRightPage=null;return}const n=(o=t.background)==null?void 0:o.innerColor;if(n){r.style.background=n,r.replaceChildren(),e==="left"?this.hardbackLeftPage=null:this.hardbackRightPage=null;return}r.style.background="";const a=new Ts(t,this.assets,{onTapActions:()=>{}});a.element.classList.add("fc-hardback-page"),r.replaceChildren(a.element),e==="left"?this.hardbackLeftPage=a:this.hardbackRightPage=a}clearHardbackBoards(){var e,t;(e=this.hardbackLeftPage)==null||e.destroy(),(t=this.hardbackRightPage)==null||t.destroy(),this.hardbackLeftPage=null,this.hardbackRightPage=null,this.hardbackLeft.replaceChildren(),this.hardbackRight.replaceChildren(),this.hardbackLeft.style.background="",this.hardbackRight.style.background=""}mountSpread(e){var t,r;this.currentSpread=e,(t=this.leftPage)==null||t.destroy(),(r=this.rightPage)==null||r.destroy(),this.leftSlot.replaceChildren(),this.rightSlot.replaceChildren(),this.leftPage=this.createLeaf(e.left),this.rightPage=this.createLeaf(e.right),this.leftSlot.appendChild(this.leftPage.element),this.rightSlot.appendChild(this.rightPage.element),this.syncHardbackBoards(),this.applyStageTransform(this.lastSize.width,this.lastSize.height,e)}createLeaf(e){if(e.kind==="blank")return new Ts(null,this.assets,{onTapActions:this.onTapActions});const t=this.story.pages[e.pageIndex];return new Ts(t,this.assets,{onTapActions:this.onTapActions})}}function Rr(s,e){const t=s==null?void 0:s.container;if(!(t!=null&&t.send))return;const r=In(e.progress);t.send("progress",r),t.send("loading",{stage:e.stage,progress:r,count:e.count,total:e.total,detail:e.detail})}function Mn(s){var e,t;(t=(e=s==null?void 0:s.container)==null?void 0:e.send)==null||t.call(e,"loaded")}function Pn(){let s;return{promise:new Promise(t=>{s=t}),resolve:s}}function In(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}function Or(s,e,t={}){const r=[];let i=!1;const n=(a,o)=>{if(!(a!=null&&a.subscribe))return;const l=a.subscribe(o);typeof l=="function"?r.push(l):l&&typeof l.unsubscribe=="function"&&r.push(()=>{var d;return(d=l.unsubscribe)==null?void 0:d.call(l)})};return s!=null&&s.state&&(n(s.state.pause,a=>{var l;const o=!!a;e.setPaused(o),(l=t.onPause)==null||l.call(t,o)}),n(s.state.soundVolume,a=>e.setVolume("sound",Number(a))),n(s.state.voVolume,a=>e.setVolume("vo",Number(a))),n(s.state.sfxVolume,a=>e.setVolume("sfx",Number(a))),n(s.state.musicVolume,a=>e.setVolume("music",Number(a))),n(s.state.captionsMuted,a=>{var o;i=!!a,(o=t.onCaptionsMuted)==null||o.call(t,i)})),{get captionsMuted(){return i},destroy(){for(const a of r)a()}}}async function Vr(s){var e,t;try{const r=await import("springroll"),i=r.Application??((e=r.default)==null?void 0:e.Application),n=r.ApplicationPlugin??((t=r.default)==null?void 0:t.ApplicationPlugin);if(!i)return null;const a=Pn(),o=`fancifully-story-load-${Math.random().toString(36).slice(2,9)}`;if(n&&typeof i.uses=="function"){const d=new n({name:o});d.preload=()=>a.promise,i.uses(d)}else a.resolve();return{app:new i({features:s}),loadGate:a,owned:!0}}catch{return null}}function Br(s){var e;return!((e=s==null?void 0:s.state)!=null&&e.ready)||s.state.ready.value===!0?Promise.resolve():new Promise(t=>{const r=s.state.ready.subscribe(i=>{i&&(typeof r=="function"&&r(),t())})})}const Nn=Object.freeze({left:0,top:0,width:16,height:16}),Rt=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),zr=Object.freeze({...Nn,...Rt}),$n=Object.freeze({...zr,body:"",hidden:!1}),Fn=Object.freeze({width:null,height:null}),Rn=Object.freeze({...Fn,...Rt});function On(s,e){const t={};!s.hFlip!=!e.hFlip&&(t.hFlip=!0),!s.vFlip!=!e.vFlip&&(t.vFlip=!0);const r=((s.rotate||0)+(e.rotate||0))%4;return r&&(t.rotate=r),t}function jr(s,e){const t=On(s,e);for(const r in $n)r in Rt?r in s&&!(r in t)&&(t[r]=Rt[r]):r in e?t[r]=e[r]:r in s&&(t[r]=s[r]);return t}function Vn(s,e){const t=s.icons,r=s.aliases||Object.create(null),i=Object.create(null);function n(a){if(t[a])return i[a]=[];if(!(a in i)){i[a]=null;const o=r[a]&&r[a].parent,l=o&&n(o);l&&(i[a]=[o].concat(l))}return i[a]}return(e||Object.keys(t).concat(Object.keys(r))).forEach(n),i}function Zr(s,e,t){const r=s.icons,i=s.aliases||Object.create(null);let n={};function a(o){n=jr(r[o]||i[o],n)}return a(e),t.forEach(a),jr(s,n)}function Bn(s,e){if(s.icons[e])return Zr(s,e,[]);const t=Vn(s,[e])[e];return t?Zr(s,e,t):null}const zn=/(-?[0-9.]*[0-9]+[0-9.]*)/g,jn=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function Ur(s,e,t){if(e===1)return s;if(t=t||100,typeof s=="number")return Math.ceil(s*e*t)/t;if(typeof s!="string")return s;const r=s.split(zn);if(r===null||!r.length)return s;const i=[];let n=r.shift(),a=jn.test(n);for(;;){if(a){const o=parseFloat(n);isNaN(o)?i.push(n):i.push(Math.ceil(o*e*t)/t)}else i.push(n);if(n=r.shift(),n===void 0)return i.join("");a=!a}}function Zn(s,e="defs"){let t="";const r=s.indexOf("<"+e);for(;r>=0;){const i=s.indexOf(">",r),n=s.indexOf("</"+e);if(i===-1||n===-1)break;const a=s.indexOf(">",n);if(a===-1)break;t+=s.slice(i+1,n).trim(),s=s.slice(0,r).trim()+s.slice(a+1)}return{defs:t,content:s}}function Un(s,e){return s?"<defs>"+s+"</defs>"+e:e}function Hn(s,e,t){const r=Zn(s);return Un(r.defs,e+r.content+t)}const Dn=s=>s==="unset"||s==="undefined"||s==="none";function Wn(s,e){const t={...zr,...s},r={...Rn,...e},i={left:t.left,top:t.top,width:t.width,height:t.height};let n=t.body;[t,r].forEach(v=>{const f=[],b=v.hFlip,_=v.vFlip;let m=v.rotate;b?_?m+=2:(f.push("translate("+(i.width+i.left).toString()+" "+(0-i.top).toString()+")"),f.push("scale(-1 1)"),i.top=i.left=0):_&&(f.push("translate("+(0-i.left).toString()+" "+(i.height+i.top).toString()+")"),f.push("scale(1 -1)"),i.top=i.left=0);let E;switch(m<0&&(m-=Math.floor(m/4)*4),m=m%4,m){case 1:E=i.height/2+i.top,f.unshift("rotate(90 "+E.toString()+" "+E.toString()+")");break;case 2:f.unshift("rotate(180 "+(i.width/2+i.left).toString()+" "+(i.height/2+i.top).toString()+")");break;case 3:E=i.width/2+i.left,f.unshift("rotate(-90 "+E.toString()+" "+E.toString()+")")}m%2===1&&(i.left!==i.top&&(E=i.left,i.left=i.top,i.top=E),i.width!==i.height&&(E=i.width,i.width=i.height,i.height=E)),f.length&&(n=Hn(n,'<g transform="'+f.join(" ")+'">',"</g>"))});const a=r.width,o=r.height,l=i.width,d=i.height;let c,h;a===null?(h=o===null?"1em":o==="auto"?d:o,c=Ur(h,l/d)):(c=a==="auto"?l:a,h=o===null?Ur(c,d/l):o==="auto"?d:o);const u={},g=(v,f)=>{Dn(f)||(u[v]=f.toString())};g("width",c),g("height",h);const x=[i.left,i.top,l,d];return u.viewBox=x.join(" "),{attributes:u,viewBox:x,body:n}}function qn(s,e){let t=s.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(const r in e)t+=" "+r+'="'+e[r]+'"';return'<svg xmlns="http://www.w3.org/2000/svg"'+t+">"+s+"</svg>"}const Yn={prefix:"mdi",icons:{"chevron-left":{body:'<path fill="currentColor" d="M15.41 16.58L10.83 12l4.58-4.59L14 6l-6 6l6 6z"/>'},"chevron-right":{body:'<path fill="currentColor" d="M8.59 16.58L13.17 12L8.59 7.41L10 6l6 6l-6 6z"/>'},"book-open-page-variant":{body:'<path fill="currentColor" d="m19 2l-5 4.5v11l5-4.5zM6.5 5C4.55 5 2.45 5.4 1 6.5v14.66c0 .25.25.5.5.5c.1 0 .15-.07.25-.07c1.35-.65 3.3-1.09 4.75-1.09c1.95 0 4.05.4 5.5 1.5c1.35-.85 3.8-1.5 5.5-1.5c1.65 0 3.35.31 4.75 1.06c.1.05.15.03.25.03c.25 0 .5-.25.5-.5V6.5c-.6-.45-1.25-.75-2-1V19c-1.1-.35-2.3-.5-3.5-.5c-1.7 0-4.15.65-5.5 1.5V6.5C10.55 5.4 8.45 5 6.5 5"/>'},pencil:{body:'<path fill="currentColor" d="M20.71 7.04c.39-.39.39-1.04 0-1.41l-2.34-2.34c-.37-.39-1.02-.39-1.41 0l-1.84 1.83l3.75 3.75M3 17.25V21h3.75L17.81 9.93l-3.75-3.75z"/>'},eye:{body:'<path fill="currentColor" d="M12 9a3 3 0 0 0-3 3a3 3 0 0 0 3 3a3 3 0 0 0 3-3a3 3 0 0 0-3-3m0 8a5 5 0 0 1-5-5a5 5 0 0 1 5-5a5 5 0 0 1 5 5a5 5 0 0 1-5 5m0-12.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5"/>'},download:{body:'<path fill="currentColor" d="M5 20h14v-2H5m14-9h-4V3H9v6H5l7 7z"/>'},cog:{body:'<path fill="currentColor" d="M12 15.5A3.5 3.5 0 0 1 8.5 12A3.5 3.5 0 0 1 12 8.5a3.5 3.5 0 0 1 3.5 3.5a3.5 3.5 0 0 1-3.5 3.5m7.43-2.53c.04-.32.07-.64.07-.97s-.03-.66-.07-1l2.11-1.63c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.31-.61-.22l-2.49 1c-.52-.39-1.06-.73-1.69-.98l-.37-2.65A.506.506 0 0 0 14 2h-4c-.25 0-.46.18-.5.42l-.37 2.65c-.63.25-1.17.59-1.69.98l-2.49-1c-.22-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64L4.57 11c-.04.34-.07.67-.07 1s.03.65.07.97l-2.11 1.66c-.19.15-.25.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1.01c.52.4 1.06.74 1.69.99l.37 2.65c.04.24.25.42.5.42h4c.25 0 .46-.18.5-.42l.37-2.65c.63-.26 1.17-.59 1.69-.99l2.49 1.01c.22.08.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64z"/>'},"file-plus":{body:'<path fill="currentColor" d="M14 2H6c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h7.81c-.53-.91-.81-1.95-.81-3c0-3.31 2.69-6 6-6c.34 0 .67.03 1 .08V8zm-1 7V3.5L18.5 9zm10 11h-3v3h-2v-3h-3v-2h3v-3h2v3h3z"/>'},"file-remove":{body:'<path fill="currentColor" d="M21.12 22.54L19 20.41l-2.12 2.13l-1.41-1.42L17.59 19l-2.12-2.12l1.41-1.41L19 17.59l2.12-2.12l1.42 1.41L20.41 19l2.13 2.12zM14 2H6c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h7.81c-.53-.91-.81-1.95-.81-3c0-3.31 2.69-6 6-6c.34 0 .67.03 1 .08V8zm-1 7V3.5L18.5 9z"/>'},book:{body:'<path fill="currentColor" d="M18 22a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-6v7L9.5 7.5L7 9V2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2z"/>'},"book-open-outline":{body:'<path fill="currentColor" d="M21 4H3a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2M3 19V6h8v13zm18 0h-8V6h8zm-7-9.5h6V11h-6zm0 2.5h6v1.5h-6zm0 2.5h6V16h-6z"/>'},"book-variant":{body:'<path fill="currentColor" d="M6 4h5v8l-2.5-1.5L6 12M18 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2"/>'},"folder-open":{body:'<path fill="currentColor" d="M19 20H4a2 2 0 0 1-2-2V6c0-1.11.89-2 2-2h6l2 2h7a2 2 0 0 1 2 2H4v10l2.14-8h17.07l-2.28 8.5c-.23.87-1.01 1.5-1.93 1.5"/>'},"drag-vertical":{body:'<path fill="currentColor" d="M9 3h2v2H9zm4 0h2v2h-2zM9 7h2v2H9zm4 0h2v2h-2zm-4 4h2v2H9zm4 0h2v2h-2zm-4 4h2v2H9zm4 0h2v2h-2zm-4 4h2v2H9zm4 0h2v2h-2z"/>'},close:{body:'<path fill="currentColor" d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12z"/>'},plus:{body:'<path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"/>'}},lastModified:1737398331,width:24,height:24};function Gn(s,e={}){const t=Bn(Yn,s);if(!t)throw new Error(`Unknown MDI icon in subset: ${s}`);const r=e.size??"1.15rem",i=Wn(t,{height:r,width:r}),n=document.createElement("span");return n.className=e.className??"fc-icon",n.setAttribute("aria-hidden","true"),n.innerHTML=qn(i.body,i.attributes),n}function Es(s,e){const t=Gn(e.icon),r=document.createElement("span");r.className=e.iconOnly?"fc-btn-label fc-btn-label--sr":"fc-btn-label",r.textContent=e.label,s.title=e.label,s.setAttribute("aria-label",e.label),s.replaceChildren(t,r)}const Jn={sound:!0,soundVolume:!0,vo:!0,voVolume:!0,sfx:!0,sfxVolume:!0,music:!0,musicVolume:!0,captions:!0};class Ls{constructor(e,t,r,i,n={},a,o,l,d){y(this,"element");y(this,"root");y(this,"stage");y(this,"chrome");y(this,"captionsEl");y(this,"loaded");y(this,"spreadView");y(this,"pager");y(this,"bus",new ye);y(this,"readAloud");y(this,"springroll");y(this,"bindings",null);y(this,"sfxAudio");y(this,"unbindSwipe",null);y(this,"resizeObserver",null);y(this,"listeners",new Map);y(this,"destroyed",!1);y(this,"btnPrev");y(this,"btnRead");y(this,"btnNext");y(this,"chromeHiddenByOptions",!1);y(this,"extraFiles",{});y(this,"defaultFontFamily",null);y(this,"navLocked",!1);var g,x,v,f,b,_;this.root=e,this.loaded=t,this.springroll=r,this.chromeHiddenByOptions=!!n.hidden,this.element=document.createElement("div"),this.element.className="fc-root",this.element.tabIndex=0,this.stage=document.createElement("div"),this.stage.className="fc-stage",this.captionsEl=document.createElement("div"),this.captionsEl.className="fc-captions",this.captionsEl.setAttribute("aria-live","polite");const c={prev:((g=n.labels)==null?void 0:g.prev)??"Prev",read:((x=n.labels)==null?void 0:x.read)??"Read",next:((v=n.labels)==null?void 0:v.next)??"Next"},h={prev:((f=n.ariaLabels)==null?void 0:f.prev)??"Previous page",read:((b=n.ariaLabels)==null?void 0:b.read)??"Read aloud",next:((_=n.ariaLabels)==null?void 0:_.next)??"Next page"};this.chrome=document.createElement("div"),this.chrome.className=["fc-chrome",n.className].filter(Boolean).join(" "),this.chrome.hidden=!!n.hidden,this.btnPrev=document.createElement("button"),this.btnPrev.type="button",this.btnPrev.className="fc-btn fc-btn-prev",this.btnPrev.setAttribute("aria-label",h.prev),Es(this.btnPrev,{icon:"chevron-left",label:c.prev,iconOnly:!0}),this.btnRead=document.createElement("button"),this.btnRead.type="button",this.btnRead.className="fc-btn fc-btn-read",this.btnRead.setAttribute("aria-label",h.read),Es(this.btnRead,{icon:"book-open-page-variant",label:c.read,iconOnly:!0}),this.btnNext=document.createElement("button"),this.btnNext.type="button",this.btnNext.className="fc-btn fc-btn-next",this.btnNext.setAttribute("aria-label",h.next),Es(this.btnNext,{icon:"chevron-right",label:c.next,iconOnly:!0});const u=document.createElement("div");u.className="fc-nav-peapod",u.append(this.btnPrev,this.btnRead,this.btnNext),this.chrome.append(u),this.spreadView=new Ln(t.story,t.assets,(m,E)=>this.handleTapActions(m,E),{flipStyle:a??"default",flipSpeed:o}),this.pager=new Sn(t.story,this.spreadView,{mode:l,singleBreakpoint:d}),this.readAloud=new Yr(this.bus),this.sfxAudio=new Audio,this.bus.register(this.sfxAudio,"sfx"),this.stage.appendChild(this.spreadView.element),this.element.append(this.stage,this.captionsEl,this.chrome),this.root.appendChild(this.element),this.wireChrome(),this.wirePager(i),this.wireSpringroll(),this.wireResize(),this.unbindSwipe=Gr(this.stage,{onSwipeLeft:()=>{this.navLocked||this.next()},onSwipeRight:()=>{this.navLocked||this.prev()}}),this.element.addEventListener("keydown",m=>{this.navLocked||(m.key==="ArrowRight"?(m.preventDefault(),this.next()):m.key==="ArrowLeft"?(m.preventDefault(),this.prev()):m.key===" "&&(m.preventDefault(),this.playReadAloud()))}),this.readAloud.onCaption(m=>{this.captionsEl.textContent=m??"",this.captionsEl.hidden=!m})}static async create(e,t){const r={...Jn,...t.features};let i=t.springroll??null,n=null;if(!i){const c=await Vr(r);c&&(i=c.app,n=c.loadGate,Kn(i))}const a=[];t.onProgress&&a.push(t.onProgress);const o=c=>{Rr(i,c);for(const h of a)h(c)};o({stage:"fetch",progress:0,detail:"start"});const l=await Lt(t.story,{baseUrl:t.baseUrl,name:t.storyName,onProgress:o});n==null||n.resolve(),await Br(i);const d=new Ls(e,l,i,t.autoPlayReadAloud??!1,t.chrome??{},t.flipStyle,t.flipSpeed,t.layoutMode,t.singleBreakpoint);return d.pager.updateLayout(e.clientWidth||window.innerWidth,e.clientHeight||window.innerHeight,!1),d.layoutStage(),await d.pager.showInitial(),d.syncChromeNavState(),d.emit("ready",{story:l.story}),d}get story(){return this.loaded.story}get assets(){return this.loaded.assets}get baseUrl(){return this.loaded.baseUrl}get blobUrls(){return this.loaded.blobUrls}get layoutMode(){return this.pager.layoutMode}get layoutPreference(){return this.pager.layoutPreference}get pageIds(){return this.pager.currentPageIds}get spreadIndex(){return this.pager.currentSpread.index}get isNavLocked(){return this.navLocked}getDefaultFontFamily(){return this.defaultFontFamily}setDefaultFontFamily(e){this.defaultFontFamily=e}getExtraFiles(){return this.extraFiles}putExtraFile(e,t){this.extraFiles[e]=t}setNavLocked(e){this.navLocked=e,e?(this.readAloud.stop(),this.chrome.hidden=!0):(this.chrome.hidden=this.chromeHiddenByOptions,this.syncChromeNavState())}getEditableLeaves(){const e=this.pager.currentSpread;return this.spreadView.getEditableLeaves(this.pager.layoutMode,e).map(t=>{var r;return{side:t.side,pageIndex:t.pageIndex,pageId:((r=this.loaded.story.pages[t.pageIndex])==null?void 0:r.id)??"",slot:t.slot}})}getSpreadElement(){return this.spreadView.bookEl}get bookState(){return this.pager.currentBookState}getSpreadPages(){const e=this.pager.currentSpread,t=this.loaded.story.pages;return{left:e.left.kind==="page"?t[e.left.pageIndex]??null:null,right:e.right.kind==="page"?t[e.right.pageIndex]??null:null}}setPageViewsHidden(e){this.spreadView.setPageViewsHidden(e)}remountCurrent(){this.spreadView.remountCurrent(),this.layoutStage()}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var r;return(r=this.listeners.get(e))==null?void 0:r.delete(t)}}next(){return this.navLocked?Promise.resolve():this.navigate(()=>this.pager.next())}prev(){return this.navLocked?Promise.resolve():this.navigate(()=>this.pager.prev())}goTo(e){return this.navigate(()=>this.pager.goTo(e))}setStageZoom(e){this.spreadView.setStageZoom(e),this.stage.classList.toggle("fc-stage-scroll",e.mode==="percent"),this.stage.classList.toggle("fc-stage-fit-page",e.mode==="fit-page"),this.layoutStage()}setLayoutMode(e){this.pager.setLayoutMode(e,this.root.clientWidth||window.innerWidth,this.root.clientHeight||window.innerHeight),this.layoutStage(),this.syncChromeNavState(),this.emit("layoutchange",{layoutMode:this.pager.layoutMode})}setFlipStyle(e){this.spreadView.setFlipStyle(e)}setFlipSpeed(e){this.spreadView.setFlipSpeed(e)}playReadAloud(){if(this.navLocked)return Promise.resolve();const e=this.buildReadAloudClips();return this.readAloud.playSequence(e)}pause(){this.readAloud.pause(),this.bus.setPaused(!0)}resume(){this.bus.setPaused(!1),this.readAloud.resume()}async replaceStory(e,t){var n;this.readAloud.stop();const r=this.loaded,i=await Lt(e,{name:t??(e instanceof File?e.name:void 0)});ws(r),this.loaded=i,this.extraFiles={},this.defaultFontFamily=null,this.spreadView.setLoaded(i.story,i.assets),this.pager.replaceStory(i.story,((n=i.story.pages[0])==null?void 0:n.id)??null),this.layoutStage(),this.syncChromeNavState(),this.emit("ready",{story:i.story})}async openFanciFile(e){if(!jt(e))throw new Error(`Expected a .fanci file, got ${e.name}`);await this.replaceStory(e,e.name)}async updatePage(e){const t=this.loaded.story.pages.findIndex(r=>r.id===e.id);t<0||(this.loaded.story.pages[t]=e,this.spreadView.setStory(this.loaded.story),this.spreadView.remountCurrent(),this.layoutStage())}async setPages(e,t){this.loaded.story.pages=e,this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(t??this.pager.currentPageIds[0]??null),this.layoutStage(),this.syncChromeNavState()}async addPage(){const e=Xn(this.loaded.story);return this.loaded.story.pages.push(e),this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(e.id),this.layoutStage(),this.syncChromeNavState(),e}async removePage(e){var i;if(this.loaded.story.pages.length<=1)return;const t=this.loaded.story.pages.findIndex(n=>n.id===e);if(t<0)return;this.loaded.story.pages.splice(t,1);const r=((i=this.loaded.story.pages[Math.min(t,this.loaded.story.pages.length-1)])==null?void 0:i.id)??null;this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(r),this.layoutStage(),this.syncChromeNavState()}async reorderPages(e,t){const r=this.loaded.story.pages;if(e<0||t<0||e>=r.length||t>=r.length||e===t)return;const[i]=r.splice(e,1);i&&(r.splice(t,0,i),this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(i.id),this.layoutStage(),this.syncChromeNavState())}async setFrontCover(e){this.loaded.story.frontCover=e,this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(this.pager.currentPageIds[0]??null),this.layoutStage(),this.syncChromeNavState()}async setBackCover(e){this.loaded.story.backCover=e,this.spreadView.setStory(this.loaded.story),this.pager.rebuildFromStory(this.pager.currentPageIds[0]??null),this.layoutStage(),this.syncChromeNavState()}async setHardback(e){this.loaded.story.hardback=e,this.spreadView.setStory(this.loaded.story),this.layoutStage()}applyFontToAllText(e){this.defaultFontFamily=e;for(const t of this.loaded.story.pages)for(const r of t.blocks)r.type==="text"&&(r.style={...r.style,fontFamily:e})}async packToBlob(){return Mr(this.loaded.story,{baseUrl:this.loaded.baseUrl,files:{...this.extraFiles}})}async downloadFanci(e){const t=e??`${this.loaded.story.id||"story"}.fanci`,r=await this.packToBlob();Pr(r,t.endsWith(".fanci")?t:`${t}.fanci`)}destroy(){var e,t,r;this.destroyed||(this.destroyed=!0,this.readAloud.destroy(),this.bus.unregister(this.sfxAudio),(e=this.bindings)==null||e.destroy(),(t=this.unbindSwipe)==null||t.call(this),(r=this.resizeObserver)==null||r.disconnect(),this.spreadView.destroy(),this.element.remove(),this.listeners.clear(),ws(this.loaded))}async navigate(e){this.readAloud.stop(),await e(),this.layoutStage()}wireChrome(){this.btnPrev.addEventListener("click",()=>void this.prev()),this.btnNext.addEventListener("click",()=>void this.next()),this.btnRead.addEventListener("click",()=>void this.playReadAloud())}syncChromeNavState(){const e=this.pager.canPrev,t=this.pager.canNext;this.btnPrev.disabled=!e,this.btnNext.disabled=!t,this.btnPrev.classList.toggle("is-disabled",!e),this.btnNext.classList.toggle("is-disabled",!t),this.btnPrev.setAttribute("aria-disabled",String(!e)),this.btnNext.setAttribute("aria-disabled",String(!t))}wirePager(e){this.pager.on("pagechange",t=>{this.syncChromeNavState(),this.emit("pagechange",t),e&&!this.navLocked&&this.playReadAloud()}),this.pager.on("layoutchange",t=>{this.readAloud.stop(),this.layoutStage(),this.syncChromeNavState(),this.emit("layoutchange",t)})}wireSpringroll(){this.bindings=Or(this.springroll,this.bus,{onCaptionsMuted:e=>this.readAloud.setCaptionsMuted(e),onPause:e=>{e?this.readAloud.pause():this.readAloud.resume()}})}wireResize(){const e=()=>{this.pager.updateLayout(this.root.clientWidth||window.innerWidth,this.root.clientHeight||window.innerHeight),this.layoutStage()};typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.root)):window.addEventListener("resize",e)}layoutStage(){const e=this.stage.clientWidth||this.root.clientWidth||window.innerWidth;let t=this.stage.clientHeight||Math.max(320,this.root.clientHeight-64);if(this.spreadView.updateStageSize(e,t,this.pager.layoutMode,this.pager.currentSpread),this.stage.classList.contains("fc-stage-fit-page")){const r=this.stage.clientHeight;r>0&&r!==t&&(t=r,this.spreadView.updateStageSize(e,t,this.pager.layoutMode,this.pager.currentSpread))}}buildReadAloudClips(){const e=this.pager.layoutMode,t=this.pager.currentSpread,r=this.pager.currentBookState;let i=[t.left,t.right];r==="closed-front"?i=[t.left]:r==="closed-back"?i=[t.right]:e==="single"&&(i=t.left.kind==="blank"?[t.right]:t.right.kind==="blank"?[t.left]:[t.left]);const n=[];for(const a of i){if(a.kind!=="page")continue;const o=this.loaded.story.pages[a.pageIndex];if(!o.readAloud)continue;const l=this.loaded.assets.audioUrls.get(o.readAloud.audio);if(!l)continue;const d=this.resolveCues(o.readAloud.cues),c=this.spreadView.getPageElement(o.id);n.push({url:l.url,channel:l.channel,cues:d,root:c})}return n}resolveCues(e){return e?Array.isArray(e)?e:this.loaded.assets.cues.get(e)??[]:[]}handleTapActions(e,t){if(!this.navLocked){for(const r of e)if("play"in r){const i=this.loaded.assets.audioUrls.get(r.play);if(!i)continue;this.sfxAudio.src=i.url,this.bus.applyTo(this.sfxAudio,i.channel),this.sfxAudio.play().catch(()=>{})}else if("toggleClass"in r){const i=t.querySelector(`[data-block-id="${r.toggleClass.target}"]`);i==null||i.classList.toggle(r.toggleClass.className)}}}emit(e,t){const r=this.listeners.get(e);if(r)for(const i of r)i(t)}}function Xn(s){let e=s.pages.length+1,t=`page-${e}`;const r=new Set(s.pages.map(i=>i.id));for(;r.has(t);)e+=1,t=`page-${e}`;return{id:t,background:{color:"#faf6ef"},blocks:[]}}function Kn(s){var t,r,i,n,a,o;const e=s.state;e&&((t=e.pause)==null||t.subscribe(()=>{}),(r=e.soundVolume)==null||r.subscribe(()=>{}),(i=e.voVolume)==null||i.subscribe(()=>{}),(n=e.sfxVolume)==null||n.subscribe(()=>{}),(a=e.musicVolume)==null||a.subscribe(()=>{}),(o=e.captionsMuted)==null||o.subscribe(()=>{}))}function He(s,e=0,t=0){if(s==null)return e;if(typeof s=="number")return Number.isFinite(s)?s:e;const r=s.trim();if(/^-?\d+(\.\d+)?$/.test(r)){const a=Number(r);return Number.isFinite(a)?a:e}const i=r.match(/^(-?\d+(?:\.\d+)?)%$/);if(i){const a=Number(i[1]);return!Number.isFinite(a)||!(t>0)?e:a/100*t}const n=r.match(/^(-?\d+(?:\.\d+)?)px$/i);if(n){const a=Number(n[1]);return Number.isFinite(a)?a:e}return e}function De(s,e){const{width:t,height:r}=e;return{x:Math.round(He(s==null?void 0:s.x,0,t)),y:Math.round(He(s==null?void 0:s.y,0,r)),width:Math.round(He(s==null?void 0:s.width,t,t)),height:Math.round(He(s==null?void 0:s.height,r*.25,r))}}function Ot(s){return typeof s=="string"&&/%$/.test(s.trim())}function dt(s,e){if(!(e>0))return"0%";const t=s/e*100,r=Math.round(t*10)/10;return Number.isInteger(r)?`${r}%`:`${r}%`}function Vt(s,e,t,r,i,n,a={}){const o=De(i,n),l=Math.abs(o.x-s)<=1&&Math.abs(o.y-e)<=1&&Math.abs(o.width-t)<=1,d=Math.abs(o.height-r)<=1;if(l&&(a.preserveHeight||d)&&i)return{...i};const c=Ot(i==null?void 0:i.x)||Ot(i==null?void 0:i.y)||Ot(i==null?void 0:i.width)||Ot(i==null?void 0:i.height),h=a.preserveHeight&&(i==null?void 0:i.height)!=null?i.height:r;return c?{...i,x:dt(s,n.width),y:dt(e,n.height),width:dt(t,n.width),height:typeof h=="string"||typeof h=="number"?typeof h=="number"?dt(h,n.height):h:dt(r,n.height)}:{...i,x:s,y:e,width:t,height:typeof h=="number"?Math.round(h):h}}function Hr(s,e,t=1.35){if(s==null)return t;if(typeof s=="number")return s>0?s:t;const r=s.trim();if(/^-?\d+(\.\d+)?$/.test(r)){const a=Number(r);return a>0?a:t}const i=r.match(/^(-?\d+(?:\.\d+)?)%$/);if(i){const a=Number(i[1])/100;return a>0?a:t}const n=r.match(/^(-?\d+(?:\.\d+)?)px$/i);if(n&&e>0){const a=Number(n[1])/e;return a>0?a:t}return t}const Qn=1;function ea(s,e,t){if(e.width===t.width&&e.height===t.height)return;const r=t.width/e.width,i=t.height/e.height;for(const n of s){const a=De(n.layout,e);n.layout={...n.layout,x:Math.round(a.x*r),y:Math.round(a.y*i),width:Math.max(1,Math.round(a.width*r)),height:Math.max(1,Math.round(a.height*i))}}}function Ms(s){return typeof DOMParser>"u"?s.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim():(new DOMParser().parseFromString(s,"text/html").body.textContent??"").replace(/\u00a0/g," ")}function Dr(s){return`<p>${s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\n/g,"<br/>")}</p>`}function Wr(s){return s.type==="text"||s.type==="image"||s.type==="hotspot"}function Ps(s,e,t,r,i){var d;const n=(i==null?void 0:i.syncHotspots)===!0,a=new Map;for(const c of e.blocks)c.type!=="hotspot"&&a.set(c.id,{...c});const o=[];for(const c of s){const h=c.blockId,u=c.blockType;if(!h||!u)continue;const g=a.get(h),x=Math.round(c.left??0),v=Math.round(c.top??0);if(u==="text"){const f=Math.round(c.width??0),b=Math.round(c.height??0),_=c.text??"",m=g&&g.type==="text"?g:void 0,E=m?Ms(m.html??""):"",R=m&&E===_&&m.html?m.html:Dr(_),L=m==null?void 0:m.style,O={fontFamily:c.fontFamily||(L==null?void 0:L.fontFamily),fontSize:c.fontSize!=null?`${Math.round(c.fontSize)}px`:L==null?void 0:L.fontSize,color:typeof c.fill=="string"?c.fill:L==null?void 0:L.color,textAlign:c.textAlign??(L==null?void 0:L.textAlign),lineHeight:c.lineHeight??(L==null?void 0:L.lineHeight),fontWeight:c.fontWeight||(L==null?void 0:L.fontWeight),fontStyle:c.fontStyle||(L==null?void 0:L.fontStyle)};o.push({id:h,type:"text",layout:Vt(x,v,f,b,m==null?void 0:m.layout,t,{preserveHeight:!0}),html:R,style:O,htmlSrc:m==null?void 0:m.htmlSrc})}else if(u==="image"){const f=Math.round((c.width??0)*(c.scaleX??1)),b=Math.round((c.height??0)*(c.scaleY??1)),_=c.assetId??(g&&g.type==="image"?g.asset:void 0);if(!_)continue;const m=g&&g.type==="image"?g:void 0,E=Vt(x,v,f,b,m==null?void 0:m.layout,t),R=c.fit??((d=m==null?void 0:m.layout)==null?void 0:d.fit);R&&(E.fit=R),o.push({id:h,type:"image",asset:_,layout:E,className:m==null?void 0:m.className})}else if(u==="hotspot"){const f=Math.round((c.width??0)*(c.scaleX??1)),b=Math.round((c.height??0)*(c.scaleY??1)),_=g&&g.type==="hotspot"?g:void 0;o.push({id:h,type:"hotspot",layout:Vt(x,v,f,b,_==null?void 0:_.layout,t),onTap:c.onTap??(_==null?void 0:_.onTap)??[],ariaLabel:c.ariaLabel??(_==null?void 0:_.ariaLabel)})}}for(const c of e.blocks)Wr(c)&&(c.type==="hotspot"&&n||o.some(h=>h.id===c.id)||o.push(c));let l=e.background?{...e.background}:void 0;return typeof r=="string"&&r&&(l={...l,color:r}),{...e,background:l,blocks:o}}function Is(s,e,t){var n,a,o,l,d,c,h,u,g,x,v;const r={color:((n=s.background)==null?void 0:n.color)??"#faf6ef"};(a=s.background)!=null&&a.asset&&(r.imageAssetId=s.background.asset,r.imageSrc=(o=e.images.get(s.background.asset))==null?void 0:o.src);const i=[];for(const f of s.blocks)if(Wr(f)){if(f.type==="text"){const b=f.html??e.html.get(`htmlSrc:${f.id}`)??(f.htmlSrc?e.html.get(f.htmlSrc):void 0)??"",_=De(f.layout,t),m=He((l=f.style)==null?void 0:l.fontSize,18)||18;i.push({kind:"text",blockId:f.id,text:Ms(b),left:_.x,top:_.y,width:Math.max(20,_.width),fontFamily:((d=f.style)==null?void 0:d.fontFamily)??"Georgia, serif",fontSize:m,fill:((c=f.style)==null?void 0:c.color)??"#1f1a14",textAlign:((h=f.style)==null?void 0:h.textAlign)??"left",lineHeight:Hr((u=f.style)==null?void 0:u.lineHeight,m,1.35),fontWeight:(g=f.style)==null?void 0:g.fontWeight,fontStyle:(x=f.style)==null?void 0:x.fontStyle})}else if(f.type==="image"){const b=e.images.get(f.asset);if(!(b!=null&&b.src))continue;const _=De(f.layout,t);i.push({kind:"image",blockId:f.id,assetId:f.asset,left:_.x,top:_.y,width:_.width,height:_.height,src:b.src,fit:(v=f.layout)==null?void 0:v.fit})}else if(f.type==="hotspot"){const b=De(f.layout,t);i.push({kind:"hotspot",blockId:f.id,left:b.x,top:b.y,width:b.width,height:b.height,ariaLabel:f.ariaLabel,onTap:f.onTap})}}return{background:r,objects:i}}function ta(s){return s.blockType==="image"||s.blockType==="hotspot"?Math.round((s.width??0)*(s.scaleX??1)):Math.round(s.width??0)}function qr(s){return s.blockType==="image"||s.blockType==="hotspot"?Math.round((s.height??0)*(s.scaleY??1)):Math.round(s.height??0)}function sa(s){return`${s}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ra(s,e){return{...s,left:s.left+e}}function ia(s,e,t,r){const i=[];let n=null,a=null;if(s){const o=Is(s,t,r);n=o.background,i.push(...o.objects)}if(e){const o=Is(e,t,r);a=o.background;for(const l of o.objects)i.push(ra(l,r.width))}return{pageSize:r,spreadWidth:r.width*2,leftBackground:n,rightBackground:a,objects:i}}function na(s,e,t,r,i,n){const a=r.width,o=[],l=[];for(const h of s){if(!h.blockId||!h.blockType)continue;const u=h.left??0,g=ta(h),x=u+g,v=x<=a+.5,f=u>=a-.5;if(v){o.push({...h});continue}if(f){l.push({...h,left:u-a});continue}const b=Math.max(1,Math.round(a-u)),_=Math.max(1,Math.round(x-a));o.push({...h,width:b,scaleX:1,scaleY:1,height:qr(h)}),l.push({...h,blockId:sa(h.blockId),left:0,width:_,scaleX:1,scaleY:1,height:qr(h)})}const d=e!=null?Ps(o,e,r,i==null?void 0:i.left,n):null,c=t!=null?Ps(l,t,r,i==null?void 0:i.right,n):null;return{left:d,right:c}}return S.CueTimeline=$s,S.DEFAULT_FLIP_SPEED_MS=$r,S.DEFAULT_LAYOUT_MODE=wr,S.DEFAULT_SINGLE_BREAKPOINT=Sr,S.DefaultFlipStyle=Ft,S.FABRIC_CSS_FONT_SIZE_MULT=Qn,S.FANCI_EXTENSION=Et,S.FlipStyle=lt,S.HARDBACK_EDGE_RATIO=xs,S.Storybook=Ls,S.bindApplication=Or,S.boxToPixels=De,S.buildBackCoverSpread=Cr,S.buildFrontCoverSpread=xr,S.buildSingleSpreads=Tr,S.buildSpreads=Pt,S.buildTwoPageSpreads=Ar,S.contentPageIds=Er,S.createFlipStyle=Ss,S.createSpringrollApplication=Vr,S.downloadBlob=Pr,S.extensionOf=Os,S.fabricLikeToPage=Ps,S.findFanciFile=Jr,S.findSpreadIndexForPage=Ze,S.findStoryJsonPath=ys,S.getRegisteredFlipStyle=_n,S.hardbackEnabled=Cs,S.hardbackOverhang=Fr,S.htmlToPlainText=Ms,S.isFanciFile=jt,S.listRegisteredFlipStyles=Nr,S.loadEpubFromBytes=rn,S.loadEpubFromZip=ms,S.loadFanciFromBytes=fn,S.loadFanciFromZip=vs,S.loadStory=Lt,S.packFanci=Mr,S.pageToFabricLike=Is,S.pagesToSpreadFabricLike=ia,S.parseStory=ze,S.parseVtt=Qt,S.plainTextToHtml=Dr,S.primaryPageId=Lr,S.registerFlipStyle=Ir,S.reportSpringrollLoaded=Mn,S.reportSpringrollProgress=Rr,S.resolveCssLineHeight=Hr,S.resolveFlipSpeedMs=_s,S.resolveLayoutMode=_r,S.revokeLoadedStory=ws,S.scaleBlocksToPageSize=ea,S.serializeLayoutBox=Vt,S.spreadFabricLikeToPages=na,S.storySchema=Qs,S.toPx=He,S.waitForSpringrollReady=Br,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"}),S})({});