@shotstack/shotstack-studio 1.3.0 → 1.4.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.
- package/dist/shotstack-studio.es.js +4912 -4754
- package/dist/shotstack-studio.umd.js +7 -7
- package/dist/src/components/canvas/index.d.ts +14 -0
- package/dist/{core/entities → src/components/canvas}/players/audio-player.d.ts +4 -4
- package/dist/{core/entities → src/components/canvas}/players/html-player.d.ts +4 -4
- package/dist/{core/entities → src/components/canvas}/players/image-player.d.ts +4 -4
- package/dist/{core/entities → src/components/canvas}/players/luma-player.d.ts +4 -4
- package/dist/{core/entities/base → src/components/canvas/players}/player.d.ts +5 -4
- package/dist/{core/entities → src/components/canvas}/players/shape-player.d.ts +4 -4
- package/dist/{core/entities → src/components/canvas}/players/text-player.d.ts +1 -1
- package/dist/{core/entities → src/components/canvas}/players/video-player.d.ts +4 -4
- package/dist/{core → src/components/canvas}/shotstack-canvas.d.ts +2 -2
- package/dist/{core/entities → src/components/canvas}/system/inspector.d.ts +1 -1
- package/dist/{core/entities → src/components/canvas}/text/text-editor.d.ts +1 -1
- package/dist/src/core/commands/add-clip-command.d.ts +14 -0
- package/dist/src/core/commands/add-track-command.d.ts +8 -0
- package/dist/src/core/commands/delete-clip-command.d.ts +10 -0
- package/dist/src/core/commands/delete-track-command.d.ts +9 -0
- package/dist/src/core/commands/set-updated-clip-command.d.ts +17 -0
- package/dist/src/core/commands/types.d.ts +25 -0
- package/dist/src/core/commands/update-text-content-command.d.ts +16 -0
- package/dist/{core/entities/system → src/core}/edit.d.ts +13 -7
- package/dist/{core → src/core}/export/video-exporter.d.ts +2 -2
- package/dist/{core → src/core}/inputs/controls.d.ts +1 -1
- package/dist/{core → src/core}/schemas/asset.d.ts +42 -38
- package/dist/{core → src/core}/schemas/audio-asset.d.ts +18 -14
- package/dist/{core → src/core}/schemas/clip.d.ts +113 -99
- package/dist/{core → src/core}/schemas/edit.d.ts +372 -344
- package/dist/{core → src/core}/schemas/track.d.ts +141 -127
- package/dist/{core → src/core}/schemas/video-asset.d.ts +18 -14
- package/dist/src/index.d.ts +4 -0
- package/dist/vite.config.d.ts +2 -0
- package/package.json +1 -1
- package/readme.md +10 -0
- package/dist/core/entities/index.d.ts +0 -14
- package/dist/index.d.ts +0 -4
- package/dist/{core/entities → src/components/canvas}/text/text-cursor.d.ts +0 -0
- package/dist/{core/entities → src/components/canvas}/text/text-input-handler.d.ts +0 -0
- package/dist/{core → src/core}/animations/curve-interpolator.d.ts +0 -0
- package/dist/{core → src/core}/animations/effect-preset-builder.d.ts +0 -0
- package/dist/{core → src/core}/animations/keyframe-builder.d.ts +0 -0
- package/dist/{core → src/core}/animations/transition-preset-builder.d.ts +0 -0
- package/dist/{core → src/core}/events/asset-load-tracker.d.ts +0 -0
- package/dist/{core → src/core}/events/event-emitter.d.ts +0 -0
- package/dist/{core → src/core}/inputs/pointer.d.ts +0 -0
- package/dist/{core → src/core}/layouts/geometry.d.ts +0 -0
- package/dist/{core → src/core}/layouts/position-builder.d.ts +0 -0
- package/dist/{core → src/core}/loaders/asset-loader.d.ts +0 -0
- package/dist/{core → src/core}/loaders/audio-load-parser.d.ts +0 -0
- package/dist/{core → src/core}/loaders/font-load-parser.d.ts +0 -0
- package/dist/{core → src/core}/schemas/html-asset.d.ts +2 -2
- package/dist/{core → src/core}/schemas/image-asset.d.ts +2 -2
- package/dist/{core → src/core}/schemas/keyframe.d.ts +2 -2
- package/dist/{core → src/core}/schemas/luma-asset.d.ts +2 -2
- /package/dist/{core → src/core}/schemas/shape-asset.d.ts +0 -0
- /package/dist/{core → src/core}/schemas/text-asset.d.ts +0 -0
- /package/dist/{core/entities/base → src/core/shared}/entity.d.ts +0 -0
- /package/dist/{main.d.ts → src/main.d.ts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(F,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("pixi.js"),require("opentype.js"),require("howler"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","opentype.js","howler","@ffmpeg/ffmpeg"],V):(F=typeof globalThis<"u"?globalThis:F||self,V(F.ShotstackStudio={},F.PIXI,F.opentype,F.Howler,F.ffmpeg))})(this,function(F,V,je,$e,Ue){"use strict";function Yt(a){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const e in a)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>a[e]})}}return t.default=a,Object.freeze(t)}const y=Yt(V),ge=Yt(je),We=Yt($e);class me{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,e){if(this.events[t])for(const i of this.events[t])i(e)}}class Xe extends me{registry;constructor(){super(),this.registry={}}}class At{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new Xe;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await y.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return At.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),s=At.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),s=typeof e=="object"?e.data??{}:{},n=await new Promise((r,o)=>{const h=document.createElement("video");h.crossOrigin="anonymous",h.playsInline=!0,h.muted=!0,h.preload="metadata",h.addEventListener("loadedmetadata",()=>{try{const l=new y.VideoSource({resource:h,autoPlay:s.autoPlay??!1,...s});r(new y.Texture({source:l}))}catch(l){o(l)}},{once:!0}),h.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),h.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class Pt{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=Pt.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(p=>p.arrayBuffer());if(s!=="woff2"){const p=ge.parse(new Uint8Array(n).buffer),k=p.names.fontFamily.en||p.names.fontFamily[Object.keys(p.names.fontFamily)[0]],O=new FontFace(k,`url(${t})`);return await O.load(),document.fonts.add(O),O}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=ge.parse(new Uint8Array(r).buffer),h=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],l=new Blob([r],{type:"font/ttf"}),c=URL.createObjectURL(l),m=new FontFace(h,`url(${c})`);return await m.load(),document.fonts.add(m),m}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}var S;(function(a){a.assertEqual=s=>s;function t(s){}a.assertIs=t;function e(s){throw new Error}a.assertNever=e,a.arrayToEnum=s=>{const n={};for(const r of s)n[r]=r;return n},a.getValidEnumValues=s=>{const n=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),r={};for(const o of n)r[o]=s[o];return a.objectValues(r)},a.objectValues=s=>a.objectKeys(s).map(function(n){return s[n]}),a.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&n.push(r);return n},a.find=(s,n)=>{for(const r of s)if(n(r))return r},a.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(r=>typeof r=="string"?`'${r}'`:r).join(n)}a.joinValues=i,a.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var ye;(function(a){a.mergeShapes=(t,e)=>({...t,...e})})(ye||(ye={}));const f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}},u=S.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 N extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const r of n.issues)if(r.code==="invalid_union")r.unionErrors.map(s);else if(r.code==="invalid_return_type")s(r.returnTypeError);else if(r.code==="invalid_arguments")s(r.argumentsError);else if(r.path.length===0)i._errors.push(e(r));else{let o=i,h=0;for(;h<r.path.length;){const l=r.path[h];h===r.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(e(r))):o[l]=o[l]||{_errors:[]},o=o[l],h++}}};return s(this),i}static assert(t){if(!(t instanceof N))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}N.create=a=>new N(a);const wt=(a,t)=>{let e;switch(a.code){case u.invalid_type:a.received===f.undefined?e="Required":e=`Expected ${a.expected}, received ${a.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(a.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(a.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(a.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(a.options)}, received '${a.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(e=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?e=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?e=`Invalid input: must end with "${a.validation.endsWith}"`:S.assertNever(a.validation):a.validation!=="regex"?e=`Invalid ${a.validation}`:e="Invalid";break;case u.too_small:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:e="Invalid input";break;case u.too_big:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?e=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${a.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(a)}return{message:e}};let Ye=wt;function Gt(){return Ye}const qt=a=>{const{data:t,path:e,errorMaps:i,issueData:s}=a,n=[...e,...s.path||[]],r={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const h=i.filter(l=>!!l).slice().reverse();for(const l of h)o=l(r,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function d(a,t){const e=Gt(),i=qt({issueData:t,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,e,e===wt?void 0:wt].filter(s=>!!s)});a.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return w;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,r=await s.value;i.push({key:n,value:r})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:r}=s;if(n.status==="aborted"||r.status==="aborted")return w;n.status==="dirty"&&t.dirty(),r.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof r.value<"u"||s.alwaysSet)&&(i[n.value]=r.value)}return{status:t.value,value:i}}}const w=Object.freeze({status:"aborted"}),Ct=a=>({status:"dirty",value:a}),z=a=>({status:"valid",value:a}),ve=a=>a.status==="aborted",xe=a=>a.status==="dirty",ut=a=>a.status==="valid",Et=a=>typeof Promise<"u"&&a instanceof Promise;function Lt(a,t,e,i){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(a)}function we(a,t,e,i,s){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(a,e),e}typeof SuppressedError=="function"&&SuppressedError;var g;(function(a){a.errToObj=t=>typeof t=="string"?{message:t}:t||{},a.toString=t=>typeof t=="string"?t:t?.message})(g||(g={}));var kt,bt;class Z{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ce=(a,t)=>{if(ut(t))return{success:!0,data:t.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new N(a.common.issues);return this._error=e,this._error}}};function C(a){if(!a)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=a;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(r,o)=>{var h,l;const{message:c}=a;return r.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:(h=c??i)!==null&&h!==void 0?h:o.defaultError}:r.code!=="invalid_type"?{message:o.defaultError}:{message:(l=c??e)!==null&&l!==void 0?l:o.defaultError}},description:s}}class b{get description(){return this._def.description}_getType(t){return J(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Et(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},n=this._parseSync({data:t,path:s.path,parent:s});return Ce(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ut(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ut(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Et(s)?s:Promise.resolve(s));return Ce(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const r=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&r instanceof Promise?r.then(h=>h?!0:(o(),!1)):r?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new X({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:e=>this["~validate"](e)}}optional(){return Y.create(this,this._def)}nullable(){return nt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this)}promise(){return Tt.create(this,this._def)}or(t){return Dt.create([this,t],this._def)}and(t){return Mt.create(this,t,this._def)}transform(t){return new X({...C(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new Vt({...C(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new Se({typeName:x.ZodBranded,type:this,...C(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Zt({...C(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Kt.create(this,t)}readonly(){return jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ge=/^c[^\s-]{8,}$/i,qe=/^[0-9a-z]+$/,Qe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Je=/^[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,ti=/^[a-z0-9_-]{21}$/i,ei=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ii=/^[-+]?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)?)??$/,si=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ni="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Qt;const ai=/^(?:(?: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])$/,ri=/^(?:(?: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])$/,oi=/^(([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]))$/,li=/^(([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])$/,ci=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ke="((\\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])))",ui=new RegExp(`^${ke}$`);function be(a){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?t=`${t}\\.\\d{${a.precision}}`:a.precision==null&&(t=`${t}(\\.\\d+)?`),t}function di(a){return new RegExp(`^${be(a)}$`)}function fi(a){let t=`${ke}T${be(a)}`;const e=[];return e.push(a.local?"Z?":"Z"),a.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function pi(a,t){return!!((t==="v4"||!t)&&ai.test(a)||(t==="v6"||!t)&&oi.test(a))}function gi(a,t){if(!ei.test(a))return!1;try{const[e]=a.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function mi(a,t){return!!((t==="v4"||!t)&&ri.test(a)||(t==="v6"||!t)&&li.test(a))}class $ extends b{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==f.string){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.string,received:n.parsedType}),w}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const r=t.data.length>n.value,o=t.data.length<n.value;(r||o)&&(s=this._getOrReturnCtx(t,s),r?d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")si.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")Qt||(Qt=new RegExp(ni,"u")),Qt.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")Je.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")ti.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Ge.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")qe.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Qe.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),d(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?fi(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?ui.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?di(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?ii.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?pi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?gi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?mi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?ci.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?hi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...g.errToObj(i)})}_addCheck(t){return new $({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...g.errToObj(t)})}url(t){return this._addCheck({kind:"url",...g.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...g.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...g.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...g.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...g.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...g.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...g.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...g.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...g.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...g.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...g.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...g.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...g.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...g.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...g.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...g.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...g.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...g.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...g.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...g.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...g.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...g.errToObj(e)})}nonempty(t){return this.min(1,g.errToObj(t))}trim(){return new $({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}$.create=a=>{var t;return new $({checks:[],typeName:x.ZodString,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...C(a)})};function yi(a,t){const e=(a.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(a.toFixed(s).replace(".","")),r=parseInt(t.toFixed(s).replace(".",""));return n%r/Math.pow(10,s)}class dt extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==f.number){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.number,received:n.parsedType}),w}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?yi(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,g.toString(e))}gt(t,e){return this.setLimit("min",t,!1,g.toString(e))}lte(t,e){return this.setLimit("max",t,!0,g.toString(e))}lt(t,e){return this.setLimit("max",t,!1,g.toString(e))}setLimit(t,e,i,s){return new dt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:g.toString(s)}]})}_addCheck(t){return new dt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:g.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:g.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:g.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}dt.create=a=>new dt({checks:[],typeName:x.ZodNumber,coerce:a?.coerce||!1,...C(a)});class ft extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==f.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.bigint,received:e.parsedType}),w}gte(t,e){return this.setLimit("min",t,!0,g.toString(e))}gt(t,e){return this.setLimit("min",t,!1,g.toString(e))}lte(t,e){return this.setLimit("max",t,!0,g.toString(e))}lt(t,e){return this.setLimit("max",t,!1,g.toString(e))}setLimit(t,e,i,s){return new ft({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:g.toString(s)}]})}_addCheck(t){return new ft({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:g.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}ft.create=a=>{var t;return new ft({checks:[],typeName:x.ZodBigInt,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...C(a)})};class Jt extends b{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==f.boolean){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.boolean,received:i.parsedType}),w}return z(t.data)}}Jt.create=a=>new Jt({typeName:x.ZodBoolean,coerce:a?.coerce||!1,...C(a)});class _t extends b{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==f.date){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.date,received:n.parsedType}),w}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_date}),w}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new _t({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:g.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:g.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}_t.create=a=>new _t({checks:[],coerce:a?.coerce||!1,typeName:x.ZodDate,...C(a)});class te extends b{_parse(t){if(this._getType(t)!==f.symbol){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.symbol,received:i.parsedType}),w}return z(t.data)}}te.create=a=>new te({typeName:x.ZodSymbol,...C(a)});class Rt extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.undefined,received:i.parsedType}),w}return z(t.data)}}Rt.create=a=>new Rt({typeName:x.ZodUndefined,...C(a)});class zt extends b{_parse(t){if(this._getType(t)!==f.null){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.null,received:i.parsedType}),w}return z(t.data)}}zt.create=a=>new zt({typeName:x.ZodNull,...C(a)});class ee extends b{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}ee.create=a=>new ee({typeName:x.ZodAny,...C(a)});class pt extends b{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}pt.create=a=>new pt({typeName:x.ZodUnknown,...C(a)});class tt extends b{_parse(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.never,received:e.parsedType}),w}}tt.create=a=>new tt({typeName:x.ZodNever,...C(a)});class ie extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.void,received:i.parsedType}),w}return z(t.data)}}ie.create=a=>new ie({typeName:x.ZodVoid,...C(a)});class K extends b{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==f.array)return d(e,{code:u.invalid_type,expected:f.array,received:e.parsedType}),w;if(s.exactLength!==null){const r=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(r||o)&&(d(e,{code:r?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:r?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(d(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(d(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((r,o)=>s.type._parseAsync(new Z(e,r,e.path,o)))).then(r=>L.mergeArray(i,r));const n=[...e.data].map((r,o)=>s.type._parseSync(new Z(e,r,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new K({...this._def,minLength:{value:t,message:g.toString(e)}})}max(t,e){return new K({...this._def,maxLength:{value:t,message:g.toString(e)}})}length(t,e){return new K({...this._def,exactLength:{value:t,message:g.toString(e)}})}nonempty(t){return this.min(1,t)}}K.create=(a,t)=>new K({type:a,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...C(t)});function gt(a){if(a instanceof A){const t={};for(const e in a.shape){const i=a.shape[e];t[e]=Y.create(gt(i))}return new A({...a._def,shape:()=>t})}else return a instanceof K?new K({...a._def,type:gt(a.element)}):a instanceof Y?Y.create(gt(a.unwrap())):a instanceof nt?nt.create(gt(a.unwrap())):a instanceof W?W.create(a.items.map(t=>gt(t))):a}class A extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==f.object){const l=this._getOrReturnCtx(t);return d(l,{code:u.invalid_type,expected:f.object,received:l.parsedType}),w}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(const l in s.data)r.includes(l)||o.push(l);const h=[];for(const l of r){const c=n[l],m=s.data[l];h.push({key:{status:"valid",value:l},value:c._parse(new Z(s,m,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof tt){const l=this._def.unknownKeys;if(l==="passthrough")for(const c of o)h.push({key:{status:"valid",value:c},value:{status:"valid",value:s.data[c]}});else if(l==="strict")o.length>0&&(d(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const c of o){const m=s.data[c];h.push({key:{status:"valid",value:c},value:l._parse(new Z(s,m,s.path,c)),alwaysSet:c in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const c of h){const m=await c.key,p=await c.value;l.push({key:m,value:p,alwaysSet:c.alwaysSet})}return l}).then(l=>L.mergeObjectSync(i,l)):L.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(t){return g.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,r,o;const h=(r=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&r!==void 0?r:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=g.errToObj(t).message)!==null&&o!==void 0?o:h}:{message:h}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return gt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof Y;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return _e(S.objectKeys(this.shape))}}A.create=(a,t)=>new A({shape:()=>a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...C(t)}),A.strictCreate=(a,t)=>new A({shape:()=>a,unknownKeys:"strict",catchall:tt.create(),typeName:x.ZodObject,...C(t)}),A.lazycreate=(a,t)=>new A({shape:a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...C(t)});class Dt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(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 e.common.issues.push(...o.ctx.common.issues),o.result;const r=n.map(o=>new N(o.ctx.common.issues));return d(e,{code:u.invalid_union,unionErrors:r}),w}if(e.common.async)return Promise.all(i.map(async n=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(s);{let n;const r=[];for(const h of i){const l={...e,common:{...e.common,issues:[]},parent:null},c=h._parseSync({data:e.data,path:e.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!n&&(n={result:c,ctx:l}),l.common.issues.length&&r.push(l.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=r.map(h=>new N(h));return d(e,{code:u.invalid_union,unionErrors:o}),w}}get options(){return this._def.options}}Dt.create=(a,t)=>new Dt({options:a,typeName:x.ZodUnion,...C(t)});const U=a=>a instanceof Nt?U(a.schema):a instanceof X?U(a.innerType()):a instanceof Ht?[a.value]:a instanceof st?a.options:a instanceof Bt?S.objectValues(a.enum):a instanceof Vt?U(a._def.innerType):a instanceof Rt?[void 0]:a instanceof zt?[null]:a instanceof Y?[void 0,...U(a.unwrap())]:a instanceof nt?[null,...U(a.unwrap())]:a instanceof Se||a instanceof jt?U(a.unwrap()):a instanceof Zt?U(a._def.innerType):[];class se extends b{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.object)return d(e,{code:u.invalid_type,expected:f.object,received:e.parsedType}),w;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(d(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const r=U(n.shape[t]);if(!r.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of r){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new se({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...C(i)})}}function ne(a,t){const e=J(a),i=J(t);if(a===t)return{valid:!0,data:a};if(e===f.object&&i===f.object){const s=S.objectKeys(t),n=S.objectKeys(a).filter(o=>s.indexOf(o)!==-1),r={...a,...t};for(const o of n){const h=ne(a[o],t[o]);if(!h.valid)return{valid:!1};r[o]=h.data}return{valid:!0,data:r}}else if(e===f.array&&i===f.array){if(a.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<a.length;n++){const r=a[n],o=t[n],h=ne(r,o);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return e===f.date&&i===f.date&&+a==+t?{valid:!0,data:a}:{valid:!1}}class Mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,r)=>{if(ve(n)||ve(r))return w;const o=ne(n.value,r.value);return o.valid?((xe(n)||xe(r))&&e.dirty(),{status:e.value,value:o.data}):(d(i,{code:u.invalid_intersection_types}),w)};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,r])=>s(n,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Mt.create=(a,t,e)=>new Mt({left:a,right:t,typeName:x.ZodIntersection,...C(e)});class W extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.array)return d(i,{code:u.invalid_type,expected:f.array,received:i.parsedType}),w;if(i.data.length<this._def.items.length)return d(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&i.data.length>this._def.items.length&&(d(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((r,o)=>{const h=this._def.items[o]||this._def.rest;return h?h._parse(new Z(i,r,i.path,o)):null}).filter(r=>!!r);return i.common.async?Promise.all(n).then(r=>L.mergeArray(e,r)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new W({...this._def,rest:t})}}W.create=(a,t)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W({items:a,typeName:x.ZodTuple,rest:null,...C(t)})};class Ft extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.object)return d(i,{code:u.invalid_type,expected:f.object,received:i.parsedType}),w;const s=[],n=this._def.keyType,r=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new Z(i,o,i.path,o)),value:r._parse(new Z(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof b?new Ft({keyType:t,valueType:e,typeName:x.ZodRecord,...C(i)}):new Ft({keyType:$.create(),valueType:t,typeName:x.ZodRecord,...C(e)})}}class ae extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.map)return d(i,{code:u.invalid_type,expected:f.map,received:i.parsedType}),w;const s=this._def.keyType,n=this._def.valueType,r=[...i.data.entries()].map(([o,h],l)=>({key:s._parse(new Z(i,o,i.path,[l,"key"])),value:n._parse(new Z(i,h,i.path,[l,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const h of r){const l=await h.key,c=await h.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&e.dirty(),o.set(l.value,c.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const h of r){const l=h.key,c=h.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&e.dirty(),o.set(l.value,c.value)}return{status:e.value,value:o}}}}ae.create=(a,t,e)=>new ae({valueType:t,keyType:a,typeName:x.ZodMap,...C(e)});class mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.set)return d(i,{code:u.invalid_type,expected:f.set,received:i.parsedType}),w;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(d(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(d(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function r(h){const l=new Set;for(const c of h){if(c.status==="aborted")return w;c.status==="dirty"&&e.dirty(),l.add(c.value)}return{status:e.value,value:l}}const o=[...i.data.values()].map((h,l)=>n._parse(new Z(i,h,i.path,l)));return i.common.async?Promise.all(o).then(h=>r(h)):r(o)}min(t,e){return new mt({...this._def,minSize:{value:t,message:g.toString(e)}})}max(t,e){return new mt({...this._def,maxSize:{value:t,message:g.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}mt.create=(a,t)=>new mt({valueType:a,minSize:null,maxSize:null,typeName:x.ZodSet,...C(t)});class St extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.function)return d(e,{code:u.invalid_type,expected:f.function,received:e.parsedType}),w;function i(o,h){return qt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Gt(),wt].filter(l=>!!l),issueData:{code:u.invalid_arguments,argumentsError:h}})}function s(o,h){return qt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Gt(),wt].filter(l=>!!l),issueData:{code:u.invalid_return_type,returnTypeError:h}})}const n={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof Tt){const o=this;return z(async function(...h){const l=new N([]),c=await o._def.args.parseAsync(h,n).catch(k=>{throw l.addIssue(i(h,k)),l}),m=await Reflect.apply(r,this,c);return await o._def.returns._def.type.parseAsync(m,n).catch(k=>{throw l.addIssue(s(m,k)),l})})}else{const o=this;return z(function(...h){const l=o._def.args.safeParse(h,n);if(!l.success)throw new N([i(h,l.error)]);const c=Reflect.apply(r,this,l.data),m=o._def.returns.safeParse(c,n);if(!m.success)throw new N([s(c,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new St({...this._def,args:W.create(t).rest(pt.create())})}returns(t){return new St({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new St({args:t||W.create([]).rest(pt.create()),returns:e||pt.create(),typeName:x.ZodFunction,...C(i)})}}class Nt extends b{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Nt.create=(a,t)=>new Nt({getter:a,typeName:x.ZodLazy,...C(t)});class Ht extends b{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return d(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ht.create=(a,t)=>new Ht({value:a,typeName:x.ZodLiteral,...C(t)});function _e(a,t){return new st({values:a,typeName:x.ZodEnum,...C(t)})}class st extends b{constructor(){super(...arguments),kt.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),w}if(Lt(this,kt)||we(this,kt,new Set(this._def.values)),!Lt(this,kt).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{received:e.data,code:u.invalid_enum_value,options:i}),w}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return st.create(t,{...this._def,...e})}exclude(t,e=this._def){return st.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}kt=new WeakMap,st.create=_e;class Bt extends b{constructor(){super(...arguments),bt.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==f.string&&i.parsedType!==f.number){const s=S.objectValues(e);return d(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),w}if(Lt(this,bt)||we(this,bt,new Set(S.getValidEnumValues(this._def.values))),!Lt(this,bt).has(t.data)){const s=S.objectValues(e);return d(i,{received:i.data,code:u.invalid_enum_value,options:s}),w}return z(t.data)}get enum(){return this._def.values}}bt=new WeakMap,Bt.create=(a,t)=>new Bt({values:a,typeName:x.ZodNativeEnum,...C(t)});class Tt extends b{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.promise&&e.common.async===!1)return d(e,{code:u.invalid_type,expected:f.promise,received:e.parsedType}),w;const i=e.parsedType===f.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Tt.create=(a,t)=>new Tt({type:a,typeName:x.ZodPromise,...C(t)});class X extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:r=>{d(i,r),r.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const r=s.transform(i.data,n);if(i.common.async)return Promise.resolve(r).then(async o=>{if(e.value==="aborted")return w;const h=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return h.status==="aborted"?w:h.status==="dirty"||e.value==="dirty"?Ct(h.value):h});{if(e.value==="aborted")return w;const o=this._def.schema._parseSync({data:r,path:i.path,parent:i});return o.status==="aborted"?w:o.status==="dirty"||e.value==="dirty"?Ct(o.value):o}}if(s.type==="refinement"){const r=o=>{const h=s.refinement(o,n);if(i.common.async)return Promise.resolve(h);if(h 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"?w:(o.status==="dirty"&&e.dirty(),r(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?w:(o.status==="dirty"&&e.dirty(),r(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const r=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ut(r))return r;const o=s.transform(r.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(r=>ut(r)?Promise.resolve(s.transform(r.value,n)).then(o=>({status:e.value,value:o})):r);S.assertNever(s)}}X.create=(a,t,e)=>new X({schema:a,typeName:x.ZodEffects,effect:t,...C(e)}),X.createWithPreprocess=(a,t,e)=>new X({schema:t,effect:{type:"preprocess",transform:a},typeName:x.ZodEffects,...C(e)});class Y extends b{_parse(t){return this._getType(t)===f.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Y.create=(a,t)=>new Y({innerType:a,typeName:x.ZodOptional,...C(t)});class nt extends b{_parse(t){return this._getType(t)===f.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nt.create=(a,t)=>new nt({innerType:a,typeName:x.ZodNullable,...C(t)});class Vt extends b{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===f.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}Vt.create=(a,t)=>new Vt({innerType:a,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...C(t)});class Zt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Et(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new N(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Zt.create=(a,t)=>new Zt({innerType:a,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...C(t)});class re extends b{_parse(t){if(this._getType(t)!==f.nan){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.nan,received:i.parsedType}),w}return{status:"valid",value:t.data}}}re.create=a=>new re({typeName:x.ZodNaN,...C(a)});class Se extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Kt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);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"?w:n.status==="dirty"?(e.dirty(),Ct(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?w:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Kt({in:t,out:e,typeName:x.ZodPipeline})}}class jt extends b{_parse(t){const e=this._def.innerType._parse(t),i=s=>(ut(s)&&(s.value=Object.freeze(s.value)),s);return Et(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}jt.create=(a,t)=>new jt({innerType:a,typeName:x.ZodReadonly,...C(t)}),A.lazycreate;var x;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(x||(x={}));const R=$.create,v=dt.create;re.create,ft.create,Jt.create,_t.create,te.create,Rt.create,zt.create,ee.create,pt.create,tt.create,ie.create,K.create;const T=A.create;A.strictCreate;const vi=Dt.create;se.create,Mt.create,W.create,Ft.create,ae.create,mt.create,St.create,Nt.create;const at=Ht.create,et=st.create;Bt.create,Tt.create,X.create,Y.create,nt.create,X.createWithPreprocess,Kt.create;const xi=et(["linear","bezier","constant"]),wi=et(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),rt=T({from:v(),to:v(),start:v().min(0),length:v().positive(),interpolation:xi.optional(),easing:wi.optional()}),Ci=R().url("Invalid audio url format."),ki=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Te=T({type:at("audio"),src:Ci,trim:v().optional(),volume:ki.optional()}),bi=et(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Oe=T({type:at("html"),html:R(),css:R(),width:v().positive().optional(),height:v().positive().optional(),position:bi.optional()}),_i=R().url("Invalid image url format."),Si=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Ie=T({type:at("image"),src:_i,crop:Si.optional()}),Ti=R().url("Invalid luma url format."),Ae=T({type:at("luma"),src:Ti}),Pe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ee=T({width:v().positive(),height:v().positive()}),Le=T({radius:v().positive()}),Re=T({length:v().positive(),thickness:v().positive()}),Oi=T({color:Pe,opacity:v().min(0).max(1)}),Ii=T({color:Pe,width:v().positive()}),ze=T({type:at("shape"),width:v().positive().optional(),height:v().positive().optional(),shape:et(["rectangle","circle","line"]),fill:Oi.optional(),stroke:Ii.optional(),rectangle:Ee.optional(),circle:Le.optional(),line:Re.optional()}).refine(a=>a.shape==="rectangle"?Ee.safeParse(a.rectangle):a.shape==="circle"?Le.safeParse(a.circle):a.shape==="line"?Re.safeParse(a.line):!1),oe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ai=T({color:oe.optional(),family:R().optional(),size:v().positive().optional(),weight:v().optional(),lineHeight:v().optional()}),Pi=T({horizontal:et(["left","center","right"]).optional(),vertical:et(["top","center","bottom"]).optional()}),Ei=T({color:oe,opacity:v().min(0).max(1)}),Li=T({width:v().positive(),color:oe}),De=T({type:at("text"),text:R(),width:v().positive().optional(),height:v().positive().optional(),font:Ai.optional(),alignment:Pi.optional(),background:Ei.optional(),stroke:Li.optional()}),Ri=R().url("Invalid video url format."),zi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Di=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Me=T({type:at("video"),src:Ri,trim:v().optional(),crop:zi.optional(),volume:Di.optional()}),Mi=vi([De,ze,Oe,Ie,Me,Ae,Te]).refine(a=>a.type==="text"?De.safeParse(a):a.type==="shape"?ze.safeParse(a):a.type==="html"?Oe.safeParse(a):a.type==="image"?Ie.safeParse(a):a.type==="video"?Me.safeParse(a):a.type==="luma"?Ae.safeParse(a):a.type==="audio"?Te.safeParse(a):!1),Fi=et(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Ni=et(["crop","cover","contain","none"]),yt=v().min(-10).max(10).default(0),Hi=rt.extend({from:yt,to:yt}).array().or(yt),Bi=rt.extend({from:yt,to:yt}).array().or(yt),Vi=T({x:Hi.default(0),y:Bi.default(0)}),Zi=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Ki=rt.extend({from:v().min(0),to:v().min(0)}).array().or(v().min(0)),ji=T({angle:rt.extend({from:v(),to:v()}).array().or(v())}),$i=R(),Fe=R(),Ui=T({in:Fe.optional(),out:Fe.optional()}),Wi=T({rotate:ji.default({angle:0})}),Ne=T({asset:Mi,start:v().min(0),length:v().positive(),position:Fi.default("center").optional(),fit:Ni.default("crop").optional(),offset:Vi.default({x:0,y:0}).optional(),opacity:Zi.default(1).optional(),scale:Ki.default(1).optional(),transform:Wi.default({rotate:{angle:0}}).optional(),effect:$i.optional(),transition:Ui.optional()}),Xi=T({clips:Ne.array()}),Yi=R().url("Invalid image url format."),Gi=T({src:Yi}),qi=T({background:R().optional(),fonts:Gi.array().optional(),tracks:Xi.array()}),Qi=T({size:T({width:v().positive(),height:v().positive()}),fps:v().positive().optional(),format:R()}),Ji=T({timeline:qi,output:Qi});class le{container;constructor(){this.container=new y.Container}getContainer(){return this.container}}class ts{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,e,i,s){const n=this.curves[s??""]??this.curves.ease,[[r,o],[h,l]]=n,c=i+(3*r-3*h+1)*i*(1-i),m=t,p=t+(e-t)*o,k=t+(e-t)*l,O=e,_=c,D=1-_;return D**3*m+3*D**2*_*p+3*D*_**2*k+_**3*O}}class E{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new ts}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const c={start:0,length:r.start,from:i,to:r.from};s.push(c)}if(s.push(r),!o){if(r.start+r.length<e){const m=r.start+r.length,p={start:m,length:e-m,from:r.to,to:r.to};s.push(p)}break}if(r.start+r.length!==o.start){const c={start:r.start+r.length,length:o.start,from:r.to,to:o.from};s.push(c)}}return s}}class $t{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=$t.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(s=>{const n={src:t},r=new Howl(n);r.on("load",()=>s(r)),r.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class es{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],r=[],o=[],{effect:h,length:l}=this.clipConfiguration;if(!h)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const c=0;switch(this.getPresetName()){case"zoomIn":{const p=this.getZoomSpeed(),k=1*this.clipConfiguration.scale,O=p*this.clipConfiguration.scale;r.push({from:k,to:O,start:c,length:l,interpolation:"linear"});break}case"zoomOut":{const k=this.getZoomSpeed()*this.clipConfiguration.scale,O=1*this.clipConfiguration.scale;r.push({from:k,to:O,start:c,length:l,interpolation:"linear"});break}case"slideLeft":{let p=this.getSlideStart();const k=t.width+t.width*p*2,O=e.height/e.width*t.height;if(O<k){const _=Math.abs(k/t.width);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.width)/2/t.width;i.push({from:p,to:-p,start:c,length:l});break}case"slideRight":{let p=this.getSlideStart();const k=t.width+t.width*p*2,O=e.height/e.width*t.height;if(O<k){const _=Math.abs(k/t.width);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.width)/2/t.width;i.push({from:-p,to:p,start:c,length:l});break}case"slideUp":{let p=this.getSlideStart();const k=t.height+t.height*p*2,O=e.height/e.width*t.width;if(O<k){const _=Math.abs(k/t.height);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.height)/2/t.height;s.push({from:p,to:-p,start:c,length:l});break}case"slideDown":{let p=this.getSlideStart();const k=t.height+t.height*p*2,O=e.height/e.width*t.width;if(O<k){const _=Math.abs(k/t.height);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.height)/2/t.height;s.push({from:-p,to:p,start:c,length:l});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class is{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],r=this.buildInPreset();t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:c,start:r,length:o,interpolation:"linear"});break}case"zoom":{const c=this.clipConfiguration.scale+9,m=this.clipConfiguration.scale;s.push({from:c,to:m,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const l=this.clipConfiguration.offset?.x+.025,c=this.clipConfiguration.offset?.x;t.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const l=this.clipConfiguration.offset?.x-.025,c=this.clipConfiguration.offset?.x;t.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const l=this.clipConfiguration.offset?.y+.025,c=this.clipConfiguration.offset?.y;e.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const l=this.clipConfiguration.offset?.y-.025,c=this.clipConfiguration.offset?.y;e.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=this.getOutPresetLength(),o=this.clipConfiguration.length-r;switch(this.getOutPresetName()){case"fade":{const l=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:l,to:0,start:o,length:r,interpolation:"linear"});break}case"zoom":{const c=this.clipConfiguration.scale,m=c+9;s.push({from:c,to:m,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const l=this.clipConfiguration.offset?.x,c=l-.025;t.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const l=this.clipConfiguration.offset?.x,c=l+.025;t.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const l=this.clipConfiguration.offset?.y,c=l-.025;e.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const l=this.clipConfiguration.offset?.y,c=l+.025;e.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const[,t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class ss{static ButtonLeftClick=0;static ButtonRightClick=3}class ns{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class P extends le{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new ns(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}configureKeyframes(){if(this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new E(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],r=new es(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=new is(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new E(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new E(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new E(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new E(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new E(n,this.getLength()))}async load(){this.outline=new y.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new y.Graphics,this.topRightScaleHandle=new y.Graphics,this.bottomRightScaleHandle=new y.Graphics,this.bottomLeftScaleHandle=new y.Graphics,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.rotationHandle=new y.Graphics,this.getContainer().addChild(this.rotationHandle),this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=this.layer,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getScale();this.getContainer().scale.set(n),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const r=this.getRotation();this.getContainer().alpha=this.getOpacity(),this.getContainer().angle=r,this.shouldDiscardFrame()&&(this.getContainer().alpha=0)}draw(){if(!this.outline)return;if((!this.isActive()||this.edit.getSelectedClip()!==this)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const t=this.isHovering||this.isDragging?65535:16777215,e=this.getSize(),i=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.rect(0,0,e.width,e.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||this.edit.getSelectedClip()!==this)return;this.topLeftScaleHandle.fillStyle={color:t},this.topLeftScaleHandle.clear();const s=P.ScaleHandleRadius*2/i;if(this.topLeftScaleHandle.rect(-s/2,-s/2,s,s),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:t},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(e.width-s/2,-s/2,s,s),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:t},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(e.width-s/2,e.height-s/2,s,s),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:t},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-s/2,e.height-s/2,s,s),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const n=e.width/2,r=-50/i;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:t},this.rotationHandle.circle(n,r,P.RotationHandleRadius/i),this.rotationHandle.fill(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.moveTo(n,0),this.outline.lineTo(n,r),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<P.DiscardedFrameCount}onPointerStart(t){if(t.button!==ss.ButtonLeftClick||(this.edit.setSelectedClip(this),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const h=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=h;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const h=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=h;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),h=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/r,l=this.scaleStart*h;this.clipConfiguration.scale=Math.max(P.MinScale,Math.min(l,P.MaxScale)),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),h=(Math.atan2(e.y-n.y,e.x-n.x)-r)*(180/Math.PI);let l=this.rotationStart+h;const c=45,m=l%c,p=2;Math.abs(m)<p?l=Math.floor(l/c)*c:Math.abs(m-c)<p&&(l=Math.ceil(l/c)*c),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=l,this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},r=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],o={x:this.edit.size.width/2,y:this.edit.size.height/2},h=[...r,o],l=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],c={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},m=[...l,c];let p=P.SnapThreshold,k=P.SnapThreshold,O=null,_=null;for(const H of m)for(const vt of h){const G=Math.abs(H.x-vt.x);G<p&&(p=G,O=n.x+(vt.x-H.x));const xt=Math.abs(H.y-vt.y);xt<k&&(k=xt,_=n.y+(vt.y-H.y))}O!==null&&(n.x=O),_!==null&&(n.y=_);const D=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=D.x,this.clipConfiguration.offset.y=D.y,this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,r=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,h=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||r!==void 0&&e!==r||o!==void 0&&i!==o||s!==h}}class ce extends P{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:$t.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof We.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var as=`in vec2 aPosition;
|
|
1
|
+
(function(M,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","@ffmpeg/ffmpeg"],V):(M=typeof globalThis<"u"?globalThis:M||self,V(M.ShotstackStudio={},M.PIXI,M.Howler,M.opentype,M.ffmpeg))})(this,function(M,V,je,Ue,$e){"use strict";function Xt(a){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const e in a)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>a[e]})}}return t.default=a,Object.freeze(t)}const y=Xt(V),We=Xt(je),me=Xt(Ue);class Xe{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,e,i,s){const n=this.curves[s??""]??this.curves.ease,[[r,o],[h,c]]=n,l=i+(3*r-3*h+1)*i*(1-i),g=t,p=t+(e-t)*o,w=t+(e-t)*c,I=e,_=l,D=1-_;return D**3*g+3*D**2*_*p+3*D*_**2*w+_**3*I}}class E{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new Xe}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const l={start:0,length:r.start,from:i,to:r.from};s.push(l)}if(s.push(r),!o){if(r.start+r.length<e){const g=r.start+r.length,p={start:g,length:e-g,from:r.to,to:r.to};s.push(p)}break}if(r.start+r.length!==o.start){const l={start:r.start+r.length,length:o.start,from:r.to,to:o.from};s.push(l)}}return s}}class Ot{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Ot.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(s=>{const n={src:t},r=new Howl(n);r.on("load",()=>s(r)),r.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class Ye{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],r=[],o=[],{effect:h,length:c}=this.clipConfiguration;if(!h)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const l=0;switch(this.getPresetName()){case"zoomIn":{const p=this.getZoomSpeed(),w=1*this.clipConfiguration.scale,I=p*this.clipConfiguration.scale;r.push({from:w,to:I,start:l,length:c,interpolation:"linear"});break}case"zoomOut":{const w=this.getZoomSpeed()*this.clipConfiguration.scale,I=1*this.clipConfiguration.scale;r.push({from:w,to:I,start:l,length:c,interpolation:"linear"});break}case"slideLeft":{let p=this.getSlideStart();const w=t.width+t.width*p*2,I=e.height/e.width*t.height;if(I<w){const _=Math.abs(w/t.width);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.width)/2/t.width;i.push({from:p,to:-p,start:l,length:c});break}case"slideRight":{let p=this.getSlideStart();const w=t.width+t.width*p*2,I=e.height/e.width*t.height;if(I<w){const _=Math.abs(w/t.width);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.width)/2/t.width;i.push({from:-p,to:p,start:l,length:c});break}case"slideUp":{let p=this.getSlideStart();const w=t.height+t.height*p*2,I=e.height/e.width*t.width;if(I<w){const _=Math.abs(w/t.height);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.height)/2/t.height;s.push({from:p,to:-p,start:l,length:c});break}case"slideDown":{let p=this.getSlideStart();const w=t.height+t.height*p*2,I=e.height/e.width*t.width;if(I<w){const _=Math.abs(w/t.height);r.push({from:_,to:_,start:l,length:c,interpolation:"linear"})}else p=(I-t.height)/2/t.height;s.push({from:-p,to:p,start:l,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class Ge{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],r=this.buildInPreset();t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const l=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:l,start:r,length:o,interpolation:"linear"});break}case"zoom":{const l=this.clipConfiguration.scale+9,g=this.clipConfiguration.scale;s.push({from:l,to:g,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x+.025,l=this.clipConfiguration.offset?.x;t.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x-.025,l=this.clipConfiguration.offset?.x;t.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y+.025,l=this.clipConfiguration.offset?.y;e.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y-.025,l=this.clipConfiguration.offset?.y;e.push({from:c,to:l,start:r,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=this.getOutPresetLength(),o=this.clipConfiguration.length-r;switch(this.getOutPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:c,to:0,start:o,length:r,interpolation:"linear"});break}case"zoom":{const l=this.clipConfiguration.scale,g=l+9;s.push({from:l,to:g,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x,l=c-.025;t.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x,l=c+.025;t.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y,l=c-.025;e.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y,l=c+.025;e.push({from:c,to:l,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const[,t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class qe{static ButtonLeftClick=0;static ButtonRightClick=3}class Qe{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class Yt{container;constructor(){this.container=new y.Container}getContainer(){return this.container}}class P extends Yt{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new Qe(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new E(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],r=new Ye(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=new Ge(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new E(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new E(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new E(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new E(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new E(n,this.getLength()))}async load(){this.outline=new y.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new y.Graphics,this.topRightScaleHandle=new y.Graphics,this.bottomRightScaleHandle=new y.Graphics,this.bottomLeftScaleHandle=new y.Graphics,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.rotationHandle=new y.Graphics,this.getContainer().addChild(this.rotationHandle),this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=this.layer,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getScale();this.getContainer().scale.set(n),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const r=this.getRotation();this.getContainer().alpha=this.getOpacity(),this.getContainer().angle=r,this.shouldDiscardFrame()&&(this.getContainer().alpha=0)}draw(){if(!this.outline)return;if((!this.isActive()||this.edit.getSelectedClip()!==this)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const t=this.isHovering||this.isDragging?65535:16777215,e=this.getSize(),i=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.rect(0,0,e.width,e.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||this.edit.getSelectedClip()!==this)return;this.topLeftScaleHandle.fillStyle={color:t},this.topLeftScaleHandle.clear();const s=P.ScaleHandleRadius*2/i;if(this.topLeftScaleHandle.rect(-s/2,-s/2,s,s),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:t},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(e.width-s/2,-s/2,s,s),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:t},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(e.width-s/2,e.height-s/2,s,s),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:t},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-s/2,e.height-s/2,s,s),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const n=e.width/2,r=-50/i;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:t},this.rotationHandle.circle(n,r,P.RotationHandleRadius/i),this.rotationHandle.fill(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.moveTo(n,0),this.outline.lineTo(n,r),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<P.DiscardedFrameCount}onPointerStart(t){if(t.button!==qe.ButtonLeftClick||(this.edit.setSelectedClip(this),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const h=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=h;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const h=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=h;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),h=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/r,c=this.scaleStart*h;this.clipConfiguration.scale=Math.max(P.MinScale,Math.min(c,P.MaxScale)),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),h=(Math.atan2(e.y-n.y,e.x-n.x)-r)*(180/Math.PI);let c=this.rotationStart+h;const l=45,g=c%l,p=2;Math.abs(g)<p?c=Math.floor(c/l)*l:Math.abs(g-l)<p&&(c=Math.ceil(c/l)*l),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=c,this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},r=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],o={x:this.edit.size.width/2,y:this.edit.size.height/2},h=[...r,o],c=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],l={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},g=[...c,l];let p=P.SnapThreshold,w=P.SnapThreshold,I=null,_=null;for(const N of g)for(const yt of h){const G=Math.abs(N.x-yt.x);G<p&&(p=G,I=n.x+(yt.x-N.x));const vt=Math.abs(N.y-yt.y);vt<w&&(w=vt,_=n.y+(yt.y-N.y))}I!==null&&(n.x=I),_!==null&&(n.y=_);const D=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=D.x,this.clipConfiguration.offset.y=D.y,this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration,structuredClone(this.clipConfiguration)),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,r=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,h=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||r!==void 0&&e!==r||o!==void 0&&i!==o||s!==h}}class Gt extends P{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:Ot.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof We.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var Je=`in vec2 aPosition;
|
|
2
2
|
out vec2 vTextureCoord;
|
|
3
3
|
|
|
4
4
|
uniform vec4 uInputSize;
|
|
@@ -25,7 +25,7 @@ void main(void)
|
|
|
25
25
|
gl_Position = filterVertexPosition();
|
|
26
26
|
vTextureCoord = filterTextureCoord();
|
|
27
27
|
}
|
|
28
|
-
`,
|
|
28
|
+
`,ti=`struct GlobalFilterUniforms {
|
|
29
29
|
uInputSize:vec4<f32>,
|
|
30
30
|
uInputPixel:vec4<f32>,
|
|
31
31
|
uInputClamp:vec4<f32>,
|
|
@@ -74,7 +74,7 @@ fn mainVertex(
|
|
|
74
74
|
filterVertexPosition(aPosition),
|
|
75
75
|
filterTextureCoord(aPosition)
|
|
76
76
|
);
|
|
77
|
-
}`,
|
|
77
|
+
}`,ei=`precision highp float;
|
|
78
78
|
in vec2 vTextureCoord;
|
|
79
79
|
out vec4 finalColor;
|
|
80
80
|
|
|
@@ -115,7 +115,7 @@ void main(void) {
|
|
|
115
115
|
vec4 outlineColor = vec4(vec3(uColor) * outlineAlpha, outlineAlpha);
|
|
116
116
|
finalColor = contentColor + outlineColor;
|
|
117
117
|
}
|
|
118
|
-
`,
|
|
118
|
+
`,ii=`struct OutlineUniforms {
|
|
119
119
|
uThickness:vec2<f32>,
|
|
120
120
|
uColor:vec3<f32>,
|
|
121
121
|
uAlpha:f32,
|
|
@@ -179,7 +179,7 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
|
|
|
179
179
|
return maxAlpha;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,cs=Object.defineProperty,hs=(a,t,e)=>t in a?cs(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,ot=(a,t,e)=>(hs(a,typeof t!="symbol"?t+"":t,e),e);const Ut=class ht extends V.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(V.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...ht.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=V.GpuProgram.from({vertex:{source:rs,entryPoint:"mainVertex"},fragment:{source:ls,entryPoint:"mainFragment"}}),n=V.GlProgram.from({vertex:as,fragment:os.replace(/\$\{ANGLE_STEP\}/,ht.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),ot(this,"uniforms"),ot(this,"_thickness"),ot(this,"_quality"),ot(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=ht.getAngleStep(i),this._color=new V.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*ht.MAX_SAMPLES,ht.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=ht.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ot(Ut,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ot(Ut,"MIN_SAMPLES",1),ot(Ut,"MAX_SAMPLES",100);let he=Ut;class us extends P{background;text;constructor(t,e){super(t,e),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new y.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const s=new y.Text;s.text=e.text;const{horizontal:n,vertical:r}=e.alignment;s.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-s.width/2,h=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),r==="top"&&(h=0),r==="bottom"&&(h=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:h},e.stroke.color&&e.stroke.width){const l=new he({thickness:e.stroke.width,color:e.stroke.color});s.filters=[l]}this.background=i,this.text=s,this.getContainer().addChild(i),this.getContainer().addChild(s),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i,position:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",h=(await new CSSStyleSheet().replace(i)).cssRules[0],l={text:r,font:{},alignment:{},background:{},stroke:{}};if(h?.constructor.name!=="CSSStyleRule"||!("style"in h))return console.warn("Unsupported css format."),l;const c=h.style,m=this.parseAlignment(s??"center");l.font={color:c.color.length?c.color:void 0,family:c.fontFamily.length?c.fontFamily:void 0,size:c.fontSize.length?parseInt(c.fontSize,10):void 0,weight:c.fontWeight.length?parseInt(c.fontWeight,10):void 0,lineHeight:c.lineHeight.length?parseInt(c.lineHeight,10):void 0},l.alignment=m;let p="";return c.background.length&&(p=c.background),c.backgroundColor.length&&(p=c.backgroundColor),l.background={color:p.length?p:void 0,opacity:c.opacity.length?parseInt(c.opacity,10):void 0},l.stroke={width:c.strokeWidth.length?parseInt(c.strokeWidth,10):void 0,color:c.stroke.length?c.stroke:void 0},l}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ds extends P{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),l=n,c=o,m=i-n-r,p=s-o-h,k=new y.Rectangle(l,c,m,p);return new y.Texture({source:t.source,frame:k})}}class He extends P{texture;sprite;isPlaying;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource||s?.source instanceof y.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof y.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class fs extends P{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new y.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new y.Graphics;switch(t.shape){case"rectangle":{const r=t.rectangle,o=i/2-r.width/2,h=s/2-r.height/2;n.rect(o,h,r.width,r.height);break}case"circle":{const r=t.circle,o=i/2,h=s/2;n.circle(o,h,r.radius);break}case"line":{const r=t.line,o=i/2-r.length/2,h=s/2-r.thickness/2;n.rect(o,h,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const r=new he({thickness:t.stroke.width,color:t.stroke.color});n.filters=[r]}this.shapeBackground=e,this.shape=n,this.getContainer().addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}}class Ot{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(t,e,i,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??Ot.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??Ot.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??Ot.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(t){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(t),this.calculateAndApplyPixelPosition()}setPosition(t,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(t){this.isVisible=t,this.cursor&&!this.isBlinking&&(this.cursor.visible=t)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(t){this.blinkIntervalMs=t,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(t){console.warn("TextCursor: Error removing cursor from parent:",t)}if(this.cursor)try{this.cursor.destroy()}catch(t){console.warn("TextCursor: Error destroying cursor graphics:",t)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new y.Graphics,this.cursor.fillStyle={color:this.color};const t=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,t),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(t){return this.textElement?Math.max(0,Math.min(t,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:t}=this.textElement,e=this.textElement.style,i=t.substring(0,this.textPosition),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
|
|
182
|
+
const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,si=Object.defineProperty,ni=(a,t,e)=>t in a?si(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,st=(a,t,e)=>(ni(a,typeof t!="symbol"?t+"":t,e),e);const At=class lt extends V.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(V.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...lt.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=V.GpuProgram.from({vertex:{source:ti,entryPoint:"mainVertex"},fragment:{source:ii,entryPoint:"mainFragment"}}),n=V.GlProgram.from({vertex:Je,fragment:ei.replace(/\$\{ANGLE_STEP\}/,lt.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),st(this,"uniforms"),st(this,"_thickness"),st(this,"_quality"),st(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=lt.getAngleStep(i),this._color=new V.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*lt.MAX_SAMPLES,lt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=lt.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};st(At,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),st(At,"MIN_SAMPLES",1),st(At,"MAX_SAMPLES",100);let qt=At;class ai extends P{background;text;constructor(t,e){super(t,e),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new y.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const s=new y.Text;s.text=e.text;const{horizontal:n,vertical:r}=e.alignment;s.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-s.width/2,h=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),r==="top"&&(h=0),r==="bottom"&&(h=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:h},e.stroke.color&&e.stroke.width){const c=new qt({thickness:e.stroke.width,color:e.stroke.color});s.filters=[c]}this.background=i,this.text=s,this.getContainer().addChild(i),this.getContainer().addChild(s),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i,position:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",h=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:r,font:{},alignment:{},background:{},stroke:{}};if(h?.constructor.name!=="CSSStyleRule"||!("style"in h))return console.warn("Unsupported css format."),c;const l=h.style,g=this.parseAlignment(s??"center");c.font={color:l.color.length?l.color:void 0,family:l.fontFamily.length?l.fontFamily:void 0,size:l.fontSize.length?parseInt(l.fontSize,10):void 0,weight:l.fontWeight.length?parseInt(l.fontWeight,10):void 0,lineHeight:l.lineHeight.length?parseInt(l.lineHeight,10):void 0},c.alignment=g;let p="";return l.background.length&&(p=l.background),l.backgroundColor.length&&(p=l.backgroundColor),c.background={color:p.length?p:void 0,opacity:l.opacity.length?parseInt(l.opacity,10):void 0},c.stroke={width:l.strokeWidth.length?parseInt(l.strokeWidth,10):void 0,color:l.stroke.length?l.stroke:void 0},c}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ri extends P{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),c=n,l=o,g=i-n-r,p=s-o-h,w=new y.Rectangle(c,l,g,p);return new y.Texture({source:t.source,frame:w})}}class ge extends P{texture;sprite;isPlaying;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource||s?.source instanceof y.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof y.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class oi extends P{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new y.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new y.Graphics;switch(t.shape){case"rectangle":{const r=t.rectangle,o=i/2-r.width/2,h=s/2-r.height/2;n.rect(o,h,r.width,r.height);break}case"circle":{const r=t.circle,o=i/2,h=s/2;n.circle(o,h,r.radius);break}case"line":{const r=t.line,o=i/2-r.length/2,h=s/2-r.thickness/2;n.rect(o,h,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const r=new qt({thickness:t.stroke.width,color:t.stroke.color});n.filters=[r]}this.shapeBackground=e,this.shape=n,this.getContainer().addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}}class xt{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(t,e,i,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??xt.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??xt.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??xt.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(t){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(t),this.calculateAndApplyPixelPosition()}setPosition(t,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(t){this.isVisible=t,this.cursor&&!this.isBlinking&&(this.cursor.visible=t)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(t){this.blinkIntervalMs=t,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(t){console.warn("TextCursor: Error removing cursor from parent:",t)}if(this.cursor)try{this.cursor.destroy()}catch(t){console.warn("TextCursor: Error destroying cursor graphics:",t)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new y.Graphics,this.cursor.fillStyle={color:this.color};const t=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,t),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(t){return this.textElement?Math.max(0,Math.min(t,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:t}=this.textElement,e=this.textElement.style,i=t.substring(0,this.textPosition),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
|
|
183
183
|
`),r=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
|
|
184
|
-
`),h=o===-1?this.textPosition:this.textPosition-o-1,l=r.substring(0,h);let c;l.length>0&&l.endsWith(" ")?c=this.measureText(`${l}x`,e)-this.measureText("x",e):c=this.measureText(l,e);const m=e.lineHeight;this.pixelY=this.currentLine*m;const k=this.clipConfig.asset.alignment?.horizontal??"center";let O=c;if(k!=="left"){const _=this.measureText(r,e),D=this.textElement.width;let H=0;k==="center"?H=(D-_)/2:k==="right"&&(H=D-_),O=H+c}this.pixelX=O}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(t,e){const i=new y.Text(t,e),{width:s}=i;return i.destroy(),s}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Wt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Wt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Wt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(t,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const t={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},0),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class j{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(t,e,i){this.parent=t,this.targetText=e,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<j.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<s.x||n>s.x+s.width||r<s.y||r>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},j.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new Ot(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new y.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new y.Graphics;t.fillStyle={color:0,alpha:j.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*j.EDITING_BG_PADDING_PX,this.targetText.height+2*j.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new y.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Wt,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof y.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:j.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*j.EDITING_BG_PADDING_PX,this.editableText.height+2*j.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class ps extends P{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new y.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new y.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new he({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.getContainer().addChild(this.background),this.getContainer().addChild(this.text),this.configureKeyframes(),this.textEditor=new j(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new y.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let r=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}updateTextContent(t,e){if(this.clipConfiguration.asset&&"text"in this.clipConfiguration.asset){if(this.clipConfiguration.asset.text=t,this.text){this.text.text=t;const i=this.clipConfiguration.asset;this.positionText(i)}this.edit.setUpdatedClip(this,e)}}}class gs extends P{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),l=n,c=o,m=i-n-r,p=s-o-h,k=new y.Rectangle(l,c,m,p);return new y.Texture({source:t.source,frame:k})}}class lt extends le{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;constructor(t,e="#ffffff"){super(),this.assetLoader=new At,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new me,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e}async load(){const t=new y.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){this.clearClips()}play(){this.isPlaying=!0}pause(){this.isPlaying=!1}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=Ji.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:Pt.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=[],e=new Map;for(const s of this.clips)e.has(s.layer)||e.set(s.layer,{clips:[]}),e.get(s.layer).clips.push(s.clipConfiguration);const i=Math.max(...e.keys(),0);for(let s=1;s<=i;s+=1)t[s-1]=e.get(s)||{clips:[]};return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=Ne.parse(e),s=this.createPlayerFromAssetType(i);s.layer=t+1,this.addPlayer(t,s),this.updateTotalDuration()}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}deleteClip(t,e){const i=this.clips.find(s=>s.layer===t+1&&this.clips.filter(n=>n.layer===t+1).indexOf(s)===e);i&&(this.queueDisposeClip(i),this.updateTotalDuration())}addTrack(t,e){this.tracks.splice(t,0,[]);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>=t+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*lt.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer+=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*lt.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new y.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),e?.clips?.forEach(s=>this.addClip(t,s)),this.updateTotalDuration()}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=this.clips.filter(s=>s.layer===t+1);for(const s of e)s.shouldDispose=!0;this.disposeClips(),this.tracks.splice(t,1);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>t+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*lt.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer-=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*lt.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new y.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),this.updateTotalDuration()}getTotalDuration(){return this.totalDuration}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t;const e=t.layer-1,s=this.clips.filter(r=>r.layer===t.layer).indexOf(t),n={clip:t.clipConfiguration,trackIndex:e,clipIndex:s};this.events.emit("clip:selected",n)}setUpdatedClip(t,e=null){this.updatedClip=t;const i=t.layer-1,n=this.clips.filter(o=>o.layer===t.layer).indexOf(t),r={previous:{clip:e,trackIndex:i,clipIndex:n},current:{clip:t.clipConfiguration,trackIndex:i,clipIndex:n}};this.events.emit("clip:updated",r)}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof y.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch{console.warn("Attempting to unmount an unmounted clip.")}this.unloadClipAssets(t),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{y.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const e of this.tracks)for(const i of e)t=Math.max(t,i.getEnd());this.totalDuration=t}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new ps(this,t);break}case"shape":{e=new fs(this,t);break}case"html":{e=new us(this,t);break}case"image":{e=new ds(this,t);break}case"video":{e=new gs(this,t);break}case"audio":{e=new ce(this,t);break}case"luma":{e=new He(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*lt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new y.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const r=e instanceof He;await e.load(),r&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}}class It extends le{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new y.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,It.Width,It.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new y.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:It.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
|
|
185
|
-
`)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class ct{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new y.Application,this.edit=e,this.inspector=new It}async load(){const t=document.querySelector(ct.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${ct.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new y.Container,this.background=new y.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,r=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},h={x:e.position.x-o.x,y:e.position.y-o.y},l=this.currentZoom/r;e.position.x=o.x+h.x*l,e.position.y=o.y+h.y*l,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerExtensions(){ct.extensionsRegistered||(y.extensions.add(new $t),y.extensions.add(new Pt),ct.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw()}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new y.Rectangle(0,0,this.size.width,this.size.height),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}dispose(){const t=document.querySelector(ct.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class ms{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class ys{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new Ue.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),r=n.visible,{x:o,y:h}=n.position,{x:l,y:c}=n.scale;n.visible=!1;const m=this.createProgressOverlay();try{const p=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},k=Math.ceil(this.edit.totalDuration*e/1e3),O=1e3/e,_=100,D=50,H=50,vt=I=>Math.round(I/k*D);this.updateProgressOverlay(m,0,_);const G=document.createElement("canvas");G.width=p.width,G.height=p.height;const xt=G.getContext("2d");if(!xt)throw new Error("Could not get 2D context for canvas");const ue=this.findAudioPlayers();this.updateProgressOverlay(m,2,_);const q=[];if(ue.length>0){this.updateProgressOverlay(m,3,_);for(let I=0;I<ue.length;I+=1){const B=await this.processAudioTrack(ue[I],I);B&&q.push(B),this.updateProgressOverlay(m,4+I,_)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let I=0;I<k;I+=1){this.edit.seek(I*O),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:B}=this.application.renderer,M=B.canvas(n);xt.clearRect(0,0,G.width,G.height),xt.drawImage(M,0,0);const Q=G.toDataURL("image/png"),Xt=await(await fetch(Q)).arrayBuffer(),ws=`frame_${I.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(ws,new Uint8Array(Xt))}catch(B){console.error(`Error capturing frame ${I}:`,B)}this.updateProgressOverlay(m,vt(I+1),_)}this.updateProgressOverlay(m,D,_);let it=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const I of q)it=it.concat(["-i",I.filename]);if(it=it.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),q.length>0){let I="";for(let M=0;M<q.length;M+=1){const Q=q[M],Ke=M+1,Xt=Math.max(0,Q.start);I+=`[${Ke}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${Q.duration/1e3+.1},adelay=${Xt}|${Xt},volume=${Q.volume}[a${M}];`}const B=q.length>1?`${q.map((M,Q)=>`[a${Q}]`).join("")}amix=inputs=${q.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";I+=B,it=it.concat(["-filter_complex",I,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const de="output.mp4";it.push(de);let Be=0;const Ve=({message:I})=>{const B=I.includes("frame=")&&I.includes("fps=")?I.match(/frame=\s*(\d+)/):null;if(B?.[1]){const M=parseInt(B[1],10);if(!Number.isNaN(M)&&M>Be&&(Be=M,M<=k)){const Q=Math.round(M/k*H);this.updateProgressOverlay(m,D+Q,_)}}};this.ffmpeg.on("log",Ve),await this.ffmpeg.exec(it),this.ffmpeg.off("log",Ve),this.updateProgressOverlay(m,D+H,_);const fe=await this.ffmpeg.readFile(de),vs=fe instanceof Uint8Array?fe:new TextEncoder().encode(fe.toString()),xs=new Blob([vs],{type:"video/mp4"}),Ze=URL.createObjectURL(xs),pe=document.createElement("a");pe.href=Ze,pe.download=t,pe.click(),URL.revokeObjectURL(Ze);for(let I=0;I<k;I+=1)try{await this.ffmpeg.deleteFile(`frame_${I.toString().padStart(6,"0")}.png`)}catch{}for(const I of q)try{await this.ffmpeg.deleteFile(I.filename)}catch{}await this.ffmpeg.deleteFile(de),this.updateProgressOverlay(m,_,_)}catch(p){throw console.error("Error during export:",p),p}finally{this.removeProgressOverlay(m),n.position.x=o,n.position.y=h,n.scale.x=l,n.scale.y=c,n.visible=r,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const r=s[n];(r instanceof ce||r.constructor.name==="AudioPlayer"||r.clipConfiguration?.asset?.type==="audio")&&(t.includes(r)||t.push(r))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof y.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof y.Container){const r=n,o=["player","clip","audioPlayer","entity"];for(const h of o){const l=r[h];l instanceof ce&&!e.includes(l)&&e.push(l)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const r=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(r)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const r=document.createElement("div");return r.className="video-export-percent",r.innerText="0%",r.style.fontSize="12px",e.appendChild(r),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),r=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),r&&(r.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}F.Canvas=ct,F.Controls=ms,F.Edit=lt,F.VideoExporter=ys,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})});
|
|
184
|
+
`),h=o===-1?this.textPosition:this.textPosition-o-1,c=r.substring(0,h);let l;c.length>0&&c.endsWith(" ")?l=this.measureText(`${c}x`,e)-this.measureText("x",e):l=this.measureText(c,e);const g=e.lineHeight;this.pixelY=this.currentLine*g;const w=this.clipConfig.asset.alignment?.horizontal??"center";let I=l;if(w!=="left"){const _=this.measureText(r,e),D=this.textElement.width;let N=0;w==="center"?N=(D-_)/2:w==="right"&&(N=D-_),I=N+l}this.pixelX=I}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(t,e){const i=new y.Text(t,e),{width:s}=i;return i.destroy(),s}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Pt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Pt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Pt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(t,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const t={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},0),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class K{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(t,e,i){this.parent=t,this.targetText=e,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<K.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<s.x||n>s.x+s.width||r<s.y||r>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},K.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new xt(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new y.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new y.Graphics;t.fillStyle={color:0,alpha:K.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*K.EDITING_BG_PADDING_PX,this.targetText.height+2*K.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new y.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Pt,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof y.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:K.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*K.EDITING_BG_PADDING_PX,this.editableText.height+2*K.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class ci extends P{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new y.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new y.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new qt({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.getContainer().addChild(this.background),this.getContainer().addChild(this.text),this.configureKeyframes(),this.textEditor=new K(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new y.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let r=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}}class li extends P{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),c=n,l=o,g=i-n-r,p=s-o-h,w=new y.Rectangle(c,l,g,p);return new y.Texture({source:t.source,frame:w})}}var S;(function(a){a.assertEqual=s=>s;function t(s){}a.assertIs=t;function e(s){throw new Error}a.assertNever=e,a.arrayToEnum=s=>{const n={};for(const r of s)n[r]=r;return n},a.getValidEnumValues=s=>{const n=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),r={};for(const o of n)r[o]=s[o];return a.objectValues(r)},a.objectValues=s=>a.objectKeys(s).map(function(n){return s[n]}),a.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&n.push(r);return n},a.find=(s,n)=>{for(const r of s)if(n(r))return r},a.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(r=>typeof r=="string"?`'${r}'`:r).join(n)}a.joinValues=i,a.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var ye;(function(a){a.mergeShapes=(t,e)=>({...t,...e})})(ye||(ye={}));const f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}},u=S.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 H extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const r of n.issues)if(r.code==="invalid_union")r.unionErrors.map(s);else if(r.code==="invalid_return_type")s(r.returnTypeError);else if(r.code==="invalid_arguments")s(r.argumentsError);else if(r.path.length===0)i._errors.push(e(r));else{let o=i,h=0;for(;h<r.path.length;){const c=r.path[h];h===r.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(e(r))):o[c]=o[c]||{_errors:[]},o=o[c],h++}}};return s(this),i}static assert(t){if(!(t instanceof H))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}H.create=a=>new H(a);const Ct=(a,t)=>{let e;switch(a.code){case u.invalid_type:a.received===f.undefined?e="Required":e=`Expected ${a.expected}, received ${a.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(a.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(a.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(a.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(a.options)}, received '${a.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(e=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?e=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?e=`Invalid input: must end with "${a.validation.endsWith}"`:S.assertNever(a.validation):a.validation!=="regex"?e=`Invalid ${a.validation}`:e="Invalid";break;case u.too_small:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:e="Invalid input";break;case u.too_big:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?e=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${a.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(a)}return{message:e}};let hi=Ct;function Qt(){return hi}const Jt=a=>{const{data:t,path:e,errorMaps:i,issueData:s}=a,n=[...e,...s.path||[]],r={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const h=i.filter(c=>!!c).slice().reverse();for(const c of h)o=c(r,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function d(a,t){const e=Qt(),i=Jt({issueData:t,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,e,e===Ct?void 0:Ct].filter(s=>!!s)});a.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return C;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,r=await s.value;i.push({key:n,value:r})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:r}=s;if(n.status==="aborted"||r.status==="aborted")return C;n.status==="dirty"&&t.dirty(),r.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof r.value<"u"||s.alwaysSet)&&(i[n.value]=r.value)}return{status:t.value,value:i}}}const C=Object.freeze({status:"aborted"}),kt=a=>({status:"dirty",value:a}),z=a=>({status:"valid",value:a}),ve=a=>a.status==="aborted",xe=a=>a.status==="dirty",ht=a=>a.status==="valid",Et=a=>typeof Promise<"u"&&a instanceof Promise;function Lt(a,t,e,i){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(a)}function Ce(a,t,e,i,s){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(a,e),e}typeof SuppressedError=="function"&&SuppressedError;var m;(function(a){a.errToObj=t=>typeof t=="string"?{message:t}:t||{},a.toString=t=>typeof t=="string"?t:t?.message})(m||(m={}));var wt,bt;class Z{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ke=(a,t)=>{if(ht(t))return{success:!0,data:t.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new H(a.common.issues);return this._error=e,this._error}}};function k(a){if(!a)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=a;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(r,o)=>{var h,c;const{message:l}=a;return r.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:(h=l??i)!==null&&h!==void 0?h:o.defaultError}:r.code!=="invalid_type"?{message:o.defaultError}:{message:(c=l??e)!==null&&c!==void 0?c:o.defaultError}},description:s}}class b{get description(){return this._def.description}_getType(t){return J(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Et(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},n=this._parseSync({data:t,path:s.path,parent:s});return ke(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ht(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ht(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Et(s)?s:Promise.resolve(s));return ke(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const r=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&r instanceof Promise?r.then(h=>h?!0:(o(),!1)):r?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new X({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:e=>this["~validate"](e)}}optional(){return Y.create(this,this._def)}nullable(){return at.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return j.create(this)}promise(){return Tt.create(this,this._def)}or(t){return Dt.create([this,t],this._def)}and(t){return Ft.create(this,t,this._def)}transform(t){return new X({...k(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new Vt({...k(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new Se({typeName:x.ZodBranded,type:this,...k(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Kt({...k(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Zt.create(this,t)}readonly(){return jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ui=/^c[^\s-]{8,}$/i,di=/^[0-9a-z]+$/,fi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pi=/^[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,mi=/^[a-z0-9_-]{21}$/i,gi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yi=/^[-+]?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)?)??$/,vi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let te;const Ci=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ki=/^(?:(?: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])$/,wi=/^(([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]))$/,bi=/^(([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])$/,_i=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Si=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we="((\\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])))",Ti=new RegExp(`^${we}$`);function be(a){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?t=`${t}\\.\\d{${a.precision}}`:a.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Ii(a){return new RegExp(`^${be(a)}$`)}function Oi(a){let t=`${we}T${be(a)}`;const e=[];return e.push(a.local?"Z?":"Z"),a.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function Ai(a,t){return!!((t==="v4"||!t)&&Ci.test(a)||(t==="v6"||!t)&&wi.test(a))}function Pi(a,t){if(!gi.test(a))return!1;try{const[e]=a.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Ei(a,t){return!!((t==="v4"||!t)&&ki.test(a)||(t==="v6"||!t)&&bi.test(a))}class U extends b{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==f.string){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.string,received:n.parsedType}),C}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const r=t.data.length>n.value,o=t.data.length<n.value;(r||o)&&(s=this._getOrReturnCtx(t,s),r?d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")vi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")te||(te=new RegExp(xi,"u")),te.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")pi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")mi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")ui.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")di.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")fi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),d(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?Oi(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?Ti.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?Ii(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?yi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Ai(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?Pi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?Ei(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?_i.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?Si.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...m.errToObj(i)})}_addCheck(t){return new U({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...m.errToObj(t)})}url(t){return this._addCheck({kind:"url",...m.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...m.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...m.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...m.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...m.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...m.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...m.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...m.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...m.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...m.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...m.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...m.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...m.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...m.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...m.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...m.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...m.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...m.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...m.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...m.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...m.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...m.errToObj(e)})}nonempty(t){return this.min(1,m.errToObj(t))}trim(){return new U({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new U({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}U.create=a=>{var t;return new U({checks:[],typeName:x.ZodString,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...k(a)})};function Li(a,t){const e=(a.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(a.toFixed(s).replace(".","")),r=parseInt(t.toFixed(s).replace(".",""));return n%r/Math.pow(10,s)}class ut extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==f.number){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.number,received:n.parsedType}),C}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?Li(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,m.toString(e))}gt(t,e){return this.setLimit("min",t,!1,m.toString(e))}lte(t,e){return this.setLimit("max",t,!0,m.toString(e))}lt(t,e){return this.setLimit("max",t,!1,m.toString(e))}setLimit(t,e,i,s){return new ut({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:m.toString(s)}]})}_addCheck(t){return new ut({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:m.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:m.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:m.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}ut.create=a=>new ut({checks:[],typeName:x.ZodNumber,coerce:a?.coerce||!1,...k(a)});class dt extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==f.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.bigint,received:e.parsedType}),C}gte(t,e){return this.setLimit("min",t,!0,m.toString(e))}gt(t,e){return this.setLimit("min",t,!1,m.toString(e))}lte(t,e){return this.setLimit("max",t,!0,m.toString(e))}lt(t,e){return this.setLimit("max",t,!1,m.toString(e))}setLimit(t,e,i,s){return new dt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:m.toString(s)}]})}_addCheck(t){return new dt({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:m.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}dt.create=a=>{var t;return new dt({checks:[],typeName:x.ZodBigInt,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...k(a)})};class ee extends b{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==f.boolean){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.boolean,received:i.parsedType}),C}return z(t.data)}}ee.create=a=>new ee({typeName:x.ZodBoolean,coerce:a?.coerce||!1,...k(a)});class _t extends b{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==f.date){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.date,received:n.parsedType}),C}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_date}),C}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new _t({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:m.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:m.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}_t.create=a=>new _t({checks:[],coerce:a?.coerce||!1,typeName:x.ZodDate,...k(a)});class ie extends b{_parse(t){if(this._getType(t)!==f.symbol){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.symbol,received:i.parsedType}),C}return z(t.data)}}ie.create=a=>new ie({typeName:x.ZodSymbol,...k(a)});class Rt extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.undefined,received:i.parsedType}),C}return z(t.data)}}Rt.create=a=>new Rt({typeName:x.ZodUndefined,...k(a)});class zt extends b{_parse(t){if(this._getType(t)!==f.null){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.null,received:i.parsedType}),C}return z(t.data)}}zt.create=a=>new zt({typeName:x.ZodNull,...k(a)});class se extends b{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}se.create=a=>new se({typeName:x.ZodAny,...k(a)});class ft extends b{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}ft.create=a=>new ft({typeName:x.ZodUnknown,...k(a)});class tt extends b{_parse(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.never,received:e.parsedType}),C}}tt.create=a=>new tt({typeName:x.ZodNever,...k(a)});class ne extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.void,received:i.parsedType}),C}return z(t.data)}}ne.create=a=>new ne({typeName:x.ZodVoid,...k(a)});class j extends b{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==f.array)return d(e,{code:u.invalid_type,expected:f.array,received:e.parsedType}),C;if(s.exactLength!==null){const r=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(r||o)&&(d(e,{code:r?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:r?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(d(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(d(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((r,o)=>s.type._parseAsync(new Z(e,r,e.path,o)))).then(r=>L.mergeArray(i,r));const n=[...e.data].map((r,o)=>s.type._parseSync(new Z(e,r,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new j({...this._def,minLength:{value:t,message:m.toString(e)}})}max(t,e){return new j({...this._def,maxLength:{value:t,message:m.toString(e)}})}length(t,e){return new j({...this._def,exactLength:{value:t,message:m.toString(e)}})}nonempty(t){return this.min(1,t)}}j.create=(a,t)=>new j({type:a,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...k(t)});function pt(a){if(a instanceof A){const t={};for(const e in a.shape){const i=a.shape[e];t[e]=Y.create(pt(i))}return new A({...a._def,shape:()=>t})}else return a instanceof j?new j({...a._def,type:pt(a.element)}):a instanceof Y?Y.create(pt(a.unwrap())):a instanceof at?at.create(pt(a.unwrap())):a instanceof W?W.create(a.items.map(t=>pt(t))):a}class A extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==f.object){const c=this._getOrReturnCtx(t);return d(c,{code:u.invalid_type,expected:f.object,received:c.parsedType}),C}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(const c in s.data)r.includes(c)||o.push(c);const h=[];for(const c of r){const l=n[c],g=s.data[c];h.push({key:{status:"valid",value:c},value:l._parse(new Z(s,g,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof tt){const c=this._def.unknownKeys;if(c==="passthrough")for(const l of o)h.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(c==="strict")o.length>0&&(d(s,{code:u.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 l of o){const g=s.data[l];h.push({key:{status:"valid",value:l},value:c._parse(new Z(s,g,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const l of h){const g=await l.key,p=await l.value;c.push({key:g,value:p,alwaysSet:l.alwaysSet})}return c}).then(c=>L.mergeObjectSync(i,c)):L.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(t){return m.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,r,o;const h=(r=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&r!==void 0?r:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=m.errToObj(t).message)!==null&&o!==void 0?o:h}:{message:h}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return pt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof Y;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return _e(S.objectKeys(this.shape))}}A.create=(a,t)=>new A({shape:()=>a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...k(t)}),A.strictCreate=(a,t)=>new A({shape:()=>a,unknownKeys:"strict",catchall:tt.create(),typeName:x.ZodObject,...k(t)}),A.lazycreate=(a,t)=>new A({shape:a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...k(t)});class Dt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(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 e.common.issues.push(...o.ctx.common.issues),o.result;const r=n.map(o=>new H(o.ctx.common.issues));return d(e,{code:u.invalid_union,unionErrors:r}),C}if(e.common.async)return Promise.all(i.map(async n=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(s);{let n;const r=[];for(const h of i){const c={...e,common:{...e.common,issues:[]},parent:null},l=h._parseSync({data:e.data,path:e.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!n&&(n={result:l,ctx:c}),c.common.issues.length&&r.push(c.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=r.map(h=>new H(h));return d(e,{code:u.invalid_union,unionErrors:o}),C}}get options(){return this._def.options}}Dt.create=(a,t)=>new Dt({options:a,typeName:x.ZodUnion,...k(t)});const $=a=>a instanceof Ht?$(a.schema):a instanceof X?$(a.innerType()):a instanceof Nt?[a.value]:a instanceof nt?a.options:a instanceof Bt?S.objectValues(a.enum):a instanceof Vt?$(a._def.innerType):a instanceof Rt?[void 0]:a instanceof zt?[null]:a instanceof Y?[void 0,...$(a.unwrap())]:a instanceof at?[null,...$(a.unwrap())]:a instanceof Se||a instanceof jt?$(a.unwrap()):a instanceof Kt?$(a._def.innerType):[];class ae extends b{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.object)return d(e,{code:u.invalid_type,expected:f.object,received:e.parsedType}),C;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(d(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),C)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const r=$(n.shape[t]);if(!r.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of r){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new ae({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...k(i)})}}function re(a,t){const e=J(a),i=J(t);if(a===t)return{valid:!0,data:a};if(e===f.object&&i===f.object){const s=S.objectKeys(t),n=S.objectKeys(a).filter(o=>s.indexOf(o)!==-1),r={...a,...t};for(const o of n){const h=re(a[o],t[o]);if(!h.valid)return{valid:!1};r[o]=h.data}return{valid:!0,data:r}}else if(e===f.array&&i===f.array){if(a.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<a.length;n++){const r=a[n],o=t[n],h=re(r,o);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return e===f.date&&i===f.date&&+a==+t?{valid:!0,data:a}:{valid:!1}}class Ft extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,r)=>{if(ve(n)||ve(r))return C;const o=re(n.value,r.value);return o.valid?((xe(n)||xe(r))&&e.dirty(),{status:e.value,value:o.data}):(d(i,{code:u.invalid_intersection_types}),C)};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,r])=>s(n,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ft.create=(a,t,e)=>new Ft({left:a,right:t,typeName:x.ZodIntersection,...k(e)});class W extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.array)return d(i,{code:u.invalid_type,expected:f.array,received:i.parsedType}),C;if(i.data.length<this._def.items.length)return d(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;!this._def.rest&&i.data.length>this._def.items.length&&(d(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((r,o)=>{const h=this._def.items[o]||this._def.rest;return h?h._parse(new Z(i,r,i.path,o)):null}).filter(r=>!!r);return i.common.async?Promise.all(n).then(r=>L.mergeArray(e,r)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new W({...this._def,rest:t})}}W.create=(a,t)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W({items:a,typeName:x.ZodTuple,rest:null,...k(t)})};class Mt extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.object)return d(i,{code:u.invalid_type,expected:f.object,received:i.parsedType}),C;const s=[],n=this._def.keyType,r=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new Z(i,o,i.path,o)),value:r._parse(new Z(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof b?new Mt({keyType:t,valueType:e,typeName:x.ZodRecord,...k(i)}):new Mt({keyType:U.create(),valueType:t,typeName:x.ZodRecord,...k(e)})}}class oe extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.map)return d(i,{code:u.invalid_type,expected:f.map,received:i.parsedType}),C;const s=this._def.keyType,n=this._def.valueType,r=[...i.data.entries()].map(([o,h],c)=>({key:s._parse(new Z(i,o,i.path,[c,"key"])),value:n._parse(new Z(i,h,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const h of r){const c=await h.key,l=await h.value;if(c.status==="aborted"||l.status==="aborted")return C;(c.status==="dirty"||l.status==="dirty")&&e.dirty(),o.set(c.value,l.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const h of r){const c=h.key,l=h.value;if(c.status==="aborted"||l.status==="aborted")return C;(c.status==="dirty"||l.status==="dirty")&&e.dirty(),o.set(c.value,l.value)}return{status:e.value,value:o}}}}oe.create=(a,t,e)=>new oe({valueType:t,keyType:a,typeName:x.ZodMap,...k(e)});class mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.set)return d(i,{code:u.invalid_type,expected:f.set,received:i.parsedType}),C;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(d(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(d(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function r(h){const c=new Set;for(const l of h){if(l.status==="aborted")return C;l.status==="dirty"&&e.dirty(),c.add(l.value)}return{status:e.value,value:c}}const o=[...i.data.values()].map((h,c)=>n._parse(new Z(i,h,i.path,c)));return i.common.async?Promise.all(o).then(h=>r(h)):r(o)}min(t,e){return new mt({...this._def,minSize:{value:t,message:m.toString(e)}})}max(t,e){return new mt({...this._def,maxSize:{value:t,message:m.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}mt.create=(a,t)=>new mt({valueType:a,minSize:null,maxSize:null,typeName:x.ZodSet,...k(t)});class St extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.function)return d(e,{code:u.invalid_type,expected:f.function,received:e.parsedType}),C;function i(o,h){return Jt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Qt(),Ct].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:h}})}function s(o,h){return Jt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Qt(),Ct].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:h}})}const n={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof Tt){const o=this;return z(async function(...h){const c=new H([]),l=await o._def.args.parseAsync(h,n).catch(w=>{throw c.addIssue(i(h,w)),c}),g=await Reflect.apply(r,this,l);return await o._def.returns._def.type.parseAsync(g,n).catch(w=>{throw c.addIssue(s(g,w)),c})})}else{const o=this;return z(function(...h){const c=o._def.args.safeParse(h,n);if(!c.success)throw new H([i(h,c.error)]);const l=Reflect.apply(r,this,c.data),g=o._def.returns.safeParse(l,n);if(!g.success)throw new H([s(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new St({...this._def,args:W.create(t).rest(ft.create())})}returns(t){return new St({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new St({args:t||W.create([]).rest(ft.create()),returns:e||ft.create(),typeName:x.ZodFunction,...k(i)})}}class Ht extends b{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Ht.create=(a,t)=>new Ht({getter:a,typeName:x.ZodLazy,...k(t)});class Nt extends b{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return d(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:t.data}}get value(){return this._def.value}}Nt.create=(a,t)=>new Nt({value:a,typeName:x.ZodLiteral,...k(t)});function _e(a,t){return new nt({values:a,typeName:x.ZodEnum,...k(t)})}class nt extends b{constructor(){super(...arguments),wt.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),C}if(Lt(this,wt)||Ce(this,wt,new Set(this._def.values)),!Lt(this,wt).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{received:e.data,code:u.invalid_enum_value,options:i}),C}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return nt.create(t,{...this._def,...e})}exclude(t,e=this._def){return nt.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}wt=new WeakMap,nt.create=_e;class Bt extends b{constructor(){super(...arguments),bt.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==f.string&&i.parsedType!==f.number){const s=S.objectValues(e);return d(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),C}if(Lt(this,bt)||Ce(this,bt,new Set(S.getValidEnumValues(this._def.values))),!Lt(this,bt).has(t.data)){const s=S.objectValues(e);return d(i,{received:i.data,code:u.invalid_enum_value,options:s}),C}return z(t.data)}get enum(){return this._def.values}}bt=new WeakMap,Bt.create=(a,t)=>new Bt({values:a,typeName:x.ZodNativeEnum,...k(t)});class Tt extends b{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.promise&&e.common.async===!1)return d(e,{code:u.invalid_type,expected:f.promise,received:e.parsedType}),C;const i=e.parsedType===f.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Tt.create=(a,t)=>new Tt({type:a,typeName:x.ZodPromise,...k(t)});class X extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:r=>{d(i,r),r.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const r=s.transform(i.data,n);if(i.common.async)return Promise.resolve(r).then(async o=>{if(e.value==="aborted")return C;const h=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return h.status==="aborted"?C:h.status==="dirty"||e.value==="dirty"?kt(h.value):h});{if(e.value==="aborted")return C;const o=this._def.schema._parseSync({data:r,path:i.path,parent:i});return o.status==="aborted"?C:o.status==="dirty"||e.value==="dirty"?kt(o.value):o}}if(s.type==="refinement"){const r=o=>{const h=s.refinement(o,n);if(i.common.async)return Promise.resolve(h);if(h 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"?C:(o.status==="dirty"&&e.dirty(),r(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?C:(o.status==="dirty"&&e.dirty(),r(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const r=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ht(r))return r;const o=s.transform(r.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(r=>ht(r)?Promise.resolve(s.transform(r.value,n)).then(o=>({status:e.value,value:o})):r);S.assertNever(s)}}X.create=(a,t,e)=>new X({schema:a,typeName:x.ZodEffects,effect:t,...k(e)}),X.createWithPreprocess=(a,t,e)=>new X({schema:t,effect:{type:"preprocess",transform:a},typeName:x.ZodEffects,...k(e)});class Y extends b{_parse(t){return this._getType(t)===f.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Y.create=(a,t)=>new Y({innerType:a,typeName:x.ZodOptional,...k(t)});class at extends b{_parse(t){return this._getType(t)===f.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}at.create=(a,t)=>new at({innerType:a,typeName:x.ZodNullable,...k(t)});class Vt extends b{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===f.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}Vt.create=(a,t)=>new Vt({innerType:a,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...k(t)});class Kt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Et(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new H(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new H(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Kt.create=(a,t)=>new Kt({innerType:a,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...k(t)});class ce extends b{_parse(t){if(this._getType(t)!==f.nan){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.nan,received:i.parsedType}),C}return{status:"valid",value:t.data}}}ce.create=a=>new ce({typeName:x.ZodNaN,...k(a)});class Se extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Zt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);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"?C:n.status==="dirty"?(e.dirty(),kt(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?C:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Zt({in:t,out:e,typeName:x.ZodPipeline})}}class jt extends b{_parse(t){const e=this._def.innerType._parse(t),i=s=>(ht(s)&&(s.value=Object.freeze(s.value)),s);return Et(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}jt.create=(a,t)=>new jt({innerType:a,typeName:x.ZodReadonly,...k(t)}),A.lazycreate;var x;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(x||(x={}));const R=U.create,v=ut.create;ce.create,dt.create,ee.create,_t.create,ie.create,Rt.create,zt.create,se.create,ft.create,tt.create,ne.create,j.create;const T=A.create;A.strictCreate;const Ri=Dt.create;ae.create,Ft.create,W.create,Mt.create,oe.create,mt.create,St.create,Ht.create;const rt=Nt.create,et=nt.create;Bt.create,Tt.create,X.create,Y.create,at.create,X.createWithPreprocess,Zt.create;const zi=et(["linear","bezier","constant"]),Di=et(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),ot=T({from:v(),to:v(),start:v().min(0),length:v().positive(),interpolation:zi.optional(),easing:Di.optional()}),Fi=R().url("Invalid audio url format."),Mi=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Te=T({type:rt("audio"),src:Fi,trim:v().optional(),volume:Mi.optional()}),Hi=et(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ie=T({type:rt("html"),html:R(),css:R(),width:v().positive().optional(),height:v().positive().optional(),position:Hi.optional()}),Ni=R().url("Invalid image url format."),Bi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Oe=T({type:rt("image"),src:Ni,crop:Bi.optional()}),Vi=R().url("Invalid luma url format."),Ae=T({type:rt("luma"),src:Vi}),Pe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ee=T({width:v().positive(),height:v().positive()}),Le=T({radius:v().positive()}),Re=T({length:v().positive(),thickness:v().positive()}),Ki=T({color:Pe,opacity:v().min(0).max(1)}),Zi=T({color:Pe,width:v().positive()}),ze=T({type:rt("shape"),width:v().positive().optional(),height:v().positive().optional(),shape:et(["rectangle","circle","line"]),fill:Ki.optional(),stroke:Zi.optional(),rectangle:Ee.optional(),circle:Le.optional(),line:Re.optional()}).refine(a=>a.shape==="rectangle"?Ee.safeParse(a.rectangle):a.shape==="circle"?Le.safeParse(a.circle):a.shape==="line"?Re.safeParse(a.line):!1),le=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),ji=T({color:le.optional(),family:R().optional(),size:v().positive().optional(),weight:v().optional(),lineHeight:v().optional()}),Ui=T({horizontal:et(["left","center","right"]).optional(),vertical:et(["top","center","bottom"]).optional()}),$i=T({color:le,opacity:v().min(0).max(1)}),Wi=T({width:v().positive(),color:le}),De=T({type:rt("text"),text:R(),width:v().positive().optional(),height:v().positive().optional(),font:ji.optional(),alignment:Ui.optional(),background:$i.optional(),stroke:Wi.optional()}),Xi=R().url("Invalid video url format."),Yi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Gi=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Fe=T({type:rt("video"),src:Xi,trim:v().optional(),crop:Yi.optional(),volume:Gi.optional()}),qi=Ri([De,ze,Ie,Oe,Fe,Ae,Te]).refine(a=>a.type==="text"?De.safeParse(a):a.type==="shape"?ze.safeParse(a):a.type==="html"?Ie.safeParse(a):a.type==="image"?Oe.safeParse(a):a.type==="video"?Fe.safeParse(a):a.type==="luma"?Ae.safeParse(a):a.type==="audio"?Te.safeParse(a):!1),Qi=et(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Ji=et(["crop","cover","contain","none"]),gt=v().min(-10).max(10).default(0),ts=ot.extend({from:gt,to:gt}).array().or(gt),es=ot.extend({from:gt,to:gt}).array().or(gt),is=T({x:ts.default(0),y:es.default(0)}),ss=ot.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),ns=ot.extend({from:v().min(0),to:v().min(0)}).array().or(v().min(0)),as=T({angle:ot.extend({from:v(),to:v()}).array().or(v())}),rs=R(),Me=R(),os=T({in:Me.optional(),out:Me.optional()}),cs=T({rotate:as.default({angle:0})}),He=T({asset:qi,start:v().min(0),length:v().positive(),position:Qi.default("center").optional(),fit:Ji.default("crop").optional(),offset:is.default({x:0,y:0}).optional(),opacity:ss.default(1).optional(),scale:ns.default(1).optional(),transform:cs.default({rotate:{angle:0}}).optional(),effect:rs.optional(),transition:os.optional()});class ls{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(!t)return;const e=He.parse(this.clip),i=t.createPlayerFromAssetType(e);i.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,i),t.updateDuration(),this.addedPlayer=i}async undo(t){!t||!this.addedPlayer||(t.queueDisposeClip(this.addedPlayer),t.updateDuration())}}class hs{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]);const s=i.filter(r=>r.layer>=this.trackIdx+1),n=t.getContainer();i.forEach((r,o)=>{r.layer>=this.trackIdx+1&&(n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),i[o].layer+=1)}),s.forEach(r=>{const o=1e5-r.layer*100;let h=n.getChildByLabel(`shotstack-track-${o}`,!1);h||(h=new y.Container({label:`shotstack-track-${o}`,zIndex:o}),n.addChild(h)),h.addChild(r.getContainer())}),t.updateDuration()}undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,1),i.forEach((s,n)=>{s.layer>this.trackIdx+1&&(i[n].layer-=1)}),t.updateDuration()}}class us{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;execute(t){if(!t)return;const i=t.getClips().filter(s=>s.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(t.queueDisposeClip(this.deletedClip),t.updateDuration())}undo(t){!t||!this.deletedClip||t.undeleteClip(this.trackIdx,this.deletedClip)}}class ds{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(r=>r.layer===this.trackIdx+1).map(r=>({config:structuredClone(r.clipConfiguration)})),e.forEach((r,o)=>{r.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const s=t.getClips(),n=t.getContainer();s.forEach((r,o)=>{if(r.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),s[o].layer-=1;const c=1e5-s[o].layer*100;let l=n.getChildByLabel(`shotstack-track-${c}`,!1);l||(l=new y.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(l)),l.addChild(s[o].getContainer())}}),t.updateDuration()}async undo(t){if(!t||this.deletedClips.length===0)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((s,n)=>{s.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:s}of this.deletedClips){const n=t.createPlayerFromAssetType(s);n.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,n)}t.updateDuration()}}class fs{constructor(t,e,i){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(t){if(!t)return;this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(r=>r.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:e,clipIndex:n}})}undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(r=>r.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class ps{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:s}=this.clip.clipConfiguration;this.previousText=s&&"text"in s?s.text:""}name="updateTextContent";previousText;execute(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const e=this.clip.text;e&&(e.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:r},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r}})}}undo(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const e=this.clip.text;e&&(e.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r},current:{clip:this.initialConfig,trackIndex:i,clipIndex:r}})}}}class Ne{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,e){if(this.events[t])for(const i of this.events[t])i(e)}}class ms extends Ne{registry;constructor(){super(),this.registry={}}}class Ut{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new ms;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await y.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return Ut.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),s=Ut.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),s=typeof e=="object"?e.data??{}:{},n=await new Promise((r,o)=>{const h=document.createElement("video");h.crossOrigin="anonymous",h.playsInline=!0,h.muted=!0,h.preload="metadata",h.addEventListener("loadedmetadata",()=>{try{const c=new y.VideoSource({resource:h,autoPlay:s.autoPlay??!1,...s});r(new y.Texture({source:c}))}catch(c){o(c)}},{once:!0}),h.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),h.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class $t{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=$t.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(p=>p.arrayBuffer());if(s!=="woff2"){const p=me.parse(new Uint8Array(n).buffer),w=p.names.fontFamily.en||p.names.fontFamily[Object.keys(p.names.fontFamily)[0]],I=new FontFace(w,`url(${t})`);return await I.load(),document.fonts.add(I),I}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=me.parse(new Uint8Array(r).buffer),h=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([r],{type:"font/ttf"}),l=URL.createObjectURL(c),g=new FontFace(h,`url(${l})`);return await g.load(),document.fonts.add(g),g}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}const gs=T({clips:He.array()}),ys=R().url("Invalid image url format."),vs=T({src:ys}),xs=T({background:R().optional(),fonts:vs.array().optional(),tracks:gs.array()}),Cs=T({size:T({width:v().positive(),height:v().positive()}),fps:v().positive().optional(),format:R()}),ks=T({timeline:xs,output:Cs});class he extends Yt{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;constructor(t,e="#ffffff"){super(),this.assetLoader=new Ut,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new Ne,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e}async load(){const t=new y.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){this.clearClips()}play(){this.isPlaying=!0}pause(){this.isPlaying=!1}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=ks.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:$t.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=[],e=new Map;for(const s of this.clips)e.has(s.layer)||e.set(s.layer,{clips:[]}),e.get(s.layer).clips.push(s.clipConfiguration);const i=Math.max(...e.keys(),0);for(let s=1;s<=i;s+=1)t[s-1]=e.get(s)||{clips:[]};return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=new ls(t,e);this.executeCommand(i)}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}deleteClip(t,e){const i=new us(t,e);this.executeCommand(i)}addTrack(t,e){const i=new hs(t);this.executeCommand(i),e?.clips?.forEach(s=>this.addClip(t,s))}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=new ds(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}undo(){if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const e=this.createCommandContext();t.undo(e),this.commandIndex-=1,this.events.emit("edit:undo",{command:t.name})}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const t=this.commandHistory[this.commandIndex],e=this.createCommandContext();t.execute(e),this.events.emit("edit:redo",{command:t.name})}}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t;const e=t.layer-1,s=this.clips.filter(r=>r.layer===t.layer).indexOf(t),n={clip:t.clipConfiguration,trackIndex:e,clipIndex:s};this.events.emit("clip:selected",n)}setUpdatedClip(t,e=null,i=null){const s=new fs(t,e,i);this.executeCommand(s)}updateTextContent(t,e,i){const s=new ps(t,e,i);this.executeCommand(s)}executeCommand(t){const e=this.createCommandContext(),i=t.execute(e);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1,i}createCommandContext(){return{getClips:()=>[...this.clips],getTracks:()=>this.tracks,getContainer:()=>this.getContainer(),addPlayer:(t,e)=>this.addPlayer(t,e),createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),undeleteClip:(t,e)=>{this.clips.push(e),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{Object.assign(t.clipConfiguration,structuredClone(e)),t.reconfigureAfterRestore(),t.draw()},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,e)=>this.events.emit(t,e)}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof y.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch{console.warn("Attempting to unmount an unmounted clip.")}this.unloadClipAssets(t),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{y.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const e of this.tracks)for(const i of e)t=Math.max(t,i.getEnd());this.totalDuration=t}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new ci(this,t);break}case"shape":{e=new oi(this,t);break}case"html":{e=new ai(this,t);break}case"image":{e=new ri(this,t);break}case"video":{e=new li(this,t);break}case"audio":{e=new Gt(this,t);break}case"luma":{e=new ge(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*he.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new y.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const r=e instanceof ge;await e.load(),r&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}}class It extends Yt{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new y.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,It.Width,It.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new y.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:It.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
|
|
185
|
+
`)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class ct{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new y.Application,this.edit=e,this.inspector=new It}async load(){const t=document.querySelector(ct.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${ct.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new y.Container,this.background=new y.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,r=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},h={x:e.position.x-o.x,y:e.position.y-o.y},c=this.currentZoom/r;e.position.x=o.x+h.x*c,e.position.y=o.y+h.y*c,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerExtensions(){ct.extensionsRegistered||(y.extensions.add(new Ot),y.extensions.add(new $t),ct.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw()}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new y.Rectangle(0,0,this.size.width,this.size.height),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}dispose(){const t=document.querySelector(ct.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class ws{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}case"KeyZ":{(t.metaKey||t.ctrlKey)&&(t.preventDefault(),t.shiftKey?this.edit.redo():this.edit.undo());break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class bs{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new $e.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),r=n.visible,{x:o,y:h}=n.position,{x:c,y:l}=n.scale;n.visible=!1;const g=this.createProgressOverlay();try{const p=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},w=Math.ceil(this.edit.totalDuration*e/1e3),I=1e3/e,_=100,D=50,N=50,yt=O=>Math.round(O/w*D);this.updateProgressOverlay(g,0,_);const G=document.createElement("canvas");G.width=p.width,G.height=p.height;const vt=G.getContext("2d");if(!vt)throw new Error("Could not get 2D context for canvas");const ue=this.findAudioPlayers();this.updateProgressOverlay(g,2,_);const q=[];if(ue.length>0){this.updateProgressOverlay(g,3,_);for(let O=0;O<ue.length;O+=1){const B=await this.processAudioTrack(ue[O],O);B&&q.push(B),this.updateProgressOverlay(g,4+O,_)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let O=0;O<w;O+=1){this.edit.seek(O*I),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:B}=this.application.renderer,F=B.canvas(n);vt.clearRect(0,0,G.width,G.height),vt.drawImage(F,0,0);const Q=G.toDataURL("image/png"),Wt=await(await fetch(Q)).arrayBuffer(),Ts=`frame_${O.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(Ts,new Uint8Array(Wt))}catch(B){console.error(`Error capturing frame ${O}:`,B)}this.updateProgressOverlay(g,yt(O+1),_)}this.updateProgressOverlay(g,D,_);let it=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const O of q)it=it.concat(["-i",O.filename]);if(it=it.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),q.length>0){let O="";for(let F=0;F<q.length;F+=1){const Q=q[F],Ze=F+1,Wt=Math.max(0,Q.start);O+=`[${Ze}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${Q.duration/1e3+.1},adelay=${Wt}|${Wt},volume=${Q.volume}[a${F}];`}const B=q.length>1?`${q.map((F,Q)=>`[a${Q}]`).join("")}amix=inputs=${q.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";O+=B,it=it.concat(["-filter_complex",O,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const de="output.mp4";it.push(de);let Be=0;const Ve=({message:O})=>{const B=O.includes("frame=")&&O.includes("fps=")?O.match(/frame=\s*(\d+)/):null;if(B?.[1]){const F=parseInt(B[1],10);if(!Number.isNaN(F)&&F>Be&&(Be=F,F<=w)){const Q=Math.round(F/w*N);this.updateProgressOverlay(g,D+Q,_)}}};this.ffmpeg.on("log",Ve),await this.ffmpeg.exec(it),this.ffmpeg.off("log",Ve),this.updateProgressOverlay(g,D+N,_);const fe=await this.ffmpeg.readFile(de),_s=fe instanceof Uint8Array?fe:new TextEncoder().encode(fe.toString()),Ss=new Blob([_s],{type:"video/mp4"}),Ke=URL.createObjectURL(Ss),pe=document.createElement("a");pe.href=Ke,pe.download=t,pe.click(),URL.revokeObjectURL(Ke);for(let O=0;O<w;O+=1)try{await this.ffmpeg.deleteFile(`frame_${O.toString().padStart(6,"0")}.png`)}catch{}for(const O of q)try{await this.ffmpeg.deleteFile(O.filename)}catch{}await this.ffmpeg.deleteFile(de),this.updateProgressOverlay(g,_,_)}catch(p){throw console.error("Error during export:",p),p}finally{this.removeProgressOverlay(g),n.position.x=o,n.position.y=h,n.scale.x=c,n.scale.y=l,n.visible=r,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const r=s[n];(r instanceof Gt||r.constructor.name==="AudioPlayer"||r.clipConfiguration?.asset?.type==="audio")&&(t.includes(r)||t.push(r))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof y.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof y.Container){const r=n,o=["player","clip","audioPlayer","entity"];for(const h of o){const c=r[h];c instanceof Gt&&!e.includes(c)&&e.push(c)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const r=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(r)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const r=document.createElement("div");return r.className="video-export-percent",r.innerText="0%",r.style.fontSize="12px",e.appendChild(r),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),r=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),r&&(r.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}M.Canvas=ct,M.Controls=ws,M.Edit=he,M.VideoExporter=bs,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});
|