UNPKG

@imgly/plugin-ai-video-generation-web

Version:

AI video generation plugin for the CE.SDK editor

39 lines (36 loc) 75.8 kB
var Kt=class{constructor(e,t,r){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=r?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=r?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{t(new Error(`Failed to open IndexedDB: ${i.target.error}`))},r.onupgradeneeded=i=>{let n=i.target.result;n.objectStoreNames.contains(this.assetStoreName)||n.createObjectStore(this.assetStoreName,{keyPath:"id"}),n.objectStoreNames.contains(this.blobStoreName)||n.createObjectStore(this.blobStoreName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,e()}})}close(){this.db&&(this.db.close(),this.db=null)}async findAssets(e){if(await this.initialize(),!this.db)throw new Error("Database not initialized");try{let t=(await this.getAllAssets("asc")).reduce((u,l)=>{let c=e.locale??"en",d="",p=[];l.label!=null&&typeof l.label=="object"&&l.label[c]&&(d=l.label[c]),l.tags!=null&&typeof l.tags=="object"&&l.tags[c]&&(p=l.tags[c]);let g={...l,label:d,tags:p};return this.filterAsset(g,e)&&u.push(g),u},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:r,perPage:i}=e,n=r*i,o=n+i,a=t.slice(n,o),s=o<t.length?r+1:void 0;return{assets:a,currentPage:r,nextPage:s,total:t.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){if(await this.initialize(),!this.db)throw new Error("Database not initialized");return new Promise((e,t)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=new Set;r.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>i.add(a))});let n=[...i];e(n)},r.onerror=()=>{t(new Error(`Failed to get groups: ${r.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),r=t.objectStore(this.assetStoreName),i=new Set;O(e,o=>{i.add(o)}),setTimeout(()=>{this.storeBlobUrls([...i])});let n={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};r.put(n),t.onerror=()=>{console.error(`Failed to add asset: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async removeAsset(e){let t=await this.getAsset(e);return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.assetStoreName,"readwrite");r.objectStore(this.assetStoreName).delete(e),r.oncomplete=()=>{O(t,i=>{this.removeBlob(i)}),this.engine.asset.assetSourceContentsChanged(this.id)},r.onerror=()=>{console.error(`Failed to remove asset: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async removeBlob(e){return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.blobStoreName,"readwrite");t.objectStore(this.blobStoreName).delete(e),t.onerror=()=>{console.error(`Failed to remove blob: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async getAllAssets(e="desc"){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let n=i.result;n.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),u=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-u:u-s}),t(n)},i.onerror=()=>{r(new Error(`Failed to get assets: ${i.error}`))}})}async getAsset(e){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async getBlob(e){return new Promise((t,r)=>{let i=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async createBlobUrlFromStore(e){let t=await this.getBlob(e);return t!=null?URL.createObjectURL(t.blob):e}async storeBlobUrls(e){let t={};return await Promise.all(e.map(async r=>{let i=await(await fetch(r)).blob();t[r]=i})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.blobStoreName,"readwrite"),i=r.objectStore(this.blobStoreName);Object.entries(t).forEach(([n,o])=>{let a={id:n,blob:o};i.put(a)}),r.onerror=()=>{console.error(`Failed to add blobs: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async restoreBlobUrls(e){let t={},r=new Set;return O(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),O(e,i=>t[i]??i)}filterAsset(e,t){let{query:r,tags:i,groups:n,excludeGroups:o}=t;if(r&&r.trim()!==""){let a=r.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",u=e.tags?.map(l=>l.toLowerCase())??[];if(!a.every(l=>s.includes(l)||u.some(c=>c.includes(l))))return!1}if(i){let a=Array.isArray(i)?i:[i];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(n&&n.length>0&&(!e.groups||!n.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:r,sortKey:i,sortActiveFirst:n}=t,o=[...e];return!r||r==="None"||(i?o.sort((a,s)=>{let u,l;return i==="id"?(u=a.id,l=s.id):(u=a.meta?.[i]??null,l=s.meta?.[i]??null),u==null?r==="Ascending"?-1:1:l==null?r==="Ascending"?1:-1:typeof u=="string"&&typeof l=="string"?r==="Ascending"?u.localeCompare(l):l.localeCompare(u):r==="Ascending"?u<l?-1:u>l?1:0:u>l?-1:u<l?1:0}):r==="Descending"&&o.reverse(),n&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function O(e,t,r=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=r?`${r}[${i}]`:`[${i}]`;if(typeof e[i]=="string"&&e[i].startsWith("blob:")){let o=t(e[i],n);typeof o=="string"&&(e[i]=o)}else e[i]=O(e[i],t,n)}return e}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],o=r?`${r}.${i}`:i;if(typeof n=="string"&&n.startsWith("blob:")){let a=t(n,o);typeof a=="string"&&(e[i]=a)}else e[i]=O(n,t,o)}return e}var Jt=class{constructor(e,t,r){this.id=e,this.cesdk=t,this.assetSourceIds=r}async findAssets(e){try{let t=this.assetSourceIds.map(c=>this.cesdk.engine.asset.findAssets(c,{...e,perPage:9999,page:0})),r=await Promise.all(t),i=[];r.forEach(c=>{c?.assets&&(i=i.concat(c.assets))}),i.sort((c,d)=>{let p=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:n,perPage:o}=e,a=n*o,s=a+o,u=i.slice(a,s),l=s<i.length?n+1:void 0;return{assets:u,currentPage:n,nextPage:l,total:i.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){let e=this.assetSourceIds.map(i=>this.cesdk.engine.asset.getGroups(i)),t=await Promise.all(e),r=new Set;return t.forEach(i=>{i.forEach(n=>r.add(n))}),Array.from(r)}addAsset(e){throw new Error("AggregatedAssetSource does not support adding assets")}removeAsset(e){throw new Error("AggregatedAssetSource does not support removing assets")}};var Xt=typeof global=="object"&&global&&global.Object===Object&&global,Xe=Xt,er=typeof self=="object"&&self&&self.Object===Object&&self,tr=Xe||er||Function("return this")(),A=tr,rr=A.Symbol,P=rr,et=Object.prototype,ir=et.hasOwnProperty,nr=et.toString,H=P?P.toStringTag:void 0;function or(e){var t=ir.call(e,H),r=e[H];try{e[H]=void 0;var i=!0}catch{}var n=nr.call(e);return i&&(t?e[H]=r:delete e[H]),n}var ar=or,sr=Object.prototype,lr=sr.toString;function ur(e){return lr.call(e)}var cr=ur,dr="[object Null]",pr="[object Undefined]",Te=P?P.toStringTag:void 0;function gr(e){return e==null?e===void 0?pr:dr:Te&&Te in Object(e)?ar(e):cr(e)}var K=gr;function fr(e){return e!=null&&typeof e=="object"}var Ae=fr,ku=Array.isArray;function hr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var tt=hr,mr="[object AsyncFunction]",br="[object Function]",yr="[object GeneratorFunction]",vr="[object Proxy]";function wr(e){if(!tt(e))return!1;var t=K(e);return t==br||t==yr||t==mr||t==vr}var kr=wr,Ir=A["__core-js_shared__"],ge=Ir,ze=function(){var e=/[^.]+$/.exec(ge&&ge.keys&&ge.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Ar(e){return!!ze&&ze in e}var xr=Ar,Sr=Function.prototype,Cr=Sr.toString;function Er(e){if(e!=null){try{return Cr.call(e)}catch{}try{return e+""}catch{}}return""}var M=Er,Mr=/[\\^$.*+?()[\]{}|]/g,jr=/^\[object .+?Constructor\]$/,_r=Function.prototype,Lr=Object.prototype,Nr=_r.toString,Or=Lr.hasOwnProperty,Pr=RegExp("^"+Nr.call(Or).replace(Mr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function $r(e){if(!tt(e)||xr(e))return!1;var t=kr(e)?Pr:jr;return t.test(M(e))}var Dr=$r;function Tr(e,t){return e?.[t]}var zr=Tr;function Rr(e,t){var r=zr(e,t);return Dr(r)?r:void 0}var $=Rr,Fr=$(A,"WeakMap"),ye=Fr;function Vr(e,t){return e===t||e!==e&&t!==t}var Ur=Vr,Br=9007199254740991;function Gr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Br}var Hr=Gr,Iu=Object.prototype,qr="[object Arguments]";function Zr(e){return Ae(e)&&K(e)==qr}var Re=Zr,rt=Object.prototype,Qr=rt.hasOwnProperty,Yr=rt.propertyIsEnumerable,Au=Re(function(){return arguments}())?Re:function(e){return Ae(e)&&Qr.call(e,"callee")&&!Yr.call(e,"callee")},it=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Fe=it&&typeof module=="object"&&module&&!module.nodeType&&module,Wr=Fe&&Fe.exports===it,Ve=Wr?A.Buffer:void 0,xu=Ve?Ve.isBuffer:void 0,Kr="[object Arguments]",Jr="[object Array]",Xr="[object Boolean]",ei="[object Date]",ti="[object Error]",ri="[object Function]",ii="[object Map]",ni="[object Number]",oi="[object Object]",ai="[object RegExp]",si="[object Set]",li="[object String]",ui="[object WeakMap]",ci="[object ArrayBuffer]",di="[object DataView]",pi="[object Float32Array]",gi="[object Float64Array]",fi="[object Int8Array]",hi="[object Int16Array]",mi="[object Int32Array]",bi="[object Uint8Array]",yi="[object Uint8ClampedArray]",vi="[object Uint16Array]",wi="[object Uint32Array]",v={};v[pi]=v[gi]=v[fi]=v[hi]=v[mi]=v[bi]=v[yi]=v[vi]=v[wi]=!0;v[Kr]=v[Jr]=v[ci]=v[Xr]=v[di]=v[ei]=v[ti]=v[ri]=v[ii]=v[ni]=v[oi]=v[ai]=v[si]=v[li]=v[ui]=!1;function ki(e){return Ae(e)&&Hr(e.length)&&!!v[K(e)]}var Ii=ki;function Ai(e){return function(t){return e(t)}}var xi=Ai,nt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Q=nt&&typeof module=="object"&&module&&!module.nodeType&&module,Si=Q&&Q.exports===nt,fe=Si&&Xe.process,Ci=function(){try{var e=Q&&Q.require&&Q.require("util").types;return e||fe&&fe.binding&&fe.binding("util")}catch{}}(),Ue=Ci,Be=Ue&&Ue.isTypedArray,Su=Be?xi(Be):Ii,Ei=Object.prototype,Cu=Ei.hasOwnProperty;function Mi(e,t){return function(r){return e(t(r))}}var ji=Mi,Eu=ji(Object.keys,Object),_i=Object.prototype,Mu=_i.hasOwnProperty,Li=$(Object,"create"),Y=Li;function Ni(){this.__data__=Y?Y(null):{},this.size=0}var Oi=Ni;function Pi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var $i=Pi,Di="__lodash_hash_undefined__",Ti=Object.prototype,zi=Ti.hasOwnProperty;function Ri(e){var t=this.__data__;if(Y){var r=t[e];return r===Di?void 0:r}return zi.call(t,e)?t[e]:void 0}var Fi=Ri,Vi=Object.prototype,Ui=Vi.hasOwnProperty;function Bi(e){var t=this.__data__;return Y?t[e]!==void 0:Ui.call(t,e)}var Gi=Bi,Hi="__lodash_hash_undefined__";function qi(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Y&&t===void 0?Hi:t,this}var Zi=qi;function D(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}D.prototype.clear=Oi;D.prototype.delete=$i;D.prototype.get=Fi;D.prototype.has=Gi;D.prototype.set=Zi;var Ge=D;function Qi(){this.__data__=[],this.size=0}var Yi=Qi;function Wi(e,t){for(var r=e.length;r--;)if(Ur(e[r][0],t))return r;return-1}var se=Wi,Ki=Array.prototype,Ji=Ki.splice;function Xi(e){var t=this.__data__,r=se(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():Ji.call(t,r,1),--this.size,!0}var en=Xi;function tn(e){var t=this.__data__,r=se(t,e);return r<0?void 0:t[r][1]}var rn=tn;function nn(e){return se(this.__data__,e)>-1}var on=nn;function an(e,t){var r=this.__data__,i=se(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var sn=an;function T(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}T.prototype.clear=Yi;T.prototype.delete=en;T.prototype.get=rn;T.prototype.has=on;T.prototype.set=sn;var le=T,ln=$(A,"Map"),W=ln;function un(){this.size=0,this.__data__={hash:new Ge,map:new(W||le),string:new Ge}}var cn=un;function dn(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var pn=dn;function gn(e,t){var r=e.__data__;return pn(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ue=gn;function fn(e){var t=ue(this,e).delete(e);return this.size-=t?1:0,t}var hn=fn;function mn(e){return ue(this,e).get(e)}var bn=mn;function yn(e){return ue(this,e).has(e)}var vn=yn;function wn(e,t){var r=ue(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var kn=wn;function z(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}z.prototype.clear=cn;z.prototype.delete=hn;z.prototype.get=bn;z.prototype.has=vn;z.prototype.set=kn;var ot=z;function In(){this.__data__=new le,this.size=0}var An=In;function xn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Sn=xn;function Cn(e){return this.__data__.get(e)}var En=Cn;function Mn(e){return this.__data__.has(e)}var jn=Mn,_n=200;function Ln(e,t){var r=this.__data__;if(r instanceof le){var i=r.__data__;if(!W||i.length<_n-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new ot(i)}return r.set(e,t),this.size=r.size,this}var Nn=Ln;function J(e){var t=this.__data__=new le(e);this.size=t.size}J.prototype.clear=An;J.prototype.delete=Sn;J.prototype.get=En;J.prototype.has=jn;J.prototype.set=Nn;var On=Object.prototype,ju=On.propertyIsEnumerable,Pn=$(A,"DataView"),ve=Pn,$n=$(A,"Promise"),we=$n,Dn=$(A,"Set"),ke=Dn,He="[object Map]",Tn="[object Object]",qe="[object Promise]",Ze="[object Set]",Qe="[object WeakMap]",Ye="[object DataView]",zn=M(ve),Rn=M(W),Fn=M(we),Vn=M(ke),Un=M(ye),N=K;(ve&&N(new ve(new ArrayBuffer(1)))!=Ye||W&&N(new W)!=He||we&&N(we.resolve())!=qe||ke&&N(new ke)!=Ze||ye&&N(new ye)!=Qe)&&(N=function(e){var t=K(e),r=t==Tn?e.constructor:void 0,i=r?M(r):"";if(i)switch(i){case zn:return Ye;case Rn:return He;case Fn:return qe;case Vn:return Ze;case Un:return Qe}return t});var _u=A.Uint8Array,Bn="__lodash_hash_undefined__";function Gn(e){return this.__data__.set(e,Bn),this}var Hn=Gn;function qn(e){return this.__data__.has(e)}var Zn=qn;function Ie(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new ot;++t<r;)this.add(e[t])}Ie.prototype.add=Ie.prototype.push=Hn;Ie.prototype.has=Zn;var We=P?P.prototype:void 0,Lu=We?We.valueOf:void 0,Qn=Object.prototype,Nu=Qn.hasOwnProperty,Yn=Object.prototype,Ou=Yn.hasOwnProperty,Pu=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),$u=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Du=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function at(e,t){if(e.startsWith("buffer:")){let r=await t.editor.getMimeType(e),i=t.editor.getBufferLength(e),n=t.editor.getBufferData(e,0,i),o=new Blob([n],{type:r});return URL.createObjectURL(o)}else return e}async function Wn(e,t){let r=await at(e,t);return new Promise((i,n)=>{let o=new Image;o.onload=()=>{i({width:o.width,height:o.height})},o.onerror=n,o.src=r})}async function Kn(e,t,r){let i,n=t.block.getFill(e),o=t.block.getSourceSet(n,"fill/image/sourceSet"),[a]=o;if(a==null){if(i=t.block.getString(n,"fill/image/imageFileURI"),i==null)throw new Error("No image source/uri found")}else i=a.uri;if(r?.throwErrorIfSvg&&await t.editor.getMimeType(i)==="image/svg+xml")throw new Error("SVG images are not supported");return at(i,t)}function Jn(e){return e!==void 0}var Xn=Jn;var xe=class st{constructor(){this.actions=new Map,this.subscribers=new Map}static get(){let t="__imgly_action_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new st),r[t]}register(t){return this.actions.set(t.id,t),this.notifySubscribers(t,"registered"),()=>{this.actions.get(t.id)===t&&(this.actions.delete(t.id),this.notifySubscribers(t,"unregistered"))}}getAll(){return Array.from(this.actions.values())}getBy(t){return this.getAll().filter(r=>this.matchesFilters(r,t))}subscribe(t){return this.subscribers.set(t,null),()=>{this.subscribers.delete(t)}}subscribeBy(t,r){return this.subscribers.set(r,t),()=>{this.subscribers.delete(r)}}notifySubscribers(t,r){this.subscribers.forEach((i,n)=>{if(i===null){n(t,r);return}this.matchesFilters(t,i)&&n(t,r)})}matchesFilters(t,r){return!(r.type&&t.type!==r.type||r.pluginId&&t.type==="plugin"&&t.pluginId!==r.pluginId||r.id&&t.id!==r.id||r.kind&&(t.type!=="quick"||t.kind!==r.kind))}},eo=class lt{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new lt),r[t]}register(t){return this.providers.has(t.provider.id)&&console.warn(`Provider with ID "${t.provider.id}" is already registered`),this.providers.set(t.provider.id,t),()=>{this.providers.get(t.provider.id)===t&&this.providers.delete(t.provider.id)}}getAll(){return Array.from(this.providers.values())}getById(t){return this.providers.get(t)}getByKind(t){return this.getAll().filter(({provider:r})=>r.kind===t)}};function to(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let o=[],a=l=>{o.push(l)},s=async(l,c,d)=>{if(l>=t.length)return r(c,d);let p=t[l],g=async(b,m)=>s(l+1,b,m),h={...d,addDisposer:a};return p(c,h,g)},u={...n,addDisposer:a};return{result:await s(0,i,u),dispose:async()=>{for(let l=o.length-1;l>=0;l--)try{await o[l]()}catch(c){console.error("Error in disposer:",c)}o.length=0}}}}function ro({enable:e=!0}){return async(t,r,i)=>{if(!e)return i(t,r);console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let n,o=Date.now();try{return n=await i(t,r),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var io=ro;var he="ly.img.ai.temp";async function no(e,t){return e.engine.asset.findAllSources().includes(he)||e.engine.asset.addLocalSource(he),e.engine.asset.apply(he,t)}function oo(e,t="We encountered an unknown error while generating the asset. Please try again."){if(e===null)return t;if(e instanceof Error)return e.message;if(typeof e=="object"){let r=e;return"message"in r&&typeof r.message=="string"?r.message:"cause"in r&&typeof r.cause=="string"?r.cause:"detail"in r&&typeof r.detail=="object"&&r.detail!==null&&"message"in r.detail&&typeof r.detail.message=="string"?r.detail.message:"error"in r&&typeof r.error=="object"&&r.error!==null&&"message"in r.error&&typeof r.error.message=="string"?r.error.message:t}return typeof e=="string"?e:String(e)||t}function ut(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function ao(e,t=0,r="image/jpeg",i=.8){return new Promise((n,o)=>{try{let a=document.createElement("video");a.crossOrigin="anonymous",a.style.display="none",a.addEventListener("loadedmetadata",()=>{a.currentTime=Math.min(t,a.duration),a.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=a.videoWidth,s.height=a.videoHeight;let u=s.getContext("2d");if(!u){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}u.drawImage(a,0,0,s.width,s.height);try{let l=s.toDataURL(r,i);document.body.removeChild(a),n(l)}catch(l){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${l instanceof Error?l.message:String(l)}`))}},{once:!0})}),a.addEventListener("error",()=>{document.body.removeChild(a),o(new Error(`Failed to load video from ${e}`))}),a.src=e,document.body.appendChild(a)}catch(a){o(a)}})}function ct(e){return e?e.replace(/[_-]/g," ").replace(/([A-Z])/g," $1").trim().split(" ").filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):""}function so(e){return typeof e=="object"&&e!==null&&"next"in e&&"return"in e&&"throw"in e&&typeof e.next=="function"&&typeof e.return=="function"&&typeof e.throw=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}function Se(e){return e instanceof Error&&e.name==="AbortError"}function lo(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function dt(e,t,r){let i="ai-plugin-version",n="ai-plugin-version-warning-shown";try{let o=e.ui.experimental.getGlobalStateValue(i);o?o!==r&&(e.ui.experimental.getGlobalStateValue(n,!1)||(console.warn(`[IMG.LY AI Plugins] Version mismatch detected! Plugin "${t}" is using version ${r}, but other AI plugins are using version ${o}. This may cause compatibility issues. Please ensure all AI plugins (@imgly/plugin-ai-*) use the same version. Consider updating all AI plugins to the same version for optimal compatibility.`),e.ui.experimental.setGlobalStateValue(n,!0))):e.ui.experimental.setGlobalStateValue(i,r)}catch(o){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",o)}}function uo(e){let{cesdk:t,panelId:r}=e;r.startsWith("ly.img.ai.")||console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai." \u2013 "${r}" was provided.`);let i=`${r}.dock`;t.ui.registerComponent(i,({builder:n})=>{let o=t.ui.isPanelOpen(r);n.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:o,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(a=>{a.startsWith("ly.img.ai.")&&t.ui.closePanel(a),!o&&a==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(a)}),o?t.ui.closePanel(r):t.ui.openPanel(r)}})})}var pt=uo;function co(){return({engine:e})=>{let t=e.block.findAllSelected();if(t==null||t.length!==1)return!1;let[r]=t;if(!e.block.supportsFill(r)||e.block.getKind(r)==="sticker"||!["//ly.img.ubq/graphic","//ly.img.ubq/page"].includes(e.block.getType(r)))return!1;let i=e.block.getFill(r);return e.block.getType(i)==="//ly.img.ubq/fill/image"}}var gt=co;function po(e,t){let{cesdk:r,provider:i,getInput:n}=t;console.error("Generation failed:",e),go(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:oo(e)})}function go(e,t,r){let i=t?.error;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.failed",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"error",message:n,action:o}),!0}var Ke=po,fo="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ce=fo;function ho(e,t,r){switch(t){case"image":return mo(e,r[t]);case"video":return bo(e,r[t]);case"sticker":return yo(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function mo(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function bo(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ce,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function yo(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var vo=ho;async function wo(e,t,r,i){switch(t){case"image":{if(i.kind!=="image")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: image)`);return ko(e,r[t],i)}case"video":{if(i.kind!=="video")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: video)`);return Io(e,r[t],i)}case"audio":{if(i.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: audio)`);return Ao(e,r[t],i)}case"sticker":{if(i.kind!=="sticker")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: sticker)`);return xo(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ko(e,t,r){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:i,height:n},payload:{sourceSet:[{uri:r.url,width:i,height:n}]}}}async function Io(e,t,r){let i=t.width,n=t.height,o=await ao(r.url,0);return{id:e,label:t.label,meta:{uri:r.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}function Ao(e,t,r){return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:r.duration.toString()}}}function xo(e,t,r){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:i,height:n},payload:{sourceSet:[{uri:r.url,width:i,height:n}]}}}var ft=wo;function So(e){switch(e.userFlow){case"placeholder":return Eo(e);case"generation-only":return Co(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Co(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(S(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(S(t,r))return{status:"aborted"};if(a.status!=="success")return a;if(a.type==="async")throw new Error("Async generation is not supported in this context yet.");if(S(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=ut(),u=await ft(s,n,o,a.output),l={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,l)}else e.debug&&console.log("No asset source ID found in history and generation only was requested. Doing nothing. If no middleware is adding functionality this could be a bug.");return a}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}}function Eo(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(S(t,r))return{status:"aborted"};let s=ut(),u=vo(s,o,a);if(i=await no(t,u),S(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),p=t.engine.block.getPositionY(i),g=t.engine.block.duplicate(i);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,p),t.engine.block.destroy(i),i=g}if(i==null)throw new Error("Could not create placeholder block");t.engine.block.setState(i,{type:"Pending",progress:0});let l=await e.generate(n,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(S(t,r,i))return{status:"aborted"};if(l.status!=="success")return l;if(l.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!t.engine.block.isValid(i))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let c=await ft(s,o,a,l.output);if(S(t,r,i))return{status:"aborted"};if(e.debug&&console.log("Updating placeholder in scene:",JSON.stringify(c,void 0,2)),await t.engine.asset.defaultApplyAssetToBlock(c,i),S(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,d)}return t.engine.block.isValid(i)&&t.engine.block.setState(i,{type:"Ready"}),l}catch(o){return i!=null&&t.engine.block.isValid(i)&&(Se(o)?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),{status:"error",message:o instanceof Error?o.message:String(o)}}}}function S(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Mo=So;function Ee(e){return`${e}.generating`}function jo(e){return`${e}.abort`}function _o(e,t,r,i,n,o,a){let{builder:s,experimental:u}=e,{cesdk:l,includeHistoryLibrary:c=!0}=o,{id:d,output:{abortable:p}}=t,g=u.global(jo(d),()=>{}),h=u.global(Ee(d),!1),b,m=h.value&&p,f=()=>{m&&(g.value(),h.setValue(!1),g.setValue(()=>{}))},L;if(o.requiredInputs!=null&&o.requiredInputs.length>0){let I=i();L=o.requiredInputs.every(k=>!I.input[k])}let y=u.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:h.value,color:"accent",isDisabled:L,suffix:m?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let I=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:k})=>{l.ui.closeDialog(k),y.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:k})=>{f(),l.ui.closeDialog(k),y.setValue(void 0)}}});y.setValue(I)}}:void 0,onClick:async()=>{b=new AbortController;let I=b.signal;await(async()=>{try{h.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),b?.abort()});let k=await Mo({kind:t.kind,generate:r,historyAssetSourceId:o.historyAssetSourceId,userFlow:o.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:I,cesdk:l,debug:a.debug,dryRun:a.dryRun})(i().input);if(k.status==="aborted")return;if(k.status==="error"){Ke(k.message,{cesdk:l,provider:t,getInput:i});return}if(k.status==="success"&&k.type==="sync"){let E=t.output.notification;Lo(l,E,()=>({input:i().input,output:k.output}))}}catch(k){if(Se(k))return;Ke(k,{cesdk:l,provider:t,getInput:i})}finally{b=void 0,h.setValue(!1),g.setValue(()=>{}),y.value!=null&&(l.ui.closeDialog(y.value),y.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function Lo(e,t,r){let i=t?.success;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.success",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"success",message:n,action:o,duration:i.duration}),!0}var ht=_o;async function No({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t,s=r.render;return u=>{let{state:l}=u,c=l(Ee(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(u,{cesdk:o,isGenerating:c});return ht(u,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Oo=No;function mt(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let r=t.substring(2).split("/"),i=e;for(let n of r){if(i==null)throw new Error(`Invalid reference path: ${t}`);i=i[n]}if(i===void 0)throw new Error(`Reference not found: ${t}`);return i}function Z(e,t,r=new Set){if(t==null||r.has(t))return t;if(r.add(t),t.$ref&&typeof t.$ref=="string"){let i=mt(e,t.$ref),n={...Z(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=Z(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>Z(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=Z(e,t[n],r));return i}return t}function Po(e){return Z(e,{...e})}function $o(e,t=!1){let r=a=>(t&&console.log(`OpenAPI Schema validation failed: ${a}`),!1);if(typeof e!="object"||e===null)return r(`Input is ${e===null?"null":typeof e}, not an object`);let i=e;if(!(typeof i.type=="string"||Array.isArray(i.enum)||typeof i.properties=="object"||typeof i.items=="object"||typeof i.allOf=="object"||typeof i.anyOf=="object"||typeof i.oneOf=="object"||typeof i.not=="object"))return r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(i.type!==void 0){let a=["string","number","integer","boolean","array","object","null"];if(typeof i.type=="string"){if(!a.includes(i.type))return r(`Invalid type: ${i.type}. Must be one of ${a.join(", ")}`)}else if(Array.isArray(i.type)){for(let s of i.type)if(typeof s!="string"||!a.includes(s))return r(`Array of types contains invalid value: ${s}. Must be one of ${a.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof i.type}`)}if(i.items!==void 0&&(typeof i.items!="object"||i.items===null))return r(`Items must be an object, got ${i.items===null?"null":typeof i.items}`);if(i.properties!==void 0&&(typeof i.properties!="object"||i.properties===null))return r(`Properties must be an object, got ${i.properties===null?"null":typeof i.properties}`);let n=["allOf","anyOf","oneOf"];for(let a of n)if(i[a]!==void 0){if(!Array.isArray(i[a]))return r(`${a} must be an array, got ${typeof i[a]}`);for(let s=0;s<i[a].length;s++){let u=i[a][s];if(typeof u!="object"||u===null)return r(`Item ${s} in ${a} must be an object, got ${u===null?"null":typeof u}`)}}if(i.not!==void 0&&(typeof i.not!="object"||i.not===null))return r(`'not' must be an object, got ${i.not===null?"null":typeof i.not}`);if(i.additionalProperties!==void 0&&typeof i.additionalProperties!="boolean"&&(typeof i.additionalProperties!="object"||i.additionalProperties===null))return r(`additionalProperties must be a boolean or an object, got ${i.additionalProperties===null?"null":typeof i.additionalProperties}`);if(i.format!==void 0&&typeof i.format!="string")return r(`format must be a string, got ${typeof i.format}`);let o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let a of o)if(i[a]!==void 0&&typeof i[a]!="number")return r(`${a} must be a number, got ${typeof i[a]}`);if(i.minLength!==void 0&&(typeof i.minLength!="number"||i.minLength<0))return r(`minLength must be a non-negative number, got ${typeof i.minLength=="number"?i.minLength:typeof i.minLength}`);if(i.maxLength!==void 0&&(typeof i.maxLength!="number"||i.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof i.maxLength=="number"?i.maxLength:typeof i.maxLength}`);if(i.pattern!==void 0&&typeof i.pattern!="string")return r(`pattern must be a string, got ${typeof i.pattern}`);if(i.minItems!==void 0&&(typeof i.minItems!="number"||i.minItems<0))return r(`minItems must be a non-negative number, got ${typeof i.minItems=="number"?i.minItems:typeof i.minItems}`);if(i.maxItems!==void 0&&(typeof i.maxItems!="number"||i.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof i.maxItems=="number"?i.maxItems:typeof i.maxItems}`);if(i.uniqueItems!==void 0&&typeof i.uniqueItems!="boolean")return r(`uniqueItems must be a boolean, got ${typeof i.uniqueItems}`);if(i.minProperties!==void 0&&(typeof i.minProperties!="number"||i.minProperties<0))return r(`minProperties must be a non-negative number, got ${typeof i.minProperties=="number"?i.minProperties:typeof i.minProperties}`);if(i.maxProperties!==void 0&&(typeof i.maxProperties!="number"||i.maxProperties<0))return r(`maxProperties must be a non-negative number, got ${typeof i.maxProperties=="number"?i.maxProperties:typeof i.maxProperties}`);if(i.required!==void 0){if(!Array.isArray(i.required))return r(`required must be an array, got ${typeof i.required}`);for(let a=0;a<i.required.length;a++){let s=i.required[a];if(typeof s!="string")return r(`Item ${a} in required array must be a string, got ${typeof s}`)}}return!0}function Do(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return To(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function To(e,t){let r=t.order;if(r!=null&&Array.isArray(r))return r;if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=Object.keys(i),o=zo(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function zo(e,t){if(t.orderExtensionKeyword==null)return;if(typeof t.orderExtensionKeyword!="string"&&!Array.isArray(t.orderExtensionKeyword))throw new Error("orderExtensionKeyword must be a string or an array of strings");let r=(typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword).find(i=>i in e);return r==null?void 0:e[r]}var bt=Do;function yt(e,t,r,i,n,o){if(t.schema==null)return i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null?i.renderCustomProperty[t.id](e,t):void 0;let a=t,s=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null)return i.renderCustomProperty[t.id](e,t);switch(s){case"string":return t.schema.enum!=null?Ro(e,a,r,i,n,o):wt(e,a,r,i,n,o);case"boolean":return kt(e,a,r,i,n,o);case"number":case"integer":return It(e,a,r,i,n,o);case"object":return vt(e,a,r,i,n,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Fo(e,a,r,i,n,o);break}default:console.error(`Unsupported property type: ${s}`)}}function vt(e,t,r,i,n,o){let a=bt(t.schema??{},i).reduce((s,u)=>{let l=yt(e,u,r,i,n,o);return l!=null&&(s[u.id]=l()),s},{});return()=>({id:t.id,type:"object",value:a})}function wt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=s(l,t.schema.default??""),p=Vo(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](l,{inputLabel:c,placeholder:n.i18n?.prompt,...d}),()=>({id:t.id,type:"string",value:d.value})}function Ro(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.enum!=null&&"x-imgly-enum-labels"in t.schema.enum&&typeof t.schema.enum["x-imgly-enum-labels"]=="object"?t.schema.enum["x-imgly-enum-labels"]:"x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},p="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},g=(t.schema.enum??[]).map(m=>({id:m,label:d[m]??ct(m),icon:p[m]})),h=t.schema.default!=null?g.find(m=>m.id===t.schema.default)??g[0]:g[0],b=s(l,h);return a.Select(l,{inputLabel:c,values:g,...b}),()=>({id:t.id,type:"string",value:b.value.id})}function kt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=!!t.schema.default,p=s(l,d);return a.Checkbox(l,{inputLabel:c,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function It(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(d!=null?g=d:p!=null?g=p:g=0);let h=s(l,g);if(d!=null&&p!=null){let b=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(b=t.schema["x-imgly-step"]),a.Slider(l,{inputLabel:c,min:d,max:p,step:b,...h})}else a.NumberInput(l,{inputLabel:c,min:d,max:p,...h});return()=>({id:t.id,type:"integer",value:h.value})}function Fo(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.anyOf??[],p=[],g={},h={};d.forEach((f,L)=>{let y=f.title??"common.custom",I=`${r.id}.${u}.anyOf[${L}]`,k="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},E="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};f.type==="string"?f.enum!=null?f.enum.forEach(ae=>{p.push({id:ae,label:k[ae]??ct(ae),icon:E[ae]})}):(g[I]=()=>wt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="boolean"?(g[I]=()=>kt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="integer"?(g[I]=()=>It(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="array"||f.type==="object"&&(g[I]=()=>vt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]}))});let b=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],m=s(l,b);if(a.Select(l,{inputLabel:c,values:p,...m}),m.value.id in g){let f=g[m.value.id]();h[m.value.id]=f}return()=>{let f=h[m.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:m.value.id}}}function Vo(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Uo=yt;async function Bo({options:e,provider:t,panelInput:r,config:i},n){let{id:o}=t;if(r==null)return;i.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=Po(r.document),s=mt(a,r.inputReference);if(!$o(s,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let u=s,l=bt(u,r);return c=>{let{builder:d}=c,p=[];d.Section(`${o}.schema.section`,{children:()=>{l.forEach(m=>{let f=Uo(c,m,t,r,e,i);f!=null&&(Array.isArray(f)?p.push(...f):p.push(f))})}});let g=p.map(m=>m()),h=m=>m.type==="object"?Object.entries(m.value).reduce((f,[L,y])=>(f[L]=h(y),f),{}):m.value,b=g.reduce((m,f)=>(m[f.id]=h(f),m),{});ht(c,t,n,()=>({input:b}),()=>r.getBlockInput(b),{...e,requiredInputs:u.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var Go=Bo;async function Ho(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Oo(e,t);case"schema":return Go(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var qo=Ho;function Zo(e){let{provider:t,options:{engine:r}}=e,i=t.output.history??"@imgly/local";if(i==null||i===!1)return;let n=r.asset.findAllSources();function o(){let a=`${t.id}.history`;for(;n.includes(a);)a+=`-${Math.random().toString(36).substring(2,6)}`;return a}if(i==="@imgly/local"){let a=o();return r.asset.addLocalSource(a),a}if(i==="@imgly/indexedDB"){let a=o();return r.asset.addSource(new Kt(a,r)),a}return i}var Qo=Zo;function Yo(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history`;return e.options.cesdk.ui.addAssetLibraryEntry({id:r,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),r}var Wo=Yo,me="@imgly/plugin-ai-generation",Ko=` <svg> <symbol fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="@imgly/Sparkle" > <path d="M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z" fill="currentColor"/> <path d="M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9632 11.7642L18.9207 9.21086C18.9709 9.077 19.0765 8.97138 19.2104 8.92118L21.7637 7.96366C22.192 7.80307 22.192 7.1973 21.7637 7.0367L19.2104 6.07918C19.0765 6.02899 18.9709 5.92337 18.9207 5.78951L17.9632 3.23614Z" fill="currentColor"/> <path d="M9.30058 7.82012C9.54712 7.1791 10.454 7.1791 10.7006 7.82012L12.3809 12.189C12.4571 12.3871 12.6136 12.5436 12.8117 12.6198L17.1806 14.3001C17.8216 14.5466 17.8216 15.4536 17.1806 15.7001L12.8117 17.3804C12.6136 17.4566 12.4571 17.6131 12.3809 17.8112L10.7006 22.1801C10.454 22.8211 9.54712 22.8211 9.30058 22.1801L7.62024 17.8112C7.54406 17.6131 7.38754 17.4566 7.18947 17.3804L2.82061 15.7001C2.17959 15.4536 2.17959 14.5466 2.82061 14.3001L7.18947 12.6198C7.38754 12.5436 7.54406 12.3871 7.62024 12.189L9.30058 7.82012Z" fill="currentColor"/> </symbol> <symbol fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="${me}/image" > <path d="M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z" fill="currentColor"/> <path d="M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z" fill="currentColor"/> <path d="M6.40053 5.38488C6.52538 5.06832 6.97338 5.06832 7.09823 5.38488L8.17455 8.11392C8.21267 8.21057 8.28917 8.28707 8.38582 8.32519L11.1149 9.40151C11.4314 9.52636 11.4314 9.97436 11.1149 10.0992L8.38582 11.1755C8.28917 11.2136 8.21267 11.2901 8.17455 11.3868L7.09823 14.1158C6.97338 14.4324 6.52538 14.4324 6.40053 14.1158L5.32421 11.3868C5.2861 11.2901 5.20959 11.2136 5.11295 11.1755L2.3839 10.0992C2.06735 9.97436 2.06735 9.52636 2.3839 9.40151L5.11295 8.32519C5.20959 8.28707 5.2861 8.21057 5.32421 8.11392L6.40053 5.38488Z" fill="currentColor"/> <path d="M18.9994 16.5008V18.0004C18.9994 18.5526 18.5517 19.0004 17.9994 19.0004H9.33302L14.3753 11.4369C14.6722 10.9916 15.3266 10.9916 15.6234 11.4369L18.9994 16.5008Z" fill="currentColor"/> </symbol> <symbol fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="${me}/video" > <path d="M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z" fill="currentColor"/> <path d="M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z" fill="currentColor"/> <path d="M18.9019 3.3845C19.0267 3.06795 19.4747 3.06795 19.5996 3.3845L20.6759 6.11355C20.714 6.2102 20.7905 6.2867 20.8872 6.32482L23.6162 7.40114C23.9328 7.52598 23.9328 7.97399 23.6162 8.09883L20.8872 9.17515C20.7905 9.21327 20.714 9.28977 20.6759 9.38642L19.5996 12.1155C19.4747 12.432 19.0267 12.432 18.9019 12.1155L17.8255 9.38642C17.7874 9.28977 17.7109 9.21327 17.6143 9.17515L14.8852 8.09883C14.5687 7.97399 14.5687 7.52598 14.8852 7.40114L17.6143 6.32482C17.7109 6.2867 17.7874 6.2102 17.8255 6.11355L18.9019 3.3845Z" fill="currentColor"/> <path d="M14.9994 13.2862C15.5089 12.8859 15.5089 12.1141 14.9995 11.7137L10.618 8.27047C9.96188 7.75485 9.00011 8.22225 9.00011 9.05673L9.00011 15.9429C9.00011 16.7773 9.96185 17.2448 10.618 16.7292L14.9994 13.2862Z" fill=