@imgly/plugin-ai-video-generation-web 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { Output } from '@imgly/plugin-ai-generation-web';
1
2
  import { type PluginConfiguration } from './types';
2
- declare const Plugin: (pluginConfiguration: PluginConfiguration) => {
3
+ import { DEFAULT_VIDEO_QUICK_ACTION_ORDER } from './constants';
4
+ declare const Plugin: <I, O extends Output>(pluginConfiguration: PluginConfiguration<I, O>) => {
3
5
  initialize: (context: import("@cesdk/engine").EnginePluginContext & {
4
6
  cesdk?: import("@cesdk/cesdk-js").default;
5
7
  }) => void;
@@ -7,3 +9,4 @@ declare const Plugin: (pluginConfiguration: PluginConfiguration) => {
7
9
  version: string;
8
10
  };
9
11
  export default Plugin;
12
+ export { DEFAULT_VIDEO_QUICK_ACTION_ORDER };
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
- var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=i?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=i?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let i=indexedDB.open(this.dbName,this.dbVersion);i.onerror=n=>{t(new Error(`Failed to open IndexedDB: ${n.target.error}`))},i.onupgradeneeded=n=>{let a=n.target.result;a.objectStoreNames.contains(this.assetStoreName)||a.createObjectStore(this.assetStoreName,{keyPath:"id"}),a.objectStoreNames.contains(this.blobStoreName)||a.createObjectStore(this.blobStoreName,{keyPath:"id"})},i.onsuccess=n=>{this.db=n.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,s)=>{let u=e.locale??"en",d="",p=[];s.label!=null&&typeof s.label=="object"&&s.label[u]&&(d=s.label[u]),s.tags!=null&&typeof s.tags=="object"&&s.tags[u]&&(p=s.tags[u]);let m={...s,label:d,tags:p};return this.filterAsset(m,e)&&c.push(m),c},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:i,perPage:n}=e,a=i*n,o=a+n,r=t.slice(a,o),l=o<t.length?i+1:void 0;return{assets:r,currentPage:i,nextPage:l,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 i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let n=new Set;i.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(r=>n.add(r))});let a=[...n];e(a)},i.onerror=()=>{t(new Error(`Failed to get groups: ${i.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),i=t.objectStore(this.assetStoreName),n=new Set;T(e,o=>{n.add(o)}),setTimeout(()=>{this.storeBlobUrls([...n])});let a={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};i.put(a),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 i=this.db.transaction(this.assetStoreName,"readwrite");i.objectStore(this.assetStoreName).delete(e),i.oncomplete=()=>{T(t,n=>{this.removeBlob(n)}),this.engine.asset.assetSourceContentsChanged(this.id)},i.onerror=()=>{console.error(`Failed to remove asset: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}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,i)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let a=n.result;a.sort((o,r)=>{let l=o.meta?.insertedAt||o._insertedAt||Date.now(),c=r.meta?.insertedAt||r._insertedAt||Date.now();return e==="asc"?l-c:c-l}),t(a)},n.onerror=()=>{i(new Error(`Failed to get assets: ${n.error}`))}})}async getAsset(e){return new Promise((t,i)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{i(new Error(`Failed to get blob: ${n.error}`))}})}async getBlob(e){return new Promise((t,i)=>{let n=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{i(new Error(`Failed to get blob: ${n.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 i=>{let n=await(await fetch(i)).blob();t[i]=n})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let i=this.db.transaction(this.blobStoreName,"readwrite"),n=i.objectStore(this.blobStoreName);Object.entries(t).forEach(([a,o])=>{let r={id:a,blob:o};n.put(r)}),i.onerror=()=>{console.error(`Failed to add blobs: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}async restoreBlobUrls(e){let t={},i=new Set;return T(e,n=>{i.add(n)}),await Promise.all([...i].map(async n=>{let a=await this.createBlobUrlFromStore(n);t[n]=a})),T(e,n=>t[n]??n)}filterAsset(e,t){let{query:i,tags:n,groups:a,excludeGroups:o}=t;if(i&&i.trim()!==""){let r=i.trim().toLowerCase().split(" "),l=e.label?.toLowerCase()??"",c=e.tags?.map(s=>s.toLowerCase())??[];if(!r.every(s=>l.includes(s)||c.some(u=>u.includes(s))))return!1}if(n){let r=Array.isArray(n)?n:[n];if(r.length>0&&(!e.tags||!r.every(l=>e.tags?.includes(l))))return!1}return!(a&&a.length>0&&(!e.groups||!a.some(r=>e.groups?.includes(r)))||o&&o.length>0&&e.groups&&e.groups.some(r=>o.includes(r)))}sortAssets(e,t){let{sortingOrder:i,sortKey:n,sortActiveFirst:a}=t,o=[...e];return!i||i==="None"||(n?o.sort((r,l)=>{let c,s;return n==="id"?(c=r.id,s=l.id):(c=r.meta?.[n]??null,s=l.meta?.[n]??null),c==null?i==="Ascending"?-1:1:s==null?i==="Ascending"?1:-1:typeof c=="string"&&typeof s=="string"?i==="Ascending"?c.localeCompare(s):s.localeCompare(c):i==="Ascending"?c<s?-1:c>s?1:0:c>s?-1:c<s?1:0}):i==="Descending"&&o.reverse(),a&&o.sort((r,l)=>r.active&&!l.active?-1:!r.active&&l.active?1:0)),o}};function T(e,t,i=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let n=0;n<e.length;n++){let a=i?`${i}[${n}]`:`[${n}]`;if(typeof e[n]=="string"&&e[n].startsWith("blob:")){let o=t(e[n],a);typeof o=="string"&&(e[n]=o)}else e[n]=T(e[n],t,a)}return e}for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let a=e[n],o=i?`${i}.${n}`:n;if(typeof a=="string"&&a.startsWith("blob:")){let r=t(a,o);typeof r=="string"&&(e[n]=r)}else e[n]=T(a,t,o)}return e}var st=class{constructor(e,t){this.engine=e,this.key=t}hasData(e){return this.engine.block.isValid(e)&&this.engine.block.hasMetadata(e,this.key)}get(e){if(this.hasData(e))return JSON.parse(this.engine.block.getMetadata(e,this.key))}set(e,t){this.engine.block.setMetadata(e,this.key,JSON.stringify(t))}clear(e){this.engine.block.hasMetadata(e,this.key)&&this.engine.block.removeMetadata(e,this.key)}},De=st,ct=typeof global=="object"&&global&&global.Object===Object&&global,Oe=ct,ut=typeof self=="object"&&self&&self.Object===Object&&self,dt=Oe||ut||Function("return this")(),E=dt,pt=E.Symbol,L=pt,Pe=Object.prototype,gt=Pe.hasOwnProperty,mt=Pe.toString,U=L?L.toStringTag:void 0;function yt(e){var t=gt.call(e,U),i=e[U];try{e[U]=void 0;var n=!0}catch{}var a=mt.call(e);return n&&(t?e[U]=i:delete e[U]),a}var bt=yt,ft=Object.prototype,ht=ft.toString;function kt(e){return ht.call(e)}var vt=kt,wt="[object Null]",At="[object Undefined]",fe=L?L.toStringTag:void 0;function It(e){return e==null?e===void 0?At:wt:fe&&fe in Object(e)?bt(e):vt(e)}var R=It;function Ct(e){return e!=null&&typeof e=="object"}var ue=Ct,$o=Array.isArray;function xt(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var _e=xt,Mt="[object AsyncFunction]",Et="[object Function]",St="[object GeneratorFunction]",$t="[object Proxy]";function jt(e){if(!_e(e))return!1;var t=R(e);return t==Et||t==St||t==Mt||t==$t}var Tt=jt,Lt=E["__core-js_shared__"],X=Lt,he=function(){var e=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Nt(e){return!!he&&he in e}var Dt=Nt,Ot=Function.prototype,Pt=Ot.toString;function _t(e){if(e!=null){try{return Pt.call(e)}catch{}try{return e+""}catch{}}return""}var $=_t,zt=/[\\^$.*+?()[\]{}|]/g,Ut=/^\[object .+?Constructor\]$/,qt=Function.prototype,Bt=Object.prototype,Vt=qt.toString,Ft=Bt.hasOwnProperty,Qt=RegExp("^"+Vt.call(Ft).replace(zt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gt(e){if(!_e(e)||Dt(e))return!1;var t=Tt(e)?Qt:Ut;return t.test($(e))}var Rt=Gt;function Yt(e,t){return e?.[t]}var Ht=Yt;function Zt(e,t){var i=Ht(e,t);return Rt(i)?i:void 0}var D=Zt,Wt=D(E,"WeakMap"),re=Wt;function Kt(e,t){return e===t||e!==e&&t!==t}var Jt=Kt,Xt=9007199254740991;function en(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Xt}var tn=en,jo=Object.prototype,nn="[object Arguments]";function rn(e){return ue(e)&&R(e)==nn}var ke=rn,ze=Object.prototype,on=ze.hasOwnProperty,an=ze.propertyIsEnumerable,To=ke(function(){return arguments}())?ke:function(e){return ue(e)&&on.call(e,"callee")&&!an.call(e,"callee")},Ue=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ve=Ue&&typeof module=="object"&&module&&!module.nodeType&&module,ln=ve&&ve.exports===Ue,we=ln?E.Buffer:void 0,Lo=we?we.isBuffer:void 0,sn="[object Arguments]",cn="[object Array]",un="[object Boolean]",dn="[object Date]",pn="[object Error]",gn="[object Function]",mn="[object Map]",yn="[object Number]",bn="[object Object]",fn="[object RegExp]",hn="[object Set]",kn="[object String]",vn="[object WeakMap]",wn="[object ArrayBuffer]",An="[object DataView]",In="[object Float32Array]",Cn="[object Float64Array]",xn="[object Int8Array]",Mn="[object Int16Array]",En="[object Int32Array]",Sn="[object Uint8Array]",$n="[object Uint8ClampedArray]",jn="[object Uint16Array]",Tn="[object Uint32Array]",A={};A[In]=A[Cn]=A[xn]=A[Mn]=A[En]=A[Sn]=A[$n]=A[jn]=A[Tn]=!0;A[sn]=A[cn]=A[wn]=A[un]=A[An]=A[dn]=A[pn]=A[gn]=A[mn]=A[yn]=A[bn]=A[fn]=A[hn]=A[kn]=A[vn]=!1;function Ln(e){return ue(e)&&tn(e.length)&&!!A[R(e)]}var Nn=Ln;function Dn(e){return function(t){return e(t)}}var On=Dn,qe=typeof exports=="object"&&exports&&!exports.nodeType&&exports,F=qe&&typeof module=="object"&&module&&!module.nodeType&&module,Pn=F&&F.exports===qe,ee=Pn&&Oe.process,_n=function(){try{var e=F&&F.require&&F.require("util").types;return e||ee&&ee.binding&&ee.binding("util")}catch{}}(),Ae=_n,Ie=Ae&&Ae.isTypedArray,No=Ie?On(Ie):Nn,zn=Object.prototype,Do=zn.hasOwnProperty;function Un(e,t){return function(i){return e(t(i))}}var qn=Un,Oo=qn(Object.keys,Object),Bn=Object.prototype,Po=Bn.hasOwnProperty,Vn=D(Object,"create"),Q=Vn;function Fn(){this.__data__=Q?Q(null):{},this.size=0}var Qn=Fn;function Gn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Rn=Gn,Yn="__lodash_hash_undefined__",Hn=Object.prototype,Zn=Hn.hasOwnProperty;function Wn(e){var t=this.__data__;if(Q){var i=t[e];return i===Yn?void 0:i}return Zn.call(t,e)?t[e]:void 0}var Kn=Wn,Jn=Object.prototype,Xn=Jn.hasOwnProperty;function ei(e){var t=this.__data__;return Q?t[e]!==void 0:Xn.call(t,e)}var ti=ei,ni="__lodash_hash_undefined__";function ii(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=Q&&t===void 0?ni:t,this}var ri=ii;function O(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}O.prototype.clear=Qn;O.prototype.delete=Rn;O.prototype.get=Kn;O.prototype.has=ti;O.prototype.set=ri;var Ce=O;function oi(){this.__data__=[],this.size=0}var ai=oi;function li(e,t){for(var i=e.length;i--;)if(Jt(e[i][0],t))return i;return-1}var W=li,si=Array.prototype,ci=si.splice;function ui(e){var t=this.__data__,i=W(t,e);if(i<0)return!1;var n=t.length-1;return i==n?t.pop():ci.call(t,i,1),--this.size,!0}var di=ui;function pi(e){var t=this.__data__,i=W(t,e);return i<0?void 0:t[i][1]}var gi=pi;function mi(e){return W(this.__data__,e)>-1}var yi=mi;function bi(e,t){var i=this.__data__,n=W(i,e);return n<0?(++this.size,i.push([e,t])):i[n][1]=t,this}var fi=bi;function P(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}P.prototype.clear=ai;P.prototype.delete=di;P.prototype.get=gi;P.prototype.has=yi;P.prototype.set=fi;var K=P,hi=D(E,"Map"),G=hi;function ki(){this.size=0,this.__data__={hash:new Ce,map:new(G||K),string:new Ce}}var vi=ki;function wi(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Ai=wi;function Ii(e,t){var i=e.__data__;return Ai(t)?i[typeof t=="string"?"string":"hash"]:i.map}var J=Ii;function Ci(e){var t=J(this,e).delete(e);return this.size-=t?1:0,t}var xi=Ci;function Mi(e){return J(this,e).get(e)}var Ei=Mi;function Si(e){return J(this,e).has(e)}var $i=Si;function ji(e,t){var i=J(this,e),n=i.size;return i.set(e,t),this.size+=i.size==n?0:1,this}var Ti=ji;function _(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}_.prototype.clear=vi;_.prototype.delete=xi;_.prototype.get=Ei;_.prototype.has=$i;_.prototype.set=Ti;var Be=_;function Li(){this.__data__=new K,this.size=0}var Ni=Li;function Di(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i}var Oi=Di;function Pi(e){return this.__data__.get(e)}var _i=Pi;function zi(e){return this.__data__.has(e)}var Ui=zi,qi=200;function Bi(e,t){var i=this.__data__;if(i instanceof K){var n=i.__data__;if(!G||n.length<qi-1)return n.push([e,t]),this.size=++i.size,this;i=this.__data__=new Be(n)}return i.set(e,t),this.size=i.size,this}var Vi=Bi;function Y(e){var t=this.__data__=new K(e);this.size=t.size}Y.prototype.clear=Ni;Y.prototype.delete=Oi;Y.prototype.get=_i;Y.prototype.has=Ui;Y.prototype.set=Vi;var Fi=Object.prototype,_o=Fi.propertyIsEnumerable,Qi=D(E,"DataView"),oe=Qi,Gi=D(E,"Promise"),ae=Gi,Ri=D(E,"Set"),le=Ri,xe="[object Map]",Yi="[object Object]",Me="[object Promise]",Ee="[object Set]",Se="[object WeakMap]",$e="[object DataView]",Hi=$(oe),Zi=$(G),Wi=$(ae),Ki=$(le),Ji=$(re),j=R;(oe&&j(new oe(new ArrayBuffer(1)))!=$e||G&&j(new G)!=xe||ae&&j(ae.resolve())!=Me||le&&j(new le)!=Ee||re&&j(new re)!=Se)&&(j=function(e){var t=R(e),i=t==Yi?e.constructor:void 0,n=i?$(i):"";if(n)switch(n){case Hi:return $e;case Zi:return xe;case Wi:return Me;case Ki:return Ee;case Ji:return Se}return t});var zo=E.Uint8Array,Xi="__lodash_hash_undefined__";function er(e){return this.__data__.set(e,Xi),this}var tr=er;function nr(e){return this.__data__.has(e)}var ir=nr;function se(e){var t=-1,i=e==null?0:e.length;for(this.__data__=new Be;++t<i;)this.add(e[t])}se.prototype.add=se.prototype.push=tr;se.prototype.has=ir;var je=L?L.prototype:void 0,Uo=je?je.valueOf:void 0,rr=Object.prototype,qo=rr.hasOwnProperty,or=Object.prototype,Bo=or.hasOwnProperty,Vo=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Fo=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Qo=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ar(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}async function Ve(e,t){if(e.startsWith("buffer:")){let i=await t.editor.getMimeType(e),n=t.editor.getBufferLength(e),a=t.editor.getBufferData(e,0,n),o=new Blob([a],{type:i});return URL.createObjectURL(o)}else return e}async function ce(e,t){let i=await Ve(e,t);return new Promise((n,a)=>{let o=new Image;o.onload=()=>{n({width:o.width,height:o.height})},o.onerror=a,o.src=i})}async function lr(e,t,i){let n,a=t.block.getFill(e),o=t.block.getSourceSet(a,"fill/image/sourceSet"),[r]=o;if(r==null){if(n=t.block.getString(a,"fill/image/imageFileURI"),n==null)throw new Error("No image source/uri found")}else n=r.uri;if(i?.throwErrorIfSvg&&await t.editor.getMimeType(n)==="image/svg+xml")throw new Error("SVG images are not supported");return Ve(n,t)}function Fe(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let i=t.substring(2).split("/"),n=e;for(let a of i){if(n==null)throw new Error(`Invalid reference path: ${t}`);n=n[a]}if(n===void 0)throw new Error(`Reference not found: ${t}`);return n}function B(e,t,i=new Set){if(t==null||i.has(t))return t;if(i.add(t),t.$ref&&typeof t.$ref=="string"){let n=Fe(e,t.$ref),a={...B(e,n,i)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(a[o]=B(e,t[o],i));return a}if(Array.isArray(t))return t.map(n=>B(e,n,i));if(typeof t=="object"){let n={};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&(n[a]=B(e,t[a],i));return n}return t}function sr(e){return B(e,{...e})}function cr(e,t=!1){let i=r=>(t&&console.log(`OpenAPI Schema validation failed: ${r}`),!1);if(typeof e!="object"||e===null)return i(`Input is ${e===null?"null":typeof e}, not an object`);let n=e;if(!(typeof n.type=="string"||Array.isArray(n.enum)||typeof n.properties=="object"||typeof n.items=="object"||typeof n.allOf=="object"||typeof n.anyOf=="object"||typeof n.oneOf=="object"||typeof n.not=="object"))return i("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(n.type!==void 0){let r=["string","number","integer","boolean","array","object","null"];if(typeof n.type=="string"){if(!r.includes(n.type))return i(`Invalid type: ${n.type}. Must be one of ${r.join(", ")}`)}else if(Array.isArray(n.type)){for(let l of n.type)if(typeof l!="string"||!r.includes(l))return i(`Array of types contains invalid value: ${l}. Must be one of ${r.join(", ")}`)}else return i(`Type must be a string or array of strings, got ${typeof n.type}`)}if(n.items!==void 0&&(typeof n.items!="object"||n.items===null))return i(`Items must be an object, got ${n.items===null?"null":typeof n.items}`);if(n.properties!==void 0&&(typeof n.properties!="object"||n.properties===null))return i(`Properties must be an object, got ${n.properties===null?"null":typeof n.properties}`);let a=["allOf","anyOf","oneOf"];for(let r of a)if(n[r]!==void 0){if(!Array.isArray(n[r]))return i(`${r} must be an array, got ${typeof n[r]}`);for(let l=0;l<n[r].length;l++){let c=n[r][l];if(typeof c!="object"||c===null)return i(`Item ${l} in ${r} must be an object, got ${c===null?"null":typeof c}`)}}if(n.not!==void 0&&(typeof n.not!="object"||n.not===null))return i(`'not' must be an object, got ${n.not===null?"null":typeof n.not}`);if(n.additionalProperties!==void 0&&typeof n.additionalProperties!="boolean"&&(typeof n.additionalProperties!="object"||n.additionalProperties===null))return i(`additionalProperties must be a boolean or an object, got ${n.additionalProperties===null?"null":typeof n.additionalProperties}`);if(n.format!==void 0&&typeof n.format!="string")return i(`format must be a string, got ${typeof n.format}`);let o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let r of o)if(n[r]!==void 0&&typeof n[r]!="number")return i(`${r} must be a number, got ${typeof n[r]}`);if(n.minLength!==void 0&&(typeof n.minLength!="number"||n.minLength<0))return i(`minLength must be a non-negative number, got ${typeof n.minLength=="number"?n.minLength:typeof n.minLength}`);if(n.maxLength!==void 0&&(typeof n.maxLength!="number"||n.maxLength<0))return i(`maxLength must be a non-negative number, got ${typeof n.maxLength=="number"?n.maxLength:typeof n.maxLength}`);if(n.pattern!==void 0&&typeof n.pattern!="string")return i(`pattern must be a string, got ${typeof n.pattern}`);if(n.minItems!==void 0&&(typeof n.minItems!="number"||n.minItems<0))return i(`minItems must be a non-negative number, got ${typeof n.minItems=="number"?n.minItems:typeof n.minItems}`);if(n.maxItems!==void 0&&(typeof n.maxItems!="number"||n.maxItems<0))return i(`maxItems must be a non-negative number, got ${typeof n.maxItems=="number"?n.maxItems:typeof n.maxItems}`);if(n.uniqueItems!==void 0&&typeof n.uniqueItems!="boolean")return i(`uniqueItems must be a boolean, got ${typeof n.uniqueItems}`);if(n.minProperties!==void 0&&(typeof n.minProperties!="number"||n.minProperties<0))return i(`minProperties must be a non-negative number, got ${typeof n.minProperties=="number"?n.minProperties:typeof n.minProperties}`);if(n.maxProperties!==void 0&&(typeof n.maxProperties!="number"||n.maxProperties<0))return i(`maxProperties must be a non-negative number, got ${typeof n.maxProperties=="number"?n.maxProperties:typeof n.maxProperties}`);if(n.required!==void 0){if(!Array.isArray(n.required))return i(`required must be an array, got ${typeof n.required}`);for(let r=0;r<n.required.length;r++){let l=n.required[r];if(typeof l!="string")return i(`Item ${r} in required array must be a string, got ${typeof l}`)}}return!0}function ur(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=[];return dr(e,t).forEach(a=>{let o=a,r=i[a]??void 0;n.push({id:o,schema:r})}),n}function dr(e,t){let i=t.order;if(i!=null&&Array.isArray(i))return i;if(e.properties==null)throw new Error("Input schema must have properties");let n=e.properties,a=Object.keys(n),o=pr(e,t)??a;return i!=null&&typeof i=="function"&&(o=i(o)),[...new Set(o)]}function pr(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 i=(typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword).find(n=>n in e);return i==null?void 0:e[i]}var Qe=ur,gr="ly.img.ai",te="ly.img.ai/temp";async function mr(e,t){return e.engine.asset.findAllSources().includes(te)||e.engine.asset.addLocalSource(te),e.engine.asset.apply(te,t)}function Ge(e){return`${gr}/${e}`}function yr(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 i=e;return"message"in i&&typeof i.message=="string"?i.message:"cause"in i&&typeof i.cause=="string"?i.cause:"detail"in i&&typeof i.detail=="object"&&i.detail!==null&&"message"in i.detail&&typeof i.detail.message=="string"?i.detail.message:"error"in i&&typeof i.error=="object"&&i.error!==null&&"message"in i.error&&typeof i.error.message=="string"?i.error.message:t}return typeof e=="string"?e:String(e)||t}function br(){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 fr(e,t=0,i="image/jpeg",n=.8){return new Promise((a,o)=>{try{let r=document.createElement("video");r.crossOrigin="anonymous",r.style.display="none",r.addEventListener("loadedmetadata",()=>{r.currentTime=Math.min(t,r.duration),r.addEventListener("seeked",()=>{let l=document.createElement("canvas");l.width=r.videoWidth,l.height=r.videoHeight;let c=l.getContext("2d");if(!c){document.body.removeChild(r),o(new Error("Failed to create canvas context"));return}c.drawImage(r,0,0,l.width,l.height);try{let s=l.toDataURL(i,n);document.body.removeChild(r),a(s)}catch(s){document.body.removeChild(r),o(new Error(`Failed to create thumbnail: ${s instanceof Error?s.message:String(s)}`))}},{once:!0})}),r.addEventListener("error",()=>{document.body.removeChild(r),o(new Error(`Failed to load video from ${e}`))}),r.src=e,document.body.appendChild(r)}catch(r){o(r)}})}function Re(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 de(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 N(e){return e instanceof Error&&e.name==="AbortError"}function Ye(e,t,i,n,a,o){if(t.schema==null)return n.renderCustomProperty!=null&&n.renderCustomProperty[t.id]!=null?n.renderCustomProperty[t.id](e,t):void 0;let r=t,l=t.schema.type;if(n.renderCustomProperty!=null&&n.renderCustomProperty[t.id]!=null)return n.renderCustomProperty[t.id](e,t);switch(l){case"string":return t.schema.enum!=null?hr(e,r,i,n,a,o):Ze(e,r,i,n,a,o);case"boolean":return We(e,r,i,n,a,o);case"number":case"integer":return Ke(e,r,i,n,a,o);case"object":return He(e,r,i,n,a,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return kr(e,r,i,n,a,o);break}default:console.error(`Unsupported property type: ${l}`)}}function He(e,t,i,n,a,o){let r=Qe(t.schema??{},n).reduce((l,c)=>{let s=Ye(e,c,i,n,a,o);return s!=null&&(l[c.id]=s()),l},{});return()=>({id:t.id,type:"object",value:r})}function Ze(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=l(s,t.schema.default??""),p=vr(t.schema),m=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return r[m](s,{inputLabel:u,placeholder:a.i18n?.prompt,...d}),()=>({id:t.id,type:"string",value:d.value})}function hr(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,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"]:{},m=(t.schema.enum??[]).map(h=>({id:h,label:d[h]??Re(h),icon:p[h]})),b=t.schema.default!=null?m.find(h=>h.id===t.schema.default)??m[0]:m[0],w=l(s,b);return r.Select(s,{inputLabel:u,values:m,...w}),()=>({id:t.id,type:"string",value:w.value.id})}function We(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=!!t.schema.default,p=l(s,d);return r.Checkbox(s,{inputLabel:u,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function Ke(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=t.schema.minimum,p=t.schema.maximum,m=t.schema.default;m==null&&(d!=null?m=d:p!=null?m=p:m=0);let b=l(s,m);if(d!=null&&p!=null){let w=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(w=t.schema["x-imgly-step"]),r.Slider(s,{inputLabel:u,min:d,max:p,step:w,...b})}else r.NumberInput(s,{inputLabel:u,min:d,max:p,...b});return()=>({id:t.id,type:"integer",value:b.value})}function kr(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=t.schema.anyOf??[],p=[],m={},b={};d.forEach((g,k)=>{let y=g.title??"common.custom",f=`${i.id}.${c}.anyOf[${k}]`,v="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},I="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};g.type==="string"?g.enum!=null?g.enum.forEach(C=>{p.push({id:C,label:v[C]??Re(C),icon:I[C]})}):(m[f]=()=>Ze(e,{id:f,schema:{...g,title:y}},i,n,a,o),p.push({id:f,label:v[y]??y,icon:I[y]})):g.type==="boolean"?(m[f]=()=>We(e,{id:f,schema:{...g,title:y}},i,n,a,o),p.push({id:f,label:v[y]??y,icon:I[y]})):g.type==="integer"?(m[f]=()=>Ke(e,{id:f,schema:{...g,title:y}},i,n,a,o),p.push({id:f,label:v[y]??y,icon:I[y]})):g.type==="array"||g.type==="object"&&(m[f]=()=>He(e,{id:f,schema:{...g,title:y}},i,n,a,o),p.push({id:f,label:v[y]??y,icon:I[y]}))});let w=t.schema.default!=null?p.find(g=>g.id===t.schema.default)??p[0]:p[0],h=l(s,w);if(r.Select(s,{inputLabel:u,values:p,...h}),h.value.id in m){let g=m[h.value.id]();b[h.value.id]=g}return()=>{let g=b[h.value.id];return g!=null?{...g(),id:t.id}:{id:t.id,type:"string",value:h.value.id}}}function vr(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var wr=Ye,Ar="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Je=Ar;function Ir(e,t,i){switch(t){case"image":return Cr(e,i[t]);case"video":return xr(e,i[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Cr(e,t){let i=t.width,n=t.height;return{id:e,meta:{previewUri:Je,fillType:"//ly.img.ubq/fill/image",kind:"image",width:i,height:n}}}function xr(e,t){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{previewUri:Je,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}var Mr=Ir;async function Er(e,t,i,n){switch(t){case"image":{if(n.kind!=="image")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: image)`);return Sr(e,i[t],n)}case"video":{if(n.kind!=="video")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: video)`);return $r(e,i[t],n)}case"audio":{if(n.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: audio)`);return jr(e,i[t],n)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Sr(e,t,i){let n=t.width,a=t.height;return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:a},payload:{sourceSet:[{uri:i.url,width:n,height:a}]}}}async function $r(e,t,i){let n=t.width,a=t.height,o=await fr(i.url,0);return{id:e,label:t.label,meta:{uri:i.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:a}}}function jr(e,t,i){return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:i.duration.toString()}}}var Te=Er;function Xe(e){let t=e.filter(i=>!!i);return i=>async(n,a)=>{let o=[],r=s=>{o.push(s)},l=async(s,u,d)=>{if(s>=t.length)return i(u,d);let p=t[s],m=async(w,h)=>l(s+1,w,h),b={...d,addDisposer:r};return p(u,b,m)},c={...a,addDisposer:r};return{result:await l(0,n,c),dispose:async()=>{for(let s=o.length-1;s>=0;s--)try{await o[s]()}catch(u){console.error("Error in disposer:",u)}o.length=0}}}}function Tr(){return async(e,t,i)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(e,null,2));let n,a=Date.now();try{return n=await i(e,t),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-a}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var et=Tr;function Lr(e){return async(t,i)=>(console.log(`[DRY RUN]: Requesting dummy AI generation for kind '${e.kind}' with inputs: `,JSON.stringify(t,void 0,2)),await Pr(2e3),await Nr(t,e,i))}async function Nr(e,t,i){switch(t.kind){case"image":return Dr(e,t,i);case"video":return Or(e,t,i);default:throw new Error(`Unsupported output kind for creating dry run output: ${t.kind}`)}}async function Dr(e,t,{engine:i}){let n,a,o=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image",r=o.match(/(\d+)x(\d+)/);if(r!=null)n=parseInt(r[1],10),a=parseInt(r[2],10);else if(t.blockInputs!=null&&(n=t.blockInputs.image.width,a=t.blockInputs.image.height),t.blockIds!=null&&Array.isArray(t.blockIds)&&t.blockIds.length>0){let[l]=t.blockIds,c=await lr(l,i),s=await ce(c,i);n=s.width,a=s.height}else n=512,a=512;return{kind:"image",url:`https://placehold.co/${n}x${a}/000000/FFF?text=${o.replace(" ","+").replace(`
2
- `,"+")}`}}async function Or(e,t,i){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function Pr(e){return new Promise(t=>{setTimeout(t,e)})}var tt=Lr;async function _r(e,t,i,n,a,o,r){let{cesdk:l,createPlaceholderBlock:c,historyAssetSourceId:s}=a,u;try{o.debug&&console.group(`Starting Generation for '${e}'`);let d=t(),p=await i(d.input),m=br(),b;if(c){if(b=Mr(m,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(b,void 0,2)),u=await mr(l,b),u!=null&&n.kind==="video"){let k=l.engine.block.getPositionX(u),y=l.engine.block.getPositionY(u),f=l.engine.block.duplicate(u);l.engine.block.setPositionX(f,k),l.engine.block.setPositionY(f,y),l.engine.block.destroy(u),u=f}if(Z(l,r,u))return{status:"aborted"};if(u==null)throw new Error("Could not create placeholder block");l.engine.block.setState(u,{type:"Pending",progress:0})}let w=Xe([...n.output.middleware??[],o.debug?et():void 0,o.dryRun?tt({kind:n.kind,blockInputs:p}):void 0]),{result:h}=await w(n.output.generate)(d.input,{abortSignal:r,engine:a.engine,cesdk:l});if(de(h))throw new Error("Streaming generation is not supported yet from a panel");if(Z(l,r,u))return{status:"aborted"};if(h==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(h,void 0,2));let g;if(u!=null&&l.engine.block.isValid(u)&&(g=await Te(m,e,p,h),o.debug&&console.log("Updating asset in scene:",JSON.stringify(g,void 0,2)),await l.engine.asset.defaultApplyAssetToBlock(g,u)),Z(l,r,u))return{status:"aborted"};if(s!=null){if(g==null&&(g=await Te(m,e,p,h),Z(l,r,u)))return{status:"aborted"};let k={...g,id:`${Date.now()}-${g.id}`,label:g.label!=null?{en:g.label}:{},tags:{}};l.engine.asset.addAssetToSource(s,k)}return u!=null&&l.engine.block.isValid(u)&&l.engine.block.setState(u,{type:"Ready"}),{status:"success",output:h}}catch(d){throw u!=null&&l.engine.block.isValid(u)&&(N(d)?l.engine.block.destroy(u):l.engine.block.setState(u,{type:"Error",error:"Unknown"})),d}finally{o.debug&&console.groupEnd()}}function Z(e,t,i){return t.aborted?(i!=null&&e.engine.block.isValid(i)&&e.engine.block.destroy(i),!0):!1}var zr=_r;function Ur(e,t,i){let{cesdk:n,provider:a,getInput:o}=t;i.onError!=null&&typeof i.onError=="function"?i.onError(e):(console.error("Generation failed:",e),qr(n,a.output.notification,()=>({input:o?.().input,error:e}))||n.ui.showNotification({type:"error",message:yr(e)}))}function qr(e,t,i){let n=t?.error;if(n==null||!(typeof n.show=="function"?n.show(i()):n.show))return!1;let a=typeof n.message=="function"?n.message(i()):n.message??"common.ai-generation.failed",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(i()):n.action.label,onClick:()=>{n?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"error",message:a,action:o}),!0}var V=Ur;function H(e){return`${e}.generating`}function Br(e){return`${e}.abort`}function Vr(e,t,i,n,a,o){let{builder:r,experimental:l}=e,{cesdk:c,includeHistoryLibrary:s=!0}=a,{id:u,output:{abortable:d}}=t,p=l.global(Br(u),()=>{}),m=l.global(H(u),!1),b,w=m.value&&d,h=()=>{w&&(p.value(),m.setValue(!1),p.setValue(()=>{}))},g;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let y=i();g=a.requiredInputs.every(f=>!y.input[f])}let k=l.global(`${u}.confirmationDialogId`,void 0);r.Section(`${u}.generate.section`,{children:()=>{r.Button(`${u}.generate`,{label:["common.ai-generation.generate",`panel.${u}.generate`],isLoading:m.value,color:"accent",isDisabled:g,suffix:w?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${u}.abort`,"common.cancel"],onClick:()=>{let y=c.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:f})=>{c.ui.closeDialog(f),k.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:f})=>{h(),c.ui.closeDialog(f),k.setValue(void 0)}}});k.setValue(y)}}:void 0,onClick:async()=>{b=new AbortController;let y=b.signal,f=async()=>{try{m.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),b?.abort()});let v=await zr(t.kind,i,n,t,a,o,y);if(v.status==="aborted")return;let I=t.output.notification;Fr(c,I,()=>({input:i().input,output:v.output}))}catch(v){if(N(v))return;V(v,{cesdk:c,provider:t,getInput:i},o)}finally{b=void 0,m.setValue(!1),p.setValue(()=>{}),k.value!=null&&(c.ui.closeDialog(k.value),k.setValue(void 0))}};o.middleware!=null?await o.middleware(f,{provider:t,abort:h}):await f()}}),t.output.generationHintText!=null&&r.Text(`${u}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),s&&a.historyAssetLibraryEntryId!=null&&r.Library(`${u}.history.library`,{entries:[a.historyAssetLibraryEntryId]})}function Fr(e,t,i){let n=t?.success;if(n==null||!(typeof n.show=="function"?n.show(i()):n.show))return!1;let a=typeof n.message=="function"?n.message(i()):n.message??"common.ai-generation.success",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(i()):n.action.label,onClick:()=>{n?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"success",message:a,action:o,duration:n.duration}),!0}var nt=Vr;async function Qr(e,t,i,n){let{cesdk:a}=i,{id:o}=e;n.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let r=sr(t.document),l=Fe(r,t.inputReference);if(!cr(l,n.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let c=l,s=Qe(c,t),u=d=>{let{builder:p}=d,m=[];p.Section(`${o}.schema.section`,{children:()=>{s.forEach(g=>{let k=wr(d,g,e,t,i,n);k!=null&&(Array.isArray(k)?m.push(...k):m.push(k))})}});let b=m.map(g=>g()),w=g=>g.type==="object"?Object.entries(g.value).reduce((k,[y,f])=>(k[y]=w(f),k),{}):g.value,h=b.reduce((g,k)=>(g[k.id]=w(k),g),{});nt(d,e,()=>({input:h}),()=>t.getBlockInput(h),{...i,requiredInputs:c.required,createPlaceholderBlock:t.userFlow==="placeholder"},n)};return a.ui.registerPanel(Ge(o),u),u}var Gr=Qr;async function Rr(e,t,i,n){let{cesdk:a}=i,{id:o}=e,r=t.render,l=c=>{let{state:s}=c,u=s(H(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=r(c,{cesdk:a,isGenerating:u});return nt(c,e,d,p,{...i,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},n),d};return a.ui.registerPanel(Ge(o),l),l}var Yr=Rr,ne="@imgly/plugin-ai-generation",Hr=`
1
+ 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;P(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=()=>{P(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 P(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),P(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 P(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]=P(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]=P(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,O=rr,et=Object.prototype,ir=et.hasOwnProperty,nr=et.toString,H=O?O.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=O?O.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,Cr=Function.prototype,Sr=Cr.toString;function Er(e){if(e!=null){try{return Sr.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,Pr=Lr.hasOwnProperty,Or=RegExp("^"+Nr.call(Pr).replace(Mr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Dr(e){if(!tt(e)||xr(e))return!1;var t=kr(e)?Or:jr;return t.test(M(e))}var $r=Dr;function Tr(e,t){return e?.[t]}var zr=Tr;function Rr(e,t){var r=zr(e,t);return $r(r)?r:void 0}var D=Rr,Fr=D(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,Ci=Q&&Q.exports===nt,fe=Ci&&Xe.process,Si=function(){try{var e=Q&&Q.require&&Q.require("util").types;return e||fe&&fe.binding&&fe.binding("util")}catch{}}(),Ue=Si,Be=Ue&&Ue.isTypedArray,Cu=Be?xi(Be):Ii,Ei=Object.prototype,Su=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=D(Object,"create"),Y=Li;function Ni(){this.__data__=Y?Y(null):{},this.size=0}var Pi=Ni;function Oi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Di=Oi,$i="__lodash_hash_undefined__",Ti=Object.prototype,zi=Ti.hasOwnProperty;function Ri(e){var t=this.__data__;if(Y){var r=t[e];return r===$i?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 $(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])}}$.prototype.clear=Pi;$.prototype.delete=Di;$.prototype.get=Fi;$.prototype.has=Gi;$.prototype.set=Zi;var Ge=$;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=D(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 Cn=xn;function Sn(e){return this.__data__.get(e)}var En=Sn;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=Cn;J.prototype.get=En;J.prototype.has=jn;J.prototype.set=Nn;var Pn=Object.prototype,ju=Pn.propertyIsEnumerable,On=D(A,"DataView"),ve=On,Dn=D(A,"Promise"),we=Dn,$n=D(A,"Set"),ke=$n,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=O?O.prototype:void 0,Lu=We?We.valueOf:void 0,Qn=Object.prototype,Nu=Qn.hasOwnProperty,Yn=Object.prototype,Pu=Yn.hasOwnProperty,Ou=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Du=new RegExp(/[A-Fa-f0-9]{1}/,"g"),$u=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 Ce(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!
2
+ Plugin "${t}" is using version ${r}, but other AI plugins are using version ${o}.
3
+ This may cause compatibility issues. Please ensure all AI plugins (@imgly/plugin-ai-*) use the same version.
4
+ 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==",Se=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:Se,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:Se,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:Se,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 Co(e){switch(e.userFlow){case"placeholder":return Eo(e);case"generation-only":return So(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function So(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(C(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(C(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(C(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(C(t,r))return{status:"aborted"};let s=ut(),u=vo(s,o,a);if(i=await no(t,u),C(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(C(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(C(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),C(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)&&(Ce(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 C(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Mo=Co;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(Ce(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 Po=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 Oo(e){return Z(e,{...e})}function Do(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 $o(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=$o;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=Oo(r.document),s=mt(a,r.inputReference);if(!Do(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 Po(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.entry`;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=`
3
5
  <svg>
4
6
  <symbol
5
7
  fill="none"
@@ -17,7 +19,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
17
19
  fill="none"
18
20
  xmlns="http://www.w3.org/2000/svg"
19
21
  viewBox="0 0 24 24"
20
- id="${ne}/image"
22
+ id="${me}/image"
21
23
  >
22
24
  <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"/>
23
25
  <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"/>
@@ -29,7 +31,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
29
31
  fill="none"
30
32
  xmlns="http://www.w3.org/2000/svg"
31
33
  viewBox="0 0 24 24"
32
- id="${ne}/video"
34
+ id="${me}/video"
33
35
  >
34
36
  <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"/>
35
37
  <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"/>
@@ -40,7 +42,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
40
42
  fill="none"
41
43
  xmlns="http://www.w3.org/2000/svg"
42
44
  viewBox="0 0 24 24"
43
- id="${ne}/audio"
45
+ id="${me}/audio"
44
46
  >
45
47
  <path d="M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z" fill="currentColor"/>
46
48
  <path d="M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z" fill="currentColor"/>
@@ -60,7 +62,8 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
60
62
 
61
63
  </symbol>
62
64
  </svg>
63
- `,Zr=Hr,Le="ly.img.ai.quickAction.order",q="ly.img.ai.quickAction.actions";function Wr(e,t){return{id:t,setQuickActionMenuOrder:i=>{e.ui.experimental.setGlobalStateValue(`${Le}.${t}`,i)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${Le}.${t}`,[]),registerQuickAction:i=>{if(!e.ui.experimental.hasGlobalStateValue(`${q}.${t}`))e.ui.experimental.setGlobalStateValue(`${q}.${t}`,{[i.id]:i});else{let n=e.ui.experimental.getGlobalStateValue(`${q}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${q}.${t}`,{...n,[i.id]:i})}},getQuickAction:i=>e.ui.experimental.getGlobalStateValue(`${q}.${t}`,{})[i]}}var Kr=Wr,ie="ly.img.ai.inference.editMode",it="ly.img.ai.inference.metadata";function rt(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function Jr(e){if(e.length===0)return[];let t=[...e];for(;t.length>0&&t[0]==="ly.img.separator";)t.shift();for(;t.length>0&&t[t.length-1]==="ly.img.separator";)t.pop();return t.reduce((i,n)=>(n==="ly.img.separator"&&i.length>0&&i[i.length-1]==="ly.img.separator"||i.push(n),i),[])}function Xr({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(i,n,a)=>{let o={},r={},l=e||t?n.blockIds??n.engine.block.findAllSelected():[];return l.forEach(c=>{if(n.engine.block.isValid(c)&&e&&(o[c]=n.engine.block.isAlwaysOnTop(c),n.engine.block.setAlwaysOnTop(c,!0)),t){let s=n.engine.block.getParent(c);s!=null&&n.engine.block.getType(s)!=="//ly.img.ubq/scene"&&(r[s]=n.engine.block.isClipped(s),n.engine.block.setClipped(s,!1))}}),n.addDisposer(async()=>{l.forEach(c=>{if(n.engine.block.isValid(c)&&e&&n.engine.block.setAlwaysOnTop(c,o[c]),t){let s=n.engine.block.getParent(c);s!=null&&n.engine.block.getType(s)!=="//ly.img.ubq/scene"&&r[s]!=null&&n.engine.block.setClipped(s,r[s])}})}),await a(i,n)}}var eo=Xr;function to({pending:e=!0}){return async(t,i,n)=>{let a=e?i.blockIds??i.engine.block.findAllSelected():[];try{return a.forEach(o=>{i.engine.block.isValid(o)&&i.engine.block.setState(o,{type:"Pending",progress:0})}),await n(t,i)}finally{a.forEach(o=>{i.engine.block.isValid(o)&&i.engine.block.setState(o,{type:"Ready"})})}}}var no=to;function io({editMode:e,automaticallyUnlock:t=!1}){return async(i,n,a)=>{let o=n.blockIds??n.engine.block.findAllSelected(),r=()=>{};t||n.addDisposer(async()=>{r?.()});try{return r=ro(n.engine,o,e),await a(i,n)}catch(l){throw N(l)&&r(),l}finally{t&&r()}}}function ro(e,t,i){let n=e.editor.getGlobalScope("editor/select"),a=e.editor.getEditMode();l(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(i);let o=e.editor.createHistory(),r=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function l(){e.block.findAllSelected().forEach(u=>{t.includes(u)||e.block.setSelected(u,!1)}),t.forEach(u=>{e.block.setSelected(u,!0)})}let c=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==i&&e.editor.setEditMode(i)}),s=e.block.onSelectionChanged(l);return()=>{n!=null&&e.editor.setGlobalScope("editor/select",n),e.editor.setEditMode(a),e.editor.setActiveHistory(r),e.editor.destroyHistory(o),s(),c()}}var oo=io;function ao(e,t){switch(t.kind){case"text":return lo(e,t);case"image":return so(e,t);case"video":return co(e,t);case"audio":return uo(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function lo(e,t){let{cesdk:i,blockIds:n,abortSignal:a}=t,o=n.map(s=>i.engine.block.getString(s,"text/text")),r;if(de(e)){let s="";for await(let u of e){if(a.aborted)break;typeof u=="string"?s=u:u.kind==="text"&&(s=u.text),n.forEach(d=>{i.engine.block.setString(d,"text/text",s)}),r={kind:"text",text:s}}}else r=e;if(r==null||r.kind!=="text")throw new Error("Output kind from generation is not text");let l=()=>{t.blockIds.forEach(s=>{t.cesdk.engine.block.setString(s,"text/text",r.text)})},c=()=>{t.blockIds.forEach((s,u)=>{t.cesdk.engine.block.setString(s,"text/text",o[u])})};return{consumedGenerationResult:r,applyCallbacks:{onBefore:c,onAfter:l,onCancel:c,onApply:()=>{l(),t.cesdk.engine.editor.addUndoStep()}}}}async function so(e,t){let{cesdk:i,blockIds:n,abortSignal:a}=t;if(n.length!==1)throw new Error("Only one block is supported for image generation");let[o]=n,r=i.engine.block.getFill(o),l=i.engine.block.getSourceSet(r,"fill/image/sourceSet"),[c]=l,s;c==null&&(s=i.engine.block.getString(r,"fill/image/imageFileURI"));let u=await i.engine.editor.getMimeType(c?.uri??s),d=await ce(c?.uri??s,t.cesdk.engine),p=d.width/d.height;if(a.throwIfAborted(),u==="image/svg+xml")throw new Error("SVG images are not supported");let m=i.engine.block.getCropScaleX(o),b=i.engine.block.getCropScaleY(o),w=i.engine.block.getCropTranslationX(o),h=i.engine.block.getCropTranslationY(o),g=i.engine.block.getCropRotation(o),k=()=>{i.engine.block.setCropScaleX(o,m),i.engine.block.setCropScaleY(o,b),i.engine.block.setCropTranslationX(o,w),i.engine.block.setCropTranslationY(o,h),i.engine.block.setCropRotation(o,g)};if(de(e))throw new Error("Streaming generation is not supported yet from a panel");if(e.kind!=="image"||typeof e.url!="string")throw new Error("Output kind from generation is not an image");let y=e.url,f=await i.engine.editor.getMimeType(y),v=await po(i,y,f),I=await ce(v,t.cesdk.engine),C=I.width/I.height,M=Math.abs(p-C)>.001,S=c?[{uri:v,width:I.width,height:I.height}]:void 0,z=v;S==null?i.engine.block.setString(r,"fill/image/imageFileURI",z):(i.engine.block.setString(r,"fill/image/imageFileURI",""),i.engine.block.setSourceSet(r,"fill/image/sourceSet",S)),M?i.engine.block.setContentFillMode(o,"Cover"):k();let ye=()=>{if(l==null||l.length===0){if(s==null)throw new Error("No image URI found");i.engine.block.setString(r,"fill/image/imageFileURI",s)}else i.engine.block.setSourceSet(r,"fill/image/sourceSet",l);k()},be=()=>{if(S==null){if(z==null)throw new Error("No image URI found");i.engine.block.setString(r,"fill/image/imageFileURI",z)}else i.engine.block.setSourceSet(r,"fill/image/sourceSet",S);M?i.engine.block.setContentFillMode(o,"Cover"):k()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:ye,onAfter:be,onCancel:()=>{ye()},onApply:()=>{be(),t.cesdk.engine.editor.addUndoStep()}}}}async function co(e,t){throw new Error("Function not implemented.")}async function uo(e,t){throw new Error("Function not implemented.")}async function po(e,t,i){let n=await(await fetch(t)).blob(),a=new File([n],`image.${ar(i)}`,{type:i}),o=await e.unstable_upload(a,()=>{});return o?.meta?.uri??(console.warn("Failed to upload image:",o),t)}var go=ao;function mo({editMode:e,automaticallyUnlock:t=!1,showNotification:i=!0}){return async(n,a,o)=>{let r=a.blockIds??a.engine.block.findAllSelected(),l=()=>{};t||a.addDisposer(async()=>{l?.()});try{l=yo(a.engine,r,e);let c=await o(n,a);if(i){let s=a.engine.block.findAllSelected();r.some(u=>s.includes(u))||a.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{r.forEach(u=>{a.engine.block.select(u)})}}})}return c}catch(c){throw N(c)&&l(),c}finally{t&&l()}}}function yo(e,t,i){function n(){let r=e.block.findAllSelected();return t.some(l=>r.includes(l))}let a=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==i&&n()&&e.editor.setEditMode(i)}),o=e.block.onSelectionChanged(()=>{n()?e.editor.setEditMode(i):e.editor.setEditMode("Transform")});return n()&&e.editor.setEditMode(i),()=>{o(),a(),e.editor.setEditMode("Transform")}}var bo=mo;async function fo(e,t){let{cesdk:i,input:n,blockIds:a,provider:o,quickAction:r,confirmationComponentId:l,abortSignal:c}=e;r.confirmation&&i.ui.setCanvasMenuOrder([l],{editMode:ie});let s=new De(i.engine,it);a.forEach(g=>{s.set(g,{status:"processing",quickActionId:r.id})});let u={cesdk:i,engine:i.engine,abortSignal:c},d=Xe([...o.output.middleware??[],t.debug?et():void 0,no({}),...r.confirmation?[r.lockDuringConfirmation?oo({editMode:ie}):bo({editMode:ie}),r.confirmation&&eo({})]:[],t.dryRun?tt({kind:o.kind,blockIds:a}):void 0]),{result:p,dispose:m}=await d(o.output.generate)(n,u),{consumedGenerationResult:b,applyCallbacks:w}=await go(p,{abortSignal:c,kind:o.kind,blockIds:a,cesdk:i});r.confirmation?a.forEach(g=>{s.set(g,{status:"confirmation",quickActionId:r.id})}):(w.onApply(),a.forEach(g=>{s.clear(g)}));let h=()=>{m(),a.forEach(g=>{s.clear(g)})};return c.addEventListener("abort",h),{dispose:h,returnValue:b,applyCallbacks:w}}var Ne=fo;function ho(e,t){let{cesdk:i,quickActionMenu:n,provider:a}=e,o=`ly.img.ai.${n.id}`,r=`${o}.confirmation`;i.setTranslations({en:{[`${r}.apply`]:"Apply",[`${r}.before`]:"Before",[`${r}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let l=`${r}.canvasnMenu`,c={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},s=()=>{let d=new AbortController,p=d.signal;return c.abort=()=>{d.abort()},p};i.ui.registerComponent(l,({builder:d,engine:p,state:m})=>{let b=p.block.findAllSelected();if(b.length===0)return null;let w=new De(i.engine,it),h=w.get(b[0]);if(h==null)return null;let g=()=>{b.forEach(k=>{w.clear(k)})};switch(h.status){case"processing":{d.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${h.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),d.Separator(`${o}.separator`),d.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{c.abort(),g()}});break}case"confirmation":{let k=m(`${r}.comparing`,"after"),y=c.applyCallbacks?.onCancel;y!=null&&d.Button(`${r}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{c.unlock(),y(),g()}});let f=c.applyCallbacks?.onBefore,v=c.applyCallbacks?.onAfter;f!=null&&v!=null&&d.ButtonGroup(`${r}.compare`,{children:()=>{d.Button(`${r}.compare.before`,{label:`${r}.before`,variant:"regular",isActive:k.value==="before",onClick:()=>{f(),k.setValue("before")}}),d.Button(`${r}.compare.after`,{label:`${r}.after`,variant:"regular",isActive:k.value==="after",onClick:()=>{v(),k.setValue("after")}})}});let I=c.applyCallbacks?.onApply;I!=null&&d.Button(`${r}.apply`,{icon:"@imgly/Checkmark",tooltip:`${r}.apply`,color:"accent",isDisabled:k.value!=="after",onClick:()=>{c.unlock(),g(),i.engine.editor._update(),I()}});break}default:}});let u=`${o}.canvasMenu`;return i.ui.registerComponent(u,d=>{let p=d.engine.block.findAllSelected(),m=p.every(y=>d.engine.block.getState(y).type==="Ready"),b=n.getQuickActionMenuOrder().map(y=>{if(y==="ly.img.separator")return y;let f=n.getQuickAction(y);if(f==null||!i.feature.isEnabled(rt({quickActionId:y,quickActionMenuId:n.id}),{engine:d.engine}))return null;let v=f.scopes;return v!=null&&v.length>0&&!p.every(I=>v.every(C=>d.engine.block.isAllowedByScope(I,C)))?null:f}).filter(y=>y!=null);if(b=Jr(b),b.length===0||b.every(y=>y==="ly.img.separator"))return null;let{builder:w,experimental:h,state:g}=d,k=g(`${o}.toggleExpandedState`,void 0);h.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",isDisabled:!m,trailingIcon:null,children:({close:y})=>{w.Section(`${o}.popover.section`,{children:()=>{if(k.value!=null){let f=k.value,v=n.getQuickAction(f);if(v!=null&&v.renderExpanded!=null){v.renderExpanded(d,{blockIds:p,closeMenu:y,toggleExpand:()=>{k.setValue(void 0)},handleGenerationError:I=>{V(I,{cesdk:i,provider:a},t)},generate:async(I,C)=>{try{let{returnValue:M,applyCallbacks:S,dispose:z}=await Ne({input:I,quickAction:v,quickActionMenu:n,provider:a,cesdk:i,abortSignal:s(),blockIds:C?.blockIds??p,confirmationComponentId:l},t);return c.unlock=z,c.applyCallbacks=S,M}catch(M){throw N(M)||V(M,{cesdk:i,provider:a},t),M}}});return}}h.builder.Menu(`${o}.menu`,{children:()=>{b.forEach(f=>{f==="ly.img.separator"?w.Separator(`${o}.separator.${Math.random().toString()}`):f.render(d,{blockIds:p,closeMenu:y,handleGenerationError:v=>{V(v,{cesdk:i,provider:a},t)},toggleExpand:()=>{k.setValue(f.id)},generate:async(v,I)=>{try{let{returnValue:C,applyCallbacks:M,dispose:S}=await Ne({input:v,quickAction:f,quickActionMenu:n,provider:a,cesdk:i,abortSignal:s(),blockIds:I?.blockIds??p,confirmationComponentId:l},t);return c.unlock=S,c.applyCallbacks=M,C}catch(C){throw N(C)||V(C,{cesdk:i,provider:a},t),C}}})})}})}})}})}),{canvasMenuComponentId:u}}var ko=ho;async function vo(e,t,i){await e.initialize?.(t);let n=await Ao(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let a=n?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:n,historyAssetLibraryEntryId:a,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};a!=null&&n!=null&&t.cesdk.ui.addAssetLibraryEntry({id:a,sourceIds:[n],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),t.cesdk.i18n.setTranslations({en:{"common.ai-generation.success":"Generation Successful","common.ai-generation.failed":"Generation Failed","common.ai-generation.generate":"Generate","common.ai-generation.prompt.placeholder":"Describe what you want to create...",[`panel.${e.id}`]:wo(e)}});let r="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(r)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",Zr),t.cesdk.ui.experimental.setGlobalStateValue(r,!0)),{renderBuilderFunctions:await Io(e,o,i)}}function wo(e){if(e.name!=null)return e.name;switch(e.kind){case"image":return"Generate Image";case"video":return"Generate Video";case"audio":return"Generate Audio";default:return"Generate Asset"}}async function Ao(e,t,i){if(!(i==null||i===!1)){if(i==="@imgly/local"){let n=`${t}.history`;return e.asset.addLocalSource(n),n}if(i==="@imgly/indexedDB"){let n=`${t}.history`;return e.asset.addSource(new lt(n,e)),n}return i}}async function Io(e,t,i){let n={panel:void 0};return e.input?.panel!=null&&(n.panel=await Co(e,e.input.panel,t,i)),e.input?.quickActions!=null&&(i.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),xo(e,e.input.quickActions,t,i)),n}async function Co(e,t,i,n){switch(t.type){case"custom":return Yr(e,t,i,n);case"schema":return Gr(e,t,i,n);default:n.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function xo(e,t,i,n){let{cesdk:a}=i,o={};t.actions.forEach(r=>{let l=r.kind??e.kind;o[l]==null&&(o[l]=Kr(a,l));let c=o[l],s=r.enable??!0;a.feature.enable(rt({quickActionId:r.id,quickActionMenuId:l}),s),c.registerQuickAction(r),n.debug&&console.log(`Registered quick action: '${r.id}' (v${r.version}) to menu '${l}'`)}),Object.values(o).forEach(r=>{let{canvasMenuComponentId:l}=ko({cesdk:a,quickActionMenu:r,provider:e},n);n.debug&&console.log(`Registered quick action menu component: ${l}`)})}var pe=vo;function Mo(e){let{cesdk:t,panelId:i}=e;i.startsWith("ly.img.ai/")&&console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai/" \u2013 "${i}" was provided.`);let n=`${i}.dock`;t.ui.registerComponent(n,({builder:a})=>{let o=t.ui.isPanelOpen(i);a.Button(`${i}.dock.button`,{label:`${i}.dock.label`,isSelected:o,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(r=>{r.startsWith("ly.img.ai/")&&t.ui.closePanel(r),!o&&r==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(r)}),o?t.ui.closePanel(i):t.ui.openPanel(i)}})})}var ot=Mo;var ge="@imgly/plugin-ai-video-generation-web";var x="ly.img.ai/video-generation",me="ly.img.ai.video-generation.fromType";function Eo(e){return{async initialize({cesdk:t}){if(t==null)return;let i={debug:e.debug??!1,dryRun:e.dryRun??!1,middleware:e.middleware};t.setTranslations({en:{[`panel.${x}`]:"Video Generation","ly.img.ai.video-generation.success":"Video Generation Successful","ly.img.ai.video-generation.success.action":"Show"}});let n=e?.text2video,a=e?.image2video,o=await n?.({cesdk:t}),r=await a?.({cesdk:t});function l(d){if(t!=null)return{success:{show:()=>{let p=t?.ui.isPanelOpen(x),m=t.ui.experimental.getGlobalStateValue(me)===d;return!p||!m},message:"ly.img.ai.video-generation.success",action:{label:"ly.img.ai.video-generation.success.action",onClick:()=>{t.ui.experimental.setGlobalStateValue(me,d),t.ui.openPanel(x)}},duration:"long"}}}o!=null&&(o.output.notification=l("fromText")),r!=null&&(r.output.notification=l("fromImage"));let c=o!=null?await pe(o,{cesdk:t,engine:t.engine},i):void 0,s=r!=null?await pe(r,{cesdk:t,engine:t.engine},i):void 0;if(c?.renderBuilderFunctions?.panel==null&&s?.renderBuilderFunctions?.panel==null){i.debug&&console.log("No providers are initialized \u2013 doing nothing");return}if(c?.renderBuilderFunctions?.panel!=null&&s?.renderBuilderFunctions?.panel!=null)t.ui.registerPanel(x,d=>{let{builder:p,experimental:m}=d,b=m.global(me,"fromText");switch(p.Section(`${x}.fromType.section`,{children:()=>{p.ButtonGroup(`${x}.fromType.buttonGroup`,{inputLabel:"Input",children:()=>{p.Button(`${x}.fromType.buttonGroup.fromText`,{label:"Text",icon:b.value!=="fromText"&&o!=null&&m.global(H(o.id),!1).value?"@imgly/LoadingSpinner":void 0,isActive:b.value==="fromText",onClick:()=>{b.setValue("fromText")}}),p.Button(`${x}.fromType.buttonGroup.fromImage`,{label:"Image",icon:b.value!=="fromImage"&&r!=null&&m.global(H(r.id),!1).value?"@imgly/LoadingSpinner":void 0,isActive:b.value==="fromImage",onClick:()=>{b.setValue("fromImage")}})}})}}),b.value){case"fromText":{c?.renderBuilderFunctions?.panel?.(d);break}case"fromImage":{s?.renderBuilderFunctions?.panel?.(d);break}default:}});else{let d=c?.renderBuilderFunctions?.panel??s?.renderBuilderFunctions?.panel;if(d==null)return;t.ui.registerPanel(x,d),t.i18n.setTranslations({en:{[`${x}.dock.label`]:"AI Video"}}),ot({cesdk:t,panelId:x})}}}}var at=Eo;var So=e=>({name:ge,version:"0.1.10",...at(e)}),Xo=So;export{Xo as default};
65
+ `,Jo=Ko;function Xo(e){return async(t,r,i)=>e.enable?(console.log(`[DRY RUN]: Requesting dummy AI generation for kind '${e.kind}' with inputs: `,JSON.stringify(t,void 0,2)),await At(2e3),await ea(t,e,r)):i(t,r)}async function ea(e,t,r){switch(t.kind){case"image":return ta(e,t,r);case"video":return ra(e,t,r);case"text":return ia(e,t,r);case"audio":return oa(e,t,r);default:throw new Error(`Unsupported output kind for creating dry run output: ${t.kind}`)}}async function ta(e,t,{engine:r}){let i,n,o=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image",a=o.match(/(\d+)x(\d+)/);if(a!=null)i=parseInt(a[1],10),n=parseInt(a[2],10);else if(t.blockInputs!=null&&(i=t.blockInputs.image.width,n=t.blockInputs.image.height),t.blockIds!=null&&Array.isArray(t.blockIds)&&t.blockIds.length>0){let[s]=t.blockIds,u=await Kn(s,r),l=await Wn(u,r);i=l.width,n=l.height}else i=512,n=512;return{kind:"image",url:`https://placehold.co/${i}x${n}/000000/FFF?text=${o.replace(" ","+").replace(`
66
+ `,"+")}`}}async function ra(e,t,r){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function ia(e,t,r){let i="";if(t.blockIds&&t.blockIds.length>0){let[a]=t.blockIds;r.engine.block.isValid(a)&&(i=r.engine.block.getString(a,"text/text"))}if(!i&&e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"){let a=e.prompt,s=a.match(/text:\s*"([^"]+)"/i)||a.match(/content:\s*"([^"]+)"/i)||a.match(/"([^"]+)"/);s&&s[1]&&(i=s[1])}let n=i.length||50,o="";if(e!=null&&typeof e=="object")if("language"in e&&typeof e.language=="string")o=q(n,"translation");else if("type"in e&&typeof e.type=="string"){let a=e.type;o=q(n,a)}else"customPrompt"in e?o=q(n,"custom"):o=q(n,"improved");else o=q(n,"generated");return na(o,r.abortSignal)}async function*na(e,t){let r=Math.max(1,Math.ceil(e.length/20)),i=0;for(;i<e.length;){if(t?.aborted)return;let n=Math.min(i+r,e.length);yield{kind:"text",text:e.substring(0,n)},i=n,i<e.length&&await At(100)}return{kind:"text",text:e}}function q(e,t){let r="[DRY RUN - Dummy Text] ",i=r.length;if(e<=i)return r.substring(0,e);let n=e-i,o={translation:"Ceci est un texte fictif traduit qui maintient la longueur approximative.",professional:"Enhanced professional content with improved clarity and structure.",casual:"Relaxed, friendly text that keeps things simple and approachable.",formal:"Refined formal documentation that preserves original structure.",humorous:"Amusing content that brings lighthearted fun to the text.",improved:"Enhanced text that demonstrates better clarity and readability.",custom:"Customized content reflecting the requested modifications.",generated:"AI-generated content maintaining original length and structure."},a=o[t]||o.generated,s="";if(n<=a.length)s=a.substring(0,n);else{s=a;let u=[" Additional content continues with similar phrasing."," Further elaboration maintains the established tone."," Extended content preserves the original style."," Continued text follows the same pattern."],l=0;for(;s.length<n;){let c=u[l%u.length];if(s.length+c.length<=n)s+=c;else{s+=c.substring(0,n-s.length);break}l++}}return r+s}async function oa(e,t,r){let i=3;if(e!=null&&typeof e=="object"){if("duration"in e&&typeof e.duration=="number")i=e.duration;else if("prompt"in e&&typeof e.prompt=="string"){let n=e.prompt.match(/(\d+)\s*(?:seconds?|secs?|s)\b/i);n&&(i=parseInt(n[1],10))}}return t.blockInputs?.audio?.duration&&(i=t.blockInputs.audio.duration),{kind:"audio",url:aa(220,i),duration:i,thumbnailUrl:void 0}}function aa(e,t){let r=Math.floor(44100*t),i=new Float32Array(r);for(let n=0;n<r;n++)i[n]=Math.sin(2*Math.PI*e*n/44100);return sa(i,44100)}function sa(e,t){let r=e.length,i=2,n=1,o=n*i,a=t*o,s=r*i,u=44+s,l=new ArrayBuffer(u),c=new DataView(l),d=(b,m)=>{for(let f=0;f<m.length;f++)c.setUint8(b+f,m.charCodeAt(f))};d(0,"RIFF"),c.setUint32(4,u-8,!0),d(8,"WAVE"),d(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,n,!0),c.setUint32(24,t,!0),c.setUint32(28,a,!0),c.setUint16(32,o,!0),c.setUint16(34,16,!0),d(36,"data"),c.setUint32(40,s,!0);let p=44;for(let b=0;b<r;b++){let m=Math.max(-1,Math.min(1,e[b])),f=Math.round(m*32767);c.setInt16(p,f,!0),p+=2}let g=new Uint8Array(l),h="";for(let b=0;b<g.length;b++)h+=String.fromCharCode(g[b]);return`data:audio/wav;base64,${btoa(h)}`}async function At(e){return new Promise(t=>{setTimeout(t,e)})}var la=Xo,ua="USER_CANCEL";function ca(e){return async(t,r)=>{if(r?.abortSignal?.aborted)return{status:"aborted"};let i=to([...e.provider.output.middleware??[],...r?.middlewares??[],io({enable:r?.debug}),la({enable:r?.dryRun,kind:e.provider.kind})]);try{let{result:n}=await i(e.provider.output.generate)(t,{abortSignal:r?.abortSignal,engine:e.engine,cesdk:e.cesdk});return r?.abortSignal?.aborted?{status:"aborted"}:n instanceof Error?{status:"error",message:n.message}:n==null?{status:"error",message:"No output generated"}:so(n)?{status:"success",type:"async",output:n}:{status:"success",type:"sync",output:n}}catch(n){return Ce(n)?{status:"aborted",message:n.message}:n===ua?{status:"aborted",message:n}:{status:"error",message:n instanceof Error?n.message:String(n)}}}}var da=ca;async function pa(e,t,r,i){let n={...i,provider:t},o={provider:t,panelInput:t.input?.panel,options:{cesdk:r.cesdk,engine:r.cesdk.engine},config:n};await t.initialize?.({...r,engine:r.cesdk.engine});let a=Qo(o),s=Wo(o,a);o.options.historyAssetSourceId=a,o.options.historyAssetLibraryEntryId=s;let u=da({provider:t,cesdk:r.cesdk,engine:r.cesdk.engine}),l=await qo(o,u);lo(r.cesdk,"@imgly/plugin-ai-generation",Jo);let c={provider:t,panel:{builderRenderFunction:l},history:{assetSourceId:a,assetLibraryEntryId:s},generate:u};return eo.get().register(c),c}var be=pa;function ga(e){let{kind:t,cesdk:r,historAssetSourceIds:i}=e,n=`ly.img.ai.${t}-generation.history`;if(r.engine.asset.findAllSources().includes(n))return n;let o=new Jt(n,r,i);return r.engine.asset.addSource(o),o.id}var fa=ga;async function ha(e,t,r,i){let n,o=[];if(Array.isArray(t)){let s=await Promise.all(t.map(u=>be(e,u,r,i)));o.push(...s),n=ba({prefix:e,providerInitializationResults:o})}else{let s=await Promise.all(t.fromText.map(l=>be(e,l,r,i)));o.push(...s);let u=await Promise.all(t.fromImage.map(l=>be(e,l,r,i)));o.push(...u),n=ma({prefix:`ly.img.ai.${e}-generation`,initializedFromTextProviders:s,initializedFromImageProviders:u})}let a=fa({kind:e,cesdk:r.cesdk,historAssetSourceIds:o.map(s=>s.history?.assetSourceId).filter(Xn)});return{panel:{builderRenderFunction:n},history:{assetSourceId:a},providerInitializationResults:o}}function ma({prefix:e,initializedFromTextProviders:t,initializedFromImageProviders:r}){let i=t.length>0&&r.length>0;return n=>{let{builder:o,experimental:a}=n,s=a.global(`${e}.fromType`,i?"fromText":void 0),u=[];s.value==="fromText"?u.push(...t):s.value==="fromImage"?u.push(...r):u.push(...t,...r);let l=t.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),c=r.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),d=n.experimental.global(`${e}.selectedProvider.fromText`,l[0]),p=n.experimental.global(`${e}.selectedProvider.fromImage`,c[0]),g=s.value==="fromText"?d:s.value==="fromImage"?p:void 0;if((i||u.length>1)&&o.Section(`${e}.providerSelection.section`,{children:()=>{if(i&&o.ButtonGroup(`${e}.fromType.buttonGroup`,{inputLabel:"Input",children:()=>{o.Button(`${e}.fromType.buttonGroup.fromText`,{label:"Text",icon:s.value!=="fromText"&&Je(t,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromText",onClick:()=>{s.setValue("fromText")}}),o.Button(`${e}.fromType.buttonGroup.fromImage`,{label:"Image",icon:s.value!=="fromImage"&&Je(r,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromImage",onClick:()=>{s.setValue("fromImage")}})}}),u.length>1){let h=s.value==="fromText"?l:s.value==="fromImage"?c:[...l,...c];g!=null&&o.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:h,...g})}}}),u.length>1)g?.value.builderRenderFunction?.(n);else{let h=u[0];h&&h.panel?.builderRenderFunction?.(n)}}}function ba({prefix:e,providerInitializationResults:t}){return r=>{let{builder:i}=r;if(t.length===0)return;let n=t.map(({provider:a,panel:s})=>({id:a.id,label:a.name??a.id,builderRenderFunction:s?.builderRenderFunction})),o=r.state(`${e}.selectedProvider`,n[0]);t.length>1&&o!=null&&i.Section(`${e}.providerSelection.section`,{children:()=>{i.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:n,...o})}}),o.value.builderRenderFunction?.(r)}}function Je(e,t){return e.length===0?!1:e.some(({provider:r})=>r.id==null?!1:t.experimental.global(Ee(r.id),!1).value)}var xt=ha;var ya=typeof global=="object"&&global&&global.Object===Object&&global,Rt=ya,va=typeof self=="object"&&self&&self.Object===Object&&self,wa=Rt||va||Function("return this")(),x=wa,ka=x.Symbol,F=ka,Ft=Object.prototype,Ia=Ft.hasOwnProperty,Aa=Ft.toString,X=F?F.toStringTag:void 0;function xa(e){var t=Ia.call(e,X),r=e[X];try{e[X]=void 0;var i=!0}catch{}var n=Aa.call(e);return i&&(t?e[X]=r:delete e[X]),n}var Ca=xa,Sa=Object.prototype,Ea=Sa.toString;function Ma(e){return Ea.call(e)}var ja=Ma,_a="[object Null]",La="[object Undefined]",Ct=F?F.toStringTag:void 0;function Na(e){return e==null?e===void 0?La:_a:Ct&&Ct in Object(e)?Ca(e):ja(e)}var ie=Na;function Pa(e){return e!=null&&typeof e=="object"}var De=Pa,Fu=Array.isArray;function Oa(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Vt=Oa,Da="[object AsyncFunction]",$a="[object Function]",Ta="[object GeneratorFunction]",za="[object Proxy]";function Ra(e){if(!Vt(e))return!1;var t=ie(e);return t==$a||t==Ta||t==Da||t==za}var Fa=Ra,Va=x["__core-js_shared__"],Me=Va,St=function(){var e=/[^.]+$/.exec(Me&&Me.keys&&Me.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Ua(e){return!!St&&St in e}var Ba=Ua,Ga=Function.prototype,Ha=Ga.toString;function qa(e){if(e!=null){try{return Ha.call(e)}catch{}try{return e+""}catch{}}return""}var j=qa,Za=/[\\^$.*+?()[\]{}|]/g,Qa=/^\[object .+?Constructor\]$/,Ya=Function.prototype,Wa=Object.prototype,Ka=Ya.toString,Ja=Wa.hasOwnProperty,Xa=RegExp("^"+Ka.call(Ja).replace(Za,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function es(e){if(!Vt(e)||Ba(e))return!1;var t=Fa(e)?Xa:Qa;return t.test(j(e))}var ts=es;function rs(e,t){return e?.[t]}var is=rs;function ns(e,t){var r=is(e,t);return ts(r)?r:void 0}var V=ns,os=V(x,"WeakMap"),_e=os;function as(e,t){return e===t||e!==e&&t!==t}var ss=as,ls=9007199254740991;function us(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=ls}var cs=us;var Vu=Object.prototype;var ds="[object Arguments]";function ps(e){return De(e)&&ie(e)==ds}var Et=ps,Ut=Object.prototype,gs=Ut.hasOwnProperty,fs=Ut.propertyIsEnumerable,Uu=Et(function(){return arguments}())?Et:function(e){return De(e)&&gs.call(e,"callee")&&!fs.call(e,"callee")};var Bt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Mt=Bt&&typeof module=="object"&&module&&!module.nodeType&&module,hs=Mt&&Mt.exports===Bt,jt=hs?x.Buffer:void 0,Bu=jt?jt.isBuffer:void 0;var ms="[object Arguments]",bs="[object Array]",ys="[object Boolean]",vs="[object Date]",ws="[object Error]",ks="[object Function]",Is="[object Map]",As="[object Number]",xs="[object Object]",Cs="[object RegExp]",Ss="[object Set]",Es="[object String]",Ms="[object WeakMap]",js="[object ArrayBuffer]",_s="[object DataView]",Ls="[object Float32Array]",Ns="[object Float64Array]",Ps="[object Int8Array]",Os="[object Int16Array]",Ds="[object Int32Array]",$s="[object Uint8Array]",Ts="[object Uint8ClampedArray]",zs="[object Uint16Array]",Rs="[object Uint32Array]",w={};w[Ls]=w[Ns]=w[Ps]=w[Os]=w[Ds]=w[$s]=w[Ts]=w[zs]=w[Rs]=!0;w[ms]=w[bs]=w[js]=w[ys]=w[_s]=w[vs]=w[ws]=w[ks]=w[Is]=w[As]=w[xs]=w[Cs]=w[Ss]=w[Es]=w[Ms]=!1;function Fs(e){return De(e)&&cs(e.length)&&!!w[ie(e)]}var Vs=Fs;function Us(e){return function(t){return e(t)}}var Bs=Us,Gt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ee=Gt&&typeof module=="object"&&module&&!module.nodeType&&module,Gs=ee&&ee.exports===Gt,je=Gs&&Rt.process,Hs=function(){try{var e=ee&&ee.require&&ee.require("util").types;return e||je&&je.binding&&je.binding("util")}catch{}}(),_t=Hs,Lt=_t&&_t.isTypedArray,Gu=Lt?Bs(Lt):Vs;var qs=Object.prototype,Hu=qs.hasOwnProperty;function Zs(e,t){return function(r){return e(t(r))}}var Qs=Zs,qu=Qs(Object.keys,Object);var Ys=Object.prototype,Zu=Ys.hasOwnProperty;var Ws=V(Object,"create"),te=Ws;function Ks(){this.__data__=te?te(null):{},this.size=0}var Js=Ks;function Xs(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var el=Xs,tl="__lodash_hash_undefined__",rl=Object.prototype,il=rl.hasOwnProperty;function nl(e){var t=this.__data__;if(te){var r=t[e];return r===tl?void 0:r}return il.call(t,e)?t[e]:void 0}var ol=nl,al=Object.prototype,sl=al.hasOwnProperty;function ll(e){var t=this.__data__;return te?t[e]!==void 0:sl.call(t,e)}var ul=ll,cl="__lodash_hash_undefined__";function dl(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=te&&t===void 0?cl:t,this}var pl=dl;function U(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])}}U.prototype.clear=Js;U.prototype.delete=el;U.prototype.get=ol;U.prototype.has=ul;U.prototype.set=pl;var Nt=U;function gl(){this.__data__=[],this.size=0}var fl=gl;function hl(e,t){for(var r=e.length;r--;)if(ss(e[r][0],t))return r;return-1}var ce=hl,ml=Array.prototype,bl=ml.splice;function yl(e){var t=this.__data__,r=ce(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():bl.call(t,r,1),--this.size,!0}var vl=yl;function wl(e){var t=this.__data__,r=ce(t,e);return r<0?void 0:t[r][1]}var kl=wl;function Il(e){return ce(this.__data__,e)>-1}var Al=Il;function xl(e,t){var r=this.__data__,i=ce(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var Cl=xl;function B(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])}}B.prototype.clear=fl;B.prototype.delete=vl;B.prototype.get=kl;B.prototype.has=Al;B.prototype.set=Cl;var de=B,Sl=V(x,"Map"),re=Sl;function El(){this.size=0,this.__data__={hash:new Nt,map:new(re||de),string:new Nt}}var Ml=El;function jl(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var _l=jl;function Ll(e,t){var r=e.__data__;return _l(t)?r[typeof t=="string"?"string":"hash"]:r.map}var pe=Ll;function Nl(e){var t=pe(this,e).delete(e);return this.size-=t?1:0,t}var Pl=Nl;function Ol(e){return pe(this,e).get(e)}var Dl=Ol;function $l(e){return pe(this,e).has(e)}var Tl=$l;function zl(e,t){var r=pe(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Rl=zl;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=Ml;G.prototype.delete=Pl;G.prototype.get=Dl;G.prototype.has=Tl;G.prototype.set=Rl;var Ht=G;function Fl(){this.__data__=new de,this.size=0}var Vl=Fl;function Ul(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Bl=Ul;function Gl(e){return this.__data__.get(e)}var Hl=Gl;function ql(e){return this.__data__.has(e)}var Zl=ql,Ql=200;function Yl(e,t){var r=this.__data__;if(r instanceof de){var i=r.__data__;if(!re||i.length<Ql-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Ht(i)}return r.set(e,t),this.size=r.size,this}var Wl=Yl;function ne(e){var t=this.__data__=new de(e);this.size=t.size}ne.prototype.clear=Vl;ne.prototype.delete=Bl;ne.prototype.get=Hl;ne.prototype.has=Zl;ne.prototype.set=Wl;var Kl=Object.prototype,Qu=Kl.propertyIsEnumerable;var Jl=V(x,"DataView"),Le=Jl,Xl=V(x,"Promise"),Ne=Xl,eu=V(x,"Set"),Pe=eu,Pt="[object Map]",tu="[object Object]",Ot="[object Promise]",Dt="[object Set]",$t="[object WeakMap]",Tt="[object DataView]",ru=j(Le),iu=j(re),nu=j(Ne),ou=j(Pe),au=j(_e),R=ie;(Le&&R(new Le(new ArrayBuffer(1)))!=Tt||re&&R(new re)!=Pt||Ne&&R(Ne.resolve())!=Ot||Pe&&R(new Pe)!=Dt||_e&&R(new _e)!=$t)&&(R=function(e){var t=ie(e),r=t==tu?e.constructor:void 0,i=r?j(r):"";if(i)switch(i){case ru:return Tt;case iu:return Pt;case nu:return Ot;case ou:return Dt;case au:return $t}return t});var Yu=x.Uint8Array;var su="__lodash_hash_undefined__";function lu(e){return this.__data__.set(e,su),this}var uu=lu;function cu(e){return this.__data__.has(e)}var du=cu;function Oe(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Ht;++t<r;)this.add(e[t])}Oe.prototype.add=Oe.prototype.push=uu;Oe.prototype.has=du;var zt=F?F.prototype:void 0,Wu=zt?zt.valueOf:void 0;var pu=Object.prototype,Ku=pu.hasOwnProperty;var gu=Object.prototype,Ju=gu.hasOwnProperty;var Xu=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),ec=new RegExp(/[A-Fa-f0-9]{1}/,"g"),tc=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function fu(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 qt(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 fu(i,t)}function hu(e){return e==null?[]:Array.isArray(e)?e:[e]}var $e=hu;var _="@imgly/plugin-ai-video-generation-web",mu=["ly.img.createVideo"];var Qt="createVideo",Zt=`ly.img.${Qt}`,oe=`ly.img.ai.quickAction.video.${Qt}`,bu=({cesdk:e})=>(e.i18n.setTranslations({en:{[`${oe}.label`]:"Create Video...",[`${oe}.description`]:"Create a video from the image"}}),{id:Zt,type:"quick",kind:"image",label:`${oe}.label`,description:`${oe}.description`,enable:gt(),scopes:[],render:({builder:r,engine:i,close:n,providerId:o})=>{r.Button(`${Zt}.button`,{label:`${oe}.label`,icon:"@imgly/plugin-ai-generation/video",labelAlignment:"left",variant:"plain",onClick:async()=>{try{let[a]=i.block.findAllSelected(),s=await qt(a,i,{throwErrorIfSvg:!0});e.ui.openPanel("ly.img.ai.video-generation"),e.ui.experimental.setGlobalStateValue("ly.img.ai.video-generation.fromType","fromImage"),e.ui.experimental.setGlobalStateValue(`${o}.image_url`,s),n()}catch(a){console.error("Error opening video generation panel:",a)}}})}}),Yt=bu;var S="ly.img.ai.video-generation";function yu(e){return{async initialize({cesdk:t}){if(t==null)return;dt(t,_,"0.2.0"),t.setTranslations({en:{[`panel.${S}`]:"Video Generation",[`${S}.dock.label`]:"AI Video"}}),vu(e);let i=xe.get().register({type:"plugin",sceneMode:"Video",id:_,pluginId:_,label:"Generate Video",meta:{panelId:S},execute:()=>{t.ui.isPanelOpen(S)?t.ui.closePanel(S):t.ui.openPanel(S)}}),n=e.providers?.text2video??e.text2video,o=e.providers?.image2video??e.image2video,a=await Promise.all($e(n).map(l=>l({cesdk:t}))),s=await Promise.all($e(o).map(l=>l({cesdk:t}))),u=await xt("video",{fromText:a,fromImage:s},{cesdk:t},e);xe.get().register(Yt({cesdk:t})),u.panel.builderRenderFunction!=null?(t.ui.registerPanel(S,u.panel.builderRenderFunction),pt({cesdk:t,panelId:S})):i()}}}function vu(e){e.debug&&(e.providers?.text2video!=null&&e.text2video!=null&&console.warn("[VideoGeneration]: Both `providers.text2video` and `text2video` configuration is provided. Since `text2video` is deprecated, only `providers.text2video` will be used."),e.providers?.image2video!=null&&e.image2video!=null&&console.warn("[VideoGeneration]: Both `providers.image2video` and `image2video` configuration is provided. Since `image2video` is deprecated, only `providers.image2video` will be used."))}var Wt=yu;var wu=e=>({name:_,version:"0.2.0",...Wt(e)}),bc=wu;export{mu as DEFAULT_VIDEO_QUICK_ACTION_ORDER,bc as default};
64
67
  /*! Bundled license information:
65
68
 
66
69
  @imgly/plugin-ai-generation-web/dist/index.mjs:
@@ -81,5 +84,20 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
81
84
  *)
82
85
  *)
83
86
  *)
87
+
88
+ @imgly/plugin-utils/dist/index.mjs:
89
+ (*! Bundled license information:
90
+
91
+ lodash-es/lodash.js:
92
+ (**
93
+ * @license
94
+ * Lodash (Custom Build) <https://lodash.com/>
95
+ * Build: `lodash modularize exports="es" -o ./`
96
+ * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
97
+ * Released under MIT license <https://lodash.com/license>
98
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
99
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
100
+ *)
101
+ *)
84
102
  */
85
103
  //# sourceMappingURL=index.mjs.map