UNPKG

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

Version:

AI video generation plugin for the CE.SDK editor

4 lines 87.2 kB
var Ir=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((c,l)=>{let u=e.locale??"en",d="",f=[];l.label!=null&&typeof l.label=="object"&&l.label[u]&&(d=l.label[u]),l.tags!=null&&typeof l.tags=="object"&&l.tags[u]&&(f=l.tags[u]);let g={...l,label:d,tags:f};return this.filterAsset(g,e)&&c.push(g),c},[]);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;V(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.oncomplete=()=>{this.engine.asset.assetSourceContentsChanged(this.id)},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=()=>{V(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(),c=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-c:c-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 V(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),V(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()??"",c=e.tags?.map(l=>l.toLowerCase())??[];if(!a.every(l=>s.includes(l)||c.some(u=>u.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 c,l;return i==="id"?(c=a.id,l=s.id):(c=a.meta?.[i]??null,l=s.meta?.[i]??null),c==null?r==="Ascending"?-1:1:l==null?r==="Ascending"?1:-1:typeof c=="string"&&typeof l=="string"?r==="Ascending"?c.localeCompare(l):l.localeCompare(c):r==="Ascending"?c<l?-1:c>l?1:0:c>l?-1:c<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 V(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]=V(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]=V(n,t,o)}return e}var Ar=class{constructor(e,t,r){this.id=e,this.cesdk=t,this.assetSourceIds=r}async findAssets(e){try{let t=this.assetSourceIds.map(u=>this.cesdk.engine.asset.findAssets(u,{...e,perPage:9999,page:0})),r=await Promise.all(t),i=[];r.forEach(u=>{u?.assets&&(i=i.concat(u.assets))}),i.sort((u,d)=>{let f=u.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-f});let{page:n,perPage:o}=e,a=n*o,s=a+o,c=i.slice(a,s),l=s<i.length?n+1:void 0;return{assets:c,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 Sr=typeof global=="object"&&global&&global.Object===Object&&global,It=Sr,xr=typeof self=="object"&&self&&self.Object===Object&&self,Cr=It||xr||Function("return this")(),M=Cr,Er=M.Symbol,U=Er,At=Object.prototype,$r=At.hasOwnProperty,Mr=At.toString,X=U?U.toStringTag:void 0;function jr(e){var t=$r.call(e,X),r=e[X];try{e[X]=void 0;var i=!0}catch{}var n=Mr.call(e);return i&&(t?e[X]=r:delete e[X]),n}var Tr=jr,_r=Object.prototype,Lr=_r.toString;function Pr(e){return Lr.call(e)}var Nr=Pr,Or="[object Null]",Dr="[object Undefined]",tt=U?U.toStringTag:void 0;function zr(e){return e==null?e===void 0?Dr:Or:tt&&tt in Object(e)?Tr(e):Nr(e)}var oe=zr;function Rr(e){return e!=null&&typeof e=="object"}var Ue=Rr,ec=Array.isArray;function Fr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var St=Fr,Vr="[object AsyncFunction]",Ur="[object Function]",Br="[object GeneratorFunction]",Gr="[object Proxy]";function qr(e){if(!St(e))return!1;var t=oe(e);return t==Ur||t==Br||t==Vr||t==Gr}var Hr=qr,Qr=M["__core-js_shared__"],je=Qr,rt=function(){var e=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Zr(e){return!!rt&&rt in e}var Kr=Zr,Yr=Function.prototype,Wr=Yr.toString;function Jr(e){if(e!=null){try{return Wr.call(e)}catch{}try{return e+""}catch{}}return""}var z=Jr,Xr=/[\\^$.*+?()[\]{}|]/g,ei=/^\[object .+?Constructor\]$/,ti=Function.prototype,ri=Object.prototype,ii=ti.toString,ni=ri.hasOwnProperty,ai=RegExp("^"+ii.call(ni).replace(Xr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function oi(e){if(!St(e)||Kr(e))return!1;var t=Hr(e)?ai:ei;return t.test(z(e))}var li=oi;function si(e,t){return e?.[t]}var ui=si;function ci(e,t){var r=ui(e,t);return li(r)?r:void 0}var B=ci,di=B(M,"WeakMap"),Ne=di;function gi(e,t){return e===t||e!==e&&t!==t}var pi=gi,fi=9007199254740991;function mi(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=fi}var yi=mi,tc=Object.prototype,hi="[object Arguments]";function bi(e){return Ue(e)&&oe(e)==hi}var it=bi,xt=Object.prototype,vi=xt.hasOwnProperty,wi=xt.propertyIsEnumerable,rc=it(function(){return arguments}())?it:function(e){return Ue(e)&&vi.call(e,"callee")&&!wi.call(e,"callee")},Ct=typeof exports=="object"&&exports&&!exports.nodeType&&exports,nt=Ct&&typeof module=="object"&&module&&!module.nodeType&&module,ki=nt&&nt.exports===Ct,at=ki?M.Buffer:void 0,ic=at?at.isBuffer:void 0,Ii="[object Arguments]",Ai="[object Array]",Si="[object Boolean]",xi="[object Date]",Ci="[object Error]",Ei="[object Function]",$i="[object Map]",Mi="[object Number]",ji="[object Object]",Ti="[object RegExp]",_i="[object Set]",Li="[object String]",Pi="[object WeakMap]",Ni="[object ArrayBuffer]",Oi="[object DataView]",Di="[object Float32Array]",zi="[object Float64Array]",Ri="[object Int8Array]",Fi="[object Int16Array]",Vi="[object Int32Array]",Ui="[object Uint8Array]",Bi="[object Uint8ClampedArray]",Gi="[object Uint16Array]",qi="[object Uint32Array]",w={};w[Di]=w[zi]=w[Ri]=w[Fi]=w[Vi]=w[Ui]=w[Bi]=w[Gi]=w[qi]=!0;w[Ii]=w[Ai]=w[Ni]=w[Si]=w[Oi]=w[xi]=w[Ci]=w[Ei]=w[$i]=w[Mi]=w[ji]=w[Ti]=w[_i]=w[Li]=w[Pi]=!1;function Hi(e){return Ue(e)&&yi(e.length)&&!!w[oe(e)]}var Qi=Hi;function Zi(e){return function(t){return e(t)}}var Ki=Zi,Et=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ie=Et&&typeof module=="object"&&module&&!module.nodeType&&module,Yi=ie&&ie.exports===Et,Te=Yi&&It.process,Wi=function(){try{var e=ie&&ie.require&&ie.require("util").types;return e||Te&&Te.binding&&Te.binding("util")}catch{}}(),ot=Wi,lt=ot&&ot.isTypedArray,nc=lt?Ki(lt):Qi,Ji=Object.prototype,ac=Ji.hasOwnProperty;function Xi(e,t){return function(r){return e(t(r))}}var en=Xi,oc=en(Object.keys,Object),tn=Object.prototype,lc=tn.hasOwnProperty,rn=B(Object,"create"),ne=rn;function nn(){this.__data__=ne?ne(null):{},this.size=0}var an=nn;function on(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var ln=on,sn="__lodash_hash_undefined__",un=Object.prototype,cn=un.hasOwnProperty;function dn(e){var t=this.__data__;if(ne){var r=t[e];return r===sn?void 0:r}return cn.call(t,e)?t[e]:void 0}var gn=dn,pn=Object.prototype,fn=pn.hasOwnProperty;function mn(e){var t=this.__data__;return ne?t[e]!==void 0:fn.call(t,e)}var yn=mn,hn="__lodash_hash_undefined__";function bn(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=ne&&t===void 0?hn:t,this}var vn=bn;function G(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])}}G.prototype.clear=an;G.prototype.delete=ln;G.prototype.get=gn;G.prototype.has=yn;G.prototype.set=vn;var st=G;function wn(){this.__data__=[],this.size=0}var kn=wn;function In(e,t){for(var r=e.length;r--;)if(pi(e[r][0],t))return r;return-1}var ve=In,An=Array.prototype,Sn=An.splice;function xn(e){var t=this.__data__,r=ve(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():Sn.call(t,r,1),--this.size,!0}var Cn=xn;function En(e){var t=this.__data__,r=ve(t,e);return r<0?void 0:t[r][1]}var $n=En;function Mn(e){return ve(this.__data__,e)>-1}var jn=Mn;function Tn(e,t){var r=this.__data__,i=ve(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var _n=Tn;function q(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])}}q.prototype.clear=kn;q.prototype.delete=Cn;q.prototype.get=$n;q.prototype.has=jn;q.prototype.set=_n;var we=q,Ln=B(M,"Map"),ae=Ln;function Pn(){this.size=0,this.__data__={hash:new st,map:new(ae||we),string:new st}}var Nn=Pn;function On(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Dn=On;function zn(e,t){var r=e.__data__;return Dn(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ke=zn;function Rn(e){var t=ke(this,e).delete(e);return this.size-=t?1:0,t}var Fn=Rn;function Vn(e){return ke(this,e).get(e)}var Un=Vn;function Bn(e){return ke(this,e).has(e)}var Gn=Bn;function qn(e,t){var r=ke(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Hn=qn;function H(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])}}H.prototype.clear=Nn;H.prototype.delete=Fn;H.prototype.get=Un;H.prototype.has=Gn;H.prototype.set=Hn;var $t=H;function Qn(){this.__data__=new we,this.size=0}var Zn=Qn;function Kn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Yn=Kn;function Wn(e){return this.__data__.get(e)}var Jn=Wn;function Xn(e){return this.__data__.has(e)}var ea=Xn,ta=200;function ra(e,t){var r=this.__data__;if(r instanceof we){var i=r.__data__;if(!ae||i.length<ta-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new $t(i)}return r.set(e,t),this.size=r.size,this}var ia=ra;function le(e){var t=this.__data__=new we(e);this.size=t.size}le.prototype.clear=Zn;le.prototype.delete=Yn;le.prototype.get=Jn;le.prototype.has=ea;le.prototype.set=ia;var na=Object.prototype,sc=na.propertyIsEnumerable,aa=B(M,"DataView"),Oe=aa,oa=B(M,"Promise"),De=oa,la=B(M,"Set"),ze=la,ut="[object Map]",sa="[object Object]",ct="[object Promise]",dt="[object Set]",gt="[object WeakMap]",pt="[object DataView]",ua=z(Oe),ca=z(ae),da=z(De),ga=z(ze),pa=z(Ne),F=oe;(Oe&&F(new Oe(new ArrayBuffer(1)))!=pt||ae&&F(new ae)!=ut||De&&F(De.resolve())!=ct||ze&&F(new ze)!=dt||Ne&&F(new Ne)!=gt)&&(F=function(e){var t=oe(e),r=t==sa?e.constructor:void 0,i=r?z(r):"";if(i)switch(i){case ua:return pt;case ca:return ut;case da:return ct;case ga:return dt;case pa:return gt}return t});var uc=M.Uint8Array,fa="__lodash_hash_undefined__";function ma(e){return this.__data__.set(e,fa),this}var ya=ma;function ha(e){return this.__data__.has(e)}var ba=ha;function Re(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new $t;++t<r;)this.add(e[t])}Re.prototype.add=Re.prototype.push=ya;Re.prototype.has=ba;var ft=U?U.prototype:void 0,cc=ft?ft.valueOf:void 0,va=Object.prototype,dc=va.hasOwnProperty,wa=Object.prototype,gc=wa.hasOwnProperty,pc=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),fc=new RegExp(/[A-Fa-f0-9]{1}/,"g"),mc=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function Mt(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 Uint8Array(n),a=new Blob([o],{type:r});return URL.createObjectURL(a)}else return e}async function ka(e,t){let r=await Mt(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 Ia(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 Mt(i,t)}function Aa(e){return e!==void 0}var Sa=Aa;function P(e,t){if(typeof e.i18n?.getTranslations!="function"){e.i18n.setTranslations(t);return}let r=Object.keys(t),i=e.i18n.getTranslations(r),n={};for(let o of r){let a=t[o];if(!a)continue;let s=i[o]??{},c={};for(let[l,u]of Object.entries(a))!(l in s)&&u!==void 0&&(c[l]=u);Object.keys(c).length>0&&(n[o]=c)}Object.keys(n).length>0&&e.i18n.setTranslations(n)}function se(e,t){let r=t?.i18n?.getLocale?.()||"en";return{engine:e,cesdk:t,locale:r}}function ue(e,t,r,i,n){if(t?.default!==void 0){let o=t.default;return typeof o!="function"?o:o(r)}return i!==void 0?i:n}var ce=class jt{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 jt),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))}},xa=class Tt{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new Tt),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 Ca(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let o=[],a=l=>{o.push(l)},s=async(l,u,d)=>{if(l>=t.length)return r(u,d);let f=t[l],g=async(p,y)=>s(l+1,p,y),m={...d,addDisposer:a};return f(u,m,g)},c={...n,addDisposer:a};return{result:await s(0,i,c),dispose:async()=>{for(let l=o.length-1;l>=0;l--)try{await o[l]()}catch(u){console.error("Error in disposer:",u)}o.length=0}}}}function Ea({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 $a=Ea;var _e="ly.img.ai.temp";async function Ma(e,t){return e.engine.asset.findAllSources().includes(_e)||e.engine.asset.addLocalSource(_e),e.engine.asset.apply(_e,t)}function ja(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 _t(){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 Ta(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 c=s.getContext("2d");if(!c){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}c.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 _a(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 Be(e){return e instanceof Error&&e.name==="AbortError"}function La(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function Lt(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 Pa(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=Pa;function Na(){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 Nt=Na;function Oa(e,t){let{cesdk:r,provider:i,getInput:n,middlewareOptions:o}=t;o?.defaultPrevented()||(console.error("Generation failed:",e),Da(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:ja(e)}))}function Da(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 mt=Oa,za="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ge=za;function Ra(e,t,r){switch(t){case"image":return Fa(e,r[t]);case"video":return Va(e,r[t]);case"sticker":return Ua(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Fa(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ge,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function Va(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ge,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Ua(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ge,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var Ba=Ra;async function Ga(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 qa(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 Ha(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 Qa(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 Za(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function qa(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 Ha(e,t,r){let i=t.width,n=t.height,o=await Ta(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 Qa(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 Za(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 Ot=Ga;function Ka(e){switch(e.userFlow){case"placeholder":return Wa(e);case"generation-only":return Ya(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Ya(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(_(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(_(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(_(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=_t(),c=await Ot(s,n,o,a.output),l={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.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 Wa(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(_(t,r))return{status:"aborted"};let s=_t(),c=Ba(s,o,a);if(i=await Ma(t,c),_(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),f=t.engine.block.getPositionY(i),g=t.engine.block.duplicate(i);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,f),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,{blockIds:[i],middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(_(t,r,i))return{status:"aborted"};if(l.status!=="success")return l.middlewareOptions?.defaultPrevented()||i!=null&&t.engine.block.isValid(i)&&(l.status==="aborted"?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),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 u=await Ot(s,o,a,l.output);if(_(t,r,i))return{status:"aborted"};if(e.debug&&console.log("Updating placeholder in scene:",JSON.stringify(u,void 0,2)),await t.engine.asset.defaultApplyAssetToBlock(u,i),_(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.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)&&(Be(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 _(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Ja=Ka;function qe(e){return`${e}.generating`}function Xa(e){return`${e}.abort`}function eo(e,t,r,i,n,o,a){let{builder:s,experimental:c}=e,{cesdk:l,includeHistoryLibrary:u=!0}=o,{id:d,output:{abortable:f}}=t,g=c.global(Xa(d),()=>{}),m=c.global(qe(d),!1),p,y=m.value&&f,v=()=>{y&&(g.value(),m.setValue(!1),g.setValue(()=>{}))},I;if(o.requiredInputs!=null&&o.requiredInputs.length>0){let x=i();I=o.requiredInputs.every(b=>!x.input[b])}let S=c.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["ly.img.plugin-ai-generation-web.generate","common.generate",`panel.${d}.generate`],isLoading:m.value,color:"accent",isDisabled:I,suffix:y?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let x=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:b})=>{l.ui.closeDialog(b),S.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:b})=>{v(),l.ui.closeDialog(b),S.setValue(void 0)}}});S.setValue(x)}}:void 0,onClick:async()=>{p=new AbortController;let x=p.signal;await(async()=>{try{m.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),p?.abort()});let b=await Ja({kind:t.kind,generate:r,historyAssetSourceId:o.historyAssetSourceId,userFlow:o.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:x,cesdk:l,debug:a.debug,dryRun:a.dryRun})(i().input);if(b.status==="aborted")return;if(b.status==="error"){mt(b.message,{cesdk:l,provider:t,getInput:i,middlewareOptions:b.middlewareOptions});return}if(b.status==="success"&&b.type==="sync"&&!b.middlewareOptions?.defaultPrevented()){let E=t.output.notification;to(l,E,()=>({input:i().input,output:b.output}))}}catch(b){if(Be(b))return;mt(b,{cesdk:l,provider:t,getInput:i})}finally{p=void 0,m.setValue(!1),g.setValue(()=>{}),S.value!=null&&(l.ui.closeDialog(S.value),S.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function to(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 Dt=eo;function Fe(e){let{name:t}=e;return(typeof t=="function"?t():t)??e.id}async function ro({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t;i.debug&&console.log(`Provider: ${a} (custom)`);let s=r.render;return c=>{let{state:l}=c,u=l(qe(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:f}=s(c,{cesdk:o,isGenerating:u});return Dt(c,t,n,d,f,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var io=ro;function zt(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 te(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=zt(e,t.$ref),n={...te(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=te(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>te(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=te(e,t[n],r));return i}return t}function no(e){return te(e,{...e})}function ao(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 c=i[a][s];if(typeof c!="object"||c===null)return r(`Item ${s} in ${a} must be an object, got ${c===null?"null":typeof c}`)}}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 oo(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return lo(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function lo(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=so(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function so(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 Rt=oo;function L(e,t,r,i){let n=`property.${e.id}${i?`.${i}`:""}`,o=[`ly.img.plugin-ai-${r}-generation-web.${t.id}.${n}`,`ly.img.plugin-ai-generation-web.${n}`,`ly.img.plugin-ai-${r}-generation-web.${t.id}.defaults.${n}`,`ly.img.plugin-ai-generation-web.defaults.${n}`];return i==="placeholder"&&o.push("ly.img.plugin-ai-generation-web.fallback.property.placeholder"),o}function Ft(e){let t="x-imgly-enum-labels"in e&&typeof e["x-imgly-enum-labels"]=="object"?e["x-imgly-enum-labels"]:{},r="x-imgly-enum-icons"in e&&typeof e["x-imgly-enum-icons"]=="object"?e["x-imgly-enum-icons"]:{};return{labels:t,icons:r}}function Vt(e,t,r,i,n,o,a,s){if(t.schema==null)if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let u={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](u,t)}else return;let c=t,l=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let u={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](u,t)}switch(l){case"string":return t.schema.enum!=null?uo(e,c,r,i,n,o,a,s):Ut(e,c,r,i,n,o,a,s);case"boolean":return Bt(e,c,r,i,n,o,a,s);case"number":case"integer":return Gt(e,c,r,i,n,o,a,s);case"object":return Ve(e,c,r,i,n,o,a,s);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return co(e,c,r,i,n,o,a,s);break}default:console.error(`Unsupported property type: ${l}`)}}function Ve(e,t,r,i,n,o,a,s){let c=Rt(t.schema??{},i).reduce((l,u)=>{let d=Vt(e,u,r,i,n,o,a,s);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:c})}function Ut(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,f=`${r.id}.${d}`,g=L(t,r,a),m=L(t,r,a,"placeholder"),p=se(u,n.cesdk),y=s?.properties?.[d]??o.properties?.[d],v=ue(d,y,p,t.schema.default,""),I=l(f,v),S=go(t.schema),x=S?.component!=null&&S?.component==="TextArea"?"TextArea":"TextInput",b=m.length>0?m:void 0;return c[x](f,{inputLabel:g,...b&&{placeholder:b},...I}),()=>({id:t.id,type:"string",value:I.value})}function uo(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,f=`${r.id}.${d}`,g=L(t,r,a),{labels:m,icons:p}=Ft(t.schema),y=(t.schema.enum??[]).map(E=>({id:E,label:L(t,r,a,E),icon:p[E]})),v=se(u,n.cesdk),I=s?.properties?.[d]??o.properties?.[d],S=ue(d,I,v,t.schema.default,y[0]?.id),x=S!=null?y.find(E=>E.id===S)??y[0]:y[0],b=l(f,x);return c.Select(f,{inputLabel:g,values:y,...b}),()=>({id:t.id,type:"string",value:b.value.id})}function Bt(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,f=`${r.id}.${d}`,g=L(t,r,a),m=se(u,n.cesdk),p=s?.properties?.[d]??o.properties?.[d],y=!!ue(d,p,m,t.schema.default,!1),v=l(f,y);return c.Checkbox(f,{inputLabel:g,...v}),()=>({id:t.id,type:"boolean",value:v.value})}function Gt(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,f=`${r.id}.${d}`,g=L(t,r,a),m=t.schema.minimum,p=t.schema.maximum,y=se(u,n.cesdk),v=s?.properties?.[d]??o.properties?.[d],I=t.schema.default;I==null&&(m!=null?I=m:p!=null?I=p:I=0);let S=ue(d,v,y,I,I),x=l(f,S);if(m!=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"]),c.Slider(f,{inputLabel:g,min:m,max:p,step:b,...x})}else c.NumberInput(f,{inputLabel:g,min:m,max:p,...x});return()=>({id:t.id,type:"integer",value:x.value})}function co(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,f=`${r.id}.${d}`,g=L(t,r,a),m=t.schema.anyOf??[],p=[],y={},v={},{labels:I,icons:S}=Ft(t.schema),x=se(u,n.cesdk),b=s?.properties?.[d]??o.properties?.[d],E={string:Ut,boolean:Bt,integer:Gt,object:Ve},he=(h,$)=>h.$ref?h.$ref.split("/").pop():$.split(".").pop()??$,D=(h,$)=>({id:h,label:L(t,r,a,$),icon:S[$]??S[h]});m.forEach((h,$)=>{let A=`${r.id}.${d}.anyOf[${$}]`;if(h.$ref||h.title){let C=h.$ref?h.$ref.split("/").pop():h.title;y[A]=()=>Ve(e,{id:A,schema:{...h,title:I[C]||C}},r,i,n,o,a,s),p.push(D(A,C))}else if(h.type==="string"&&h.enum)h.enum.forEach(C=>{p.push(D(C,C))});else if(h.type&&E[h.type]){let C=E[h.type];y[A]=()=>C(e,{id:A,schema:{...h,title:h.title}},r,i,n,o,a,s);let Me=he(h,A);p.push(h.type==="string"&&!h.enum?{id:A,label:h.title||Me,icon:h.title&&S[h.title]||S[Me]}:D(A,Me))}});let be=ue(d,b,x,t.schema.default,null),$e=be!=null?p.find(h=>h.id===be)??p[0]:p[0],T=l(f,$e);if(c.Select(f,{inputLabel:g,values:p,...T}),T.value.id in y){let h=y[T.value.id]();v[T.value.id]=h}return()=>{let h=v[T.value.id];return h!=null?{...h(),id:t.id}:{id:t.id,type:"string",value:T.value.id}}}function go(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var po=Vt,fo={"ly.img.plugin-ai-generation-web.fallback.property.placeholder":"","ly.img.plugin-ai-generation-web.defaults.property.prompt":"Prompt","ly.img.plugin-ai-generation-web.defaults.property.style":"Style","ly.img.plugin-ai-generation-web.defaults.property.image_size":"Image Size","ly.img.plugin-ai-generation-web.defaults.property.size":"Image Size","ly.img.plugin-ai-generation-web.defaults.property.colors":"Colors","ly.img.plugin-ai-generation-web.defaults.property.background":"Background","ly.img.plugin-ai-generation-web.defaults.property.width":"Width","ly.img.plugin-ai-generation-web.defaults.property.height":"Height","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio":"Aspect Ratio","ly.img.plugin-ai-generation-web.defaults.property.duration":"Duration","ly.img.plugin-ai-generation-web.defaults.property.resolution":"Resolution","ly.img.plugin-ai-generation-web.defaults.property.generate_audio":"Generate Audio","ly.img.plugin-ai-generation-web.defaults.property.voice_id":"Voice","ly.img.plugin-ai-generation-web.defaults.property.speed":"Speed","ly.img.plugin-ai-generation-web.defaults.property.text":"Text","ly.img.plugin-ai-generation-web.defaults.property.duration_seconds":"Duration (seconds)","ly.img.plugin-ai-generation-web.defaults.property.style.type":"Type","ly.img.plugin-ai-generation-web.defaults.property.style.type.image":"Image","ly.img.plugin-ai-generation-web.defaults.property.style.type.vector":"Vector","ly.img.plugin-ai-generation-web.defaults.property.style.type.icon":"Icon","ly.img.plugin-ai-generation-web.defaults.property.image_size.square":"Square","ly.img.plugin-ai-generation-web.defaults.property.image_size.portrait":"Portrait","ly.img.plugin-ai-generation-web.defaults.property.image_size.landscape":"Landscape","ly.img.plugin-ai-generation-web.defaults.property.background.auto":"Auto","ly.img.plugin-ai-generation-web.defaults.property.background.transparent":"Transparent","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.1:1":"1:1 (Square)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.16:9":"16:9 (Widescreen)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.9:16":"9:16 (Vertical)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.4:3":"4:3","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.3:4":"3:4","ly.img.plugin-ai-generation-web.defaults.property.resolution.720p":"720p HD","ly.img.plugin-ai-generation-web.defaults.property.resolution.1080p":"1080p Full HD"};function yt(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function ht(e,t,r,i){let n={},o=(l,u)=>`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${l}${u?`.${u}`:""}`,a=l=>"x-imgly-enum-labels"in l&&typeof l["x-imgly-enum-labels"]=="object"?l["x-imgly-enum-labels"]:{},s=(l,u,d)=>{l.forEach(f=>{let g=String(f),m=d[g]||yt(g);n[o(u,g)]=m})};e.forEach(l=>{if(l.schema?.title&&(n[o(l.id)]=l.schema.title),l.schema?.enum){let u=a(l.schema);s(l.schema.enum,l.id,u)}if(l.schema?.anyOf&&Array.isArray(l.schema.anyOf)){let u=a(l.schema);l.schema.anyOf.forEach(d=>{let f=d;if(f.enum&&Array.isArray(f.enum))s(f.enum,l.id,u);else if(f.$ref){let g=f.$ref.split("/").pop();g&&u[g]&&(n[o(l.id,g)]=u[g])}else if(f.title){let g=f.title,m=u[g]||yt(g);n[o(l.id,g)]=m}})}});let c={...fo,...n};Object.keys(c).length>0&&P(r.cesdk,{en:c})}function bt(e){return typeof e.document=="function"?e.document():e.document}function vt(e,t,r){let i=no(e),n=zt(i,t.inputReference);if(!ao(n,r))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let o=n,a=Rt(o,t);return{inputSchema:o,properties:a}}function wt(e,t,r,{options:i,provider:n,config:o,providerConfig:a},s){let{id:c}=n;return l=>{let{builder:u}=l,d=[];u.Section(`${c}.schema.section`,{children:()=>{t.forEach(p=>{let y=po(l,p,n,r,i,o,n.kind,a);y!=null&&(Array.isArray(y)?d.push(...y):d.push(y))})}});let f=d.map(p=>p()),g=p=>p.type==="object"?Object.entries(p.value).reduce((y,[v,I])=>(y[v]=g(I),y),{}):p.value,m=f.reduce((p,y)=>(p[y.id]=g(y),p),{});Dt(l,n,s,()=>({input:m}),()=>r.getBlockInput(m),{...i,requiredInputs:e.required,createPlaceholderBlock:r.userFlow==="placeholder"},o)}}async function mo(e,t){let{options:r,provider:i,panelInput:n,config:o}=e,{id:a}=i;if(n==null)return;let s=n;o.debug&&console.log(`Provider: ${a} (schema-based)`);let c=bt(s);if(!(c instanceof Promise)){let{inputSchema:g,properties:m}=vt(c,s,o.debug);return ht(m,i,r,i.kind),wt(g,m,s,e,t)}let l=null,u=null,d=`${a}.schema.loading`;function f(){l=null,u=null,r.cesdk.ui.experimental.setGlobalStateValue(d,!0),Promise.resolve(bt(s)).then(g=>{let{inputSchema:m,properties:p}=vt(g,s,o.debug);ht(p,i,r,i.kind),u=wt(m,p,s,e,t)}).catch(g=>{l=g instanceof Error?g:new Error(String(g))}).finally(()=>{r.cesdk.ui.experimental.setGlobalStateValue(d,!1)})}return f(),g=>{let{builder:m}=g;if(u!=null){u(g);return}if(l!=null){m.Section(`${a}.schema.error`,{children:()=>{m.Text(`${a}.schema.error.title`,{content:"ly.img.plugin-ai-generation-web.schema.error.title"}),m.Text(`${a}.schema.error.details`,{content:l.message}),m.Button(`${a}.schema.error.retry`,{label:"ly.img.plugin-ai-generation-web.schema.error.retry",onClick:()=>{f()}})}});return}m.Section(`${a}.schema.loading`,{children:()=>{m.B