@imgly/plugin-ai-generation-web 0.1.1 → 0.1.2

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.mjs CHANGED
@@ -1,5 +1,5 @@
1
- function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]:(o,a)=>{let{builder:s,experimental:{global:l},payload:u}=o,d=u?.url??t.defaultUrl,c=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:c.value},action:{label:"Select Image",onClick:()=>{n?.ui.openPanel(`${e}.imageSelection`,{payload:{onSelect:p=>{p.meta?.uri!=null&&c.setValue(p.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:c.value})}}}function Ct(e,t){t?.ui.registerPanel(`${e}.imageSelection`,({builder:n,payload:r})=>{n.Library(`${e}.library.image`,{entries:["ly.img.image"],onSelect:async i=>{let o=i?.meta?.uri;if(o==null)return;let a=await t.engine.editor.getMimeType(o);a==="image/svg+xml"?t.ui.showNotification({type:"warning",message:"SVG images are not supported. Please choose a different image."}):a.startsWith("image/")?(r?.onSelect(i),t?.ui.closePanel(`${e}.imageSelection`)):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}var Ae=Ot;function ae(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let n=t.substring(2).split("/"),r=e;for(let i of n){if(r==null)throw new Error(`Invalid reference path: ${t}`);r=r[i]}if(r===void 0)throw new Error(`Reference not found: ${t}`);return r}function B(e,t,n=new Set){if(t==null||n.has(t))return t;if(n.add(t),t.$ref&&typeof t.$ref=="string"){let r=ae(e,t.$ref),o={...B(e,r,n)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(o[a]=B(e,t[a],n));return o}if(Array.isArray(t))return t.map(r=>B(e,r,n));if(typeof t=="object"){let r={};for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=B(e,t[i],n));return r}return t}function se(e){return B(e,{...e})}function Ee(e,t=!1){let n=s=>(t&&console.log(`OpenAPI Schema validation failed: ${s}`),!1);if(typeof e!="object"||e===null)return n(`Input is ${e===null?"null":typeof e}, not an object`);let r=e;if(!(typeof r.type=="string"||Array.isArray(r.enum)||typeof r.properties=="object"||typeof r.items=="object"||typeof r.allOf=="object"||typeof r.anyOf=="object"||typeof r.oneOf=="object"||typeof r.not=="object"))return n("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(r.type!==void 0){let s=["string","number","integer","boolean","array","object","null"];if(typeof r.type=="string"){if(!s.includes(r.type))return n(`Invalid type: ${r.type}. Must be one of ${s.join(", ")}`)}else if(Array.isArray(r.type)){for(let l of r.type)if(typeof l!="string"||!s.includes(l))return n(`Array of types contains invalid value: ${l}. Must be one of ${s.join(", ")}`)}else return n(`Type must be a string or array of strings, got ${typeof r.type}`)}if(r.items!==void 0&&(typeof r.items!="object"||r.items===null))return n(`Items must be an object, got ${r.items===null?"null":typeof r.items}`);if(r.properties!==void 0&&(typeof r.properties!="object"||r.properties===null))return n(`Properties must be an object, got ${r.properties===null?"null":typeof r.properties}`);let o=["allOf","anyOf","oneOf"];for(let s of o)if(r[s]!==void 0){if(!Array.isArray(r[s]))return n(`${s} must be an array, got ${typeof r[s]}`);for(let l=0;l<r[s].length;l++){let u=r[s][l];if(typeof u!="object"||u===null)return n(`Item ${l} in ${s} must be an object, got ${u===null?"null":typeof u}`)}}if(r.not!==void 0&&(typeof r.not!="object"||r.not===null))return n(`'not' must be an object, got ${r.not===null?"null":typeof r.not}`);if(r.additionalProperties!==void 0&&typeof r.additionalProperties!="boolean"&&(typeof r.additionalProperties!="object"||r.additionalProperties===null))return n(`additionalProperties must be a boolean or an object, got ${r.additionalProperties===null?"null":typeof r.additionalProperties}`);if(r.format!==void 0&&typeof r.format!="string")return n(`format must be a string, got ${typeof r.format}`);let a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let s of a)if(r[s]!==void 0&&typeof r[s]!="number")return n(`${s} must be a number, got ${typeof r[s]}`);if(r.minLength!==void 0&&(typeof r.minLength!="number"||r.minLength<0))return n(`minLength must be a non-negative number, got ${typeof r.minLength=="number"?r.minLength:typeof r.minLength}`);if(r.maxLength!==void 0&&(typeof r.maxLength!="number"||r.maxLength<0))return n(`maxLength must be a non-negative number, got ${typeof r.maxLength=="number"?r.maxLength:typeof r.maxLength}`);if(r.pattern!==void 0&&typeof r.pattern!="string")return n(`pattern must be a string, got ${typeof r.pattern}`);if(r.minItems!==void 0&&(typeof r.minItems!="number"||r.minItems<0))return n(`minItems must be a non-negative number, got ${typeof r.minItems=="number"?r.minItems:typeof r.minItems}`);if(r.maxItems!==void 0&&(typeof r.maxItems!="number"||r.maxItems<0))return n(`maxItems must be a non-negative number, got ${typeof r.maxItems=="number"?r.maxItems:typeof r.maxItems}`);if(r.uniqueItems!==void 0&&typeof r.uniqueItems!="boolean")return n(`uniqueItems must be a boolean, got ${typeof r.uniqueItems}`);if(r.minProperties!==void 0&&(typeof r.minProperties!="number"||r.minProperties<0))return n(`minProperties must be a non-negative number, got ${typeof r.minProperties=="number"?r.minProperties:typeof r.minProperties}`);if(r.maxProperties!==void 0&&(typeof r.maxProperties!="number"||r.maxProperties<0))return n(`maxProperties must be a non-negative number, got ${typeof r.maxProperties=="number"?r.maxProperties:typeof r.maxProperties}`);if(r.required!==void 0){if(!Array.isArray(r.required))return n(`required must be an array, got ${typeof r.required}`);for(let s=0;s<r.required.length;s++){let l=r.required[s];if(typeof l!="string")return n(`Item ${s} in required array must be a string, got ${typeof l}`)}}return!0}function wt(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let n=[],r=xt(e,t);return r??(Object.entries(e.properties).forEach(i=>{let o=i[0],a=i[1];n.push({id:o,schema:a})}),n)}function xt(e,t){if(t.orderExtensionKeyword==null)return;let n=[];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,i=r.find(a=>a in e);if(i==null)return;let o=e[i];if(o==null||Array.isArray(o)===!1)throw new Error(`Extension keyword ${i} must be an array of strings`);if([...new Set(o)].forEach(a=>{let s=e.properties?.[a];s!=null&&n.push({id:a,schema:s})}),n.length===0)throw new Error(`Could not find any properties with order extension keyword(s) ${r.join(", ")}`);return n}var q=wt;var kt="ly.img.ai",le="ly.img.ai/temp";async function Se(e,t){return e.engine.asset.findAllSources().includes(le)||e.engine.asset.addLocalSource(le),e.engine.asset.apply(le,t)}function G(e){return`${kt}/${e}`}function Pe(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 n=e;return"message"in n&&typeof n.message=="string"?n.message:"cause"in n&&typeof n.cause=="string"?n.cause:"detail"in n&&typeof n.detail=="object"&&n.detail!==null&&"message"in n.detail&&typeof n.detail.message=="string"?n.detail.message:"error"in n&&typeof n.error=="object"&&n.error!==null&&"message"in n.error&&typeof n.error.message=="string"?n.error.message:t}return typeof e=="string"?e:String(e)||t}function De(){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 Mt(e){return new Promise((t,n)=>{try{let r=document.createElement("video");r.style.display="none",r.addEventListener("loadedmetadata",()=>{r.duration===1/0?(r.currentTime=1e101,setTimeout(()=>{r.currentTime=0,t(r.duration),document.body.removeChild(r)},50)):(t(r.duration),document.body.removeChild(r))}),r.addEventListener("error",()=>{document.body.removeChild(r),n(new Error(`Failed to load video from ${e}`))}),r.src=e,document.body.appendChild(r)}catch(r){n(r)}})}function ue(e,t=0,n="image/jpeg",r=.8){return new Promise((i,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 l=s.getContext("2d");if(!l){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}l.drawImage(a,0,0,s.width,s.height);try{let u=s.toDataURL(n,r);document.body.removeChild(a),i(u)}catch(u){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${u instanceof Error?u.message:String(u)}`))}},{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 Y(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 A(e){return typeof e=="object"&&e!==null&&"next"in e&&"return"in e&&"throw"in e&&typeof e.next=="function"&&typeof e.return=="function"&&typeof e.throw=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}function k(e){return e instanceof Error&&e.name==="AbortError"}function Re(e,t,n,r,i,o){let a=t.schema.type;if(r.renderCustomProperty!=null&&r.renderCustomProperty[t.id]!=null)return r.renderCustomProperty[t.id](e,t);switch(a){case"string":return t.schema.enum!=null?At(e,t,n,r,i,o):je(e,t,n,r,i,o);case"boolean":return Le(e,t,n,r,i,o);case"number":case"integer":return Te(e,t,n,r,i,o);case"object":return Ne(e,t,n,r,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Et(e,t,n,r,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function Ne(e,t,n,r,i,o){let s=q(t.schema??{},r).reduce((l,u)=>{let d=Re(e,u,n,r,i,o);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function je(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=s(u,t.schema.default??""),p=St(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](u,{inputLabel:d,placeholder:i.i18n?.prompt,...c}),()=>({id:t.id,type:"string",value:c.value})}function At(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=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"]:{},p=(t.schema.enum??[]).map(I=>({id:I,label:c[I]??Y(I)})),g=t.schema.default!=null?p.find(I=>I.id===t.schema.default)??p[0]:p[0],v=s(u,g);return a.Select(u,{inputLabel:d,values:p,...v}),()=>({id:t.id,type:"string",value:v.value.id})}function Le(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=!!t.schema.default,p=s(u,c);return a.Checkbox(u,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function Te(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(c!=null?g=c:p!=null?g=p:g=0);let v=s(u,g);if(c!=null&&p!=null){let I=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(I=t.schema["x-imgly-step"]),a.Slider(u,{inputLabel:d,min:c,max:p,step:I,...v})}else a.NumberInput(u,{inputLabel:d,min:c,max:p,...v});return()=>({id:t.id,type:"integer",value:v.value})}function Et(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.anyOf??[],p=[],g={},v={};c.forEach((f,m)=>{let h=f.title??"common.custom",y=`${n.id}.${l}.anyOf[${m}]`,O="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},w="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(x=>{p.push({id:x,label:O[x]??Y(x),icon:w[x]})}):(g[y]=()=>je(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="boolean"?(g[y]=()=>Le(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="integer"?(g[y]=()=>Te(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="array"||f.type==="object"&&(g[y]=()=>Ne(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]}))});let I=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],b=s(u,I);if(a.Select(u,{inputLabel:d,values:p,...b}),b.value.id in g){let f=g[b.value.id]();v[b.value.id]=f}return()=>{let f=v[b.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:b.value.id}}}function St(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var $e=Re;var Pt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",ce=Pt;function Dt(e,t,n){switch(t){case"image":return Rt(e,n[t]);case"video":return Nt(e,n[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Rt(e,t){let n=t.width,r=t.height;return{id:e,meta:{previewUri:ce,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:r}}}function Nt(e,t){let n=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:ce,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:r}}}var Be=Dt;function jt(e,t){switch(e){case"image":return Lt(t[e]);case"video":return Tt(t[e]);default:throw new Error(`Unsupported output kind for creating dry run output: ${e}`)}}function Lt(e){let t=e.width,n=e.height,r=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image";return{kind:"image",url:`https://placehold.co/${t}x${n}/000000/FFF?text=${r.replace(" ","+").replace(`
2
- `,"+")}`}}function Tt(e){return{kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"}}var Ge=jt;async function $t(e,t,n,r){switch(t){case"image":{if(r.kind!=="image")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: image)`);return Bt(e,n[t],r)}case"video":{if(r.kind!=="video")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: video)`);return Gt(e,n[t],r)}case"audio":{if(r.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: audio)`);return Vt(e,n[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Bt(e,t,n){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i},payload:{sourceSet:[{uri:n.url,width:r,height:i}]}}}async function Gt(e,t,n){let r=t.width,i=t.height,o=await ue(n.url,0);return{id:e,label:t.label,meta:{uri:n.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Vt(e,t,n){return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:n.duration.toString()}}}var de=$t;function V(e){let t=e.filter(n=>!!n);return n=>async(r,i)=>{let o=[],a=c=>{o.push(c)},s=async(c,p,g)=>{if(c>=t.length)return n(p,g);let v=t[c],I=async(f,m)=>s(c+1,f,m),b={...g,addDisposer:a};return v(p,b,I)},l={...i,addDisposer:a};return{result:await s(0,r,l),dispose:async()=>{for(let c=o.length-1;c>=0;c--)try{await o[c]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function Ft(){return async(t,n,r)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let i,o=Date.now();try{return i=await r(t,n),i}finally{i!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(i,null,2))),console.groupEnd()}}}var F=Ft;async function _t(e,t,n,r,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:u}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let c=t(),p=await n(c.input),g=De(),v;if(l){if(v=Be(g,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(v,void 0,2)),d=await Se(s,v),d!=null&&r.kind==="video"){let m=s.engine.block.getPositionX(d),h=s.engine.block.getPositionY(d),y=s.engine.block.duplicate(d);s.engine.block.setPositionX(y,m),s.engine.block.setPositionY(y,h),s.engine.block.destroy(d),d=y}if(W(s,a,d))return{status:"aborted"};if(d==null)throw new Error("Could not create placeholder block");s.engine.block.setState(d,{type:"Pending",progress:0})}let I=V([...r.output.middleware??[],o.debug?F():void 0]),b;if(o.dryRun?b=await Kt(e,p):b=(await I(r.output.generate)(c.input,{abortSignal:a,engine:i.engine,cesdk:s})).result,A(b))throw new Error("Streaming generation is not supported yet from a panel");if(W(s,a,d))return{status:"aborted"};if(b==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(b,void 0,2));let f;if(d!=null&&s.engine.block.isValid(d)&&(f=await de(g,e,p,b),o.debug&&console.log("Updating asset in scene:",JSON.stringify(f,void 0,2)),await s.engine.asset.defaultApplyAssetToBlock(f,d)),W(s,a,d))return{status:"aborted"};if(u!=null){if(f==null&&(f=await de(g,e,p,b),W(s,a,d)))return{status:"aborted"};let m={...f,id:`${Date.now()}-${f.id}`,label:f.label!=null?{en:f.label}:{},tags:{}};s.engine.asset.addAssetToSource(u,m)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:b}}catch(c){throw d!=null&&s.engine.block.isValid(d)&&(k(c)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),c}finally{o.debug&&console.groupEnd()}}function W(e,t,n){return t.aborted?(n!=null&&e.engine.block.isValid(n)&&e.engine.block.destroy(n),!0):!1}async function Kt(e,t){console.log("[DRY RUN]: Requesting dummy AI generation with block inputs: ",JSON.stringify(t,void 0,2));let n=Ge(e,t);return await Ut(3e3),n}async function Ut(e){return new Promise(t=>{setTimeout(t,e)})}var Ve=_t;function zt(e,t,n){let{cesdk:r,provider:i,getInput:o}=t;n.onError!=null&&typeof n.onError=="function"?n.onError(e):(console.error("Generation failed:",e),Ht(r,i.output.notification,()=>({input:o?.().input,error:e}))||r.ui.showNotification({type:"error",message:Pe(e)}))}function Ht(e,t,n){let r=t?.error;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.failed",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"error",message:o,action:a}),!0}var E=zt;function J(e){return`${e}.generating`}function Fe(e){return`${e}.abort`}function Qt(e,t,n,r,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:u=!0}=i,{id:d,output:{abortable:c}}=t,p=s.global(Fe(d),()=>{}),g=s.global(J(d),!1),v,I=g.value&&c,b=()=>{I&&(p.value(),g.setValue(!1),p.setValue(()=>{}))},f;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let h=n();f=i.requiredInputs.every(y=>!h.input[y])}let m=s.global(`${d}.confirmationDialogId`,void 0);a.Section(`${d}.generate.section`,{children:()=>{a.Button(`${d}.generate`,{label:["common.ai-generation.generate",`panel.${d}.generate`],isLoading:g.value,color:"accent",isDisabled:f,suffix:I?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let h=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:y})=>{l.ui.closeDialog(y),m.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:y})=>{b(),l.ui.closeDialog(y),m.setValue(void 0)}}});m.setValue(h)}}:void 0,onClick:async()=>{v=new AbortController;let h=v.signal,y=async()=>{try{g.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),v?.abort()});let O=await Ve(t.kind,n,r,t,i,o,h);if(O.status==="aborted")return;let w=t.output.notification;Zt(l,w,()=>({input:n().input,output:O.output}))}catch(O){if(k(O))return;E(O,{cesdk:l,provider:t,getInput:n},o)}finally{v=void 0,g.setValue(!1),p.setValue(()=>{}),m.value!=null&&(l.ui.closeDialog(m.value),m.setValue(void 0))}};o.middleware!=null?await o.middleware(y,{provider:t,abort:b}):await y()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&i.historyAssetLibraryEntryId!=null&&a.Library(`${d}.history.library`,{entries:[i.historyAssetLibraryEntryId]})}function Zt(e,t,n){let r=t?.success;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.success",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"success",message:o,action:a,duration:r.duration}),!0}var X=Qt;async function qt(e,t,n,r){let{cesdk:i}=n,{id:o}=e;r.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=se(t.document),s=ae(a,t.inputReference);if(!Ee(s,r.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,u=q(l,t),d=c=>{let{builder:p}=c,g=[];p.Section(`${o}.schema.section`,{children:()=>{u.forEach(f=>{let m=$e(c,f,e,t,n,r);m!=null&&(Array.isArray(m)?g.push(...m):g.push(m))})}});let v=g.map(f=>f()),I=f=>f.type==="object"?Object.entries(f.value).reduce((m,[h,y])=>(m[h]=I(y),m),{}):f.value,b=v.reduce((f,m)=>(f[m.id]=I(m),f),{});X(c,e,()=>({input:b}),()=>t.getBlockInput(b),{...n,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},r)};return i.ui.registerPanel(G(o),d),d}var _e=qt;async function Yt(e,t,n,r){let{cesdk:i}=n,{id:o}=e,a=t.render,s=l=>{let{state:u}=l,d=u(J(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:c,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return X(l,e,c,p,{...n,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},r),c};return i.ui.registerPanel(G(o),s),s}var Ke=Yt;var it=class{constructor(e,t,n){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=n?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=n?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=r=>{t(new Error(`Failed to open IndexedDB: ${r.target.error}`))},n.onupgradeneeded=r=>{let i=r.target.result;i.objectStoreNames.contains(this.assetStoreName)||i.createObjectStore(this.assetStoreName,{keyPath:"id"}),i.objectStoreNames.contains(this.blobStoreName)||i.createObjectStore(this.blobStoreName,{keyPath:"id"})},n.onsuccess=r=>{this.db=r.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((l,u)=>{let d=e.locale??"en",c="",p=[];u.label!=null&&typeof u.label=="object"&&u.label[d]&&(c=u.label[d]),u.tags!=null&&typeof u.tags=="object"&&u.tags[d]&&(p=u.tags[d]);let g={...u,label:c,tags:p};return this.filterAsset(g,e)&&l.push(g),l},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:n,perPage:r}=e,i=n*r,o=i+r,a=t.slice(i,o),s=o<t.length?n+1:void 0;return{assets:a,currentPage:n,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 n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let r=new Set;n.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>r.add(a))});let i=[...r];e(i)},n.onerror=()=>{t(new Error(`Failed to get groups: ${n.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),n=t.objectStore(this.assetStoreName),r=new Set;R(e,o=>{r.add(o)}),setTimeout(()=>{this.storeBlobUrls([...r])});let i={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};n.put(i),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 n=this.db.transaction(this.assetStoreName,"readwrite");n.objectStore(this.assetStoreName).delete(e),n.oncomplete=()=>{R(t,r=>{this.removeBlob(r)}),this.engine.asset.assetSourceContentsChanged(this.id)},n.onerror=()=>{console.error(`Failed to remove asset: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}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,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=r.result;i.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),l=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-l:l-s}),t(i)},r.onerror=()=>{n(new Error(`Failed to get assets: ${r.error}`))}})}async getAsset(e){return new Promise((t,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.error}`))}})}async getBlob(e){return new Promise((t,n)=>{let r=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.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 n=>{let r=await(await fetch(n)).blob();t[n]=r})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let n=this.db.transaction(this.blobStoreName,"readwrite"),r=n.objectStore(this.blobStoreName);Object.entries(t).forEach(([i,o])=>{let a={id:i,blob:o};r.put(a)}),n.onerror=()=>{console.error(`Failed to add blobs: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}async restoreBlobUrls(e){let t={},n=new Set;return R(e,r=>{n.add(r)}),await Promise.all([...n].map(async r=>{let i=await this.createBlobUrlFromStore(r);t[r]=i})),R(e,r=>t[r]??r)}filterAsset(e,t){let{query:n,tags:r,groups:i,excludeGroups:o}=t;if(n&&n.trim()!==""){let a=n.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",l=e.tags?.map(u=>u.toLowerCase())??[];if(!a.every(u=>s.includes(u)||l.some(d=>d.includes(u))))return!1}if(r){let a=Array.isArray(r)?r:[r];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(i&&i.length>0&&(!e.groups||!i.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:n,sortKey:r,sortActiveFirst:i}=t,o=[...e];return!n||n==="None"||(r?o.sort((a,s)=>{let l,u;return r==="id"?(l=a.id,u=s.id):(l=a.meta?.[r]??null,u=s.meta?.[r]??null),l==null?n==="Ascending"?-1:1:u==null?n==="Ascending"?1:-1:typeof l=="string"&&typeof u=="string"?n==="Ascending"?l.localeCompare(u):u.localeCompare(l):n==="Ascending"?l<u?-1:l>u?1:0:l>u?-1:l<u?1:0}):n==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function R(e,t,n=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let r=0;r<e.length;r++){let i=n?`${n}[${r}]`:`[${r}]`;if(typeof e[r]=="string"&&e[r].startsWith("blob:")){let o=t(e[r],i);typeof o=="string"&&(e[r]=o)}else e[r]=R(e[r],t,i)}return e}for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let i=e[r],o=n?`${n}.${r}`:r;if(typeof i=="string"&&i.startsWith("blob:")){let a=t(i,o);typeof a=="string"&&(e[r]=a)}else e[r]=R(i,t,o)}return e}var Wt=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)}},Ie=Wt,Jt=typeof global=="object"&&global&&global.Object===Object&&global,ot=Jt,Xt=typeof self=="object"&&self&&self.Object===Object&&self,er=ot||Xt||Function("return this")(),M=er,tr=M.Symbol,N=tr,at=Object.prototype,rr=at.hasOwnProperty,nr=at.toString,_=N?N.toStringTag:void 0;function ir(e){var t=rr.call(e,_),n=e[_];try{e[_]=void 0;var r=!0}catch{}var i=nr.call(e);return r&&(t?e[_]=n:delete e[_]),i}var or=ir,ar=Object.prototype,sr=ar.toString;function lr(e){return sr.call(e)}var ur=lr,cr="[object Null]",dr="[object Undefined]",Ue=N?N.toStringTag:void 0;function pr(e){return e==null?e===void 0?dr:cr:Ue&&Ue in Object(e)?or(e):ur(e)}var H=pr;function fr(e){return e!=null&&typeof e=="object"}var ve=fr,ca=Array.isArray;function mr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var st=mr,gr="[object AsyncFunction]",yr="[object Function]",br="[object GeneratorFunction]",hr="[object Proxy]";function Ir(e){if(!st(e))return!1;var t=H(e);return t==yr||t==br||t==gr||t==hr}var vr=Ir,Or=M["__core-js_shared__"],pe=Or,ze=function(){var e=/[^.]+$/.exec(pe&&pe.keys&&pe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Cr(e){return!!ze&&ze in e}var wr=Cr,xr=Function.prototype,kr=xr.toString;function Mr(e){if(e!=null){try{return kr.call(e)}catch{}try{return e+""}catch{}}return""}var S=Mr,Ar=/[\\^$.*+?()[\]{}|]/g,Er=/^\[object .+?Constructor\]$/,Sr=Function.prototype,Pr=Object.prototype,Dr=Sr.toString,Rr=Pr.hasOwnProperty,Nr=RegExp("^"+Dr.call(Rr).replace(Ar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jr(e){if(!st(e)||wr(e))return!1;var t=vr(e)?Nr:Er;return t.test(S(e))}var Lr=jr;function Tr(e,t){return e?.[t]}var $r=Tr;function Br(e,t){var n=$r(e,t);return Lr(n)?n:void 0}var j=Br,Gr=j(M,"WeakMap"),me=Gr;function Vr(e,t){return e===t||e!==e&&t!==t}var Fr=Vr,_r=9007199254740991;function Kr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=_r}var Ur=Kr;var da=Object.prototype;var zr="[object Arguments]";function Hr(e){return ve(e)&&H(e)==zr}var He=Hr,lt=Object.prototype,Qr=lt.hasOwnProperty,Zr=lt.propertyIsEnumerable,pa=He(function(){return arguments}())?He:function(e){return ve(e)&&Qr.call(e,"callee")&&!Zr.call(e,"callee")};var ut=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qe=ut&&typeof module=="object"&&module&&!module.nodeType&&module,qr=Qe&&Qe.exports===ut,Ze=qr?M.Buffer:void 0,fa=Ze?Ze.isBuffer:void 0;var Yr="[object Arguments]",Wr="[object Array]",Jr="[object Boolean]",Xr="[object Date]",en="[object Error]",tn="[object Function]",rn="[object Map]",nn="[object Number]",on="[object Object]",an="[object RegExp]",sn="[object Set]",ln="[object String]",un="[object WeakMap]",cn="[object ArrayBuffer]",dn="[object DataView]",pn="[object Float32Array]",fn="[object Float64Array]",mn="[object Int8Array]",gn="[object Int16Array]",yn="[object Int32Array]",bn="[object Uint8Array]",hn="[object Uint8ClampedArray]",In="[object Uint16Array]",vn="[object Uint32Array]",C={};C[pn]=C[fn]=C[mn]=C[gn]=C[yn]=C[bn]=C[hn]=C[In]=C[vn]=!0;C[Yr]=C[Wr]=C[cn]=C[Jr]=C[dn]=C[Xr]=C[en]=C[tn]=C[rn]=C[nn]=C[on]=C[an]=C[sn]=C[ln]=C[un]=!1;function On(e){return ve(e)&&Ur(e.length)&&!!C[H(e)]}var Cn=On;function wn(e){return function(t){return e(t)}}var xn=wn,ct=typeof exports=="object"&&exports&&!exports.nodeType&&exports,K=ct&&typeof module=="object"&&module&&!module.nodeType&&module,kn=K&&K.exports===ct,fe=kn&&ot.process,Mn=function(){try{var e=K&&K.require&&K.require("util").types;return e||fe&&fe.binding&&fe.binding("util")}catch{}}(),qe=Mn,Ye=qe&&qe.isTypedArray,ma=Ye?xn(Ye):Cn;var An=Object.prototype,ga=An.hasOwnProperty;function En(e,t){return function(n){return e(t(n))}}var Sn=En,ya=Sn(Object.keys,Object);var Pn=Object.prototype,ba=Pn.hasOwnProperty;var Dn=j(Object,"create"),U=Dn;function Rn(){this.__data__=U?U(null):{},this.size=0}var Nn=Rn;function jn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Ln=jn,Tn="__lodash_hash_undefined__",$n=Object.prototype,Bn=$n.hasOwnProperty;function Gn(e){var t=this.__data__;if(U){var n=t[e];return n===Tn?void 0:n}return Bn.call(t,e)?t[e]:void 0}var Vn=Gn,Fn=Object.prototype,_n=Fn.hasOwnProperty;function Kn(e){var t=this.__data__;return U?t[e]!==void 0:_n.call(t,e)}var Un=Kn,zn="__lodash_hash_undefined__";function Hn(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=U&&t===void 0?zn:t,this}var Qn=Hn;function L(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}L.prototype.clear=Nn;L.prototype.delete=Ln;L.prototype.get=Vn;L.prototype.has=Un;L.prototype.set=Qn;var We=L;function Zn(){this.__data__=[],this.size=0}var qn=Zn;function Yn(e,t){for(var n=e.length;n--;)if(Fr(e[n][0],t))return n;return-1}var ee=Yn,Wn=Array.prototype,Jn=Wn.splice;function Xn(e){var t=this.__data__,n=ee(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Jn.call(t,n,1),--this.size,!0}var ei=Xn;function ti(e){var t=this.__data__,n=ee(t,e);return n<0?void 0:t[n][1]}var ri=ti;function ni(e){return ee(this.__data__,e)>-1}var ii=ni;function oi(e,t){var n=this.__data__,r=ee(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var ai=oi;function T(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}T.prototype.clear=qn;T.prototype.delete=ei;T.prototype.get=ri;T.prototype.has=ii;T.prototype.set=ai;var te=T,si=j(M,"Map"),z=si;function li(){this.size=0,this.__data__={hash:new We,map:new(z||te),string:new We}}var ui=li;function ci(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var di=ci;function pi(e,t){var n=e.__data__;return di(t)?n[typeof t=="string"?"string":"hash"]:n.map}var re=pi;function fi(e){var t=re(this,e).delete(e);return this.size-=t?1:0,t}var mi=fi;function gi(e){return re(this,e).get(e)}var yi=gi;function bi(e){return re(this,e).has(e)}var hi=bi;function Ii(e,t){var n=re(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var vi=Ii;function $(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}$.prototype.clear=ui;$.prototype.delete=mi;$.prototype.get=yi;$.prototype.has=hi;$.prototype.set=vi;var dt=$;function Oi(){this.__data__=new te,this.size=0}var Ci=Oi;function wi(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var xi=wi;function ki(e){return this.__data__.get(e)}var Mi=ki;function Ai(e){return this.__data__.has(e)}var Ei=Ai,Si=200;function Pi(e,t){var n=this.__data__;if(n instanceof te){var r=n.__data__;if(!z||r.length<Si-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new dt(r)}return n.set(e,t),this.size=n.size,this}var Di=Pi;function Q(e){var t=this.__data__=new te(e);this.size=t.size}Q.prototype.clear=Ci;Q.prototype.delete=xi;Q.prototype.get=Mi;Q.prototype.has=Ei;Q.prototype.set=Di;var Ri=Object.prototype,ha=Ri.propertyIsEnumerable;var Ni=j(M,"DataView"),ge=Ni,ji=j(M,"Promise"),ye=ji,Li=j(M,"Set"),be=Li,Je="[object Map]",Ti="[object Object]",Xe="[object Promise]",et="[object Set]",tt="[object WeakMap]",rt="[object DataView]",$i=S(ge),Bi=S(z),Gi=S(ye),Vi=S(be),Fi=S(me),D=H;(ge&&D(new ge(new ArrayBuffer(1)))!=rt||z&&D(new z)!=Je||ye&&D(ye.resolve())!=Xe||be&&D(new be)!=et||me&&D(new me)!=tt)&&(D=function(e){var t=H(e),n=t==Ti?e.constructor:void 0,r=n?S(n):"";if(r)switch(r){case $i:return rt;case Bi:return Je;case Gi:return Xe;case Vi:return et;case Fi:return tt}return t});var Ia=M.Uint8Array;var _i="__lodash_hash_undefined__";function Ki(e){return this.__data__.set(e,_i),this}var Ui=Ki;function zi(e){return this.__data__.has(e)}var Hi=zi;function he(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new dt;++t<n;)this.add(e[t])}he.prototype.add=he.prototype.push=Ui;he.prototype.has=Hi;var nt=N?N.prototype:void 0,va=nt?nt.valueOf:void 0;var Qi=Object.prototype,Oa=Qi.hasOwnProperty;var Zi=Object.prototype,Ca=Zi.hasOwnProperty;var wa=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),xa=new RegExp(/[A-Fa-f0-9]{1}/,"g"),ka=new RegExp(/[A-Fa-f0-9]{2}/,"g");var Oe="@imgly/plugin-ai-generation",qi=`
1
+ function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]:(o,a)=>{let{builder:s,experimental:{global:l},payload:u}=o,d=u?.url??t.defaultUrl,c=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:c.value},action:{label:"Select Image",onClick:()=>{if(n==null)return;let p=ae(e);n.ui.openPanel(p,{payload:{onSelect:m=>{m.meta?.uri!=null&&c.setValue(m.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:c.value})}}}function wt(e,t){t?.ui.registerPanel(ae(e),({builder:n,payload:r})=>{n.Library(`${e}.library.image`,{entries:["ly.img.image"],onSelect:async i=>{let o=i?.meta?.uri;if(o==null)return;let a=await t.engine.editor.getMimeType(o);a==="image/svg+xml"?t.ui.showNotification({type:"warning",message:"SVG images are not supported. Please choose a different image."}):a.startsWith("image/")?(r?.onSelect(i),t?.ui.closePanel(ae(e))):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}function ae(e){return`ly.img.ai/${e}.imageSelection`}var Ee=Ct;function se(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let n=t.substring(2).split("/"),r=e;for(let i of n){if(r==null)throw new Error(`Invalid reference path: ${t}`);r=r[i]}if(r===void 0)throw new Error(`Reference not found: ${t}`);return r}function B(e,t,n=new Set){if(t==null||n.has(t))return t;if(n.add(t),t.$ref&&typeof t.$ref=="string"){let r=se(e,t.$ref),o={...B(e,r,n)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(o[a]=B(e,t[a],n));return o}if(Array.isArray(t))return t.map(r=>B(e,r,n));if(typeof t=="object"){let r={};for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=B(e,t[i],n));return r}return t}function le(e){return B(e,{...e})}function Se(e,t=!1){let n=s=>(t&&console.log(`OpenAPI Schema validation failed: ${s}`),!1);if(typeof e!="object"||e===null)return n(`Input is ${e===null?"null":typeof e}, not an object`);let r=e;if(!(typeof r.type=="string"||Array.isArray(r.enum)||typeof r.properties=="object"||typeof r.items=="object"||typeof r.allOf=="object"||typeof r.anyOf=="object"||typeof r.oneOf=="object"||typeof r.not=="object"))return n("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(r.type!==void 0){let s=["string","number","integer","boolean","array","object","null"];if(typeof r.type=="string"){if(!s.includes(r.type))return n(`Invalid type: ${r.type}. Must be one of ${s.join(", ")}`)}else if(Array.isArray(r.type)){for(let l of r.type)if(typeof l!="string"||!s.includes(l))return n(`Array of types contains invalid value: ${l}. Must be one of ${s.join(", ")}`)}else return n(`Type must be a string or array of strings, got ${typeof r.type}`)}if(r.items!==void 0&&(typeof r.items!="object"||r.items===null))return n(`Items must be an object, got ${r.items===null?"null":typeof r.items}`);if(r.properties!==void 0&&(typeof r.properties!="object"||r.properties===null))return n(`Properties must be an object, got ${r.properties===null?"null":typeof r.properties}`);let o=["allOf","anyOf","oneOf"];for(let s of o)if(r[s]!==void 0){if(!Array.isArray(r[s]))return n(`${s} must be an array, got ${typeof r[s]}`);for(let l=0;l<r[s].length;l++){let u=r[s][l];if(typeof u!="object"||u===null)return n(`Item ${l} in ${s} must be an object, got ${u===null?"null":typeof u}`)}}if(r.not!==void 0&&(typeof r.not!="object"||r.not===null))return n(`'not' must be an object, got ${r.not===null?"null":typeof r.not}`);if(r.additionalProperties!==void 0&&typeof r.additionalProperties!="boolean"&&(typeof r.additionalProperties!="object"||r.additionalProperties===null))return n(`additionalProperties must be a boolean or an object, got ${r.additionalProperties===null?"null":typeof r.additionalProperties}`);if(r.format!==void 0&&typeof r.format!="string")return n(`format must be a string, got ${typeof r.format}`);let a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let s of a)if(r[s]!==void 0&&typeof r[s]!="number")return n(`${s} must be a number, got ${typeof r[s]}`);if(r.minLength!==void 0&&(typeof r.minLength!="number"||r.minLength<0))return n(`minLength must be a non-negative number, got ${typeof r.minLength=="number"?r.minLength:typeof r.minLength}`);if(r.maxLength!==void 0&&(typeof r.maxLength!="number"||r.maxLength<0))return n(`maxLength must be a non-negative number, got ${typeof r.maxLength=="number"?r.maxLength:typeof r.maxLength}`);if(r.pattern!==void 0&&typeof r.pattern!="string")return n(`pattern must be a string, got ${typeof r.pattern}`);if(r.minItems!==void 0&&(typeof r.minItems!="number"||r.minItems<0))return n(`minItems must be a non-negative number, got ${typeof r.minItems=="number"?r.minItems:typeof r.minItems}`);if(r.maxItems!==void 0&&(typeof r.maxItems!="number"||r.maxItems<0))return n(`maxItems must be a non-negative number, got ${typeof r.maxItems=="number"?r.maxItems:typeof r.maxItems}`);if(r.uniqueItems!==void 0&&typeof r.uniqueItems!="boolean")return n(`uniqueItems must be a boolean, got ${typeof r.uniqueItems}`);if(r.minProperties!==void 0&&(typeof r.minProperties!="number"||r.minProperties<0))return n(`minProperties must be a non-negative number, got ${typeof r.minProperties=="number"?r.minProperties:typeof r.minProperties}`);if(r.maxProperties!==void 0&&(typeof r.maxProperties!="number"||r.maxProperties<0))return n(`maxProperties must be a non-negative number, got ${typeof r.maxProperties=="number"?r.maxProperties:typeof r.maxProperties}`);if(r.required!==void 0){if(!Array.isArray(r.required))return n(`required must be an array, got ${typeof r.required}`);for(let s=0;s<r.required.length;s++){let l=r.required[s];if(typeof l!="string")return n(`Item ${s} in required array must be a string, got ${typeof l}`)}}return!0}function xt(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let n=[],r=kt(e,t);return r??(Object.entries(e.properties).forEach(i=>{let o=i[0],a=i[1];n.push({id:o,schema:a})}),n)}function kt(e,t){if(t.orderExtensionKeyword==null)return;let n=[];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,i=r.find(a=>a in e);if(i==null)return;let o=e[i];if(o==null||Array.isArray(o)===!1)throw new Error(`Extension keyword ${i} must be an array of strings`);if([...new Set(o)].forEach(a=>{let s=e.properties?.[a];s!=null&&n.push({id:a,schema:s})}),n.length===0)throw new Error(`Could not find any properties with order extension keyword(s) ${r.join(", ")}`);return n}var q=xt;var Mt="ly.img.ai",ue="ly.img.ai/temp";async function Pe(e,t){return e.engine.asset.findAllSources().includes(ue)||e.engine.asset.addLocalSource(ue),e.engine.asset.apply(ue,t)}function G(e){return`${Mt}/${e}`}function De(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 n=e;return"message"in n&&typeof n.message=="string"?n.message:"cause"in n&&typeof n.cause=="string"?n.cause:"detail"in n&&typeof n.detail=="object"&&n.detail!==null&&"message"in n.detail&&typeof n.detail.message=="string"?n.detail.message:"error"in n&&typeof n.error=="object"&&n.error!==null&&"message"in n.error&&typeof n.error.message=="string"?n.error.message:t}return typeof e=="string"?e:String(e)||t}function Re(){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 At(e){return new Promise((t,n)=>{try{let r=document.createElement("video");r.style.display="none",r.addEventListener("loadedmetadata",()=>{r.duration===1/0?(r.currentTime=1e101,setTimeout(()=>{r.currentTime=0,t(r.duration),document.body.removeChild(r)},50)):(t(r.duration),document.body.removeChild(r))}),r.addEventListener("error",()=>{document.body.removeChild(r),n(new Error(`Failed to load video from ${e}`))}),r.src=e,document.body.appendChild(r)}catch(r){n(r)}})}function ce(e,t=0,n="image/jpeg",r=.8){return new Promise((i,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 l=s.getContext("2d");if(!l){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}l.drawImage(a,0,0,s.width,s.height);try{let u=s.toDataURL(n,r);document.body.removeChild(a),i(u)}catch(u){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${u instanceof Error?u.message:String(u)}`))}},{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 Y(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 A(e){return typeof e=="object"&&e!==null&&"next"in e&&"return"in e&&"throw"in e&&typeof e.next=="function"&&typeof e.return=="function"&&typeof e.throw=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}function k(e){return e instanceof Error&&e.name==="AbortError"}function Ne(e,t,n,r,i,o){let a=t.schema.type;if(r.renderCustomProperty!=null&&r.renderCustomProperty[t.id]!=null)return r.renderCustomProperty[t.id](e,t);switch(a){case"string":return t.schema.enum!=null?Et(e,t,n,r,i,o):Le(e,t,n,r,i,o);case"boolean":return Te(e,t,n,r,i,o);case"number":case"integer":return $e(e,t,n,r,i,o);case"object":return je(e,t,n,r,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return St(e,t,n,r,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function je(e,t,n,r,i,o){let s=q(t.schema??{},r).reduce((l,u)=>{let d=Ne(e,u,n,r,i,o);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function Le(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=s(u,t.schema.default??""),p=Pt(t.schema),m=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[m](u,{inputLabel:d,placeholder:i.i18n?.prompt,...c}),()=>({id:t.id,type:"string",value:c.value})}function Et(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=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"]:{},p=(t.schema.enum??[]).map(I=>({id:I,label:c[I]??Y(I)})),m=t.schema.default!=null?p.find(I=>I.id===t.schema.default)??p[0]:p[0],v=s(u,m);return a.Select(u,{inputLabel:d,values:p,...v}),()=>({id:t.id,type:"string",value:v.value.id})}function Te(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=!!t.schema.default,p=s(u,c);return a.Checkbox(u,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function $e(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.minimum,p=t.schema.maximum,m=t.schema.default;m==null&&(c!=null?m=c:p!=null?m=p:m=0);let v=s(u,m);if(c!=null&&p!=null){let I=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(I=t.schema["x-imgly-step"]),a.Slider(u,{inputLabel:d,min:c,max:p,step:I,...v})}else a.NumberInput(u,{inputLabel:d,min:c,max:p,...v});return()=>({id:t.id,type:"integer",value:v.value})}function St(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.anyOf??[],p=[],m={},v={};c.forEach((f,g)=>{let h=f.title??"common.custom",y=`${n.id}.${l}.anyOf[${g}]`,O="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},w="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(x=>{p.push({id:x,label:O[x]??Y(x),icon:w[x]})}):(m[y]=()=>Le(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="boolean"?(m[y]=()=>Te(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="integer"?(m[y]=()=>$e(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="array"||f.type==="object"&&(m[y]=()=>je(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]}))});let I=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],b=s(u,I);if(a.Select(u,{inputLabel:d,values:p,...b}),b.value.id in m){let f=m[b.value.id]();v[b.value.id]=f}return()=>{let f=v[b.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:b.value.id}}}function Pt(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Be=Ne;var Dt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",de=Dt;function Rt(e,t,n){switch(t){case"image":return Nt(e,n[t]);case"video":return jt(e,n[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Nt(e,t){let n=t.width,r=t.height;return{id:e,meta:{previewUri:de,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:r}}}function jt(e,t){let n=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:de,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:r}}}var Ge=Rt;function Lt(e,t){switch(e){case"image":return Tt(t[e]);case"video":return $t(t[e]);default:throw new Error(`Unsupported output kind for creating dry run output: ${e}`)}}function Tt(e){let t=e.width,n=e.height,r=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image";return{kind:"image",url:`https://placehold.co/${t}x${n}/000000/FFF?text=${r.replace(" ","+").replace(`
2
+ `,"+")}`}}function $t(e){return{kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"}}var Ve=Lt;async function Bt(e,t,n,r){switch(t){case"image":{if(r.kind!=="image")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: image)`);return Gt(e,n[t],r)}case"video":{if(r.kind!=="video")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: video)`);return Vt(e,n[t],r)}case"audio":{if(r.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: audio)`);return Ft(e,n[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Gt(e,t,n){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i},payload:{sourceSet:[{uri:n.url,width:r,height:i}]}}}async function Vt(e,t,n){let r=t.width,i=t.height,o=await ce(n.url,0);return{id:e,label:t.label,meta:{uri:n.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Ft(e,t,n){return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:n.duration.toString()}}}var pe=Bt;function V(e){let t=e.filter(n=>!!n);return n=>async(r,i)=>{let o=[],a=c=>{o.push(c)},s=async(c,p,m)=>{if(c>=t.length)return n(p,m);let v=t[c],I=async(f,g)=>s(c+1,f,g),b={...m,addDisposer:a};return v(p,b,I)},l={...i,addDisposer:a};return{result:await s(0,r,l),dispose:async()=>{for(let c=o.length-1;c>=0;c--)try{await o[c]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function _t(){return async(t,n,r)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let i,o=Date.now();try{return i=await r(t,n),i}finally{i!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(i,null,2))),console.groupEnd()}}}var F=_t;async function Kt(e,t,n,r,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:u}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let c=t(),p=await n(c.input),m=Re(),v;if(l){if(v=Ge(m,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(v,void 0,2)),d=await Pe(s,v),d!=null&&r.kind==="video"){let g=s.engine.block.getPositionX(d),h=s.engine.block.getPositionY(d),y=s.engine.block.duplicate(d);s.engine.block.setPositionX(y,g),s.engine.block.setPositionY(y,h),s.engine.block.destroy(d),d=y}if(W(s,a,d))return{status:"aborted"};if(d==null)throw new Error("Could not create placeholder block");s.engine.block.setState(d,{type:"Pending",progress:0})}let I=V([...r.output.middleware??[],o.debug?F():void 0]),b;if(o.dryRun?b=await Ut(e,p):b=(await I(r.output.generate)(c.input,{abortSignal:a,engine:i.engine,cesdk:s})).result,A(b))throw new Error("Streaming generation is not supported yet from a panel");if(W(s,a,d))return{status:"aborted"};if(b==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(b,void 0,2));let f;if(d!=null&&s.engine.block.isValid(d)&&(f=await pe(m,e,p,b),o.debug&&console.log("Updating asset in scene:",JSON.stringify(f,void 0,2)),await s.engine.asset.defaultApplyAssetToBlock(f,d)),W(s,a,d))return{status:"aborted"};if(u!=null){if(f==null&&(f=await pe(m,e,p,b),W(s,a,d)))return{status:"aborted"};let g={...f,id:`${Date.now()}-${f.id}`,label:f.label!=null?{en:f.label}:{},tags:{}};s.engine.asset.addAssetToSource(u,g)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:b}}catch(c){throw d!=null&&s.engine.block.isValid(d)&&(k(c)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),c}finally{o.debug&&console.groupEnd()}}function W(e,t,n){return t.aborted?(n!=null&&e.engine.block.isValid(n)&&e.engine.block.destroy(n),!0):!1}async function Ut(e,t){console.log("[DRY RUN]: Requesting dummy AI generation with block inputs: ",JSON.stringify(t,void 0,2));let n=Ve(e,t);return await zt(3e3),n}async function zt(e){return new Promise(t=>{setTimeout(t,e)})}var Fe=Kt;function Ht(e,t,n){let{cesdk:r,provider:i,getInput:o}=t;n.onError!=null&&typeof n.onError=="function"?n.onError(e):(console.error("Generation failed:",e),Qt(r,i.output.notification,()=>({input:o?.().input,error:e}))||r.ui.showNotification({type:"error",message:De(e)}))}function Qt(e,t,n){let r=t?.error;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.failed",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"error",message:o,action:a}),!0}var E=Ht;function J(e){return`${e}.generating`}function _e(e){return`${e}.abort`}function Zt(e,t,n,r,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:u=!0}=i,{id:d,output:{abortable:c}}=t,p=s.global(_e(d),()=>{}),m=s.global(J(d),!1),v,I=m.value&&c,b=()=>{I&&(p.value(),m.setValue(!1),p.setValue(()=>{}))},f;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let h=n();f=i.requiredInputs.every(y=>!h.input[y])}let g=s.global(`${d}.confirmationDialogId`,void 0);a.Section(`${d}.generate.section`,{children:()=>{a.Button(`${d}.generate`,{label:["common.ai-generation.generate",`panel.${d}.generate`],isLoading:m.value,color:"accent",isDisabled:f,suffix:I?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let h=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:y})=>{l.ui.closeDialog(y),g.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:y})=>{b(),l.ui.closeDialog(y),g.setValue(void 0)}}});g.setValue(h)}}:void 0,onClick:async()=>{v=new AbortController;let h=v.signal,y=async()=>{try{m.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),v?.abort()});let O=await Fe(t.kind,n,r,t,i,o,h);if(O.status==="aborted")return;let w=t.output.notification;qt(l,w,()=>({input:n().input,output:O.output}))}catch(O){if(k(O))return;E(O,{cesdk:l,provider:t,getInput:n},o)}finally{v=void 0,m.setValue(!1),p.setValue(()=>{}),g.value!=null&&(l.ui.closeDialog(g.value),g.setValue(void 0))}};o.middleware!=null?await o.middleware(y,{provider:t,abort:b}):await y()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&i.historyAssetLibraryEntryId!=null&&a.Library(`${d}.history.library`,{entries:[i.historyAssetLibraryEntryId]})}function qt(e,t,n){let r=t?.success;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.success",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"success",message:o,action:a,duration:r.duration}),!0}var X=Zt;async function Yt(e,t,n,r){let{cesdk:i}=n,{id:o}=e;r.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=le(t.document),s=se(a,t.inputReference);if(!Se(s,r.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,u=q(l,t),d=c=>{let{builder:p}=c,m=[];p.Section(`${o}.schema.section`,{children:()=>{u.forEach(f=>{let g=Be(c,f,e,t,n,r);g!=null&&(Array.isArray(g)?m.push(...g):m.push(g))})}});let v=m.map(f=>f()),I=f=>f.type==="object"?Object.entries(f.value).reduce((g,[h,y])=>(g[h]=I(y),g),{}):f.value,b=v.reduce((f,g)=>(f[g.id]=I(g),f),{});X(c,e,()=>({input:b}),()=>t.getBlockInput(b),{...n,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},r)};return i.ui.registerPanel(G(o),d),d}var Ke=Yt;async function Wt(e,t,n,r){let{cesdk:i}=n,{id:o}=e,a=t.render,s=l=>{let{state:u}=l,d=u(J(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:c,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return X(l,e,c,p,{...n,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},r),c};return i.ui.registerPanel(G(o),s),s}var Ue=Wt;var ot=class{constructor(e,t,n){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=n?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=n?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=r=>{t(new Error(`Failed to open IndexedDB: ${r.target.error}`))},n.onupgradeneeded=r=>{let i=r.target.result;i.objectStoreNames.contains(this.assetStoreName)||i.createObjectStore(this.assetStoreName,{keyPath:"id"}),i.objectStoreNames.contains(this.blobStoreName)||i.createObjectStore(this.blobStoreName,{keyPath:"id"})},n.onsuccess=r=>{this.db=r.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((l,u)=>{let d=e.locale??"en",c="",p=[];u.label!=null&&typeof u.label=="object"&&u.label[d]&&(c=u.label[d]),u.tags!=null&&typeof u.tags=="object"&&u.tags[d]&&(p=u.tags[d]);let m={...u,label:c,tags:p};return this.filterAsset(m,e)&&l.push(m),l},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:n,perPage:r}=e,i=n*r,o=i+r,a=t.slice(i,o),s=o<t.length?n+1:void 0;return{assets:a,currentPage:n,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 n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let r=new Set;n.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>r.add(a))});let i=[...r];e(i)},n.onerror=()=>{t(new Error(`Failed to get groups: ${n.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),n=t.objectStore(this.assetStoreName),r=new Set;R(e,o=>{r.add(o)}),setTimeout(()=>{this.storeBlobUrls([...r])});let i={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};n.put(i),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 n=this.db.transaction(this.assetStoreName,"readwrite");n.objectStore(this.assetStoreName).delete(e),n.oncomplete=()=>{R(t,r=>{this.removeBlob(r)}),this.engine.asset.assetSourceContentsChanged(this.id)},n.onerror=()=>{console.error(`Failed to remove asset: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}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,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=r.result;i.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),l=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-l:l-s}),t(i)},r.onerror=()=>{n(new Error(`Failed to get assets: ${r.error}`))}})}async getAsset(e){return new Promise((t,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.error}`))}})}async getBlob(e){return new Promise((t,n)=>{let r=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.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 n=>{let r=await(await fetch(n)).blob();t[n]=r})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let n=this.db.transaction(this.blobStoreName,"readwrite"),r=n.objectStore(this.blobStoreName);Object.entries(t).forEach(([i,o])=>{let a={id:i,blob:o};r.put(a)}),n.onerror=()=>{console.error(`Failed to add blobs: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}async restoreBlobUrls(e){let t={},n=new Set;return R(e,r=>{n.add(r)}),await Promise.all([...n].map(async r=>{let i=await this.createBlobUrlFromStore(r);t[r]=i})),R(e,r=>t[r]??r)}filterAsset(e,t){let{query:n,tags:r,groups:i,excludeGroups:o}=t;if(n&&n.trim()!==""){let a=n.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",l=e.tags?.map(u=>u.toLowerCase())??[];if(!a.every(u=>s.includes(u)||l.some(d=>d.includes(u))))return!1}if(r){let a=Array.isArray(r)?r:[r];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(i&&i.length>0&&(!e.groups||!i.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:n,sortKey:r,sortActiveFirst:i}=t,o=[...e];return!n||n==="None"||(r?o.sort((a,s)=>{let l,u;return r==="id"?(l=a.id,u=s.id):(l=a.meta?.[r]??null,u=s.meta?.[r]??null),l==null?n==="Ascending"?-1:1:u==null?n==="Ascending"?1:-1:typeof l=="string"&&typeof u=="string"?n==="Ascending"?l.localeCompare(u):u.localeCompare(l):n==="Ascending"?l<u?-1:l>u?1:0:l>u?-1:l<u?1:0}):n==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function R(e,t,n=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let r=0;r<e.length;r++){let i=n?`${n}[${r}]`:`[${r}]`;if(typeof e[r]=="string"&&e[r].startsWith("blob:")){let o=t(e[r],i);typeof o=="string"&&(e[r]=o)}else e[r]=R(e[r],t,i)}return e}for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let i=e[r],o=n?`${n}.${r}`:r;if(typeof i=="string"&&i.startsWith("blob:")){let a=t(i,o);typeof a=="string"&&(e[r]=a)}else e[r]=R(i,t,o)}return e}var Jt=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)}},ve=Jt,Xt=typeof global=="object"&&global&&global.Object===Object&&global,at=Xt,er=typeof self=="object"&&self&&self.Object===Object&&self,tr=at||er||Function("return this")(),M=tr,rr=M.Symbol,N=rr,st=Object.prototype,nr=st.hasOwnProperty,ir=st.toString,_=N?N.toStringTag:void 0;function or(e){var t=nr.call(e,_),n=e[_];try{e[_]=void 0;var r=!0}catch{}var i=ir.call(e);return r&&(t?e[_]=n:delete e[_]),i}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]",ze=N?N.toStringTag:void 0;function fr(e){return e==null?e===void 0?pr:dr:ze&&ze in Object(e)?ar(e):cr(e)}var H=fr;function gr(e){return e!=null&&typeof e=="object"}var Oe=gr,da=Array.isArray;function mr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var lt=mr,yr="[object AsyncFunction]",br="[object Function]",hr="[object GeneratorFunction]",Ir="[object Proxy]";function vr(e){if(!lt(e))return!1;var t=H(e);return t==br||t==hr||t==yr||t==Ir}var Or=vr,Cr=M["__core-js_shared__"],fe=Cr,He=function(){var e=/[^.]+$/.exec(fe&&fe.keys&&fe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function wr(e){return!!He&&He in e}var xr=wr,kr=Function.prototype,Mr=kr.toString;function Ar(e){if(e!=null){try{return Mr.call(e)}catch{}try{return e+""}catch{}}return""}var S=Ar,Er=/[\\^$.*+?()[\]{}|]/g,Sr=/^\[object .+?Constructor\]$/,Pr=Function.prototype,Dr=Object.prototype,Rr=Pr.toString,Nr=Dr.hasOwnProperty,jr=RegExp("^"+Rr.call(Nr).replace(Er,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Lr(e){if(!lt(e)||xr(e))return!1;var t=Or(e)?jr:Sr;return t.test(S(e))}var Tr=Lr;function $r(e,t){return e?.[t]}var Br=$r;function Gr(e,t){var n=Br(e,t);return Tr(n)?n:void 0}var j=Gr,Vr=j(M,"WeakMap"),me=Vr;function Fr(e,t){return e===t||e!==e&&t!==t}var _r=Fr,Kr=9007199254740991;function Ur(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Kr}var zr=Ur;var pa=Object.prototype;var Hr="[object Arguments]";function Qr(e){return Oe(e)&&H(e)==Hr}var Qe=Qr,ut=Object.prototype,Zr=ut.hasOwnProperty,qr=ut.propertyIsEnumerable,fa=Qe(function(){return arguments}())?Qe:function(e){return Oe(e)&&Zr.call(e,"callee")&&!qr.call(e,"callee")};var ct=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ze=ct&&typeof module=="object"&&module&&!module.nodeType&&module,Yr=Ze&&Ze.exports===ct,qe=Yr?M.Buffer:void 0,ga=qe?qe.isBuffer:void 0;var Wr="[object Arguments]",Jr="[object Array]",Xr="[object Boolean]",en="[object Date]",tn="[object Error]",rn="[object Function]",nn="[object Map]",on="[object Number]",an="[object Object]",sn="[object RegExp]",ln="[object Set]",un="[object String]",cn="[object WeakMap]",dn="[object ArrayBuffer]",pn="[object DataView]",fn="[object Float32Array]",gn="[object Float64Array]",mn="[object Int8Array]",yn="[object Int16Array]",bn="[object Int32Array]",hn="[object Uint8Array]",In="[object Uint8ClampedArray]",vn="[object Uint16Array]",On="[object Uint32Array]",C={};C[fn]=C[gn]=C[mn]=C[yn]=C[bn]=C[hn]=C[In]=C[vn]=C[On]=!0;C[Wr]=C[Jr]=C[dn]=C[Xr]=C[pn]=C[en]=C[tn]=C[rn]=C[nn]=C[on]=C[an]=C[sn]=C[ln]=C[un]=C[cn]=!1;function Cn(e){return Oe(e)&&zr(e.length)&&!!C[H(e)]}var wn=Cn;function xn(e){return function(t){return e(t)}}var kn=xn,dt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,K=dt&&typeof module=="object"&&module&&!module.nodeType&&module,Mn=K&&K.exports===dt,ge=Mn&&at.process,An=function(){try{var e=K&&K.require&&K.require("util").types;return e||ge&&ge.binding&&ge.binding("util")}catch{}}(),Ye=An,We=Ye&&Ye.isTypedArray,ma=We?kn(We):wn;var En=Object.prototype,ya=En.hasOwnProperty;function Sn(e,t){return function(n){return e(t(n))}}var Pn=Sn,ba=Pn(Object.keys,Object);var Dn=Object.prototype,ha=Dn.hasOwnProperty;var Rn=j(Object,"create"),U=Rn;function Nn(){this.__data__=U?U(null):{},this.size=0}var jn=Nn;function Ln(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Tn=Ln,$n="__lodash_hash_undefined__",Bn=Object.prototype,Gn=Bn.hasOwnProperty;function Vn(e){var t=this.__data__;if(U){var n=t[e];return n===$n?void 0:n}return Gn.call(t,e)?t[e]:void 0}var Fn=Vn,_n=Object.prototype,Kn=_n.hasOwnProperty;function Un(e){var t=this.__data__;return U?t[e]!==void 0:Kn.call(t,e)}var zn=Un,Hn="__lodash_hash_undefined__";function Qn(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=U&&t===void 0?Hn:t,this}var Zn=Qn;function L(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}L.prototype.clear=jn;L.prototype.delete=Tn;L.prototype.get=Fn;L.prototype.has=zn;L.prototype.set=Zn;var Je=L;function qn(){this.__data__=[],this.size=0}var Yn=qn;function Wn(e,t){for(var n=e.length;n--;)if(_r(e[n][0],t))return n;return-1}var ee=Wn,Jn=Array.prototype,Xn=Jn.splice;function ei(e){var t=this.__data__,n=ee(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Xn.call(t,n,1),--this.size,!0}var ti=ei;function ri(e){var t=this.__data__,n=ee(t,e);return n<0?void 0:t[n][1]}var ni=ri;function ii(e){return ee(this.__data__,e)>-1}var oi=ii;function ai(e,t){var n=this.__data__,r=ee(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var si=ai;function T(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}T.prototype.clear=Yn;T.prototype.delete=ti;T.prototype.get=ni;T.prototype.has=oi;T.prototype.set=si;var te=T,li=j(M,"Map"),z=li;function ui(){this.size=0,this.__data__={hash:new Je,map:new(z||te),string:new Je}}var ci=ui;function di(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var pi=di;function fi(e,t){var n=e.__data__;return pi(t)?n[typeof t=="string"?"string":"hash"]:n.map}var re=fi;function gi(e){var t=re(this,e).delete(e);return this.size-=t?1:0,t}var mi=gi;function yi(e){return re(this,e).get(e)}var bi=yi;function hi(e){return re(this,e).has(e)}var Ii=hi;function vi(e,t){var n=re(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var Oi=vi;function $(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}$.prototype.clear=ci;$.prototype.delete=mi;$.prototype.get=bi;$.prototype.has=Ii;$.prototype.set=Oi;var pt=$;function Ci(){this.__data__=new te,this.size=0}var wi=Ci;function xi(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var ki=xi;function Mi(e){return this.__data__.get(e)}var Ai=Mi;function Ei(e){return this.__data__.has(e)}var Si=Ei,Pi=200;function Di(e,t){var n=this.__data__;if(n instanceof te){var r=n.__data__;if(!z||r.length<Pi-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new pt(r)}return n.set(e,t),this.size=n.size,this}var Ri=Di;function Q(e){var t=this.__data__=new te(e);this.size=t.size}Q.prototype.clear=wi;Q.prototype.delete=ki;Q.prototype.get=Ai;Q.prototype.has=Si;Q.prototype.set=Ri;var Ni=Object.prototype,Ia=Ni.propertyIsEnumerable;var ji=j(M,"DataView"),ye=ji,Li=j(M,"Promise"),be=Li,Ti=j(M,"Set"),he=Ti,Xe="[object Map]",$i="[object Object]",et="[object Promise]",tt="[object Set]",rt="[object WeakMap]",nt="[object DataView]",Bi=S(ye),Gi=S(z),Vi=S(be),Fi=S(he),_i=S(me),D=H;(ye&&D(new ye(new ArrayBuffer(1)))!=nt||z&&D(new z)!=Xe||be&&D(be.resolve())!=et||he&&D(new he)!=tt||me&&D(new me)!=rt)&&(D=function(e){var t=H(e),n=t==$i?e.constructor:void 0,r=n?S(n):"";if(r)switch(r){case Bi:return nt;case Gi:return Xe;case Vi:return et;case Fi:return tt;case _i:return rt}return t});var va=M.Uint8Array;var Ki="__lodash_hash_undefined__";function Ui(e){return this.__data__.set(e,Ki),this}var zi=Ui;function Hi(e){return this.__data__.has(e)}var Qi=Hi;function Ie(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new pt;++t<n;)this.add(e[t])}Ie.prototype.add=Ie.prototype.push=zi;Ie.prototype.has=Qi;var it=N?N.prototype:void 0,Oa=it?it.valueOf:void 0;var Zi=Object.prototype,Ca=Zi.hasOwnProperty;var qi=Object.prototype,wa=qi.hasOwnProperty;var xa=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),ka=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Ma=new RegExp(/[A-Fa-f0-9]{2}/,"g");var Ce="@imgly/plugin-ai-generation",Yi=`
3
3
  <svg>
4
4
  <symbol
5
5
  fill="none"
@@ -17,7 +17,7 @@ function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]
17
17
  fill="none"
18
18
  xmlns="http://www.w3.org/2000/svg"
19
19
  viewBox="0 0 24 24"
20
- id="${Oe}/image"
20
+ id="${Ce}/image"
21
21
  >
22
22
  <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
23
  <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 +29,7 @@ function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]
29
29
  fill="none"
30
30
  xmlns="http://www.w3.org/2000/svg"
31
31
  viewBox="0 0 24 24"
32
- id="${Oe}/video"
32
+ id="${Ce}/video"
33
33
  >
34
34
  <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
35
  <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 +40,7 @@ function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]
40
40
  fill="none"
41
41
  xmlns="http://www.w3.org/2000/svg"
42
42
  viewBox="0 0 24 24"
43
- id="${Oe}/audio"
43
+ id="${Ce}/audio"
44
44
  >
45
45
  <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
46
  <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 +60,7 @@ function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]
