@makefully/fancifully 0.1.0 → 0.2.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 (41) hide show
  1. package/CHANGELOG.md +31 -12
  2. package/LICENSE +21 -21
  3. package/README.md +250 -147
  4. package/dist/Storybook.d.ts +68 -0
  5. package/dist/Storybook.d.ts.map +1 -1
  6. package/dist/editor/EditorChrome.d.ts +33 -0
  7. package/dist/editor/EditorChrome.d.ts.map +1 -0
  8. package/dist/editor/PageCanvas.d.ts +50 -0
  9. package/dist/editor/PageCanvas.d.ts.map +1 -0
  10. package/dist/editor/dropImport.d.ts +16 -0
  11. package/dist/editor/dropImport.d.ts.map +1 -0
  12. package/dist/editor/index.d.ts +7 -0
  13. package/dist/editor/index.d.ts.map +1 -0
  14. package/dist/editor/layoutUnits.d.ts +39 -0
  15. package/dist/editor/layoutUnits.d.ts.map +1 -0
  16. package/dist/editor/packFanci.d.ts +16 -0
  17. package/dist/editor/packFanci.d.ts.map +1 -0
  18. package/dist/editor/storyFabricMap.d.ts +29 -0
  19. package/dist/editor/storyFabricMap.d.ts.map +1 -0
  20. package/dist/fancifully.css +1 -1
  21. package/dist/fancifully.iife.js +4 -8
  22. package/dist/fancifully.js +3432 -2065
  23. package/dist/flip/DefaultFlipStyle.d.ts +11 -0
  24. package/dist/flip/DefaultFlipStyle.d.ts.map +1 -0
  25. package/dist/flip/FlipStyle.d.ts +47 -0
  26. package/dist/flip/FlipStyle.d.ts.map +1 -0
  27. package/dist/flip/index.d.ts +4 -0
  28. package/dist/flip/index.d.ts.map +1 -0
  29. package/dist/index.d.ts +8 -3
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/nav/Pager.d.ts +18 -3
  32. package/dist/nav/Pager.d.ts.map +1 -1
  33. package/dist/nav/hardback.d.ts +21 -0
  34. package/dist/nav/hardback.d.ts.map +1 -0
  35. package/dist/nav/layoutMode.d.ts +43 -3
  36. package/dist/nav/layoutMode.d.ts.map +1 -1
  37. package/dist/render/SpreadView.d.ts +48 -2
  38. package/dist/render/SpreadView.d.ts.map +1 -1
  39. package/dist/schema/story.d.ts +30 -6
  40. package/dist/schema/story.d.ts.map +1 -1
  41. package/package.json +75 -74
@@ -1,8 +1,4 @@
1
- var Fancifully=(function(T){"use strict";var hr=Object.defineProperty;var pr=(T,Y,te)=>Y in T?hr(T,Y,{enumerable:!0,configurable:!0,writable:!0,value:te}):T[Y]=te;var g=(T,Y,te)=>pr(T,typeof Y!="symbol"?Y+"":Y,te);class Y{constructor(){g(this,"volumes",{sound:1,vo:1,sfx:1,music:1});g(this,"elements",new Set);g(this,"paused",!1)}setVolume(e,t){this.volumes[e]=te(t),this.applyAll()}getVolume(e){return te(this.volumes.sound)*te(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 te(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}class Rt{constructor(e=[]){g(this,"cues");g(this,"root",null);g(this,"lastActiveId",null);g(this,"readIds",new Set);this.cues=[...e].sort((t,n)=>t.start-n.start)}setCues(e){this.cues=[...e].sort((t,n)=>t.start-n.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(n=>e>=n.start&&e<n.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(n=>n.classList.remove("is-active"));const t=this.root.querySelector(`#${Lt(e)}, [data-cue-id="${Mt(e)}"]`);t&&t.classList.add("fc-cue","is-active","is-read");for(const n of this.readIds){if(n===e)continue;const r=this.root.querySelector(`#${Lt(n)}, [data-cue-id="${Mt(n)}"]`);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 Lt(s){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}function Mt(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}class Ns{constructor(e){g(this,"bus");g(this,"audio");g(this,"timeline",new Rt);g(this,"queue",[]);g(this,"raf",0);g(this,"captionsMuted",!1);g(this,"onCaptionLine",null);g(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 n=this.timeline.update(this.audio.currentTime);this.captionsMuted||(t=this.onCaptionLine)==null||t.call(this,(n==null?void 0:n.text)??(n==null?void 0:n.id)??null)}this.raf=requestAnimationFrame(e)}};this.raf=requestAnimationFrame(e)}cancelTick(){this.raf&&(cancelAnimationFrame(this.raf),this.raf=0)}}function Is(s,e){let t=0,n=0,r=!1;const i=c=>{c.button!=null&&c.button!==0||(r=!0,t=c.clientX,n=c.clientY)},a=c=>{var h,y;if(!r)return;r=!1;const l=c.clientX-t,d=c.clientY-n;Math.abs(l)<50||Math.abs(l)<Math.abs(d)||(l<0?(h=e.onSwipeLeft)==null||h.call(e):(y=e.onSwipeRight)==null||y.call(e))},o=()=>{r=!1};return s.addEventListener("pointerdown",i),s.addEventListener("pointerup",a),s.addEventListener("pointercancel",o),()=>{s.removeEventListener("pointerdown",i),s.removeEventListener("pointerup",a),s.removeEventListener("pointercancel",o)}}var x;(function(s){s.assertEqual=r=>{};function e(r){}s.assertIs=e;function t(r){throw new Error}s.assertNever=t,s.arrayToEnum=r=>{const i={};for(const a of r)i[a]=a;return i},s.getValidEnumValues=r=>{const i=s.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of i)a[o]=r[o];return s.objectValues(a)},s.objectValues=r=>s.objectKeys(r).map(function(i){return r[i]}),s.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&i.push(a);return i},s.find=(r,i)=>{for(const a of r)if(i(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 n(r,i=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s.joinValues=n,s.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(x||(x={}));var Zt;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Zt||(Zt={}));const p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),se=s=>{switch(typeof s){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(s)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(s)?p.array:s===null?p.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?p.promise:typeof Map<"u"&&s instanceof Map?p.map:typeof Set<"u"&&s instanceof Set?p.set:typeof Date<"u"&&s instanceof Date?p.date:p.object;default:return p.unknown}},u=x.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 G extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};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(i){return i.message},n={_errors:[]},r=i=>{for(const a of i.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)n._errors.push(t(a));else{let o=n,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(a))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return r(this),n}static assert(e){if(!(e instanceof G))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}G.create=s=>new G(s);const nt=(s,e)=>{let t;switch(s.code){case u.invalid_type:s.received===p.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,x.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(s.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(s.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(s.options)}, received '${s.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.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}"`:x.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case u.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 u.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 u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(s)}return{message:t}};let $s=nt;function Ps(){return $s}const Os=s=>{const{data:e,path:t,errorMaps:n,issueData:r}=s,i=[...t,...r.path||[]],a={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let o="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)o=l(a,{data:e,defaultError:o}).message;return{...r,path:i,message:o}};function f(s,e){const t=Ps(),n=Os({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===nt?void 0:nt].filter(r=>!!r)});s.common.issues.push(n)}class O{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if(r.status==="aborted")return v;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const i=await r.key,a=await r.value;n.push({key:i,value:a})}return O.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:i,value:a}=r;if(i.status==="aborted"||a.status==="aborted")return v;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const v=Object.freeze({status:"aborted"}),Ae=s=>({status:"dirty",value:s}),z=s=>({status:"valid",value:s}),jt=s=>s.status==="aborted",Vt=s=>s.status==="dirty",he=s=>s.status==="valid",ze=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(m||(m={}));class D{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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 zt=(s,e)=>{if(he(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 G(s.common.issues);return this._error=t,this._error}}};function b(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:r}=s;if(e&&(t||n))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:c}=s;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:r}}class w{get description(){return this._def.description}_getType(e){return se(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new O,ctx:{common:e.parent.common,data:e.data,parsedType:se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ze(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={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:se(e)},r=this._parseSync({data:e,path:n.path,parent:n});return zt(n,r)}"~validate"(e){var n,r;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:se(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return he(i)?{value:i.value}:{issues:t.common.issues}}catch(i){(r=(n=i==null?void 0:i.message)==null?void 0:n.toLowerCase())!=null&&r.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>he(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={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:se(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(ze(r)?r:Promise.resolve(r));return zt(n,i)}refine(e,t){const n=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const a=e(r),o=()=>i.addIssue({code:u.custom,...n(r)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new le({schema:this,typeName:_.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 ee.create(this,this._def)}nullable(){return ue.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return qe.create(this,this._def)}or(e){return Fe.create([this,e],this._def)}and(e){return Ue.create(this,e,this._def)}transform(e){return new le({...b(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new He({...b(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new Gt({typeName:_.ZodBranded,type:this,...b(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Je({...b(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return dt.create(this,e)}readonly(){return Xe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Rs=/^c[^\s-]{8,}$/i,Ls=/^[0-9a-z]+$/,Ms=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zs=/^[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,js=/^[a-z0-9_-]{21}$/i,Vs=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zs=/^[-+]?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)?)??$/,Bs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let rt;const Us=/^(?:(?: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])$/,Ds=/^(?:(?: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])$/,Ws=/^(([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]))$/,qs=/^(([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])$/,Hs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Js=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bt="((\\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])))",Xs=new RegExp(`^${Bt}$`);function Ft(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 Ys(s){return new RegExp(`^${Ft(s)}$`)}function Gs(s){let e=`${Bt}T${Ft(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 Qs(s,e){return!!((e==="v4"||!e)&&Us.test(s)||(e==="v6"||!e)&&Ws.test(s))}function Ks(s,e){if(!Vs.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(n));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 en(s,e){return!!((e==="v4"||!e)&&Ds.test(s)||(e==="v6"||!e)&&qs.test(s))}class Q extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){const i=this._getOrReturnCtx(e);return f(i,{code:u.invalid_type,expected:p.string,received:i.parsedType}),v}const n=new O;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?f(r,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&f(r,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Bs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")rt||(rt=new RegExp(Fs,"u")),rt.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")js.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"nanoid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Rs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Ls.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Ms.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:u.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:u.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Gs(i).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Xs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Ys(i).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?zs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"duration",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Qs(e.data,i.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?Ks(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"jwt",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?en(e.data,i.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cidr",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Hs.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Js.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64url",code:u.invalid_string,message:i.message}),n.dirty()):x.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(r=>e.test(r),{validation:t,code:u.invalid_string,...m.errToObj(n)})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.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,...m.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,...m.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...m.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new Q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Q({...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}}Q.create=s=>new Q({checks:[],typeName:_.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...b(s)});function tn(s,e){const t=(s.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=t>n?t:n,i=Number.parseInt(s.toFixed(r).replace(".","")),a=Number.parseInt(e.toFixed(r).replace(".",""));return i%a/10**r}class pe extends w{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)!==p.number){const i=this._getOrReturnCtx(e);return f(i,{code:u.invalid_type,expected:p.number,received:i.parsedType}),v}let n;const r=new O;for(const i of this._def.checks)i.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?tn(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.not_finite,message:i.message}),r.dirty()):x.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,n,r){return new pe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(r)}]})}_addCheck(e){return new pe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.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"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}pe.create=s=>new pe({checks:[],typeName:_.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...b(s)});class Te extends w{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)!==p.bigint)return this._getInvalidInput(e);let n;const r=new O;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):x.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:p.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,n,r){return new Te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:m.toString(r)}]})}_addCheck(e){return new Te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.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}}Te.create=s=>new Te({checks:[],typeName:_.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...b(s)});class Ut extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.boolean,received:n.parsedType}),v}return z(e.data)}}Ut.create=s=>new Ut({typeName:_.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...b(s)});class Be extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){const i=this._getOrReturnCtx(e);return f(i,{code:u.invalid_type,expected:p.date,received:i.parsedType}),v}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return f(i,{code:u.invalid_date}),v}const n=new O;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):x.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Be({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.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}}Be.create=s=>new Be({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:_.ZodDate,...b(s)});class Dt extends w{_parse(e){if(this._getType(e)!==p.symbol){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.symbol,received:n.parsedType}),v}return z(e.data)}}Dt.create=s=>new Dt({typeName:_.ZodSymbol,...b(s)});class it extends w{_parse(e){if(this._getType(e)!==p.undefined){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.undefined,received:n.parsedType}),v}return z(e.data)}}it.create=s=>new it({typeName:_.ZodUndefined,...b(s)});class at extends w{_parse(e){if(this._getType(e)!==p.null){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.null,received:n.parsedType}),v}return z(e.data)}}at.create=s=>new at({typeName:_.ZodNull,...b(s)});class Wt extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}}Wt.create=s=>new Wt({typeName:_.ZodAny,...b(s)});class qt extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}}qt.create=s=>new qt({typeName:_.ZodUnknown,...b(s)});class ne extends w{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:p.never,received:t.parsedType}),v}}ne.create=s=>new ne({typeName:_.ZodNever,...b(s)});class Ht extends w{_parse(e){if(this._getType(e)!==p.undefined){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.void,received:n.parsedType}),v}return z(e.data)}}Ht.create=s=>new Ht({typeName:_.ZodVoid,...b(s)});class W extends w{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==p.array)return f(t,{code:u.invalid_type,expected:p.array,received:t.parsedType}),v;if(r.exactLength!==null){const a=t.data.length>r.exactLength.value,o=t.data.length<r.exactLength.value;(a||o)&&(f(t,{code:a?u.too_big:u.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}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(f(t,{code:u.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(f(t,{code:u.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>r.type._parseAsync(new D(t,a,t.path,o)))).then(a=>O.mergeArray(n,a));const i=[...t.data].map((a,o)=>r.type._parseSync(new D(t,a,t.path,o)));return O.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}W.create=(s,e)=>new W({type:s,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...b(e)});function me(s){if(s instanceof N){const e={};for(const t in s.shape){const n=s.shape[t];e[t]=ee.create(me(n))}return new N({...s._def,shape:()=>e})}else return s instanceof W?new W({...s._def,type:me(s.element)}):s instanceof ee?ee.create(me(s.unwrap())):s instanceof ue?ue.create(me(s.unwrap())):s instanceof oe?oe.create(s.items.map(e=>me(e))):s}class N extends w{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=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==p.object){const l=this._getOrReturnCtx(e);return f(l,{code:u.invalid_type,expected:p.object,received:l.parsedType}),v}const{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof ne&&this._def.unknownKeys==="strip"))for(const l in r.data)a.includes(l)||o.push(l);const c=[];for(const l of a){const d=i[l],h=r.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new D(r,h,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof ne){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(l==="strict")o.length>0&&(f(r,{code:u.unrecognized_keys,keys:o}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of o){const h=r.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new D(r,h,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of c){const h=await d.key,y=await d.value;l.push({key:h,value:y,alwaysSet:d.alwaysSet})}return l}).then(l=>O.mergeObjectSync(n,l)):O.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new N({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,a;const r=((a=(i=this._def).errorMap)==null?void 0:a.call(i,t,n).message)??n.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(e){return new N({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new N({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new N({...this._def,catchall:e})}pick(e){const t={};for(const n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new N({...this._def,shape:()=>t})}omit(e){const t={};for(const n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new N({...this._def,shape:()=>t})}deepPartial(){return me(this)}partial(e){const t={};for(const n of x.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new N({...this._def,shape:()=>t})}required(e){const t={};for(const n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ee;)i=i._def.innerType;t[n]=i}return new N({...this._def,shape:()=>t})}keyof(){return Xt(x.objectKeys(this.shape))}}N.create=(s,e)=>new N({shape:()=>s,unknownKeys:"strip",catchall:ne.create(),typeName:_.ZodObject,...b(e)}),N.strictCreate=(s,e)=>new N({shape:()=>s,unknownKeys:"strict",catchall:ne.create(),typeName:_.ZodObject,...b(e)}),N.lazycreate=(s,e)=>new N({shape:s,unknownKeys:"strip",catchall:ne.create(),typeName:_.ZodObject,...b(e)});class Fe extends w{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function r(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new G(o.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:a}),v}if(t.common.async)return Promise.all(n.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let i;const a=[];for(const c of n){const l={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new G(c));return f(t,{code:u.invalid_union,unionErrors:o}),v}}get options(){return this._def.options}}Fe.create=(s,e)=>new Fe({options:s,typeName:_.ZodUnion,...b(e)});const K=s=>s instanceof lt?K(s.schema):s instanceof le?K(s.innerType()):s instanceof We?[s.value]:s instanceof ce?s.options:s instanceof ut?x.objectValues(s.enum):s instanceof He?K(s._def.innerType):s instanceof it?[void 0]:s instanceof at?[null]:s instanceof ee?[void 0,...K(s.unwrap())]:s instanceof ue?[null,...K(s.unwrap())]:s instanceof Gt||s instanceof Xe?K(s.unwrap()):s instanceof Je?K(s._def.innerType):[];class ot extends w{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return f(t,{code:u.invalid_type,expected:p.object,received:t.parsedType}),v;const n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const r=new Map;for(const i of t){const a=K(i.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,i)}}return new ot({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...b(n)})}}function ct(s,e){const t=se(s),n=se(e);if(s===e)return{valid:!0,data:s};if(t===p.object&&n===p.object){const r=x.objectKeys(e),i=x.objectKeys(s).filter(o=>r.indexOf(o)!==-1),a={...s,...e};for(const o of i){const c=ct(s[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===p.array&&n===p.array){if(s.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<s.length;i++){const a=s[i],o=e[i],c=ct(a,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return t===p.date&&n===p.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class Ue extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(i,a)=>{if(jt(i)||jt(a))return v;const o=ct(i.value,a.value);return o.valid?((Vt(i)||Vt(a))&&t.dirty(),{status:t.value,value:o.data}):(f(n,{code:u.invalid_intersection_types}),v)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>r(i,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ue.create=(s,e,t)=>new Ue({left:s,right:e,typeName:_.ZodIntersection,...b(t)});class oe extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return f(n,{code:u.invalid_type,expected:p.array,received:n.parsedType}),v;if(n.data.length<this._def.items.length)return f(n,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new D(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>O.mergeArray(t,a)):O.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new oe({...this._def,rest:e})}}oe.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:s,typeName:_.ZodTuple,rest:null,...b(e)})};class De extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return f(n,{code:u.invalid_type,expected:p.object,received:n.parsedType}),v;const r=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)r.push({key:i._parse(new D(n,o,n.path,o)),value:a._parse(new D(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?O.mergeObjectAsync(t,r):O.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof w?new De({keyType:e,valueType:t,typeName:_.ZodRecord,...b(n)}):new De({keyType:Q.create(),valueType:e,typeName:_.ZodRecord,...b(t)})}}class Jt extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return f(n,{code:u.invalid_type,expected:p.map,received:n.parsedType}),v;const r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],l)=>({key:r._parse(new D(n,o,n.path,[l,"key"])),value:i._parse(new D(n,c,n.path,[l,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return v;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(l.value,d.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return v;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(l.value,d.value)}return{status:t.value,value:o}}}}Jt.create=(s,e,t)=>new Jt({valueType:e,keyType:s,typeName:_.ZodMap,...b(t)});class Ce extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return f(n,{code:u.invalid_type,expected:p.set,received:n.parsedType}),v;const r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(f(n,{code:u.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(f(n,{code:u.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function a(c){const l=new Set;for(const d of c){if(d.status==="aborted")return v;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}const o=[...n.data.values()].map((c,l)=>i._parse(new D(n,c,n.path,l)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new Ce({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new Ce({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ce.create=(s,e)=>new Ce({valueType:s,minSize:null,maxSize:null,typeName:_.ZodSet,...b(e)});class lt extends w{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})}}lt.create=(s,e)=>new lt({getter:s,typeName:_.ZodLazy,...b(e)});class We extends w{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}We.create=(s,e)=>new We({value:s,typeName:_.ZodLiteral,...b(e)});function Xt(s,e){return new ce({values:s,typeName:_.ZodEnum,...b(e)})}class ce extends w{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{expected:x.joinValues(n),received:t.parsedType,code:u.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:n}),v}return z(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 ce.create(e,{...this._def,...t})}exclude(e,t=this._def){return ce.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}ce.create=Xt;class ut extends w{_parse(e){const t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){const r=x.objectValues(t);return f(n,{expected:x.joinValues(r),received:n.parsedType,code:u.invalid_type}),v}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=x.objectValues(t);return f(n,{received:n.data,code:u.invalid_enum_value,options:r}),v}return z(e.data)}get enum(){return this._def.values}}ut.create=(s,e)=>new ut({values:s,typeName:_.ZodNativeEnum,...b(e)});class qe extends w{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return f(t,{code:u.invalid_type,expected:p.promise,received:t.parsedType}),v;const n=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return z(n.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}qe.create=(s,e)=>new qe({type:s,typeName:_.ZodPromise,...b(e)});class le extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:a=>{f(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const a=r.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return v;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?v:c.status==="dirty"||t.value==="dirty"?Ae(c.value):c});{if(t.value==="aborted")return v;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?v:o.status==="dirty"||t.value==="dirty"?Ae(o.value):o}}if(r.type==="refinement"){const a=o=>{const c=r.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(r.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!he(a))return v;const o=r.transform(a.value,i);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:n.data,path:n.path,parent:n}).then(a=>he(a)?Promise.resolve(r.transform(a.value,i)).then(o=>({status:t.value,value:o})):v);x.assertNever(r)}}le.create=(s,e,t)=>new le({schema:s,typeName:_.ZodEffects,effect:e,...b(t)}),le.createWithPreprocess=(s,e,t)=>new le({schema:e,effect:{type:"preprocess",transform:s},typeName:_.ZodEffects,...b(t)});class ee extends w{_parse(e){return this._getType(e)===p.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ee.create=(s,e)=>new ee({innerType:s,typeName:_.ZodOptional,...b(e)});class ue extends w{_parse(e){return this._getType(e)===p.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ue.create=(s,e)=>new ue({innerType:s,typeName:_.ZodNullable,...b(e)});class He extends w{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}He.create=(s,e)=>new He({innerType:s,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});class Je extends w{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ze(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new G(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new G(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Je.create=(s,e)=>new Je({innerType:s,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});class Yt extends w{_parse(e){if(this._getType(e)!==p.nan){const n=this._getOrReturnCtx(e);return f(n,{code:u.invalid_type,expected:p.nan,received:n.parsedType}),v}return{status:"valid",value:e.data}}}Yt.create=s=>new Yt({typeName:_.ZodNaN,...b(s)});class Gt extends w{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class dt extends w{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?v:i.status==="dirty"?(t.dirty(),Ae(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?v:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new dt({in:e,out:t,typeName:_.ZodPipeline})}}class Xe extends w{_parse(e){const t=this._def.innerType._parse(e),n=r=>(he(r)&&(r.value=Object.freeze(r.value)),r);return ze(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}}Xe.create=(s,e)=>new Xe({innerType:s,typeName:_.ZodReadonly,...b(e)});var _;(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"})(_||(_={}));const S=Q.create,re=pe.create;ne.create;const Ee=W.create,I=N.create,Ne=Fe.create,Qt=ot.create;Ue.create,oe.create;const sn=De.create,de=We.create,ge=ce.create;qe.create,ee.create,ue.create;const Ye=Ne([re(),S()]),ft=I({x:Ye.optional().default(0),y:Ye.optional().default(0),width:Ye.optional(),height:Ye.optional(),fit:ge(["contain","cover","fill","none"]).optional(),horizontalAlign:ge(["left","center","right"]).optional(),verticalAlign:ge(["top","center","bottom"]).optional()}),nn=I({id:S(),start:re(),end:re(),text:S().optional()}),rn=Qt("type",[I({type:de("image"),src:S()}),I({type:de("audio"),src:S(),channel:ge(["vo","sfx","music"]).optional().default("vo")}),I({type:de("vtt"),src:S()}),I({type:de("html"),src:S()})]),an=Ne([I({play:S()}),I({toggleClass:I({target:S(),className:S()})})]),on=I({id:S(),type:de("text"),layout:ft.optional().default({}),html:S().optional(),htmlSrc:S().optional(),style:I({fontFamily:S().optional(),fontSize:S().optional(),color:S().optional(),textAlign:ge(["left","center","right"]).optional(),lineHeight:Ne([S(),re()]).optional()}).optional()}),cn=I({id:S(),type:de("image"),asset:S(),layout:ft.optional().default({}),className:S().optional()}),ln=I({id:S(),type:de("hotspot"),layout:ft.optional().default({}),onTap:Ee(an).optional().default([]),ariaLabel:S().optional()}),un=Qt("type",[on,cn,ln]),dn=I({id:S(),background:I({asset:S().optional(),color:S().optional()}).optional(),readAloud:I({audio:S(),cues:Ne([S(),Ee(nn)]).optional()}).optional(),blocks:Ee(un).optional().default([])}),Kt=I({id:S(),title:S().optional(),pageSize:I({width:re().positive(),height:re().positive()}),layout:I({mode:ge(["single","two-page","auto"]).default("auto"),singleBreakpoint:re().positive().default(900)}).default({mode:"auto",singleBreakpoint:900}),fonts:Ee(I({family:S(),src:S(),weight:Ne([S(),re()]).optional(),style:S().optional()})).optional().default([]),assets:sn(rn).optional().default({}),pages:Ee(dn).min(1)});function ye(s){return Kt.parse(s)}function ht(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 n=e.slice(e.indexOf(`
3
- `)+1).split(/\n\n+/),r=[];let i=0;for(const a of n){const o=a.split(`
4
- `).map(k=>k.trim()).filter(k=>k.length>0&&!k.startsWith("NOTE"));if(o.length===0)continue;const c=o.findIndex(k=>k.includes("-->"));if(c===-1)continue;const l=c>0?o[0]:void 0,d=o[c],h=o.slice(c+1),y=d.split("-->").map(k=>k.trim().split(/\s+/)[0]);if(y.length<2)continue;const $=es(y[0]),R=es(y[1]),C=h.join(" ").trim(),A=l||C||`cue-${i++}`;r.push({id:A,start:$,end:R,text:C||void 0})}return r}function es(s){const e=s.trim().split(":");if(e.length===3){const[t,n,r]=e;return Number(t)*3600+Number(n)*60+Number(r)}if(e.length===2){const[t,n]=e;return Number(t)*60+Number(n)}return Number(s)}function Ge(s,e){if(/^(?:[a-z]+:)?\/\//i.test(e)||e.startsWith("data:")||e.startsWith("blob:")||!s)return e;try{return new URL(e,pt(s)).href}catch{return`${pt(s)}${e.replace(/^\//,"")}`}}function pt(s){return s.endsWith("/")||s.includes("?")?s.endsWith("/")?s:`${s}/`:/\.[a-z0-9]+$/i.test(s.split("/").pop()??"")?s.replace(/[^/]+$/,""):`${s}/`}function fn(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 pt(s.replace(/[^/]+$/,""))}}async function Ie(s,e){typeof document>"u"||!("fonts"in document)||await Promise.all(s.fonts.map(async t=>{const n=Ge(e,t.src),i=await new FontFace(t.family,`url(${JSON.stringify(n)})`,{weight:t.weight!=null?String(t.weight):"normal",style:t.style??"normal"}).load();document.fonts.add(i)}))}var j=Uint8Array,ve=Uint16Array,hn=Int32Array,ts=new j([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]),ss=new j([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]),pn=new j([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ns=function(s,e){for(var t=new ve(31),n=0;n<31;++n)t[n]=e+=1<<s[n-1];for(var r=new hn(t[30]),n=1;n<30;++n)for(var i=t[n];i<t[n+1];++i)r[i]=i-t[n]<<5|n;return{b:t,r}},rs=ns(ts,2),is=rs.b,mn=rs.r;is[28]=258,mn[258]=28;for(var gn=ns(ss,0),yn=gn.b,mt=new ve(32768),E=0;E<32768;++E){var ie=(E&43690)>>1|(E&21845)<<1;ie=(ie&52428)>>2|(ie&13107)<<2,ie=(ie&61680)>>4|(ie&3855)<<4,mt[E]=((ie&65280)>>8|(ie&255)<<8)>>1}for(var $e=(function(s,e,t){for(var n=s.length,r=0,i=new ve(e);r<n;++r)s[r]&&++i[s[r]-1];var a=new ve(e);for(r=1;r<e;++r)a[r]=a[r-1]+i[r-1]<<1;var o;if(t){o=new ve(1<<e);var c=15-e;for(r=0;r<n;++r)if(s[r])for(var l=r<<4|s[r],d=e-s[r],h=a[s[r]-1]++<<d,y=h|(1<<d)-1;h<=y;++h)o[mt[h]>>c]=l}else for(o=new ve(n),r=0;r<n;++r)s[r]&&(o[r]=mt[a[s[r]-1]++]>>15-s[r]);return o}),Pe=new j(288),E=0;E<144;++E)Pe[E]=8;for(var E=144;E<256;++E)Pe[E]=9;for(var E=256;E<280;++E)Pe[E]=7;for(var E=280;E<288;++E)Pe[E]=8;for(var as=new j(32),E=0;E<32;++E)as[E]=5;var vn=$e(Pe,9,1),_n=$e(as,5,1),gt=function(s){for(var e=s[0],t=1;t<s.length;++t)s[t]>e&&(e=s[t]);return e},F=function(s,e,t){var n=e/8|0;return(s[n]|s[n+1]<<8)>>(e&7)&t},yt=function(s,e){var t=e/8|0;return(s[t]|s[t+1]<<8|s[t+2]<<16)>>(e&7)},bn=function(s){return(s+7)/8|0},vt=function(s,e,t){return(e==null||e<0)&&(e=0),(t==null||t>s.length)&&(t=s.length),new j(s.subarray(e,t))},wn=["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"],V=function(s,e,t){var n=new Error(e||wn[s]);if(n.code=s,Error.captureStackTrace&&Error.captureStackTrace(n,V),!t)throw n;return n},kn=function(s,e,t,n){var r=s.length,i=n?n.length:0;if(!r||e.f&&!e.l)return t||new j(0);var a=!t,o=a||e.i!=2,c=e.i;a&&(t=new j(r*3));var l=function(Ts){var Cs=t.length;if(Ts>Cs){var Es=new j(Math.max(Cs*2,Ts));Es.set(t),t=Es}},d=e.f||0,h=e.p||0,y=e.b||0,$=e.l,R=e.d,C=e.m,A=e.n,k=r*8;do{if(!$){d=F(s,h,1);var L=F(s,h+1,3);if(h+=3,L)if(L==1)$=vn,R=_n,C=9,A=5;else if(L==2){var we=F(s,h,31)+257,tt=F(s,h+10,15)+4,st=we+F(s,h+5,31)+1;h+=14;for(var fe=new j(st),Me=new j(19),M=0;M<tt;++M)Me[pn[M]]=F(s,h+M*3,7);h+=tt*3;for(var ke=gt(Me),Ze=(1<<ke)-1,Z=$e(Me,ke,1),M=0;M<st;){var U=Z[F(s,h,Ze)];h+=U&15;var P=U>>4;if(P<16)fe[M++]=P;else{var X=0,xe=0;for(P==16?(xe=3+F(s,h,3),h+=2,X=fe[M-1]):P==17?(xe=3+F(s,h,7),h+=3):P==18&&(xe=11+F(s,h,127),h+=7);xe--;)fe[M++]=X}}var je=fe.subarray(0,we),ae=fe.subarray(we);C=gt(je),A=gt(ae),$=$e(je,C,1),R=$e(ae,A,1)}else V(1);else{var P=bn(h)+4,Le=s[P-4]|s[P-3]<<8,be=P+Le;if(be>r){c&&V(0);break}o&&l(y+Le),t.set(s.subarray(P,be),y),e.b=y+=Le,e.p=h=be*8,e.f=d;continue}if(h>k){c&&V(0);break}}o&&l(y+131072);for(var ur=(1<<C)-1,dr=(1<<A)-1,$t=h;;$t=h){var X=$[yt(s,h)&ur],Se=X>>4;if(h+=X&15,h>k){c&&V(0);break}if(X||V(2),Se<256)t[y++]=Se;else if(Se==256){$t=h,$=null;break}else{var xs=Se-254;if(Se>264){var M=Se-257,Ve=ts[M];xs=F(s,h,(1<<Ve)-1)+is[M],h+=Ve}var Pt=R[yt(s,h)&dr],Ot=Pt>>4;Pt||V(3),h+=Pt&15;var ae=yn[Ot];if(Ot>3){var Ve=ss[Ot];ae+=yt(s,h)&(1<<Ve)-1,h+=Ve}if(h>k){c&&V(0);break}o&&l(y+131072);var Ss=y+xs;if(y<ae){var As=i-ae,fr=Math.min(ae,Ss);for(As+y<0&&V(3);y<fr;++y)t[y]=n[As+y]}for(;y<Ss;++y)t[y]=t[y-ae]}}e.l=$,e.p=$t,e.b=y,e.f=d,$&&(d=1,e.m=C,e.d=R,e.n=A)}while(!d);return y!=t.length&&a?vt(t,0,y):t.subarray(0,y)},xn=new j(0),q=function(s,e){return s[e]|s[e+1]<<8},B=function(s,e){return(s[e]|s[e+1]<<8|s[e+2]<<16|s[e+3]<<24)>>>0},_t=function(s,e){return B(s,e)+B(s,e+4)*4294967296};function Sn(s,e){return kn(s,{i:2},e&&e.out,e&&e.dictionary)}var bt=typeof TextDecoder<"u"&&new TextDecoder,An=0;try{bt.decode(xn,{stream:!0}),An=1}catch{}var Tn=function(s){for(var e="",t=0;;){var n=s[t++],r=(n>127)+(n>223)+(n>239);if(t+r>s.length)return{s:e,r:vt(s,t-1)};r?r==3?(n=((n&15)<<18|(s[t++]&63)<<12|(s[t++]&63)<<6|s[t++]&63)-65536,e+=String.fromCharCode(55296|n>>10,56320|n&1023)):r&1?e+=String.fromCharCode((n&31)<<6|s[t++]&63):e+=String.fromCharCode((n&15)<<12|(s[t++]&63)<<6|s[t++]&63):e+=String.fromCharCode(n)}};function os(s,e){if(e){for(var t="",n=0;n<s.length;n+=16384)t+=String.fromCharCode.apply(null,s.subarray(n,n+16384));return t}else{if(bt)return bt.decode(s);var r=Tn(s),i=r.s,t=r.r;return t.length&&V(8),i}}var Cn=function(s,e){return e+30+q(s,e+26)+q(s,e+28)},En=function(s,e,t){var n=q(s,e+28),r=q(s,e+30),i=os(s.subarray(e+46,e+46+n),!(q(s,e+8)&2048)),a=e+46+n,o=Nn(s,a,r,t,B(s,e+20),B(s,e+24),B(s,e+42)),c=o[0],l=o[1],d=o[2];return[q(s,e+10),c,l,i,a+r+q(s,e+32),d]},Nn=function(s,e,t,n,r,i,a){var o=r==4294967295,c=i==4294967295,l=a==4294967295,d=e+t,h=o+c+l;if(n&&h){for(;e+4<d;e+=4+q(s,e+2))if(q(s,e)==1)return[o?_t(s,e+4+8*c):r,c?_t(s,e+4):i,l?_t(s,e+4+8*(c+o)):a,1];n<2&&V(13)}return[r,i,a,0]};function In(s,e){for(var t={},n=s.length-22;B(s,n)!=101010256;--n)(!n||s.length-n>65558)&&V(13);var r=q(s,n+8);if(!r)return{};var i=B(s,n+16),a=B(s,n-20)==117853008;if(a){var o=B(s,n-12);a=B(s,o)==101075792,a&&(r=B(s,o+32),i=B(s,o+48))}for(var c=0;c<r;++c){var l=En(s,i,a),d=l[0],h=l[1],y=l[2],$=l[3],R=l[4],C=l[5],A=Cn(s,C);i=R,d?d==8?t[$]=Sn(s.subarray(A,A+h),{out:new j(y)}):V(14,"unknown compression type "+d):t[$]=vt(s,A,A+h)}return t}const cs=[80,75];function wt(s){return s.length>=2&&s[0]===cs[0]&&s[1]===cs[1]}function kt(s){const e=s instanceof Uint8Array?s:new Uint8Array(s);if(!wt(e))throw new Error("Not a ZIP archive");const t=In(e),n=new Map;for(const[r,i]of Object.entries(t))!i||r.endsWith("/")||n.set(H(r),i);return n}function H(s){return s.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function Oe(s,e){const t=Qe(s,e);if(!t)throw new Error(`Missing zip entry: ${e}`);return os(t)}function Qe(s,e){const t=H(e);if(s.has(t))return s.get(t);const n=t.toLowerCase();for(const[r,i]of s)if(r.toLowerCase()===n)return i}function $n(s){return[...s.keys()]}function Pn(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 ls(s,e){const t=new Uint8Array(s.byteLength);t.set(s);const n=new Blob([t.buffer],{type:Pn(e)});return URL.createObjectURL(n)}async function On(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 xt(kt(s))}function xt(s){const e=Oe(s,"META-INF/container.xml"),t=J(e,/full-path\s*=\s*"([^"]+)"/i);if(!t)throw new Error("Invalid EPUB: missing rootfile in container.xml");const n=H(t),r=n.includes("/")?n.replace(/\/[^/]+$/,"/"):"",i=Oe(s,n),a=fs(i,"dc:title")||fs(i,"title")||"EPUB Story",o=jn(i)??{width:768,height:1024},c=Mn(i,r),l=Zn(i),d=[],h=new Map,y=A=>{const k=H(A);if(h.has(k))return h.get(k);const L=Qe(s,k);if(!L)throw new Error(`EPUB missing file: ${k}`);const P=ls(L,k);return d.push(P),h.set(k,P),P},$={},R=[];if(l.forEach((A,k)=>{const L=c.get(A);if(!L||!/html|xml/i.test(L.mediaType)&&!L.href.match(/\.x?html?$/i))return;const P=L.href,Le=Oe(s,P),be=P.includes("/")?P.replace(/\/[^/]+$/,"/"):"",we=`page-${k+1}`,tt=zn(Le),{html:st,imageHrefs:fe}=Bn(tt,be,Z=>{const U=H(Z.includes(":")?Z:`${be}${Z}`);try{return y(U)}catch{return Z}}),Me=[{id:`${we}-text`,type:"text",layout:{x:"5%",y:"5%",width:"90%",height:"90%"},html:st}],M=fe[0];let ke;if(M){const Z=`img-${k}-0`;$[Z]={type:"image",src:y(M)},ke={asset:Z,color:"#ffffff"}}else ke={color:"#ffffff"};let Ze;if(L.mediaOverlay){const Z=c.get(L.mediaOverlay);if(Z){const U=Vn(Oe(s,Z.href),Z.href);if(U.audioHref){const X=`vo-${k}`,xe=H(U.audioHref.includes("/")||U.audioHref.startsWith(".")?ds(Z.href,U.audioHref):`${r}${U.audioHref}`);$[X]={type:"audio",src:y(xe),channel:"vo"};const je=U.cues;je.length?Ze={audio:X,cues:je}:Ze={audio:X}}}}R.push({id:we,background:ke,readAloud:Ze,blocks:Me})}),R.length===0)throw new Error("Invalid EPUB: no spine HTML documents found");return{story:ye({id:`epub-${Fn(a)}`,title:a,pageSize:o,layout:{mode:"auto",singleBreakpoint:900},fonts:[],assets:$,pages:R}),blobUrls:d}}function Ln(s){return!!Qe(s,"META-INF/container.xml")}function Mn(s,e){const t=new Map,n=/<item\b[^>]*>/gi;let r;for(;r=n.exec(s);){const i=r[0],a=J(i,/\bid\s*=\s*"([^"]+)"/i),o=J(i,/\bhref\s*=\s*"([^"]+)"/i),c=J(i,/\bmedia-type\s*=\s*"([^"]+)"/i)??"",l=J(i,/\bmedia-overlay\s*=\s*"([^"]+)"/i)??void 0,d=J(i,/\bproperties\s*=\s*"([^"]+)"/i)??void 0;!a||!o||t.set(a,{id:a,href:H(`${e}${o}`),mediaType:c,mediaOverlay:l,properties:d})}return t}function Zn(s){const e=s.match(/<spine\b[^>]*>([\s\S]*?)<\/spine>/i);if(!e)return[];const t=[],n=/<itemref\b[^>]*\bidref\s*=\s*"([^"]+)"[^>]*>/gi;let r;for(;r=n.exec(e[1]);)t.push(r[1]);return t}function jn(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],n=t.match(/width\s*=\s*(\d+)/i),r=t.match(/height\s*=\s*(\d+)/i);return!n||!r?null:{width:Number(n[1]),height:Number(r[1])}}function Vn(s,e){const t=[];let n;const r=J(s,/<audio\b[^>]*\bsrc\s*=\s*"([^"]+)"/i);r&&(n=ds(e,r));const i=/<par\b[^>]*>([\s\S]*?)<\/par>/gi;let a,o=0;for(;a=i.exec(s);){const c=a[1],l=J(c,/<text\b[^>]*\bsrc\s*=\s*"([^"]+)"/i),d=J(c,/\bclipBegin\s*=\s*"([^"]+)"/i),h=J(c,/\bclipEnd\s*=\s*"([^"]+)"/i),y=l!=null&&l.includes("#")?l.split("#")[1]:`cue-${o}`;d==null||h==null||(t.push({id:y||`cue-${o}`,start:us(d),end:us(h)}),o+=1)}return{audioHref:n,cues:t}}function us(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 zn(s){const e=s.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i);return e?e[1].trim():s}function Bn(s,e,t){const n=[];return{html:s.replace(/\b(src|href)\s*=\s*["']([^"']+)["']/gi,(i,a,o)=>{if(/^(?:[a-z]+:|#|data:)/i.test(o))return i;const c=H(`${e}${o}`);/\.(png|jpe?g|gif|webp|svg)$/i.test(o)&&n.push(c);const l=t(o);return`${a}="${l}"`}),imageHrefs:n}}function ds(s,e){if(/^(?:[a-z]+:)/i.test(e))return e;const n=((s.includes("/")?s.replace(/\/[^/]+$/,"/"):"")+e).split("/"),r=[];for(const i of n)!i||i==="."||(i===".."?r.pop():r.push(i));return r.join("/")}function J(s,e){const t=s.match(e);return t?t[1]:null}function fs(s,e){const t=new RegExp(`<${e.replace(":",":")}[^>]*>([^<]*)</${e.replace(":",":")}>`,"i"),n=s.match(t);return n?n[1].trim():null}function Fn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"book"}function St(s){const e=$n(s),t=e.find(r=>r==="story.json"||r.toLowerCase()==="story.json");if(t)return t;const n=e.filter(r=>r.toLowerCase().endsWith("/story.json")||r.toLowerCase()==="story.json").sort((r,i)=>r.length-i.length);if(n[0])return n[0];throw new Error("Invalid .fanci package: missing story.json")}function At(s){const e=St(s),t=e.includes("/")?e.replace(/\/[^/]+$/,"/"):"",n=ye(JSON.parse(Oe(s,e))),r=new Map,i=[];for(const[a,o]of s){if(a===e)continue;const c=ls(o,a);i.push(c),r.set(a,c),t&&a.startsWith(t)&&r.set(a.slice(t.length),c)}return Wn(n,a=>Dn(r,t,a)),{story:n,pathUrls:r,blobUrls:i,storyDir:t}}function Un(s){return At(kt(s))}function Dn(s,e,t){const n=H(t);if(s.has(n))return s.get(n);const r=H(`${e}${n}`);if(s.has(r))return s.get(r);const i=n.toLowerCase();for(const[a,o]of s)if(a.toLowerCase()===i||a.toLowerCase().endsWith(`/${i}`))return o}function Wn(s,e){for(const t of s.fonts){const n=e(t.src);n&&(t.src=n)}for(const t of Object.values(s.assets)){const n=e(t.src);n&&(t.src=n)}for(const t of s.pages)for(const n of t.blocks)if(n.type==="text"&&n.htmlSrc){const r=e(n.htmlSrc);r&&(n.htmlSrc=r)}}function qn(s){if(Qe(s,"META-INF/container.xml"))return!1;try{return St(s),!0}catch{return!1}}const Ke=".fanci";function Tt(s){const e=s.split("?")[0].split("#")[0],t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function Hn(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:""),n=Tt(t);return n===Ke||n===".fanci.zip"?"fanci":n===".epub"?"epub":"json"}async function Jn(s){return s instanceof ArrayBuffer?s:s instanceof Uint8Array?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s.arrayBuffer()}async function Ct(s,e){const t=typeof e=="string"?{baseUrl:e}:e??{},n=t.onProgress??(()=>{});if(Yn(s)){n({stage:"parse",progress:.1,detail:"story object"});const r=ye(s),i=t.baseUrl??(typeof location<"u"?location.href:"");n({stage:"assets",progress:.2,detail:"fonts"}),await Ie(r,i);const a=await Re(r,i,n,.25,1);return n({stage:"complete",progress:1}),{story:r,baseUrl:i,assets:a,blobUrls:[],kind:"object"}}if(typeof s=="object"&&s!==null&&"story"in s&&!hs(s)){const r=s;return Ct(r.story,{baseUrl:t.baseUrl??r.baseUrl,name:t.name,onProgress:t.onProgress})}if(typeof s=="string")return Xn(s,t,n);if(hs(s)){n({stage:"fetch",progress:.05,detail:"bytes"});const r=await Jn(s),i=t.name??(s instanceof File?s.name:void 0)??"";return Et(r,i,t.baseUrl,n)}throw new Error("Unsupported story source")}async function Xn(s,e,t){const n=Tt(s),r=Hn(s,e.name??s);if(t({stage:"fetch",progress:.02,detail:s}),n===Ke||n===".epub"||r==="fanci"||r==="epub"){const y=await On(s);return t({stage:"fetch",progress:.15,detail:"package downloaded"}),Et(y,e.name??s,e.baseUrl,t)}const i=await fetch(s);if(!i.ok)throw new Error(`Failed to load story: ${i.status} ${i.statusText}`);const a=await i.arrayBuffer(),o=new Uint8Array(a);if(wt(o))return t({stage:"fetch",progress:.15,detail:"zip downloaded"}),Et(a,e.name??s,e.baseUrl,t);t({stage:"parse",progress:.2,detail:"json"});const c=new TextDecoder().decode(o),l=ye(JSON.parse(c)),d=e.baseUrl??fn(new URL(s,location.href).href);await Ie(l,d);const h=await Re(l,d,t,.3,1);return t({stage:"complete",progress:1}),{story:l,baseUrl:d,assets:h,blobUrls:[],kind:"json"}}async function Et(s,e,t,n){const r=new Uint8Array(s),i=Tt(e);if(wt(r)){n({stage:"unpack",progress:.2,detail:"unzip"});const l=kt(r);if(n({stage:"unpack",progress:.35,detail:`${l.size} entries`}),i===".epub"||Ln(l)){n({stage:"parse",progress:.4,detail:"epub"});const{story:d,blobUrls:h}=xt(l);await Ie(d,t??"");const y=await Re(d,t??"",n,.5,1);return n({stage:"complete",progress:1}),{story:d,baseUrl:t??"",assets:y,blobUrls:h,kind:"epub"}}if(i===Ke||qn(l)){n({stage:"parse",progress:.4,detail:"fanci"});const{story:d,blobUrls:h}=At(l);await Ie(d,t??"");const y=await Re(d,t??"",n,.5,1);return n({stage:"complete",progress:1}),{story:d,baseUrl:t??"",assets:y,blobUrls:h,kind:"fanci"}}throw new Error("ZIP archive is neither a .fanci package (story.json) nor an EPUB (META-INF/container.xml)")}n({stage:"parse",progress:.25,detail:"json bytes"});const a=ye(JSON.parse(new TextDecoder().decode(r))),o=t??(typeof location<"u"?location.href:"");await Ie(a,o);const c=await Re(a,o,n,.35,1);return n({stage:"complete",progress:1}),{story:a,baseUrl:o,assets:c,blobUrls:[],kind:"json"}}function Yn(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 hs(s){return s instanceof ArrayBuffer||s instanceof Uint8Array||s instanceof Blob||typeof File<"u"&&s instanceof File}async function Re(s,e,t,n,r){var R;const i=new Map,a=new Map,o=new Map,c=new Map,l=Object.entries(s.assets),d=[];for(const C of s.pages)for(const A of C.blocks)if(A.type==="text"&&A.htmlSrc&&!A.html&&d.push(async()=>{const k=Ge(e,A.htmlSrc);c.set(`htmlSrc:${A.id}`,await et(k))}),(R=C.readAloud)!=null&&R.cues&&typeof C.readAloud.cues=="string"){const k=C.readAloud.cues;s.assets[k]||d.push(async()=>{const L=Ge(e,k);try{o.set(k,ht(await et(L)))}catch{}})}const h=l.length+d.length||1;let y=0;const $=C=>{y+=1;const A=y/h,k=n+(r-n)*Math.min(1,A);t({stage:"assets",progress:k,count:y,total:h,detail:C})};return await Promise.all(l.map(async([C,A])=>{const k=Ge(e,A.src);A.type==="image"?i.set(C,await Gn(k)):A.type==="audio"?a.set(C,{url:k,channel:A.channel??"vo"}):A.type==="vtt"?o.set(C,ht(await et(k))):A.type==="html"&&c.set(C,await et(k)),$(C)})),await Promise.all(d.map(async C=>{await C(),$("fragment")})),l.length===0&&d.length===0&&t({stage:"assets",progress:r,count:0,total:0,detail:"none"}),{images:i,audioUrls:a,cues:o,html:c}}function Gn(s){return new Promise((e,t)=>{const n=new Image;n.decoding="async",n.onload=()=>e(n),n.onerror=()=>t(new Error(`Failed to load image: ${s}`)),n.src=s})}async function et(s){const e=await fetch(s);if(!e.ok)throw new Error(`Failed to load ${s}: ${e.status}`);return e.text()}function ps(s){for(const e of s.blobUrls)try{URL.revokeObjectURL(e)}catch{}s.blobUrls.length=0}function ms(s,e,t){return s==="auto"?e>=t?"two-page":"single":s}function gs(s){if(s.length===0)return[];const e=[];e.push({index:0,left:{kind:"blank"},right:{kind:"page",pageIndex:0,pageId:s[0].id}});let t=1;for(;t<s.length;){const n={kind:"page",pageIndex:t,pageId:s[t].id},r=t+1<s.length?{kind:"page",pageIndex:t+1,pageId:s[t+1].id}:{kind:"blank"};e.push({index:e.length,left:n,right:r}),t+=2}return e}function ys(s){const e=[];return s.left.kind==="page"&&e.push(s.left.pageId),s.right.kind==="page"&&e.push(s.right.pageId),e}function Qn(s,e){const t=s.findIndex(n=>n.left.kind==="page"&&n.left.pageId===e||n.right.kind==="page"&&n.right.pageId===e);return t<0?0:t}class Kn{constructor(e,t){g(this,"story");g(this,"spreadView");g(this,"spreads");g(this,"spreadIndex",0);g(this,"preferredMode");g(this,"resolvedMode","single");g(this,"breakpoint");g(this,"listeners",new Map);g(this,"busy",!1);this.story=e,this.spreadView=t,this.spreads=gs(e.pages),this.preferredMode=e.layout.mode,this.breakpoint=e.layout.singleBreakpoint}get layoutMode(){return this.resolvedMode}get currentSpread(){return this.spreads[this.spreadIndex]}get currentPageIds(){return ys(this.currentSpread)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var n;return(n=this.listeners.get(e))==null?void 0:n.delete(t)}}setLayoutMode(e,t){this.preferredMode=e,this.updateLayout(t,!1)}updateLayout(e,t=!0){const n=ms(this.preferredMode,e,this.breakpoint),r=n!==this.resolvedMode;this.resolvedMode=n,this.spreadView.setLayoutMode(n),r&&t&&this.emit("layoutchange",{layoutMode:n})}async showInitial(){await this.spreadView.showSpread(this.currentSpread,"none"),this.emitPageChange()}async next(){this.busy||this.spreadIndex>=this.spreads.length-1||(this.busy=!0,this.spreadIndex+=1,await this.spreadView.showSpread(this.currentSpread,"next"),this.emitPageChange(),this.busy=!1)}async prev(){this.busy||this.spreadIndex<=0||(this.busy=!0,this.spreadIndex-=1,await this.spreadView.showSpread(this.currentSpread,"prev"),this.emitPageChange(),this.busy=!1)}async goTo(e){const t=Qn(this.spreads,e);if(t===this.spreadIndex)return;const n=t>this.spreadIndex?"next":"prev";this.busy=!0,this.spreadIndex=t,await this.spreadView.showSpread(this.currentSpread,n),this.emitPageChange(),this.busy=!1}emitPageChange(){this.emit("pagechange",{pageIds:this.currentPageIds,index:this.spreadIndex,layoutMode:this.resolvedMode})}emit(e,t){const n=this.listeners.get(e);if(n)for(const r of n)r(t)}}function er(s){const e=s??{},t={left:_e(e.x??0),top:_e(e.y??0)};return e.width!=null&&(t.width=_e(e.width)),e.height!=null&&(t.height=_e(e.height)),t}function Nt(s,e){const t=er(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=_e(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=_e(e.y??0)):(e==null?void 0:e.verticalAlign)==="center"&&(s.style.top="50%",s.style.transform=`${s.style.transform||""} translateY(-50%)`.trim())}function _e(s){return typeof s=="number"?`${s}px`:/^-?\d+(\.\d+)?$/.test(s)?`${s}px`:s}function tr(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),Nt(t,s.layout),t.addEventListener("click",n=>{n.stopPropagation(),e(s.onTap??[])}),t}function sr(s,e){var i;const t=document.createElement("div");t.className=`fc-block fc-block-image${s.className?` ${s.className}`:""}`,t.dataset.blockId=s.id,Nt(t,s.layout);const n=document.createElement("img");n.alt="",n.draggable=!1,e&&(n.src=e.src);const r=((i=s.layout)==null?void 0:i.fit)??"contain";return n.style.objectFit=r,t.appendChild(n),t}function nr(s,e){const t=document.createElement("div");return t.className="fc-block fc-block-text",t.dataset.blockId=s.id,Nt(t,s.layout),t.innerHTML=e,t.querySelectorAll("[id]").forEach(n=>{n.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 vs{constructor(e,t,n){g(this,"element");g(this,"page");g(this,"blank");var r,i;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),(i=e.background)!=null&&i.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(nr(a,o))}else a.type==="image"?this.element.appendChild(sr(a,t.images.get(a.asset))):a.type==="hotspot"&&this.element.appendChild(tr(a,o=>n.onTapActions(o,this.element)))}destroy(){this.element.remove()}}class rr{constructor(e,t,n){g(this,"element");g(this,"bookEl");g(this,"leftSlot");g(this,"rightSlot");g(this,"leftPage",null);g(this,"rightPage",null);g(this,"story");g(this,"assets");g(this,"onTapActions");g(this,"turning",!1);this.story=e,this.assets=t,this.onTapActions=n,this.element=document.createElement("div"),this.element.className="fc-spread-viewport",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.appendChild(this.bookEl)}setLayoutMode(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")}showSpread(e,t="none"){return t==="none"||this.turning?(this.mountSpread(e),Promise.resolve()):(this.turning=!0,this.bookEl.classList.remove("fc-turn-next","fc-turn-prev"),this.bookEl.offsetWidth,this.bookEl.classList.add(t==="next"?"fc-turn-next":"fc-turn-prev"),new Promise(n=>{const r=()=>{this.bookEl.removeEventListener("animationend",r),this.bookEl.classList.remove("fc-turn-next","fc-turn-prev"),this.mountSpread(e),this.turning=!1,n()};this.bookEl.addEventListener("animationend",r),window.setTimeout(r,450)}))}getPageElement(e){var t,n,r,i;return((n=(t=this.leftPage)==null?void 0:t.page)==null?void 0:n.id)===e?this.leftPage.element:((i=(r=this.rightPage)==null?void 0:r.page)==null?void 0:i.id)===e?this.rightPage.element:null}getVisiblePageElements(e,t){const n=[];return e==="two-page"?(t.left.kind==="page"&&this.leftPage&&n.push(this.leftPage.element),t.right.kind==="page"&&this.rightPage&&n.push(this.rightPage.element)):t.left.kind==="blank"&&t.right.kind==="page"&&this.rightPage?n.push(this.rightPage.element):t.right.kind==="blank"&&t.left.kind==="page"&&this.leftPage?n.push(this.leftPage.element):t.left.kind==="page"&&this.leftPage?n.push(this.leftPage.element):t.right.kind==="page"&&this.rightPage&&n.push(this.rightPage.element),n}updateStageSize(e,t,n,r){const{width:i,height:a}=this.story.pageSize,o=i*2,c=a;let l;n==="single"?l=Math.min(e/i,t/a):l=Math.min(e/o,t/c),this.bookEl.style.width=`${o}px`,this.bookEl.style.height=`${c}px`,this.bookEl.style.setProperty("--fc-page-width",`${i}px`),this.bookEl.style.setProperty("--fc-page-height",`${a}px`);let d=0;n==="single"&&r&&r.left.kind==="blank"&&(d=-i*l),this.bookEl.style.transform=`translateX(${d}px) scale(${l})`,this.bookEl.style.transformOrigin="left top",this.element.style.width=n==="single"?`${i*l}px`:`${o*l}px`,this.element.style.height=`${c*l}px`}destroy(){var e,t;(e=this.leftPage)==null||e.destroy(),(t=this.rightPage)==null||t.destroy(),this.element.remove()}mountSpread(e){var t,n;(t=this.leftPage)==null||t.destroy(),(n=this.rightPage)==null||n.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)}createLeaf(e){if(e.kind==="blank")return new vs(null,this.assets,{onTapActions:this.onTapActions});const t=this.story.pages[e.pageIndex];return new vs(t,this.assets,{onTapActions:this.onTapActions})}}function _s(s,e){const t=s==null?void 0:s.container;if(!(t!=null&&t.send))return;const n=or(e.progress);t.send("progress",n),t.send("loading",{stage:e.stage,progress:n,count:e.count,total:e.total,detail:e.detail})}function ir(s){var e,t;(t=(e=s==null?void 0:s.container)==null?void 0:e.send)==null||t.call(e,"loaded")}function ar(){let s;return{promise:new Promise(t=>{s=t}),resolve:s}}function or(s){return Number.isNaN(s)?0:Math.min(1,Math.max(0,s))}function bs(s,e,t={}){const n=[];let r=!1;const i=(a,o)=>{if(!(a!=null&&a.subscribe))return;const c=a.subscribe(o);typeof c=="function"?n.push(c):c&&typeof c.unsubscribe=="function"&&n.push(()=>{var l;return(l=c.unsubscribe)==null?void 0:l.call(c)})};return s!=null&&s.state&&(i(s.state.pause,a=>{var c;const o=!!a;e.setPaused(o),(c=t.onPause)==null||c.call(t,o)}),i(s.state.soundVolume,a=>e.setVolume("sound",Number(a))),i(s.state.voVolume,a=>e.setVolume("vo",Number(a))),i(s.state.sfxVolume,a=>e.setVolume("sfx",Number(a))),i(s.state.musicVolume,a=>e.setVolume("music",Number(a))),i(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 n)a()}}}async function ws(s){var e,t;try{const n=await import("springroll"),r=n.Application??((e=n.default)==null?void 0:e.Application),i=n.ApplicationPlugin??((t=n.default)==null?void 0:t.ApplicationPlugin);if(!r)return null;const a=ar(),o=`fancifully-story-load-${Math.random().toString(36).slice(2,9)}`;if(i&&typeof r.uses=="function"){const l=new i({name:o});l.preload=()=>a.promise,r.uses(l)}else a.resolve();return{app:new r({features:s}),loadGate:a,owned:!0}}catch{return null}}function ks(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 n=s.state.ready.subscribe(r=>{r&&(typeof n=="function"&&n(),t())})})}const cr={sound:!0,soundVolume:!0,vo:!0,voVolume:!0,sfx:!0,sfxVolume:!0,music:!0,musicVolume:!0,captions:!0};class It{constructor(e,t,n,r){g(this,"element");g(this,"root");g(this,"stage");g(this,"chrome");g(this,"captionsEl");g(this,"loaded");g(this,"spreadView");g(this,"pager");g(this,"bus",new Y);g(this,"readAloud");g(this,"springroll");g(this,"bindings",null);g(this,"sfxAudio");g(this,"unbindSwipe",null);g(this,"resizeObserver",null);g(this,"listeners",new Map);g(this,"destroyed",!1);this.root=e,this.loaded=t,this.springroll=n,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"),this.chrome=document.createElement("div"),this.chrome.className="fc-chrome",this.chrome.innerHTML=`
5
- <button type="button" class="fc-btn fc-btn-prev" aria-label="Previous page">Prev</button>
6
- <button type="button" class="fc-btn fc-btn-read" aria-label="Read aloud">Read</button>
7
- <button type="button" class="fc-btn fc-btn-next" aria-label="Next page">Next</button>
8
- `,this.spreadView=new rr(t.story,t.assets,(i,a)=>this.handleTapActions(i,a)),this.pager=new Kn(t.story,this.spreadView),this.readAloud=new Ns(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=Is(this.stage,{onSwipeLeft:()=>void this.next(),onSwipeRight:()=>void this.prev()}),this.element.addEventListener("keydown",i=>{i.key==="ArrowRight"?(i.preventDefault(),this.next()):i.key==="ArrowLeft"?(i.preventDefault(),this.prev()):i.key===" "&&(i.preventDefault(),this.playReadAloud())}),this.readAloud.onCaption(i=>{this.captionsEl.textContent=i??"",this.captionsEl.hidden=!i})}static async create(e,t){const n={...cr,...t.features};let r=t.springroll??null,i=null;if(!r){const d=await ws(n);d&&(r=d.app,i=d.loadGate,lr(r))}const a=[];t.onProgress&&a.push(t.onProgress);const o=d=>{_s(r,d);for(const h of a)h(d)};o({stage:"fetch",progress:0,detail:"start"});const c=await Ct(t.story,{baseUrl:t.baseUrl,name:t.storyName,onProgress:o});i==null||i.resolve(),await ks(r);const l=new It(e,c,r,t.autoPlayReadAloud??!1);return l.pager.updateLayout(e.clientWidth||window.innerWidth,!1),l.layoutStage(),await l.pager.showInitial(),l.emit("ready",{story:c.story}),l}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}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{var n;return(n=this.listeners.get(e))==null?void 0:n.delete(t)}}next(){return this.readAloud.stop(),this.pager.next().then(()=>this.layoutStage())}prev(){return this.readAloud.stop(),this.pager.prev().then(()=>this.layoutStage())}goTo(e){return this.readAloud.stop(),this.pager.goTo(e).then(()=>this.layoutStage())}setLayoutMode(e){this.pager.setLayoutMode(e,this.root.clientWidth||window.innerWidth),this.layoutStage(),this.emit("layoutchange",{layoutMode:this.pager.layoutMode})}playReadAloud(){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()}destroy(){var e,t,n;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),(n=this.resizeObserver)==null||n.disconnect(),this.spreadView.destroy(),this.element.remove(),this.listeners.clear(),ps(this.loaded))}wireChrome(){var e,t,n;(e=this.chrome.querySelector(".fc-btn-prev"))==null||e.addEventListener("click",()=>void this.prev()),(t=this.chrome.querySelector(".fc-btn-next"))==null||t.addEventListener("click",()=>void this.next()),(n=this.chrome.querySelector(".fc-btn-read"))==null||n.addEventListener("click",()=>void this.playReadAloud())}wirePager(e){this.pager.on("pagechange",t=>{this.emit("pagechange",t),e&&this.playReadAloud()}),this.pager.on("layoutchange",t=>{this.layoutStage(),this.emit("layoutchange",t)})}wireSpringroll(){this.bindings=bs(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.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,n=e==="two-page"?[t.left,t.right]:t.left.kind==="blank"?[t.right]:t.right.kind==="blank"?[t.left]:[t.left],r=[];for(const i of n){if(i.kind!=="page")continue;const a=this.loaded.story.pages[i.pageIndex];if(!a.readAloud)continue;const o=this.loaded.assets.audioUrls.get(a.readAloud.audio);if(!o)continue;const c=this.resolveCues(a.readAloud.cues),l=this.spreadView.getPageElement(a.id);r.push({url:o.url,channel:o.channel,cues:c,root:l})}return r}resolveCues(e){return e?Array.isArray(e)?e:this.loaded.assets.cues.get(e)??[]:[]}handleTapActions(e,t){for(const n of e)if("play"in n){const r=this.loaded.assets.audioUrls.get(n.play);if(!r)continue;this.sfxAudio.src=r.url,this.bus.applyTo(this.sfxAudio,r.channel),this.sfxAudio.play().catch(()=>{})}else if("toggleClass"in n){const r=t.querySelector(`[data-block-id="${n.toggleClass.target}"]`);r==null||r.classList.toggle(n.toggleClass.className)}}emit(e,t){const n=this.listeners.get(e);if(n)for(const r of n)r(t)}}function lr(s){var t,n,r,i,a,o;const e=s.state;e&&((t=e.pause)==null||t.subscribe(()=>{}),(n=e.soundVolume)==null||n.subscribe(()=>{}),(r=e.voVolume)==null||r.subscribe(()=>{}),(i=e.sfxVolume)==null||i.subscribe(()=>{}),(a=e.musicVolume)==null||a.subscribe(()=>{}),(o=e.captionsMuted)==null||o.subscribe(()=>{}))}return T.CueTimeline=Rt,T.FANCI_EXTENSION=Ke,T.Storybook=It,T.bindApplication=bs,T.buildSpreads=gs,T.contentPageIds=ys,T.createSpringrollApplication=ws,T.findStoryJsonPath=St,T.loadEpubFromBytes=Rn,T.loadEpubFromZip=xt,T.loadFanciFromBytes=Un,T.loadFanciFromZip=At,T.loadStory=Ct,T.parseStory=ye,T.parseVtt=ht,T.reportSpringrollLoaded=ir,T.reportSpringrollProgress=_s,T.resolveLayoutMode=ms,T.revokeLoadedStory=ps,T.storySchema=Kt,T.waitForSpringrollReady=ks,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"}),T})({});
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"}),_})({});