60
60
 
61
61
  </symbol>
62
62
  </svg>
63
- `,pt=qi;var ft="ly.img.ai.quickAction.order",Z="ly.img.ai.quickAction.actions";function Yi(e,t){return{id:t,setQuickActionMenuOrder:r=>{e.ui.experimental.setGlobalStateValue(`${ft}.${t}`,r)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${ft}.${t}`,[]),registerQuickAction:r=>{if(!e.ui.experimental.hasGlobalStateValue(`${Z}.${t}`))e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{[r.id]:r});else{let i=e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{...i,[r.id]:r})}},getQuickAction:r=>e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{})[r]}}var Ce=Yi;var ne="ly.img.ai.inference.editMode",we="ly.img.ai.inference.metadata";function ie(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function mt(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((n,r)=>(r==="ly.img.separator"&&n.length>0&&n[n.length-1]==="ly.img.separator"||n.push(r),n),[])}function Wi({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(r,i,o)=>{let a={},s={},l=e||t?i.blockIds??i.engine.block.findAllSelected():[];return l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&(a[d]=i.engine.block.isAlwaysOnTop(d),i.engine.block.setAlwaysOnTop(d,!0)),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&(s[c]=i.engine.block.isClipped(c),i.engine.block.setClipped(c,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&s[c]!=null&&i.engine.block.setClipped(c,s[c])}})}),await o(r,i)}}var gt=Wi;function Ji({pending:e=!0}){return async(n,r,i)=>{let o=e?r.blockIds??r.engine.block.findAllSelected():[];try{return o.forEach(s=>{r.engine.block.isValid(s)&&r.engine.block.setState(s,{type:"Pending",progress:0})}),await i(n,r)}finally{o.forEach(a=>{r.engine.block.isValid(a)&&r.engine.block.setState(a,{type:"Ready"})})}}}var yt=Ji;function Xi({editMode:e,automaticallyUnlock:t=!1}){return async(r,i,o)=>{let a=i.blockIds??i.engine.block.findAllSelected(),s=()=>{};t||i.addDisposer(async()=>{s?.()});try{return s=eo(i.engine,a,e),await o(r,i)}catch(l){throw k(l)&&s(),l}finally{t&&s()}}}function eo(e,t,n){let r=e.editor.getGlobalScope("editor/select"),i=e.editor.getEditMode();s(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(n);let o=e.editor.createHistory(),a=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function s(){e.block.findAllSelected().forEach(c=>{t.includes(c)||e.block.setSelected(c,!1)}),t.forEach(c=>{e.block.setSelected(c,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&e.editor.setEditMode(n)}),u=e.block.onSelectionChanged(s);return()=>{r!=null&&e.editor.setGlobalScope("editor/select",r),e.editor.setEditMode(i),e.editor.setActiveHistory(a),e.editor.destroyHistory(o),u(),l()}}var bt=Xi;function to(e,t){switch(t.kind){case"text":return ro(e,t);case"image":return no(e,t);case"video":return io(e,t);case"audio":return oo(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function ro(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t,o=r.map(c=>n.engine.block.getString(c,"text/text")),a;if(A(e)){let c="";for await(let p of e){if(i.aborted)break;typeof p=="string"?c=p:p.kind==="text"&&(c=p.text),r.forEach(v=>{n.engine.block.setString(v,"text/text",c)}),a={kind:"text",text:c}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(c=>{t.cesdk.engine.block.setString(c,"text/text",a.text)})},l=()=>{t.blockIds.forEach((c,p)=>{t.cesdk.engine.block.setString(c,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:s}}}async function no(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t;if(r.length!==1)throw new Error("Only one block is supported for image generation");let[o]=r,a=n.engine.block.getFill(o),s=n.engine.block.getSourceSet(a,"fill/image/sourceSet"),[l]=s,u;l==null&&(u=n.engine.block.getString(a,"fill/image/imageFileURI"));let d=await n.engine.editor.getMimeType(l?.uri??u);if(i.throwIfAborted(),d==="image/svg+xml")throw new Error("SVG images are not supported");let c=n.engine.block.getCropScaleX(o),p=n.engine.block.getCropScaleY(o),g=n.engine.block.getCropTranslationX(o),v=n.engine.block.getCropTranslationY(o),I=n.engine.block.getCropRotation(o),b=()=>{n.engine.block.setCropScaleX(o,c),n.engine.block.setCropScaleY(o,p),n.engine.block.setCropTranslationX(o,g),n.engine.block.setCropTranslationY(o,v),n.engine.block.setCropRotation(o,I)};if(A(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 f=e.url,m=await n.engine.editor.getMimeType(f),h=await ao(n,f,m),y=l?[{uri:h,width:l.width,height:l.height}]:void 0,O=h;y==null?n.engine.block.setString(a,"fill/image/imageFileURI",O):n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),b();let w=()=>{if(s==null){if(u==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",u)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",s);b()},x=()=>{if(y==null){if(O==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",O)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",y);b()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:w,onAfter:x,onCancel:()=>{w()},onApply:()=>{x()}}}}async function io(e,t){throw new Error("Function not implemented.")}async function oo(e,t){throw new Error("Function not implemented.")}async function ao(e,t,n){let i=await(await fetch(t)).blob(),o=new File([i],`image.${so(n)}`,{type:n}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}function so(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}var ht=to;function lo({editMode:e,automaticallyUnlock:t=!1,showNotification:n=!0}){return async(i,o,a)=>{let s=o.blockIds??o.engine.block.findAllSelected(),l=()=>{};t||o.addDisposer(async()=>{l?.()});try{l=uo(o.engine,s,e);let u=await a(i,o);if(n){let d=o.engine.block.findAllSelected();s.some(p=>d.includes(p))||o.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{s.forEach(p=>{o.engine.block.select(p)})}}})}return u}catch(u){throw k(u)&&l(),u}finally{t&&l()}}}function uo(e,t,n){function r(){let s=e.block.findAllSelected();return t.some(l=>s.includes(l))}let i=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&r()&&e.editor.setEditMode(n)}),o=e.block.onSelectionChanged(()=>{r()?e.editor.setEditMode(n):e.editor.setEditMode("Transform")});return r()&&e.editor.setEditMode(n),()=>{o(),i(),e.editor.setEditMode("Transform")}}var It=lo;function co(e,t){let{cesdk:n,quickActionMenu:r,provider:i}=e,o=`ly.img.ai.${r.id}`,a=`${o}.confirmation`;n.setTranslations({en:{[`${a}.apply`]:"Apply",[`${a}.before`]:"Before",[`${a}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let s=`${a}.canvasnMenu`,l={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},u=()=>{let c=new AbortController,p=c.signal;return l.abort=()=>{c.abort()},p};n.ui.registerComponent(s,({builder:c,engine:p,state:g})=>{let v=p.block.findAllSelected();if(v.length===0)return null;let I=new Ie(n.engine,we),b=I.get(v[0]);if(b==null)return null;let f=()=>{v.forEach(m=>{I.clear(m)})};switch(b.status){case"processing":{c.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${b.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),c.Separator(`${o}.separator`),c.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),f()}});break}case"confirmation":{let m=g(`${a}.comparing`,"after"),h=l.applyCallbacks?.onCancel;h!=null&&c.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),h(),f()}});let y=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;y!=null&&O!=null&&c.ButtonGroup(`${a}.compare`,{children:()=>{c.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:m.value==="before",onClick:()=>{y(),m.setValue("before")}}),c.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:m.value==="after",onClick:()=>{O(),m.setValue("after")}})}});let w=l.applyCallbacks?.onApply;w!=null&&c.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:m.value!=="after",onClick:()=>{l.unlock(),f(),n.engine.editor._update(),w(),p.editor.addUndoStep()}});break}default:}});let d=`${o}.canvasMenu`;return n.ui.registerComponent(d,c=>{let p=c.engine.block.findAllSelected(),g=r.getQuickActionMenuOrder().map(m=>{if(m==="ly.img.separator")return m;let h=r.getQuickAction(m);if(h==null||!n.feature.isEnabled(ie({quickActionId:m,quickActionMenuId:r.id}),{engine:c.engine}))return null;let O=h.scopes;return O!=null&&O.length>0&&!p.every(x=>O.every(P=>c.engine.block.isAllowedByScope(x,P)))?null:h}).filter(m=>m!=null);if(g=mt(g),g.length===0||g.every(m=>m==="ly.img.separator"))return null;let{builder:v,experimental:I,state:b}=c,f=b(`${o}.toggleExpandedState`,void 0);I.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:m})=>{v.Section(`${o}.popover.section`,{children:()=>{if(f.value!=null){let h=f.value,y=r.getQuickAction(h);if(y!=null&&y.renderExpanded!=null){y.renderExpanded(c,{blockIds:p,closeMenu:m,toggleExpand:()=>{f.setValue(void 0)},handleGenerationError:O=>{E(O,{cesdk:n,provider:i},t)},generate:async(O,w)=>{try{let{returnValue:x,applyCallbacks:P,dispose:Me}=await vt({input:O,quickAction:y,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:w?.blockIds??p,confirmationComponentId:s},t);return l.unlock=Me,l.applyCallbacks=P,x}catch(x){throw k(x)||E(x,{cesdk:n,provider:i},t),x}}});return}}I.builder.Menu(`${o}.menu`,{children:()=>{g.forEach(h=>{h==="ly.img.separator"?v.Separator(`${o}.separator.${Math.random().toString()}`):h.render(c,{blockIds:p,closeMenu:m,handleGenerationError:y=>{E(y,{cesdk:n,provider:i},t)},toggleExpand:()=>{f.setValue(h.id)},generate:async(y,O)=>{try{let{returnValue:w,applyCallbacks:x,dispose:P}=await vt({input:y,quickAction:h,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=P,l.applyCallbacks=x,w}catch(w){throw k(w)||E(w,{cesdk:n,provider:i},t),w}}})})}})}})}})}),{canvasMenuComponentId:d}}async function vt(e,t){let{cesdk:n,input:r,blockIds:i,provider:o,quickAction:a,confirmationComponentId:s,abortSignal:l}=e;a.confirmation&&n.ui.setCanvasMenuOrder([s],{editMode:ne});let u=new Ie(n.engine,we);i.forEach(f=>{u.set(f,{status:"processing",quickActionId:a.id})});let d={cesdk:n,engine:n.engine,abortSignal:l},c=V([...o.output.middleware??[],t.debug?F():void 0,yt({}),...a.confirmation?[a.lockDuringConfirmation?bt({editMode:ne}):It({editMode:ne}),a.confirmation&&gt({})]:[]]),{result:p,dispose:g}=await c(o.output.generate)(r,d),{consumedGenerationResult:v,applyCallbacks:I}=await ht(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:n});a.confirmation?i.forEach(f=>{u.set(f,{status:"confirmation",quickActionId:a.id})}):i.forEach(f=>{u.clear(f)});let b=()=>{g(),i.forEach(f=>{u.clear(f)})};return l.addEventListener("abort",b),{dispose:b,returnValue:v,applyCallbacks:I}}var xe=co;async function po(e,t,n){await e.initialize(t);let r=await mo(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let i=r?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:r,historyAssetLibraryEntryId:i,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};i!=null&&r!=null&&t.cesdk.ui.addAssetLibraryEntry({id:i,sourceIds:[r],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}`]:fo(e)}});let a="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(a)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",pt),t.cesdk.ui.experimental.setGlobalStateValue(a,!0)),{renderBuilderFunctions:await go(e,o,n)}}function fo(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 mo(e,t,n){if(!(n==null||n===!1)){if(n==="@imgly/local"){let r=`${t}.history`;return e.asset.addLocalSource(r),r}if(n==="@imgly/indexedDB"){let r=`${t}.history`;return e.asset.addSource(new it(r,e)),r}return n}}async function go(e,t,n){let r={panel:void 0};return e.input?.panel!=null&&(r.panel=await yo(e,e.input.panel,t,n)),e.input?.quickActions!=null&&(n.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),bo(e,e.input.quickActions,t,n)),r}async function yo(e,t,n,r){switch(t.type){case"custom":return Ke(e,t,n,r);case"schema":return _e(e,t,n,r);default:r.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function bo(e,t,n,r){let{cesdk:i}=n,o=e.kind,a=Ce(i,o);t.actions.forEach(l=>{let u=l.enable??!0;i.feature.enable(ie({quickActionId:l.id,quickActionMenuId:o}),u),a.registerQuickAction(l),r.debug&&console.log(`Registered quick action: '${l.id}' (v${l.version}) to menu '${o}'`)});let{canvasMenuComponentId:s}=xe({cesdk:i,quickActionMenu:a,provider:e},r);r.debug&&console.log(`Registered quick action menu component: ${s}`)}var ho=po;function Io(e){return async(n,r,i)=>{let o=await i(n,r);return A(o)?o:await e(o)}}var vo=Io;var ke=new Map,oe=class{constructor(t,n,r){this.db=null;this.dbVersion=1;this.isInitializing=!1;this.initPromise=null;this.instanceId=t,this.dbName=n??"ly.img.ai.rateLimit",this.storeName=r??"rateLimits"}async initialize(){if(!this.db)return this.isInitializing?this.initPromise:(this.isInitializing=!0,this.initPromise=new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{this.isInitializing=!1,console.error("Failed to open IndexedDB for rate limiting:",i),n(new Error("Failed to open IndexedDB for rate limiting"))},r.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,this.isInitializing=!1,t()}}catch(r){this.isInitializing=!1,console.error("Error initializing IndexedDB:",r),n(r)}}),this.initPromise)}async getTracker(t){try{await this.initialize();let r=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((i,o)=>{let l=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(r);l.onsuccess=()=>{l.result?i(l.result.data):i(null)},l.onerror=()=>{console.error(`Failed to get tracker for key ${r}:`,l.error),o(l.error)}})}catch(n){return console.error("Error getting tracker from IndexedDB:",n),Promise.reject(n)}}async saveTracker(t,n){try{await this.initialize();let i=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((o,a)=>{let s=this.db.transaction(this.storeName,"readwrite");s.objectStore(this.storeName).put({id:i,data:n}),s.oncomplete=()=>{o()},s.onerror=()=>{console.error(`Failed to save tracker for key ${i}:`,s.error),a(s.error)}})}catch(r){return console.error("Error saving tracker to IndexedDB:",r),Promise.reject(r)}}static isAvailable(){return typeof indexedDB<"u"}close(){this.db&&(this.db.close(),this.db=null)}};function Oo(e){let{maxRequests:t,timeWindowMs:n,keyFn:r=()=>"global",onRateLimitExceeded:i,dbName:o}=e,s=`rate-limit-middleware-${t}-${n}`,l=oe.isAvailable(),u=l?new oe(s,o):null;ke.has(s)||ke.set(s,{});let d=ke.get(s);return async(p,g,v)=>{if(e.disable)return v(p,g);let I=typeof r=="string"?r:r(p,g),b=Date.now(),f;if(l&&u)try{let m=await u.getTracker(I);m?f=m:f={timestamps:[],lastCleanup:b}}catch(m){console.error("IndexedDB access failed, using in-memory fallback:",m),d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I]}else d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I];if(b-f.lastCleanup>n&&(f.timestamps=f.timestamps.filter(m=>b-m<n),f.lastCleanup=b),f.timestamps.length>=t){let m=Math.min(...f.timestamps),h=Math.max(0,n-(b-m));if(i){let y={key:I,currentCount:f.timestamps.length,maxRequests:t,timeWindowMs:n,remainingTimeMs:h};if(!await i(p,g,y))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(f.timestamps.push(b),l&&u)try{await u.saveTracker(I,f)}catch(m){console.error("Failed to save tracker to IndexedDB:",m),d[I]=f}else d[I]=f;return v(p,g)}}var Co=Oo;function wo(e){let{cesdk:t,panelId:n}=e;n.startsWith("ly.img.ai/")&&console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai/" \u2013 "${n}" was provided.`);let r=`${n}.dock`;t.ui.registerComponent(r,({builder:i})=>{let o=t.ui.isPanelOpen(n);i.Button(`${n}.dock.button`,{label:`${n}.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(n):t.ui.openPanel(n)}})})}var xo=wo;var ds={ImageUrl:Ae};export{ds as CommonProperties,Fe as abortGenerationStateKey,V as composeMiddlewares,Mt as getDurationForVideo,Y as getLabelFromId,G as getPanelId,Ce as getQuickActionMenu,ue as getThumbnailForVideo,ho as initProvider,J as isGeneratingStateKey,F as loggingMiddleware,Co as rateLimitMiddleware,xo as registerDockComponent,xe as registerQuickActionMenuComponent,vo as uploadMiddleware};
63
+ `,ft=Yi;var gt="ly.img.ai.quickAction.order",Z="ly.img.ai.quickAction.actions";function Wi(e,t){return{id:t,setQuickActionMenuOrder:r=>{e.ui.experimental.setGlobalStateValue(`${gt}.${t}`,r)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${gt}.${t}`,[]),registerQuickAction:r=>{if(!e.ui.experimental.hasGlobalStateValue(`${Z}.${t}`))e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{[r.id]:r});else{let i=e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{...i,[r.id]:r})}},getQuickAction:r=>e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{})[r]}}var we=Wi;var ne="ly.img.ai.inference.editMode",xe="ly.img.ai.inference.metadata";function ie(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function mt(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((n,r)=>(r==="ly.img.separator"&&n.length>0&&n[n.length-1]==="ly.img.separator"||n.push(r),n),[])}function Ji({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(r,i,o)=>{let a={},s={},l=e||t?i.blockIds??i.engine.block.findAllSelected():[];return l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&(a[d]=i.engine.block.isAlwaysOnTop(d),i.engine.block.setAlwaysOnTop(d,!0)),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&(s[c]=i.engine.block.isClipped(c),i.engine.block.setClipped(c,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&s[c]!=null&&i.engine.block.setClipped(c,s[c])}})}),await o(r,i)}}var yt=Ji;function Xi({pending:e=!0}){return async(n,r,i)=>{let o=e?r.blockIds??r.engine.block.findAllSelected():[];try{return o.forEach(s=>{r.engine.block.isValid(s)&&r.engine.block.setState(s,{type:"Pending",progress:0})}),await i(n,r)}finally{o.forEach(a=>{r.engine.block.isValid(a)&&r.engine.block.setState(a,{type:"Ready"})})}}}var bt=Xi;function eo({editMode:e,automaticallyUnlock:t=!1}){return async(r,i,o)=>{let a=i.blockIds??i.engine.block.findAllSelected(),s=()=>{};t||i.addDisposer(async()=>{s?.()});try{return s=to(i.engine,a,e),await o(r,i)}catch(l){throw k(l)&&s(),l}finally{t&&s()}}}function to(e,t,n){let r=e.editor.getGlobalScope("editor/select"),i=e.editor.getEditMode();s(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(n);let o=e.editor.createHistory(),a=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function s(){e.block.findAllSelected().forEach(c=>{t.includes(c)||e.block.setSelected(c,!1)}),t.forEach(c=>{e.block.setSelected(c,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&e.editor.setEditMode(n)}),u=e.block.onSelectionChanged(s);return()=>{r!=null&&e.editor.setGlobalScope("editor/select",r),e.editor.setEditMode(i),e.editor.setActiveHistory(a),e.editor.destroyHistory(o),u(),l()}}var ht=eo;function ro(e,t){switch(t.kind){case"text":return no(e,t);case"image":return io(e,t);case"video":return oo(e,t);case"audio":return ao(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function no(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t,o=r.map(c=>n.engine.block.getString(c,"text/text")),a;if(A(e)){let c="";for await(let p of e){if(i.aborted)break;typeof p=="string"?c=p:p.kind==="text"&&(c=p.text),r.forEach(v=>{n.engine.block.setString(v,"text/text",c)}),a={kind:"text",text:c}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(c=>{t.cesdk.engine.block.setString(c,"text/text",a.text)})},l=()=>{t.blockIds.forEach((c,p)=>{t.cesdk.engine.block.setString(c,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:s}}}async function io(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t;if(r.length!==1)throw new Error("Only one block is supported for image generation");let[o]=r,a=n.engine.block.getFill(o),s=n.engine.block.getSourceSet(a,"fill/image/sourceSet"),[l]=s,u;l==null&&(u=n.engine.block.getString(a,"fill/image/imageFileURI"));let d=await n.engine.editor.getMimeType(l?.uri??u);if(i.throwIfAborted(),d==="image/svg+xml")throw new Error("SVG images are not supported");let c=n.engine.block.getCropScaleX(o),p=n.engine.block.getCropScaleY(o),m=n.engine.block.getCropTranslationX(o),v=n.engine.block.getCropTranslationY(o),I=n.engine.block.getCropRotation(o),b=()=>{n.engine.block.setCropScaleX(o,c),n.engine.block.setCropScaleY(o,p),n.engine.block.setCropTranslationX(o,m),n.engine.block.setCropTranslationY(o,v),n.engine.block.setCropRotation(o,I)};if(A(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 f=e.url,g=await n.engine.editor.getMimeType(f),h=await so(n,f,g),y=l?[{uri:h,width:l.width,height:l.height}]:void 0,O=h;y==null?n.engine.block.setString(a,"fill/image/imageFileURI",O):n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),b();let w=()=>{if(s==null){if(u==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",u)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",s);b()},x=()=>{if(y==null){if(O==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",O)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",y);b()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:w,onAfter:x,onCancel:()=>{w()},onApply:()=>{x()}}}}async function oo(e,t){throw new Error("Function not implemented.")}async function ao(e,t){throw new Error("Function not implemented.")}async function so(e,t,n){let i=await(await fetch(t)).blob(),o=new File([i],`image.${lo(n)}`,{type:n}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}function lo(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}var It=ro;function uo({editMode:e,automaticallyUnlock:t=!1,showNotification:n=!0}){return async(i,o,a)=>{let s=o.blockIds??o.engine.block.findAllSelected(),l=()=>{};t||o.addDisposer(async()=>{l?.()});try{l=co(o.engine,s,e);let u=await a(i,o);if(n){let d=o.engine.block.findAllSelected();s.some(p=>d.includes(p))||o.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{s.forEach(p=>{o.engine.block.select(p)})}}})}return u}catch(u){throw k(u)&&l(),u}finally{t&&l()}}}function co(e,t,n){function r(){let s=e.block.findAllSelected();return t.some(l=>s.includes(l))}let i=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&r()&&e.editor.setEditMode(n)}),o=e.block.onSelectionChanged(()=>{r()?e.editor.setEditMode(n):e.editor.setEditMode("Transform")});return r()&&e.editor.setEditMode(n),()=>{o(),i(),e.editor.setEditMode("Transform")}}var vt=uo;function po(e,t){let{cesdk:n,quickActionMenu:r,provider:i}=e,o=`ly.img.ai.${r.id}`,a=`${o}.confirmation`;n.setTranslations({en:{[`${a}.apply`]:"Apply",[`${a}.before`]:"Before",[`${a}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let s=`${a}.canvasnMenu`,l={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},u=()=>{let c=new AbortController,p=c.signal;return l.abort=()=>{c.abort()},p};n.ui.registerComponent(s,({builder:c,engine:p,state:m})=>{let v=p.block.findAllSelected();if(v.length===0)return null;let I=new ve(n.engine,xe),b=I.get(v[0]);if(b==null)return null;let f=()=>{v.forEach(g=>{I.clear(g)})};switch(b.status){case"processing":{c.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${b.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),c.Separator(`${o}.separator`),c.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),f()}});break}case"confirmation":{let g=m(`${a}.comparing`,"after"),h=l.applyCallbacks?.onCancel;h!=null&&c.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),h(),f()}});let y=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;y!=null&&O!=null&&c.ButtonGroup(`${a}.compare`,{children:()=>{c.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:g.value==="before",onClick:()=>{y(),g.setValue("before")}}),c.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:g.value==="after",onClick:()=>{O(),g.setValue("after")}})}});let w=l.applyCallbacks?.onApply;w!=null&&c.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:g.value!=="after",onClick:()=>{l.unlock(),f(),n.engine.editor._update(),w(),p.editor.addUndoStep()}});break}default:}});let d=`${o}.canvasMenu`;return n.ui.registerComponent(d,c=>{let p=c.engine.block.findAllSelected(),m=r.getQuickActionMenuOrder().map(g=>{if(g==="ly.img.separator")return g;let h=r.getQuickAction(g);if(h==null||!n.feature.isEnabled(ie({quickActionId:g,quickActionMenuId:r.id}),{engine:c.engine}))return null;let O=h.scopes;return O!=null&&O.length>0&&!p.every(x=>O.every(P=>c.engine.block.isAllowedByScope(x,P)))?null:h}).filter(g=>g!=null);if(m=mt(m),m.length===0||m.every(g=>g==="ly.img.separator"))return null;let{builder:v,experimental:I,state:b}=c,f=b(`${o}.toggleExpandedState`,void 0);I.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:g})=>{v.Section(`${o}.popover.section`,{children:()=>{if(f.value!=null){let h=f.value,y=r.getQuickAction(h);if(y!=null&&y.renderExpanded!=null){y.renderExpanded(c,{blockIds:p,closeMenu:g,toggleExpand:()=>{f.setValue(void 0)},handleGenerationError:O=>{E(O,{cesdk:n,provider:i},t)},generate:async(O,w)=>{try{let{returnValue:x,applyCallbacks:P,dispose:Ae}=await Ot({input:O,quickAction:y,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:w?.blockIds??p,confirmationComponentId:s},t);return l.unlock=Ae,l.applyCallbacks=P,x}catch(x){throw k(x)||E(x,{cesdk:n,provider:i},t),x}}});return}}I.builder.Menu(`${o}.menu`,{children:()=>{m.forEach(h=>{h==="ly.img.separator"?v.Separator(`${o}.separator.${Math.random().toString()}`):h.render(c,{blockIds:p,closeMenu:g,handleGenerationError:y=>{E(y,{cesdk:n,provider:i},t)},toggleExpand:()=>{f.setValue(h.id)},generate:async(y,O)=>{try{let{returnValue:w,applyCallbacks:x,dispose:P}=await Ot({input:y,quickAction:h,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=P,l.applyCallbacks=x,w}catch(w){throw k(w)||E(w,{cesdk:n,provider:i},t),w}}})})}})}})}})}),{canvasMenuComponentId:d}}async function Ot(e,t){let{cesdk:n,input:r,blockIds:i,provider:o,quickAction:a,confirmationComponentId:s,abortSignal:l}=e;a.confirmation&&n.ui.setCanvasMenuOrder([s],{editMode:ne});let u=new ve(n.engine,xe);i.forEach(f=>{u.set(f,{status:"processing",quickActionId:a.id})});let d={cesdk:n,engine:n.engine,abortSignal:l},c=V([...o.output.middleware??[],t.debug?F():void 0,bt({}),...a.confirmation?[a.lockDuringConfirmation?ht({editMode:ne}):vt({editMode:ne}),a.confirmation&&yt({})]:[]]),{result:p,dispose:m}=await c(o.output.generate)(r,d),{consumedGenerationResult:v,applyCallbacks:I}=await It(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:n});a.confirmation?i.forEach(f=>{u.set(f,{status:"confirmation",quickActionId:a.id})}):i.forEach(f=>{u.clear(f)});let b=()=>{m(),i.forEach(f=>{u.clear(f)})};return l.addEventListener("abort",b),{dispose:b,returnValue:v,applyCallbacks:I}}var ke=po;async function fo(e,t,n){await e.initialize(t);let r=await mo(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let i=r?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:r,historyAssetLibraryEntryId:i,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};i!=null&&r!=null&&t.cesdk.ui.addAssetLibraryEntry({id:i,sourceIds:[r],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}`]:go(e)}});let a="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(a)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",ft),t.cesdk.ui.experimental.setGlobalStateValue(a,!0)),{renderBuilderFunctions:await yo(e,o,n)}}function go(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 mo(e,t,n){if(!(n==null||n===!1)){if(n==="@imgly/local"){let r=`${t}.history`;return e.asset.addLocalSource(r),r}if(n==="@imgly/indexedDB"){let r=`${t}.history`;return e.asset.addSource(new ot(r,e)),r}return n}}async function yo(e,t,n){let r={panel:void 0};return e.input?.panel!=null&&(r.panel=await bo(e,e.input.panel,t,n)),e.input?.quickActions!=null&&(n.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),ho(e,e.input.quickActions,t,n)),r}async function bo(e,t,n,r){switch(t.type){case"custom":return Ue(e,t,n,r);case"schema":return Ke(e,t,n,r);default:r.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function ho(e,t,n,r){let{cesdk:i}=n,o=e.kind,a=we(i,o);t.actions.forEach(l=>{let u=l.enable??!0;i.feature.enable(ie({quickActionId:l.id,quickActionMenuId:o}),u),a.registerQuickAction(l),r.debug&&console.log(`Registered quick action: '${l.id}' (v${l.version}) to menu '${o}'`)});let{canvasMenuComponentId:s}=ke({cesdk:i,quickActionMenu:a,provider:e},r);r.debug&&console.log(`Registered quick action menu component: ${s}`)}var Io=fo;function vo(e){return async(n,r,i)=>{let o=await i(n,r);return A(o)?o:await e(o)}}var Oo=vo;var Me=new Map,oe=class{constructor(t,n,r){this.db=null;this.dbVersion=1;this.isInitializing=!1;this.initPromise=null;this.instanceId=t,this.dbName=n??"ly.img.ai.rateLimit",this.storeName=r??"rateLimits"}async initialize(){if(!this.db)return this.isInitializing?this.initPromise:(this.isInitializing=!0,this.initPromise=new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{this.isInitializing=!1,console.error("Failed to open IndexedDB for rate limiting:",i),n(new Error("Failed to open IndexedDB for rate limiting"))},r.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,this.isInitializing=!1,t()}}catch(r){this.isInitializing=!1,console.error("Error initializing IndexedDB:",r),n(r)}}),this.initPromise)}async getTracker(t){try{await this.initialize();let r=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((i,o)=>{let l=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(r);l.onsuccess=()=>{l.result?i(l.result.data):i(null)},l.onerror=()=>{console.error(`Failed to get tracker for key ${r}:`,l.error),o(l.error)}})}catch(n){return console.error("Error getting tracker from IndexedDB:",n),Promise.reject(n)}}async saveTracker(t,n){try{await this.initialize();let i=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((o,a)=>{let s=this.db.transaction(this.storeName,"readwrite");s.objectStore(this.storeName).put({id:i,data:n}),s.oncomplete=()=>{o()},s.onerror=()=>{console.error(`Failed to save tracker for key ${i}:`,s.error),a(s.error)}})}catch(r){return console.error("Error saving tracker to IndexedDB:",r),Promise.reject(r)}}static isAvailable(){return typeof indexedDB<"u"}close(){this.db&&(this.db.close(),this.db=null)}};function Co(e){let{maxRequests:t,timeWindowMs:n,keyFn:r=()=>"global",onRateLimitExceeded:i,dbName:o}=e,s=`rate-limit-middleware-${t}-${n}`,l=oe.isAvailable(),u=l?new oe(s,o):null;Me.has(s)||Me.set(s,{});let d=Me.get(s);return async(p,m,v)=>{if(e.disable)return v(p,m);let I=typeof r=="string"?r:r(p,m),b=Date.now(),f;if(l&&u)try{let g=await u.getTracker(I);g?f=g:f={timestamps:[],lastCleanup:b}}catch(g){console.error("IndexedDB access failed, using in-memory fallback:",g),d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I]}else d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I];if(b-f.lastCleanup>n&&(f.timestamps=f.timestamps.filter(g=>b-g<n),f.lastCleanup=b),f.timestamps.length>=t){let g=Math.min(...f.timestamps),h=Math.max(0,n-(b-g));if(i){let y={key:I,currentCount:f.timestamps.length,maxRequests:t,timeWindowMs:n,remainingTimeMs:h};if(!await i(p,m,y))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(f.timestamps.push(b),l&&u)try{await u.saveTracker(I,f)}catch(g){console.error("Failed to save tracker to IndexedDB:",g),d[I]=f}else d[I]=f;return v(p,m)}}var wo=Co;function xo(e){let{cesdk:t,panelId:n}=e;n.startsWith("ly.img.ai/")&&console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai/" \u2013 "${n}" was provided.`);let r=`${n}.dock`;t.ui.registerComponent(r,({builder:i})=>{let o=t.ui.isPanelOpen(n);i.Button(`${n}.dock.button`,{label:`${n}.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(n):t.ui.openPanel(n)}})})}var ko=xo;var ps={ImageUrl:Ee};export{ps as CommonProperties,_e as abortGenerationStateKey,V as composeMiddlewares,At as getDurationForVideo,Y as getLabelFromId,G as getPanelId,we as getQuickActionMenu,ce as getThumbnailForVideo,Io as initProvider,J as isGeneratingStateKey,F as loggingMiddleware,wo as rateLimitMiddleware,ko as registerDockComponent,ke as registerQuickActionMenuComponent,Oo as uploadMiddleware};
64
64
  /*! Bundled license information:
65
65
 
66
66
  @imgly/plugin-utils/dist/index.mjs: