handler-playable-sdk 0.3.11 → 0.3.15

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.
@@ -1,5 +1,5 @@
1
- import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./chunk-LV4HGC5G.js";import{c as en,d as ar,g as rc,h as Va,j as Ka,l as ac,m as sc,n as Xa,o as oc}from"./chunk-ZLL42OOV.js";import{a as Ne,b as I,c as rg}from"./chunk-Q7FPWOA3.js";var tn=I((Y0,rs)=>{"use strict";typeof process=="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?rs.exports={nextTick:og}:rs.exports=process;function og(e,t,i,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var r=arguments.length,a,s;switch(r){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t)});case 3:return process.nextTick(function(){e.call(null,t,i)});case 4:return process.nextTick(function(){e.call(null,t,i,n)});default:for(a=new Array(r-1),s=0;s<a.length;)a[s++]=arguments[s];return process.nextTick(function(){e.apply(null,a)})}}});var Dc=I((V0,Oc)=>{"use strict";var lg={}.toString;Oc.exports=Array.isArray||function(e){return lg.call(e)=="[object Array]"}});var as=I((K0,zc)=>{"use strict";zc.exports=Ne("stream")});var nn=I((ss,Bc)=>{"use strict";var Er=Ne("buffer"),tt=Er.Buffer;function jc(e,t){for(var i in e)t[i]=e[i]}tt.from&&tt.alloc&&tt.allocUnsafe&&tt.allocUnsafeSlow?Bc.exports=Er:(jc(Er,ss),ss.Buffer=ui);function ui(e,t,i){return tt(e,t,i)}jc(tt,ui);ui.from=function(e,t,i){if(typeof e=="number")throw new TypeError("Argument must not be a number");return tt(e,t,i)};ui.alloc=function(e,t,i){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=tt(e);return t!==void 0?typeof i=="string"?n.fill(t,i):n.fill(t):n.fill(0),n};ui.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return tt(e)};ui.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Er.SlowBuffer(e)}});var pi=I(le=>{"use strict";function cg(e){return Array.isArray?Array.isArray(e):Sr(e)==="[object Array]"}le.isArray=cg;function dg(e){return typeof e=="boolean"}le.isBoolean=dg;function ug(e){return e===null}le.isNull=ug;function pg(e){return e==null}le.isNullOrUndefined=pg;function fg(e){return typeof e=="number"}le.isNumber=fg;function hg(e){return typeof e=="string"}le.isString=hg;function gg(e){return typeof e=="symbol"}le.isSymbol=gg;function bg(e){return e===void 0}le.isUndefined=bg;function mg(e){return Sr(e)==="[object RegExp]"}le.isRegExp=mg;function vg(e){return typeof e=="object"&&e!==null}le.isObject=vg;function yg(e){return Sr(e)==="[object Date]"}le.isDate=yg;function xg(e){return Sr(e)==="[object Error]"||e instanceof Error}le.isError=xg;function wg(e){return typeof e=="function"}le.isFunction=wg;function _g(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e=="undefined"}le.isPrimitive=_g;le.isBuffer=Ne("buffer").Buffer.isBuffer;function Sr(e){return Object.prototype.toString.call(e)}});var Fc=I((Z0,os)=>{"use strict";typeof Object.create=="function"?os.exports=function(t,i){i&&(t.super_=i,t.prototype=Object.create(i.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:os.exports=function(t,i){if(i){t.super_=i;var n=function(){};n.prototype=i.prototype,t.prototype=new n,t.prototype.constructor=t}}});var fi=I((J0,cs)=>{"use strict";try{if(ls=Ne("util"),typeof ls.inherits!="function")throw"";cs.exports=ls.inherits}catch{cs.exports=Fc()}var ls});var Hc=I((Q0,ds)=>{"use strict";function Eg(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var Nc=nn().Buffer,rn=Ne("util");function Sg(e,t,i){e.copy(t,i)}ds.exports=(function(){function e(){Eg(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(i){var n={data:i,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},e.prototype.unshift=function(i){var n={data:i,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},e.prototype.shift=function(){if(this.length!==0){var i=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,i}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(i){if(this.length===0)return"";for(var n=this.head,r=""+n.data;n=n.next;)r+=i+n.data;return r},e.prototype.concat=function(i){if(this.length===0)return Nc.alloc(0);for(var n=Nc.allocUnsafe(i>>>0),r=this.head,a=0;r;)Sg(r.data,n,a),a+=r.data.length,r=r.next;return n},e})();rn&&rn.inspect&&rn.inspect.custom&&(ds.exports.prototype[rn.inspect.custom]=function(){var e=rn.inspect({length:this.length});return this.constructor.name+" "+e})});var us=I((ew,Uc)=>{"use strict";var Ar=tn();function Ag(e,t){var i=this,n=this._readableState&&this._readableState.destroyed,r=this._writableState&&this._writableState.destroyed;return n||r?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,Ar.nextTick(Cr,this,e)):Ar.nextTick(Cr,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(a){!t&&a?i._writableState?i._writableState.errorEmitted||(i._writableState.errorEmitted=!0,Ar.nextTick(Cr,i,a)):Ar.nextTick(Cr,i,a):t&&t(a)}),this)}function Cg(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Cr(e,t){e.emit("error",t)}Uc.exports={destroy:Ag,undestroy:Cg}});var qc=I((tw,$c)=>{"use strict";$c.exports=Ne("util").deprecate});var fs=I((iw,Jc)=>{"use strict";var Bt=tn();Jc.exports=Q;function Wc(e){var t=this;this.next=null,this.entry=null,this.finish=function(){qg(t,e)}}var kg=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:Bt.nextTick,hi;Q.WritableState=sn;var Yc=Object.create(pi());Yc.inherits=fi();var Tg={deprecate:qc()},Vc=as(),Tr=nn().Buffer,Lg=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function Rg(e){return Tr.from(e)}function Pg(e){return Tr.isBuffer(e)||e instanceof Lg}var Kc=us();Yc.inherits(Q,Vc);function Ig(){}function sn(e,t){hi=hi||Ft(),e=e||{};var i=t instanceof hi;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,r=e.writableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=e.decodeStrings===!1;this.decodeStrings=!s,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(o){Fg(t,o)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new Wc(this)}sn.prototype.getBuffer=function(){for(var t=this.bufferedRequest,i=[];t;)i.push(t),t=t.next;return i};(function(){try{Object.defineProperty(sn.prototype,"buffer",{get:Tg.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var kr;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(kr=Function.prototype[Symbol.hasInstance],Object.defineProperty(Q,Symbol.hasInstance,{value:function(e){return kr.call(this,e)?!0:this!==Q?!1:e&&e._writableState instanceof sn}})):kr=function(e){return e instanceof this};function Q(e){if(hi=hi||Ft(),!kr.call(Q,this)&&!(this instanceof hi))return new Q(e);this._writableState=new sn(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),Vc.call(this)}Q.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function Mg(e,t){var i=new Error("write after end");e.emit("error",i),Bt.nextTick(t,i)}function Og(e,t,i,n){var r=!0,a=!1;return i===null?a=new TypeError("May not write null values to stream"):typeof i!="string"&&i!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),Bt.nextTick(n,a),r=!1),r}Q.prototype.write=function(e,t,i){var n=this._writableState,r=!1,a=!n.objectMode&&Pg(e);return a&&!Tr.isBuffer(e)&&(e=Rg(e)),typeof t=="function"&&(i=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),typeof i!="function"&&(i=Ig),n.ended?Mg(this,i):(a||Og(this,n,e,i))&&(n.pendingcb++,r=zg(this,n,a,e,t,i)),r};Q.prototype.cork=function(){var e=this._writableState;e.corked++};Q.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&Xc(this,e))};Q.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function Dg(e,t,i){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Tr.from(t,i)),t}Object.defineProperty(Q.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function zg(e,t,i,n,r,a){if(!i){var s=Dg(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var o=t.objectMode?1:n.length;t.length+=o;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else ps(e,t,!1,o,n,r,a);return c}function ps(e,t,i,n,r,a,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,i?e._writev(r,t.onwrite):e._write(r,a,t.onwrite),t.sync=!1}function jg(e,t,i,n,r){--t.pendingcb,i?(Bt.nextTick(r,n),Bt.nextTick(an,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(r(n),e._writableState.errorEmitted=!0,e.emit("error",n),an(e,t))}function Bg(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function Fg(e,t){var i=e._writableState,n=i.sync,r=i.writecb;if(Bg(i),t)jg(e,i,n,t,r);else{var a=Zc(i);!a&&!i.corked&&!i.bufferProcessing&&i.bufferedRequest&&Xc(e,i),n?kg(Gc,e,i,a,r):Gc(e,i,a,r)}}function Gc(e,t,i,n){i||Ng(e,t),t.pendingcb--,n(),an(e,t)}function Ng(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function Xc(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,r=new Array(n),a=t.corkedRequestsFree;a.entry=i;for(var s=0,o=!0;i;)r[s]=i,i.isBuf||(o=!1),i=i.next,s+=1;r.allBuffers=o,ps(e,t,!0,t.length,r,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new Wc(t),t.bufferedRequestCount=0}else{for(;i;){var c=i.chunk,l=i.encoding,d=i.callback,u=t.objectMode?1:c.length;if(ps(e,t,!1,u,c,l,d),i=i.next,t.bufferedRequestCount--,t.writing)break}i===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}Q.prototype._write=function(e,t,i){i(new Error("_write() is not implemented"))};Q.prototype._writev=null;Q.prototype.end=function(e,t,i){var n=this._writableState;typeof e=="function"?(i=e,e=null,t=null):typeof t=="function"&&(i=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||$g(this,n,i)};function Zc(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function Hg(e,t){e._final(function(i){t.pendingcb--,i&&e.emit("error",i),t.prefinished=!0,e.emit("prefinish"),an(e,t)})}function Ug(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=!0,Bt.nextTick(Hg,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function an(e,t){var i=Zc(t);return i&&(Ug(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"))),i}function $g(e,t,i){t.ending=!0,an(e,t),i&&(t.finished?Bt.nextTick(i):e.once("finish",i)),t.ended=!0,e.writable=!1}function qg(e,t,i){var n=e.entry;for(e.entry=null;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}Object.defineProperty(Q.prototype,"destroyed",{get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}});Q.prototype.destroy=Kc.destroy;Q.prototype._undestroy=Kc.undestroy;Q.prototype._destroy=function(e,t){this.end(),t(e)}});var Ft=I((nw,id)=>{"use strict";var Qc=tn(),Gg=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};id.exports=it;var ed=Object.create(pi());ed.inherits=fi();var td=bs(),gs=fs();ed.inherits(it,td);for(hs=Gg(gs.prototype),Lr=0;Lr<hs.length;Lr++)Rr=hs[Lr],it.prototype[Rr]||(it.prototype[Rr]=gs.prototype[Rr]);var hs,Rr,Lr;function it(e){if(!(this instanceof it))return new it(e);td.call(this,e),gs.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",Wg)}Object.defineProperty(it.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function Wg(){this.allowHalfOpen||this._writableState.ended||Qc.nextTick(Yg,this)}function Yg(e){e.end()}Object.defineProperty(it.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}});it.prototype._destroy=function(e,t){this.push(null),this.end(),Qc.nextTick(t,e)}});var ys=I(rd=>{"use strict";var vs=nn().Buffer,nd=vs.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Vg(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function Kg(e){var t=Vg(e);if(typeof t!="string"&&(vs.isEncoding===nd||!nd(e)))throw new Error("Unknown encoding: "+e);return t||e}rd.StringDecoder=on;function on(e){this.encoding=Kg(e);var t;switch(this.encoding){case"utf16le":this.text=tb,this.end=ib,t=4;break;case"utf8":this.fillLast=Jg,t=4;break;case"base64":this.text=nb,this.end=rb,t=3;break;default:this.write=ab,this.end=sb;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=vs.allocUnsafe(t)}on.prototype.write=function(e){if(e.length===0)return"";var t,i;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""};on.prototype.end=eb;on.prototype.text=Qg;on.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function ms(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function Xg(e,t,i){var n=t.length-1;if(n<i)return 0;var r=ms(t[n]);return r>=0?(r>0&&(e.lastNeed=r-1),r):--n<i||r===-2?0:(r=ms(t[n]),r>=0?(r>0&&(e.lastNeed=r-2),r):--n<i||r===-2?0:(r=ms(t[n]),r>=0?(r>0&&(r===2?r=0:e.lastNeed=r-3),r):0))}function Zg(e,t,i){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function Jg(e){var t=this.lastTotal-this.lastNeed,i=Zg(this,e,t);if(i!==void 0)return i;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function Qg(e,t){var i=Xg(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function eb(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function tb(e,t){if((e.length-t)%2===0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function ib(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function nb(e,t){var i=(e.length-t)%3;return i===0?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,i===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function rb(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function ab(e){return e.toString(this.encoding)}function sb(e){return e&&e.length?this.write(e):""}});var bs=I((sw,bd)=>{"use strict";var bi=tn();bd.exports=G;var ob=Dc(),ln;G.ReadableState=ud;var aw=Ne("events").EventEmitter,ld=function(e,t){return e.listeners(t).length},Ss=as(),cn=nn().Buffer,lb=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function cb(e){return cn.from(e)}function db(e){return cn.isBuffer(e)||e instanceof lb}var cd=Object.create(pi());cd.inherits=fi();var xs=Ne("util"),H=void 0;xs&&xs.debuglog?H=xs.debuglog("stream"):H=function(){};var ub=Hc(),dd=us(),gi;cd.inherits(G,Ss);var ws=["error","close","destroy","pause","resume"];function pb(e,t,i){if(typeof e.prependListener=="function")return e.prependListener(t,i);!e._events||!e._events[t]?e.on(t,i):ob(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]}function ud(e,t){ln=ln||Ft(),e=e||{};var i=t instanceof ln;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,r=e.readableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new ub,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(gi||(gi=ys().StringDecoder),this.decoder=new gi(e.encoding),this.encoding=e.encoding)}function G(e){if(ln=ln||Ft(),!(this instanceof G))return new G(e);this._readableState=new ud(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Ss.call(this)}Object.defineProperty(G.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});G.prototype.destroy=dd.destroy;G.prototype._undestroy=dd.undestroy;G.prototype._destroy=function(e,t){this.push(null),t(e)};G.prototype.push=function(e,t){var i=this._readableState,n;return i.objectMode?n=!0:typeof e=="string"&&(t=t||i.defaultEncoding,t!==i.encoding&&(e=cn.from(e,t),t=""),n=!0),pd(this,e,t,!1,n)};G.prototype.unshift=function(e){return pd(this,e,null,!0,!1)};function pd(e,t,i,n,r){var a=e._readableState;if(t===null)a.reading=!1,bb(e,a);else{var s;r||(s=fb(a,t)),s?e.emit("error",s):a.objectMode||t&&t.length>0?(typeof t!="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==cn.prototype&&(t=cb(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_s(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!i?(t=a.decoder.write(t),a.objectMode||t.length!==0?_s(e,a,t,!1):fd(e,a)):_s(e,a,t,!1))):n||(a.reading=!1)}return hb(a)}function _s(e,t,i,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",i),e.read(0)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&Pr(e)),fd(e,t)}function fb(e,t){var i;return!db(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(i=new TypeError("Invalid non-string/buffer chunk")),i}function hb(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}G.prototype.isPaused=function(){return this._readableState.flowing===!1};G.prototype.setEncoding=function(e){return gi||(gi=ys().StringDecoder),this._readableState.decoder=new gi(e),this._readableState.encoding=e,this};var ad=8388608;function gb(e){return e>=ad?e=ad:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function sd(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=gb(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}G.prototype.read=function(e){H("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return H("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?Es(this):Pr(this),null;if(e=sd(e,t),e===0&&t.ended)return t.length===0&&Es(this),null;var n=t.needReadable;H("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,H("length less than watermark",n)),t.ended||t.reading?(n=!1,H("reading or ended",n)):n&&(H("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=sd(i,t)));var r;return e>0?r=hd(e,t):r=null,r===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&Es(this)),r!==null&&this.emit("data",r),r};function bb(e,t){if(!t.ended){if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,Pr(e)}}function Pr(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(H("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?bi.nextTick(od,e):od(e))}function od(e){H("emit readable"),e.emit("readable"),As(e)}function fd(e,t){t.readingMore||(t.readingMore=!0,bi.nextTick(mb,e,t))}function mb(e,t){for(var i=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(H("maybeReadMore read 0"),e.read(0),i!==t.length);)i=t.length;t.readingMore=!1}G.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))};G.prototype.pipe=function(e,t){var i=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,H("pipe count=%d opts=%j",n.pipesCount,t);var r=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr,a=r?o:g;n.endEmitted?bi.nextTick(a):i.once("end",a),e.on("unpipe",s);function s(m,v){H("onunpipe"),m===i&&v&&v.hasUnpiped===!1&&(v.hasUnpiped=!0,d())}function o(){H("onend"),e.end()}var c=vb(i);e.on("drain",c);var l=!1;function d(){H("cleanup"),e.removeListener("close",b),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",f),e.removeListener("unpipe",s),i.removeListener("end",o),i.removeListener("end",g),i.removeListener("data",p),l=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}var u=!1;i.on("data",p);function p(m){H("ondata"),u=!1;var v=e.write(m);v===!1&&!u&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&gd(n.pipes,e)!==-1)&&!l&&(H("false write response, pause",n.awaitDrain),n.awaitDrain++,u=!0),i.pause())}function f(m){H("onerror",m),g(),e.removeListener("error",f),ld(e,"error")===0&&e.emit("error",m)}pb(e,"error",f);function b(){e.removeListener("finish",h),g()}e.once("close",b);function h(){H("onfinish"),e.removeListener("close",b),g()}e.once("finish",h);function g(){H("unpipe"),i.unpipe(e)}return e.emit("pipe",i),n.flowing||(H("pipe resume"),i.resume()),e};function vb(e){return function(){var t=e._readableState;H("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&ld(e,"data")&&(t.flowing=!0,As(e))}}G.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<r;a++)n[a].emit("unpipe",this,{hasUnpiped:!1});return this}var s=gd(t.pipes,e);return s===-1?this:(t.pipes.splice(s,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i),this)};G.prototype.on=function(e,t){var i=Ss.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==!1&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&Pr(this):bi.nextTick(yb,this))}return i};G.prototype.addListener=G.prototype.on;function yb(e){H("readable nexttick read 0"),e.read(0)}G.prototype.resume=function(){var e=this._readableState;return e.flowing||(H("resume"),e.flowing=!0,xb(this,e)),this};function xb(e,t){t.resumeScheduled||(t.resumeScheduled=!0,bi.nextTick(wb,e,t))}function wb(e,t){t.reading||(H("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),As(e),t.flowing&&!t.reading&&e.read(0)}G.prototype.pause=function(){return H("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(H("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function As(e){var t=e._readableState;for(H("flow",t.flowing);t.flowing&&e.read()!==null;);}G.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;e.on("end",function(){if(H("wrapped end"),i.decoder&&!i.ended){var s=i.decoder.end();s&&s.length&&t.push(s)}t.push(null)}),e.on("data",function(s){if(H("wrapped data"),i.decoder&&(s=i.decoder.write(s)),!(i.objectMode&&s==null)&&!(!i.objectMode&&(!s||!s.length))){var o=t.push(s);o||(n=!0,e.pause())}});for(var r in e)this[r]===void 0&&typeof e[r]=="function"&&(this[r]=(function(s){return function(){return e[s].apply(e,arguments)}})(r));for(var a=0;a<ws.length;a++)e.on(ws[a],this.emit.bind(this,ws[a]));return this._read=function(s){H("wrapped _read",s),n&&(n=!1,e.resume())},this};Object.defineProperty(G.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});G._fromList=hd;function hd(e,t){if(t.length===0)return null;var i;return t.objectMode?i=t.buffer.shift():!e||e>=t.length?(t.decoder?i=t.buffer.join(""):t.buffer.length===1?i=t.buffer.head.data:i=t.buffer.concat(t.length),t.buffer.clear()):i=_b(e,t.buffer,t.decoder),i}function _b(e,t,i){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=i?Eb(e,t):Sb(e,t),n}function Eb(e,t){var i=t.head,n=1,r=i.data;for(e-=r.length;i=i.next;){var a=i.data,s=e>a.length?a.length:e;if(s===a.length?r+=a:r+=a.slice(0,e),e-=s,e===0){s===a.length?(++n,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=a.slice(s));break}++n}return t.length-=n,r}function Sb(e,t){var i=cn.allocUnsafe(e),n=t.head,r=1;for(n.data.copy(i),e-=n.data.length;n=n.next;){var a=n.data,s=e>a.length?a.length:e;if(a.copy(i,i.length-e,0,s),e-=s,e===0){s===a.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(s));break}++r}return t.length-=r,i}function Es(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,bi.nextTick(Ab,t,e))}function Ab(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function gd(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}});var Cs=I((ow,yd)=>{"use strict";yd.exports=nt;var Ir=Ft(),vd=Object.create(pi());vd.inherits=fi();vd.inherits(nt,Ir);function Cb(e,t){var i=this._transformState;i.transforming=!1;var n=i.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,t!=null&&this.push(t),n(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}function nt(e){if(!(this instanceof nt))return new nt(e);Ir.call(this,e),this._transformState={afterTransform:Cb.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",kb)}function kb(){var e=this;typeof this._flush=="function"?this._flush(function(t,i){md(e,t,i)}):md(this,null,null)}nt.prototype.push=function(e,t){return this._transformState.needTransform=!1,Ir.prototype.push.call(this,e,t)};nt.prototype._transform=function(e,t,i){throw new Error("_transform() is not implemented")};nt.prototype._write=function(e,t,i){var n=this._transformState;if(n.writecb=i,n.writechunk=e,n.writeencoding=t,!n.transforming){var r=this._readableState;(n.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}};nt.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};nt.prototype._destroy=function(e,t){var i=this;Ir.prototype._destroy.call(this,e,function(n){t(n),i.emit("close")})};function md(e,t,i){if(t)return e.emit("error",t);if(i!=null&&e.push(i),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var Ed=I((lw,_d)=>{"use strict";_d.exports=dn;var xd=Cs(),wd=Object.create(pi());wd.inherits=fi();wd.inherits(dn,xd);function dn(e){if(!(this instanceof dn))return new dn(e);xd.call(this,e)}dn.prototype._transform=function(e,t,i){i(null,e)}});var ks=I((re,Mr)=>{"use strict";var Ue=Ne("stream");process.env.READABLE_STREAM==="disable"&&Ue?(Mr.exports=Ue,re=Mr.exports=Ue.Readable,re.Readable=Ue.Readable,re.Writable=Ue.Writable,re.Duplex=Ue.Duplex,re.Transform=Ue.Transform,re.PassThrough=Ue.PassThrough,re.Stream=Ue):(re=Mr.exports=bs(),re.Stream=Ue||re,re.Readable=re,re.Writable=fs(),re.Duplex=Ft(),re.Transform=Cs(),re.PassThrough=Ed())});var rt=I(ve=>{"use strict";ve.base64=!0;ve.array=!0;ve.string=!0;ve.arraybuffer=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined";ve.nodebuffer=typeof Buffer!="undefined";ve.uint8array=typeof Uint8Array!="undefined";if(typeof ArrayBuffer=="undefined")ve.blob=!1;else{Ts=new ArrayBuffer(0);try{ve.blob=new Blob([Ts],{type:"application/zip"}).size===0}catch{try{Sd=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,Ls=new Sd,Ls.append(Ts),ve.blob=Ls.getBlob("application/zip").size===0}catch{ve.blob=!1}}}var Ts,Sd,Ls;try{ve.nodestream=!!ks().Readable}catch{ve.nodestream=!1}});var Ps=I(Rs=>{"use strict";var Tb=Y(),Lb=rt(),$e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";Rs.encode=function(e){for(var t=[],i,n,r,a,s,o,c,l=0,d=e.length,u=d,p=Tb.getTypeOf(e)!=="string";l<e.length;)u=d-l,p?(i=e[l++],n=l<d?e[l++]:0,r=l<d?e[l++]:0):(i=e.charCodeAt(l++),n=l<d?e.charCodeAt(l++):0,r=l<d?e.charCodeAt(l++):0),a=i>>2,s=(i&3)<<4|n>>4,o=u>1?(n&15)<<2|r>>6:64,c=u>2?r&63:64,t.push($e.charAt(a)+$e.charAt(s)+$e.charAt(o)+$e.charAt(c));return t.join("")};Rs.decode=function(e){var t,i,n,r,a,s,o,c=0,l=0,d="data:";if(e.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");e=e.replace(/[^A-Za-z0-9+/=]/g,"");var u=e.length*3/4;if(e.charAt(e.length-1)===$e.charAt(64)&&u--,e.charAt(e.length-2)===$e.charAt(64)&&u--,u%1!==0)throw new Error("Invalid base64 input, bad content length.");var p;for(Lb.uint8array?p=new Uint8Array(u|0):p=new Array(u|0);c<e.length;)r=$e.indexOf(e.charAt(c++)),a=$e.indexOf(e.charAt(c++)),s=$e.indexOf(e.charAt(c++)),o=$e.indexOf(e.charAt(c++)),t=r<<2|a>>4,i=(a&15)<<4|s>>2,n=(s&3)<<6|o,p[l++]=t,s!==64&&(p[l++]=i),o!==64&&(p[l++]=n);return p}});var un=I((uw,Ad)=>{"use strict";Ad.exports={isNode:typeof Buffer!="undefined",newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}});var Ld=I((pw,Td)=>{"use strict";var Cd=global.MutationObserver||global.WebKitMutationObserver,mi;process.browser?Cd?(Is=0,kd=new Cd(pn),Ms=global.document.createTextNode(""),kd.observe(Ms,{characterData:!0}),mi=function(){Ms.data=Is=++Is%2}):!global.setImmediate&&typeof global.MessageChannel!="undefined"?(Os=new global.MessageChannel,Os.port1.onmessage=pn,mi=function(){Os.port2.postMessage(0)}):"document"in global&&"onreadystatechange"in global.document.createElement("script")?mi=function(){var e=global.document.createElement("script");e.onreadystatechange=function(){pn(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},global.document.documentElement.appendChild(e)}:mi=function(){setTimeout(pn,0)}:mi=function(){process.nextTick(pn)};var Is,kd,Ms,Os,Ds,fn=[];function pn(){Ds=!0;for(var e,t,i=fn.length;i;){for(t=fn,fn=[],e=-1;++e<i;)t[e]();i=fn.length}Ds=!1}Td.exports=Rb;function Rb(e){fn.push(e)===1&&!Ds&&mi()}});var zd=I((fw,Dd)=>{"use strict";var Rd=Ld();function vi(){}var ce={},Pd=["REJECTED"],zs=["FULFILLED"],Id=["PENDING"];process.browser||(hn=["UNHANDLED"]);var hn;Dd.exports=xt;function xt(e){if(typeof e!="function")throw new TypeError("resolver must be a function");this.state=Id,this.queue=[],this.outcome=void 0,process.browser||(this.handled=hn),e!==vi&&Md(this,e)}xt.prototype.finally=function(e){if(typeof e!="function")return this;var t=this.constructor;return this.then(i,n);function i(r){function a(){return r}return t.resolve(e()).then(a)}function n(r){function a(){throw r}return t.resolve(e()).then(a)}};xt.prototype.catch=function(e){return this.then(null,e)};xt.prototype.then=function(e,t){if(typeof e!="function"&&this.state===zs||typeof t!="function"&&this.state===Pd)return this;var i=new this.constructor(vi);if(process.browser||this.handled===hn&&(this.handled=null),this.state!==Id){var n=this.state===zs?e:t;js(i,n,this.outcome)}else this.queue.push(new gn(i,e,t));return i};function gn(e,t,i){this.promise=e,typeof t=="function"&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),typeof i=="function"&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}gn.prototype.callFulfilled=function(e){ce.resolve(this.promise,e)};gn.prototype.otherCallFulfilled=function(e){js(this.promise,this.onFulfilled,e)};gn.prototype.callRejected=function(e){ce.reject(this.promise,e)};gn.prototype.otherCallRejected=function(e){js(this.promise,this.onRejected,e)};function js(e,t,i){Rd(function(){var n;try{n=t(i)}catch(r){return ce.reject(e,r)}n===e?ce.reject(e,new TypeError("Cannot resolve promise with itself")):ce.resolve(e,n)})}ce.resolve=function(e,t){var i=Od(Pb,t);if(i.status==="error")return ce.reject(e,i.value);var n=i.value;if(n)Md(e,n);else{e.state=zs,e.outcome=t;for(var r=-1,a=e.queue.length;++r<a;)e.queue[r].callFulfilled(t)}return e};ce.reject=function(e,t){e.state=Pd,e.outcome=t,process.browser||e.handled===hn&&Rd(function(){e.handled===hn&&process.emit("unhandledRejection",t,e)});for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e};function Pb(e){var t=e&&e.then;if(e&&(typeof e=="object"||typeof e=="function")&&typeof t=="function")return function(){t.apply(e,arguments)}}function Md(e,t){var i=!1;function n(o){i||(i=!0,ce.reject(e,o))}function r(o){i||(i=!0,ce.resolve(e,o))}function a(){t(r,n)}var s=Od(a);s.status==="error"&&n(s.value)}function Od(e,t){var i={};try{i.value=e(t),i.status="success"}catch(n){i.status="error",i.value=n}return i}xt.resolve=Ib;function Ib(e){return e instanceof this?e:ce.resolve(new this(vi),e)}xt.reject=Mb;function Mb(e){var t=new this(vi);return ce.reject(t,e)}xt.all=Ob;function Ob(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=new Array(i),a=0,s=-1,o=new this(vi);++s<i;)c(e[s],s);return o;function c(l,d){t.resolve(l).then(u,function(p){n||(n=!0,ce.reject(o,p))});function u(p){r[d]=p,++a===i&&!n&&(n=!0,ce.resolve(o,r))}}}xt.race=Db;function Db(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=-1,a=new this(vi);++r<i;)s(e[r]);return a;function s(o){t.resolve(o).then(function(c){n||(n=!0,ce.resolve(a,c))},function(c){n||(n=!0,ce.reject(a,c))})}}});var yi=I((hw,jd)=>{"use strict";var Bs=null;typeof Promise!="undefined"?Bs=Promise:Bs=zd();jd.exports={Promise:Bs}});var Fd=I(Bd=>{"use strict";(function(e,t){"use strict";if(e.setImmediate)return;var i=1,n={},r=!1,a=e.document,s;function o(v){typeof v!="function"&&(v=new Function(""+v));for(var y=new Array(arguments.length-1),x=0;x<y.length;x++)y[x]=arguments[x+1];var w={callback:v,args:y};return n[i]=w,s(i),i++}function c(v){delete n[v]}function l(v){var y=v.callback,x=v.args;switch(x.length){case 0:y();break;case 1:y(x[0]);break;case 2:y(x[0],x[1]);break;case 3:y(x[0],x[1],x[2]);break;default:y.apply(t,x);break}}function d(v){if(r)setTimeout(d,0,v);else{var y=n[v];if(y){r=!0;try{l(y)}finally{c(v),r=!1}}}}function u(){s=function(v){process.nextTick(function(){d(v)})}}function p(){if(e.postMessage&&!e.importScripts){var v=!0,y=e.onmessage;return e.onmessage=function(){v=!1},e.postMessage("","*"),e.onmessage=y,v}}function f(){var v="setImmediate$"+Math.random()+"$",y=function(x){x.source===e&&typeof x.data=="string"&&x.data.indexOf(v)===0&&d(+x.data.slice(v.length))};e.addEventListener?e.addEventListener("message",y,!1):e.attachEvent("onmessage",y),s=function(x){e.postMessage(v+x,"*")}}function b(){var v=new MessageChannel;v.port1.onmessage=function(y){var x=y.data;d(x)},s=function(y){v.port2.postMessage(y)}}function h(){var v=a.documentElement;s=function(y){var x=a.createElement("script");x.onreadystatechange=function(){d(y),x.onreadystatechange=null,v.removeChild(x),x=null},v.appendChild(x)}}function g(){s=function(v){setTimeout(d,0,v)}}var m=Object.getPrototypeOf&&Object.getPrototypeOf(e);m=m&&m.setTimeout?m:e,{}.toString.call(e.process)==="[object process]"?u():p()?f():e.MessageChannel?b():a&&"onreadystatechange"in a.createElement("script")?h():g(),m.setImmediate=o,m.clearImmediate=c})(typeof self=="undefined"?typeof global=="undefined"?Bd:global:self)});var Y=I(ee=>{"use strict";var wt=rt(),zb=Ps(),xi=un(),Fs=yi();Fd();function jb(e){var t=null;return wt.uint8array?t=new Uint8Array(e.length):t=new Array(e.length),Dr(e,t)}ee.newBlob=function(e,t){ee.checkSupport("blob");try{return new Blob([e],{type:t})}catch{try{var i=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,n=new i;return n.append(e),n.getBlob(t)}catch{throw new Error("Bug : can't construct the Blob.")}}};function bn(e){return e}function Dr(e,t){for(var i=0;i<e.length;++i)t[i]=e.charCodeAt(i)&255;return t}var Or={stringifyByChunk:function(e,t,i){var n=[],r=0,a=e.length;if(a<=i)return String.fromCharCode.apply(null,e);for(;r<a;)t==="array"||t==="nodebuffer"?n.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+i,a)))):n.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+i,a)))),r+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:(function(){try{return wt.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return wt.nodebuffer&&String.fromCharCode.apply(null,xi.allocBuffer(1)).length===1}catch{return!1}})()}};function mn(e){var t=65536,i=ee.getTypeOf(e),n=!0;if(i==="uint8array"?n=Or.applyCanBeUsed.uint8array:i==="nodebuffer"&&(n=Or.applyCanBeUsed.nodebuffer),n)for(;t>1;)try{return Or.stringifyByChunk(e,i,t)}catch{t=Math.floor(t/2)}return Or.stringifyByChar(e)}ee.applyFromCharCode=mn;function zr(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}var _t={};_t.string={string:bn,array:function(e){return Dr(e,new Array(e.length))},arraybuffer:function(e){return _t.string.uint8array(e).buffer},uint8array:function(e){return Dr(e,new Uint8Array(e.length))},nodebuffer:function(e){return Dr(e,xi.allocBuffer(e.length))}};_t.array={string:mn,array:bn,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return xi.newBufferFrom(e)}};_t.arraybuffer={string:function(e){return mn(new Uint8Array(e))},array:function(e){return zr(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:bn,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return xi.newBufferFrom(new Uint8Array(e))}};_t.uint8array={string:mn,array:function(e){return zr(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:bn,nodebuffer:function(e){return xi.newBufferFrom(e)}};_t.nodebuffer={string:mn,array:function(e){return zr(e,new Array(e.length))},arraybuffer:function(e){return _t.nodebuffer.uint8array(e).buffer},uint8array:function(e){return zr(e,new Uint8Array(e.length))},nodebuffer:bn};ee.transformTo=function(e,t){if(t||(t=""),!e)return t;ee.checkSupport(e);var i=ee.getTypeOf(t),n=_t[i][e](t);return n};ee.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var r=t[n];r==="."||r===""&&n!==0&&n!==t.length-1||(r===".."?i.pop():i.push(r))}return i.join("/")};ee.getTypeOf=function(e){if(typeof e=="string")return"string";if(Object.prototype.toString.call(e)==="[object Array]")return"array";if(wt.nodebuffer&&xi.isBuffer(e))return"nodebuffer";if(wt.uint8array&&e instanceof Uint8Array)return"uint8array";if(wt.arraybuffer&&e instanceof ArrayBuffer)return"arraybuffer"};ee.checkSupport=function(e){var t=wt[e.toLowerCase()];if(!t)throw new Error(e+" is not supported by this platform")};ee.MAX_VALUE_16BITS=65535;ee.MAX_VALUE_32BITS=-1;ee.pretty=function(e){var t="",i,n;for(n=0;n<(e||"").length;n++)i=e.charCodeAt(n),t+="\\x"+(i<16?"0":"")+i.toString(16).toUpperCase();return t};ee.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})};ee.inherits=function(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i};ee.extend=function(){var e={},t,i;for(t=0;t<arguments.length;t++)for(i in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],i)&&typeof e[i]=="undefined"&&(e[i]=arguments[t][i]);return e};ee.prepareContent=function(e,t,i,n,r){var a=Fs.Promise.resolve(t).then(function(s){var o=wt.blob&&(s instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(s))!==-1);return o&&typeof FileReader!="undefined"?new Fs.Promise(function(c,l){var d=new FileReader;d.onload=function(u){c(u.target.result)},d.onerror=function(u){l(u.target.error)},d.readAsArrayBuffer(s)}):s});return a.then(function(s){var o=ee.getTypeOf(s);return o?(o==="arraybuffer"?s=ee.transformTo("uint8array",s):o==="string"&&(r?s=zb.decode(s):i&&n!==!0&&(s=jb(s))),s):Fs.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}});var ye=I((mw,Hd)=>{"use strict";function Nd(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}Nd.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return this.isFinished?!1:(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.end()}),e.on("error",function(i){t.error(i)}),this},pause:function(){return this.isPaused||this.isFinished?!1:(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;this.isPaused=!1;var e=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}};Hd.exports=Nd});var _i=I(Et=>{"use strict";var wi=Y(),Nt=rt(),Bb=un(),jr=ye(),vn=new Array(256);for(at=0;at<256;at++)vn[at]=at>=252?6:at>=248?5:at>=240?4:at>=224?3:at>=192?2:1;var at;vn[254]=vn[254]=1;var Fb=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(Nt.uint8array?t=new Uint8Array(o):t=new Array(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t},Nb=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+vn[e[i]]>t?i:t},Hb=function(e){var t,i,n,r,a=e.length,s=new Array(a*2);for(i=0,t=0;t<a;){if(n=e[t++],n<128){s[i++]=n;continue}if(r=vn[n],r>4){s[i++]=65533,t+=r-1;continue}for(n&=r===2?31:r===3?15:7;r>1&&t<a;)n=n<<6|e[t++]&63,r--;if(r>1){s[i++]=65533;continue}n<65536?s[i++]=n:(n-=65536,s[i++]=55296|n>>10&1023,s[i++]=56320|n&1023)}return s.length!==i&&(s.subarray?s=s.subarray(0,i):s.length=i),wi.applyFromCharCode(s)};Et.utf8encode=function(t){return Nt.nodebuffer?Bb.newBufferFrom(t,"utf-8"):Fb(t)};Et.utf8decode=function(t){return Nt.nodebuffer?wi.transformTo("nodebuffer",t).toString("utf-8"):(t=wi.transformTo(Nt.uint8array?"uint8array":"array",t),Hb(t))};function Br(){jr.call(this,"utf-8 decode"),this.leftOver=null}wi.inherits(Br,jr);Br.prototype.processChunk=function(e){var t=wi.transformTo(Nt.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(Nt.uint8array){var i=t;t=new Uint8Array(i.length+this.leftOver.length),t.set(this.leftOver,0),t.set(i,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var n=Nb(t),r=t;n!==t.length&&(Nt.uint8array?(r=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(r=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:Et.utf8decode(r),meta:e.meta})};Br.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:Et.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)};Et.Utf8DecodeWorker=Br;function Ns(){jr.call(this,"utf-8 encode")}wi.inherits(Ns,jr);Ns.prototype.processChunk=function(e){this.push({data:Et.utf8encode(e.data),meta:e.meta})};Et.Utf8EncodeWorker=Ns});var Gd=I((yw,qd)=>{"use strict";var Ud=ye(),$d=Y();function Hs(e){Ud.call(this,"ConvertWorker to "+e),this.destType=e}$d.inherits(Hs,Ud);Hs.prototype.processChunk=function(e){this.push({data:$d.transformTo(this.destType,e.data),meta:e.meta})};qd.exports=Hs});var Vd=I((xw,Yd)=>{"use strict";var Wd=ks().Readable,Ub=Y();Ub.inherits(Us,Wd);function Us(e,t,i){Wd.call(this,t),this._helper=e;var n=this;e.on("data",function(r,a){n.push(r)||n._helper.pause(),i&&i(a)}).on("error",function(r){n.emit("error",r)}).on("end",function(){n.push(null)})}Us.prototype._read=function(){this._helper.resume()};Yd.exports=Us});var $s=I((ww,Zd)=>{"use strict";var Ht=Y(),$b=Gd(),qb=ye(),Gb=Ps(),Wb=rt(),Yb=yi(),Kd=null;if(Wb.nodestream)try{Kd=Vd()}catch{}function Vb(e,t,i){switch(e){case"blob":return Ht.newBlob(Ht.transformTo("arraybuffer",t),i);case"base64":return Gb.encode(t);default:return Ht.transformTo(e,t)}}function Kb(e,t){var i,n=0,r=null,a=0;for(i=0;i<t.length;i++)a+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(a),i=0;i<t.length;i++)r.set(t[i],n),n+=t[i].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}function Xb(e,t){return new Yb.Promise(function(i,n){var r=[],a=e._internalType,s=e._outputType,o=e._mimeType;e.on("data",function(c,l){r.push(c),t&&t(l)}).on("error",function(c){r=[],n(c)}).on("end",function(){try{var c=Vb(s,Kb(a,r),o);i(c)}catch(l){n(l)}r=[]}).resume()})}function Xd(e,t,i){var n=t;switch(t){case"blob":case"arraybuffer":n="uint8array";break;case"base64":n="string";break}try{this._internalType=n,this._outputType=t,this._mimeType=i,Ht.checkSupport(n),this._worker=e.pipe(new $b(n)),e.lock()}catch(r){this._worker=new qb("error"),this._worker.error(r)}}Xd.prototype={accumulate:function(e){return Xb(this,e)},on:function(e,t){var i=this;return e==="data"?this._worker.on(e,function(n){t.call(i,n.data,n.meta)}):this._worker.on(e,function(){Ht.delay(t,arguments,i)}),this},resume:function(){return Ht.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(Ht.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new Kd(this,{objectMode:this._outputType!=="nodebuffer"},e)}};Zd.exports=Xd});var qs=I(Ie=>{"use strict";Ie.base64=!1;Ie.binary=!1;Ie.dir=!1;Ie.createFolders=!0;Ie.date=null;Ie.compression=null;Ie.compressionOptions=null;Ie.comment=null;Ie.unixPermissions=null;Ie.dosPermissions=null});var Gs=I((Ew,Jd)=>{"use strict";var Fr=Y(),Nr=ye(),Zb=16*1024;function Ei(e){Nr.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(i){t.dataIsReady=!0,t.data=i,t.max=i&&i.length||0,t.type=Fr.getTypeOf(i),t.isPaused||t._tickAndRepeat()},function(i){t.error(i)})}Fr.inherits(Ei,Nr);Ei.prototype.cleanUp=function(){Nr.prototype.cleanUp.call(this),this.data=null};Ei.prototype.resume=function(){return Nr.prototype.resume.call(this)?(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,Fr.delay(this._tickAndRepeat,[],this)),!0):!1};Ei.prototype._tickAndRepeat=function(){this._tickScheduled=!1,!(this.isPaused||this.isFinished)&&(this._tick(),this.isFinished||(Fr.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))};Ei.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=Zb,t=null,i=Math.min(this.max,this.index+e);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,i);break;case"uint8array":t=this.data.subarray(this.index,i);break;case"array":case"nodebuffer":t=this.data.slice(this.index,i);break}return this.index=i,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})};Jd.exports=Ei});var Hr=I((Sw,eu)=>{"use strict";var Jb=Y();function Qb(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var Qd=Qb();function em(e,t,i,n){var r=Qd,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}function tm(e,t,i,n){var r=Qd,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t.charCodeAt(s))&255];return e^-1}eu.exports=function(t,i){if(typeof t=="undefined"||!t.length)return 0;var n=Jb.getTypeOf(t)!=="string";return n?em(i|0,t,t.length,0):tm(i|0,t,t.length,0)}});var Ys=I((Aw,iu)=>{"use strict";var tu=ye(),im=Hr(),nm=Y();function Ws(){tu.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}nm.inherits(Ws,tu);Ws.prototype.processChunk=function(e){this.streamInfo.crc32=im(e.data,this.streamInfo.crc32||0),this.push(e)};iu.exports=Ws});var ru=I((Cw,nu)=>{"use strict";var rm=Y(),Vs=ye();function Ks(e){Vs.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}rm.inherits(Ks,Vs);Ks.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}Vs.prototype.processChunk.call(this,e)};nu.exports=Ks});var Ur=I((kw,ou)=>{"use strict";var au=yi(),su=Gs(),am=Ys(),Xs=ru();function Zs(e,t,i,n,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=r}Zs.prototype={getContentWorker:function(){var e=new su(au.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new Xs("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new su(au.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};Zs.createWorkerFrom=function(e,t,i){return e.pipe(new am).pipe(new Xs("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new Xs("compressedSize")).withStreamInfo("compression",t)};ou.exports=Zs});var uu=I((Tw,du)=>{"use strict";var sm=$s(),om=Gs(),Js=_i(),Qs=Ur(),lu=ye(),eo=function(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}};eo.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");i=e.toLowerCase();var n=i==="string"||i==="text";(i==="binarystring"||i==="text")&&(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new Js.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new Js.Utf8DecodeWorker))}catch(a){t=new lu("error"),t.error(a)}return new sm(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof Qs&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new Js.Utf8EncodeWorker)),Qs.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof Qs?this._data.getContentWorker():this._data instanceof lu?this._data:new om(this._data)}};var cu=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],lm=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for($r=0;$r<cu.length;$r++)eo.prototype[cu[$r]]=lm;var $r;du.exports=eo});var st=I(he=>{"use strict";var cm=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function dm(e,t){return Object.prototype.hasOwnProperty.call(e,t)}he.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if(typeof i!="object")throw new TypeError(i+"must be non-object");for(var n in i)dm(i,n)&&(e[n]=i[n])}}return e};he.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var um={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray){e.set(t.subarray(i,i+n),r);return}for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){var t,i,n,r,a,s;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(s=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)a=e[t],s.set(a,r),r+=a.length;return s}},pm={arraySet:function(e,t,i,n,r){for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){return[].concat.apply([],e)}};he.setTyped=function(e){e?(he.Buf8=Uint8Array,he.Buf16=Uint16Array,he.Buf32=Int32Array,he.assign(he,um)):(he.Buf8=Array,he.Buf16=Array,he.Buf32=Array,he.assign(he,pm))};he.setTyped(cm)});var Ou=I(Ci=>{"use strict";var fm=st(),hm=4,pu=0,fu=1,gm=2;function Ai(e){for(var t=e.length;--t>=0;)e[t]=0}var bm=0,yu=1,mm=2,vm=3,ym=258,oo=29,Sn=256,xn=Sn+1+oo,Si=30,lo=19,xu=2*xn+1,Ut=15,to=16,xm=7,co=256,wu=16,_u=17,Eu=18,ao=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],qr=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],wm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Su=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],_m=512,ot=new Array((xn+2)*2);Ai(ot);var yn=new Array(Si*2);Ai(yn);var wn=new Array(_m);Ai(wn);var _n=new Array(ym-vm+1);Ai(_n);var uo=new Array(oo);Ai(uo);var Gr=new Array(Si);Ai(Gr);function io(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}var Au,Cu,ku;function no(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Tu(e){return e<256?wn[e]:wn[256+(e>>>7)]}function En(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function be(e,t,i){e.bi_valid>to-i?(e.bi_buf|=t<<e.bi_valid&65535,En(e,e.bi_buf),e.bi_buf=t>>to-e.bi_valid,e.bi_valid+=i-to):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function qe(e,t,i){be(e,i[t*2],i[t*2+1])}function Lu(e,t){var i=0;do i|=e&1,e>>>=1,i<<=1;while(--t>0);return i>>>1}function Em(e){e.bi_valid===16?(En(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Sm(e,t){var i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,d,u,p,f,b,h=0;for(p=0;p<=Ut;p++)e.bl_count[p]=0;for(i[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<xu;l++)d=e.heap[l],p=i[i[d*2+1]*2+1]+1,p>c&&(p=c,h++),i[d*2+1]=p,!(d>n)&&(e.bl_count[p]++,f=0,d>=o&&(f=s[d-o]),b=i[d*2],e.opt_len+=b*(p+f),a&&(e.static_len+=b*(r[d*2+1]+f)));if(h!==0){do{for(p=c-1;e.bl_count[p]===0;)p--;e.bl_count[p]--,e.bl_count[p+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(p=c;p!==0;p--)for(d=e.bl_count[p];d!==0;)u=e.heap[--l],!(u>n)&&(i[u*2+1]!==p&&(e.opt_len+=(p-i[u*2+1])*i[u*2],i[u*2+1]=p),d--)}}function Ru(e,t,i){var n=new Array(Ut+1),r=0,a,s;for(a=1;a<=Ut;a++)n[a]=r=r+i[a-1]<<1;for(s=0;s<=t;s++){var o=e[s*2+1];o!==0&&(e[s*2]=Lu(n[o]++,o))}}function Am(){var e,t,i,n,r,a=new Array(Ut+1);for(i=0,n=0;n<oo-1;n++)for(uo[n]=i,e=0;e<1<<ao[n];e++)_n[i++]=n;for(_n[i-1]=n,r=0,n=0;n<16;n++)for(Gr[n]=r,e=0;e<1<<qr[n];e++)wn[r++]=n;for(r>>=7;n<Si;n++)for(Gr[n]=r<<7,e=0;e<1<<qr[n]-7;e++)wn[256+r++]=n;for(t=0;t<=Ut;t++)a[t]=0;for(e=0;e<=143;)ot[e*2+1]=8,e++,a[8]++;for(;e<=255;)ot[e*2+1]=9,e++,a[9]++;for(;e<=279;)ot[e*2+1]=7,e++,a[7]++;for(;e<=287;)ot[e*2+1]=8,e++,a[8]++;for(Ru(ot,xn+1,a),e=0;e<Si;e++)yn[e*2+1]=5,yn[e*2]=Lu(e,5);Au=new io(ot,ao,Sn+1,xn,Ut),Cu=new io(yn,qr,0,Si,Ut),ku=new io(new Array(0),wm,0,lo,xm)}function Pu(e){var t;for(t=0;t<xn;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Si;t++)e.dyn_dtree[t*2]=0;for(t=0;t<lo;t++)e.bl_tree[t*2]=0;e.dyn_ltree[co*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Iu(e){e.bi_valid>8?En(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Cm(e,t,i,n){Iu(e),n&&(En(e,i),En(e,~i)),fm.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}function hu(e,t,i,n){var r=t*2,a=i*2;return e[r]<e[a]||e[r]===e[a]&&n[t]<=n[i]}function ro(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&hu(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!hu(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function gu(e,t,i){var n,r,a=0,s,o;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],r=e.pending_buf[e.l_buf+a],a++,n===0?qe(e,r,t):(s=_n[r],qe(e,s+Sn+1,t),o=ao[s],o!==0&&(r-=uo[s],be(e,r,o)),n--,s=Tu(n),qe(e,s,i),o=qr[s],o!==0&&(n-=Gr[s],be(e,n,o)));while(a<e.last_lit);qe(e,co,t)}function so(e,t){var i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.elems,s,o,c=-1,l;for(e.heap_len=0,e.heap_max=xu,s=0;s<a;s++)i[s*2]!==0?(e.heap[++e.heap_len]=c=s,e.depth[s]=0):i[s*2+1]=0;for(;e.heap_len<2;)l=e.heap[++e.heap_len]=c<2?++c:0,i[l*2]=1,e.depth[l]=0,e.opt_len--,r&&(e.static_len-=n[l*2+1]);for(t.max_code=c,s=e.heap_len>>1;s>=1;s--)ro(e,i,s);l=a;do s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ro(e,i,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,i[l*2]=i[s*2]+i[o*2],e.depth[l]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,i[s*2+1]=i[o*2+1]=l,e.heap[1]=l++,ro(e,i,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Sm(e,t),Ru(i,c,e.bl_count)}function bu(e,t,i){var n,r=-1,a,s=t[1],o=0,c=7,l=4;for(s===0&&(c=138,l=3),t[(i+1)*2+1]=65535,n=0;n<=i;n++)a=s,s=t[(n+1)*2+1],!(++o<c&&a===s)&&(o<l?e.bl_tree[a*2]+=o:a!==0?(a!==r&&e.bl_tree[a*2]++,e.bl_tree[wu*2]++):o<=10?e.bl_tree[_u*2]++:e.bl_tree[Eu*2]++,o=0,r=a,s===0?(c=138,l=3):a===s?(c=6,l=3):(c=7,l=4))}function mu(e,t,i){var n,r=-1,a,s=t[1],o=0,c=7,l=4;for(s===0&&(c=138,l=3),n=0;n<=i;n++)if(a=s,s=t[(n+1)*2+1],!(++o<c&&a===s)){if(o<l)do qe(e,a,e.bl_tree);while(--o!==0);else a!==0?(a!==r&&(qe(e,a,e.bl_tree),o--),qe(e,wu,e.bl_tree),be(e,o-3,2)):o<=10?(qe(e,_u,e.bl_tree),be(e,o-3,3)):(qe(e,Eu,e.bl_tree),be(e,o-11,7));o=0,r=a,s===0?(c=138,l=3):a===s?(c=6,l=3):(c=7,l=4)}}function km(e){var t;for(bu(e,e.dyn_ltree,e.l_desc.max_code),bu(e,e.dyn_dtree,e.d_desc.max_code),so(e,e.bl_desc),t=lo-1;t>=3&&e.bl_tree[Su[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Tm(e,t,i,n){var r;for(be(e,t-257,5),be(e,i-1,5),be(e,n-4,4),r=0;r<n;r++)be(e,e.bl_tree[Su[r]*2+1],3);mu(e,e.dyn_ltree,t-1),mu(e,e.dyn_dtree,i-1)}function Lm(e){var t=4093624447,i;for(i=0;i<=31;i++,t>>>=1)if(t&1&&e.dyn_ltree[i*2]!==0)return pu;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return fu;for(i=32;i<Sn;i++)if(e.dyn_ltree[i*2]!==0)return fu;return pu}var vu=!1;function Rm(e){vu||(Am(),vu=!0),e.l_desc=new no(e.dyn_ltree,Au),e.d_desc=new no(e.dyn_dtree,Cu),e.bl_desc=new no(e.bl_tree,ku),e.bi_buf=0,e.bi_valid=0,Pu(e)}function Mu(e,t,i,n){be(e,(bm<<1)+(n?1:0),3),Cm(e,t,i,!0)}function Pm(e){be(e,yu<<1,3),qe(e,co,ot),Em(e)}function Im(e,t,i,n){var r,a,s=0;e.level>0?(e.strm.data_type===gm&&(e.strm.data_type=Lm(e)),so(e,e.l_desc),so(e,e.d_desc),s=km(e),r=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=r&&(r=a)):r=a=i+5,i+4<=r&&t!==-1?Mu(e,t,i,n):e.strategy===hm||a===r?(be(e,(yu<<1)+(n?1:0),3),gu(e,ot,yn)):(be(e,(mm<<1)+(n?1:0),3),Tm(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),gu(e,e.dyn_ltree,e.dyn_dtree)),Pu(e),n&&Iu(e)}function Mm(e,t,i){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=i&255,e.last_lit++,t===0?e.dyn_ltree[i*2]++:(e.matches++,t--,e.dyn_ltree[(_n[i]+Sn+1)*2]++,e.dyn_dtree[Tu(t)*2]++),e.last_lit===e.lit_bufsize-1}Ci._tr_init=Rm;Ci._tr_stored_block=Mu;Ci._tr_flush_block=Im;Ci._tr_tally=Mm;Ci._tr_align=Pm});var po=I((Pw,Du)=>{"use strict";function Om(e,t,i,n){for(var r=e&65535|0,a=e>>>16&65535|0,s=0;i!==0;){s=i>2e3?2e3:i,i-=s;do r=r+t[n++]|0,a=a+r|0;while(--s);r%=65521,a%=65521}return r|a<<16|0}Du.exports=Om});var fo=I((Iw,zu)=>{"use strict";function Dm(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var zm=Dm();function jm(e,t,i,n){var r=zm,a=n+i;e^=-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}zu.exports=jm});var Wr=I((Mw,ju)=>{"use strict";ju.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var Wu=I(Ye=>{"use strict";var ge=st(),Se=Ou(),Hu=po(),St=fo(),Bm=Wr(),Wt=0,Fm=1,Nm=3,Lt=4,Bu=5,We=0,Fu=1,Ae=-2,Hm=-3,ho=-5,Um=-1,$m=1,Yr=2,qm=3,Gm=4,Wm=0,Ym=2,Zr=8,Vm=9,Km=15,Xm=8,Zm=29,Jm=256,bo=Jm+1+Zm,Qm=30,ev=19,tv=2*bo+1,iv=15,B=3,kt=258,Me=kt+B+1,nv=32,Jr=42,mo=69,Vr=73,Kr=91,Xr=103,$t=113,Cn=666,ne=1,kn=2,qt=3,Li=4,rv=3;function Tt(e,t){return e.msg=Bm[t],t}function Nu(e){return(e<<1)-(e>4?9:0)}function Ct(e){for(var t=e.length;--t>=0;)e[t]=0}function At(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),i!==0&&(ge.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,t.pending===0&&(t.pending_out=0))}function ae(e,t){Se._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,At(e.strm)}function F(e,t){e.pending_buf[e.pending++]=t}function An(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function av(e,t,i,n){var r=e.avail_in;return r>n&&(r=n),r===0?0:(e.avail_in-=r,ge.arraySet(t,e.input,e.next_in,r,i),e.state.wrap===1?e.adler=Hu(e.adler,t,r,i):e.state.wrap===2&&(e.adler=St(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)}function Uu(e,t){var i=e.max_chain_length,n=e.strstart,r,a,s=e.prev_length,o=e.nice_match,c=e.strstart>e.w_size-Me?e.strstart-(e.w_size-Me):0,l=e.window,d=e.w_mask,u=e.prev,p=e.strstart+kt,f=l[n+s-1],b=l[n+s];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do if(r=t,!(l[r+s]!==b||l[r+s-1]!==f||l[r]!==l[n]||l[++r]!==l[n+1])){n+=2,r++;do;while(l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&n<p);if(a=kt-(p-n),n=p-kt,a>s){if(e.match_start=t,s=a,a>=o)break;f=l[n+s-1],b=l[n+s]}}while((t=u[t&d])>c&&--i!==0);return s<=e.lookahead?s:e.lookahead}function Gt(e){var t=e.w_size,i,n,r,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Me)){ge.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,i=n;do r=e.head[--i],e.head[i]=r>=t?r-t:0;while(--n);n=t,i=n;do r=e.prev[--i],e.prev[i]=r>=t?r-t:0;while(--n);a+=t}if(e.strm.avail_in===0)break;if(n=av(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=B)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+B-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<B)););}while(e.lookahead<Me&&e.strm.avail_in!==0)}function sv(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Gt(e),e.lookahead===0&&t===Wt)return ne;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,ae(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Me&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):(e.strstart>e.block_start&&(ae(e,!1),e.strm.avail_out===0),ne)}function go(e,t){for(var i,n;;){if(e.lookahead<Me){if(Gt(e),e.lookahead<Me&&t===Wt)return ne;if(e.lookahead===0)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),i!==0&&e.strstart-i<=e.w_size-Me&&(e.match_length=Uu(e,i)),e.match_length>=B)if(n=Se._tr_tally(e,e.strstart-e.match_start,e.match_length-B),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=B){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=e.strstart<B-1?e.strstart:B-1,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function ki(e,t){for(var i,n,r;;){if(e.lookahead<Me){if(Gt(e),e.lookahead<Me&&t===Wt)return ne;if(e.lookahead===0)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=B-1,i!==0&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-Me&&(e.match_length=Uu(e,i),e.match_length<=5&&(e.strategy===$m||e.match_length===B&&e.strstart-e.match_start>4096)&&(e.match_length=B-1)),e.prev_length>=B&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-B,n=Se._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-B),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=B-1,e.strstart++,n&&(ae(e,!1),e.strm.avail_out===0))return ne}else if(e.match_available){if(n=Se._tr_tally(e,0,e.window[e.strstart-1]),n&&ae(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return ne}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Se._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<B-1?e.strstart:B-1,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function ov(e,t){for(var i,n,r,a,s=e.window;;){if(e.lookahead<=kt){if(Gt(e),e.lookahead<=kt&&t===Wt)return ne;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=B&&e.strstart>0&&(r=e.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){a=e.strstart+kt;do;while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<a);e.match_length=kt-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=B?(i=Se._tr_tally(e,1,e.match_length-B),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function lv(e,t){for(var i;;){if(e.lookahead===0&&(Gt(e),e.lookahead===0)){if(t===Wt)return ne;break}if(e.match_length=0,i=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function Ge(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}var Ti;Ti=[new Ge(0,0,0,0,sv),new Ge(4,4,8,4,go),new Ge(4,5,16,8,go),new Ge(4,6,32,32,go),new Ge(4,4,16,16,ki),new Ge(8,16,32,32,ki),new Ge(8,16,128,128,ki),new Ge(8,32,128,256,ki),new Ge(32,128,258,1024,ki),new Ge(32,258,258,4096,ki)];function cv(e){e.window_size=2*e.w_size,Ct(e.head),e.max_lazy_match=Ti[e.level].max_lazy,e.good_match=Ti[e.level].good_length,e.nice_match=Ti[e.level].nice_length,e.max_chain_length=Ti[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=B-1,e.match_available=0,e.ins_h=0}function dv(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Zr,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ge.Buf16(tv*2),this.dyn_dtree=new ge.Buf16((2*Qm+1)*2),this.bl_tree=new ge.Buf16((2*ev+1)*2),Ct(this.dyn_ltree),Ct(this.dyn_dtree),Ct(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ge.Buf16(iv+1),this.heap=new ge.Buf16(2*bo+1),Ct(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ge.Buf16(2*bo+1),Ct(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function $u(e){var t;return!e||!e.state?Tt(e,Ae):(e.total_in=e.total_out=0,e.data_type=Ym,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?Jr:$t,e.adler=t.wrap===2?0:1,t.last_flush=Wt,Se._tr_init(t),We)}function qu(e){var t=$u(e);return t===We&&cv(e.state),t}function uv(e,t){return!e||!e.state||e.state.wrap!==2?Ae:(e.state.gzhead=t,We)}function Gu(e,t,i,n,r,a){if(!e)return Ae;var s=1;if(t===Um&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>Vm||i!==Zr||n<8||n>15||t<0||t>9||a<0||a>Gm)return Tt(e,Ae);n===8&&(n=9);var o=new dv;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+B-1)/B),o.window=new ge.Buf8(o.w_size*2),o.head=new ge.Buf16(o.hash_size),o.prev=new ge.Buf16(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new ge.Buf8(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=a,o.method=i,qu(e)}function pv(e,t){return Gu(e,t,Zr,Km,Xm,Wm)}function fv(e,t){var i,n,r,a;if(!e||!e.state||t>Bu||t<0)return e?Tt(e,Ae):Ae;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Cn&&t!==Lt)return Tt(e,e.avail_out===0?ho:Ae);if(n.strm=e,i=n.last_flush,n.last_flush=t,n.status===Jr)if(n.wrap===2)e.adler=0,F(n,31),F(n,139),F(n,8),n.gzhead?(F(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),F(n,n.gzhead.time&255),F(n,n.gzhead.time>>8&255),F(n,n.gzhead.time>>16&255),F(n,n.gzhead.time>>24&255),F(n,n.level===9?2:n.strategy>=Yr||n.level<2?4:0),F(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(F(n,n.gzhead.extra.length&255),F(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=St(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=mo):(F(n,0),F(n,0),F(n,0),F(n,0),F(n,0),F(n,n.level===9?2:n.strategy>=Yr||n.level<2?4:0),F(n,rv),n.status=$t);else{var s=Zr+(n.w_bits-8<<4)<<8,o=-1;n.strategy>=Yr||n.level<2?o=0:n.level<6?o=1:n.level===6?o=2:o=3,s|=o<<6,n.strstart!==0&&(s|=nv),s+=31-s%31,n.status=$t,An(n,s),n.strstart!==0&&(An(n,e.adler>>>16),An(n,e.adler&65535)),e.adler=1}if(n.status===mo)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size));)F(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=Vr)}else n.status=Vr;if(n.status===Vr)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.name.length?a=n.gzhead.name.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.gzindex=0,n.status=Kr)}else n.status=Kr;if(n.status===Kr)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.comment.length?a=n.gzhead.comment.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.status=Xr)}else n.status=Xr;if(n.status===Xr&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&At(e),n.pending+2<=n.pending_buf_size&&(F(n,e.adler&255),F(n,e.adler>>8&255),e.adler=0,n.status=$t)):n.status=$t),n.pending!==0){if(At(e),e.avail_out===0)return n.last_flush=-1,We}else if(e.avail_in===0&&Nu(t)<=Nu(i)&&t!==Lt)return Tt(e,ho);if(n.status===Cn&&e.avail_in!==0)return Tt(e,ho);if(e.avail_in!==0||n.lookahead!==0||t!==Wt&&n.status!==Cn){var c=n.strategy===Yr?lv(n,t):n.strategy===qm?ov(n,t):Ti[n.level].func(n,t);if((c===qt||c===Li)&&(n.status=Cn),c===ne||c===qt)return e.avail_out===0&&(n.last_flush=-1),We;if(c===kn&&(t===Fm?Se._tr_align(n):t!==Bu&&(Se._tr_stored_block(n,0,0,!1),t===Nm&&(Ct(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),At(e),e.avail_out===0))return n.last_flush=-1,We}return t!==Lt?We:n.wrap<=0?Fu:(n.wrap===2?(F(n,e.adler&255),F(n,e.adler>>8&255),F(n,e.adler>>16&255),F(n,e.adler>>24&255),F(n,e.total_in&255),F(n,e.total_in>>8&255),F(n,e.total_in>>16&255),F(n,e.total_in>>24&255)):(An(n,e.adler>>>16),An(n,e.adler&65535)),At(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?We:Fu)}function hv(e){var t;return!e||!e.state?Ae:(t=e.state.status,t!==Jr&&t!==mo&&t!==Vr&&t!==Kr&&t!==Xr&&t!==$t&&t!==Cn?Tt(e,Ae):(e.state=null,t===$t?Tt(e,Hm):We))}function gv(e,t){var i=t.length,n,r,a,s,o,c,l,d;if(!e||!e.state||(n=e.state,s=n.wrap,s===2||s===1&&n.status!==Jr||n.lookahead))return Ae;for(s===1&&(e.adler=Hu(e.adler,t,i,0)),n.wrap=0,i>=n.w_size&&(s===0&&(Ct(n.head),n.strstart=0,n.block_start=0,n.insert=0),d=new ge.Buf8(n.w_size),ge.arraySet(d,t,i-n.w_size,n.w_size,0),t=d,i=n.w_size),o=e.avail_in,c=e.next_in,l=e.input,e.avail_in=i,e.next_in=0,e.input=t,Gt(n);n.lookahead>=B;){r=n.strstart,a=n.lookahead-(B-1);do n.ins_h=(n.ins_h<<n.hash_shift^n.window[r+B-1])&n.hash_mask,n.prev[r&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=r,r++;while(--a);n.strstart=r,n.lookahead=B-1,Gt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=B-1,n.match_available=0,e.next_in=c,e.input=l,e.avail_in=o,n.wrap=s,We}Ye.deflateInit=pv;Ye.deflateInit2=Gu;Ye.deflateReset=qu;Ye.deflateResetKeep=$u;Ye.deflateSetHeader=uv;Ye.deflate=fv;Ye.deflateEnd=hv;Ye.deflateSetDictionary=gv;Ye.deflateInfo="pako deflate (from Nodeca project)"});var vo=I(Ri=>{"use strict";var Qr=st(),Yu=!0,Vu=!0;try{String.fromCharCode.apply(null,[0])}catch{Yu=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Vu=!1}var Tn=new Qr.Buf8(256);for(lt=0;lt<256;lt++)Tn[lt]=lt>=252?6:lt>=248?5:lt>=240?4:lt>=224?3:lt>=192?2:1;var lt;Tn[254]=Tn[254]=1;Ri.string2buf=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Qr.Buf8(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t};function Ku(e,t){if(t<65534&&(e.subarray&&Vu||!e.subarray&&Yu))return String.fromCharCode.apply(null,Qr.shrinkBuf(e,t));for(var i="",n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i}Ri.buf2binstring=function(e){return Ku(e,e.length)};Ri.binstring2buf=function(e){for(var t=new Qr.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t};Ri.buf2string=function(e,t){var i,n,r,a,s=t||e.length,o=new Array(s*2);for(n=0,i=0;i<s;){if(r=e[i++],r<128){o[n++]=r;continue}if(a=Tn[r],a>4){o[n++]=65533,i+=a-1;continue}for(r&=a===2?31:a===3?15:7;a>1&&i<s;)r=r<<6|e[i++]&63,a--;if(a>1){o[n++]=65533;continue}r<65536?o[n++]=r:(r-=65536,o[n++]=55296|r>>10&1023,o[n++]=56320|r&1023)}return Ku(o,n)};Ri.utf8border=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+Tn[e[i]]>t?i:t}});var yo=I((zw,Xu)=>{"use strict";function bv(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}Xu.exports=bv});var ep=I(Pn=>{"use strict";var Ln=Wu(),Rn=st(),wo=vo(),_o=Wr(),mv=yo(),Qu=Object.prototype.toString,vv=0,xo=4,Pi=0,Zu=1,Ju=2,yv=-1,xv=0,wv=8;function Yt(e){if(!(this instanceof Yt))return new Yt(e);this.options=Rn.assign({level:yv,method:wv,chunkSize:16384,windowBits:15,memLevel:8,strategy:xv,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new mv,this.strm.avail_out=0;var i=Ln.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Pi)throw new Error(_o[i]);if(t.header&&Ln.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(typeof t.dictionary=="string"?n=wo.string2buf(t.dictionary):Qu.call(t.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(t.dictionary):n=t.dictionary,i=Ln.deflateSetDictionary(this.strm,n),i!==Pi)throw new Error(_o[i]);this._dict_set=!0}}Yt.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r,a;if(this.ended)return!1;a=t===~~t?t:t===!0?xo:vv,typeof e=="string"?i.input=wo.string2buf(e):Qu.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new Rn.Buf8(n),i.next_out=0,i.avail_out=n),r=Ln.deflate(i,a),r!==Zu&&r!==Pi)return this.onEnd(r),this.ended=!0,!1;(i.avail_out===0||i.avail_in===0&&(a===xo||a===Ju))&&(this.options.to==="string"?this.onData(wo.buf2binstring(Rn.shrinkBuf(i.output,i.next_out))):this.onData(Rn.shrinkBuf(i.output,i.next_out)))}while((i.avail_in>0||i.avail_out===0)&&r!==Zu);return a===xo?(r=Ln.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===Pi):(a===Ju&&(this.onEnd(Pi),i.avail_out=0),!0)};Yt.prototype.onData=function(e){this.chunks.push(e)};Yt.prototype.onEnd=function(e){e===Pi&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Rn.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Eo(e,t){var i=new Yt(t);if(i.push(e,!0),i.err)throw i.msg||_o[i.err];return i.result}function _v(e,t){return t=t||{},t.raw=!0,Eo(e,t)}function Ev(e,t){return t=t||{},t.gzip=!0,Eo(e,t)}Pn.Deflate=Yt;Pn.deflate=Eo;Pn.deflateRaw=_v;Pn.gzip=Ev});var ip=I((Bw,tp)=>{"use strict";var ea=30,Sv=12;tp.exports=function(t,i){var n,r,a,s,o,c,l,d,u,p,f,b,h,g,m,v,y,x,w,C,k,E,P,M,_;n=t.state,r=t.next_in,M=t.input,a=r+(t.avail_in-5),s=t.next_out,_=t.output,o=s-(i-t.avail_out),c=s+(t.avail_out-257),l=n.dmax,d=n.wsize,u=n.whave,p=n.wnext,f=n.window,b=n.hold,h=n.bits,g=n.lencode,m=n.distcode,v=(1<<n.lenbits)-1,y=(1<<n.distbits)-1;e:do{h<15&&(b+=M[r++]<<h,h+=8,b+=M[r++]<<h,h+=8),x=g[b&v];t:for(;;){if(w=x>>>24,b>>>=w,h-=w,w=x>>>16&255,w===0)_[s++]=x&65535;else if(w&16){C=x&65535,w&=15,w&&(h<w&&(b+=M[r++]<<h,h+=8),C+=b&(1<<w)-1,b>>>=w,h-=w),h<15&&(b+=M[r++]<<h,h+=8,b+=M[r++]<<h,h+=8),x=m[b&y];i:for(;;){if(w=x>>>24,b>>>=w,h-=w,w=x>>>16&255,w&16){if(k=x&65535,w&=15,h<w&&(b+=M[r++]<<h,h+=8,h<w&&(b+=M[r++]<<h,h+=8)),k+=b&(1<<w)-1,k>l){t.msg="invalid distance too far back",n.mode=ea;break e}if(b>>>=w,h-=w,w=s-o,k>w){if(w=k-w,w>u&&n.sane){t.msg="invalid distance too far back",n.mode=ea;break e}if(E=0,P=f,p===0){if(E+=d-w,w<C){C-=w;do _[s++]=f[E++];while(--w);E=s-k,P=_}}else if(p<w){if(E+=d+p-w,w-=p,w<C){C-=w;do _[s++]=f[E++];while(--w);if(E=0,p<C){w=p,C-=w;do _[s++]=f[E++];while(--w);E=s-k,P=_}}}else if(E+=p-w,w<C){C-=w;do _[s++]=f[E++];while(--w);E=s-k,P=_}for(;C>2;)_[s++]=P[E++],_[s++]=P[E++],_[s++]=P[E++],C-=3;C&&(_[s++]=P[E++],C>1&&(_[s++]=P[E++]))}else{E=s-k;do _[s++]=_[E++],_[s++]=_[E++],_[s++]=_[E++],C-=3;while(C>2);C&&(_[s++]=_[E++],C>1&&(_[s++]=_[E++]))}}else if((w&64)===0){x=m[(x&65535)+(b&(1<<w)-1)];continue i}else{t.msg="invalid distance code",n.mode=ea;break e}break}}else if((w&64)===0){x=g[(x&65535)+(b&(1<<w)-1)];continue t}else if(w&32){n.mode=Sv;break e}else{t.msg="invalid literal/length code",n.mode=ea;break e}break}}while(r<a&&s<c);C=h>>3,r-=C,h-=C<<3,b&=(1<<h)-1,t.next_in=r,t.next_out=s,t.avail_in=r<a?5+(a-r):5-(r-a),t.avail_out=s<c?257+(c-s):257-(s-c),n.hold=b,n.bits=h}});var cp=I((Fw,lp)=>{"use strict";var np=st(),Ii=15,rp=852,ap=592,sp=0,So=1,op=2,Av=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Cv=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],kv=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Tv=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];lp.exports=function(t,i,n,r,a,s,o,c){var l=c.bits,d=0,u=0,p=0,f=0,b=0,h=0,g=0,m=0,v=0,y=0,x,w,C,k,E,P=null,M=0,_,S=new np.Buf16(Ii+1),L=new np.Buf16(Ii+1),R=null,O=0,A,z,T;for(d=0;d<=Ii;d++)S[d]=0;for(u=0;u<r;u++)S[i[n+u]]++;for(b=l,f=Ii;f>=1&&S[f]===0;f--);if(b>f&&(b=f),f===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,c.bits=1,0;for(p=1;p<f&&S[p]===0;p++);for(b<p&&(b=p),m=1,d=1;d<=Ii;d++)if(m<<=1,m-=S[d],m<0)return-1;if(m>0&&(t===sp||f!==1))return-1;for(L[1]=0,d=1;d<Ii;d++)L[d+1]=L[d]+S[d];for(u=0;u<r;u++)i[n+u]!==0&&(o[L[i[n+u]]++]=u);if(t===sp?(P=R=o,_=19):t===So?(P=Av,M-=257,R=Cv,O-=257,_=256):(P=kv,R=Tv,_=-1),y=0,u=0,d=p,E=s,h=b,g=0,C=-1,v=1<<b,k=v-1,t===So&&v>rp||t===op&&v>ap)return 1;for(;;){A=d-g,o[u]<_?(z=0,T=o[u]):o[u]>_?(z=R[O+o[u]],T=P[M+o[u]]):(z=96,T=0),x=1<<d-g,w=1<<h,p=w;do w-=x,a[E+(y>>g)+w]=A<<24|z<<16|T|0;while(w!==0);for(x=1<<d-1;y&x;)x>>=1;if(x!==0?(y&=x-1,y+=x):y=0,u++,--S[d]===0){if(d===f)break;d=i[n+o[u]]}if(d>b&&(y&k)!==C){for(g===0&&(g=b),E+=p,h=d-g,m=1<<h;h+g<f&&(m-=S[h+g],!(m<=0));)h++,m<<=1;if(v+=1<<h,t===So&&v>rp||t===op&&v>ap)return 1;C=y&k,a[C]=b<<24|h<<16|E-s|0}}return y!==0&&(a[E+y]=d-g<<24|64<<16|0),c.bits=b,0}});var qp=I(Oe=>{"use strict";var xe=st(),Ro=po(),Ve=fo(),Lv=ip(),In=cp(),Rv=0,Dp=1,zp=2,dp=4,Pv=5,ta=6,Vt=0,Iv=1,Mv=2,Ce=-2,jp=-3,Po=-4,Ov=-5,up=8,Bp=1,pp=2,fp=3,hp=4,gp=5,bp=6,mp=7,vp=8,yp=9,xp=10,ra=11,ct=12,Ao=13,wp=14,Co=15,_p=16,Ep=17,Sp=18,Ap=19,ia=20,na=21,Cp=22,kp=23,Tp=24,Lp=25,Rp=26,ko=27,Pp=28,Ip=29,W=30,Io=31,Dv=32,zv=852,jv=592,Bv=15,Fv=Bv;function Mp(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Nv(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new xe.Buf16(320),this.work=new xe.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Fp(e){var t;return!e||!e.state?Ce:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Bp,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new xe.Buf32(zv),t.distcode=t.distdyn=new xe.Buf32(jv),t.sane=1,t.back=-1,Vt)}function Np(e){var t;return!e||!e.state?Ce:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,Fp(e))}function Hp(e,t){var i,n;return!e||!e.state||(n=e.state,t<0?(i=0,t=-t):(i=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Ce:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,Np(e))}function Up(e,t){var i,n;return e?(n=new Nv,e.state=n,n.window=null,i=Hp(e,t),i!==Vt&&(e.state=null),i):Ce}function Hv(e){return Up(e,Fv)}var Op=!0,To,Lo;function Uv(e){if(Op){var t;for(To=new xe.Buf32(512),Lo=new xe.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(In(Dp,e.lens,0,288,To,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;In(zp,e.lens,0,32,Lo,0,e.work,{bits:5}),Op=!1}e.lencode=To,e.lenbits=9,e.distcode=Lo,e.distbits=5}function $p(e,t,i,n){var r,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new xe.Buf8(a.wsize)),n>=a.wsize?(xe.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(r=a.wsize-a.wnext,r>n&&(r=n),xe.arraySet(a.window,t,i-n,r,a.wnext),n-=r,n?(xe.arraySet(a.window,t,i-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=r))),0}function $v(e,t){var i,n,r,a,s,o,c,l,d,u,p,f,b,h,g=0,m,v,y,x,w,C,k,E,P=new xe.Buf8(4),M,_,S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Ce;i=e.state,i.mode===ct&&(i.mode=Ao),s=e.next_out,r=e.output,c=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,l=i.hold,d=i.bits,u=o,p=c,E=Vt;e:for(;;)switch(i.mode){case Bp:if(i.wrap===0){i.mode=Ao;break}for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.wrap&2&&l===35615){i.check=0,P[0]=l&255,P[1]=l>>>8&255,i.check=Ve(i.check,P,2,0),l=0,d=0,i.mode=pp;break}if(i.flags=0,i.head&&(i.head.done=!1),!(i.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=W;break}if((l&15)!==up){e.msg="unknown compression method",i.mode=W;break}if(l>>>=4,d-=4,k=(l&15)+8,i.wbits===0)i.wbits=k;else if(k>i.wbits){e.msg="invalid window size",i.mode=W;break}i.dmax=1<<k,e.adler=i.check=1,i.mode=l&512?xp:ct,l=0,d=0;break;case pp:for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.flags=l,(i.flags&255)!==up){e.msg="unknown compression method",i.mode=W;break}if(i.flags&57344){e.msg="unknown header flags set",i.mode=W;break}i.head&&(i.head.text=l>>8&1),i.flags&512&&(P[0]=l&255,P[1]=l>>>8&255,i.check=Ve(i.check,P,2,0)),l=0,d=0,i.mode=fp;case fp:for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.head&&(i.head.time=l),i.flags&512&&(P[0]=l&255,P[1]=l>>>8&255,P[2]=l>>>16&255,P[3]=l>>>24&255,i.check=Ve(i.check,P,4,0)),l=0,d=0,i.mode=hp;case hp:for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.head&&(i.head.xflags=l&255,i.head.os=l>>8),i.flags&512&&(P[0]=l&255,P[1]=l>>>8&255,i.check=Ve(i.check,P,2,0)),l=0,d=0,i.mode=gp;case gp:if(i.flags&1024){for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.length=l,i.head&&(i.head.extra_len=l),i.flags&512&&(P[0]=l&255,P[1]=l>>>8&255,i.check=Ve(i.check,P,2,0)),l=0,d=0}else i.head&&(i.head.extra=null);i.mode=bp;case bp:if(i.flags&1024&&(f=i.length,f>o&&(f=o),f&&(i.head&&(k=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),xe.arraySet(i.head.extra,n,a,f,k)),i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,i.length-=f),i.length))break e;i.length=0,i.mode=mp;case mp:if(i.flags&2048){if(o===0)break e;f=0;do k=n[a+f++],i.head&&k&&i.length<65536&&(i.head.name+=String.fromCharCode(k));while(k&&f<o);if(i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,k)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=vp;case vp:if(i.flags&4096){if(o===0)break e;f=0;do k=n[a+f++],i.head&&k&&i.length<65536&&(i.head.comment+=String.fromCharCode(k));while(k&&f<o);if(i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,k)break e}else i.head&&(i.head.comment=null);i.mode=yp;case yp:if(i.flags&512){for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l!==(i.check&65535)){e.msg="header crc mismatch",i.mode=W;break}l=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ct;break;case xp:for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}e.adler=i.check=Mp(l),l=0,d=0,i.mode=ra;case ra:if(i.havedict===0)return e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,Mv;e.adler=i.check=1,i.mode=ct;case ct:if(t===Pv||t===ta)break e;case Ao:if(i.last){l>>>=d&7,d-=d&7,i.mode=ko;break}for(;d<3;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}switch(i.last=l&1,l>>>=1,d-=1,l&3){case 0:i.mode=wp;break;case 1:if(Uv(i),i.mode=ia,t===ta){l>>>=2,d-=2;break e}break;case 2:i.mode=Ep;break;case 3:e.msg="invalid block type",i.mode=W}l>>>=2,d-=2;break;case wp:for(l>>>=d&7,d-=d&7;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if((l&65535)!==(l>>>16^65535)){e.msg="invalid stored block lengths",i.mode=W;break}if(i.length=l&65535,l=0,d=0,i.mode=Co,t===ta)break e;case Co:i.mode=_p;case _p:if(f=i.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;xe.arraySet(r,n,a,f,s),o-=f,a+=f,c-=f,s+=f,i.length-=f;break}i.mode=ct;break;case Ep:for(;d<14;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.nlen=(l&31)+257,l>>>=5,d-=5,i.ndist=(l&31)+1,l>>>=5,d-=5,i.ncode=(l&15)+4,l>>>=4,d-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=W;break}i.have=0,i.mode=Sp;case Sp:for(;i.have<i.ncode;){for(;d<3;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.lens[S[i.have++]]=l&7,l>>>=3,d-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,M={bits:i.lenbits},E=In(Rv,i.lens,0,19,i.lencode,0,i.work,M),i.lenbits=M.bits,E){e.msg="invalid code lengths set",i.mode=W;break}i.have=0,i.mode=Ap;case Ap:for(;i.have<i.nlen+i.ndist;){for(;g=i.lencode[l&(1<<i.lenbits)-1],m=g>>>24,v=g>>>16&255,y=g&65535,!(m<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(y<16)l>>>=m,d-=m,i.lens[i.have++]=y;else{if(y===16){for(_=m+2;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l>>>=m,d-=m,i.have===0){e.msg="invalid bit length repeat",i.mode=W;break}k=i.lens[i.have-1],f=3+(l&3),l>>>=2,d-=2}else if(y===17){for(_=m+3;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=m,d-=m,k=0,f=3+(l&7),l>>>=3,d-=3}else{for(_=m+7;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=m,d-=m,k=0,f=11+(l&127),l>>>=7,d-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=W;break}for(;f--;)i.lens[i.have++]=k}}if(i.mode===W)break;if(i.lens[256]===0){e.msg="invalid code -- missing end-of-block",i.mode=W;break}if(i.lenbits=9,M={bits:i.lenbits},E=In(Dp,i.lens,0,i.nlen,i.lencode,0,i.work,M),i.lenbits=M.bits,E){e.msg="invalid literal/lengths set",i.mode=W;break}if(i.distbits=6,i.distcode=i.distdyn,M={bits:i.distbits},E=In(zp,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,M),i.distbits=M.bits,E){e.msg="invalid distances set",i.mode=W;break}if(i.mode=ia,t===ta)break e;case ia:i.mode=na;case na:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,Lv(e,p),s=e.next_out,r=e.output,c=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,l=i.hold,d=i.bits,i.mode===ct&&(i.back=-1);break}for(i.back=0;g=i.lencode[l&(1<<i.lenbits)-1],m=g>>>24,v=g>>>16&255,y=g&65535,!(m<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(v&&(v&240)===0){for(x=m,w=v,C=y;g=i.lencode[C+((l&(1<<x+w)-1)>>x)],m=g>>>24,v=g>>>16&255,y=g&65535,!(x+m<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=x,d-=x,i.back+=x}if(l>>>=m,d-=m,i.back+=m,i.length=y,v===0){i.mode=Rp;break}if(v&32){i.back=-1,i.mode=ct;break}if(v&64){e.msg="invalid literal/length code",i.mode=W;break}i.extra=v&15,i.mode=Cp;case Cp:if(i.extra){for(_=i.extra;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.length+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=kp;case kp:for(;g=i.distcode[l&(1<<i.distbits)-1],m=g>>>24,v=g>>>16&255,y=g&65535,!(m<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if((v&240)===0){for(x=m,w=v,C=y;g=i.distcode[C+((l&(1<<x+w)-1)>>x)],m=g>>>24,v=g>>>16&255,y=g&65535,!(x+m<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=x,d-=x,i.back+=x}if(l>>>=m,d-=m,i.back+=m,v&64){e.msg="invalid distance code",i.mode=W;break}i.offset=y,i.extra=v&15,i.mode=Tp;case Tp:if(i.extra){for(_=i.extra;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.offset+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=W;break}i.mode=Lp;case Lp:if(c===0)break e;if(f=p-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=W;break}f>i.wnext?(f-=i.wnext,b=i.wsize-f):b=i.wnext-f,f>i.length&&(f=i.length),h=i.window}else h=r,b=s-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do r[s++]=h[b++];while(--f);i.length===0&&(i.mode=na);break;case Rp:if(c===0)break e;r[s++]=i.length,c--,i.mode=na;break;case ko:if(i.wrap){for(;d<32;){if(o===0)break e;o--,l|=n[a++]<<d,d+=8}if(p-=c,e.total_out+=p,i.total+=p,p&&(e.adler=i.check=i.flags?Ve(i.check,r,p,s-p):Ro(i.check,r,p,s-p)),p=c,(i.flags?l:Mp(l))!==i.check){e.msg="incorrect data check",i.mode=W;break}l=0,d=0}i.mode=Pp;case Pp:if(i.wrap&&i.flags){for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l!==(i.total&4294967295)){e.msg="incorrect length check",i.mode=W;break}l=0,d=0}i.mode=Ip;case Ip:E=Iv;break e;case W:E=jp;break e;case Io:return Po;case Dv:default:return Ce}return e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,(i.wsize||p!==e.avail_out&&i.mode<W&&(i.mode<ko||t!==dp))&&$p(e,e.output,e.next_out,p-e.avail_out)?(i.mode=Io,Po):(u-=e.avail_in,p-=e.avail_out,e.total_in+=u,e.total_out+=p,i.total+=p,i.wrap&&p&&(e.adler=i.check=i.flags?Ve(i.check,r,p,e.next_out-p):Ro(i.check,r,p,e.next_out-p)),e.data_type=i.bits+(i.last?64:0)+(i.mode===ct?128:0)+(i.mode===ia||i.mode===Co?256:0),(u===0&&p===0||t===dp)&&E===Vt&&(E=Ov),E)}function qv(e){if(!e||!e.state)return Ce;var t=e.state;return t.window&&(t.window=null),e.state=null,Vt}function Gv(e,t){var i;return!e||!e.state||(i=e.state,(i.wrap&2)===0)?Ce:(i.head=t,t.done=!1,Vt)}function Wv(e,t){var i=t.length,n,r,a;return!e||!e.state||(n=e.state,n.wrap!==0&&n.mode!==ra)?Ce:n.mode===ra&&(r=1,r=Ro(r,t,i,0),r!==n.check)?jp:(a=$p(e,t,i,i),a?(n.mode=Io,Po):(n.havedict=1,Vt))}Oe.inflateReset=Np;Oe.inflateReset2=Hp;Oe.inflateResetKeep=Fp;Oe.inflateInit=Hv;Oe.inflateInit2=Up;Oe.inflate=$v;Oe.inflateEnd=qv;Oe.inflateGetHeader=Gv;Oe.inflateSetDictionary=Wv;Oe.inflateInfo="pako inflate (from Nodeca project)"});var Mo=I((Hw,Gp)=>{"use strict";Gp.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var Yp=I((Uw,Wp)=>{"use strict";function Yv(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}Wp.exports=Yv});var Kp=I(On=>{"use strict";var Mi=qp(),Mn=st(),aa=vo(),J=Mo(),Oo=Wr(),Vv=yo(),Kv=Yp(),Vp=Object.prototype.toString;function Kt(e){if(!(this instanceof Kt))return new Kt(e);this.options=Mn.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Vv,this.strm.avail_out=0;var i=Mi.inflateInit2(this.strm,t.windowBits);if(i!==J.Z_OK)throw new Error(Oo[i]);if(this.header=new Kv,Mi.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=aa.string2buf(t.dictionary):Vp.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Mi.inflateSetDictionary(this.strm,t.dictionary),i!==J.Z_OK)))throw new Error(Oo[i])}Kt.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r=this.options.dictionary,a,s,o,c,l,d=!1;if(this.ended)return!1;s=t===~~t?t:t===!0?J.Z_FINISH:J.Z_NO_FLUSH,typeof e=="string"?i.input=aa.binstring2buf(e):Vp.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new Mn.Buf8(n),i.next_out=0,i.avail_out=n),a=Mi.inflate(i,J.Z_NO_FLUSH),a===J.Z_NEED_DICT&&r&&(a=Mi.inflateSetDictionary(this.strm,r)),a===J.Z_BUF_ERROR&&d===!0&&(a=J.Z_OK,d=!1),a!==J.Z_STREAM_END&&a!==J.Z_OK)return this.onEnd(a),this.ended=!0,!1;i.next_out&&(i.avail_out===0||a===J.Z_STREAM_END||i.avail_in===0&&(s===J.Z_FINISH||s===J.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=aa.utf8border(i.output,i.next_out),c=i.next_out-o,l=aa.buf2string(i.output,o),i.next_out=c,i.avail_out=n-c,c&&Mn.arraySet(i.output,i.output,o,c,0),this.onData(l)):this.onData(Mn.shrinkBuf(i.output,i.next_out))),i.avail_in===0&&i.avail_out===0&&(d=!0)}while((i.avail_in>0||i.avail_out===0)&&a!==J.Z_STREAM_END);return a===J.Z_STREAM_END&&(s=J.Z_FINISH),s===J.Z_FINISH?(a=Mi.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===J.Z_OK):(s===J.Z_SYNC_FLUSH&&(this.onEnd(J.Z_OK),i.avail_out=0),!0)};Kt.prototype.onData=function(e){this.chunks.push(e)};Kt.prototype.onEnd=function(e){e===J.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Mn.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Do(e,t){var i=new Kt(t);if(i.push(e,!0),i.err)throw i.msg||Oo[i.err];return i.result}function Xv(e,t){return t=t||{},t.raw=!0,Do(e,t)}On.Inflate=Kt;On.inflate=Do;On.inflateRaw=Xv;On.ungzip=Do});var Jp=I((qw,Zp)=>{"use strict";var Zv=st().assign,Jv=ep(),Qv=Kp(),ey=Mo(),Xp={};Zv(Xp,Jv,Qv,ey);Zp.exports=Xp});var ef=I(oa=>{"use strict";var ty=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",iy=Jp(),Qp=Y(),sa=ye(),ny=ty?"uint8array":"array";oa.magic="\b\0";function Xt(e,t){sa.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}Qp.inherits(Xt,sa);Xt.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(Qp.transformTo(ny,e.data),!1)};Xt.prototype.flush=function(){sa.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)};Xt.prototype.cleanUp=function(){sa.prototype.cleanUp.call(this),this._pako=null};Xt.prototype._createPako=function(){this._pako=new iy[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}};oa.compressWorker=function(e){return new Xt("Deflate",e)};oa.uncompressWorker=function(){return new Xt("Inflate",{})}});var jo=I(zo=>{"use strict";var tf=ye();zo.STORE={magic:"\0\0",compressWorker:function(){return new tf("STORE compression")},uncompressWorker:function(){return new tf("STORE decompression")}};zo.DEFLATE=ef()});var Bo=I(Zt=>{"use strict";Zt.LOCAL_FILE_HEADER="PK";Zt.CENTRAL_FILE_HEADER="PK";Zt.CENTRAL_DIRECTORY_END="PK";Zt.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07";Zt.ZIP64_CENTRAL_DIRECTORY_END="PK";Zt.DATA_DESCRIPTOR="PK\x07\b"});var sf=I((Vw,af)=>{"use strict";var Oi=Y(),Di=ye(),Fo=_i(),nf=Hr(),la=Bo(),U=function(e,t){var i="",n;for(n=0;n<t;n++)i+=String.fromCharCode(e&255),e=e>>>8;return i},ry=function(e,t){var i=e;return e||(i=t?16893:33204),(i&65535)<<16},ay=function(e){return(e||0)&63},rf=function(e,t,i,n,r,a){var s=e.file,o=e.compression,c=a!==Fo.utf8encode,l=Oi.transformTo("string",a(s.name)),d=Oi.transformTo("string",Fo.utf8encode(s.name)),u=s.comment,p=Oi.transformTo("string",a(u)),f=Oi.transformTo("string",Fo.utf8encode(u)),b=d.length!==s.name.length,h=f.length!==u.length,g,m,v="",y="",x="",w=s.dir,C=s.date,k={crc32:0,compressedSize:0,uncompressedSize:0};(!t||i)&&(k.crc32=e.crc32,k.compressedSize=e.compressedSize,k.uncompressedSize=e.uncompressedSize);var E=0;t&&(E|=8),!c&&(b||h)&&(E|=2048);var P=0,M=0;w&&(P|=16),r==="UNIX"?(M=798,P|=ry(s.unixPermissions,w)):(M=20,P|=ay(s.dosPermissions,w)),g=C.getUTCHours(),g=g<<6,g=g|C.getUTCMinutes(),g=g<<5,g=g|C.getUTCSeconds()/2,m=C.getUTCFullYear()-1980,m=m<<4,m=m|C.getUTCMonth()+1,m=m<<5,m=m|C.getUTCDate(),b&&(y=U(1,1)+U(nf(l),4)+d,v+="up"+U(y.length,2)+y),h&&(x=U(1,1)+U(nf(p),4)+f,v+="uc"+U(x.length,2)+x);var _="";_+=`
2
- \0`,_+=U(E,2),_+=o.magic,_+=U(g,2),_+=U(m,2),_+=U(k.crc32,4),_+=U(k.compressedSize,4),_+=U(k.uncompressedSize,4),_+=U(l.length,2),_+=U(v.length,2);var S=la.LOCAL_FILE_HEADER+_+l+v,L=la.CENTRAL_FILE_HEADER+U(M,2)+_+U(p.length,2)+"\0\0\0\0"+U(P,4)+U(n,4)+l+v+p;return{fileRecord:S,dirRecord:L}},sy=function(e,t,i,n,r){var a="",s=Oi.transformTo("string",r(n));return a=la.CENTRAL_DIRECTORY_END+"\0\0\0\0"+U(e,2)+U(e,2)+U(t,4)+U(i,4)+U(s.length,2)+s,a},oy=function(e){var t="";return t=la.DATA_DESCRIPTOR+U(e.crc32,4)+U(e.compressedSize,4)+U(e.uncompressedSize,4),t};function De(e,t,i,n){Di.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Oi.inherits(De,Di);De.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,Di.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))};De.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=rf(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0};De.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,i=rf(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(i.dirRecord),t)this.push({data:oy(e),meta:{percent:100}});else for(this.push({data:i.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null};De.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i=this.bytesWritten-e,n=sy(this.dirRecords.length,i,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}})};De.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()};De.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(i){t.error(i)}),this};De.prototype.resume=function(){if(!Di.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};De.prototype.error=function(e){var t=this._sources;if(!Di.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch{}return!0};De.prototype.lock=function(){Di.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()};af.exports=De});var lf=I(of=>{"use strict";var ly=jo(),cy=sf(),dy=function(e,t){var i=e||t,n=ly[i];if(!n)throw new Error(i+" is not a valid compression method !");return n};of.generateWorker=function(e,t,i){var n=new cy(t.streamFiles,i,t.platform,t.encodeFileName),r=0;try{e.forEach(function(a,s){r++;var o=dy(s.options.compression,t.compression),c=s.options.compressionOptions||t.compressionOptions||{},l=s.dir,d=s.date;s._compressWorker(o,c).withStreamInfo("file",{name:a,dir:l,date:d,comment:s.comment||"",unixPermissions:s.unixPermissions,dosPermissions:s.dosPermissions}).pipe(n)}),n.entriesCount=r}catch(a){n.error(a)}return n}});var df=I((Xw,cf)=>{"use strict";var uy=Y(),ca=ye();function Dn(e,t){ca.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}uy.inherits(Dn,ca);Dn.prototype._bindStream=function(e){var t=this;this._stream=e,e.pause(),e.on("data",function(i){t.push({data:i,meta:{percent:0}})}).on("error",function(i){t.isPaused?this.generatedError=i:t.error(i)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})};Dn.prototype.pause=function(){return ca.prototype.pause.call(this)?(this._stream.pause(),!0):!1};Dn.prototype.resume=function(){return ca.prototype.resume.call(this)?(this._upstreamEnded?this.end():this._stream.resume(),!0):!1};cf.exports=Dn});var xf=I((Zw,yf)=>{"use strict";var py=_i(),zn=Y(),hf=ye(),fy=$s(),gf=qs(),uf=Ur(),hy=uu(),gy=lf(),pf=un(),by=df(),bf=function(e,t,i){var n=zn.getTypeOf(t),r,a=zn.extend(i||{},gf);a.date=a.date||new Date,a.compression!==null&&(a.compression=a.compression.toUpperCase()),typeof a.unixPermissions=="string"&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&a.unixPermissions&16384&&(a.dir=!0),a.dosPermissions&&a.dosPermissions&16&&(a.dir=!0),a.dir&&(e=mf(e)),a.createFolders&&(r=my(e))&&vf.call(this,r,!0);var s=n==="string"&&a.binary===!1&&a.base64===!1;(!i||typeof i.binary=="undefined")&&(a.binary=!s);var o=t instanceof uf&&t.uncompressedSize===0;(o||a.dir||!t||t.length===0)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",n="string");var c=null;t instanceof uf||t instanceof hf?c=t:pf.isNode&&pf.isStream(t)?c=new by(e,t):c=zn.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var l=new hy(e,c,a);this.files[e]=l},my=function(e){e.slice(-1)==="/"&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return t>0?e.substring(0,t):""},mf=function(e){return e.slice(-1)!=="/"&&(e+="/"),e},vf=function(e,t){return t=typeof t!="undefined"?t:gf.createFolders,e=mf(e),this.files[e]||bf.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function ff(e){return Object.prototype.toString.call(e)==="[object RegExp]"}var vy={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],i=t.slice(this.root.length,t.length),i&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(arguments.length===1)if(ff(e)){var n=e;return this.filter(function(a,s){return!s.dir&&n.test(a)})}else{var r=this.files[this.root+e];return r&&!r.dir?r:null}else e=this.root+e,bf.call(this,e,t,i);return this},folder:function(e){if(!e)return this;if(ff(e))return this.filter(function(r,a){return a.dir&&e.test(r)});var t=this.root+e,i=vf.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||(e.slice(-1)!=="/"&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(r,a){return a.name.slice(0,e.length)===e}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if(i=zn.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:py.utf8encode}),i.type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),i.type==="binarystring"&&(i.type="string"),!i.type)throw new Error("No output type specified.");zn.checkSupport(i.type),(i.platform==="darwin"||i.platform==="freebsd"||i.platform==="linux"||i.platform==="sunos")&&(i.platform="UNIX"),i.platform==="win32"&&(i.platform="DOS");var n=i.comment||this.comment||"";t=gy.generateWorker(this,i,n)}catch(r){t=new hf("error"),t.error(r)}return new fy(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return e=e||{},e.type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};yf.exports=vy});var No=I((Jw,_f)=>{"use strict";var yy=Y();function wf(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}wf.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t=0,i;for(this.checkOffset(e),i=this.index+e-1;i>=this.index;i--)t=(t<<8)+this.byteAt(i);return this.index+=e,t},readString:function(e){return yy.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC((e>>25&127)+1980,(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(e&31)<<1))}};_f.exports=wf});var Ho=I((Qw,Sf)=>{"use strict";var Ef=No(),xy=Y();function zi(e){Ef.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=e[t]&255}xy.inherits(zi,Ef);zi.prototype.byteAt=function(e){return this.data[this.zero+e]};zi.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.length-4;a>=0;--a)if(this.data[a]===t&&this.data[a+1]===i&&this.data[a+2]===n&&this.data[a+3]===r)return a-this.zero;return-1};zi.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.readData(4);return t===a[0]&&i===a[1]&&n===a[2]&&r===a[3]};zi.prototype.readData=function(e){if(this.checkOffset(e),e===0)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Sf.exports=zi});var kf=I((e1,Cf)=>{"use strict";var Af=No(),wy=Y();function ji(e){Af.call(this,e)}wy.inherits(ji,Af);ji.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)};ji.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero};ji.prototype.readAndCheckSignature=function(e){var t=this.readData(4);return e===t};ji.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Cf.exports=ji});var $o=I((t1,Lf)=>{"use strict";var Tf=Ho(),_y=Y();function Uo(e){Tf.call(this,e)}_y.inherits(Uo,Tf);Uo.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Lf.exports=Uo});var If=I((i1,Pf)=>{"use strict";var Rf=$o(),Ey=Y();function qo(e){Rf.call(this,e)}Ey.inherits(qo,Rf);qo.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Pf.exports=qo});var Go=I((n1,Of)=>{"use strict";var da=Y(),Mf=rt(),Sy=Ho(),Ay=kf(),Cy=If(),ky=$o();Of.exports=function(e){var t=da.getTypeOf(e);return da.checkSupport(t),t==="string"&&!Mf.uint8array?new Ay(e):t==="nodebuffer"?new Cy(e):Mf.uint8array?new ky(da.transformTo("uint8array",e)):new Sy(da.transformTo("array",e))}});var Bf=I((r1,jf)=>{"use strict";var Wo=Go(),Rt=Y(),Ty=Ur(),Df=Hr(),ua=_i(),pa=jo(),Ly=rt(),Ry=0,Py=3,Iy=function(e){for(var t in pa)if(Object.prototype.hasOwnProperty.call(pa,t)&&pa[t].magic===e)return pa[t];return null};function zf(e,t){this.options=e,this.loadOptions=t}zf.prototype={isEncrypted:function(){return(this.bitFlag&1)===1},useUTF8:function(){return(this.bitFlag&2048)===2048},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(t=Iy(this.compressionMethod),t===null)throw new Error("Corrupted zip : compression "+Rt.pretty(this.compressionMethod)+" unknown (inner file : "+Rt.transformTo("string",this.fileName)+")");this.decompressed=new Ty(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(this.externalFileAttributes&16),e===Ry&&(this.dosPermissions=this.externalFileAttributes&63),e===Py&&(this.unixPermissions=this.externalFileAttributes>>16&65535),!this.dir&&this.fileNameStr.slice(-1)==="/"&&(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=Wo(this.extraFields[1].value);this.uncompressedSize===Rt.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===Rt.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===Rt.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===Rt.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t=e.index+this.extraFieldsLength,i,n,r;for(this.extraFields||(this.extraFields={});e.index+4<t;)i=e.readInt(2),n=e.readInt(2),r=e.readData(n),this.extraFields[i]={id:i,length:n,value:r};e.setIndex(t)},handleUTF8:function(){var e=Ly.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=ua.utf8decode(this.fileName),this.fileCommentStr=ua.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(t!==null)this.fileNameStr=t;else{var i=Rt.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(n!==null)this.fileCommentStr=n;else{var r=Rt.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=Wo(e.value);return t.readInt(1)!==1||Df(this.fileName)!==t.readInt(4)?null:ua.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=Wo(e.value);return t.readInt(1)!==1||Df(this.fileComment)!==t.readInt(4)?null:ua.utf8decode(t.readData(e.length-5))}return null}};jf.exports=zf});var Hf=I((a1,Nf)=>{"use strict";var My=Go(),dt=Y(),ze=Bo(),Oy=Bf(),Dy=rt();function Ff(e){this.files=[],this.loadOptions=e}Ff.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+dt.pretty(t)+", expected "+dt.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4),r=n===t;return this.reader.setIndex(i),r},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=Dy.uint8array?"uint8array":"array",i=dt.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e=this.zip64EndOfCentralSize-44,t=0,i,n,r;t<e;)i=this.reader.readInt(2),n=this.reader.readInt(4),r=this.reader.readData(n),this.zip64ExtensibleData[i]={id:i,length:n,value:r}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(ze.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(ze.CENTRAL_FILE_HEADER);)e=new Oy({zip64:this.zip64},this.loadOptions),e.readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(ze.CENTRAL_DIRECTORY_END);if(e<0){var t=!this.isSignature(0,ze.LOCAL_FILE_HEADER);throw t?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(e);var i=e;if(this.checkSignature(ze.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===dt.MAX_VALUE_16BITS||this.diskWithCentralDirStart===dt.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===dt.MAX_VALUE_16BITS||this.centralDirRecords===dt.MAX_VALUE_16BITS||this.centralDirSize===dt.MAX_VALUE_32BITS||this.centralDirOffset===dt.MAX_VALUE_32BITS){if(this.zip64=!0,e=this.reader.lastIndexOfSignature(ze.ZIP64_CENTRAL_DIRECTORY_LOCATOR),e<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(ze.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,ze.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(ze.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(ze.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var r=i-n;if(r>0)this.isSignature(i,ze.CENTRAL_FILE_HEADER)||(this.reader.zero=r);else if(r<0)throw new Error("Corrupted zip: missing "+Math.abs(r)+" bytes.")},prepareReader:function(e){this.reader=My(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}};Nf.exports=Ff});var qf=I((s1,$f)=>{"use strict";var Yo=Y(),fa=yi(),zy=_i(),jy=Hf(),By=Ys(),Uf=un();function Fy(e){return new fa.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new By);n.on("error",function(r){i(r)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}$f.exports=function(e,t){var i=this;return t=Yo.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:zy.utf8decode}),Uf.isNode&&Uf.isStream(e)?fa.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):Yo.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(n){var r=new jy(t);return r.load(n),r}).then(function(r){var a=[fa.Promise.resolve(r)],s=r.files;if(t.checkCRC32)for(var o=0;o<s.length;o++)a.push(Fy(s[o]));return fa.Promise.all(a)}).then(function(r){for(var a=r.shift(),s=a.files,o=0;o<s.length;o++){var c=s[o],l=c.fileNameStr,d=Yo.resolve(c.fileNameStr);i.file(d,c.decompressed,{binary:!0,optimizedBinaryString:!0,date:c.date,dir:c.dir,comment:c.fileCommentStr.length?c.fileCommentStr:null,unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions,createFolders:t.createFolders}),c.dir||(i.file(d).unsafeOriginalName=l)}return a.zipComment.length&&(i.comment=a.zipComment),i})}});var Wf=I((o1,Gf)=>{"use strict";function ke(){if(!(this instanceof ke))return new ke;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new ke;for(var t in this)typeof this[t]!="function"&&(e[t]=this[t]);return e}}ke.prototype=xf();ke.prototype.loadAsync=qf();ke.support=rt();ke.defaults=qs();ke.version="3.10.1";ke.loadAsync=function(e,t){return new ke().loadAsync(e,t)};ke.external=yi();Gf.exports=ke});import{Application as wx}from"pixi.js";var yt={};function or(e,t,i=!1){yt[e]||(yt[e]=[]),yt[e].push({fn:t,once:i})}function Za(e,t){if(yt[e]){if(!t){delete yt[e];return}yt[e]=yt[e].filter(i=>i.fn!==t)}}function lr(e,...t){let i=yt[e];if(i)for(let n of[...i])n.fn(...t),n.once&&Za(e,n.fn)}function _e(e,t){or(e,t,!0)}var te=null,Pe=[],si=null;function dc(e){te=e,Pe=[],si!==null&&(clearTimeout(si),si=null)}function uc(){var e,t,i;return{endpoint:(te==null?void 0:te.endpoint)||"",transport:(te==null?void 0:te.transport)||"beacon",batchSize:(e=te==null?void 0:te.batchSize)!=null?e:10,flushIntervalMs:(t=te==null?void 0:te.flushIntervalMs)!=null?t:300,maxQueue:(i=te==null?void 0:te.maxQueue)!=null?i:200,debug:!!(te!=null&&te.debug)}}async function lc(e,t,i,n){let r=JSON.stringify(t);if(i==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(e,new Blob([r],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,t);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",t)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function Ja(e,t){let i=uc();if(t&&i.endpoint){if(Pe.push(e),Pe.length>i.maxQueue&&(Pe=Pe.slice(Pe.length-i.maxQueue)),Pe.length>=i.batchSize){cc();return}si===null&&(si=window.setTimeout(()=>{si=null,cc()},i.flushIntervalMs))}}async function cc(){let e=uc();if(!e.endpoint||Pe.length===0)return;let t=Pe.splice(0,e.batchSize);await lc(e.endpoint,{events:t},e.transport,e.debug),Pe.length>0&&await lc(e.endpoint,{events:Pe.splice(0,e.batchSize)},e.transport,e.debug)}var Ee=0,ag=Ee++,pc=Ee++,fc=Ee++,hc=Ee++,gc=Ee++,bc=Ee++,mc=Ee++,vc=Ee++,yc=Ee++,xc=Ee++,wc=Ee++,_c=Ee++,K=ag;function Ec(){return K===pc}function Sc(){return K===fc}function Ac(){return K===hc}function Cc(){return K===gc}function oi(){return K===bc}function li(){return K===mc}function kc(){return K===vc}function Tc(){return K===yc}function Lc(){return K===xc}function Qa(){return K===wc}function es(){return K===_c}function Rc(){let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",t=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(e==="mraid")try{mraid.getState(),K=pc;return}catch{}else if(e==="dapi")try{dapi.isReady(),K=fc;return}catch{}if(t==="facebook")try{typeof FbPlayableAd!="undefined"&&(K=hc)}catch{}else if(t==="google")try{typeof ExitApi!="undefined"&&(K=gc)}catch{}else if(t==="mintegral")window.gameReady&&(K=bc);else if(t==="tapjoy")window.TJ_API&&(K=mc);else if(t==="tiktok")window.openAppStore&&(K=vc);else if(t==="smadex")try{window.smxTracking&&(K=yc)}catch{}else if(t==="snapchat")try{window.ScPlayableAd&&(K=xc)}catch{}else t==="vungle"?K=wc:(e==="nucleo"||t==="nucleo")&&(K=_c)}import ts from"lottie-web";var Pc=ts;typeof window!="undefined"&&(window.lottie=ts,window.__baseLottie=ts);function ie(e,t){let i=(r,a)=>a===0?r:i(a,r%a),n=i(e,t);return`${e/n}:${t/n}`}var p0=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ie(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ie(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ie(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ie(360,780)}],f0=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ie(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ie(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ie(412,915)}],h0=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ie(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ie(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ie(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ie(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ie(800,1280)}],is=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:ie(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ie(768,1024),mraidScale:.7}];var Ic=[...is],Mc=[{category:"playable",label:"Playable Ad",devices:is}],ns=is[0];function ci(e){return Ic.find(t=>t.id===e)||ns}function g0(e){return Ic.filter(t=>t.category===e)}var cr=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
1
+ import{c as Va,d as He,e as Ka}from"./chunk-I5OOVR5U.js";import{i as or}from"./chunk-LV4HGC5G.js";import{c as en,d as sr,g as sc,h as Xa,j as Za,l as oc,m as lc,n as Ja,o as cc}from"./chunk-ZLL42OOV.js";import{a as Ne,b as P,c as pg}from"./chunk-Q7FPWOA3.js";var nn=P((cw,ss)=>{"use strict";typeof process=="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?ss.exports={nextTick:vg}:ss.exports=process;function vg(e,t,i,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var r=arguments.length,a,s;switch(r){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t)});case 3:return process.nextTick(function(){e.call(null,t,i)});case 4:return process.nextTick(function(){e.call(null,t,i,n)});default:for(a=new Array(r-1),s=0;s<a.length;)a[s++]=arguments[s];return process.nextTick(function(){e.apply(null,a)})}}});var $c=P((dw,Uc)=>{"use strict";var yg={}.toString;Uc.exports=Array.isArray||function(e){return yg.call(e)=="[object Array]"}});var os=P((uw,qc)=>{"use strict";qc.exports=Ne("stream")});var rn=P((ls,Wc)=>{"use strict";var Ar=Ne("buffer"),tt=Ar.Buffer;function Gc(e,t){for(var i in e)t[i]=e[i]}tt.from&&tt.alloc&&tt.allocUnsafe&&tt.allocUnsafeSlow?Wc.exports=Ar:(Gc(Ar,ls),ls.Buffer=ui);function ui(e,t,i){return tt(e,t,i)}Gc(tt,ui);ui.from=function(e,t,i){if(typeof e=="number")throw new TypeError("Argument must not be a number");return tt(e,t,i)};ui.alloc=function(e,t,i){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=tt(e);return t!==void 0?typeof i=="string"?n.fill(t,i):n.fill(t):n.fill(0),n};ui.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return tt(e)};ui.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Ar.SlowBuffer(e)}});var pi=P(le=>{"use strict";function xg(e){return Array.isArray?Array.isArray(e):Cr(e)==="[object Array]"}le.isArray=xg;function wg(e){return typeof e=="boolean"}le.isBoolean=wg;function _g(e){return e===null}le.isNull=_g;function Eg(e){return e==null}le.isNullOrUndefined=Eg;function Sg(e){return typeof e=="number"}le.isNumber=Sg;function Ag(e){return typeof e=="string"}le.isString=Ag;function Cg(e){return typeof e=="symbol"}le.isSymbol=Cg;function Tg(e){return e===void 0}le.isUndefined=Tg;function kg(e){return Cr(e)==="[object RegExp]"}le.isRegExp=kg;function Lg(e){return typeof e=="object"&&e!==null}le.isObject=Lg;function Rg(e){return Cr(e)==="[object Date]"}le.isDate=Rg;function Mg(e){return Cr(e)==="[object Error]"||e instanceof Error}le.isError=Mg;function Pg(e){return typeof e=="function"}le.isFunction=Pg;function Ig(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e=="undefined"}le.isPrimitive=Ig;le.isBuffer=Ne("buffer").Buffer.isBuffer;function Cr(e){return Object.prototype.toString.call(e)}});var Yc=P((fw,cs)=>{"use strict";typeof Object.create=="function"?cs.exports=function(t,i){i&&(t.super_=i,t.prototype=Object.create(i.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:cs.exports=function(t,i){if(i){t.super_=i;var n=function(){};n.prototype=i.prototype,t.prototype=new n,t.prototype.constructor=t}}});var fi=P((hw,us)=>{"use strict";try{if(ds=Ne("util"),typeof ds.inherits!="function")throw"";us.exports=ds.inherits}catch{us.exports=Yc()}var ds});var Kc=P((gw,ps)=>{"use strict";function Og(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var Vc=rn().Buffer,an=Ne("util");function Dg(e,t,i){e.copy(t,i)}ps.exports=(function(){function e(){Og(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(i){var n={data:i,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},e.prototype.unshift=function(i){var n={data:i,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},e.prototype.shift=function(){if(this.length!==0){var i=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,i}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(i){if(this.length===0)return"";for(var n=this.head,r=""+n.data;n=n.next;)r+=i+n.data;return r},e.prototype.concat=function(i){if(this.length===0)return Vc.alloc(0);for(var n=Vc.allocUnsafe(i>>>0),r=this.head,a=0;r;)Dg(r.data,n,a),a+=r.data.length,r=r.next;return n},e})();an&&an.inspect&&an.inspect.custom&&(ps.exports.prototype[an.inspect.custom]=function(){var e=an.inspect({length:this.length});return this.constructor.name+" "+e})});var fs=P((mw,Xc)=>{"use strict";var Tr=nn();function zg(e,t){var i=this,n=this._readableState&&this._readableState.destroyed,r=this._writableState&&this._writableState.destroyed;return n||r?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,Tr.nextTick(kr,this,e)):Tr.nextTick(kr,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(a){!t&&a?i._writableState?i._writableState.errorEmitted||(i._writableState.errorEmitted=!0,Tr.nextTick(kr,i,a)):Tr.nextTick(kr,i,a):t&&t(a)}),this)}function jg(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function kr(e,t){e.emit("error",t)}Xc.exports={destroy:zg,undestroy:jg}});var Jc=P((bw,Zc)=>{"use strict";Zc.exports=Ne("util").deprecate});var gs=P((vw,sd)=>{"use strict";var Bt=nn();sd.exports=Q;function ed(e){var t=this;this.next=null,this.entry=null,this.finish=function(){tm(t,e)}}var Bg=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:Bt.nextTick,hi;Q.WritableState=on;var td=Object.create(pi());td.inherits=fi();var Fg={deprecate:Jc()},id=os(),Rr=rn().Buffer,Ng=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function Hg(e){return Rr.from(e)}function Ug(e){return Rr.isBuffer(e)||e instanceof Ng}var nd=fs();td.inherits(Q,id);function $g(){}function on(e,t){hi=hi||Ft(),e=e||{};var i=t instanceof hi;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,r=e.writableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=e.decodeStrings===!1;this.decodeStrings=!s,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(o){Xg(t,o)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new ed(this)}on.prototype.getBuffer=function(){for(var t=this.bufferedRequest,i=[];t;)i.push(t),t=t.next;return i};(function(){try{Object.defineProperty(on.prototype,"buffer",{get:Fg.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var Lr;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Lr=Function.prototype[Symbol.hasInstance],Object.defineProperty(Q,Symbol.hasInstance,{value:function(e){return Lr.call(this,e)?!0:this!==Q?!1:e&&e._writableState instanceof on}})):Lr=function(e){return e instanceof this};function Q(e){if(hi=hi||Ft(),!Lr.call(Q,this)&&!(this instanceof hi))return new Q(e);this._writableState=new on(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),id.call(this)}Q.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function qg(e,t){var i=new Error("write after end");e.emit("error",i),Bt.nextTick(t,i)}function Gg(e,t,i,n){var r=!0,a=!1;return i===null?a=new TypeError("May not write null values to stream"):typeof i!="string"&&i!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),Bt.nextTick(n,a),r=!1),r}Q.prototype.write=function(e,t,i){var n=this._writableState,r=!1,a=!n.objectMode&&Ug(e);return a&&!Rr.isBuffer(e)&&(e=Hg(e)),typeof t=="function"&&(i=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),typeof i!="function"&&(i=$g),n.ended?qg(this,i):(a||Gg(this,n,e,i))&&(n.pendingcb++,r=Yg(this,n,a,e,t,i)),r};Q.prototype.cork=function(){var e=this._writableState;e.corked++};Q.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&rd(this,e))};Q.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function Wg(e,t,i){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Rr.from(t,i)),t}Object.defineProperty(Q.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function Yg(e,t,i,n,r,a){if(!i){var s=Wg(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var o=t.objectMode?1:n.length;t.length+=o;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else hs(e,t,!1,o,n,r,a);return c}function hs(e,t,i,n,r,a,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,i?e._writev(r,t.onwrite):e._write(r,a,t.onwrite),t.sync=!1}function Vg(e,t,i,n,r){--t.pendingcb,i?(Bt.nextTick(r,n),Bt.nextTick(sn,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(r(n),e._writableState.errorEmitted=!0,e.emit("error",n),sn(e,t))}function Kg(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function Xg(e,t){var i=e._writableState,n=i.sync,r=i.writecb;if(Kg(i),t)Vg(e,i,n,t,r);else{var a=ad(i);!a&&!i.corked&&!i.bufferProcessing&&i.bufferedRequest&&rd(e,i),n?Bg(Qc,e,i,a,r):Qc(e,i,a,r)}}function Qc(e,t,i,n){i||Zg(e,t),t.pendingcb--,n(),sn(e,t)}function Zg(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function rd(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,r=new Array(n),a=t.corkedRequestsFree;a.entry=i;for(var s=0,o=!0;i;)r[s]=i,i.isBuf||(o=!1),i=i.next,s+=1;r.allBuffers=o,hs(e,t,!0,t.length,r,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new ed(t),t.bufferedRequestCount=0}else{for(;i;){var c=i.chunk,l=i.encoding,d=i.callback,u=t.objectMode?1:c.length;if(hs(e,t,!1,u,c,l,d),i=i.next,t.bufferedRequestCount--,t.writing)break}i===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}Q.prototype._write=function(e,t,i){i(new Error("_write() is not implemented"))};Q.prototype._writev=null;Q.prototype.end=function(e,t,i){var n=this._writableState;typeof e=="function"?(i=e,e=null,t=null):typeof t=="function"&&(i=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||em(this,n,i)};function ad(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function Jg(e,t){e._final(function(i){t.pendingcb--,i&&e.emit("error",i),t.prefinished=!0,e.emit("prefinish"),sn(e,t)})}function Qg(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=!0,Bt.nextTick(Jg,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function sn(e,t){var i=ad(t);return i&&(Qg(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"))),i}function em(e,t,i){t.ending=!0,sn(e,t),i&&(t.finished?Bt.nextTick(i):e.once("finish",i)),t.ended=!0,e.writable=!1}function tm(e,t,i){var n=e.entry;for(e.entry=null;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}Object.defineProperty(Q.prototype,"destroyed",{get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}});Q.prototype.destroy=nd.destroy;Q.prototype._undestroy=nd.undestroy;Q.prototype._destroy=function(e,t){this.end(),t(e)}});var Ft=P((yw,dd)=>{"use strict";var od=nn(),im=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};dd.exports=it;var ld=Object.create(pi());ld.inherits=fi();var cd=vs(),bs=gs();ld.inherits(it,cd);for(ms=im(bs.prototype),Mr=0;Mr<ms.length;Mr++)Pr=ms[Mr],it.prototype[Pr]||(it.prototype[Pr]=bs.prototype[Pr]);var ms,Pr,Mr;function it(e){if(!(this instanceof it))return new it(e);cd.call(this,e),bs.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",nm)}Object.defineProperty(it.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function nm(){this.allowHalfOpen||this._writableState.ended||od.nextTick(rm,this)}function rm(e){e.end()}Object.defineProperty(it.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}});it.prototype._destroy=function(e,t){this.push(null),this.end(),od.nextTick(t,e)}});var ws=P(pd=>{"use strict";var xs=rn().Buffer,ud=xs.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function am(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function sm(e){var t=am(e);if(typeof t!="string"&&(xs.isEncoding===ud||!ud(e)))throw new Error("Unknown encoding: "+e);return t||e}pd.StringDecoder=ln;function ln(e){this.encoding=sm(e);var t;switch(this.encoding){case"utf16le":this.text=pm,this.end=fm,t=4;break;case"utf8":this.fillLast=cm,t=4;break;case"base64":this.text=hm,this.end=gm,t=3;break;default:this.write=mm,this.end=bm;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=xs.allocUnsafe(t)}ln.prototype.write=function(e){if(e.length===0)return"";var t,i;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""};ln.prototype.end=um;ln.prototype.text=dm;ln.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function ys(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function om(e,t,i){var n=t.length-1;if(n<i)return 0;var r=ys(t[n]);return r>=0?(r>0&&(e.lastNeed=r-1),r):--n<i||r===-2?0:(r=ys(t[n]),r>=0?(r>0&&(e.lastNeed=r-2),r):--n<i||r===-2?0:(r=ys(t[n]),r>=0?(r>0&&(r===2?r=0:e.lastNeed=r-3),r):0))}function lm(e,t,i){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function cm(e){var t=this.lastTotal-this.lastNeed,i=lm(this,e,t);if(i!==void 0)return i;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function dm(e,t){var i=om(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function um(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function pm(e,t){if((e.length-t)%2===0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function fm(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function hm(e,t){var i=(e.length-t)%3;return i===0?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,i===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function gm(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function mm(e){return e.toString(this.encoding)}function bm(e){return e&&e.length?this.write(e):""}});var vs=P((_w,Sd)=>{"use strict";var mi=nn();Sd.exports=G;var vm=$c(),cn;G.ReadableState=yd;var ww=Ne("events").EventEmitter,md=function(e,t){return e.listeners(t).length},Cs=os(),dn=rn().Buffer,ym=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function xm(e){return dn.from(e)}function wm(e){return dn.isBuffer(e)||e instanceof ym}var bd=Object.create(pi());bd.inherits=fi();var _s=Ne("util"),H=void 0;_s&&_s.debuglog?H=_s.debuglog("stream"):H=function(){};var _m=Kc(),vd=fs(),gi;bd.inherits(G,Cs);var Es=["error","close","destroy","pause","resume"];function Em(e,t,i){if(typeof e.prependListener=="function")return e.prependListener(t,i);!e._events||!e._events[t]?e.on(t,i):vm(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]}function yd(e,t){cn=cn||Ft(),e=e||{};var i=t instanceof cn;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,r=e.readableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new _m,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(gi||(gi=ws().StringDecoder),this.decoder=new gi(e.encoding),this.encoding=e.encoding)}function G(e){if(cn=cn||Ft(),!(this instanceof G))return new G(e);this._readableState=new yd(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Cs.call(this)}Object.defineProperty(G.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});G.prototype.destroy=vd.destroy;G.prototype._undestroy=vd.undestroy;G.prototype._destroy=function(e,t){this.push(null),t(e)};G.prototype.push=function(e,t){var i=this._readableState,n;return i.objectMode?n=!0:typeof e=="string"&&(t=t||i.defaultEncoding,t!==i.encoding&&(e=dn.from(e,t),t=""),n=!0),xd(this,e,t,!1,n)};G.prototype.unshift=function(e){return xd(this,e,null,!0,!1)};function xd(e,t,i,n,r){var a=e._readableState;if(t===null)a.reading=!1,Tm(e,a);else{var s;r||(s=Sm(a,t)),s?e.emit("error",s):a.objectMode||t&&t.length>0?(typeof t!="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==dn.prototype&&(t=xm(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):Ss(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!i?(t=a.decoder.write(t),a.objectMode||t.length!==0?Ss(e,a,t,!1):wd(e,a)):Ss(e,a,t,!1))):n||(a.reading=!1)}return Am(a)}function Ss(e,t,i,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",i),e.read(0)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&Ir(e)),wd(e,t)}function Sm(e,t){var i;return!wm(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(i=new TypeError("Invalid non-string/buffer chunk")),i}function Am(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}G.prototype.isPaused=function(){return this._readableState.flowing===!1};G.prototype.setEncoding=function(e){return gi||(gi=ws().StringDecoder),this._readableState.decoder=new gi(e),this._readableState.encoding=e,this};var fd=8388608;function Cm(e){return e>=fd?e=fd:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function hd(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=Cm(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}G.prototype.read=function(e){H("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return H("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?As(this):Ir(this),null;if(e=hd(e,t),e===0&&t.ended)return t.length===0&&As(this),null;var n=t.needReadable;H("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,H("length less than watermark",n)),t.ended||t.reading?(n=!1,H("reading or ended",n)):n&&(H("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=hd(i,t)));var r;return e>0?r=_d(e,t):r=null,r===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&As(this)),r!==null&&this.emit("data",r),r};function Tm(e,t){if(!t.ended){if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,Ir(e)}}function Ir(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(H("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?mi.nextTick(gd,e):gd(e))}function gd(e){H("emit readable"),e.emit("readable"),Ts(e)}function wd(e,t){t.readingMore||(t.readingMore=!0,mi.nextTick(km,e,t))}function km(e,t){for(var i=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(H("maybeReadMore read 0"),e.read(0),i!==t.length);)i=t.length;t.readingMore=!1}G.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))};G.prototype.pipe=function(e,t){var i=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,H("pipe count=%d opts=%j",n.pipesCount,t);var r=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr,a=r?o:g;n.endEmitted?mi.nextTick(a):i.once("end",a),e.on("unpipe",s);function s(v,b){H("onunpipe"),v===i&&b&&b.hasUnpiped===!1&&(b.hasUnpiped=!0,d())}function o(){H("onend"),e.end()}var c=Lm(i);e.on("drain",c);var l=!1;function d(){H("cleanup"),e.removeListener("close",m),e.removeListener("finish",h),e.removeListener("drain",c),e.removeListener("error",f),e.removeListener("unpipe",s),i.removeListener("end",o),i.removeListener("end",g),i.removeListener("data",p),l=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&c()}var u=!1;i.on("data",p);function p(v){H("ondata"),u=!1;var b=e.write(v);b===!1&&!u&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&Ed(n.pipes,e)!==-1)&&!l&&(H("false write response, pause",n.awaitDrain),n.awaitDrain++,u=!0),i.pause())}function f(v){H("onerror",v),g(),e.removeListener("error",f),md(e,"error")===0&&e.emit("error",v)}Em(e,"error",f);function m(){e.removeListener("finish",h),g()}e.once("close",m);function h(){H("onfinish"),e.removeListener("close",m),g()}e.once("finish",h);function g(){H("unpipe"),i.unpipe(e)}return e.emit("pipe",i),n.flowing||(H("pipe resume"),i.resume()),e};function Lm(e){return function(){var t=e._readableState;H("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&md(e,"data")&&(t.flowing=!0,Ts(e))}}G.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<r;a++)n[a].emit("unpipe",this,{hasUnpiped:!1});return this}var s=Ed(t.pipes,e);return s===-1?this:(t.pipes.splice(s,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i),this)};G.prototype.on=function(e,t){var i=Cs.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==!1&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&Ir(this):mi.nextTick(Rm,this))}return i};G.prototype.addListener=G.prototype.on;function Rm(e){H("readable nexttick read 0"),e.read(0)}G.prototype.resume=function(){var e=this._readableState;return e.flowing||(H("resume"),e.flowing=!0,Mm(this,e)),this};function Mm(e,t){t.resumeScheduled||(t.resumeScheduled=!0,mi.nextTick(Pm,e,t))}function Pm(e,t){t.reading||(H("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),Ts(e),t.flowing&&!t.reading&&e.read(0)}G.prototype.pause=function(){return H("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(H("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function Ts(e){var t=e._readableState;for(H("flow",t.flowing);t.flowing&&e.read()!==null;);}G.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;e.on("end",function(){if(H("wrapped end"),i.decoder&&!i.ended){var s=i.decoder.end();s&&s.length&&t.push(s)}t.push(null)}),e.on("data",function(s){if(H("wrapped data"),i.decoder&&(s=i.decoder.write(s)),!(i.objectMode&&s==null)&&!(!i.objectMode&&(!s||!s.length))){var o=t.push(s);o||(n=!0,e.pause())}});for(var r in e)this[r]===void 0&&typeof e[r]=="function"&&(this[r]=(function(s){return function(){return e[s].apply(e,arguments)}})(r));for(var a=0;a<Es.length;a++)e.on(Es[a],this.emit.bind(this,Es[a]));return this._read=function(s){H("wrapped _read",s),n&&(n=!1,e.resume())},this};Object.defineProperty(G.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});G._fromList=_d;function _d(e,t){if(t.length===0)return null;var i;return t.objectMode?i=t.buffer.shift():!e||e>=t.length?(t.decoder?i=t.buffer.join(""):t.buffer.length===1?i=t.buffer.head.data:i=t.buffer.concat(t.length),t.buffer.clear()):i=Im(e,t.buffer,t.decoder),i}function Im(e,t,i){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=i?Om(e,t):Dm(e,t),n}function Om(e,t){var i=t.head,n=1,r=i.data;for(e-=r.length;i=i.next;){var a=i.data,s=e>a.length?a.length:e;if(s===a.length?r+=a:r+=a.slice(0,e),e-=s,e===0){s===a.length?(++n,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=a.slice(s));break}++n}return t.length-=n,r}function Dm(e,t){var i=dn.allocUnsafe(e),n=t.head,r=1;for(n.data.copy(i),e-=n.data.length;n=n.next;){var a=n.data,s=e>a.length?a.length:e;if(a.copy(i,i.length-e,0,s),e-=s,e===0){s===a.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(s));break}++r}return t.length-=r,i}function As(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,mi.nextTick(zm,t,e))}function zm(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function Ed(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}});var ks=P((Ew,Td)=>{"use strict";Td.exports=nt;var Or=Ft(),Cd=Object.create(pi());Cd.inherits=fi();Cd.inherits(nt,Or);function jm(e,t){var i=this._transformState;i.transforming=!1;var n=i.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,t!=null&&this.push(t),n(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}function nt(e){if(!(this instanceof nt))return new nt(e);Or.call(this,e),this._transformState={afterTransform:jm.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",Bm)}function Bm(){var e=this;typeof this._flush=="function"?this._flush(function(t,i){Ad(e,t,i)}):Ad(this,null,null)}nt.prototype.push=function(e,t){return this._transformState.needTransform=!1,Or.prototype.push.call(this,e,t)};nt.prototype._transform=function(e,t,i){throw new Error("_transform() is not implemented")};nt.prototype._write=function(e,t,i){var n=this._transformState;if(n.writecb=i,n.writechunk=e,n.writeencoding=t,!n.transforming){var r=this._readableState;(n.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}};nt.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};nt.prototype._destroy=function(e,t){var i=this;Or.prototype._destroy.call(this,e,function(n){t(n),i.emit("close")})};function Ad(e,t,i){if(t)return e.emit("error",t);if(i!=null&&e.push(i),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var Md=P((Sw,Rd)=>{"use strict";Rd.exports=un;var kd=ks(),Ld=Object.create(pi());Ld.inherits=fi();Ld.inherits(un,kd);function un(e){if(!(this instanceof un))return new un(e);kd.call(this,e)}un.prototype._transform=function(e,t,i){i(null,e)}});var Ls=P((re,Dr)=>{"use strict";var Ue=Ne("stream");process.env.READABLE_STREAM==="disable"&&Ue?(Dr.exports=Ue,re=Dr.exports=Ue.Readable,re.Readable=Ue.Readable,re.Writable=Ue.Writable,re.Duplex=Ue.Duplex,re.Transform=Ue.Transform,re.PassThrough=Ue.PassThrough,re.Stream=Ue):(re=Dr.exports=vs(),re.Stream=Ue||re,re.Readable=re,re.Writable=gs(),re.Duplex=Ft(),re.Transform=ks(),re.PassThrough=Md())});var rt=P(ve=>{"use strict";ve.base64=!0;ve.array=!0;ve.string=!0;ve.arraybuffer=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined";ve.nodebuffer=typeof Buffer!="undefined";ve.uint8array=typeof Uint8Array!="undefined";if(typeof ArrayBuffer=="undefined")ve.blob=!1;else{Rs=new ArrayBuffer(0);try{ve.blob=new Blob([Rs],{type:"application/zip"}).size===0}catch{try{Pd=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,Ms=new Pd,Ms.append(Rs),ve.blob=Ms.getBlob("application/zip").size===0}catch{ve.blob=!1}}}var Rs,Pd,Ms;try{ve.nodestream=!!Ls().Readable}catch{ve.nodestream=!1}});var Is=P(Ps=>{"use strict";var Fm=Y(),Nm=rt(),$e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";Ps.encode=function(e){for(var t=[],i,n,r,a,s,o,c,l=0,d=e.length,u=d,p=Fm.getTypeOf(e)!=="string";l<e.length;)u=d-l,p?(i=e[l++],n=l<d?e[l++]:0,r=l<d?e[l++]:0):(i=e.charCodeAt(l++),n=l<d?e.charCodeAt(l++):0,r=l<d?e.charCodeAt(l++):0),a=i>>2,s=(i&3)<<4|n>>4,o=u>1?(n&15)<<2|r>>6:64,c=u>2?r&63:64,t.push($e.charAt(a)+$e.charAt(s)+$e.charAt(o)+$e.charAt(c));return t.join("")};Ps.decode=function(e){var t,i,n,r,a,s,o,c=0,l=0,d="data:";if(e.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");e=e.replace(/[^A-Za-z0-9+/=]/g,"");var u=e.length*3/4;if(e.charAt(e.length-1)===$e.charAt(64)&&u--,e.charAt(e.length-2)===$e.charAt(64)&&u--,u%1!==0)throw new Error("Invalid base64 input, bad content length.");var p;for(Nm.uint8array?p=new Uint8Array(u|0):p=new Array(u|0);c<e.length;)r=$e.indexOf(e.charAt(c++)),a=$e.indexOf(e.charAt(c++)),s=$e.indexOf(e.charAt(c++)),o=$e.indexOf(e.charAt(c++)),t=r<<2|a>>4,i=(a&15)<<4|s>>2,n=(s&3)<<6|o,p[l++]=t,s!==64&&(p[l++]=i),o!==64&&(p[l++]=n);return p}});var pn=P((Tw,Id)=>{"use strict";Id.exports={isNode:typeof Buffer!="undefined",newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}});var jd=P((kw,zd)=>{"use strict";var Od=global.MutationObserver||global.WebKitMutationObserver,bi;process.browser?Od?(Os=0,Dd=new Od(fn),Ds=global.document.createTextNode(""),Dd.observe(Ds,{characterData:!0}),bi=function(){Ds.data=Os=++Os%2}):!global.setImmediate&&typeof global.MessageChannel!="undefined"?(zs=new global.MessageChannel,zs.port1.onmessage=fn,bi=function(){zs.port2.postMessage(0)}):"document"in global&&"onreadystatechange"in global.document.createElement("script")?bi=function(){var e=global.document.createElement("script");e.onreadystatechange=function(){fn(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},global.document.documentElement.appendChild(e)}:bi=function(){setTimeout(fn,0)}:bi=function(){process.nextTick(fn)};var Os,Dd,Ds,zs,js,hn=[];function fn(){js=!0;for(var e,t,i=hn.length;i;){for(t=hn,hn=[],e=-1;++e<i;)t[e]();i=hn.length}js=!1}zd.exports=Hm;function Hm(e){hn.push(e)===1&&!js&&bi()}});var qd=P((Lw,$d)=>{"use strict";var Bd=jd();function vi(){}var ce={},Fd=["REJECTED"],Bs=["FULFILLED"],Nd=["PENDING"];process.browser||(gn=["UNHANDLED"]);var gn;$d.exports=xt;function xt(e){if(typeof e!="function")throw new TypeError("resolver must be a function");this.state=Nd,this.queue=[],this.outcome=void 0,process.browser||(this.handled=gn),e!==vi&&Hd(this,e)}xt.prototype.finally=function(e){if(typeof e!="function")return this;var t=this.constructor;return this.then(i,n);function i(r){function a(){return r}return t.resolve(e()).then(a)}function n(r){function a(){throw r}return t.resolve(e()).then(a)}};xt.prototype.catch=function(e){return this.then(null,e)};xt.prototype.then=function(e,t){if(typeof e!="function"&&this.state===Bs||typeof t!="function"&&this.state===Fd)return this;var i=new this.constructor(vi);if(process.browser||this.handled===gn&&(this.handled=null),this.state!==Nd){var n=this.state===Bs?e:t;Fs(i,n,this.outcome)}else this.queue.push(new mn(i,e,t));return i};function mn(e,t,i){this.promise=e,typeof t=="function"&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),typeof i=="function"&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}mn.prototype.callFulfilled=function(e){ce.resolve(this.promise,e)};mn.prototype.otherCallFulfilled=function(e){Fs(this.promise,this.onFulfilled,e)};mn.prototype.callRejected=function(e){ce.reject(this.promise,e)};mn.prototype.otherCallRejected=function(e){Fs(this.promise,this.onRejected,e)};function Fs(e,t,i){Bd(function(){var n;try{n=t(i)}catch(r){return ce.reject(e,r)}n===e?ce.reject(e,new TypeError("Cannot resolve promise with itself")):ce.resolve(e,n)})}ce.resolve=function(e,t){var i=Ud(Um,t);if(i.status==="error")return ce.reject(e,i.value);var n=i.value;if(n)Hd(e,n);else{e.state=Bs,e.outcome=t;for(var r=-1,a=e.queue.length;++r<a;)e.queue[r].callFulfilled(t)}return e};ce.reject=function(e,t){e.state=Fd,e.outcome=t,process.browser||e.handled===gn&&Bd(function(){e.handled===gn&&process.emit("unhandledRejection",t,e)});for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e};function Um(e){var t=e&&e.then;if(e&&(typeof e=="object"||typeof e=="function")&&typeof t=="function")return function(){t.apply(e,arguments)}}function Hd(e,t){var i=!1;function n(o){i||(i=!0,ce.reject(e,o))}function r(o){i||(i=!0,ce.resolve(e,o))}function a(){t(r,n)}var s=Ud(a);s.status==="error"&&n(s.value)}function Ud(e,t){var i={};try{i.value=e(t),i.status="success"}catch(n){i.status="error",i.value=n}return i}xt.resolve=$m;function $m(e){return e instanceof this?e:ce.resolve(new this(vi),e)}xt.reject=qm;function qm(e){var t=new this(vi);return ce.reject(t,e)}xt.all=Gm;function Gm(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=new Array(i),a=0,s=-1,o=new this(vi);++s<i;)c(e[s],s);return o;function c(l,d){t.resolve(l).then(u,function(p){n||(n=!0,ce.reject(o,p))});function u(p){r[d]=p,++a===i&&!n&&(n=!0,ce.resolve(o,r))}}}xt.race=Wm;function Wm(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=-1,a=new this(vi);++r<i;)s(e[r]);return a;function s(o){t.resolve(o).then(function(c){n||(n=!0,ce.resolve(a,c))},function(c){n||(n=!0,ce.reject(a,c))})}}});var yi=P((Rw,Gd)=>{"use strict";var Ns=null;typeof Promise!="undefined"?Ns=Promise:Ns=qd();Gd.exports={Promise:Ns}});var Yd=P(Wd=>{"use strict";(function(e,t){"use strict";if(e.setImmediate)return;var i=1,n={},r=!1,a=e.document,s;function o(b){typeof b!="function"&&(b=new Function(""+b));for(var y=new Array(arguments.length-1),x=0;x<y.length;x++)y[x]=arguments[x+1];var w={callback:b,args:y};return n[i]=w,s(i),i++}function c(b){delete n[b]}function l(b){var y=b.callback,x=b.args;switch(x.length){case 0:y();break;case 1:y(x[0]);break;case 2:y(x[0],x[1]);break;case 3:y(x[0],x[1],x[2]);break;default:y.apply(t,x);break}}function d(b){if(r)setTimeout(d,0,b);else{var y=n[b];if(y){r=!0;try{l(y)}finally{c(b),r=!1}}}}function u(){s=function(b){process.nextTick(function(){d(b)})}}function p(){if(e.postMessage&&!e.importScripts){var b=!0,y=e.onmessage;return e.onmessage=function(){b=!1},e.postMessage("","*"),e.onmessage=y,b}}function f(){var b="setImmediate$"+Math.random()+"$",y=function(x){x.source===e&&typeof x.data=="string"&&x.data.indexOf(b)===0&&d(+x.data.slice(b.length))};e.addEventListener?e.addEventListener("message",y,!1):e.attachEvent("onmessage",y),s=function(x){e.postMessage(b+x,"*")}}function m(){var b=new MessageChannel;b.port1.onmessage=function(y){var x=y.data;d(x)},s=function(y){b.port2.postMessage(y)}}function h(){var b=a.documentElement;s=function(y){var x=a.createElement("script");x.onreadystatechange=function(){d(y),x.onreadystatechange=null,b.removeChild(x),x=null},b.appendChild(x)}}function g(){s=function(b){setTimeout(d,0,b)}}var v=Object.getPrototypeOf&&Object.getPrototypeOf(e);v=v&&v.setTimeout?v:e,{}.toString.call(e.process)==="[object process]"?u():p()?f():e.MessageChannel?m():a&&"onreadystatechange"in a.createElement("script")?h():g(),v.setImmediate=o,v.clearImmediate=c})(typeof self=="undefined"?typeof global=="undefined"?Wd:global:self)});var Y=P(ee=>{"use strict";var wt=rt(),Ym=Is(),xi=pn(),Hs=yi();Yd();function Vm(e){var t=null;return wt.uint8array?t=new Uint8Array(e.length):t=new Array(e.length),jr(e,t)}ee.newBlob=function(e,t){ee.checkSupport("blob");try{return new Blob([e],{type:t})}catch{try{var i=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,n=new i;return n.append(e),n.getBlob(t)}catch{throw new Error("Bug : can't construct the Blob.")}}};function bn(e){return e}function jr(e,t){for(var i=0;i<e.length;++i)t[i]=e.charCodeAt(i)&255;return t}var zr={stringifyByChunk:function(e,t,i){var n=[],r=0,a=e.length;if(a<=i)return String.fromCharCode.apply(null,e);for(;r<a;)t==="array"||t==="nodebuffer"?n.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+i,a)))):n.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+i,a)))),r+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:(function(){try{return wt.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return wt.nodebuffer&&String.fromCharCode.apply(null,xi.allocBuffer(1)).length===1}catch{return!1}})()}};function vn(e){var t=65536,i=ee.getTypeOf(e),n=!0;if(i==="uint8array"?n=zr.applyCanBeUsed.uint8array:i==="nodebuffer"&&(n=zr.applyCanBeUsed.nodebuffer),n)for(;t>1;)try{return zr.stringifyByChunk(e,i,t)}catch{t=Math.floor(t/2)}return zr.stringifyByChar(e)}ee.applyFromCharCode=vn;function Br(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}var _t={};_t.string={string:bn,array:function(e){return jr(e,new Array(e.length))},arraybuffer:function(e){return _t.string.uint8array(e).buffer},uint8array:function(e){return jr(e,new Uint8Array(e.length))},nodebuffer:function(e){return jr(e,xi.allocBuffer(e.length))}};_t.array={string:vn,array:bn,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return xi.newBufferFrom(e)}};_t.arraybuffer={string:function(e){return vn(new Uint8Array(e))},array:function(e){return Br(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:bn,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return xi.newBufferFrom(new Uint8Array(e))}};_t.uint8array={string:vn,array:function(e){return Br(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:bn,nodebuffer:function(e){return xi.newBufferFrom(e)}};_t.nodebuffer={string:vn,array:function(e){return Br(e,new Array(e.length))},arraybuffer:function(e){return _t.nodebuffer.uint8array(e).buffer},uint8array:function(e){return Br(e,new Uint8Array(e.length))},nodebuffer:bn};ee.transformTo=function(e,t){if(t||(t=""),!e)return t;ee.checkSupport(e);var i=ee.getTypeOf(t),n=_t[i][e](t);return n};ee.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var r=t[n];r==="."||r===""&&n!==0&&n!==t.length-1||(r===".."?i.pop():i.push(r))}return i.join("/")};ee.getTypeOf=function(e){if(typeof e=="string")return"string";if(Object.prototype.toString.call(e)==="[object Array]")return"array";if(wt.nodebuffer&&xi.isBuffer(e))return"nodebuffer";if(wt.uint8array&&e instanceof Uint8Array)return"uint8array";if(wt.arraybuffer&&e instanceof ArrayBuffer)return"arraybuffer"};ee.checkSupport=function(e){var t=wt[e.toLowerCase()];if(!t)throw new Error(e+" is not supported by this platform")};ee.MAX_VALUE_16BITS=65535;ee.MAX_VALUE_32BITS=-1;ee.pretty=function(e){var t="",i,n;for(n=0;n<(e||"").length;n++)i=e.charCodeAt(n),t+="\\x"+(i<16?"0":"")+i.toString(16).toUpperCase();return t};ee.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})};ee.inherits=function(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i};ee.extend=function(){var e={},t,i;for(t=0;t<arguments.length;t++)for(i in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],i)&&typeof e[i]=="undefined"&&(e[i]=arguments[t][i]);return e};ee.prepareContent=function(e,t,i,n,r){var a=Hs.Promise.resolve(t).then(function(s){var o=wt.blob&&(s instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(s))!==-1);return o&&typeof FileReader!="undefined"?new Hs.Promise(function(c,l){var d=new FileReader;d.onload=function(u){c(u.target.result)},d.onerror=function(u){l(u.target.error)},d.readAsArrayBuffer(s)}):s});return a.then(function(s){var o=ee.getTypeOf(s);return o?(o==="arraybuffer"?s=ee.transformTo("uint8array",s):o==="string"&&(r?s=Ym.decode(s):i&&n!==!0&&(s=Vm(s))),s):Hs.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}});var ye=P((Iw,Kd)=>{"use strict";function Vd(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}Vd.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return this.isFinished?!1:(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.end()}),e.on("error",function(i){t.error(i)}),this},pause:function(){return this.isPaused||this.isFinished?!1:(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;this.isPaused=!1;var e=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}};Kd.exports=Vd});var _i=P(Et=>{"use strict";var wi=Y(),Nt=rt(),Km=pn(),Fr=ye(),yn=new Array(256);for(at=0;at<256;at++)yn[at]=at>=252?6:at>=248?5:at>=240?4:at>=224?3:at>=192?2:1;var at;yn[254]=yn[254]=1;var Xm=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(Nt.uint8array?t=new Uint8Array(o):t=new Array(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t},Zm=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+yn[e[i]]>t?i:t},Jm=function(e){var t,i,n,r,a=e.length,s=new Array(a*2);for(i=0,t=0;t<a;){if(n=e[t++],n<128){s[i++]=n;continue}if(r=yn[n],r>4){s[i++]=65533,t+=r-1;continue}for(n&=r===2?31:r===3?15:7;r>1&&t<a;)n=n<<6|e[t++]&63,r--;if(r>1){s[i++]=65533;continue}n<65536?s[i++]=n:(n-=65536,s[i++]=55296|n>>10&1023,s[i++]=56320|n&1023)}return s.length!==i&&(s.subarray?s=s.subarray(0,i):s.length=i),wi.applyFromCharCode(s)};Et.utf8encode=function(t){return Nt.nodebuffer?Km.newBufferFrom(t,"utf-8"):Xm(t)};Et.utf8decode=function(t){return Nt.nodebuffer?wi.transformTo("nodebuffer",t).toString("utf-8"):(t=wi.transformTo(Nt.uint8array?"uint8array":"array",t),Jm(t))};function Nr(){Fr.call(this,"utf-8 decode"),this.leftOver=null}wi.inherits(Nr,Fr);Nr.prototype.processChunk=function(e){var t=wi.transformTo(Nt.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(Nt.uint8array){var i=t;t=new Uint8Array(i.length+this.leftOver.length),t.set(this.leftOver,0),t.set(i,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var n=Zm(t),r=t;n!==t.length&&(Nt.uint8array?(r=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(r=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:Et.utf8decode(r),meta:e.meta})};Nr.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:Et.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)};Et.Utf8DecodeWorker=Nr;function Us(){Fr.call(this,"utf-8 encode")}wi.inherits(Us,Fr);Us.prototype.processChunk=function(e){this.push({data:Et.utf8encode(e.data),meta:e.meta})};Et.Utf8EncodeWorker=Us});var Qd=P((Dw,Jd)=>{"use strict";var Xd=ye(),Zd=Y();function $s(e){Xd.call(this,"ConvertWorker to "+e),this.destType=e}Zd.inherits($s,Xd);$s.prototype.processChunk=function(e){this.push({data:Zd.transformTo(this.destType,e.data),meta:e.meta})};Jd.exports=$s});var iu=P((zw,tu)=>{"use strict";var eu=Ls().Readable,Qm=Y();Qm.inherits(qs,eu);function qs(e,t,i){eu.call(this,t),this._helper=e;var n=this;e.on("data",function(r,a){n.push(r)||n._helper.pause(),i&&i(a)}).on("error",function(r){n.emit("error",r)}).on("end",function(){n.push(null)})}qs.prototype._read=function(){this._helper.resume()};tu.exports=qs});var Gs=P((jw,au)=>{"use strict";var Ht=Y(),eb=Qd(),tb=ye(),ib=Is(),nb=rt(),rb=yi(),nu=null;if(nb.nodestream)try{nu=iu()}catch{}function ab(e,t,i){switch(e){case"blob":return Ht.newBlob(Ht.transformTo("arraybuffer",t),i);case"base64":return ib.encode(t);default:return Ht.transformTo(e,t)}}function sb(e,t){var i,n=0,r=null,a=0;for(i=0;i<t.length;i++)a+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(a),i=0;i<t.length;i++)r.set(t[i],n),n+=t[i].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}function ob(e,t){return new rb.Promise(function(i,n){var r=[],a=e._internalType,s=e._outputType,o=e._mimeType;e.on("data",function(c,l){r.push(c),t&&t(l)}).on("error",function(c){r=[],n(c)}).on("end",function(){try{var c=ab(s,sb(a,r),o);i(c)}catch(l){n(l)}r=[]}).resume()})}function ru(e,t,i){var n=t;switch(t){case"blob":case"arraybuffer":n="uint8array";break;case"base64":n="string";break}try{this._internalType=n,this._outputType=t,this._mimeType=i,Ht.checkSupport(n),this._worker=e.pipe(new eb(n)),e.lock()}catch(r){this._worker=new tb("error"),this._worker.error(r)}}ru.prototype={accumulate:function(e){return ob(this,e)},on:function(e,t){var i=this;return e==="data"?this._worker.on(e,function(n){t.call(i,n.data,n.meta)}):this._worker.on(e,function(){Ht.delay(t,arguments,i)}),this},resume:function(){return Ht.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(Ht.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new nu(this,{objectMode:this._outputType!=="nodebuffer"},e)}};au.exports=ru});var Ws=P(Pe=>{"use strict";Pe.base64=!1;Pe.binary=!1;Pe.dir=!1;Pe.createFolders=!0;Pe.date=null;Pe.compression=null;Pe.compressionOptions=null;Pe.comment=null;Pe.unixPermissions=null;Pe.dosPermissions=null});var Ys=P((Fw,su)=>{"use strict";var Hr=Y(),Ur=ye(),lb=16*1024;function Ei(e){Ur.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(i){t.dataIsReady=!0,t.data=i,t.max=i&&i.length||0,t.type=Hr.getTypeOf(i),t.isPaused||t._tickAndRepeat()},function(i){t.error(i)})}Hr.inherits(Ei,Ur);Ei.prototype.cleanUp=function(){Ur.prototype.cleanUp.call(this),this.data=null};Ei.prototype.resume=function(){return Ur.prototype.resume.call(this)?(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,Hr.delay(this._tickAndRepeat,[],this)),!0):!1};Ei.prototype._tickAndRepeat=function(){this._tickScheduled=!1,!(this.isPaused||this.isFinished)&&(this._tick(),this.isFinished||(Hr.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))};Ei.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=lb,t=null,i=Math.min(this.max,this.index+e);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,i);break;case"uint8array":t=this.data.subarray(this.index,i);break;case"array":case"nodebuffer":t=this.data.slice(this.index,i);break}return this.index=i,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})};su.exports=Ei});var $r=P((Nw,lu)=>{"use strict";var cb=Y();function db(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var ou=db();function ub(e,t,i,n){var r=ou,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}function pb(e,t,i,n){var r=ou,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t.charCodeAt(s))&255];return e^-1}lu.exports=function(t,i){if(typeof t=="undefined"||!t.length)return 0;var n=cb.getTypeOf(t)!=="string";return n?ub(i|0,t,t.length,0):pb(i|0,t,t.length,0)}});var Ks=P((Hw,du)=>{"use strict";var cu=ye(),fb=$r(),hb=Y();function Vs(){cu.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}hb.inherits(Vs,cu);Vs.prototype.processChunk=function(e){this.streamInfo.crc32=fb(e.data,this.streamInfo.crc32||0),this.push(e)};du.exports=Vs});var pu=P((Uw,uu)=>{"use strict";var gb=Y(),Xs=ye();function Zs(e){Xs.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}gb.inherits(Zs,Xs);Zs.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}Xs.prototype.processChunk.call(this,e)};uu.exports=Zs});var qr=P(($w,gu)=>{"use strict";var fu=yi(),hu=Ys(),mb=Ks(),Js=pu();function Qs(e,t,i,n,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=r}Qs.prototype={getContentWorker:function(){var e=new hu(fu.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new Js("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new hu(fu.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};Qs.createWorkerFrom=function(e,t,i){return e.pipe(new mb).pipe(new Js("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new Js("compressedSize")).withStreamInfo("compression",t)};gu.exports=Qs});var yu=P((qw,vu)=>{"use strict";var bb=Gs(),vb=Ys(),eo=_i(),to=qr(),mu=ye(),io=function(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}};io.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");i=e.toLowerCase();var n=i==="string"||i==="text";(i==="binarystring"||i==="text")&&(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new eo.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new eo.Utf8DecodeWorker))}catch(a){t=new mu("error"),t.error(a)}return new bb(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof to&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new eo.Utf8EncodeWorker)),to.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof to?this._data.getContentWorker():this._data instanceof mu?this._data:new vb(this._data)}};var bu=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],yb=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for(Gr=0;Gr<bu.length;Gr++)io.prototype[bu[Gr]]=yb;var Gr;vu.exports=io});var st=P(he=>{"use strict";var xb=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function wb(e,t){return Object.prototype.hasOwnProperty.call(e,t)}he.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if(typeof i!="object")throw new TypeError(i+"must be non-object");for(var n in i)wb(i,n)&&(e[n]=i[n])}}return e};he.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var _b={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray){e.set(t.subarray(i,i+n),r);return}for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){var t,i,n,r,a,s;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(s=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)a=e[t],s.set(a,r),r+=a.length;return s}},Eb={arraySet:function(e,t,i,n,r){for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){return[].concat.apply([],e)}};he.setTyped=function(e){e?(he.Buf8=Uint8Array,he.Buf16=Uint16Array,he.Buf32=Int32Array,he.assign(he,_b)):(he.Buf8=Array,he.Buf16=Array,he.Buf32=Array,he.assign(he,Eb))};he.setTyped(xb)});var Uu=P(Ci=>{"use strict";var Sb=st(),Ab=4,xu=0,wu=1,Cb=2;function Ai(e){for(var t=e.length;--t>=0;)e[t]=0}var Tb=0,Tu=1,kb=2,Lb=3,Rb=258,co=29,An=256,wn=An+1+co,Si=30,uo=19,ku=2*wn+1,Ut=15,no=16,Mb=7,po=256,Lu=16,Ru=17,Mu=18,oo=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Wr=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Pb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Pu=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Ib=512,ot=new Array((wn+2)*2);Ai(ot);var xn=new Array(Si*2);Ai(xn);var _n=new Array(Ib);Ai(_n);var En=new Array(Rb-Lb+1);Ai(En);var fo=new Array(co);Ai(fo);var Yr=new Array(Si);Ai(Yr);function ro(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}var Iu,Ou,Du;function ao(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function zu(e){return e<256?_n[e]:_n[256+(e>>>7)]}function Sn(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function me(e,t,i){e.bi_valid>no-i?(e.bi_buf|=t<<e.bi_valid&65535,Sn(e,e.bi_buf),e.bi_buf=t>>no-e.bi_valid,e.bi_valid+=i-no):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function qe(e,t,i){me(e,i[t*2],i[t*2+1])}function ju(e,t){var i=0;do i|=e&1,e>>>=1,i<<=1;while(--t>0);return i>>>1}function Ob(e){e.bi_valid===16?(Sn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function Db(e,t){var i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,d,u,p,f,m,h=0;for(p=0;p<=Ut;p++)e.bl_count[p]=0;for(i[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<ku;l++)d=e.heap[l],p=i[i[d*2+1]*2+1]+1,p>c&&(p=c,h++),i[d*2+1]=p,!(d>n)&&(e.bl_count[p]++,f=0,d>=o&&(f=s[d-o]),m=i[d*2],e.opt_len+=m*(p+f),a&&(e.static_len+=m*(r[d*2+1]+f)));if(h!==0){do{for(p=c-1;e.bl_count[p]===0;)p--;e.bl_count[p]--,e.bl_count[p+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(p=c;p!==0;p--)for(d=e.bl_count[p];d!==0;)u=e.heap[--l],!(u>n)&&(i[u*2+1]!==p&&(e.opt_len+=(p-i[u*2+1])*i[u*2],i[u*2+1]=p),d--)}}function Bu(e,t,i){var n=new Array(Ut+1),r=0,a,s;for(a=1;a<=Ut;a++)n[a]=r=r+i[a-1]<<1;for(s=0;s<=t;s++){var o=e[s*2+1];o!==0&&(e[s*2]=ju(n[o]++,o))}}function zb(){var e,t,i,n,r,a=new Array(Ut+1);for(i=0,n=0;n<co-1;n++)for(fo[n]=i,e=0;e<1<<oo[n];e++)En[i++]=n;for(En[i-1]=n,r=0,n=0;n<16;n++)for(Yr[n]=r,e=0;e<1<<Wr[n];e++)_n[r++]=n;for(r>>=7;n<Si;n++)for(Yr[n]=r<<7,e=0;e<1<<Wr[n]-7;e++)_n[256+r++]=n;for(t=0;t<=Ut;t++)a[t]=0;for(e=0;e<=143;)ot[e*2+1]=8,e++,a[8]++;for(;e<=255;)ot[e*2+1]=9,e++,a[9]++;for(;e<=279;)ot[e*2+1]=7,e++,a[7]++;for(;e<=287;)ot[e*2+1]=8,e++,a[8]++;for(Bu(ot,wn+1,a),e=0;e<Si;e++)xn[e*2+1]=5,xn[e*2]=ju(e,5);Iu=new ro(ot,oo,An+1,wn,Ut),Ou=new ro(xn,Wr,0,Si,Ut),Du=new ro(new Array(0),Pb,0,uo,Mb)}function Fu(e){var t;for(t=0;t<wn;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Si;t++)e.dyn_dtree[t*2]=0;for(t=0;t<uo;t++)e.bl_tree[t*2]=0;e.dyn_ltree[po*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Nu(e){e.bi_valid>8?Sn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function jb(e,t,i,n){Nu(e),n&&(Sn(e,i),Sn(e,~i)),Sb.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}function _u(e,t,i,n){var r=t*2,a=i*2;return e[r]<e[a]||e[r]===e[a]&&n[t]<=n[i]}function so(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&_u(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!_u(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function Eu(e,t,i){var n,r,a=0,s,o;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],r=e.pending_buf[e.l_buf+a],a++,n===0?qe(e,r,t):(s=En[r],qe(e,s+An+1,t),o=oo[s],o!==0&&(r-=fo[s],me(e,r,o)),n--,s=zu(n),qe(e,s,i),o=Wr[s],o!==0&&(n-=Yr[s],me(e,n,o)));while(a<e.last_lit);qe(e,po,t)}function lo(e,t){var i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.elems,s,o,c=-1,l;for(e.heap_len=0,e.heap_max=ku,s=0;s<a;s++)i[s*2]!==0?(e.heap[++e.heap_len]=c=s,e.depth[s]=0):i[s*2+1]=0;for(;e.heap_len<2;)l=e.heap[++e.heap_len]=c<2?++c:0,i[l*2]=1,e.depth[l]=0,e.opt_len--,r&&(e.static_len-=n[l*2+1]);for(t.max_code=c,s=e.heap_len>>1;s>=1;s--)so(e,i,s);l=a;do s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],so(e,i,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,i[l*2]=i[s*2]+i[o*2],e.depth[l]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,i[s*2+1]=i[o*2+1]=l,e.heap[1]=l++,so(e,i,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],Db(e,t),Bu(i,c,e.bl_count)}function Su(e,t,i){var n,r=-1,a,s=t[1],o=0,c=7,l=4;for(s===0&&(c=138,l=3),t[(i+1)*2+1]=65535,n=0;n<=i;n++)a=s,s=t[(n+1)*2+1],!(++o<c&&a===s)&&(o<l?e.bl_tree[a*2]+=o:a!==0?(a!==r&&e.bl_tree[a*2]++,e.bl_tree[Lu*2]++):o<=10?e.bl_tree[Ru*2]++:e.bl_tree[Mu*2]++,o=0,r=a,s===0?(c=138,l=3):a===s?(c=6,l=3):(c=7,l=4))}function Au(e,t,i){var n,r=-1,a,s=t[1],o=0,c=7,l=4;for(s===0&&(c=138,l=3),n=0;n<=i;n++)if(a=s,s=t[(n+1)*2+1],!(++o<c&&a===s)){if(o<l)do qe(e,a,e.bl_tree);while(--o!==0);else a!==0?(a!==r&&(qe(e,a,e.bl_tree),o--),qe(e,Lu,e.bl_tree),me(e,o-3,2)):o<=10?(qe(e,Ru,e.bl_tree),me(e,o-3,3)):(qe(e,Mu,e.bl_tree),me(e,o-11,7));o=0,r=a,s===0?(c=138,l=3):a===s?(c=6,l=3):(c=7,l=4)}}function Bb(e){var t;for(Su(e,e.dyn_ltree,e.l_desc.max_code),Su(e,e.dyn_dtree,e.d_desc.max_code),lo(e,e.bl_desc),t=uo-1;t>=3&&e.bl_tree[Pu[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function Fb(e,t,i,n){var r;for(me(e,t-257,5),me(e,i-1,5),me(e,n-4,4),r=0;r<n;r++)me(e,e.bl_tree[Pu[r]*2+1],3);Au(e,e.dyn_ltree,t-1),Au(e,e.dyn_dtree,i-1)}function Nb(e){var t=4093624447,i;for(i=0;i<=31;i++,t>>>=1)if(t&1&&e.dyn_ltree[i*2]!==0)return xu;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return wu;for(i=32;i<An;i++)if(e.dyn_ltree[i*2]!==0)return wu;return xu}var Cu=!1;function Hb(e){Cu||(zb(),Cu=!0),e.l_desc=new ao(e.dyn_ltree,Iu),e.d_desc=new ao(e.dyn_dtree,Ou),e.bl_desc=new ao(e.bl_tree,Du),e.bi_buf=0,e.bi_valid=0,Fu(e)}function Hu(e,t,i,n){me(e,(Tb<<1)+(n?1:0),3),jb(e,t,i,!0)}function Ub(e){me(e,Tu<<1,3),qe(e,po,ot),Ob(e)}function $b(e,t,i,n){var r,a,s=0;e.level>0?(e.strm.data_type===Cb&&(e.strm.data_type=Nb(e)),lo(e,e.l_desc),lo(e,e.d_desc),s=Bb(e),r=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=r&&(r=a)):r=a=i+5,i+4<=r&&t!==-1?Hu(e,t,i,n):e.strategy===Ab||a===r?(me(e,(Tu<<1)+(n?1:0),3),Eu(e,ot,xn)):(me(e,(kb<<1)+(n?1:0),3),Fb(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),Eu(e,e.dyn_ltree,e.dyn_dtree)),Fu(e),n&&Nu(e)}function qb(e,t,i){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=i&255,e.last_lit++,t===0?e.dyn_ltree[i*2]++:(e.matches++,t--,e.dyn_ltree[(En[i]+An+1)*2]++,e.dyn_dtree[zu(t)*2]++),e.last_lit===e.lit_bufsize-1}Ci._tr_init=Hb;Ci._tr_stored_block=Hu;Ci._tr_flush_block=$b;Ci._tr_tally=qb;Ci._tr_align=Ub});var ho=P((Yw,$u)=>{"use strict";function Gb(e,t,i,n){for(var r=e&65535|0,a=e>>>16&65535|0,s=0;i!==0;){s=i>2e3?2e3:i,i-=s;do r=r+t[n++]|0,a=a+r|0;while(--s);r%=65521,a%=65521}return r|a<<16|0}$u.exports=Gb});var go=P((Vw,qu)=>{"use strict";function Wb(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var Yb=Wb();function Vb(e,t,i,n){var r=Yb,a=n+i;e^=-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}qu.exports=Vb});var Vr=P((Kw,Gu)=>{"use strict";Gu.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var ep=P(Ye=>{"use strict";var ge=st(),Se=Uu(),Ku=ho(),St=go(),Kb=Vr(),Wt=0,Xb=1,Zb=3,Lt=4,Wu=5,We=0,Yu=1,Ae=-2,Jb=-3,mo=-5,Qb=-1,ev=1,Kr=2,tv=3,iv=4,nv=0,rv=2,Qr=8,av=9,sv=15,ov=8,lv=29,cv=256,vo=cv+1+lv,dv=30,uv=19,pv=2*vo+1,fv=15,B=3,Tt=258,Ie=Tt+B+1,hv=32,ea=42,yo=69,Xr=73,Zr=91,Jr=103,$t=113,Tn=666,ne=1,kn=2,qt=3,Li=4,gv=3;function kt(e,t){return e.msg=Kb[t],t}function Vu(e){return(e<<1)-(e>4?9:0)}function Ct(e){for(var t=e.length;--t>=0;)e[t]=0}function At(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),i!==0&&(ge.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,t.pending===0&&(t.pending_out=0))}function ae(e,t){Se._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,At(e.strm)}function F(e,t){e.pending_buf[e.pending++]=t}function Cn(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function mv(e,t,i,n){var r=e.avail_in;return r>n&&(r=n),r===0?0:(e.avail_in-=r,ge.arraySet(t,e.input,e.next_in,r,i),e.state.wrap===1?e.adler=Ku(e.adler,t,r,i):e.state.wrap===2&&(e.adler=St(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)}function Xu(e,t){var i=e.max_chain_length,n=e.strstart,r,a,s=e.prev_length,o=e.nice_match,c=e.strstart>e.w_size-Ie?e.strstart-(e.w_size-Ie):0,l=e.window,d=e.w_mask,u=e.prev,p=e.strstart+Tt,f=l[n+s-1],m=l[n+s];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do if(r=t,!(l[r+s]!==m||l[r+s-1]!==f||l[r]!==l[n]||l[++r]!==l[n+1])){n+=2,r++;do;while(l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&l[++n]===l[++r]&&n<p);if(a=Tt-(p-n),n=p-Tt,a>s){if(e.match_start=t,s=a,a>=o)break;f=l[n+s-1],m=l[n+s]}}while((t=u[t&d])>c&&--i!==0);return s<=e.lookahead?s:e.lookahead}function Gt(e){var t=e.w_size,i,n,r,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ie)){ge.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,i=n;do r=e.head[--i],e.head[i]=r>=t?r-t:0;while(--n);n=t,i=n;do r=e.prev[--i],e.prev[i]=r>=t?r-t:0;while(--n);a+=t}if(e.strm.avail_in===0)break;if(n=mv(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=B)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+B-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<B)););}while(e.lookahead<Ie&&e.strm.avail_in!==0)}function bv(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Gt(e),e.lookahead===0&&t===Wt)return ne;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,ae(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Ie&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):(e.strstart>e.block_start&&(ae(e,!1),e.strm.avail_out===0),ne)}function bo(e,t){for(var i,n;;){if(e.lookahead<Ie){if(Gt(e),e.lookahead<Ie&&t===Wt)return ne;if(e.lookahead===0)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),i!==0&&e.strstart-i<=e.w_size-Ie&&(e.match_length=Xu(e,i)),e.match_length>=B)if(n=Se._tr_tally(e,e.strstart-e.match_start,e.match_length-B),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=B){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=e.strstart<B-1?e.strstart:B-1,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function Ti(e,t){for(var i,n,r;;){if(e.lookahead<Ie){if(Gt(e),e.lookahead<Ie&&t===Wt)return ne;if(e.lookahead===0)break}if(i=0,e.lookahead>=B&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=B-1,i!==0&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-Ie&&(e.match_length=Xu(e,i),e.match_length<=5&&(e.strategy===ev||e.match_length===B&&e.strstart-e.match_start>4096)&&(e.match_length=B-1)),e.prev_length>=B&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-B,n=Se._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-B),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+B-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=B-1,e.strstart++,n&&(ae(e,!1),e.strm.avail_out===0))return ne}else if(e.match_available){if(n=Se._tr_tally(e,0,e.window[e.strstart-1]),n&&ae(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return ne}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Se._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<B-1?e.strstart:B-1,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function vv(e,t){for(var i,n,r,a,s=e.window;;){if(e.lookahead<=Tt){if(Gt(e),e.lookahead<=Tt&&t===Wt)return ne;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=B&&e.strstart>0&&(r=e.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){a=e.strstart+Tt;do;while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<a);e.match_length=Tt-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=B?(i=Se._tr_tally(e,1,e.match_length-B),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function yv(e,t){for(var i;;){if(e.lookahead===0&&(Gt(e),e.lookahead===0)){if(t===Wt)return ne;break}if(e.match_length=0,i=Se._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ae(e,!1),e.strm.avail_out===0))return ne}return e.insert=0,t===Lt?(ae(e,!0),e.strm.avail_out===0?qt:Li):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ne:kn}function Ge(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}var ki;ki=[new Ge(0,0,0,0,bv),new Ge(4,4,8,4,bo),new Ge(4,5,16,8,bo),new Ge(4,6,32,32,bo),new Ge(4,4,16,16,Ti),new Ge(8,16,32,32,Ti),new Ge(8,16,128,128,Ti),new Ge(8,32,128,256,Ti),new Ge(32,128,258,1024,Ti),new Ge(32,258,258,4096,Ti)];function xv(e){e.window_size=2*e.w_size,Ct(e.head),e.max_lazy_match=ki[e.level].max_lazy,e.good_match=ki[e.level].good_length,e.nice_match=ki[e.level].nice_length,e.max_chain_length=ki[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=B-1,e.match_available=0,e.ins_h=0}function wv(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Qr,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ge.Buf16(pv*2),this.dyn_dtree=new ge.Buf16((2*dv+1)*2),this.bl_tree=new ge.Buf16((2*uv+1)*2),Ct(this.dyn_ltree),Ct(this.dyn_dtree),Ct(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ge.Buf16(fv+1),this.heap=new ge.Buf16(2*vo+1),Ct(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ge.Buf16(2*vo+1),Ct(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Zu(e){var t;return!e||!e.state?kt(e,Ae):(e.total_in=e.total_out=0,e.data_type=rv,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?ea:$t,e.adler=t.wrap===2?0:1,t.last_flush=Wt,Se._tr_init(t),We)}function Ju(e){var t=Zu(e);return t===We&&xv(e.state),t}function _v(e,t){return!e||!e.state||e.state.wrap!==2?Ae:(e.state.gzhead=t,We)}function Qu(e,t,i,n,r,a){if(!e)return Ae;var s=1;if(t===Qb&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>av||i!==Qr||n<8||n>15||t<0||t>9||a<0||a>iv)return kt(e,Ae);n===8&&(n=9);var o=new wv;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+B-1)/B),o.window=new ge.Buf8(o.w_size*2),o.head=new ge.Buf16(o.hash_size),o.prev=new ge.Buf16(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new ge.Buf8(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=a,o.method=i,Ju(e)}function Ev(e,t){return Qu(e,t,Qr,sv,ov,nv)}function Sv(e,t){var i,n,r,a;if(!e||!e.state||t>Wu||t<0)return e?kt(e,Ae):Ae;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Tn&&t!==Lt)return kt(e,e.avail_out===0?mo:Ae);if(n.strm=e,i=n.last_flush,n.last_flush=t,n.status===ea)if(n.wrap===2)e.adler=0,F(n,31),F(n,139),F(n,8),n.gzhead?(F(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),F(n,n.gzhead.time&255),F(n,n.gzhead.time>>8&255),F(n,n.gzhead.time>>16&255),F(n,n.gzhead.time>>24&255),F(n,n.level===9?2:n.strategy>=Kr||n.level<2?4:0),F(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(F(n,n.gzhead.extra.length&255),F(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=St(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=yo):(F(n,0),F(n,0),F(n,0),F(n,0),F(n,0),F(n,n.level===9?2:n.strategy>=Kr||n.level<2?4:0),F(n,gv),n.status=$t);else{var s=Qr+(n.w_bits-8<<4)<<8,o=-1;n.strategy>=Kr||n.level<2?o=0:n.level<6?o=1:n.level===6?o=2:o=3,s|=o<<6,n.strstart!==0&&(s|=hv),s+=31-s%31,n.status=$t,Cn(n,s),n.strstart!==0&&(Cn(n,e.adler>>>16),Cn(n,e.adler&65535)),e.adler=1}if(n.status===yo)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size));)F(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=Xr)}else n.status=Xr;if(n.status===Xr)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.name.length?a=n.gzhead.name.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.gzindex=0,n.status=Zr)}else n.status=Zr;if(n.status===Zr)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),At(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.comment.length?a=n.gzhead.comment.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=St(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.status=Jr)}else n.status=Jr;if(n.status===Jr&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&At(e),n.pending+2<=n.pending_buf_size&&(F(n,e.adler&255),F(n,e.adler>>8&255),e.adler=0,n.status=$t)):n.status=$t),n.pending!==0){if(At(e),e.avail_out===0)return n.last_flush=-1,We}else if(e.avail_in===0&&Vu(t)<=Vu(i)&&t!==Lt)return kt(e,mo);if(n.status===Tn&&e.avail_in!==0)return kt(e,mo);if(e.avail_in!==0||n.lookahead!==0||t!==Wt&&n.status!==Tn){var c=n.strategy===Kr?yv(n,t):n.strategy===tv?vv(n,t):ki[n.level].func(n,t);if((c===qt||c===Li)&&(n.status=Tn),c===ne||c===qt)return e.avail_out===0&&(n.last_flush=-1),We;if(c===kn&&(t===Xb?Se._tr_align(n):t!==Wu&&(Se._tr_stored_block(n,0,0,!1),t===Zb&&(Ct(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),At(e),e.avail_out===0))return n.last_flush=-1,We}return t!==Lt?We:n.wrap<=0?Yu:(n.wrap===2?(F(n,e.adler&255),F(n,e.adler>>8&255),F(n,e.adler>>16&255),F(n,e.adler>>24&255),F(n,e.total_in&255),F(n,e.total_in>>8&255),F(n,e.total_in>>16&255),F(n,e.total_in>>24&255)):(Cn(n,e.adler>>>16),Cn(n,e.adler&65535)),At(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?We:Yu)}function Av(e){var t;return!e||!e.state?Ae:(t=e.state.status,t!==ea&&t!==yo&&t!==Xr&&t!==Zr&&t!==Jr&&t!==$t&&t!==Tn?kt(e,Ae):(e.state=null,t===$t?kt(e,Jb):We))}function Cv(e,t){var i=t.length,n,r,a,s,o,c,l,d;if(!e||!e.state||(n=e.state,s=n.wrap,s===2||s===1&&n.status!==ea||n.lookahead))return Ae;for(s===1&&(e.adler=Ku(e.adler,t,i,0)),n.wrap=0,i>=n.w_size&&(s===0&&(Ct(n.head),n.strstart=0,n.block_start=0,n.insert=0),d=new ge.Buf8(n.w_size),ge.arraySet(d,t,i-n.w_size,n.w_size,0),t=d,i=n.w_size),o=e.avail_in,c=e.next_in,l=e.input,e.avail_in=i,e.next_in=0,e.input=t,Gt(n);n.lookahead>=B;){r=n.strstart,a=n.lookahead-(B-1);do n.ins_h=(n.ins_h<<n.hash_shift^n.window[r+B-1])&n.hash_mask,n.prev[r&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=r,r++;while(--a);n.strstart=r,n.lookahead=B-1,Gt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=B-1,n.match_available=0,e.next_in=c,e.input=l,e.avail_in=o,n.wrap=s,We}Ye.deflateInit=Ev;Ye.deflateInit2=Qu;Ye.deflateReset=Ju;Ye.deflateResetKeep=Zu;Ye.deflateSetHeader=_v;Ye.deflate=Sv;Ye.deflateEnd=Av;Ye.deflateSetDictionary=Cv;Ye.deflateInfo="pako deflate (from Nodeca project)"});var xo=P(Ri=>{"use strict";var ta=st(),tp=!0,ip=!0;try{String.fromCharCode.apply(null,[0])}catch{tp=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{ip=!1}var Ln=new ta.Buf8(256);for(lt=0;lt<256;lt++)Ln[lt]=lt>=252?6:lt>=248?5:lt>=240?4:lt>=224?3:lt>=192?2:1;var lt;Ln[254]=Ln[254]=1;Ri.string2buf=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new ta.Buf8(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t};function np(e,t){if(t<65534&&(e.subarray&&ip||!e.subarray&&tp))return String.fromCharCode.apply(null,ta.shrinkBuf(e,t));for(var i="",n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i}Ri.buf2binstring=function(e){return np(e,e.length)};Ri.binstring2buf=function(e){for(var t=new ta.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t};Ri.buf2string=function(e,t){var i,n,r,a,s=t||e.length,o=new Array(s*2);for(n=0,i=0;i<s;){if(r=e[i++],r<128){o[n++]=r;continue}if(a=Ln[r],a>4){o[n++]=65533,i+=a-1;continue}for(r&=a===2?31:a===3?15:7;a>1&&i<s;)r=r<<6|e[i++]&63,a--;if(a>1){o[n++]=65533;continue}r<65536?o[n++]=r:(r-=65536,o[n++]=55296|r>>10&1023,o[n++]=56320|r&1023)}return np(o,n)};Ri.utf8border=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+Ln[e[i]]>t?i:t}});var wo=P((Jw,rp)=>{"use strict";function Tv(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}rp.exports=Tv});var lp=P(Pn=>{"use strict";var Rn=ep(),Mn=st(),Eo=xo(),So=Vr(),kv=wo(),op=Object.prototype.toString,Lv=0,_o=4,Mi=0,ap=1,sp=2,Rv=-1,Mv=0,Pv=8;function Yt(e){if(!(this instanceof Yt))return new Yt(e);this.options=Mn.assign({level:Rv,method:Pv,chunkSize:16384,windowBits:15,memLevel:8,strategy:Mv,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kv,this.strm.avail_out=0;var i=Rn.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Mi)throw new Error(So[i]);if(t.header&&Rn.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(typeof t.dictionary=="string"?n=Eo.string2buf(t.dictionary):op.call(t.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(t.dictionary):n=t.dictionary,i=Rn.deflateSetDictionary(this.strm,n),i!==Mi)throw new Error(So[i]);this._dict_set=!0}}Yt.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r,a;if(this.ended)return!1;a=t===~~t?t:t===!0?_o:Lv,typeof e=="string"?i.input=Eo.string2buf(e):op.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new Mn.Buf8(n),i.next_out=0,i.avail_out=n),r=Rn.deflate(i,a),r!==ap&&r!==Mi)return this.onEnd(r),this.ended=!0,!1;(i.avail_out===0||i.avail_in===0&&(a===_o||a===sp))&&(this.options.to==="string"?this.onData(Eo.buf2binstring(Mn.shrinkBuf(i.output,i.next_out))):this.onData(Mn.shrinkBuf(i.output,i.next_out)))}while((i.avail_in>0||i.avail_out===0)&&r!==ap);return a===_o?(r=Rn.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===Mi):(a===sp&&(this.onEnd(Mi),i.avail_out=0),!0)};Yt.prototype.onData=function(e){this.chunks.push(e)};Yt.prototype.onEnd=function(e){e===Mi&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Mn.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Ao(e,t){var i=new Yt(t);if(i.push(e,!0),i.err)throw i.msg||So[i.err];return i.result}function Iv(e,t){return t=t||{},t.raw=!0,Ao(e,t)}function Ov(e,t){return t=t||{},t.gzip=!0,Ao(e,t)}Pn.Deflate=Yt;Pn.deflate=Ao;Pn.deflateRaw=Iv;Pn.gzip=Ov});var dp=P((e1,cp)=>{"use strict";var ia=30,Dv=12;cp.exports=function(t,i){var n,r,a,s,o,c,l,d,u,p,f,m,h,g,v,b,y,x,w,A,T,E,M,I,_;n=t.state,r=t.next_in,I=t.input,a=r+(t.avail_in-5),s=t.next_out,_=t.output,o=s-(i-t.avail_out),c=s+(t.avail_out-257),l=n.dmax,d=n.wsize,u=n.whave,p=n.wnext,f=n.window,m=n.hold,h=n.bits,g=n.lencode,v=n.distcode,b=(1<<n.lenbits)-1,y=(1<<n.distbits)-1;e:do{h<15&&(m+=I[r++]<<h,h+=8,m+=I[r++]<<h,h+=8),x=g[m&b];t:for(;;){if(w=x>>>24,m>>>=w,h-=w,w=x>>>16&255,w===0)_[s++]=x&65535;else if(w&16){A=x&65535,w&=15,w&&(h<w&&(m+=I[r++]<<h,h+=8),A+=m&(1<<w)-1,m>>>=w,h-=w),h<15&&(m+=I[r++]<<h,h+=8,m+=I[r++]<<h,h+=8),x=v[m&y];i:for(;;){if(w=x>>>24,m>>>=w,h-=w,w=x>>>16&255,w&16){if(T=x&65535,w&=15,h<w&&(m+=I[r++]<<h,h+=8,h<w&&(m+=I[r++]<<h,h+=8)),T+=m&(1<<w)-1,T>l){t.msg="invalid distance too far back",n.mode=ia;break e}if(m>>>=w,h-=w,w=s-o,T>w){if(w=T-w,w>u&&n.sane){t.msg="invalid distance too far back",n.mode=ia;break e}if(E=0,M=f,p===0){if(E+=d-w,w<A){A-=w;do _[s++]=f[E++];while(--w);E=s-T,M=_}}else if(p<w){if(E+=d+p-w,w-=p,w<A){A-=w;do _[s++]=f[E++];while(--w);if(E=0,p<A){w=p,A-=w;do _[s++]=f[E++];while(--w);E=s-T,M=_}}}else if(E+=p-w,w<A){A-=w;do _[s++]=f[E++];while(--w);E=s-T,M=_}for(;A>2;)_[s++]=M[E++],_[s++]=M[E++],_[s++]=M[E++],A-=3;A&&(_[s++]=M[E++],A>1&&(_[s++]=M[E++]))}else{E=s-T;do _[s++]=_[E++],_[s++]=_[E++],_[s++]=_[E++],A-=3;while(A>2);A&&(_[s++]=_[E++],A>1&&(_[s++]=_[E++]))}}else if((w&64)===0){x=v[(x&65535)+(m&(1<<w)-1)];continue i}else{t.msg="invalid distance code",n.mode=ia;break e}break}}else if((w&64)===0){x=g[(x&65535)+(m&(1<<w)-1)];continue t}else if(w&32){n.mode=Dv;break e}else{t.msg="invalid literal/length code",n.mode=ia;break e}break}}while(r<a&&s<c);A=h>>3,r-=A,h-=A<<3,m&=(1<<h)-1,t.next_in=r,t.next_out=s,t.avail_in=r<a?5+(a-r):5-(r-a),t.avail_out=s<c?257+(c-s):257-(s-c),n.hold=m,n.bits=h}});var bp=P((t1,mp)=>{"use strict";var up=st(),Pi=15,pp=852,fp=592,hp=0,Co=1,gp=2,zv=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],jv=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Bv=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Fv=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];mp.exports=function(t,i,n,r,a,s,o,c){var l=c.bits,d=0,u=0,p=0,f=0,m=0,h=0,g=0,v=0,b=0,y=0,x,w,A,T,E,M=null,I=0,_,S=new up.Buf16(Pi+1),L=new up.Buf16(Pi+1),R=null,O=0,C,z,k;for(d=0;d<=Pi;d++)S[d]=0;for(u=0;u<r;u++)S[i[n+u]]++;for(m=l,f=Pi;f>=1&&S[f]===0;f--);if(m>f&&(m=f),f===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,c.bits=1,0;for(p=1;p<f&&S[p]===0;p++);for(m<p&&(m=p),v=1,d=1;d<=Pi;d++)if(v<<=1,v-=S[d],v<0)return-1;if(v>0&&(t===hp||f!==1))return-1;for(L[1]=0,d=1;d<Pi;d++)L[d+1]=L[d]+S[d];for(u=0;u<r;u++)i[n+u]!==0&&(o[L[i[n+u]]++]=u);if(t===hp?(M=R=o,_=19):t===Co?(M=zv,I-=257,R=jv,O-=257,_=256):(M=Bv,R=Fv,_=-1),y=0,u=0,d=p,E=s,h=m,g=0,A=-1,b=1<<m,T=b-1,t===Co&&b>pp||t===gp&&b>fp)return 1;for(;;){C=d-g,o[u]<_?(z=0,k=o[u]):o[u]>_?(z=R[O+o[u]],k=M[I+o[u]]):(z=96,k=0),x=1<<d-g,w=1<<h,p=w;do w-=x,a[E+(y>>g)+w]=C<<24|z<<16|k|0;while(w!==0);for(x=1<<d-1;y&x;)x>>=1;if(x!==0?(y&=x-1,y+=x):y=0,u++,--S[d]===0){if(d===f)break;d=i[n+o[u]]}if(d>m&&(y&T)!==A){for(g===0&&(g=m),E+=p,h=d-g,v=1<<h;h+g<f&&(v-=S[h+g],!(v<=0));)h++,v<<=1;if(b+=1<<h,t===Co&&b>pp||t===gp&&b>fp)return 1;A=y&T,a[A]=m<<24|h<<16|E-s|0}}return y!==0&&(a[E+y]=d-g<<24|64<<16|0),c.bits=m,0}});var Jp=P(Oe=>{"use strict";var xe=st(),Po=ho(),Ve=go(),Nv=dp(),In=bp(),Hv=0,$p=1,qp=2,vp=4,Uv=5,na=6,Vt=0,$v=1,qv=2,Ce=-2,Gp=-3,Io=-4,Gv=-5,yp=8,Wp=1,xp=2,wp=3,_p=4,Ep=5,Sp=6,Ap=7,Cp=8,Tp=9,kp=10,sa=11,ct=12,To=13,Lp=14,ko=15,Rp=16,Mp=17,Pp=18,Ip=19,ra=20,aa=21,Op=22,Dp=23,zp=24,jp=25,Bp=26,Lo=27,Fp=28,Np=29,W=30,Oo=31,Wv=32,Yv=852,Vv=592,Kv=15,Xv=Kv;function Hp(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Zv(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new xe.Buf16(320),this.work=new xe.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Yp(e){var t;return!e||!e.state?Ce:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Wp,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new xe.Buf32(Yv),t.distcode=t.distdyn=new xe.Buf32(Vv),t.sane=1,t.back=-1,Vt)}function Vp(e){var t;return!e||!e.state?Ce:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,Yp(e))}function Kp(e,t){var i,n;return!e||!e.state||(n=e.state,t<0?(i=0,t=-t):(i=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Ce:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,Vp(e))}function Xp(e,t){var i,n;return e?(n=new Zv,e.state=n,n.window=null,i=Kp(e,t),i!==Vt&&(e.state=null),i):Ce}function Jv(e){return Xp(e,Xv)}var Up=!0,Ro,Mo;function Qv(e){if(Up){var t;for(Ro=new xe.Buf32(512),Mo=new xe.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(In($p,e.lens,0,288,Ro,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;In(qp,e.lens,0,32,Mo,0,e.work,{bits:5}),Up=!1}e.lencode=Ro,e.lenbits=9,e.distcode=Mo,e.distbits=5}function Zp(e,t,i,n){var r,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new xe.Buf8(a.wsize)),n>=a.wsize?(xe.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(r=a.wsize-a.wnext,r>n&&(r=n),xe.arraySet(a.window,t,i-n,r,a.wnext),n-=r,n?(xe.arraySet(a.window,t,i-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=r))),0}function ey(e,t){var i,n,r,a,s,o,c,l,d,u,p,f,m,h,g=0,v,b,y,x,w,A,T,E,M=new xe.Buf8(4),I,_,S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Ce;i=e.state,i.mode===ct&&(i.mode=To),s=e.next_out,r=e.output,c=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,l=i.hold,d=i.bits,u=o,p=c,E=Vt;e:for(;;)switch(i.mode){case Wp:if(i.wrap===0){i.mode=To;break}for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.wrap&2&&l===35615){i.check=0,M[0]=l&255,M[1]=l>>>8&255,i.check=Ve(i.check,M,2,0),l=0,d=0,i.mode=xp;break}if(i.flags=0,i.head&&(i.head.done=!1),!(i.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=W;break}if((l&15)!==yp){e.msg="unknown compression method",i.mode=W;break}if(l>>>=4,d-=4,T=(l&15)+8,i.wbits===0)i.wbits=T;else if(T>i.wbits){e.msg="invalid window size",i.mode=W;break}i.dmax=1<<T,e.adler=i.check=1,i.mode=l&512?kp:ct,l=0,d=0;break;case xp:for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.flags=l,(i.flags&255)!==yp){e.msg="unknown compression method",i.mode=W;break}if(i.flags&57344){e.msg="unknown header flags set",i.mode=W;break}i.head&&(i.head.text=l>>8&1),i.flags&512&&(M[0]=l&255,M[1]=l>>>8&255,i.check=Ve(i.check,M,2,0)),l=0,d=0,i.mode=wp;case wp:for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.head&&(i.head.time=l),i.flags&512&&(M[0]=l&255,M[1]=l>>>8&255,M[2]=l>>>16&255,M[3]=l>>>24&255,i.check=Ve(i.check,M,4,0)),l=0,d=0,i.mode=_p;case _p:for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.head&&(i.head.xflags=l&255,i.head.os=l>>8),i.flags&512&&(M[0]=l&255,M[1]=l>>>8&255,i.check=Ve(i.check,M,2,0)),l=0,d=0,i.mode=Ep;case Ep:if(i.flags&1024){for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.length=l,i.head&&(i.head.extra_len=l),i.flags&512&&(M[0]=l&255,M[1]=l>>>8&255,i.check=Ve(i.check,M,2,0)),l=0,d=0}else i.head&&(i.head.extra=null);i.mode=Sp;case Sp:if(i.flags&1024&&(f=i.length,f>o&&(f=o),f&&(i.head&&(T=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),xe.arraySet(i.head.extra,n,a,f,T)),i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,i.length-=f),i.length))break e;i.length=0,i.mode=Ap;case Ap:if(i.flags&2048){if(o===0)break e;f=0;do T=n[a+f++],i.head&&T&&i.length<65536&&(i.head.name+=String.fromCharCode(T));while(T&&f<o);if(i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,T)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=Cp;case Cp:if(i.flags&4096){if(o===0)break e;f=0;do T=n[a+f++],i.head&&T&&i.length<65536&&(i.head.comment+=String.fromCharCode(T));while(T&&f<o);if(i.flags&512&&(i.check=Ve(i.check,n,f,a)),o-=f,a+=f,T)break e}else i.head&&(i.head.comment=null);i.mode=Tp;case Tp:if(i.flags&512){for(;d<16;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l!==(i.check&65535)){e.msg="header crc mismatch",i.mode=W;break}l=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ct;break;case kp:for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}e.adler=i.check=Hp(l),l=0,d=0,i.mode=sa;case sa:if(i.havedict===0)return e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,qv;e.adler=i.check=1,i.mode=ct;case ct:if(t===Uv||t===na)break e;case To:if(i.last){l>>>=d&7,d-=d&7,i.mode=Lo;break}for(;d<3;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}switch(i.last=l&1,l>>>=1,d-=1,l&3){case 0:i.mode=Lp;break;case 1:if(Qv(i),i.mode=ra,t===na){l>>>=2,d-=2;break e}break;case 2:i.mode=Mp;break;case 3:e.msg="invalid block type",i.mode=W}l>>>=2,d-=2;break;case Lp:for(l>>>=d&7,d-=d&7;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if((l&65535)!==(l>>>16^65535)){e.msg="invalid stored block lengths",i.mode=W;break}if(i.length=l&65535,l=0,d=0,i.mode=ko,t===na)break e;case ko:i.mode=Rp;case Rp:if(f=i.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;xe.arraySet(r,n,a,f,s),o-=f,a+=f,c-=f,s+=f,i.length-=f;break}i.mode=ct;break;case Mp:for(;d<14;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(i.nlen=(l&31)+257,l>>>=5,d-=5,i.ndist=(l&31)+1,l>>>=5,d-=5,i.ncode=(l&15)+4,l>>>=4,d-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=W;break}i.have=0,i.mode=Pp;case Pp:for(;i.have<i.ncode;){for(;d<3;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.lens[S[i.have++]]=l&7,l>>>=3,d-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,I={bits:i.lenbits},E=In(Hv,i.lens,0,19,i.lencode,0,i.work,I),i.lenbits=I.bits,E){e.msg="invalid code lengths set",i.mode=W;break}i.have=0,i.mode=Ip;case Ip:for(;i.have<i.nlen+i.ndist;){for(;g=i.lencode[l&(1<<i.lenbits)-1],v=g>>>24,b=g>>>16&255,y=g&65535,!(v<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(y<16)l>>>=v,d-=v,i.lens[i.have++]=y;else{if(y===16){for(_=v+2;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l>>>=v,d-=v,i.have===0){e.msg="invalid bit length repeat",i.mode=W;break}T=i.lens[i.have-1],f=3+(l&3),l>>>=2,d-=2}else if(y===17){for(_=v+3;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=v,d-=v,T=0,f=3+(l&7),l>>>=3,d-=3}else{for(_=v+7;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=v,d-=v,T=0,f=11+(l&127),l>>>=7,d-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=W;break}for(;f--;)i.lens[i.have++]=T}}if(i.mode===W)break;if(i.lens[256]===0){e.msg="invalid code -- missing end-of-block",i.mode=W;break}if(i.lenbits=9,I={bits:i.lenbits},E=In($p,i.lens,0,i.nlen,i.lencode,0,i.work,I),i.lenbits=I.bits,E){e.msg="invalid literal/lengths set",i.mode=W;break}if(i.distbits=6,i.distcode=i.distdyn,I={bits:i.distbits},E=In(qp,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,I),i.distbits=I.bits,E){e.msg="invalid distances set",i.mode=W;break}if(i.mode=ra,t===na)break e;case ra:i.mode=aa;case aa:if(o>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,Nv(e,p),s=e.next_out,r=e.output,c=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,l=i.hold,d=i.bits,i.mode===ct&&(i.back=-1);break}for(i.back=0;g=i.lencode[l&(1<<i.lenbits)-1],v=g>>>24,b=g>>>16&255,y=g&65535,!(v<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(b&&(b&240)===0){for(x=v,w=b,A=y;g=i.lencode[A+((l&(1<<x+w)-1)>>x)],v=g>>>24,b=g>>>16&255,y=g&65535,!(x+v<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=x,d-=x,i.back+=x}if(l>>>=v,d-=v,i.back+=v,i.length=y,b===0){i.mode=Bp;break}if(b&32){i.back=-1,i.mode=ct;break}if(b&64){e.msg="invalid literal/length code",i.mode=W;break}i.extra=b&15,i.mode=Op;case Op:if(i.extra){for(_=i.extra;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.length+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=Dp;case Dp:for(;g=i.distcode[l&(1<<i.distbits)-1],v=g>>>24,b=g>>>16&255,y=g&65535,!(v<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if((b&240)===0){for(x=v,w=b,A=y;g=i.distcode[A+((l&(1<<x+w)-1)>>x)],v=g>>>24,b=g>>>16&255,y=g&65535,!(x+v<=d);){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}l>>>=x,d-=x,i.back+=x}if(l>>>=v,d-=v,i.back+=v,b&64){e.msg="invalid distance code",i.mode=W;break}i.offset=y,i.extra=b&15,i.mode=zp;case zp:if(i.extra){for(_=i.extra;d<_;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}i.offset+=l&(1<<i.extra)-1,l>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=W;break}i.mode=jp;case jp:if(c===0)break e;if(f=p-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=W;break}f>i.wnext?(f-=i.wnext,m=i.wsize-f):m=i.wnext-f,f>i.length&&(f=i.length),h=i.window}else h=r,m=s-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do r[s++]=h[m++];while(--f);i.length===0&&(i.mode=aa);break;case Bp:if(c===0)break e;r[s++]=i.length,c--,i.mode=aa;break;case Lo:if(i.wrap){for(;d<32;){if(o===0)break e;o--,l|=n[a++]<<d,d+=8}if(p-=c,e.total_out+=p,i.total+=p,p&&(e.adler=i.check=i.flags?Ve(i.check,r,p,s-p):Po(i.check,r,p,s-p)),p=c,(i.flags?l:Hp(l))!==i.check){e.msg="incorrect data check",i.mode=W;break}l=0,d=0}i.mode=Fp;case Fp:if(i.wrap&&i.flags){for(;d<32;){if(o===0)break e;o--,l+=n[a++]<<d,d+=8}if(l!==(i.total&4294967295)){e.msg="incorrect length check",i.mode=W;break}l=0,d=0}i.mode=Np;case Np:E=$v;break e;case W:E=Gp;break e;case Oo:return Io;case Wv:default:return Ce}return e.next_out=s,e.avail_out=c,e.next_in=a,e.avail_in=o,i.hold=l,i.bits=d,(i.wsize||p!==e.avail_out&&i.mode<W&&(i.mode<Lo||t!==vp))&&Zp(e,e.output,e.next_out,p-e.avail_out)?(i.mode=Oo,Io):(u-=e.avail_in,p-=e.avail_out,e.total_in+=u,e.total_out+=p,i.total+=p,i.wrap&&p&&(e.adler=i.check=i.flags?Ve(i.check,r,p,e.next_out-p):Po(i.check,r,p,e.next_out-p)),e.data_type=i.bits+(i.last?64:0)+(i.mode===ct?128:0)+(i.mode===ra||i.mode===ko?256:0),(u===0&&p===0||t===vp)&&E===Vt&&(E=Gv),E)}function ty(e){if(!e||!e.state)return Ce;var t=e.state;return t.window&&(t.window=null),e.state=null,Vt}function iy(e,t){var i;return!e||!e.state||(i=e.state,(i.wrap&2)===0)?Ce:(i.head=t,t.done=!1,Vt)}function ny(e,t){var i=t.length,n,r,a;return!e||!e.state||(n=e.state,n.wrap!==0&&n.mode!==sa)?Ce:n.mode===sa&&(r=1,r=Po(r,t,i,0),r!==n.check)?Gp:(a=Zp(e,t,i,i),a?(n.mode=Oo,Io):(n.havedict=1,Vt))}Oe.inflateReset=Vp;Oe.inflateReset2=Kp;Oe.inflateResetKeep=Yp;Oe.inflateInit=Jv;Oe.inflateInit2=Xp;Oe.inflate=ey;Oe.inflateEnd=ty;Oe.inflateGetHeader=iy;Oe.inflateSetDictionary=ny;Oe.inflateInfo="pako inflate (from Nodeca project)"});var Do=P((n1,Qp)=>{"use strict";Qp.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var tf=P((r1,ef)=>{"use strict";function ry(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}ef.exports=ry});var rf=P(Dn=>{"use strict";var Ii=Jp(),On=st(),oa=xo(),J=Do(),zo=Vr(),ay=wo(),sy=tf(),nf=Object.prototype.toString;function Kt(e){if(!(this instanceof Kt))return new Kt(e);this.options=On.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ay,this.strm.avail_out=0;var i=Ii.inflateInit2(this.strm,t.windowBits);if(i!==J.Z_OK)throw new Error(zo[i]);if(this.header=new sy,Ii.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=oa.string2buf(t.dictionary):nf.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Ii.inflateSetDictionary(this.strm,t.dictionary),i!==J.Z_OK)))throw new Error(zo[i])}Kt.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r=this.options.dictionary,a,s,o,c,l,d=!1;if(this.ended)return!1;s=t===~~t?t:t===!0?J.Z_FINISH:J.Z_NO_FLUSH,typeof e=="string"?i.input=oa.binstring2buf(e):nf.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new On.Buf8(n),i.next_out=0,i.avail_out=n),a=Ii.inflate(i,J.Z_NO_FLUSH),a===J.Z_NEED_DICT&&r&&(a=Ii.inflateSetDictionary(this.strm,r)),a===J.Z_BUF_ERROR&&d===!0&&(a=J.Z_OK,d=!1),a!==J.Z_STREAM_END&&a!==J.Z_OK)return this.onEnd(a),this.ended=!0,!1;i.next_out&&(i.avail_out===0||a===J.Z_STREAM_END||i.avail_in===0&&(s===J.Z_FINISH||s===J.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=oa.utf8border(i.output,i.next_out),c=i.next_out-o,l=oa.buf2string(i.output,o),i.next_out=c,i.avail_out=n-c,c&&On.arraySet(i.output,i.output,o,c,0),this.onData(l)):this.onData(On.shrinkBuf(i.output,i.next_out))),i.avail_in===0&&i.avail_out===0&&(d=!0)}while((i.avail_in>0||i.avail_out===0)&&a!==J.Z_STREAM_END);return a===J.Z_STREAM_END&&(s=J.Z_FINISH),s===J.Z_FINISH?(a=Ii.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===J.Z_OK):(s===J.Z_SYNC_FLUSH&&(this.onEnd(J.Z_OK),i.avail_out=0),!0)};Kt.prototype.onData=function(e){this.chunks.push(e)};Kt.prototype.onEnd=function(e){e===J.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=On.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function jo(e,t){var i=new Kt(t);if(i.push(e,!0),i.err)throw i.msg||zo[i.err];return i.result}function oy(e,t){return t=t||{},t.raw=!0,jo(e,t)}Dn.Inflate=Kt;Dn.inflate=jo;Dn.inflateRaw=oy;Dn.ungzip=jo});var of=P((s1,sf)=>{"use strict";var ly=st().assign,cy=lp(),dy=rf(),uy=Do(),af={};ly(af,cy,dy,uy);sf.exports=af});var cf=P(ca=>{"use strict";var py=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",fy=of(),lf=Y(),la=ye(),hy=py?"uint8array":"array";ca.magic="\b\0";function Xt(e,t){la.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}lf.inherits(Xt,la);Xt.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(lf.transformTo(hy,e.data),!1)};Xt.prototype.flush=function(){la.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)};Xt.prototype.cleanUp=function(){la.prototype.cleanUp.call(this),this._pako=null};Xt.prototype._createPako=function(){this._pako=new fy[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}};ca.compressWorker=function(e){return new Xt("Deflate",e)};ca.uncompressWorker=function(){return new Xt("Inflate",{})}});var Fo=P(Bo=>{"use strict";var df=ye();Bo.STORE={magic:"\0\0",compressWorker:function(){return new df("STORE compression")},uncompressWorker:function(){return new df("STORE decompression")}};Bo.DEFLATE=cf()});var No=P(Zt=>{"use strict";Zt.LOCAL_FILE_HEADER="PK";Zt.CENTRAL_FILE_HEADER="PK";Zt.CENTRAL_DIRECTORY_END="PK";Zt.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07";Zt.ZIP64_CENTRAL_DIRECTORY_END="PK";Zt.DATA_DESCRIPTOR="PK\x07\b"});var hf=P((d1,ff)=>{"use strict";var Oi=Y(),Di=ye(),Ho=_i(),uf=$r(),da=No(),U=function(e,t){var i="",n;for(n=0;n<t;n++)i+=String.fromCharCode(e&255),e=e>>>8;return i},gy=function(e,t){var i=e;return e||(i=t?16893:33204),(i&65535)<<16},my=function(e){return(e||0)&63},pf=function(e,t,i,n,r,a){var s=e.file,o=e.compression,c=a!==Ho.utf8encode,l=Oi.transformTo("string",a(s.name)),d=Oi.transformTo("string",Ho.utf8encode(s.name)),u=s.comment,p=Oi.transformTo("string",a(u)),f=Oi.transformTo("string",Ho.utf8encode(u)),m=d.length!==s.name.length,h=f.length!==u.length,g,v,b="",y="",x="",w=s.dir,A=s.date,T={crc32:0,compressedSize:0,uncompressedSize:0};(!t||i)&&(T.crc32=e.crc32,T.compressedSize=e.compressedSize,T.uncompressedSize=e.uncompressedSize);var E=0;t&&(E|=8),!c&&(m||h)&&(E|=2048);var M=0,I=0;w&&(M|=16),r==="UNIX"?(I=798,M|=gy(s.unixPermissions,w)):(I=20,M|=my(s.dosPermissions,w)),g=A.getUTCHours(),g=g<<6,g=g|A.getUTCMinutes(),g=g<<5,g=g|A.getUTCSeconds()/2,v=A.getUTCFullYear()-1980,v=v<<4,v=v|A.getUTCMonth()+1,v=v<<5,v=v|A.getUTCDate(),m&&(y=U(1,1)+U(uf(l),4)+d,b+="up"+U(y.length,2)+y),h&&(x=U(1,1)+U(uf(p),4)+f,b+="uc"+U(x.length,2)+x);var _="";_+=`
2
+ \0`,_+=U(E,2),_+=o.magic,_+=U(g,2),_+=U(v,2),_+=U(T.crc32,4),_+=U(T.compressedSize,4),_+=U(T.uncompressedSize,4),_+=U(l.length,2),_+=U(b.length,2);var S=da.LOCAL_FILE_HEADER+_+l+b,L=da.CENTRAL_FILE_HEADER+U(I,2)+_+U(p.length,2)+"\0\0\0\0"+U(M,4)+U(n,4)+l+b+p;return{fileRecord:S,dirRecord:L}},by=function(e,t,i,n,r){var a="",s=Oi.transformTo("string",r(n));return a=da.CENTRAL_DIRECTORY_END+"\0\0\0\0"+U(e,2)+U(e,2)+U(t,4)+U(i,4)+U(s.length,2)+s,a},vy=function(e){var t="";return t=da.DATA_DESCRIPTOR+U(e.crc32,4)+U(e.compressedSize,4)+U(e.uncompressedSize,4),t};function De(e,t,i,n){Di.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Oi.inherits(De,Di);De.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,Di.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))};De.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=pf(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0};De.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,i=pf(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(i.dirRecord),t)this.push({data:vy(e),meta:{percent:100}});else for(this.push({data:i.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null};De.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i=this.bytesWritten-e,n=by(this.dirRecords.length,i,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}})};De.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()};De.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(i){t.error(i)}),this};De.prototype.resume=function(){if(!Di.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};De.prototype.error=function(e){var t=this._sources;if(!Di.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch{}return!0};De.prototype.lock=function(){Di.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()};ff.exports=De});var mf=P(gf=>{"use strict";var yy=Fo(),xy=hf(),wy=function(e,t){var i=e||t,n=yy[i];if(!n)throw new Error(i+" is not a valid compression method !");return n};gf.generateWorker=function(e,t,i){var n=new xy(t.streamFiles,i,t.platform,t.encodeFileName),r=0;try{e.forEach(function(a,s){r++;var o=wy(s.options.compression,t.compression),c=s.options.compressionOptions||t.compressionOptions||{},l=s.dir,d=s.date;s._compressWorker(o,c).withStreamInfo("file",{name:a,dir:l,date:d,comment:s.comment||"",unixPermissions:s.unixPermissions,dosPermissions:s.dosPermissions}).pipe(n)}),n.entriesCount=r}catch(a){n.error(a)}return n}});var vf=P((p1,bf)=>{"use strict";var _y=Y(),ua=ye();function zn(e,t){ua.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}_y.inherits(zn,ua);zn.prototype._bindStream=function(e){var t=this;this._stream=e,e.pause(),e.on("data",function(i){t.push({data:i,meta:{percent:0}})}).on("error",function(i){t.isPaused?this.generatedError=i:t.error(i)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})};zn.prototype.pause=function(){return ua.prototype.pause.call(this)?(this._stream.pause(),!0):!1};zn.prototype.resume=function(){return ua.prototype.resume.call(this)?(this._upstreamEnded?this.end():this._stream.resume(),!0):!1};bf.exports=zn});var kf=P((f1,Tf)=>{"use strict";var Ey=_i(),jn=Y(),_f=ye(),Sy=Gs(),Ef=Ws(),yf=qr(),Ay=yu(),Cy=mf(),xf=pn(),Ty=vf(),Sf=function(e,t,i){var n=jn.getTypeOf(t),r,a=jn.extend(i||{},Ef);a.date=a.date||new Date,a.compression!==null&&(a.compression=a.compression.toUpperCase()),typeof a.unixPermissions=="string"&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&a.unixPermissions&16384&&(a.dir=!0),a.dosPermissions&&a.dosPermissions&16&&(a.dir=!0),a.dir&&(e=Af(e)),a.createFolders&&(r=ky(e))&&Cf.call(this,r,!0);var s=n==="string"&&a.binary===!1&&a.base64===!1;(!i||typeof i.binary=="undefined")&&(a.binary=!s);var o=t instanceof yf&&t.uncompressedSize===0;(o||a.dir||!t||t.length===0)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",n="string");var c=null;t instanceof yf||t instanceof _f?c=t:xf.isNode&&xf.isStream(t)?c=new Ty(e,t):c=jn.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var l=new Ay(e,c,a);this.files[e]=l},ky=function(e){e.slice(-1)==="/"&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return t>0?e.substring(0,t):""},Af=function(e){return e.slice(-1)!=="/"&&(e+="/"),e},Cf=function(e,t){return t=typeof t!="undefined"?t:Ef.createFolders,e=Af(e),this.files[e]||Sf.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function wf(e){return Object.prototype.toString.call(e)==="[object RegExp]"}var Ly={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],i=t.slice(this.root.length,t.length),i&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(arguments.length===1)if(wf(e)){var n=e;return this.filter(function(a,s){return!s.dir&&n.test(a)})}else{var r=this.files[this.root+e];return r&&!r.dir?r:null}else e=this.root+e,Sf.call(this,e,t,i);return this},folder:function(e){if(!e)return this;if(wf(e))return this.filter(function(r,a){return a.dir&&e.test(r)});var t=this.root+e,i=Cf.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||(e.slice(-1)!=="/"&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(r,a){return a.name.slice(0,e.length)===e}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if(i=jn.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:Ey.utf8encode}),i.type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),i.type==="binarystring"&&(i.type="string"),!i.type)throw new Error("No output type specified.");jn.checkSupport(i.type),(i.platform==="darwin"||i.platform==="freebsd"||i.platform==="linux"||i.platform==="sunos")&&(i.platform="UNIX"),i.platform==="win32"&&(i.platform="DOS");var n=i.comment||this.comment||"";t=Cy.generateWorker(this,i,n)}catch(r){t=new _f("error"),t.error(r)}return new Sy(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return e=e||{},e.type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};Tf.exports=Ly});var Uo=P((h1,Rf)=>{"use strict";var Ry=Y();function Lf(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}Lf.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t=0,i;for(this.checkOffset(e),i=this.index+e-1;i>=this.index;i--)t=(t<<8)+this.byteAt(i);return this.index+=e,t},readString:function(e){return Ry.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC((e>>25&127)+1980,(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(e&31)<<1))}};Rf.exports=Lf});var $o=P((g1,Pf)=>{"use strict";var Mf=Uo(),My=Y();function zi(e){Mf.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=e[t]&255}My.inherits(zi,Mf);zi.prototype.byteAt=function(e){return this.data[this.zero+e]};zi.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.length-4;a>=0;--a)if(this.data[a]===t&&this.data[a+1]===i&&this.data[a+2]===n&&this.data[a+3]===r)return a-this.zero;return-1};zi.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.readData(4);return t===a[0]&&i===a[1]&&n===a[2]&&r===a[3]};zi.prototype.readData=function(e){if(this.checkOffset(e),e===0)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Pf.exports=zi});var Df=P((m1,Of)=>{"use strict";var If=Uo(),Py=Y();function ji(e){If.call(this,e)}Py.inherits(ji,If);ji.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)};ji.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero};ji.prototype.readAndCheckSignature=function(e){var t=this.readData(4);return e===t};ji.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Of.exports=ji});var Go=P((b1,jf)=>{"use strict";var zf=$o(),Iy=Y();function qo(e){zf.call(this,e)}Iy.inherits(qo,zf);qo.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};jf.exports=qo});var Nf=P((v1,Ff)=>{"use strict";var Bf=Go(),Oy=Y();function Wo(e){Bf.call(this,e)}Oy.inherits(Wo,Bf);Wo.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Ff.exports=Wo});var Yo=P((y1,Uf)=>{"use strict";var pa=Y(),Hf=rt(),Dy=$o(),zy=Df(),jy=Nf(),By=Go();Uf.exports=function(e){var t=pa.getTypeOf(e);return pa.checkSupport(t),t==="string"&&!Hf.uint8array?new zy(e):t==="nodebuffer"?new jy(e):Hf.uint8array?new By(pa.transformTo("uint8array",e)):new Dy(pa.transformTo("array",e))}});var Wf=P((x1,Gf)=>{"use strict";var Vo=Yo(),Rt=Y(),Fy=qr(),$f=$r(),fa=_i(),ha=Fo(),Ny=rt(),Hy=0,Uy=3,$y=function(e){for(var t in ha)if(Object.prototype.hasOwnProperty.call(ha,t)&&ha[t].magic===e)return ha[t];return null};function qf(e,t){this.options=e,this.loadOptions=t}qf.prototype={isEncrypted:function(){return(this.bitFlag&1)===1},useUTF8:function(){return(this.bitFlag&2048)===2048},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(t=$y(this.compressionMethod),t===null)throw new Error("Corrupted zip : compression "+Rt.pretty(this.compressionMethod)+" unknown (inner file : "+Rt.transformTo("string",this.fileName)+")");this.decompressed=new Fy(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(this.externalFileAttributes&16),e===Hy&&(this.dosPermissions=this.externalFileAttributes&63),e===Uy&&(this.unixPermissions=this.externalFileAttributes>>16&65535),!this.dir&&this.fileNameStr.slice(-1)==="/"&&(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=Vo(this.extraFields[1].value);this.uncompressedSize===Rt.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===Rt.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===Rt.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===Rt.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t=e.index+this.extraFieldsLength,i,n,r;for(this.extraFields||(this.extraFields={});e.index+4<t;)i=e.readInt(2),n=e.readInt(2),r=e.readData(n),this.extraFields[i]={id:i,length:n,value:r};e.setIndex(t)},handleUTF8:function(){var e=Ny.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=fa.utf8decode(this.fileName),this.fileCommentStr=fa.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(t!==null)this.fileNameStr=t;else{var i=Rt.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(n!==null)this.fileCommentStr=n;else{var r=Rt.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=Vo(e.value);return t.readInt(1)!==1||$f(this.fileName)!==t.readInt(4)?null:fa.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=Vo(e.value);return t.readInt(1)!==1||$f(this.fileComment)!==t.readInt(4)?null:fa.utf8decode(t.readData(e.length-5))}return null}};Gf.exports=qf});var Kf=P((w1,Vf)=>{"use strict";var qy=Yo(),dt=Y(),ze=No(),Gy=Wf(),Wy=rt();function Yf(e){this.files=[],this.loadOptions=e}Yf.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+dt.pretty(t)+", expected "+dt.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4),r=n===t;return this.reader.setIndex(i),r},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=Wy.uint8array?"uint8array":"array",i=dt.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e=this.zip64EndOfCentralSize-44,t=0,i,n,r;t<e;)i=this.reader.readInt(2),n=this.reader.readInt(4),r=this.reader.readData(n),this.zip64ExtensibleData[i]={id:i,length:n,value:r}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(ze.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(ze.CENTRAL_FILE_HEADER);)e=new Gy({zip64:this.zip64},this.loadOptions),e.readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(ze.CENTRAL_DIRECTORY_END);if(e<0){var t=!this.isSignature(0,ze.LOCAL_FILE_HEADER);throw t?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(e);var i=e;if(this.checkSignature(ze.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===dt.MAX_VALUE_16BITS||this.diskWithCentralDirStart===dt.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===dt.MAX_VALUE_16BITS||this.centralDirRecords===dt.MAX_VALUE_16BITS||this.centralDirSize===dt.MAX_VALUE_32BITS||this.centralDirOffset===dt.MAX_VALUE_32BITS){if(this.zip64=!0,e=this.reader.lastIndexOfSignature(ze.ZIP64_CENTRAL_DIRECTORY_LOCATOR),e<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(ze.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,ze.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(ze.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(ze.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var r=i-n;if(r>0)this.isSignature(i,ze.CENTRAL_FILE_HEADER)||(this.reader.zero=r);else if(r<0)throw new Error("Corrupted zip: missing "+Math.abs(r)+" bytes.")},prepareReader:function(e){this.reader=qy(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}};Vf.exports=Yf});var Jf=P((_1,Zf)=>{"use strict";var Ko=Y(),ga=yi(),Yy=_i(),Vy=Kf(),Ky=Ks(),Xf=pn();function Xy(e){return new ga.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new Ky);n.on("error",function(r){i(r)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}Zf.exports=function(e,t){var i=this;return t=Ko.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:Yy.utf8decode}),Xf.isNode&&Xf.isStream(e)?ga.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):Ko.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(n){var r=new Vy(t);return r.load(n),r}).then(function(r){var a=[ga.Promise.resolve(r)],s=r.files;if(t.checkCRC32)for(var o=0;o<s.length;o++)a.push(Xy(s[o]));return ga.Promise.all(a)}).then(function(r){for(var a=r.shift(),s=a.files,o=0;o<s.length;o++){var c=s[o],l=c.fileNameStr,d=Ko.resolve(c.fileNameStr);i.file(d,c.decompressed,{binary:!0,optimizedBinaryString:!0,date:c.date,dir:c.dir,comment:c.fileCommentStr.length?c.fileCommentStr:null,unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions,createFolders:t.createFolders}),c.dir||(i.file(d).unsafeOriginalName=l)}return a.zipComment.length&&(i.comment=a.zipComment),i})}});var eh=P((E1,Qf)=>{"use strict";function Te(){if(!(this instanceof Te))return new Te;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new Te;for(var t in this)typeof this[t]!="function"&&(e[t]=this[t]);return e}}Te.prototype=kf();Te.prototype.loadAsync=Jf();Te.support=rt();Te.defaults=Ws();Te.version="3.10.1";Te.loadAsync=function(e,t){return new Te().loadAsync(e,t)};Te.external=yi();Qf.exports=Te});import{Application as Px}from"pixi.js";var yt={};function lr(e,t,i=!1){yt[e]||(yt[e]=[]),yt[e].push({fn:t,once:i})}function Qa(e,t){if(yt[e]){if(!t){delete yt[e];return}yt[e]=yt[e].filter(i=>i.fn!==t)}}function cr(e,...t){let i=yt[e];if(i)for(let n of[...i])n.fn(...t),n.once&&Qa(e,n.fn)}function _e(e,t){lr(e,t,!0)}var te=null,Me=[],si=null;function pc(e){te=e,Me=[],si!==null&&(clearTimeout(si),si=null)}function fc(){var e,t,i;return{endpoint:(te==null?void 0:te.endpoint)||"",transport:(te==null?void 0:te.transport)||"beacon",batchSize:(e=te==null?void 0:te.batchSize)!=null?e:10,flushIntervalMs:(t=te==null?void 0:te.flushIntervalMs)!=null?t:300,maxQueue:(i=te==null?void 0:te.maxQueue)!=null?i:200,debug:!!(te!=null&&te.debug)}}async function dc(e,t,i,n){let r=JSON.stringify(t);if(i==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(e,new Blob([r],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,t);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",t)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function es(e,t){let i=fc();if(t&&i.endpoint){if(Me.push(e),Me.length>i.maxQueue&&(Me=Me.slice(Me.length-i.maxQueue)),Me.length>=i.batchSize){uc();return}si===null&&(si=window.setTimeout(()=>{si=null,uc()},i.flushIntervalMs))}}async function uc(){let e=fc();if(!e.endpoint||Me.length===0)return;let t=Me.splice(0,e.batchSize);await dc(e.endpoint,{events:t},e.transport,e.debug),Me.length>0&&await dc(e.endpoint,{events:Me.splice(0,e.batchSize)},e.transport,e.debug)}function hc(e){return Math.max(0,Math.min(1,e))}function fg(e){let t=String(e!=null?e:"power2.out");if(t==="linear")return i=>i;if(t==="sine.inOut")return i=>.5-Math.cos(Math.PI*i)/2;if(t==="power2.out"||t==="easeOutQuad")return i=>1-(1-i)*(1-i);if(t.startsWith("back.out")){let i=t.match(/back\.out\(([\d.]+)\)/),n=i?Number(i[1]):1.8;return r=>1+(n+1)*Math.pow(r-1,3)+n*Math.pow(r-1,2)}return i=>1-(1-i)*(1-i)}function tn(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function hg(e,t){let i=e==null?void 0:e[t];return typeof i=="number"?i:0}function gc(e,t,i){try{e[t]=i}catch{}}function gg(e){let t=e==null?void 0:e.scale;if(!t)return null;let i=typeof t.x=="number"?t.x:1,n=typeof t.y=="number"?t.y:1;return{x:i,y:n}}function mc(e,t){let i=e==null?void 0:e.scale;if(i)try{typeof i.set=="function"?i.set(t.x,t.y):(typeof i.x=="number"&&(i.x=t.x),typeof i.y=="number"&&(i.y=t.y))}catch{}}function bc(e,t){let i=gg(e);if(!i)return{from:null,to:null};let n=null,r=null;return typeof t.scale=="number"?(n=t.scale,r=t.scale):t.scale&&typeof t.scale=="object"&&(typeof t.scale.x=="number"&&(n=t.scale.x),typeof t.scale.y=="number"&&(r=t.scale.y)),typeof t.scaleX=="number"&&(n=t.scaleX),typeof t.scaleY=="number"&&(r=t.scaleY),n===null&&r===null?{from:null,to:null}:{from:{x:i.x,y:i.y},to:{x:n!=null?n:i.x,y:r!=null?r:i.y}}}function vc(){let e=new Set,t=new WeakMap,i=null,n=()=>{if(i!=null)return;i=requestAnimationFrame(()=>{i=null,o(),e.size>0&&n()})},r=d=>{var p;e.add(d);let u=(p=t.get(d.target))!=null?p:new Set;u.add(d),t.set(d.target,u),n()},a=d=>{e.delete(d);let u=t.get(d.target);u&&(u.delete(d),u.size===0&&t.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var u,p;let d=tn();for(let f of Array.from(e)){if(f.killed||f.paused)continue;let m=d-f.startMs-f.delayMs;if(m<0)continue;let h=f.durationMs>0?m/f.durationMs:1,g=hc(h),v=f.repeat>=0?f.repeat+1:1,b=f.repeat>0?Math.min(Math.floor(h),v-1):0;if(f.repeat>0&&h>=1){let w=h-b;g=hc(w)}let y=f.ease(g);f.yoyo&&b%2===1&&(y=1-y);for(let w of f.props)gc(f.target,w.key,w.from+(w.to-w.from)*y);f.scaleFrom&&f.scaleTo&&mc(f.target,{x:f.scaleFrom.x+(f.scaleTo.x-f.scaleFrom.x)*y,y:f.scaleFrom.y+(f.scaleTo.y-f.scaleFrom.y)*y});try{(u=f.onUpdate)==null||u.call(f)}catch{}if(h>=v){s(f);try{(p=f.onComplete)==null||p.call(f)}catch{}}}},c=(d,u,p)=>{var w;let f=Math.max(0,(typeof u.duration=="number"?u.duration:.5)*1e3),m=Math.max(0,(typeof u.delay=="number"?u.delay:0)*1e3+((w=p==null?void 0:p.delayMsOverride)!=null?w:0)),h=fg(u.ease),g=typeof u.repeat=="number"?Math.max(0,u.repeat|0):0,v=u.yoyo===!0,b=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),y=[];for(let A of Object.keys(u)){if(b.has(A))continue;let T=u[A];typeof T=="number"&&y.push({key:A,from:hg(d,A),to:T})}let x=bc(d,u);return{target:d,startMs:tn(),delayMs:m,durationMs:f,ease:h,props:y,scaleFrom:x.from,scaleTo:x.to,repeat:g,yoyo:v,onUpdate:typeof u.onUpdate=="function"?u.onUpdate:void 0,onComplete:typeof u.onComplete=="function"?u.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},l={to(d,u){let p=c(d,u);return r(p),{kill:()=>s(p),pause:()=>{p.paused||(p.paused=!0,p.pauseAtMs=tn())},resume:()=>{var h;if(!p.paused)return;let f=(h=p.pauseAtMs)!=null?h:tn(),m=tn()-f;p.startMs+=m,p.paused=!1,p.pauseAtMs=null},isActive:()=>!p.killed&&!p.paused}},fromTo(d,u,p){return l.set(d,u),l.to(d,p)},set(d,u){if(!d||!u)return;for(let f of Object.keys(u)){let m=u[f];f==="scale"||f==="scaleX"||f==="scaleY"||typeof m=="number"&&gc(d,f,m)}let p=bc(d,u);p.to&&mc(d,p.to)},killTweensOf(d){let u=t.get(d);if(u)for(let p of Array.from(u))s(p)},timeline(d={}){let u=[],p=0,f=!1,m=[],h=b=>{if(typeof b=="number")return Math.max(0,b*1e3);let y=typeof b=="string"?b.trim():"";return y.startsWith("+=")?p+Math.max(0,Number(y.slice(2))*1e3||0):y?Math.max(0,Number(y)*1e3||0):p},g=b=>{u.push(b);let y=Math.max(0,(typeof b.vars.duration=="number"?b.vars.duration:.5)*1e3);p=Math.max(p,b.atMs+y)},v={to(b,y,x){return g({kind:"to",target:b,vars:y,atMs:h(x)}),v},fromTo(b,y,x,w){return g({kind:"fromTo",target:b,vars:x,from:y,atMs:h(w)}),v},play(){var b,y;if(f)return v;f=!0,m=[];for(let x of u)x.kind==="fromTo"&&l.set(x.target,(b=x.from)!=null?b:{}),m.push(l.to(x.target,{...x.vars,delay:x.atMs/1e3+((y=x.vars.delay)!=null?y:0)}));return v},pause(){for(let b of m)b.pause();return v},kill(){for(let b of m)b.kill();m=[],f=!1}};return d.paused||v.play(),v}};return l}function yc(){if(typeof window=="undefined")return;let e=window;if(!e.gsap)try{e.gsap=vc()}catch{}}var Ee=0,mg=Ee++,xc=Ee++,wc=Ee++,_c=Ee++,Ec=Ee++,Sc=Ee++,Ac=Ee++,Cc=Ee++,Tc=Ee++,kc=Ee++,Lc=Ee++,Rc=Ee++,K=mg;function Mc(){return K===xc}function Pc(){return K===wc}function Ic(){return K===_c}function Oc(){return K===Ec}function oi(){return K===Sc}function li(){return K===Ac}function Dc(){return K===Cc}function zc(){return K===Tc}function jc(){return K===kc}function ts(){return K===Lc}function is(){return K===Rc}function Bc(){let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",t=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(e==="mraid")try{mraid.getState(),K=xc;return}catch{}else if(e==="dapi")try{dapi.isReady(),K=wc;return}catch{}if(t==="facebook")try{typeof FbPlayableAd!="undefined"&&(K=_c)}catch{}else if(t==="google")try{typeof ExitApi!="undefined"&&(K=Ec)}catch{}else if(t==="mintegral")window.gameReady&&(K=Sc);else if(t==="tapjoy")window.TJ_API&&(K=Ac);else if(t==="tiktok")window.openAppStore&&(K=Cc);else if(t==="smadex")try{window.smxTracking&&(K=Tc)}catch{}else if(t==="snapchat")try{window.ScPlayableAd&&(K=kc)}catch{}else t==="vungle"?K=Lc:(e==="nucleo"||t==="nucleo")&&(K=Rc)}import ns from"lottie-web";var Fc=ns;typeof window!="undefined"&&(window.lottie=ns,window.__baseLottie=ns);function ie(e,t){let i=(r,a)=>a===0?r:i(a,r%a),n=i(e,t);return`${e/n}:${t/n}`}var C0=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ie(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ie(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ie(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ie(360,780)}],T0=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ie(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ie(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ie(412,915)}],k0=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ie(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ie(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ie(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ie(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ie(800,1280)}],rs=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:ie(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ie(768,1024),mraidScale:.7}];var Nc=[...rs],Hc=[{category:"playable",label:"Playable Ad",devices:rs}],as=rs[0];function ci(e){return Nc.find(t=>t.id===e)||as}function L0(e){return Nc.filter(t=>t.category===e)}var dr=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
3
3
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects" style="left:16px; top:72px;">
4
4
  <div class="scene-panel-header" data-panel-handle>
5
5
  <div class="panel-title">
@@ -27,7 +27,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
27
27
  <div class="scene-object-list" data-object-list></div>
28
28
  </div>
29
29
  </div>
30
- `}initialize(t,i){var r,a,s,o,c;this.options=i,this.root=t.querySelector('[data-panel="scene-objects"]'),this.listContainer=(r=this.root)==null?void 0:r.querySelector("[data-object-list]"),this.searchInput=(a=this.root)==null?void 0:a.querySelector("#scene-object-search"),(s=this.searchInput)==null||s.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let l=window.localStorage.getItem(this.getScreenFilterStorageKey());l&&(this.screenFilter=l)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let l=n.value||"all";this.screenFilter=l;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}this.refreshObjects()})}(c=this.root)==null||c.addEventListener("click",l=>{let d=l.target;if(!d)return;let u=d.closest("[data-object-id]");if(!u)return;let p=u.dataset.objectId;p&&this.select(p)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(t){if(this.selectedId=t,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(n=>{n.classList.toggle("selected",n.dataset.objectId===t)})}refreshObjects(){var d;if(!this.listContainer)return;let t=window.getEditableObjectList,i=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof t!="function"){this.scheduleRetry();return}let r=t();if(!Array.isArray(r)||r.length===0){let u=window.__editableObjectConfigs;u&&typeof u.keys=="function"&&(r=Array.from(u.keys()))}if(!Array.isArray(r)||r.length===0){this.scheduleRetry();return}let a=(((d=this.searchInput)==null?void 0:d.value)||"").trim().toLowerCase(),s=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(s.map(u=>[u,[]])),c=Object.fromEntries(s.map(u=>[u,[]]));r.forEach(u=>{var P,M,_,S;let p=typeof i=="function"?i(u):null;if(!p){let L=window.__editableObjectConfigs;L&&typeof L.get=="function"&&(p=(P=L.get(u))!=null?P:null)}let f=(((M=p==null?void 0:p.identity)==null?void 0:M.category)||"scene").toString(),b=(((_=p==null?void 0:p.identity)==null?void 0:_.id)||u).toString(),h=f.toLowerCase(),g=b.toLowerCase(),m=h.includes("ui")||g.startsWith("ui")||g.includes("label"),v=this.formatDisplayName(b||u),y=((S=p==null?void 0:p.render)==null?void 0:S.visible)===!1||(p==null?void 0:p.enabled)===!1,x=this.getObjectType(p),w={id:u,label:v,category:f,isUi:m,isUnused:y,objectType:x},C=this.inferScreen(w.id,p);if(this.screenFilter!=="all"&&C!==this.screenFilter||!(!a||w.id.toLowerCase().includes(a)||w.label.toLowerCase().includes(a)))return;(w.isUnused?c:o)[C].push(w)});let l={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
30
+ `}initialize(t,i){var r,a,s,o,c;this.options=i,this.root=t.querySelector('[data-panel="scene-objects"]'),this.listContainer=(r=this.root)==null?void 0:r.querySelector("[data-object-list]"),this.searchInput=(a=this.root)==null?void 0:a.querySelector("#scene-object-search"),(s=this.searchInput)==null||s.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let l=window.localStorage.getItem(this.getScreenFilterStorageKey());l&&(this.screenFilter=l)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let l=n.value||"all";this.screenFilter=l;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}this.refreshObjects()})}(c=this.root)==null||c.addEventListener("click",l=>{let d=l.target;if(!d)return;let u=d.closest("[data-object-id]");if(!u)return;let p=u.dataset.objectId;p&&this.select(p)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(t){if(this.selectedId=t,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(n=>{n.classList.toggle("selected",n.dataset.objectId===t)})}refreshObjects(){var d;if(!this.listContainer)return;let t=window.getEditableObjectList,i=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof t!="function"){this.scheduleRetry();return}let r=t();if(!Array.isArray(r)||r.length===0){let u=window.__editableObjectConfigs;u&&typeof u.keys=="function"&&(r=Array.from(u.keys()))}if(!Array.isArray(r)||r.length===0){this.scheduleRetry();return}let a=(((d=this.searchInput)==null?void 0:d.value)||"").trim().toLowerCase(),s=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(s.map(u=>[u,[]])),c=Object.fromEntries(s.map(u=>[u,[]]));r.forEach(u=>{var M,I,_,S;let p=typeof i=="function"?i(u):null;if(!p){let L=window.__editableObjectConfigs;L&&typeof L.get=="function"&&(p=(M=L.get(u))!=null?M:null)}let f=(((I=p==null?void 0:p.identity)==null?void 0:I.category)||"scene").toString(),m=(((_=p==null?void 0:p.identity)==null?void 0:_.id)||u).toString(),h=f.toLowerCase(),g=m.toLowerCase(),v=h.includes("ui")||g.startsWith("ui")||g.includes("label"),b=this.formatDisplayName(m||u),y=((S=p==null?void 0:p.render)==null?void 0:S.visible)===!1||(p==null?void 0:p.enabled)===!1,x=this.getObjectType(p),w={id:u,label:b,category:f,isUi:v,isUnused:y,objectType:x},A=this.inferScreen(w.id,p);if(this.screenFilter!=="all"&&A!==this.screenFilter||!(!a||w.id.toLowerCase().includes(a)||w.label.toLowerCase().includes(a)))return;(w.isUnused?c:o)[A].push(w)});let l={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
31
31
  ${s.map(u=>this.renderGroup(l[u],[...o[u],...c[u]])).join("")}
32
32
  `,this.setSelected(this.selectedId)}formatDisplayName(t){let i=t.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return i=i.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),i}inferScreen(t,i){var o,c;let n=window.__HANDLER_SCREEN_INDEX,r=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[t];if(r==="loading"||r==="start"||r==="gameplay"||r==="tutorial"||r==="endgame")return r;let a=(((c=i==null?void 0:i.identity)==null?void 0:c.id)||"").toString(),s=`${t} ${a}`.toLowerCase();return s.includes("loading")?"loading":s.includes("start")?"start":s.includes("tutorial")?"tutorial":s.includes("endgame")||s.includes("end_card")||s.includes("endcard")?"endgame":"gameplay"}getObjectType(t){var i,n,r,a,s,o,c,l,d;return t?(i=t.ui)!=null&&i.text?"text":(a=(r=(n=t.render)==null?void 0:n.asset)==null?void 0:r.path)!=null&&a.endsWith(".json")?"animation":((o=(s=t.render)==null?void 0:s.asset)==null?void 0:o.type)==="image"||(c=t.render)!=null&&c.texture?"sprite":(d=(l=t.gameplay)==null?void 0:l.tuning)!=null&&d.panel_width?"graphics":"container":"container"}renderGroup(t,i){if(!i.length)return"";let n=window.getEditableObjectConfig,r=i.map(a=>{var d,u;let s=typeof n=="function"?n(a.id):null;if(!s){let p=window.__editableObjectConfigs;p&&typeof p.get=="function"&&(s=(d=p.get(a.id))!=null?d:null)}let o=this.getTypeIconByType(a.objectType),c=this.getAssetPreview(s),l=(u=s==null?void 0:s.ui)!=null&&u.text?`"${s.ui.text.substring(0,12)}${s.ui.text.length>12?"...":""}"`:"";return`
33
33
  <button class="scene-object-item ${a.isUnused?"unused":""}" data-object-id="${a.id}">
@@ -42,7 +42,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
42
42
  ${r}
43
43
  </div>
44
44
  </div>
45
- `}getTypeIconByType(t){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[t]||"\u{1F4E6}"}getTypeIcon(t){var n,r,a,s,o,c;if(!t)return"\u{1F4E6}";if((n=t.render)!=null&&n.texture){let l=t.render.texture;return l.includes("button")?"\u{1F518}":l.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((r=t.ui)!=null&&r.text)return"\u{1F4DD}";if(((a=t.identity)==null?void 0:a.category)==="ui")return"\u{1F3A8}";if(t.effects||(o=(s=t.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(t.audio)return"\u{1F50A}";let i=((c=t.identity)==null?void 0:c.id)||"";return i.includes("background")?"\u{1F5BC}\uFE0F":i.includes("character")?"\u{1F464}":i.includes("key")?"\u{1F511}":i.includes("draggable")?"\u{1F3AF}":i.includes("machine")?"\u2699\uFE0F":i.includes("tutorial")||i.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(t){var n;if(!t)return null;let i=(n=t.render)==null?void 0:n.texture;return i&&(i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg"))?i.startsWith("library/")||i.startsWith("/raw/")?`/raw/${i.replace(/^\/raw\//,"")}`:`/raw/${i}`:null}getColorIndicator(t){var n,r,a,s;if(!t)return"";let i=((n=t.render)==null?void 0:n.background_color)||((a=(r=t.gameplay)==null?void 0:r.tuning)==null?void 0:a.panel_bg_color)||((s=t.ui)==null?void 0:s.backgroundColor);return i?`<span class="scene-object-color-dot" style="background-color: ${i}" title="${i}"></span>`:""}getMetadata(t){var n,r,a,s;if(!t)return"";let i=[];return((n=t.render)==null?void 0:n.visible)===!1&&i.push("hidden"),((r=t.render)==null?void 0:r.z_index)!==void 0&&i.push(`z:${t.render.z_index}`),((a=t.interaction)!=null&&a.clickable||(s=t.ui)!=null&&s.button)&&i.push("clickable"),i.length>0?i.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(t){var i;this.selectedId=t,this.setSelected(t),(i=this.options)==null||i.onSelect(t)}};var dr=class{constructor(){this.root=null;this.infoEls={};this.options=null}render(){return`
45
+ `}getTypeIconByType(t){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[t]||"\u{1F4E6}"}getTypeIcon(t){var n,r,a,s,o,c;if(!t)return"\u{1F4E6}";if((n=t.render)!=null&&n.texture){let l=t.render.texture;return l.includes("button")?"\u{1F518}":l.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((r=t.ui)!=null&&r.text)return"\u{1F4DD}";if(((a=t.identity)==null?void 0:a.category)==="ui")return"\u{1F3A8}";if(t.effects||(o=(s=t.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(t.audio)return"\u{1F50A}";let i=((c=t.identity)==null?void 0:c.id)||"";return i.includes("background")?"\u{1F5BC}\uFE0F":i.includes("character")?"\u{1F464}":i.includes("key")?"\u{1F511}":i.includes("draggable")?"\u{1F3AF}":i.includes("machine")?"\u2699\uFE0F":i.includes("tutorial")||i.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(t){var n;if(!t)return null;let i=(n=t.render)==null?void 0:n.texture;return i&&(i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg"))?i.startsWith("library/")||i.startsWith("/raw/")?`/raw/${i.replace(/^\/raw\//,"")}`:`/raw/${i}`:null}getColorIndicator(t){var n,r,a,s;if(!t)return"";let i=((n=t.render)==null?void 0:n.background_color)||((a=(r=t.gameplay)==null?void 0:r.tuning)==null?void 0:a.panel_bg_color)||((s=t.ui)==null?void 0:s.backgroundColor);return i?`<span class="scene-object-color-dot" style="background-color: ${i}" title="${i}"></span>`:""}getMetadata(t){var n,r,a,s;if(!t)return"";let i=[];return((n=t.render)==null?void 0:n.visible)===!1&&i.push("hidden"),((r=t.render)==null?void 0:r.z_index)!==void 0&&i.push(`z:${t.render.z_index}`),((a=t.interaction)!=null&&a.clickable||(s=t.ui)!=null&&s.button)&&i.push("clickable"),i.length>0?i.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(t){var i;this.selectedId=t,this.setSelected(t),(i=this.options)==null||i.onSelect(t)}};var ur=class{constructor(){this.root=null;this.infoEls={};this.options=null}render(){return`
46
46
  <div class="scene-panel scene-tools panel-accent-amber" data-panel="scene-tools">
47
47
  <div class="scene-panel-header" data-panel-handle>
48
48
  <div class="panel-title">
@@ -201,7 +201,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
201
201
  </div>
202
202
  </div>
203
203
  </div>
204
- `}initialize(t,i){var g,m,v,y,x,w,C,k,E,P,M,_,S,L,R,O;this.options=i,this.root=t.querySelector('[data-panel="scene-tools"]');let n=(g=this.root)==null?void 0:g.querySelector("#debug-highlight-object");n==null||n.addEventListener("change",()=>{var A;return(A=this.options)==null?void 0:A.onHighlightObject(!!n.checked)});let r=(m=this.root)==null?void 0:m.querySelector("#debug-highlight-anchor");r==null||r.addEventListener("change",()=>{var A;return(A=this.options)==null?void 0:A.onHighlightAnchor(!!r.checked)});let a=(v=this.root)==null?void 0:v.querySelector("#debug-nudge-enabled"),s=(y=this.root)==null?void 0:y.querySelector("#debug-nudge-controls");if(a&&s){let A=()=>s.classList.toggle("hidden",!a.checked);a.addEventListener("change",A),A()}Array.from(((x=this.root)==null?void 0:x.querySelectorAll(".debug-arrow-btn"))||[]).forEach(A=>{A.addEventListener("click",()=>{var T,D,$,ue;switch(A.dataset.nudge){case"up":(T=this.options)==null||T.onNudge(0,-1);break;case"down":(D=this.options)==null||D.onNudge(0,1);break;case"left":($=this.options)==null||$.onNudge(-1,0);break;case"right":(ue=this.options)==null||ue.onNudge(1,0);break;default:break}})});let l=(()=>{var z;let A=window.getEditableEngineConfig;if(typeof A=="function"){let T=A();return(z=T==null?void 0:T.splash)!=null?z:{}}return{}})(),d=(w=this.root)==null?void 0:w.querySelector("#debug-loading-text"),u=(C=this.root)==null?void 0:C.querySelector("#debug-loading-text-scale"),p=(k=this.root)==null?void 0:k.querySelector("#debug-loading-text-scale-value"),f=(E=this.root)==null?void 0:E.querySelector("#debug-splash-on-start"),b=(P=this.root)==null?void 0:P.querySelector("#debug-show-splash");if(d&&(d.value=typeof l.loading_text=="string"&&l.loading_text.length>0?l.loading_text:"Y\xFCkleniyor...",d.addEventListener("input",()=>{var A,z;(z=(A=this.options)==null?void 0:A.onUpdateSplash)==null||z.call(A,{loading_text:d.value})})),u){let A=typeof l.loading_text_scale=="number"?l.loading_text_scale:.6;u.value=A.toString(),p&&(p.textContent=A.toFixed(2)),u.addEventListener("input",()=>{var T,D;let z=Number(u.value);p&&(p.textContent=Number.isFinite(z)?z.toFixed(2):"0.6"),Number.isFinite(z)&&((D=(T=this.options)==null?void 0:T.onUpdateSplash)==null||D.call(T,{loading_text_scale:z}))})}f&&(f.checked=!!l.show_on_start,f.addEventListener("change",()=>{var A,z;(z=(A=this.options)==null?void 0:A.onUpdateSplash)==null||z.call(A,{show_on_start:!!f.checked})})),b==null||b.addEventListener("click",()=>{var A,z;(z=(A=this.options)==null?void 0:A.onShowSplash)==null||z.call(A)}),this.infoEls={instance:(M=this.root)==null?void 0:M.querySelector("#debug-instance-id"),worldX:(_=this.root)==null?void 0:_.querySelector("#debug-world-x"),worldY:(S=this.root)==null?void 0:S.querySelector("#debug-world-y"),anchorX:(L=this.root)==null?void 0:L.querySelector("#debug-config-x"),anchorY:(R=this.root)==null?void 0:R.querySelector("#debug-config-y")};let h=(O=this.root)==null?void 0:O.querySelector("[data-advanced-toggle]");h&&h.addEventListener("click",()=>{let A=h.closest(".debug-collapsible");A==null||A.classList.toggle("collapsed")})}getNudgeStep(){var n,r;let t=(n=this.root)==null?void 0:n.querySelector("#debug-nudge-step"),i=Number((r=t==null?void 0:t.value)!=null?r:10);return Number.isFinite(i)?i:10}updateInfo(t){if(!t){this.infoEls.instance&&(this.infoEls.instance.textContent="\u2014"),this.infoEls.worldX&&(this.infoEls.worldX.textContent="0"),this.infoEls.worldY&&(this.infoEls.worldY.textContent="0"),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent="\u2014"),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent="\u2014");return}this.infoEls.instance&&(this.infoEls.instance.textContent=t.instanceId),this.infoEls.worldX&&(this.infoEls.worldX.textContent=t.worldX.toFixed(1)),this.infoEls.worldY&&(this.infoEls.worldY.textContent=t.worldY.toFixed(1)),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent=t.anchorX==null?"\u2014":t.anchorX.toFixed(1)),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent=t.anchorY==null?"\u2014":t.anchorY.toFixed(1))}};var ur=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(t,i){let n=t||{},r=i||{},a={slots:Array.isArray(r.slots)?[...r.slots]:[],libraryAssets:typeof r.libraryAssets=="object"&&r.libraryAssets?{...r.libraryAssets}:{},categories:Array.isArray(r.categories)?[...r.categories]:[]},s=Array.isArray(n.slots)?n.slots:[];if(s.length>0&&a.slots.length>0)for(let l of a.slots){let d=s.find(u=>(u==null?void 0:u.slotId)&&u.slotId===(l==null?void 0:l.slotId));d!=null&&d.currentAsset&&d.currentAsset!==(l==null?void 0:l.currentAsset)&&(l.currentAsset=d.currentAsset)}let o=n.libraryAssets||{};for(let[l,d]of Object.entries(o)){if(!Array.isArray(d))continue;a.libraryAssets[l]||(a.libraryAssets[l]=[]);let u=new Set((a.libraryAssets[l]||[]).map(p=>p==null?void 0:p.filename));for(let p of d){let f=p==null?void 0:p.filename;!f||u.has(f)||(a.libraryAssets[l].unshift(p),u.add(f))}}let c=new Set(a.categories||[]);for(let l of n.categories||[])typeof l=="string"&&c.add(l);return a.categories=Array.from(c),a}render(){return`
204
+ `}initialize(t,i){var g,v,b,y,x,w,A,T,E,M,I,_,S,L,R,O;this.options=i,this.root=t.querySelector('[data-panel="scene-tools"]');let n=(g=this.root)==null?void 0:g.querySelector("#debug-highlight-object");n==null||n.addEventListener("change",()=>{var C;return(C=this.options)==null?void 0:C.onHighlightObject(!!n.checked)});let r=(v=this.root)==null?void 0:v.querySelector("#debug-highlight-anchor");r==null||r.addEventListener("change",()=>{var C;return(C=this.options)==null?void 0:C.onHighlightAnchor(!!r.checked)});let a=(b=this.root)==null?void 0:b.querySelector("#debug-nudge-enabled"),s=(y=this.root)==null?void 0:y.querySelector("#debug-nudge-controls");if(a&&s){let C=()=>s.classList.toggle("hidden",!a.checked);a.addEventListener("change",C),C()}Array.from(((x=this.root)==null?void 0:x.querySelectorAll(".debug-arrow-btn"))||[]).forEach(C=>{C.addEventListener("click",()=>{var k,D,$,ue;switch(C.dataset.nudge){case"up":(k=this.options)==null||k.onNudge(0,-1);break;case"down":(D=this.options)==null||D.onNudge(0,1);break;case"left":($=this.options)==null||$.onNudge(-1,0);break;case"right":(ue=this.options)==null||ue.onNudge(1,0);break;default:break}})});let l=(()=>{var z;let C=window.getEditableEngineConfig;if(typeof C=="function"){let k=C();return(z=k==null?void 0:k.splash)!=null?z:{}}return{}})(),d=(w=this.root)==null?void 0:w.querySelector("#debug-loading-text"),u=(A=this.root)==null?void 0:A.querySelector("#debug-loading-text-scale"),p=(T=this.root)==null?void 0:T.querySelector("#debug-loading-text-scale-value"),f=(E=this.root)==null?void 0:E.querySelector("#debug-splash-on-start"),m=(M=this.root)==null?void 0:M.querySelector("#debug-show-splash");if(d&&(d.value=typeof l.loading_text=="string"&&l.loading_text.length>0?l.loading_text:"Y\xFCkleniyor...",d.addEventListener("input",()=>{var C,z;(z=(C=this.options)==null?void 0:C.onUpdateSplash)==null||z.call(C,{loading_text:d.value})})),u){let C=typeof l.loading_text_scale=="number"?l.loading_text_scale:.6;u.value=C.toString(),p&&(p.textContent=C.toFixed(2)),u.addEventListener("input",()=>{var k,D;let z=Number(u.value);p&&(p.textContent=Number.isFinite(z)?z.toFixed(2):"0.6"),Number.isFinite(z)&&((D=(k=this.options)==null?void 0:k.onUpdateSplash)==null||D.call(k,{loading_text_scale:z}))})}f&&(f.checked=!!l.show_on_start,f.addEventListener("change",()=>{var C,z;(z=(C=this.options)==null?void 0:C.onUpdateSplash)==null||z.call(C,{show_on_start:!!f.checked})})),m==null||m.addEventListener("click",()=>{var C,z;(z=(C=this.options)==null?void 0:C.onShowSplash)==null||z.call(C)}),this.infoEls={instance:(I=this.root)==null?void 0:I.querySelector("#debug-instance-id"),worldX:(_=this.root)==null?void 0:_.querySelector("#debug-world-x"),worldY:(S=this.root)==null?void 0:S.querySelector("#debug-world-y"),anchorX:(L=this.root)==null?void 0:L.querySelector("#debug-config-x"),anchorY:(R=this.root)==null?void 0:R.querySelector("#debug-config-y")};let h=(O=this.root)==null?void 0:O.querySelector("[data-advanced-toggle]");h&&h.addEventListener("click",()=>{let C=h.closest(".debug-collapsible");C==null||C.classList.toggle("collapsed")})}getNudgeStep(){var n,r;let t=(n=this.root)==null?void 0:n.querySelector("#debug-nudge-step"),i=Number((r=t==null?void 0:t.value)!=null?r:10);return Number.isFinite(i)?i:10}updateInfo(t){if(!t){this.infoEls.instance&&(this.infoEls.instance.textContent="\u2014"),this.infoEls.worldX&&(this.infoEls.worldX.textContent="0"),this.infoEls.worldY&&(this.infoEls.worldY.textContent="0"),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent="\u2014"),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent="\u2014");return}this.infoEls.instance&&(this.infoEls.instance.textContent=t.instanceId),this.infoEls.worldX&&(this.infoEls.worldX.textContent=t.worldX.toFixed(1)),this.infoEls.worldY&&(this.infoEls.worldY.textContent=t.worldY.toFixed(1)),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent=t.anchorX==null?"\u2014":t.anchorX.toFixed(1)),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent=t.anchorY==null?"\u2014":t.anchorY.toFixed(1))}};var pr=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(t,i){let n=t||{},r=i||{},a={slots:Array.isArray(r.slots)?[...r.slots]:[],libraryAssets:typeof r.libraryAssets=="object"&&r.libraryAssets?{...r.libraryAssets}:{},categories:Array.isArray(r.categories)?[...r.categories]:[]},s=Array.isArray(n.slots)?n.slots:[];if(s.length>0&&a.slots.length>0)for(let l of a.slots){let d=s.find(u=>(u==null?void 0:u.slotId)&&u.slotId===(l==null?void 0:l.slotId));d!=null&&d.currentAsset&&d.currentAsset!==(l==null?void 0:l.currentAsset)&&(l.currentAsset=d.currentAsset)}let o=n.libraryAssets||{};for(let[l,d]of Object.entries(o)){if(!Array.isArray(d))continue;a.libraryAssets[l]||(a.libraryAssets[l]=[]);let u=new Set((a.libraryAssets[l]||[]).map(p=>p==null?void 0:p.filename));for(let p of d){let f=p==null?void 0:p.filename;!f||u.has(f)||(a.libraryAssets[l].unshift(p),u.add(f))}}let c=new Set(a.categories||[]);for(let l of n.categories||[])typeof l=="string"&&c.add(l);return a.categories=Array.from(c),a}render(){return`
205
205
  <div class="scene-panel library-panel panel-accent-purple" data-panel="library">
206
206
  <div class="scene-panel-header" data-panel-handle>
207
207
  <div class="panel-title">
@@ -220,7 +220,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
220
220
  </div>
221
221
  <div class="panel-resize-handle" data-panel-resize></div>
222
222
  </div>
223
- `}initialize(t,i){var a,s,o;this.options=i,this.root=t.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let r=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");r==null||r.addEventListener("click",()=>{r.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>r.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let t=window.getEditableAssets,i=typeof t=="function"?t():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let r=await n.json(),a=this.mergeRegistries(i,r);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(t){console.warn("[LIBRARY] Failed to re-fetch registry:",t)}this.loadAssetRegistry()}loadAssetRegistry(t=0){let i=window.getEditableAssets;if(typeof i=="function"){let n=i();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}t<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${t+1}/15)`),setTimeout(()=>this.loadAssetRegistry(t+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let t={};for(let n of this.registry.slots)t[n.category]||(t[n.category]=[]),t[n.category].push(n);let i=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let r=t[n]||[];if(r.length===0)continue;let a=document.createElement("div");a.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let c of r){let l=this.createSlotElement(c,i);o.appendChild(l)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(t,i){let n=this.expandedSlot===t.slotId,r=document.createElement("div");r.className=`library-slot ${n?"expanded":""}`,r.dataset.slotId=t.slotId;let a=document.createElement("div");a.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${t.currentAsset}?t=${i}`,o.alt=t.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),a.appendChild(s);let c=document.createElement("div");c.className="slot-info";let l=document.createElement("div");l.className="slot-name",l.textContent=t.displayName;let d=document.createElement("div");d.className="slot-asset",d.textContent=t.currentAsset,c.appendChild(l),c.appendChild(d),a.appendChild(c);let u=document.createElement("div");u.className="slot-actions";let p=document.createElement("button");p.className="slot-ai-edit",p.title="Edit with AI",p.textContent="\u2728 AI",p.addEventListener("click",async h=>{h.stopPropagation(),await this.handleAIEdit(t)}),u.appendChild(p);let f=document.createElement("button");f.className="slot-reset",f.title="Reset to default",f.textContent="\u21BA",f.addEventListener("click",async h=>{h.stopPropagation(),await this.handleReset(t)}),u.appendChild(f);let b=document.createElement("span");if(b.className="slot-expand-icon",b.textContent=n?"\u25BC":"\u25B6",u.appendChild(b),a.appendChild(u),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===t.slotId?null:t.slotId,this.renderSlots()}),r.appendChild(a),n){let h=this.createLibraryElement(t,i);r.appendChild(h)}return r}createLibraryElement(t,i){var a;let n=document.createElement("div");n.className="slot-library";let r=((a=this.registry)==null?void 0:a.libraryAssets[t.libraryFolder])||[];return this.fetchFolderAssets(t.libraryFolder,i).then(s=>{let o=new Map;for(let l of r)o.set(l.filename,l);for(let l of s)o.has(l.filename)||o.set(l.filename,l);let c=Array.from(o.values());if(c.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let l of c){let d=document.createElement("div");d.className="library-item";let u=document.createElement("img");u.src=`/raw/library/${t.libraryFolder}/${l.filename}?t=${i}`,u.alt=l.displayName,u.className="library-thumbnail",u.onerror=()=>{u.style.opacity="0.3"},d.appendChild(u);let p=document.createElement("div");p.className="library-label",p.textContent=l.displayName,d.appendChild(p),d.addEventListener("click",async()=>{await this.handleApply(t,l.filename)}),n.appendChild(d)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(t,i){try{let n=await fetch(`/raw/library/${t}/?t=${i}`);if(!n.ok)return[];let r=await n.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(r))!==null;){let c=o[1];if(!c.startsWith("/")&&!c.startsWith("..")){let l=c.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:c,displayName:l})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(t,i){var n;console.log("[LIBRARY] Applying asset:",i,"to slot:",t.slotId);try{await((n=this.options)==null?void 0:n.onApply(t.objectId,i,t.category)),t.currentAsset=i,this.renderSlots()}catch(r){console.error("[LIBRARY] Failed to apply asset:",r)}}async handleReset(t){var i;console.log("[LIBRARY] Resetting slot:",t.slotId,"to default:",t.defaultAsset);try{await((i=this.options)==null?void 0:i.onReset(t.objectId,t.defaultAsset,t.category)),t.currentAsset=t.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(t){return t.replace(/_/g," ").split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}async handleAIEdit(t){console.log("[Library] Opening AI Edit for slot:",t);let i=window.__openAiEditor;if(typeof i=="function"){let n=t.slotId||t.objectId,r="render.texture";t.category==="ui"&&(r="ui.image"),t.category==="audio"&&(r="audio.src"),i(n,`Edit ${t.displayName} with AI`,t.currentAsset,{objectId:t.objectId,path:r})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let t=window.__openAiEditor;typeof t=="function"?t("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(t,i){if(!this.registry||!this.slotsContainer)return;let n=t.startsWith("json.")?t.replace("json.",""):t,r=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!i||a.category===i));r?(console.log("[LIBRARY] Highlighting slot:",r.slotId),this.expandedSlot=r.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${r.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",t,i)}};var pr=class{detectType(t,i,n){let r=t.toLowerCase();return typeof i=="string"&&i.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":r.includes("color")||r.includes("tint")?"color":typeof i=="boolean"?"boolean":typeof i=="number"?"number":Array.isArray(i)?"array":typeof i=="object"&&i!==null?"object":"text"}isHexColor(t){return/^#[0-9a-fA-F]{6}$/i.test(t)}isImagePath(t){return/\.(png|jpg|jpeg|gif|svg)$/i.test(t)}};var fr=class{render(t,i,n,r){let a=n&&n.trim(),s=a?`/raw/${n}`:"";return`
223
+ `}initialize(t,i){var a,s,o;this.options=i,this.root=t.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let r=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");r==null||r.addEventListener("click",()=>{r.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>r.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let t=window.getEditableAssets,i=typeof t=="function"?t():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let r=await n.json(),a=this.mergeRegistries(i,r);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(t){console.warn("[LIBRARY] Failed to re-fetch registry:",t)}this.loadAssetRegistry()}loadAssetRegistry(t=0){let i=window.getEditableAssets;if(typeof i=="function"){let n=i();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}t<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${t+1}/15)`),setTimeout(()=>this.loadAssetRegistry(t+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let t={};for(let n of this.registry.slots)t[n.category]||(t[n.category]=[]),t[n.category].push(n);let i=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let r=t[n]||[];if(r.length===0)continue;let a=document.createElement("div");a.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let c of r){let l=this.createSlotElement(c,i);o.appendChild(l)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(t,i){let n=this.expandedSlot===t.slotId,r=document.createElement("div");r.className=`library-slot ${n?"expanded":""}`,r.dataset.slotId=t.slotId;let a=document.createElement("div");a.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${t.currentAsset}?t=${i}`,o.alt=t.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),a.appendChild(s);let c=document.createElement("div");c.className="slot-info";let l=document.createElement("div");l.className="slot-name",l.textContent=t.displayName;let d=document.createElement("div");d.className="slot-asset",d.textContent=t.currentAsset,c.appendChild(l),c.appendChild(d),a.appendChild(c);let u=document.createElement("div");u.className="slot-actions";let p=document.createElement("button");p.className="slot-ai-edit",p.title="Edit with AI",p.textContent="\u2728 AI",p.addEventListener("click",async h=>{h.stopPropagation(),await this.handleAIEdit(t)}),u.appendChild(p);let f=document.createElement("button");f.className="slot-reset",f.title="Reset to default",f.textContent="\u21BA",f.addEventListener("click",async h=>{h.stopPropagation(),await this.handleReset(t)}),u.appendChild(f);let m=document.createElement("span");if(m.className="slot-expand-icon",m.textContent=n?"\u25BC":"\u25B6",u.appendChild(m),a.appendChild(u),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===t.slotId?null:t.slotId,this.renderSlots()}),r.appendChild(a),n){let h=this.createLibraryElement(t,i);r.appendChild(h)}return r}createLibraryElement(t,i){var a;let n=document.createElement("div");n.className="slot-library";let r=((a=this.registry)==null?void 0:a.libraryAssets[t.libraryFolder])||[];return this.fetchFolderAssets(t.libraryFolder,i).then(s=>{let o=new Map;for(let l of r)o.set(l.filename,l);for(let l of s)o.has(l.filename)||o.set(l.filename,l);let c=Array.from(o.values());if(c.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let l of c){let d=document.createElement("div");d.className="library-item";let u=document.createElement("img");u.src=`/raw/library/${t.libraryFolder}/${l.filename}?t=${i}`,u.alt=l.displayName,u.className="library-thumbnail",u.onerror=()=>{u.style.opacity="0.3"},d.appendChild(u);let p=document.createElement("div");p.className="library-label",p.textContent=l.displayName,d.appendChild(p),d.addEventListener("click",async()=>{await this.handleApply(t,l.filename)}),n.appendChild(d)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(t,i){try{let n=await fetch(`/raw/library/${t}/?t=${i}`);if(!n.ok)return[];let r=await n.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(r))!==null;){let c=o[1];if(!c.startsWith("/")&&!c.startsWith("..")){let l=c.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:c,displayName:l})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(t,i){var n;console.log("[LIBRARY] Applying asset:",i,"to slot:",t.slotId);try{await((n=this.options)==null?void 0:n.onApply(t.objectId,i,t.category)),t.currentAsset=i,this.renderSlots()}catch(r){console.error("[LIBRARY] Failed to apply asset:",r)}}async handleReset(t){var i;console.log("[LIBRARY] Resetting slot:",t.slotId,"to default:",t.defaultAsset);try{await((i=this.options)==null?void 0:i.onReset(t.objectId,t.defaultAsset,t.category)),t.currentAsset=t.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(t){return t.replace(/_/g," ").split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}async handleAIEdit(t){console.log("[Library] Opening AI Edit for slot:",t);let i=window.__openAiEditor;if(typeof i=="function"){let n=t.slotId||t.objectId,r="render.texture";t.category==="ui"&&(r="ui.image"),t.category==="audio"&&(r="audio.src"),i(n,`Edit ${t.displayName} with AI`,t.currentAsset,{objectId:t.objectId,path:r})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let t=window.__openAiEditor;typeof t=="function"?t("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(t,i){if(!this.registry||!this.slotsContainer)return;let n=t.startsWith("json.")?t.replace("json.",""):t,r=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!i||a.category===i));r?(console.log("[LIBRARY] Highlighting slot:",r.slotId),this.expandedSlot=r.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${r.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",t,i)}};var fr=class{detectType(t,i,n){let r=t.toLowerCase();return typeof i=="string"&&i.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":r.includes("color")||r.includes("tint")?"color":typeof i=="boolean"?"boolean":typeof i=="number"?"number":Array.isArray(i)?"array":typeof i=="object"&&i!==null?"object":"text"}isHexColor(t){return/^#[0-9a-fA-F]{6}$/i.test(t)}isImagePath(t){return/\.(png|jpg|jpeg|gif|svg)$/i.test(t)}};var hr=class{render(t,i,n,r){let a=n&&n.trim(),s=a?`/raw/${n}`:"";return`
224
224
  <div class="inspector-property inspector-property-image">
225
225
  <div class="property-header">
226
226
  <label class="inspector-property-label">${this.formatLabel(i)}</label>
@@ -270,7 +270,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
270
270
  </div>
271
271
  </div>
272
272
  </div>
273
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var hr=class{render(t,i,n,r){let a=n||"#000000";return`
273
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var gr=class{render(t,i,n,r){let a=n||"#000000";return`
274
274
  <div class="inspector-property inspector-property-color">
275
275
  <label class="inspector-property-label">${this.formatLabel(i)}</label>
276
276
  <div class="inspector-color-group">
@@ -286,7 +286,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
286
286
  data-object-id="${t}" />
287
287
  </div>
288
288
  </div>
289
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var gr=class{render(t,i,n,r){return`
289
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var mr=class{render(t,i,n,r){return`
290
290
  <div class="inspector-property inspector-property-number">
291
291
  <label class="inspector-property-label">${this.formatLabel(i)}</label>
292
292
  <input type="number"
@@ -307,7 +307,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
307
307
  data-object-id="${t}" />
308
308
  </div>
309
309
  </div>
310
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var mr=class{render(t,i,n,r){return`
310
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var vr=class{render(t,i,n,r){return`
311
311
  <div class="inspector-property inspector-property-boolean">
312
312
  <label class="inspector-property-label">
313
313
  <input type="checkbox"
@@ -318,7 +318,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
318
318
  <span>${this.formatLabel(i)}</span>
319
319
  </label>
320
320
  </div>
321
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var vr=class{render(t,i,n,r){if(!Array.isArray(n)||n.length===0)return`
321
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var yr=class{render(t,i,n,r){if(!Array.isArray(n)||n.length===0)return`
322
322
  <div class="inspector-property inspector-property-array">
323
323
  <label class="inspector-property-label">${this.formatLabel(i)}</label>
324
324
  <div class="inspector-array-empty">Empty array</div>
@@ -330,7 +330,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
330
330
  ${a}
331
331
  </div>
332
332
  </div>
333
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var yr=class{constructor(t){this.registry=t}render(t,i,n,r){if(i==="logic"&&n&&typeof n=="object")return this.renderLogic(t,i,n,r);let a=[];for(let o in n){let c=n[o],l=`${r}.${o}`,d=this.registry.renderProperty(t,o,c,l);d&&a.push(d)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
333
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var xr=class{constructor(t){this.registry=t}render(t,i,n,r){if(i==="logic"&&n&&typeof n=="object")return this.renderLogic(t,i,n,r);let a=[];for(let o in n){let c=n[o],l=`${r}.${o}`,d=this.registry.renderProperty(t,o,c,l);d&&a.push(d)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
334
334
  <div class="inspector-subsection">
335
335
  <div class="inspector-subsection-title">${this.formatLabel(i)}</div>
336
336
  <div class="inspector-subsection-content">
@@ -344,32 +344,55 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
344
344
  ${a.join("")}
345
345
  </div>
346
346
  </div>
347
- `}renderLogic(t,i,n,r){let a=[],s=typeof(n==null?void 0:n.id)=="string"?n.id:"",o=(()=>{let d=window,u=Array.isArray(d==null?void 0:d.__HANDLER_LOGIC_OPTIONS)?d.__HANDLER_LOGIC_OPTIONS:[],f=[...["DragToWin","SwerveMove","DragSnap","JoystickMove","GsapEntrance"],...u].map(b=>String(b)).filter(b=>b.trim().length>0);return Array.from(new Set(f)).sort((b,h)=>b.localeCompare(h))})(),c=`handler-logic-ids-${t.replace(/[^a-zA-Z0-9_-]/g,"_")}`,l=`
348
- <datalist id="${c}">
349
- ${o.map(d=>`<option value="${d}"></option>`).join("")}
350
- </datalist>
351
- `;a.push(`
347
+ `}renderLogic(t,i,n,r){let a=[],s=typeof(n==null?void 0:n.id)=="string"?n.id:"",o=(()=>{try{let u=window,p=u==null?void 0:u.__HANDLER_LOGIC_META;return s&&p&&typeof p=="object"?p[s]:null}catch{return null}})(),c=o!=null&&o.enums&&typeof o.enums=="object"?o.enums:{},l=(()=>{let u=window,p=Array.isArray(u==null?void 0:u.__HANDLER_LOGIC_OPTIONS)?u.__HANDLER_LOGIC_OPTIONS:[],m=[...["DragToWin","SwerveMove","DragSnap","JoystickMove","GsapEntrance"],...p].map(h=>String(h)).filter(h=>h.trim().length>0);return Array.from(new Set(m)).sort((h,g)=>h.localeCompare(g))})(),d=s&&!l.includes(s)?[s,...l]:l;a.push(`
352
348
  <div class="inspector-property inspector-property-text">
353
349
  <label class="inspector-property-label">Id</label>
354
350
  <div class="inspector-input-group">
355
- <input type="text"
356
- class="inspector-input"
357
- value="${s}"
358
- list="${c}"
359
- data-property-path="${r}.id"
360
- data-object-id="${t}"
361
- placeholder="Select logic id..." />
362
- ${l}
351
+ <select class="inspector-component-select inspector-input"
352
+ data-property-path="${r}.id"
353
+ data-object-id="${t}">
354
+ <option value="" ${s?"":"selected"}>None</option>
355
+ ${d.map(u=>`<option value="${u}" ${u===s?"selected":""}>${u}</option>`).join("")}
356
+ </select>
363
357
  </div>
364
358
  </div>
365
- `);for(let d in n){if(d==="id")continue;let u=n[d],p=`${r}.${d}`,f=this.registry.renderProperty(t,d,u,p);f&&a.push(f)}return a.length===0?"":`
359
+ `);for(let u in n){if(u==="id")continue;let p=n[u],f=`${r}.${u}`;if(u==="props"&&p&&typeof p=="object"){let h=[];for(let g in p){let v=p[g],b=`${f}.${g}`,y=c==null?void 0:c[g];if(Array.isArray(y)&&y.length)h.push(`
360
+ <div class="inspector-property inspector-property-text">
361
+ <label class="inspector-property-label">${this.formatLabel(g)}</label>
362
+ <div class="inspector-input-group">
363
+ <select class="inspector-component-select inspector-input"
364
+ data-property-path="${b}"
365
+ data-object-id="${t}">
366
+ ${y.map(x=>`<option value="${String(x)}" ${String(x)===String(v)?"selected":""}>${String(x)}</option>`).join("")}
367
+ </select>
368
+ </div>
369
+ </div>
370
+ `);else{let x=this.registry.renderProperty(t,g,v,b);x&&h.push(x)}}h.length&&a.push(`
371
+ <div class="inspector-property inspector-property-object">
372
+ <div class="inspector-object-header">Props</div>
373
+ <div class="inspector-object-body">
374
+ ${h.join("")}
375
+ </div>
376
+ </div>
377
+ `);continue}let m=this.registry.renderProperty(t,u,p,f);m&&a.push(m)}return a.length===0?"":`
366
378
  <div class="inspector-property inspector-property-object">
367
379
  <div class="inspector-object-header">${this.formatLabel(i)}</div>
368
380
  <div class="inspector-object-body">
369
381
  ${a.join("")}
370
382
  </div>
371
383
  </div>
372
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var xr=class{constructor(){this.typeDetector=new pr,this.imageRenderer=new fr,this.colorRenderer=new hr,this.numberRenderer=new gr,this.textRenderer=new br,this.booleanRenderer=new mr,this.arrayRenderer=new vr,this.objectRenderer=new yr(this)}renderProperty(t,i,n,r){switch(this.typeDetector.detectType(i,n)){case"image":return this.imageRenderer.render(t,i,n,r);case"color":return this.colorRenderer.render(t,i,n,r);case"number":return this.numberRenderer.render(t,i,n,r);case"boolean":return this.booleanRenderer.render(t,i,n,r);case"array":return this.arrayRenderer.render(t,i,n,r);case"object":return this.objectRenderer.render(t,i,n,r);default:return this.textRenderer.render(t,i,n,r)}}getTypeDetector(){return this.typeDetector}};var di=class{async updateProperty(t,i,n,r={}){var c,l,d;console.log("[PropertyUpdateManager] Updating:",t,i,n);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(t);if(!s){console.error("[PropertyUpdateManager] Config not found for:",t);return}en({objectId:t,path:i,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let u=window.__editableConfig,p=(d=(l=(c=u==null?void 0:u.objects)==null?void 0:c.get)==null?void 0:l.call(c,t))!=null?d:s;await o(t,p),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(t),r.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(t,i){let n=i.split("."),r=t;for(let a of n)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}triggerRefresh(t){let i=window.__refreshHierarchy;typeof i=="function"&&i(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:t}}))}};var wr=class{constructor(){this.updateManager=new di}async handleAction(t,i,n){console.log("[QuickActionsBar] Action:",t,i,n);let r=window.getEditableObjectConfig;if(typeof r!="function")return;let a=r(i);if(!a)return;let s=this.updateManager.getNestedProperty(a,n);if(t==="ai-convert"||t==="upload"||t==="library"){let o=n==="ui.text"||n==="render.asset.path",c=n==="render.asset.path";o&&(await this.prepareForImageConversion(i,a),t==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(t){case"library":this.openLibrary(i,n,s);break;case"ai-edit":this.openAIEditor(i,n,s);break;case"upload":this.openUpload(i,n);break;case"reset":await this.resetToDefault(i,n);break;case"ai-convert":this.handleAiConvert(i,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",t)}}async prepareForImageConversion(t,i){var n,r;if(console.log("[QuickActionsBar] Preparing for image conversion:",t),i.render||(i.render={alpha:1,visible:!0}),(i.render.alpha===0||i.render.alpha===void 0)&&(i.render.alpha=1,await this.updateManager.updateProperty(t,"render.alpha",1)),(i.render.visible===!1||i.render.visible===void 0)&&(i.render.visible=!0,await this.updateManager.updateProperty(t,"render.visible",!0)),i.render.asset||(i.render.asset={type:"image",path:""}),i.render.asset.type!=="image"&&(i.render.asset.type="image",await this.updateManager.updateProperty(t,"render.asset",{type:"image",path:i.render.asset.path||""})),i.ui&&i.ui.renderMode!=="png"){await this.updateManager.updateProperty(t,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(t,"render.tint","#ffffff");let s=((r=(n=i.transform)==null?void 0:n.scale)!=null?r:1)*.3;await this.updateManager.updateProperty(t,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(t,i)}ensureSlotInRegistry(t,i){var o,c,l;let n=window.getEditableAssets;if(typeof n!="function")return;let r=n();if(!r||!r.slots)return;let a=t.startsWith("json.")?t.replace("json.",""):t;if(!r.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=i.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),r.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((l=(c=i.render)==null?void 0:c.asset)==null?void 0:l.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),r.categories&&!r.categories.includes(d)&&r.categories.push(d),r.libraryAssets&&!r.libraryAssets[d]&&(r.libraryAssets[d]=[]);let u=window.reRenderAssetLibrary;typeof u=="function"&&u()}}openLibrary(t,i,n){var a;let r=window.__debugContext;if(r){if(r.activeTab!=="library"){r.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(r.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(t),c=(a=o==null?void 0:o.identity)==null?void 0:a.category;c||(c=i.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",t,"category:",c),r.libraryPanel.highlightSlot(t,c)}}}openAIEditor(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let a=i.split(".").pop()||i;r(a,`Edit ${a} for ${t}`,n,{objectId:t,path:i})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(t,i){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async r=>{var o;let a=(o=r.target.files)==null?void 0:o[0];if(!a)return;console.log("[QuickActionsBar] Preparing upload for:",a.name);let s=new FileReader;s.onload=async()=>{var l,d,u;let c=s.result;try{let p=window.getEditableObjectConfig,f=p==null?void 0:p(t),b=((l=f==null?void 0:f.identity)==null?void 0:l.category)||(i.split(".")[0]==="render"?"environment":"ui"),g=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:b,filename:a.name,data:c,overwrite:!0})})).json();if(g.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",g.path),this.updateManager.updateProperty(t,i,g.path);let m=window.__debugContext;(u=(d=m==null?void 0:m.options)==null?void 0:d.onPropertyChange)==null||u.call(d,t,i,g.path);let v=window.addAssetToRegistry;typeof v=="function"&&v(b,a.name);let y=window.reRenderAssetLibrary;typeof y=="function"&&y(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",g.error),alert(`Upload failed: ${g.error}`)}catch(p){console.error("[QuickActionsBar] \u274C Upload error:",p),alert("Upload failed. Check console.")}},s.readAsDataURL(a)},n.click()}async resetToDefault(t,i){console.log("[QuickActionsBar] Reset to default:",t,i);try{let n=await this.getDefaultValue(t,i);n!==void 0?(await this.updateManager.updateProperty(t,i,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(t,i){let n=i.split(".");if(n.length<2)return;let r=n[0],a=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(r):typeof s.schemas=="object"&&(o=s.schemas[r]),!(o!=null&&o.defaults))return;let c=o.defaults;for(let l of a)if(c&&typeof c=="object")c=c[l];else return;return c}handleAiConvert(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||t.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",t,"from:",i,"to:",o),r(t,s,"",{objectId:t,path:o});let c=window.__debugContext;if(c){c.activeTab="ai";let l=window.__updateWorkbenchTabs;typeof l=="function"&&l()}}else console.warn("[QuickActionsBar] AI Editor not available")}};function sg(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}var _r=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new xr,this.updateManager=new di,this.quickActions=new wr,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
384
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var wr=class{render(t,i,n,r,a){let s=n==null?"":String(n),o=Array.from(new Set(a.map(l=>String(l)))),c=s&&!o.includes(s)?[s,...o]:o;return`
385
+ <div class="inspector-property inspector-property-text">
386
+ <label class="inspector-property-label">${this.formatLabel(i)}</label>
387
+ <div class="inspector-input-group">
388
+ <select class="inspector-component-select inspector-input"
389
+ data-property-path="${r}"
390
+ data-object-id="${t}">
391
+ ${c.map(l=>`<option value="${l}" ${l===s?"selected":""}>${l}</option>`).join("")}
392
+ </select>
393
+ </div>
394
+ </div>
395
+ `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var _r=class{constructor(){this.typeDetector=new fr,this.imageRenderer=new hr,this.colorRenderer=new gr,this.numberRenderer=new mr,this.textRenderer=new br,this.booleanRenderer=new vr,this.arrayRenderer=new yr,this.objectRenderer=new xr(this),this.selectRenderer=new wr}getEnumOptionsFromSchemas(t){var i;try{let n=window,r=n==null?void 0:n.__editableConfig,a=r==null?void 0:r.schemas;if(!a)return null;let s=String(t||"").split(".").filter(Boolean);if(s.length<2)return null;let o=s[0],c=s.slice(1).join("."),l=a instanceof Map?a.get(o):a==null?void 0:a[o];if(!l)return null;let d=(i=l==null?void 0:l.types)==null?void 0:i[c];if(typeof d!="string"||!d.startsWith("enum:"))return null;let p=d.slice(5).split("|").map(f=>f.trim()).filter(Boolean);return p.length?p:null}catch{return null}}renderProperty(t,i,n,r){let a=this.getEnumOptionsFromSchemas(r);if(a)return this.selectRenderer.render(t,i,n,r,a);switch(this.typeDetector.detectType(i,n)){case"image":return this.imageRenderer.render(t,i,n,r);case"color":return this.colorRenderer.render(t,i,n,r);case"number":return this.numberRenderer.render(t,i,n,r);case"boolean":return this.booleanRenderer.render(t,i,n,r);case"array":return this.arrayRenderer.render(t,i,n,r);case"object":return this.objectRenderer.render(t,i,n,r);case"select":return this.selectRenderer.render(t,i,n,r,[]);default:return this.textRenderer.render(t,i,n,r)}}getTypeDetector(){return this.typeDetector}};var di=class{async updateProperty(t,i,n,r={}){var c,l,d;console.log("[PropertyUpdateManager] Updating:",t,i,n);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(t);if(!s){console.error("[PropertyUpdateManager] Config not found for:",t);return}en({objectId:t,path:i,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let u=window.__editableConfig,p=(d=(l=(c=u==null?void 0:u.objects)==null?void 0:c.get)==null?void 0:l.call(c,t))!=null?d:s;await o(t,p),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(t),r.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(t,i){let n=i.split("."),r=t;for(let a of n)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}triggerRefresh(t){let i=window.__refreshHierarchy;typeof i=="function"&&i(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:t}}))}};var Er=class{constructor(){this.updateManager=new di}async handleAction(t,i,n){console.log("[QuickActionsBar] Action:",t,i,n);let r=window.getEditableObjectConfig;if(typeof r!="function")return;let a=r(i);if(!a)return;let s=this.updateManager.getNestedProperty(a,n);if(t==="ai-convert"||t==="upload"||t==="library"){let o=n==="ui.text"||n==="render.asset.path",c=n==="render.asset.path";o&&(await this.prepareForImageConversion(i,a),t==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(t){case"library":this.openLibrary(i,n,s);break;case"ai-edit":this.openAIEditor(i,n,s);break;case"upload":this.openUpload(i,n);break;case"reset":await this.resetToDefault(i,n);break;case"ai-convert":this.handleAiConvert(i,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",t)}}async prepareForImageConversion(t,i){var n,r;if(console.log("[QuickActionsBar] Preparing for image conversion:",t),i.render||(i.render={alpha:1,visible:!0}),(i.render.alpha===0||i.render.alpha===void 0)&&(i.render.alpha=1,await this.updateManager.updateProperty(t,"render.alpha",1)),(i.render.visible===!1||i.render.visible===void 0)&&(i.render.visible=!0,await this.updateManager.updateProperty(t,"render.visible",!0)),i.render.asset||(i.render.asset={type:"image",path:""}),i.render.asset.type!=="image"&&(i.render.asset.type="image",await this.updateManager.updateProperty(t,"render.asset",{type:"image",path:i.render.asset.path||""})),i.ui&&i.ui.renderMode!=="png"){await this.updateManager.updateProperty(t,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(t,"render.tint","#ffffff");let s=((r=(n=i.transform)==null?void 0:n.scale)!=null?r:1)*.3;await this.updateManager.updateProperty(t,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(t,i)}ensureSlotInRegistry(t,i){var o,c,l;let n=window.getEditableAssets;if(typeof n!="function")return;let r=n();if(!r||!r.slots)return;let a=t.startsWith("json.")?t.replace("json.",""):t;if(!r.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=i.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),r.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((l=(c=i.render)==null?void 0:c.asset)==null?void 0:l.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),r.categories&&!r.categories.includes(d)&&r.categories.push(d),r.libraryAssets&&!r.libraryAssets[d]&&(r.libraryAssets[d]=[]);let u=window.reRenderAssetLibrary;typeof u=="function"&&u()}}openLibrary(t,i,n){var a;let r=window.__debugContext;if(r){if(r.activeTab!=="library"){r.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(r.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(t),c=(a=o==null?void 0:o.identity)==null?void 0:a.category;c||(c=i.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",t,"category:",c),r.libraryPanel.highlightSlot(t,c)}}}openAIEditor(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let a=i.split(".").pop()||i;r(a,`Edit ${a} for ${t}`,n,{objectId:t,path:i})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(t,i){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async r=>{var o;let a=(o=r.target.files)==null?void 0:o[0];if(!a)return;console.log("[QuickActionsBar] Preparing upload for:",a.name);let s=new FileReader;s.onload=async()=>{var l,d,u;let c=s.result;try{let p=window.getEditableObjectConfig,f=p==null?void 0:p(t),m=((l=f==null?void 0:f.identity)==null?void 0:l.category)||(i.split(".")[0]==="render"?"environment":"ui"),g=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:m,filename:a.name,data:c,overwrite:!0})})).json();if(g.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",g.path),this.updateManager.updateProperty(t,i,g.path);let v=window.__debugContext;(u=(d=v==null?void 0:v.options)==null?void 0:d.onPropertyChange)==null||u.call(d,t,i,g.path);let b=window.addAssetToRegistry;typeof b=="function"&&b(m,a.name);let y=window.reRenderAssetLibrary;typeof y=="function"&&y(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",g.error),alert(`Upload failed: ${g.error}`)}catch(p){console.error("[QuickActionsBar] \u274C Upload error:",p),alert("Upload failed. Check console.")}},s.readAsDataURL(a)},n.click()}async resetToDefault(t,i){console.log("[QuickActionsBar] Reset to default:",t,i);try{let n=await this.getDefaultValue(t,i);n!==void 0?(await this.updateManager.updateProperty(t,i,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(t,i){let n=i.split(".");if(n.length<2)return;let r=n[0],a=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(r):typeof s.schemas=="object"&&(o=s.schemas[r]),!(o!=null&&o.defaults))return;let c=o.defaults;for(let l of a)if(c&&typeof c=="object")c=c[l];else return;return c}handleAiConvert(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||t.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",t,"from:",i,"to:",o),r(t,s,"",{objectId:t,path:o});let c=window.__debugContext;if(c){c.activeTab="ai";let l=window.__updateWorkbenchTabs;typeof l=="function"&&l()}}else console.warn("[QuickActionsBar] AI Editor not available")}};function bg(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}var Sr=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new _r,this.updateManager=new di,this.quickActions=new Er,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
373
396
  <div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector" style="right:16px; top:72px;">
374
397
  <div class="scene-panel-header" data-panel-handle>
375
398
  <div class="panel-title">
@@ -430,7 +453,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
430
453
  ${a.join("")}
431
454
  </div>
432
455
  </div>
433
- `}attachEventListeners(){var l,d,u,p;if(!this.contentContainer)return;let t=this.contentContainer.querySelectorAll("[data-property-path]"),i=sg((f,b,h)=>{var g,m;this.updateManager.updateProperty(f,b,h),(m=(g=this.options)==null?void 0:g.onPropertyChange)==null||m.call(g,f,b,h)},300);t.forEach(f=>{let b=h=>{var y,x;let g=h.target,m=g.dataset.propertyPath,v=g.dataset.objectId;if(m&&v){let w=g.value;if(g.type==="checkbox")w=g.checked;else if(g.type==="number"&&(w=parseFloat(g.value),isNaN(w)))return;g.type==="text"||g.type==="range"||g.tagName==="TEXTAREA"?i(v,m,w):(this.updateManager.updateProperty(v,m,w),(x=(y=this.options)==null?void 0:y.onPropertyChange)==null||x.call(y,v,m,w))}};f.addEventListener("change",b),(f.tagName==="INPUT"||f.tagName==="TEXTAREA")&&f.addEventListener("input",b)}),this.contentContainer.querySelectorAll("[data-action]").forEach(f=>{f.addEventListener("click",b=>{let h=b.target,g=h.dataset.action,m=h.dataset.path,v=h.dataset.object;g&&m&&v&&this.quickActions.handleAction(g,v,m)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(f=>{f.addEventListener("click",b=>{var m,v;let h=b.target,g=h.dataset.sectionToggle||((m=h.closest("[data-section-toggle]"))==null?void 0:m.getAttribute("data-section-toggle"));if(g){let y=(v=this.contentContainer)==null?void 0:v.querySelector(`[data-section="${g}"]`);y==null||y.classList.toggle("collapsed")}})});let a=(l=this.root)==null?void 0:l.querySelector("[data-inspector-advanced]");a==null||a.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let s=(d=this.root)==null?void 0:d.querySelector("[data-convert-toggle]");s==null||s.addEventListener("click",()=>{var b;let f=(b=this.root)==null?void 0:b.querySelector("[data-convert-menu]");f==null||f.classList.toggle("hidden")});let o=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-add-component-btn]"),c=(p=this.contentContainer)==null?void 0:p.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let f=c.value;f&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,f)})}async addComponent(t,i){console.log("[InspectorPanel] Adding component:",i,"to:",t);let n=window.getEditableObjectConfig,r=n==null?void 0:n(t);if(!r){console.error("[InspectorPanel] Failed to get config for:",t);return}let a=window.__editableConfig,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(i):s&&typeof s=="object"&&(o=s[i]),o||console.warn("[InspectorPanel] Schema not found for component:",i);let c=(o==null?void 0:o.defaults)||{enabled:!0};r[i]={...c},await this.updateManager.updateProperty(t,i,r[i]),this.loadObject(t),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(t,i,n){var a,s;if(["identity","transform","render"].includes(t))return!0;if(!i||typeof i!="object"||t==="ui"&&((s=(a=n.render)==null?void 0:a.asset)==null?void 0:s.type)==="image")return!1;if(t==="interaction")return i.clickable===!0||i.draggable===!0;if(i.enabled===!0||i.active===!0||i.visible===!0)return!0;if(t==="ui")return!!(i.text||i.font||i.fontSize);let r=Object.keys(i);return r.length===0||r.length===1&&r[0]==="enabled"&&i.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(t)?i.enabled===!0:!0}showError(t){this.contentContainer&&(this.contentContainer.innerHTML=`
456
+ `}attachEventListeners(){var l,d,u,p;if(!this.contentContainer)return;let t=this.contentContainer.querySelectorAll("[data-property-path]"),i=bg((f,m,h)=>{var g,v;this.updateManager.updateProperty(f,m,h),(v=(g=this.options)==null?void 0:g.onPropertyChange)==null||v.call(g,f,m,h)},300);t.forEach(f=>{let m=h=>{var y,x;let g=h.target,v=g.dataset.propertyPath,b=g.dataset.objectId;if(v&&b){let w=g.value;if(g.type==="checkbox")w=g.checked;else if(g.type==="number"&&(w=parseFloat(g.value),isNaN(w)))return;g.type==="text"||g.type==="range"||g.tagName==="TEXTAREA"?i(b,v,w):(this.updateManager.updateProperty(b,v,w),(x=(y=this.options)==null?void 0:y.onPropertyChange)==null||x.call(y,b,v,w))}};f.addEventListener("change",m),(f.tagName==="INPUT"||f.tagName==="TEXTAREA")&&f.addEventListener("input",m)}),this.contentContainer.querySelectorAll("[data-action]").forEach(f=>{f.addEventListener("click",m=>{let h=m.target,g=h.dataset.action,v=h.dataset.path,b=h.dataset.object;g&&v&&b&&this.quickActions.handleAction(g,b,v)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(f=>{f.addEventListener("click",m=>{var v,b;let h=m.target,g=h.dataset.sectionToggle||((v=h.closest("[data-section-toggle]"))==null?void 0:v.getAttribute("data-section-toggle"));if(g){let y=(b=this.contentContainer)==null?void 0:b.querySelector(`[data-section="${g}"]`);y==null||y.classList.toggle("collapsed")}})});let a=(l=this.root)==null?void 0:l.querySelector("[data-inspector-advanced]");a==null||a.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let s=(d=this.root)==null?void 0:d.querySelector("[data-convert-toggle]");s==null||s.addEventListener("click",()=>{var m;let f=(m=this.root)==null?void 0:m.querySelector("[data-convert-menu]");f==null||f.classList.toggle("hidden")});let o=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-add-component-btn]"),c=(p=this.contentContainer)==null?void 0:p.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let f=c.value;f&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,f)})}async addComponent(t,i){console.log("[InspectorPanel] Adding component:",i,"to:",t);let n=window.getEditableObjectConfig,r=n==null?void 0:n(t);if(!r){console.error("[InspectorPanel] Failed to get config for:",t);return}let a=window.__editableConfig,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(i):s&&typeof s=="object"&&(o=s[i]),o||console.warn("[InspectorPanel] Schema not found for component:",i);let c=(o==null?void 0:o.defaults)||{enabled:!0};r[i]={...c},await this.updateManager.updateProperty(t,i,r[i]),this.loadObject(t),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(t,i,n){var a,s;if(["identity","transform","render"].includes(t))return!0;if(!i||typeof i!="object"||t==="ui"&&((s=(a=n.render)==null?void 0:a.asset)==null?void 0:s.type)==="image")return!1;if(t==="interaction")return i.clickable===!0||i.draggable===!0;if(i.enabled===!0||i.active===!0||i.visible===!0)return!0;if(t==="ui")return!!(i.text||i.font||i.fontSize);let r=Object.keys(i);return r.length===0||r.length===1&&r[0]==="enabled"&&i.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(t)?i.enabled===!0:!0}showError(t){this.contentContainer&&(this.contentContainer.innerHTML=`
434
457
  <div class="inspector-empty">
435
458
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
436
459
  <span class="inspector-empty-text">${t}</span>
@@ -440,7 +463,7 @@ import{c as Wa,d as He,e as Ya}from"./chunk-I5OOVR5U.js";import{i as sr}from"./c
440
463
  <span class="inspector-empty-icon">\u{1F3AF}</span>
441
464
  <span class="inspector-empty-text">Select an object to inspect</span>
442
465
  </div>
443
- `)}};var ah=rg(Wf(),1);function Vo(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function Yf(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}async function Vf(e){return await new Promise(t=>{let i=new Image;i.onload=()=>t({width:i.naturalWidth||i.width,height:i.naturalHeight||i.height}),i.onerror=()=>t(null),i.src=e})}async function ha(e){var t,i;try{console.log("[ImageUtils] Fetching image data from URL:",e);let n=await fetch(e);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,e),null;let r=await n.blob();console.log("[ImageUtils] Blob received, size:",r.size,"type:",r.type);let a=await Vo(r),s=await Vf(a),o=Yf(a);return console.log("[ImageUtils] Success resolution:",s==null?void 0:s.width,"x",s==null?void 0:s.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(t=s==null?void 0:s.width)!=null?t:0,height:(i=s==null?void 0:s.height)!=null?i:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Pt(e){var t,i;try{let n=await Vo(e),r=await Vf(n),a=Yf(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(t=r==null?void 0:r.width)!=null?t:0,height:(i=r==null?void 0:r.height)!=null?i:0}}catch{return null}}function Kf(e){return Vo(e).then(t=>t).catch(()=>null)}function Ko(e,t){var i;try{let[n,r]=e.split(","),a=n.match(/data:(.*?);base64/),s=(i=a==null?void 0:a[1])!=null?i:"image/png",o=atob(r),c=new Uint8Array(o.length);for(let l=0;l<o.length;l++)c[l]=o.charCodeAt(l);return new File([c],t,{type:s})}catch{return null}}async function Bi(e,t=30){try{console.log("[ImageUtils] Removing background color...");let i=await new Promise((u,p)=>{let f=new Image;f.onload=()=>u(f),f.onerror=()=>p(new Error("Failed to load image")),f.src=e}),n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");if(!r)return console.error("[ImageUtils] Failed to get canvas context"),e;r.drawImage(i,0,0);let a=r.getImageData(0,0,n.width,n.height),s=a.data,c=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(u=>({r:s[u.offset],g:s[u.offset+1],b:s[u.offset+2]})),l=0;for(let u=0;u<s.length;u+=4){let p=s[u],f=s[u+1],b=s[u+2],h=!1;for(let g of c)if(Math.sqrt(Math.pow(p-g.r,2)+Math.pow(f-g.g,2)+Math.pow(b-g.b,2))<t){h=!0;break}h&&(s[u+3]=0,l++)}return console.log(`[ImageUtils] Removed background from ${l} pixels (4-corner sampling, tolerance: ${t})`),r.putImageData(a,0,0),n.toDataURL("image/png")}catch(i){return console.error("[ImageUtils] Error removing background:",i),e}}function Xf(e,t){if(!e||!t)return"1:1";let i=e/t;return i>1.3?"16:9":i<.77?"9:16":"1:1"}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e){return typeof e=="string"?e:void 0}function Zf(e){return e.toLowerCase().endsWith(".png")?e.slice(0,-4):e}function Ny(e){var n,r,a;let t=(n=de(e.id))!=null?n:de(e.name);if(t)return t;let i=(r=de(e.file))!=null?r:de(e.asset);return i?Zf((a=i.split("/").pop())!=null?a:i):void 0}function Hy(e,t,i){var n,r,a;if(typeof t=="string")return{id:e,file:t,role:i};if(ut(t)){let s=(n=de(t.file))!=null?n:de(t.asset);return s?{id:(r=de(t.id))!=null?r:e,file:s,role:(a=de(t.role))!=null?a:i,dataUrl:de(t.dataUrl),layout:t.layout}:null}return null}function Xo(e,t){var i,n,r;if(!e)return[];if(Array.isArray(e)){let a=[];for(let s of e){if(typeof s=="string"){let o=Zf((i=s.split("/").pop())!=null?i:s);a.push({id:o,file:s,role:t});continue}if(ut(s)){let o=Ny(s),c=(n=de(s.file))!=null?n:de(s.asset);if(!o||!c)continue;a.push({id:o,file:c,role:(r=de(s.role))!=null?r:t,dataUrl:de(s.dataUrl),layout:s.layout})}}return a}if(ut(e)){let a=[];for(let[s,o]of Object.entries(e)){let c=Hy(s,o,t);c&&a.push(c)}return a}return[]}function Uy(e){var t,i;return(i=(t=de(e.brand_name))!=null?t:de(e.brandName))!=null?i:de(e.name)}function $y(e){if(ut(e.brand_dna)&&ut(e.brand_dna.colors))return e.brand_dna;if(ut(e.colors)){let t={colors:e.colors};return typeof e.style=="string"&&(t.style=e.style),ut(e.fonts)&&(t.fonts=e.fonts),t}}function qy(e){var i;let t=new Map;for(let n of e){let r=t.get(n.id);if(!r){t.set(n.id,n);continue}t.set(n.id,{...r,...n,file:n.file||r.file,role:n.role||r.role,dataUrl:n.dataUrl||r.dataUrl,layout:(i=n.layout)!=null?i:r.layout})}return Array.from(t.values())}function Zo(e,t={}){var s,o,c;let i=e.filter(ut),n=(o=(s=i.map(Uy).find(Boolean))!=null?s:t.defaultBrandName)!=null?o:"Imported Brand",r=(c=i.map($y).find(Boolean))!=null?c:{colors:{}},a=[];for(let l of i)"layers"in l&&a.push(...Xo(l.layers,"visual element")),"assets"in l&&a.push(...Xo(l.assets,"visual element")),ut(l.endgame)&&"assets"in l.endgame&&a.push(...Xo(l.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:r,assets:qy(a)}}import{GoogleGenAI as Gy}from"@google/genai";async function ga(e,t,i=[],n={}){var r,a,s,o,c,l,d;try{if(!(e!=null&&e.trim()))throw new Error("Gemini API key is required");if(!(t!=null&&t.trim()))throw new Error("Prompt is required");for(let m=0;m<i.length;m++){let v=i[m];if(!v.base64||!v.mimeType)throw new Error(`Image ${m+1} is missing required data`);if(v.base64.length<1e3&&console.warn(`Image ${m+1} data appears very small, may be corrupted`),!v.mimeType.startsWith("image/"))throw new Error(`Image ${m+1} has invalid MIME type: ${v.mimeType}`)}let u=new Gy({apiKey:e}),p="gemini-2.5-flash",f=[t];i.length>0&&i.forEach((m,v)=>{f.push({inlineData:{data:m.base64,mimeType:m.mimeType}}),console.log(`[Gemini] Added image ${v+1}: ${m.mimeType}, size: ${Math.round(m.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${i.length} images and prompt length: ${t.length}`);let b=await u.models.generateContent({model:p,contents:f}),h="",g=(s=(a=(r=b.candidates)==null?void 0:r[0])==null?void 0:a.content)==null?void 0:s.parts;if(g)for(let m of g)m.text&&(h+=m.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(u){throw console.error("[Gemini] API error:",u),(o=u.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(c=u.message)!=null&&c.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(l=u.message)!=null&&l.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(d=u.message)!=null&&d.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):u}}import{GoogleGenAI as Wy}from"@google/genai";async function Fi(e,t,i=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let r=new Wy({apiKey:e}),a=[{text:t}];i.length>0&&i.forEach((o,c)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${c}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let s=await r.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!s.candidates||!s.candidates[0]||!s.candidates[0].content||!s.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of s.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let c=o.inlineData.data,l=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${l};base64,${c}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(r){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(r,Object.getOwnPropertyNames(r),2)),r}}function Jf(e){let t=e.brandAssets.map(a=>{let s=`- ${a.id}: ${a.role}`;return a.layout&&(s+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),s}).join(`
466
+ `)}};var fh=pg(eh(),1);function Xo(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function th(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}async function ih(e){return await new Promise(t=>{let i=new Image;i.onload=()=>t({width:i.naturalWidth||i.width,height:i.naturalHeight||i.height}),i.onerror=()=>t(null),i.src=e})}async function ma(e){var t,i;try{console.log("[ImageUtils] Fetching image data from URL:",e);let n=await fetch(e);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,e),null;let r=await n.blob();console.log("[ImageUtils] Blob received, size:",r.size,"type:",r.type);let a=await Xo(r),s=await ih(a),o=th(a);return console.log("[ImageUtils] Success resolution:",s==null?void 0:s.width,"x",s==null?void 0:s.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(t=s==null?void 0:s.width)!=null?t:0,height:(i=s==null?void 0:s.height)!=null?i:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Mt(e){var t,i;try{let n=await Xo(e),r=await ih(n),a=th(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(t=r==null?void 0:r.width)!=null?t:0,height:(i=r==null?void 0:r.height)!=null?i:0}}catch{return null}}function nh(e){return Xo(e).then(t=>t).catch(()=>null)}function Zo(e,t){var i;try{let[n,r]=e.split(","),a=n.match(/data:(.*?);base64/),s=(i=a==null?void 0:a[1])!=null?i:"image/png",o=atob(r),c=new Uint8Array(o.length);for(let l=0;l<o.length;l++)c[l]=o.charCodeAt(l);return new File([c],t,{type:s})}catch{return null}}async function Bi(e,t=30){try{console.log("[ImageUtils] Removing background color...");let i=await new Promise((u,p)=>{let f=new Image;f.onload=()=>u(f),f.onerror=()=>p(new Error("Failed to load image")),f.src=e}),n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");if(!r)return console.error("[ImageUtils] Failed to get canvas context"),e;r.drawImage(i,0,0);let a=r.getImageData(0,0,n.width,n.height),s=a.data,c=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(u=>({r:s[u.offset],g:s[u.offset+1],b:s[u.offset+2]})),l=0;for(let u=0;u<s.length;u+=4){let p=s[u],f=s[u+1],m=s[u+2],h=!1;for(let g of c)if(Math.sqrt(Math.pow(p-g.r,2)+Math.pow(f-g.g,2)+Math.pow(m-g.b,2))<t){h=!0;break}h&&(s[u+3]=0,l++)}return console.log(`[ImageUtils] Removed background from ${l} pixels (4-corner sampling, tolerance: ${t})`),r.putImageData(a,0,0),n.toDataURL("image/png")}catch(i){return console.error("[ImageUtils] Error removing background:",i),e}}function rh(e,t){if(!e||!t)return"1:1";let i=e/t;return i>1.3?"16:9":i<.77?"9:16":"1:1"}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function de(e){return typeof e=="string"?e:void 0}function ah(e){return e.toLowerCase().endsWith(".png")?e.slice(0,-4):e}function Zy(e){var n,r,a;let t=(n=de(e.id))!=null?n:de(e.name);if(t)return t;let i=(r=de(e.file))!=null?r:de(e.asset);return i?ah((a=i.split("/").pop())!=null?a:i):void 0}function Jy(e,t,i){var n,r,a;if(typeof t=="string")return{id:e,file:t,role:i};if(ut(t)){let s=(n=de(t.file))!=null?n:de(t.asset);return s?{id:(r=de(t.id))!=null?r:e,file:s,role:(a=de(t.role))!=null?a:i,dataUrl:de(t.dataUrl),layout:t.layout}:null}return null}function Jo(e,t){var i,n,r;if(!e)return[];if(Array.isArray(e)){let a=[];for(let s of e){if(typeof s=="string"){let o=ah((i=s.split("/").pop())!=null?i:s);a.push({id:o,file:s,role:t});continue}if(ut(s)){let o=Zy(s),c=(n=de(s.file))!=null?n:de(s.asset);if(!o||!c)continue;a.push({id:o,file:c,role:(r=de(s.role))!=null?r:t,dataUrl:de(s.dataUrl),layout:s.layout})}}return a}if(ut(e)){let a=[];for(let[s,o]of Object.entries(e)){let c=Jy(s,o,t);c&&a.push(c)}return a}return[]}function Qy(e){var t,i;return(i=(t=de(e.brand_name))!=null?t:de(e.brandName))!=null?i:de(e.name)}function ex(e){if(ut(e.brand_dna)&&ut(e.brand_dna.colors))return e.brand_dna;if(ut(e.colors)){let t={colors:e.colors};return typeof e.style=="string"&&(t.style=e.style),ut(e.fonts)&&(t.fonts=e.fonts),t}}function tx(e){var i;let t=new Map;for(let n of e){let r=t.get(n.id);if(!r){t.set(n.id,n);continue}t.set(n.id,{...r,...n,file:n.file||r.file,role:n.role||r.role,dataUrl:n.dataUrl||r.dataUrl,layout:(i=n.layout)!=null?i:r.layout})}return Array.from(t.values())}function Qo(e,t={}){var s,o,c;let i=e.filter(ut),n=(o=(s=i.map(Qy).find(Boolean))!=null?s:t.defaultBrandName)!=null?o:"Imported Brand",r=(c=i.map(ex).find(Boolean))!=null?c:{colors:{}},a=[];for(let l of i)"layers"in l&&a.push(...Jo(l.layers,"visual element")),"assets"in l&&a.push(...Jo(l.assets,"visual element")),ut(l.endgame)&&"assets"in l.endgame&&a.push(...Jo(l.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:r,assets:tx(a)}}import{GoogleGenAI as ix}from"@google/genai";async function ba(e,t,i=[],n={}){var r,a,s,o,c,l,d;try{if(!(e!=null&&e.trim()))throw new Error("Gemini API key is required");if(!(t!=null&&t.trim()))throw new Error("Prompt is required");for(let v=0;v<i.length;v++){let b=i[v];if(!b.base64||!b.mimeType)throw new Error(`Image ${v+1} is missing required data`);if(b.base64.length<1e3&&console.warn(`Image ${v+1} data appears very small, may be corrupted`),!b.mimeType.startsWith("image/"))throw new Error(`Image ${v+1} has invalid MIME type: ${b.mimeType}`)}let u=new ix({apiKey:e}),p="gemini-2.5-flash",f=[t];i.length>0&&i.forEach((v,b)=>{f.push({inlineData:{data:v.base64,mimeType:v.mimeType}}),console.log(`[Gemini] Added image ${b+1}: ${v.mimeType}, size: ${Math.round(v.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${i.length} images and prompt length: ${t.length}`);let m=await u.models.generateContent({model:p,contents:f}),h="",g=(s=(a=(r=m.candidates)==null?void 0:r[0])==null?void 0:a.content)==null?void 0:s.parts;if(g)for(let v of g)v.text&&(h+=v.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(u){throw console.error("[Gemini] API error:",u),(o=u.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(c=u.message)!=null&&c.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(l=u.message)!=null&&l.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(d=u.message)!=null&&d.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):u}}import{GoogleGenAI as nx}from"@google/genai";async function Fi(e,t,i=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let r=new nx({apiKey:e}),a=[{text:t}];i.length>0&&i.forEach((o,c)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${c}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let s=await r.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!s.candidates||!s.candidates[0]||!s.candidates[0].content||!s.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of s.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let c=o.inlineData.data,l=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${l};base64,${c}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(r){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(r,Object.getOwnPropertyNames(r),2)),r}}function sh(e){let t=e.brandAssets.map(a=>{let s=`- ${a.id}: ${a.role}`;return a.layout&&(s+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),s}).join(`
444
467
  `)||"None",i=e.brandDna?`Colors: ${JSON.stringify(e.brandDna.colors)}, Style: ${e.brandDna.style||"not specified"}`:"Not provided",n=e.gameObjects.map(a=>typeof a=="string"?`- id: ${a}`:`- id: ${a.id}${a.category?`, category: ${a.category}`:""}${a.type?`, type: ${a.type}`:""}`).join(`
445
468
  `),r="";if(e.brandConfig){let a=e.brandConfig,s=[];a.splash&&s.push(`SPLASH: title="${a.splash.title||""}", subtitle="${a.splash.subtitle||""}", button="${a.splash.button_label||""}"`),a.endgame&&s.push(`ENDGAME: title="${a.endgame.title||""}", subtitle="${a.endgame.subtitle||""}", cta="${a.endgame.cta_label||""}"`),a.tutorial&&s.push(`TUTORIAL: text="${a.tutorial.label_text||""}", helper="${a.tutorial.helper_text||""}"`),s.length>0&&(r=`
446
469
  BRAND CONTENT:
@@ -504,7 +527,7 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
504
527
  }
505
528
  ]
506
529
  }
507
- `.trim()}function Qf(e){var r,a;let t=(r=e.brandDna)!=null&&r.colors?`Primary: ${e.brandDna.colors.primary}, Secondary: ${e.brandDna.colors.secondary||"N/A"}, Accent: ${e.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",i=((a=e.brandDna)==null?void 0:a.style)||"modern gaming style",n=e.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
530
+ `.trim()}function oh(e){var r,a;let t=(r=e.brandDna)!=null&&r.colors?`Primary: ${e.brandDna.colors.primary}, Secondary: ${e.brandDna.colors.secondary||"N/A"}, Accent: ${e.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",i=((a=e.brandDna)==null?void 0:a.style)||"modern gaming style",n=e.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
508
531
  TASK: ${e.prompt}
509
532
 
510
533
  BRAND STYLE:
@@ -525,7 +548,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
525
548
 
526
549
  OUTPUT:
527
550
  Generate the requested asset matching the brand style.${e.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
528
- `.trim()}function eh(e){return e.map(t=>{if(typeof t=="string"){let i=t,n,r;return i.includes("background")?(n="background",r="background"):i.includes("button")||i.includes("cta")?(n="ui",r="button"):i.includes("logo")?(n="ui",r="logo"):i.includes("title")||i.includes("subtitle")||i.includes("text")?(n="text",r="text"):i.includes("effect")||i.includes("confetti")||i.includes("particle")?(n="effects",r="effect"):i.includes("ui.")||i.includes("splash")||i.includes("endgame")?(n="ui",r="image"):(n="environment",r="interactive"),{id:i,category:n,type:r}}return t})}function th(e,t){return!(e.includes("background")&&(e.includes("_1")||e.includes("splash")||e.includes("endgame")||e.includes("main"))||t==="text"||t==="effects"&&e.includes("particle"))}async function ih(e){var s,o;let t=eh(e.gameObjects),i={gamePrompt:e.gamePrompt,gameObjects:t,brandAssets:e.manifest.assets,brandDna:e.manifest.brand_dna,brandName:e.manifest.brand_name},n=Jf(i),r=[];if(e.flatDesignDataUrl)try{let c=nh(e.flatDesignDataUrl);c&&c.base64&&c.mimeType?c.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(r.push(c),console.log("[Pipeline] Added flat design to analysis, size:",c.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(c){console.warn("[Pipeline] Error processing flat design:",c)}console.log("[Pipeline] Running analysis chain with",r.length,"images...");let a;try{a=await ga(e.apiKey,n,r,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(c){throw console.error("[Pipeline] Gemini API error:",c),(s=c.message)!=null&&s.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=c.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):c}return Yy(a,e.gameObjects)}function Yy(e,t){try{let i=e,n=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)i=n[1].trim();else{let a=e.match(/\{[\s\S]*\}/);a&&(i=a[0])}let r=JSON.parse(i);return r.mappings&&Array.isArray(r.mappings)?{mappingResult:r,rawResponse:e,parsed:!0}:{mappingResult:{mappings:t.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:e,parsed:!1,parseError:"Missing mappings[] array"}}catch(i){return{mappingResult:{mappings:t.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:e,parsed:!1,parseError:i!=null&&i.message?String(i.message):"JSON parse failed"}}}async function Jo(e,t,i={}){var r;let n=t.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let s=n[a];(r=i.onProgress)==null||r.call(i,a+1,n.length,s.game_object);try{let o=await Vy(e,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function Vy(e,t){if(!t.generation_prompt)throw new Error("No generation prompt provided");let i=[];if(t.reference_asset&&e.manifest){let o=e.manifest.assets.find(c=>c.id===t.reference_asset);if(o){let c=e.assetFiles.get(o.file);if(c){let l=await Pt(c);l&&i.push({base64:l.base64,mimeType:l.mimeType})}}}if(e.flatDesignDataUrl){let o=nh(e.flatDesignDataUrl);o&&i.push(o)}let n=th(t.game_object),r={prompt:t.generation_prompt,hasReference:i.length>0,brandDna:e.manifest.brand_dna,needsTransparency:n},a=Qf(r);console.log(`[Pipeline] Generating asset for ${t.game_object}... (transparency: ${n})`);let s=await Fi(e.apiKey,a,i,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await Bi(s)||s}function nh(e){let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return i&&n?{base64:i,mimeType:n[1]}:null}async function rh(e,t){let i=e.assets,n=[];Array.isArray(i)?n=i:i&&typeof i=="object"?n=Object.entries(i).map(([r,a])=>({id:r,file:String(a),role:"visual element"})):n=[],e.assets=n;for(let r of n){let a=t.get(r.file);if(a){let s=await Pt(a);s&&(r.dataUrl=s.dataUrl)}}}var ba=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
551
+ `.trim()}function lh(e){return e.map(t=>{if(typeof t=="string"){let i=t,n,r;return i.includes("background")?(n="background",r="background"):i.includes("button")||i.includes("cta")?(n="ui",r="button"):i.includes("logo")?(n="ui",r="logo"):i.includes("title")||i.includes("subtitle")||i.includes("text")?(n="text",r="text"):i.includes("effect")||i.includes("confetti")||i.includes("particle")?(n="effects",r="effect"):i.includes("ui.")||i.includes("splash")||i.includes("endgame")?(n="ui",r="image"):(n="environment",r="interactive"),{id:i,category:n,type:r}}return t})}function ch(e,t){return!(e.includes("background")&&(e.includes("_1")||e.includes("splash")||e.includes("endgame")||e.includes("main"))||t==="text"||t==="effects"&&e.includes("particle"))}async function dh(e){var s,o;let t=lh(e.gameObjects),i={gamePrompt:e.gamePrompt,gameObjects:t,brandAssets:e.manifest.assets,brandDna:e.manifest.brand_dna,brandName:e.manifest.brand_name},n=sh(i),r=[];if(e.flatDesignDataUrl)try{let c=uh(e.flatDesignDataUrl);c&&c.base64&&c.mimeType?c.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(r.push(c),console.log("[Pipeline] Added flat design to analysis, size:",c.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(c){console.warn("[Pipeline] Error processing flat design:",c)}console.log("[Pipeline] Running analysis chain with",r.length,"images...");let a;try{a=await ba(e.apiKey,n,r,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(c){throw console.error("[Pipeline] Gemini API error:",c),(s=c.message)!=null&&s.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=c.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):c}return rx(a,e.gameObjects)}function rx(e,t){try{let i=e,n=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)i=n[1].trim();else{let a=e.match(/\{[\s\S]*\}/);a&&(i=a[0])}let r=JSON.parse(i);return r.mappings&&Array.isArray(r.mappings)?{mappingResult:r,rawResponse:e,parsed:!0}:{mappingResult:{mappings:t.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:e,parsed:!1,parseError:"Missing mappings[] array"}}catch(i){return{mappingResult:{mappings:t.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:e,parsed:!1,parseError:i!=null&&i.message?String(i.message):"JSON parse failed"}}}async function el(e,t,i={}){var r;let n=t.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let s=n[a];(r=i.onProgress)==null||r.call(i,a+1,n.length,s.game_object);try{let o=await ax(e,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function ax(e,t){if(!t.generation_prompt)throw new Error("No generation prompt provided");let i=[];if(t.reference_asset&&e.manifest){let o=e.manifest.assets.find(c=>c.id===t.reference_asset);if(o){let c=e.assetFiles.get(o.file);if(c){let l=await Mt(c);l&&i.push({base64:l.base64,mimeType:l.mimeType})}}}if(e.flatDesignDataUrl){let o=uh(e.flatDesignDataUrl);o&&i.push(o)}let n=ch(t.game_object),r={prompt:t.generation_prompt,hasReference:i.length>0,brandDna:e.manifest.brand_dna,needsTransparency:n},a=oh(r);console.log(`[Pipeline] Generating asset for ${t.game_object}... (transparency: ${n})`);let s=await Fi(e.apiKey,a,i,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await Bi(s)||s}function uh(e){let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return i&&n?{base64:i,mimeType:n[1]}:null}async function ph(e,t){let i=e.assets,n=[];Array.isArray(i)?n=i:i&&typeof i=="object"?n=Object.entries(i).map(([r,a])=>({id:r,file:String(a),role:"visual element"})):n=[],e.assets=n;for(let r of n){let a=t.get(r.file);if(a){let s=await Mt(a);s&&(r.dataUrl=s.dataUrl)}}}var va=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
529
552
  <div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
530
553
  <div class="scene-panel-header" data-panel-handle>
531
554
  <div class="panel-title">
@@ -641,15 +664,15 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
641
664
  </div>
642
665
  <div class="panel-resize-handle" data-panel-resize></div>
643
666
  </div>
644
- `}initialize(t,i){this.root=t.querySelector('[data-panel="brand-vision"]'),this.onClose=i,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var i,n,r,a,s,o,c,l,d,u,p,f,b;if(!this.root)return;(i=this.root.querySelector("[data-panel-close]"))==null||i.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let g=h.dataset.visionTab;this.switchTab(g)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let g=h.target.value;this.switchUploadMethod(g)}),(r=this.root.querySelector("[data-vision-upload-manifest]"))==null||r.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||g.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||g.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(c=this.root.querySelector("[data-vision-upload-assets]"))==null||c.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||g.click()}),(l=this.root.querySelector("[data-vision-assets-input]"))==null||l.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(d=this.root.querySelector("[data-vision-upload-flat]"))==null||d.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||g.click()}),(u=this.root.querySelector("[data-vision-flat-input]"))==null||u.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(p=this.root.querySelector("[data-vision-analyze]"))==null||p.addEventListener("click",()=>{this.runAnalysis()}),(f=this.root.querySelector("[data-vision-generate-all]"))==null||f.addEventListener("click",()=>{this.generateAllMissing()}),(b=this.root.querySelector("[data-vision-apply-all]"))==null||b.addEventListener("click",()=>{this.applyAll()});let t=this.root.querySelector("[data-vision-mappings]");t==null||t.addEventListener("click",h=>{let g=h.target;if(!g)return;let m=g.closest("[data-mapping-item]"),v=m==null?void 0:m.dataset.mappingItem;v&&(g.closest("[data-mapping-apply-one]")&&this.applyOne(v),g.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(v),g.closest("[data-mapping-edit-one]")&&this.openEditorForOne(v),g.closest("[data-mapping-generate-one]")&&this.generateOne(v),g.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),t==null||t.addEventListener("change",h=>{let g=h.target;if(!g||!this.mappingResult)return;let m=g.closest("[data-mapping-item]"),v=m==null?void 0:m.dataset.mappingItem;if(!v)return;let y=this.mappingResult.mappings.find(x=>x.game_object===v);y&&(g.matches("[data-mapping-action]")&&(y.action=String(g.value||"KEEP"),y.status="Edited",this.renderMappings()),g.matches("[data-mapping-brand-asset]")&&(y.brand_asset=String(g.value||""),y.status="Edited",this.renderMappings()))}),t==null||t.addEventListener("input",h=>{let g=h.target;if(!g||!this.mappingResult||!g.matches("[data-mapping-prompt]"))return;let m=g.closest("[data-mapping-item]"),v=m==null?void 0:m.dataset.mappingItem;if(!v)return;let y=this.mappingResult.mappings.find(x=>x.game_object===v);y&&(y.generation_prompt=String(g.value||""),y.status="Edited")})}switchTab(t){var i,n;this.root&&(this.currentTab=t,this.root.querySelectorAll("[data-vision-tab]").forEach(r=>r.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(r=>r.classList.remove("active")),(i=this.root.querySelector(`[data-vision-tab="${t}"]`))==null||i.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${t}"]`))==null||n.classList.add("active"))}switchUploadMethod(t){var i;this.root&&(this.uploadMethod=t,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(i=this.root.querySelector(`[data-vision-upload-section="${t}"]`))==null||i.classList.add("active"))}async handleZipUpload(t){var r;let n=(r=t.target.files)==null?void 0:r[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(t){var s,o;let i=await ah.default.loadAsync(t),n=[],r=[];i.forEach((c,l)=>{let d=c.toLowerCase();d.endsWith(".json")?n.push({name:c,content:null}):d.startsWith("assets/")&&d.endsWith(".png")&&r.push({name:c,file:l})});for(let c of n)try{let l=await((s=i.file(c.name))==null?void 0:s.async("text"));l&&(c.content=JSON.parse(l))}catch(l){console.warn(`Failed to parse ${c.name}:`,l)}let a=new Map;for(let c of r)try{let l=await c.file.async("uint8array"),d=new Blob([l],{type:"image/png"}),u=c.name.split("/").pop()||c.name;console.log(`Processing ${u}, uint8array length: ${l.length}, blob size: ${d.size}`);let p;try{p=await this.blobToDataUrl(d)}catch(g){console.warn(`FileReader failed for ${u}, using fallback:`,g),p=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(l)))}`}if(console.log(`Data URL length: ${p.length}, starts with: ${p.substring(0,50)}...`),!p.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${u}:`,p.substring(0,100));continue}let f=this.inferAssetCategory(u.replace(".png",""));console.log(`Saving ${u} to category: ${f}`);let h=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:f,filename:u,data:p,overwrite:!0})})).json();if(console.log(`Save result for ${u}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${u} (${f}) at ${h.path}`);let g=new File([d],u,{type:"image/png"});a.set(u,g)}else console.warn(`\u274C Failed to save ${u}:`,h.error)}catch(l){console.warn(`Failed to extract ${c.name}:`,l)}this.uploadedJsons.clear(),n.forEach(({name:c,content:l})=>{l&&this.uploadedJsons.set(c,l)}),this.assetFiles=a;try{this.normalizedManifest=Zo(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let c=[];for(let[d,u]of a){let p=await this.fileToDataUrl(u);c.push({id:d.replace(".png",""),filename:d,dataUrl:p,category:this.inferAssetCategory(d.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=c);let l=c.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${l} PNGs
667
+ `}initialize(t,i){this.root=t.querySelector('[data-panel="brand-vision"]'),this.onClose=i,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var i,n,r,a,s,o,c,l,d,u,p,f,m;if(!this.root)return;(i=this.root.querySelector("[data-panel-close]"))==null||i.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let g=h.dataset.visionTab;this.switchTab(g)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let g=h.target.value;this.switchUploadMethod(g)}),(r=this.root.querySelector("[data-vision-upload-manifest]"))==null||r.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||g.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||g.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(c=this.root.querySelector("[data-vision-upload-assets]"))==null||c.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||g.click()}),(l=this.root.querySelector("[data-vision-assets-input]"))==null||l.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(d=this.root.querySelector("[data-vision-upload-flat]"))==null||d.addEventListener("click",()=>{var h,g;(g=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||g.click()}),(u=this.root.querySelector("[data-vision-flat-input]"))==null||u.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(p=this.root.querySelector("[data-vision-analyze]"))==null||p.addEventListener("click",()=>{this.runAnalysis()}),(f=this.root.querySelector("[data-vision-generate-all]"))==null||f.addEventListener("click",()=>{this.generateAllMissing()}),(m=this.root.querySelector("[data-vision-apply-all]"))==null||m.addEventListener("click",()=>{this.applyAll()});let t=this.root.querySelector("[data-vision-mappings]");t==null||t.addEventListener("click",h=>{let g=h.target;if(!g)return;let v=g.closest("[data-mapping-item]"),b=v==null?void 0:v.dataset.mappingItem;b&&(g.closest("[data-mapping-apply-one]")&&this.applyOne(b),g.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(b),g.closest("[data-mapping-edit-one]")&&this.openEditorForOne(b),g.closest("[data-mapping-generate-one]")&&this.generateOne(b),g.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),t==null||t.addEventListener("change",h=>{let g=h.target;if(!g||!this.mappingResult)return;let v=g.closest("[data-mapping-item]"),b=v==null?void 0:v.dataset.mappingItem;if(!b)return;let y=this.mappingResult.mappings.find(x=>x.game_object===b);y&&(g.matches("[data-mapping-action]")&&(y.action=String(g.value||"KEEP"),y.status="Edited",this.renderMappings()),g.matches("[data-mapping-brand-asset]")&&(y.brand_asset=String(g.value||""),y.status="Edited",this.renderMappings()))}),t==null||t.addEventListener("input",h=>{let g=h.target;if(!g||!this.mappingResult||!g.matches("[data-mapping-prompt]"))return;let v=g.closest("[data-mapping-item]"),b=v==null?void 0:v.dataset.mappingItem;if(!b)return;let y=this.mappingResult.mappings.find(x=>x.game_object===b);y&&(y.generation_prompt=String(g.value||""),y.status="Edited")})}switchTab(t){var i,n;this.root&&(this.currentTab=t,this.root.querySelectorAll("[data-vision-tab]").forEach(r=>r.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(r=>r.classList.remove("active")),(i=this.root.querySelector(`[data-vision-tab="${t}"]`))==null||i.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${t}"]`))==null||n.classList.add("active"))}switchUploadMethod(t){var i;this.root&&(this.uploadMethod=t,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(i=this.root.querySelector(`[data-vision-upload-section="${t}"]`))==null||i.classList.add("active"))}async handleZipUpload(t){var r;let n=(r=t.target.files)==null?void 0:r[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(t){var s,o;let i=await fh.default.loadAsync(t),n=[],r=[];i.forEach((c,l)=>{let d=c.toLowerCase();d.endsWith(".json")?n.push({name:c,content:null}):d.startsWith("assets/")&&d.endsWith(".png")&&r.push({name:c,file:l})});for(let c of n)try{let l=await((s=i.file(c.name))==null?void 0:s.async("text"));l&&(c.content=JSON.parse(l))}catch(l){console.warn(`Failed to parse ${c.name}:`,l)}let a=new Map;for(let c of r)try{let l=await c.file.async("uint8array"),d=new Blob([l],{type:"image/png"}),u=c.name.split("/").pop()||c.name;console.log(`Processing ${u}, uint8array length: ${l.length}, blob size: ${d.size}`);let p;try{p=await this.blobToDataUrl(d)}catch(g){console.warn(`FileReader failed for ${u}, using fallback:`,g),p=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(l)))}`}if(console.log(`Data URL length: ${p.length}, starts with: ${p.substring(0,50)}...`),!p.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${u}:`,p.substring(0,100));continue}let f=this.inferAssetCategory(u.replace(".png",""));console.log(`Saving ${u} to category: ${f}`);let h=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:f,filename:u,data:p,overwrite:!0})})).json();if(console.log(`Save result for ${u}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${u} (${f}) at ${h.path}`);let g=new File([d],u,{type:"image/png"});a.set(u,g)}else console.warn(`\u274C Failed to save ${u}:`,h.error)}catch(l){console.warn(`Failed to extract ${c.name}:`,l)}this.uploadedJsons.clear(),n.forEach(({name:c,content:l})=>{l&&this.uploadedJsons.set(c,l)}),this.assetFiles=a;try{this.normalizedManifest=Qo(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let c=[];for(let[d,u]of a){let p=await this.fileToDataUrl(u);c.push({id:d.replace(".png",""),filename:d,dataUrl:p,category:this.inferAssetCategory(d.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=c);let l=c.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${l} PNGs
645
668
  \u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(c),this.refreshLibrary()}catch(c){console.error("[BrandVision] Failed to normalize ZIP manifest:",c),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(t){return new Promise((i,n)=>{let r=new FileReader;r.onload=()=>i(r.result),r.onerror=n,r.readAsDataURL(t)})}async blobToDataUrl(t){return new Promise((i,n)=>{let r=new FileReader;r.onload=()=>{let a=r.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),i(a)},r.onerror=a=>{console.error("FileReader error:",a),n(a)},r.readAsDataURL(t)})}inferAssetCategory(t){let i=t.toLowerCase();return i.includes("background")||i.includes("bg")?"backgrounds":i.includes("ui")||i.includes("button")||i.includes("cta")||i.includes("logo")||i.includes("text")?"ui":i.includes("sparkle")||i.includes("effect")||i.includes("particle")?"effects":i.includes("bottle")||i.includes("product")||i.includes("item")?"products":"misc"}addAssetsToRegistry(t){let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!(n!=null&&n.libraryAssets))return;let r={};for(let a of t){let s=a.category||"misc";r[s]||(r[s]=[]),n.libraryAssets[s]||(n.libraryAssets[s]=[]),n.libraryAssets[s].some(c=>c.filename===a.filename)||(n.libraryAssets[s].unshift({filename:a.filename,displayName:a.id.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase())}),console.log(`[BrandVision] Added ${a.filename} to registry category ${s}`))}}refreshLibrary(){let t=window.refreshAssetLibrary;typeof t=="function"&&t();let i=window.reRenderAssetLibrary;typeof i=="function"&&i()}async handleManifestUpload(t){var a;let i=t.target,n=i.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let r="";for(let s of Array.from(n))try{let o=await s.text(),c=JSON.parse(o);this.uploadedJsons.set(s.name,c),c.layers?r+=`\u2705 Layers: ${s.name}
646
669
  `:c.brand_dna||c.colors?r+=`\u2705 Brand: ${s.name}
647
670
  `:r+=`\u2705 Loaded: ${s.name}
648
671
  `}catch{r+=`\u274C Error in ${s.name}
649
- `}try{this.normalizedManifest=Zo(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let s=Array.isArray((a=this.normalizedManifest)==null?void 0:a.assets)?this.normalizedManifest.assets.length:0;r+=`
672
+ `}try{this.normalizedManifest=Qo(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let s=Array.isArray((a=this.normalizedManifest)==null?void 0:a.assets)?this.normalizedManifest.assets.length:0;r+=`
650
673
  \u{1F4E6} Normalized manifest: ${s} assets`,r+=`
651
674
  \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:s,brandName:this.normalizedManifest.brand_name})}catch(s){console.error("[BrandVision] Failed to normalize manifest:",s),this.normalizedManifest=null,r+=`
652
- \u274C Failed to normalize manifest`}i.value="",this.setStatus("manifest",r.trim())}async handleAssetsUpload(t){let n=t.target.files;if(!(!n||n.length===0)){for(let r of Array.from(n))this.assetFiles.set(r.name,r);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(t){var a,s;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let r=await Pt(n);if(r){this.flatDesignDataUrl=r.dataUrl,this.setStatus("flat",n.name);let o=(s=this.root)==null?void 0:s.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${r.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,r,a,s,o,c,l;if(this.isAnalyzing)return;let t=(a=(r=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:a.trim();if(!t){this.setStatus("upload","Missing API key");return}let i=this.manifest;if(!i){this.setStatus("upload","Upload manifest first");return}Array.isArray(i.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:i.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await rh(i,this.assetFiles);let d={apiKey:t,manifest:i,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},u=await ih(d);this.mappingResult=u.mappingResult,this.analysisRawResponse=u.rawResponse,this.analysisParsedOk=u.parsed,this.analysisParseError=(s=u.parseError)!=null?s:null,this.renderMappings(),u.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(l=(c=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:c.length)!=null?l:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${u.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(d){console.error("[BrandVision] Analysis failed:",d),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var i,n,r;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let t=(r=(n=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:r.trim();if(!t){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:t,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await Jo(a,this.mappingResult,{onProgress:(s,o,c)=>{this.setStatus("apply",`Generating ${s}/${o}: ${c}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let t=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!t||!this.mappingResult)return;let i=this.manifest,n=this.getEngineAssets(),r=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((i==null?void 0:i.assets)||[]).map(c=>`<option value="${c.id}">${c.id}</option>`).join(""),s=r?`
675
+ \u274C Failed to normalize manifest`}i.value="",this.setStatus("manifest",r.trim())}async handleAssetsUpload(t){let n=t.target.files;if(!(!n||n.length===0)){for(let r of Array.from(n))this.assetFiles.set(r.name,r);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(t){var a,s;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let r=await Mt(n);if(r){this.flatDesignDataUrl=r.dataUrl,this.setStatus("flat",n.name);let o=(s=this.root)==null?void 0:s.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${r.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,r,a,s,o,c,l;if(this.isAnalyzing)return;let t=(a=(r=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:a.trim();if(!t){this.setStatus("upload","Missing API key");return}let i=this.manifest;if(!i){this.setStatus("upload","Upload manifest first");return}Array.isArray(i.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:i.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await ph(i,this.assetFiles);let d={apiKey:t,manifest:i,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},u=await dh(d);this.mappingResult=u.mappingResult,this.analysisRawResponse=u.rawResponse,this.analysisParsedOk=u.parsed,this.analysisParseError=(s=u.parseError)!=null?s:null,this.renderMappings(),u.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(l=(c=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:c.length)!=null?l:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${u.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(d){console.error("[BrandVision] Analysis failed:",d),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var i,n,r;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let t=(r=(n=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:r.trim();if(!t){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:t,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await el(a,this.mappingResult,{onProgress:(s,o,c)=>{this.setStatus("apply",`Generating ${s}/${o}: ${c}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let t=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!t||!this.mappingResult)return;let i=this.manifest,n=this.getEngineAssets(),r=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((i==null?void 0:i.assets)||[]).map(c=>`<option value="${c.id}">${c.id}</option>`).join(""),s=r?`
653
676
  <div class="vision-raw-block">
654
677
  <div class="inspector-text-sm" style="white-space: pre-wrap;">
655
678
  \u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
@@ -659,7 +682,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
659
682
  </div>
660
683
  `:"";t.innerHTML=`
661
684
  ${s}
662
- ${this.mappingResult.mappings.map(c=>{var m;let l=n[c.game_object]||"",d=c.brand_asset||"",u=(m=i==null?void 0:i.assets)==null?void 0:m.find(v=>v.id===d),p=(u==null?void 0:u.dataUrl)||"",f=c.output_dataUrl||"",b=c.action==="GENERATE"?f:c.action==="APPLY"?p:"",h=!!b,g=`
685
+ ${this.mappingResult.mappings.map(c=>{var v;let l=n[c.game_object]||"",d=c.brand_asset||"",u=(v=i==null?void 0:i.assets)==null?void 0:v.find(b=>b.id===d),p=(u==null?void 0:u.dataUrl)||"",f=c.output_dataUrl||"",m=c.action==="GENERATE"?f:c.action==="APPLY"?p:"",h=!!m,g=`
663
686
  <select class="inspector-input" data-mapping-brand-asset style="flex:1; padding:6px 8px;">
664
687
  <option value="">Select brand asset\u2026</option>
665
688
  ${a.replace(`value="${d}"`,`value="${d}" selected`)}
@@ -700,7 +723,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
700
723
  </div>
701
724
  <div class="vision-mapping-preview">
702
725
  <div class="inspector-text-sm" style="opacity:0.8;">Preview</div>
703
- ${h?`<img src="${b}">`:'<div class="inspector-text-sm" style="opacity:0.6;">None</div>'}
726
+ ${h?`<img src="${m}">`:'<div class="inspector-text-sm" style="opacity:0.6;">None</div>'}
704
727
  </div>
705
728
  </div>
706
729
 
@@ -711,8 +734,8 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
711
734
  </div>
712
735
  </div>
713
736
  `}).join("")}
714
- `}async applyAll(){let t=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",t>0?`Staged ${t} asset overrides`:"No assets to stage")}getEngineAssets(){let t=window.getEditableEngineConfig;if(typeof t!="function")return{};let i=t();return i!=null&&i.assets&&typeof i.assets=="object"?i.assets:{}}getPreviewValueForMapping(t){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let i=this.mappingResult.mappings.find(n=>n.game_object===t);if(!i)return{value:null,source:"none"};if(i.action==="GENERATE"&&i.output_dataUrl)return{value:i.output_dataUrl,source:"generated"};if(i.action==="APPLY"&&i.brand_asset){let n=this.manifest.assets.find(r=>r.id===i.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(t){if(!this.mappingResult)return 0;let i=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let r=n.game_object,a=this.getPreviewValueForMapping(r);if(!a.value)continue;let s=t.saveToLibrary?await this.saveToLibraryAndReturnPath(r,a.value):a.value;s&&(await this.stageEngineAssetOverride(r,s),n.status=t.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",i++)}return this.renderMappings(),i}async applyOne(t){var r;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to apply for ${t}`);return}await this.stageEngineAssetOverride(t,i.value);let n=(r=this.mappingResult)==null?void 0:r.mappings.find(a=>a.game_object===t);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${t}`)}async saveAndApplyOne(t){var a;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to save for ${t}`);return}let n=await this.saveToLibraryAndReturnPath(t,i.value);if(!n){this.setStatus("apply",`Save failed for ${t}`);return}await this.stageEngineAssetOverride(t,n);let r=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===t);r&&(r.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${t}`)}openEditorForOne(t){if(!this.mappingResult)return;let i=this.mappingResult.mappings.find(s=>s.game_object===t);if(!i)return;let n=this.getPreviewValueForMapping(t),r=window.__openAiEditor;if(typeof r!="function"){this.setStatus("apply","AI editor not available");return}let a=i.action==="GENERATE"?i.generation_prompt:void 0;r(t,a,n.value||void 0,{path:`assets.${t}`})}async generateOne(t){var r,a,s;if(!this.mappingResult||this.isGenerating)return;let i=this.mappingResult.mappings.find(o=>o.game_object===t);if(!i)return;if(i.action="GENERATE",!i.generation_prompt){i.status="Missing prompt",this.renderMappings();return}let n=(s=(a=(r=this.root)==null?void 0:r.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,i.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await Jo(o,{mappings:[i]}),i.status=i.output_dataUrl?"Generated \u2713":i.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),i.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(t,i){let{applyConfigOverride:n}=await import("./ConfigOverride-C26KK6X2.js");n({path:`assets.${t}`,value:i},{silent:!0});let r=window.applyEditableEngineConfig;typeof r=="function"&&r({assets:{[t]:i}})}async saveToLibraryAndReturnPath(t,i){if(!/^(data:|blob:)/.test(i))return i;let n=this.inferCategoryFromAssetKey(t),r=`${t.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let s=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:r,data:i,overwrite:!0})})).json();if(!(s!=null&&s.success)||!(s!=null&&s.path))return console.error("[BrandVision] Save to library failed:",(s==null?void 0:s.error)||s),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,r);let c=window.refreshAssetLibrary;return typeof c=="function"&&c(),String(s.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(t){let i=window.getEditableAssets;if(typeof i=="function"){let r=i();if(r!=null&&r.slots&&Array.isArray(r.slots)){let s=r.slots.find(o=>o.slotId===t||o.currentAsset===t);if(s!=null&&s.category)return String(s.category)}let a=r==null?void 0:r.categories;if(Array.isArray(a)&&a.length>0){let s=t.toLowerCase(),o=c=>a.find(l=>l.toLowerCase().includes(c));return s.includes("bg")||s.includes("background")?o("background")||a[0]:(s.includes("cta")||s.includes("button")||s.includes("ui")||s.includes("logo"))&&o("ui")||a[0]}}let n=t.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(t,i){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},r=(a=this.root)==null?void 0:a.querySelector(n[t]);r&&(r.textContent=i)}getGameObjects(){let t=window.getEditableObjectList;return typeof t=="function"?t():[]}async getGamePrompt(){try{let t=await fetch("./configs/engine/game.prompt.json");if(t.ok)return(await t.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");t&&t.addEventListener("pointerdown",i=>{let n=i.clientX,r=this.root.getBoundingClientRect().width,a=o=>{let c=Math.max(300,r+(o.clientX-n));this.root.style.width=`${c}px`},s=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",s)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",s)})}refresh(){}};function sh(e,t={}){let{includeReference:i=!1,includeMagenta:n=!0,changeLevel:r=5}=t;return[`TASK: ${e}`,`CHANGE_STRENGTH: ${r}/10`,i?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
715
- `)}var Ky=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],Xy=["cta_hint","cta_label_end"],oh=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],Zy=["brand.primary","brand.heading","brand.body","brand.warning"],ma=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
737
+ `}async applyAll(){let t=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",t>0?`Staged ${t} asset overrides`:"No assets to stage")}getEngineAssets(){let t=window.getEditableEngineConfig;if(typeof t!="function")return{};let i=t();return i!=null&&i.assets&&typeof i.assets=="object"?i.assets:{}}getPreviewValueForMapping(t){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let i=this.mappingResult.mappings.find(n=>n.game_object===t);if(!i)return{value:null,source:"none"};if(i.action==="GENERATE"&&i.output_dataUrl)return{value:i.output_dataUrl,source:"generated"};if(i.action==="APPLY"&&i.brand_asset){let n=this.manifest.assets.find(r=>r.id===i.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(t){if(!this.mappingResult)return 0;let i=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let r=n.game_object,a=this.getPreviewValueForMapping(r);if(!a.value)continue;let s=t.saveToLibrary?await this.saveToLibraryAndReturnPath(r,a.value):a.value;s&&(await this.stageEngineAssetOverride(r,s),n.status=t.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",i++)}return this.renderMappings(),i}async applyOne(t){var r;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to apply for ${t}`);return}await this.stageEngineAssetOverride(t,i.value);let n=(r=this.mappingResult)==null?void 0:r.mappings.find(a=>a.game_object===t);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${t}`)}async saveAndApplyOne(t){var a;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to save for ${t}`);return}let n=await this.saveToLibraryAndReturnPath(t,i.value);if(!n){this.setStatus("apply",`Save failed for ${t}`);return}await this.stageEngineAssetOverride(t,n);let r=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===t);r&&(r.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${t}`)}openEditorForOne(t){if(!this.mappingResult)return;let i=this.mappingResult.mappings.find(s=>s.game_object===t);if(!i)return;let n=this.getPreviewValueForMapping(t),r=window.__openAiEditor;if(typeof r!="function"){this.setStatus("apply","AI editor not available");return}let a=i.action==="GENERATE"?i.generation_prompt:void 0;r(t,a,n.value||void 0,{path:`assets.${t}`})}async generateOne(t){var r,a,s;if(!this.mappingResult||this.isGenerating)return;let i=this.mappingResult.mappings.find(o=>o.game_object===t);if(!i)return;if(i.action="GENERATE",!i.generation_prompt){i.status="Missing prompt",this.renderMappings();return}let n=(s=(a=(r=this.root)==null?void 0:r.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,i.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await el(o,{mappings:[i]}),i.status=i.output_dataUrl?"Generated \u2713":i.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),i.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(t,i){let{applyConfigOverride:n}=await import("./ConfigOverride-C26KK6X2.js");n({path:`assets.${t}`,value:i},{silent:!0});let r=window.applyEditableEngineConfig;typeof r=="function"&&r({assets:{[t]:i}})}async saveToLibraryAndReturnPath(t,i){if(!/^(data:|blob:)/.test(i))return i;let n=this.inferCategoryFromAssetKey(t),r=`${t.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let s=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:r,data:i,overwrite:!0})})).json();if(!(s!=null&&s.success)||!(s!=null&&s.path))return console.error("[BrandVision] Save to library failed:",(s==null?void 0:s.error)||s),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,r);let c=window.refreshAssetLibrary;return typeof c=="function"&&c(),String(s.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(t){let i=window.getEditableAssets;if(typeof i=="function"){let r=i();if(r!=null&&r.slots&&Array.isArray(r.slots)){let s=r.slots.find(o=>o.slotId===t||o.currentAsset===t);if(s!=null&&s.category)return String(s.category)}let a=r==null?void 0:r.categories;if(Array.isArray(a)&&a.length>0){let s=t.toLowerCase(),o=c=>a.find(l=>l.toLowerCase().includes(c));return s.includes("bg")||s.includes("background")?o("background")||a[0]:(s.includes("cta")||s.includes("button")||s.includes("ui")||s.includes("logo"))&&o("ui")||a[0]}}let n=t.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(t,i){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},r=(a=this.root)==null?void 0:a.querySelector(n[t]);r&&(r.textContent=i)}getGameObjects(){let t=window.getEditableObjectList;return typeof t=="function"?t():[]}async getGamePrompt(){try{let t=await fetch("./configs/engine/game.prompt.json");if(t.ok)return(await t.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");t&&t.addEventListener("pointerdown",i=>{let n=i.clientX,r=this.root.getBoundingClientRect().width,a=o=>{let c=Math.max(300,r+(o.clientX-n));this.root.style.width=`${c}px`},s=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",s)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",s)})}refresh(){}};function hh(e,t={}){let{includeReference:i=!1,includeMagenta:n=!0,changeLevel:r=5}=t;return[`TASK: ${e}`,`CHANGE_STRENGTH: ${r}/10`,i?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
738
+ `)}var sx=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],ox=["cta_hint","cta_label_end"],gh=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],lx=["brand.primary","brand.heading","brand.body","brand.warning"],ya=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
716
739
  <div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
717
740
  <div class="scene-panel-header" data-panel-handle>
718
741
  <div class="panel-title">
@@ -780,7 +803,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
780
803
  <path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
781
804
  <path d="M5 14v4h14v-4h2v6H3v-6h2z" />
782
805
  </svg>
783
- `;let u=document.createElement("input");u.type="file",u.accept="image/*,audio/*,application/json",u.className="customize-file",u.addEventListener("change",()=>{var b;let f=(b=u.files)==null?void 0:b[0];f&&this.handleAssetUpload(f,o,n)}),d.addEventListener("click",()=>u.click()),c.appendChild(l),c.appendChild(d),c.appendChild(u),a.appendChild(s),a.appendChild(o),a.appendChild(c),(p=this.assetsContainer)==null||p.appendChild(a)})}renderColors(t){this.colorsContainer&&(this.colorsContainer.innerHTML="",Ky.forEach(i=>{var c,l,d;let n=(c=t==null?void 0:t[i])!=null?c:"#ffffff";if(i.includes("_text_color")||i.includes("_color")){let p={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[i];p&&(n=(l=this.getObjectPropertyValue(p.objectId,p.property))!=null?l:"#ffffff")}let r=document.createElement("label");r.className="customize-color-field";let a=document.createElement("span");a.textContent=i.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=i;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=i,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),r.appendChild(a),r.appendChild(s),r.appendChild(o),(d=this.colorsContainer)==null||d.appendChild(r)}))}renderFonts(t){this.fontsContainer&&(this.fontsContainer.innerHTML="",Zy.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=t==null?void 0:t[i])!=null?s:i,a.className="customize-input",a.dataset.fontKey=i,n.appendChild(r),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(t){this.textsContainer&&(this.textsContainer.innerHTML="",Xy.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=this.readUiValue(t,i))!=null?s:"",a.className="customize-input",a.dataset.textKey=i,n.appendChild(r),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),oh.forEach(({key:i,objectId:n})=>{var o,c;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=i;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=i,r.appendChild(a),r.appendChild(s),(c=this.textsContainer)==null||c.appendChild(r)}))}renderAudio(t){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,c;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=t==null?void 0:t[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),r.appendChild(a),r.appendChild(s),(c=this.audioContainer)==null||c.appendChild(r)})}readUiValue(t,i){if(i.includes(".")){let r=i.split("."),a=t;for(let s of r){if(a==null)return null;a=a[s]}return typeof a=="string"?a:null}let n=t==null?void 0:t[i];return typeof n=="string"?n:null}getObjectTextValue(t){var r,a;let i=window.getEditableObjectConfig;if(typeof i!="function")return null;let n=i(t);return(a=(r=n==null?void 0:n.ui)==null?void 0:r.text)!=null?a:null}getObjectPropertyValue(t,i){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let r=n(t);if(!r)return null;let a=i.split("."),s=r;for(let o of a){if(s==null)return null;s=s[o]}return typeof s=="string"?s:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(t){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${t}`),!this.root||!this.options)return;let i={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let c=o;c.dataset.assetKey&&(i[c.dataset.assetKey]=c.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(i).length,"total"),console.log("[CustomizePanel] Asset values:",i);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let c=o,l=c.dataset.colorTextKey;l&&(l.includes("_text_color")||l.includes("_color")?this.applyTextColorToObject(l,c.value):n[l]=c.value)});let r={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let c=o,l=c.dataset.fontKey;l&&(r[l]=c.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let c=o,l=c.dataset.textKey;l&&(a[l]=c.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let c=o,l=c.dataset.audioKey;if(l)if(l.includes("volume")){let d=parseFloat(c.value);s[l]=isNaN(d)?0:d}else s[l]=c.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let c=o,l=c.dataset.objectTextKey;if(!l)return;let d=oh.find(u=>u.key===l);d&&this.applyObjectPropertyValue(d.objectId,d.property,c.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",t),this.options.onApply({assets:i,runtime:{theme:n,ui:a,fonts:r,audio:s}},{source:t})}setupAiPanel(){}setAiStatus(t){this.aiStatusEl&&(this.aiStatusEl.textContent=t)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let t=this.getSelectedAssetKey();return!this.root||!t?null:this.root.querySelector(`input[data-asset-key="${t}"]`)}async getImageDataFromAsset(t){let i=this.resolveAssetUrls(t);console.log("[CustomizePanel] Resolving asset urls for AI:",t,i);for(let n of i)try{let r=await ha(n);if(r)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:r.base64,mimeType:r.mimeType},dataUrl:r.dataUrl,width:r.width,height:r.height}}catch(r){console.warn("[CustomizePanel] Failed to fetch image data from:",n,r)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(t){var r,a,s;let i=(t==null?void 0:t.trim())||"";if(!i){let o=this.getSelectedAssetInput();i=(a=(r=o==null?void 0:o.value)==null?void 0:r.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",i),!i){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(i);this.aiBaseDataUrl=(s=n==null?void 0:n.dataUrl)!=null?s:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let t=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!t){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=t}updateAiModalPreview(t,i){if(!t)return;let n=i!=null?i:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){t.classList.add("hidden");return}let r=t.querySelector(".asset-preview-ai-image");r&&(r.src=this.aiOutputDataUrl),t.classList.remove("hidden")}setAiLoading(t){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",t),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=t)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let t=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=t?"Gallery":"Hide Gallery",t||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let t=this.getAiGalleryEntries();if(!t.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",t.forEach(({key:i,value:n})=>{var c;let r=document.createElement("button");r.type="button",r.className="ai-gallery-item",i===this.aiTargetKey&&r.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=i;let s=this.resolveAssetUrls(n);s[0]&&(a.src=s[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=i,r.appendChild(a),r.appendChild(o),r.addEventListener("click",()=>this.selectAiGalleryAsset(i)),(c=this.aiGalleryGrid)==null||c.appendChild(r)})}getAiGalleryEntries(){if(!this.root)return[];let t=[];return this.root.querySelectorAll("[data-asset-key]").forEach(i=>{var s,o;let n=i,r=n.dataset.assetKey,a=(o=(s=n.value)==null?void 0:s.trim())!=null?o:"";!r||!a||this.isAiGalleryImage(a)&&t.push({key:r,value:a})}),t}isAiGalleryImage(t){let i=t.trim();if(!i)return!1;if(/^(data:image|blob:)/.test(i))return!0;let n=i.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(r=>n.endsWith(r))}selectAiGalleryAsset(t){this.aiTargetKey!==t&&(this.aiTargetKey=t,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=t),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(t,i,n){var o,c,l,d,u,p,f,b,h,g;this.closeAiModal(),this.aiTargetKey=t,this.aiBaseValue=i||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let r=document.createElement("div");r.className="ai-modal",r.innerHTML=`
806
+ `;let u=document.createElement("input");u.type="file",u.accept="image/*,audio/*,application/json",u.className="customize-file",u.addEventListener("change",()=>{var m;let f=(m=u.files)==null?void 0:m[0];f&&this.handleAssetUpload(f,o,n)}),d.addEventListener("click",()=>u.click()),c.appendChild(l),c.appendChild(d),c.appendChild(u),a.appendChild(s),a.appendChild(o),a.appendChild(c),(p=this.assetsContainer)==null||p.appendChild(a)})}renderColors(t){this.colorsContainer&&(this.colorsContainer.innerHTML="",sx.forEach(i=>{var c,l,d;let n=(c=t==null?void 0:t[i])!=null?c:"#ffffff";if(i.includes("_text_color")||i.includes("_color")){let p={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[i];p&&(n=(l=this.getObjectPropertyValue(p.objectId,p.property))!=null?l:"#ffffff")}let r=document.createElement("label");r.className="customize-color-field";let a=document.createElement("span");a.textContent=i.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=i;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=i,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),r.appendChild(a),r.appendChild(s),r.appendChild(o),(d=this.colorsContainer)==null||d.appendChild(r)}))}renderFonts(t){this.fontsContainer&&(this.fontsContainer.innerHTML="",lx.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=t==null?void 0:t[i])!=null?s:i,a.className="customize-input",a.dataset.fontKey=i,n.appendChild(r),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(t){this.textsContainer&&(this.textsContainer.innerHTML="",ox.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=this.readUiValue(t,i))!=null?s:"",a.className="customize-input",a.dataset.textKey=i,n.appendChild(r),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),gh.forEach(({key:i,objectId:n})=>{var o,c;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=i;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=i,r.appendChild(a),r.appendChild(s),(c=this.textsContainer)==null||c.appendChild(r)}))}renderAudio(t){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,c;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=t==null?void 0:t[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),r.appendChild(a),r.appendChild(s),(c=this.audioContainer)==null||c.appendChild(r)})}readUiValue(t,i){if(i.includes(".")){let r=i.split("."),a=t;for(let s of r){if(a==null)return null;a=a[s]}return typeof a=="string"?a:null}let n=t==null?void 0:t[i];return typeof n=="string"?n:null}getObjectTextValue(t){var r,a;let i=window.getEditableObjectConfig;if(typeof i!="function")return null;let n=i(t);return(a=(r=n==null?void 0:n.ui)==null?void 0:r.text)!=null?a:null}getObjectPropertyValue(t,i){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let r=n(t);if(!r)return null;let a=i.split("."),s=r;for(let o of a){if(s==null)return null;s=s[o]}return typeof s=="string"?s:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(t){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${t}`),!this.root||!this.options)return;let i={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let c=o;c.dataset.assetKey&&(i[c.dataset.assetKey]=c.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(i).length,"total"),console.log("[CustomizePanel] Asset values:",i);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let c=o,l=c.dataset.colorTextKey;l&&(l.includes("_text_color")||l.includes("_color")?this.applyTextColorToObject(l,c.value):n[l]=c.value)});let r={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let c=o,l=c.dataset.fontKey;l&&(r[l]=c.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let c=o,l=c.dataset.textKey;l&&(a[l]=c.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let c=o,l=c.dataset.audioKey;if(l)if(l.includes("volume")){let d=parseFloat(c.value);s[l]=isNaN(d)?0:d}else s[l]=c.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let c=o,l=c.dataset.objectTextKey;if(!l)return;let d=gh.find(u=>u.key===l);d&&this.applyObjectPropertyValue(d.objectId,d.property,c.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",t),this.options.onApply({assets:i,runtime:{theme:n,ui:a,fonts:r,audio:s}},{source:t})}setupAiPanel(){}setAiStatus(t){this.aiStatusEl&&(this.aiStatusEl.textContent=t)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let t=this.getSelectedAssetKey();return!this.root||!t?null:this.root.querySelector(`input[data-asset-key="${t}"]`)}async getImageDataFromAsset(t){let i=this.resolveAssetUrls(t);console.log("[CustomizePanel] Resolving asset urls for AI:",t,i);for(let n of i)try{let r=await ma(n);if(r)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:r.base64,mimeType:r.mimeType},dataUrl:r.dataUrl,width:r.width,height:r.height}}catch(r){console.warn("[CustomizePanel] Failed to fetch image data from:",n,r)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(t){var r,a,s;let i=(t==null?void 0:t.trim())||"";if(!i){let o=this.getSelectedAssetInput();i=(a=(r=o==null?void 0:o.value)==null?void 0:r.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",i),!i){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(i);this.aiBaseDataUrl=(s=n==null?void 0:n.dataUrl)!=null?s:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let t=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!t){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=t}updateAiModalPreview(t,i){if(!t)return;let n=i!=null?i:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){t.classList.add("hidden");return}let r=t.querySelector(".asset-preview-ai-image");r&&(r.src=this.aiOutputDataUrl),t.classList.remove("hidden")}setAiLoading(t){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",t),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=t)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let t=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=t?"Gallery":"Hide Gallery",t||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let t=this.getAiGalleryEntries();if(!t.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",t.forEach(({key:i,value:n})=>{var c;let r=document.createElement("button");r.type="button",r.className="ai-gallery-item",i===this.aiTargetKey&&r.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=i;let s=this.resolveAssetUrls(n);s[0]&&(a.src=s[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=i,r.appendChild(a),r.appendChild(o),r.addEventListener("click",()=>this.selectAiGalleryAsset(i)),(c=this.aiGalleryGrid)==null||c.appendChild(r)})}getAiGalleryEntries(){if(!this.root)return[];let t=[];return this.root.querySelectorAll("[data-asset-key]").forEach(i=>{var s,o;let n=i,r=n.dataset.assetKey,a=(o=(s=n.value)==null?void 0:s.trim())!=null?o:"";!r||!a||this.isAiGalleryImage(a)&&t.push({key:r,value:a})}),t}isAiGalleryImage(t){let i=t.trim();if(!i)return!1;if(/^(data:image|blob:)/.test(i))return!0;let n=i.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(r=>n.endsWith(r))}selectAiGalleryAsset(t){this.aiTargetKey!==t&&(this.aiTargetKey=t,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=t),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(t,i,n){var o,c,l,d,u,p,f,m,h,g;this.closeAiModal(),this.aiTargetKey=t,this.aiBaseValue=i||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let r=document.createElement("div");r.className="ai-modal",r.innerHTML=`
784
807
  <div class="ai-modal-card">
785
808
  <div class="ai-modal-header">
786
809
  <div>
@@ -851,7 +874,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
851
874
  </div>
852
875
  </div>
853
876
  </div>
854
- `;let a=r.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),r.addEventListener("click",m=>{m.target===r&&this.closeAiModal()}),this.aiModal=r,this.aiKeyInput=r.querySelector("[data-ai-key]"),this.aiModelSelect=r.querySelector("[data-ai-model]"),this.aiPromptInput=r.querySelector("[data-ai-prompt]"),this.aiStrengthInput=r.querySelector("[data-ai-strength]"),this.aiStrengthValue=r.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=r.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=r.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=r.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=r.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=r.querySelector("[data-ai-ref-input]"),this.aiReferenceName=r.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=r.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=r.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=r.querySelector("[data-ai-generate]"),this.aiApplyBtn=r.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=r.querySelector("[data-ai-save-library]"),this.aiCropBtn=r.querySelector("[data-ai-crop]"),this.aiDownloadBtn=r.querySelector("[data-ai-download]"),this.aiPreviewImg=r.querySelector("[data-ai-preview]"),this.aiStatusEl=r.querySelector("[data-ai-status]"),this.aiLoadingEl=r.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=r.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=r.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=r.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var m;return(m=this.aiReferenceInput)==null?void 0:m.click()}),(c=this.aiGalleryToggle)==null||c.addEventListener("click",()=>this.toggleAiGallery()),(l=this.aiStrengthInput)==null||l.addEventListener("input",()=>{var v,y;let m=(y=(v=this.aiStrengthInput)==null?void 0:v.value)!=null?y:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=m)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var v,y;let m=(y=(v=this.aiBgToleranceInput)==null?void 0:v.value)!=null?y:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=m),this.refreshAiOutputFromRaw()}),(u=this.aiReferenceInput)==null||u.addEventListener("change",()=>{var v,y,x;let m=(x=(y=(v=this.aiReferenceInput)==null?void 0:v.files)==null?void 0:y[0])!=null?x:null;this.aiReferenceFile=m,this.aiReferenceName&&(this.aiReferenceName.textContent=m?`${m.name} (loaded)`:"Optional"),m&&this.setAiStatus(`Reference attached: ${m.name}`)}),(p=this.aiGenerateBtn)==null||p.addEventListener("click",()=>{this.handleAiGenerate()}),(f=this.aiApplyBtn)==null||f.addEventListener("click",()=>this.handleAiApply()),(b=this.aiSaveLibraryBtn)==null||b.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(g=this.aiDownloadBtn)==null||g.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(r),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(i),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,u,p,f,b,h,g,m,v,y,x,w,C,k,E,P,M,_,S,L;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let t=(p=(u=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:u.trim())!=null?p:"",i=(b=(f=this.aiModelSelect)==null?void 0:f.value)!=null?b:"gemini-2.5-flash-image",n=(m=(g=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:g.trim())!=null?m:"",r=(y=(v=this.aiRemoveBgToggle)==null?void 0:v.checked)!=null?y:!1,a=r,s=r,o=Number((w=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?w:"5");if(!t){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let c=this.getSelectedAssetInput(),l=((C=c==null?void 0:c.value)==null?void 0:C.trim())||((k=this.aiBaseValue)==null?void 0:k.trim())||"";if(!l&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let R=null,O=(E=this.getSelectedAssetKey())!=null?E:"unknown",A=(P=this.aiUseOutputToggle)!=null&&P.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl){let se=Ko(this.aiOutputDataUrl,"ai-output.png");if(se){let oe=await Pt(se);oe&&(R={input:{base64:oe.base64,mimeType:oe.mimeType},dataUrl:oe.dataUrl,width:oe.width,height:oe.height})}}if(R||(R=await this.getImageDataFromAsset(l)),!R){this.setAiStatus("Unable to load the base image.");return}let z=[R.input],T=!1;if(this.aiReferenceFile){let se=await Pt(this.aiReferenceFile);se?(z.push({base64:se.base64,mimeType:se.mimeType}),T=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let D=sh(n,{includeReference:T,includeMagenta:a,changeLevel:o}),$=(S=(_=this.aiReferenceFile)==null?void 0:_.name)!=null?S:"none";console.info("[AI] Final prompt:",D),console.info("[AI] Image sources:",{assetKey:O,base:A,reference:$});let ue=Xf(R.width,R.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await Fi(t,D,z,{aspectRatio:ue,model:i});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(R){console.error("[CustomizePanel] AI Generate Error:",R),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((L=this.aiStatusEl)==null?void 0:L.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var r,a,s,o;if(!this.aiRawOutputDataUrl)return;let t=(a=(r=this.aiRemoveBgToggle)==null?void 0:r.checked)!=null?a:!1,i=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(t){let c=await Bi(this.aiRawOutputDataUrl,i);c&&(n=c)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(t){var n,r;this.aiOutputDataUrl=t,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let i=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(i,(r=this.activePreviewKey)!=null?r:void 0)}setAiOutputButtonsEnabled(t){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!t),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!t),this.aiCropBtn&&(this.aiCropBtn.disabled=!t),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!t)}handleAiApply(){var i,n,r;let t=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(t)console.log("[CustomizePanel] Applying AI output to brand asset:",t.dataset.assetKey),t.value=this.aiOutputDataUrl,this.handleAssetValueChange((i=t.dataset.assetKey)!=null?i:"",t),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_")}_ai_${Date.now()}`,r=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let l=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:r,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(l.success){console.log("[CustomizePanel] \u2705 Saved to library:",l.path),this.setAiStatus(`Saved as ${n}. Applying...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",r),d(r,`${n}.png`));let u=window.refreshAssetLibrary;typeof u=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),u());let p=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),f=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),b=this.getSelectedAssetInput();if(b&&(b.value=l.path,this.handleAssetValueChange((o=b.dataset.assetKey)!=null?o:"",b)),p&&f){console.log("[CustomizePanel] Saved and applying directly to object:",p,f);let h=window.applyAssetToSlot,g=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(png|jpg|jpeg)$/i.test(String(l.path||""));if(typeof h=="function"&&g){let m=this.getFilenameFromPath(l.path);h(p,m,r)}else this.applyObjectPropertyValue(p,f,l.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}else console.error("[CustomizePanel] \u274C Save failed:",l.error),this.setAiStatus(`Save failed: ${l.error}`)}catch(c){console.error("[CustomizePanel] \u274C Save error:",c),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(t){var s;let i=(s=this.aiContext)==null?void 0:s.objectId,n=t||this.aiTargetKey||"",r=window.getEditableAssets;if(typeof r=="function"){let o=r();if(o!=null&&o.slots){let c=o.slots.find(l=>i&&l.objectId===i||l.currentAsset===n||l.slotId===n||l.currentAsset&&l.currentAsset.includes(n)||n.includes(l.slotId));if(c){let l=c.libraryFolder||c.category;if(l)return l}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(a=>a.currentAsset===t||a.slotId===t);return(r==null?void 0:r.objectId)||null}inferPathFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(s=>s.currentAsset===t||s.slotId===t);if(!r)return null;let a=r.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(t){if(!t)return"";let i=t.split("/");return i[i.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let t=this.getSelectedAssetInput(),i=(o=t==null?void 0:t.value)!=null?o:"",n=await this.getImageDimensions(i);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let r=Ko(this.aiOutputDataUrl,"ai-output.png");if(!r)return;let a=await this.showManualCropModal(r,n,i);if(!a)return;let s=await Kf(a);s&&this.setAiOutput(s)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let t=(n=this.getSelectedAssetKey())!=null?n:"ai-image",i=document.createElement("a");i.href=this.aiOutputDataUrl,i.download=`${t}-ai.png`,i.click()}handleAssetValueChange(t,i){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(t,i.value,i.dataset.assetType)}async handleAssetUpload(t,i,n){let r=i.value,a=t;if(t.type.startsWith("image/")){let c=await this.getImageDimensions(r);if(c){let l=await this.showManualCropModal(t,c,r);if(!l)return;a=l}}let s=URL.createObjectURL(a),o=i.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}i.dataset.objectUrl=s,i.dataset.assetType=a.type,i.value=s,this.handleAssetValueChange(n,i)}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(t,i,n,r){if(!i)return;let a=this.resolveAssetUrls(i);if(a.length===0)return;let s=n||this.guessMimeType(i);this.activePreviewKey=t,this.activePreviewValue=i,this.activePreviewFileInput=r!=null?r:null,this.openPreviewModal(t,i,a,s)}resolveAssetUrls(t){let i=t.trim();if(!i)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",i),/^(blob:|data:|https?:|\/)/.test(i))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[i];let n=i.replace(/^\.?\//,""),r=[];return n.startsWith("raw/")?r=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?r=[`/${n}`]:r=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",r),r}guessMimeType(t){let i=t.toLowerCase();return i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg")||i.endsWith(".gif")||i.endsWith(".webp")||i.endsWith(".svg")?"image":i.endsWith(".mp3")||i.endsWith(".wav")||i.endsWith(".ogg")?"audio":i.endsWith(".json")?"json":"file"}openPreviewModal(t,i,n,r){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
877
+ `;let a=r.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),r.addEventListener("click",v=>{v.target===r&&this.closeAiModal()}),this.aiModal=r,this.aiKeyInput=r.querySelector("[data-ai-key]"),this.aiModelSelect=r.querySelector("[data-ai-model]"),this.aiPromptInput=r.querySelector("[data-ai-prompt]"),this.aiStrengthInput=r.querySelector("[data-ai-strength]"),this.aiStrengthValue=r.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=r.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=r.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=r.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=r.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=r.querySelector("[data-ai-ref-input]"),this.aiReferenceName=r.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=r.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=r.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=r.querySelector("[data-ai-generate]"),this.aiApplyBtn=r.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=r.querySelector("[data-ai-save-library]"),this.aiCropBtn=r.querySelector("[data-ai-crop]"),this.aiDownloadBtn=r.querySelector("[data-ai-download]"),this.aiPreviewImg=r.querySelector("[data-ai-preview]"),this.aiStatusEl=r.querySelector("[data-ai-status]"),this.aiLoadingEl=r.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=r.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=r.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=r.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var v;return(v=this.aiReferenceInput)==null?void 0:v.click()}),(c=this.aiGalleryToggle)==null||c.addEventListener("click",()=>this.toggleAiGallery()),(l=this.aiStrengthInput)==null||l.addEventListener("input",()=>{var b,y;let v=(y=(b=this.aiStrengthInput)==null?void 0:b.value)!=null?y:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=v)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var b,y;let v=(y=(b=this.aiBgToleranceInput)==null?void 0:b.value)!=null?y:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=v),this.refreshAiOutputFromRaw()}),(u=this.aiReferenceInput)==null||u.addEventListener("change",()=>{var b,y,x;let v=(x=(y=(b=this.aiReferenceInput)==null?void 0:b.files)==null?void 0:y[0])!=null?x:null;this.aiReferenceFile=v,this.aiReferenceName&&(this.aiReferenceName.textContent=v?`${v.name} (loaded)`:"Optional"),v&&this.setAiStatus(`Reference attached: ${v.name}`)}),(p=this.aiGenerateBtn)==null||p.addEventListener("click",()=>{this.handleAiGenerate()}),(f=this.aiApplyBtn)==null||f.addEventListener("click",()=>this.handleAiApply()),(m=this.aiSaveLibraryBtn)==null||m.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(g=this.aiDownloadBtn)==null||g.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(r),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(i),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,u,p,f,m,h,g,v,b,y,x,w,A,T,E,M,I,_,S,L;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let t=(p=(u=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:u.trim())!=null?p:"",i=(m=(f=this.aiModelSelect)==null?void 0:f.value)!=null?m:"gemini-2.5-flash-image",n=(v=(g=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:g.trim())!=null?v:"",r=(y=(b=this.aiRemoveBgToggle)==null?void 0:b.checked)!=null?y:!1,a=r,s=r,o=Number((w=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?w:"5");if(!t){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let c=this.getSelectedAssetInput(),l=((A=c==null?void 0:c.value)==null?void 0:A.trim())||((T=this.aiBaseValue)==null?void 0:T.trim())||"";if(!l&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let R=null,O=(E=this.getSelectedAssetKey())!=null?E:"unknown",C=(M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((I=this.aiUseOutputToggle)!=null&&I.checked&&this.aiOutputDataUrl){let se=Zo(this.aiOutputDataUrl,"ai-output.png");if(se){let oe=await Mt(se);oe&&(R={input:{base64:oe.base64,mimeType:oe.mimeType},dataUrl:oe.dataUrl,width:oe.width,height:oe.height})}}if(R||(R=await this.getImageDataFromAsset(l)),!R){this.setAiStatus("Unable to load the base image.");return}let z=[R.input],k=!1;if(this.aiReferenceFile){let se=await Mt(this.aiReferenceFile);se?(z.push({base64:se.base64,mimeType:se.mimeType}),k=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let D=hh(n,{includeReference:k,includeMagenta:a,changeLevel:o}),$=(S=(_=this.aiReferenceFile)==null?void 0:_.name)!=null?S:"none";console.info("[AI] Final prompt:",D),console.info("[AI] Image sources:",{assetKey:O,base:C,reference:$});let ue=rh(R.width,R.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await Fi(t,D,z,{aspectRatio:ue,model:i});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(R){console.error("[CustomizePanel] AI Generate Error:",R),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((L=this.aiStatusEl)==null?void 0:L.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var r,a,s,o;if(!this.aiRawOutputDataUrl)return;let t=(a=(r=this.aiRemoveBgToggle)==null?void 0:r.checked)!=null?a:!1,i=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(t){let c=await Bi(this.aiRawOutputDataUrl,i);c&&(n=c)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(t){var n,r;this.aiOutputDataUrl=t,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let i=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(i,(r=this.activePreviewKey)!=null?r:void 0)}setAiOutputButtonsEnabled(t){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!t),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!t),this.aiCropBtn&&(this.aiCropBtn.disabled=!t),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!t)}handleAiApply(){var i,n,r;let t=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(t)console.log("[CustomizePanel] Applying AI output to brand asset:",t.dataset.assetKey),t.value=this.aiOutputDataUrl,this.handleAssetValueChange((i=t.dataset.assetKey)!=null?i:"",t),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_")}_ai_${Date.now()}`,r=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let l=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:r,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(l.success){console.log("[CustomizePanel] \u2705 Saved to library:",l.path),this.setAiStatus(`Saved as ${n}. Applying...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",r),d(r,`${n}.png`));let u=window.refreshAssetLibrary;typeof u=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),u());let p=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),f=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),m=this.getSelectedAssetInput();if(m&&(m.value=l.path,this.handleAssetValueChange((o=m.dataset.assetKey)!=null?o:"",m)),p&&f){console.log("[CustomizePanel] Saved and applying directly to object:",p,f);let h=window.applyAssetToSlot,g=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(png|jpg|jpeg)$/i.test(String(l.path||""));if(typeof h=="function"&&g){let v=this.getFilenameFromPath(l.path);h(p,v,r)}else this.applyObjectPropertyValue(p,f,l.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}else console.error("[CustomizePanel] \u274C Save failed:",l.error),this.setAiStatus(`Save failed: ${l.error}`)}catch(c){console.error("[CustomizePanel] \u274C Save error:",c),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(t){var s;let i=(s=this.aiContext)==null?void 0:s.objectId,n=t||this.aiTargetKey||"",r=window.getEditableAssets;if(typeof r=="function"){let o=r();if(o!=null&&o.slots){let c=o.slots.find(l=>i&&l.objectId===i||l.currentAsset===n||l.slotId===n||l.currentAsset&&l.currentAsset.includes(n)||n.includes(l.slotId));if(c){let l=c.libraryFolder||c.category;if(l)return l}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(a=>a.currentAsset===t||a.slotId===t);return(r==null?void 0:r.objectId)||null}inferPathFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(s=>s.currentAsset===t||s.slotId===t);if(!r)return null;let a=r.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(t){if(!t)return"";let i=t.split("/");return i[i.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let t=this.getSelectedAssetInput(),i=(o=t==null?void 0:t.value)!=null?o:"",n=await this.getImageDimensions(i);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let r=Zo(this.aiOutputDataUrl,"ai-output.png");if(!r)return;let a=await this.showManualCropModal(r,n,i);if(!a)return;let s=await nh(a);s&&this.setAiOutput(s)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let t=(n=this.getSelectedAssetKey())!=null?n:"ai-image",i=document.createElement("a");i.href=this.aiOutputDataUrl,i.download=`${t}-ai.png`,i.click()}handleAssetValueChange(t,i){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(t,i.value,i.dataset.assetType)}async handleAssetUpload(t,i,n){let r=i.value,a=t;if(t.type.startsWith("image/")){let c=await this.getImageDimensions(r);if(c){let l=await this.showManualCropModal(t,c,r);if(!l)return;a=l}}let s=URL.createObjectURL(a),o=i.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}i.dataset.objectUrl=s,i.dataset.assetType=a.type,i.value=s,this.handleAssetValueChange(n,i)}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(t,i,n,r){if(!i)return;let a=this.resolveAssetUrls(i);if(a.length===0)return;let s=n||this.guessMimeType(i);this.activePreviewKey=t,this.activePreviewValue=i,this.activePreviewFileInput=r!=null?r:null,this.openPreviewModal(t,i,a,s)}resolveAssetUrls(t){let i=t.trim();if(!i)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",i),/^(blob:|data:|https?:|\/)/.test(i))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[i];let n=i.replace(/^\.?\//,""),r=[];return n.startsWith("raw/")?r=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?r=[`/${n}`]:r=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",r),r}guessMimeType(t){let i=t.toLowerCase();return i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg")||i.endsWith(".gif")||i.endsWith(".webp")||i.endsWith(".svg")?"image":i.endsWith(".mp3")||i.endsWith(".wav")||i.endsWith(".ogg")?"audio":i.endsWith(".json")?"json":"file"}openPreviewModal(t,i,n,r){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
855
878
  <div class="asset-preview-card">
856
879
  <div class="asset-preview-header">
857
880
  <div class="asset-preview-title">${t}</div>
@@ -867,7 +890,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
867
890
  <img class="asset-preview-ai-image" alt="AI output preview">
868
891
  </div>
869
892
  </div>
870
- `;let s=a.querySelector(".asset-preview-body"),o=a.querySelector(".asset-preview-close"),c=a.querySelector(".asset-preview-change"),l=a.querySelector(".asset-preview-ai"),d=a.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",t),this.openAiModal(t,i)}),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",t),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),a.addEventListener("click",u=>{u.target===a&&this.closePreviewModal()}),s)if(r==="image"){let u=document.createElement("img");this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="audio"){let u=document.createElement("audio");u.controls=!0,this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="json"){let u=document.createElement("pre");this.fetchWithFallback(n).then(p=>{u.textContent=p!=null?p:"Unable to load JSON."}),s.appendChild(u)}else{let u=document.createElement("a");u.href=n[0],u.target="_blank",u.rel="noreferrer",u.textContent="Open asset",s.appendChild(u)}document.body.appendChild(a),this.previewModal=a,this.updateAiModalPreview(d,t)}loadWithFallback(t,i){if(i.length===0)return;let n=0,r=()=>{n>=i.length||(t.src=i[n],n+=1)};t.addEventListener("error",r),r()}async fetchWithFallback(t){for(let i of t)try{let n=await fetch(i);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(t,i,n){let r=window.getEditableObjectConfig,a=window.applyEditableObjectConfig;if(typeof r!="function"||typeof a!="function")return;let s=r(t);if(!s)return;let o=JSON.parse(JSON.stringify(s)),c=i.split("."),l=o;for(let d=0;d<c.length-1;d++){let u=c[d];l[u]=l[u]||{},l=l[u]}l[c[c.length-1]]=n,a(t,o)}applyTextColorToObject(t,i){let r={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];r&&this.applyObjectPropertyValue(r.objectId,r.property,i)}closePreviewModal(t){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),t||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(t,i,n){var a;if(!this.previewModal||this.activePreviewKey!==t)return;let r=i!=null?i:"";this.activePreviewValue!==r&&this.previewAsset(t,r,n,(a=this.activePreviewFileInput)!=null?a:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");if(!t)return;let i=window.localStorage.getItem("customizePanelWidth"),n=i?Number(i):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let r=a=>{var p,f;a.preventDefault();let s=a.clientX,o=(f=(p=this.root)==null?void 0:p.getBoundingClientRect().width)!=null?f:0,c=260,l=620,d=b=>{let h=b.clientX-s,g=Math.min(l,Math.max(c,o+h));this.root&&(this.root.style.width=`${g}px`)},u=()=>{var h,g;window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u);let b=(g=(h=this.root)==null?void 0:h.getBoundingClientRect().width)!=null?g:0;b>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(b)))};window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)};t.addEventListener("pointerdown",r)}async getImageDimensions(t){let i=this.resolveAssetUrls(t);if(i.length===0)return null;for(let n of i){let r=await this.loadImage(n);if(r!=null&&r.naturalWidth&&(r!=null&&r.naturalHeight))return{width:r.naturalWidth,height:r.naturalHeight}}return null}async loadImage(t){return await new Promise(i=>{let n=new Image;n.onload=()=>i(n),n.onerror=()=>i(null),n.src=t})}async showManualCropModal(t,i,n){let r=i.width/i.height,a=URL.createObjectURL(t),s=await this.loadImage(a);try{URL.revokeObjectURL(a)}catch{}if(!(s!=null&&s.naturalWidth)||!(s!=null&&s.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(c=>{let l=document.createElement("div");l.className="asset-crop-modal";let d=Math.min(860,window.innerWidth-60),b=Math.max(220,Math.floor((d-32-16)/2)),h=Math.min(520,window.innerHeight-240),g=b,m=g/r;m>h&&(m=h,g=m*r),l.innerHTML=`
893
+ `;let s=a.querySelector(".asset-preview-body"),o=a.querySelector(".asset-preview-close"),c=a.querySelector(".asset-preview-change"),l=a.querySelector(".asset-preview-ai"),d=a.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",t),this.openAiModal(t,i)}),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",t),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),a.addEventListener("click",u=>{u.target===a&&this.closePreviewModal()}),s)if(r==="image"){let u=document.createElement("img");this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="audio"){let u=document.createElement("audio");u.controls=!0,this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="json"){let u=document.createElement("pre");this.fetchWithFallback(n).then(p=>{u.textContent=p!=null?p:"Unable to load JSON."}),s.appendChild(u)}else{let u=document.createElement("a");u.href=n[0],u.target="_blank",u.rel="noreferrer",u.textContent="Open asset",s.appendChild(u)}document.body.appendChild(a),this.previewModal=a,this.updateAiModalPreview(d,t)}loadWithFallback(t,i){if(i.length===0)return;let n=0,r=()=>{n>=i.length||(t.src=i[n],n+=1)};t.addEventListener("error",r),r()}async fetchWithFallback(t){for(let i of t)try{let n=await fetch(i);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(t,i,n){let r=window.getEditableObjectConfig,a=window.applyEditableObjectConfig;if(typeof r!="function"||typeof a!="function")return;let s=r(t);if(!s)return;let o=JSON.parse(JSON.stringify(s)),c=i.split("."),l=o;for(let d=0;d<c.length-1;d++){let u=c[d];l[u]=l[u]||{},l=l[u]}l[c[c.length-1]]=n,a(t,o)}applyTextColorToObject(t,i){let r={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];r&&this.applyObjectPropertyValue(r.objectId,r.property,i)}closePreviewModal(t){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),t||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(t,i,n){var a;if(!this.previewModal||this.activePreviewKey!==t)return;let r=i!=null?i:"";this.activePreviewValue!==r&&this.previewAsset(t,r,n,(a=this.activePreviewFileInput)!=null?a:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");if(!t)return;let i=window.localStorage.getItem("customizePanelWidth"),n=i?Number(i):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let r=a=>{var p,f;a.preventDefault();let s=a.clientX,o=(f=(p=this.root)==null?void 0:p.getBoundingClientRect().width)!=null?f:0,c=260,l=620,d=m=>{let h=m.clientX-s,g=Math.min(l,Math.max(c,o+h));this.root&&(this.root.style.width=`${g}px`)},u=()=>{var h,g;window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u);let m=(g=(h=this.root)==null?void 0:h.getBoundingClientRect().width)!=null?g:0;m>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(m)))};window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)};t.addEventListener("pointerdown",r)}async getImageDimensions(t){let i=this.resolveAssetUrls(t);if(i.length===0)return null;for(let n of i){let r=await this.loadImage(n);if(r!=null&&r.naturalWidth&&(r!=null&&r.naturalHeight))return{width:r.naturalWidth,height:r.naturalHeight}}return null}async loadImage(t){return await new Promise(i=>{let n=new Image;n.onload=()=>i(n),n.onerror=()=>i(null),n.src=t})}async showManualCropModal(t,i,n){let r=i.width/i.height,a=URL.createObjectURL(t),s=await this.loadImage(a);try{URL.revokeObjectURL(a)}catch{}if(!(s!=null&&s.naturalWidth)||!(s!=null&&s.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(c=>{let l=document.createElement("div");l.className="asset-crop-modal";let d=Math.min(860,window.innerWidth-60),m=Math.max(220,Math.floor((d-32-16)/2)),h=Math.min(520,window.innerHeight-240),g=m,v=g/r;v>h&&(v=h,g=v*r),l.innerHTML=`
871
894
  <div class="asset-crop-card" style="width:${d}px;">
872
895
  <div class="asset-crop-header">
873
896
  <div>
@@ -879,11 +902,11 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
879
902
  <div class="asset-crop-body">
880
903
  <div class="asset-crop-column">
881
904
  <div class="asset-crop-label">Crop</div>
882
- <canvas class="asset-crop-canvas" width="${Math.round(g)}" height="${Math.round(m)}"></canvas>
905
+ <canvas class="asset-crop-canvas" width="${Math.round(g)}" height="${Math.round(v)}"></canvas>
883
906
  </div>
884
907
  <div class="asset-crop-column">
885
908
  <div class="asset-crop-label">Compare</div>
886
- <canvas class="asset-crop-preview" width="${Math.round(g)}" height="${Math.round(m)}"></canvas>
909
+ <canvas class="asset-crop-preview" width="${Math.round(g)}" height="${Math.round(v)}"></canvas>
887
910
  </div>
888
911
  </div>
889
912
  <div class="asset-crop-controls">
@@ -897,7 +920,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
897
920
  <button class="asset-crop-apply" type="button">Apply Crop</button>
898
921
  </div>
899
922
  </div>
900
- `;let v=l.querySelector(".asset-crop-canvas"),y=l.querySelector(".asset-crop-preview"),x=l.querySelector(".asset-crop-zoom"),w=l.querySelector(".asset-crop-zoom-value"),C=l.querySelector(".asset-crop-close"),k=l.querySelector(".asset-crop-cancel"),E=l.querySelector(".asset-crop-apply"),P=l.querySelector(".asset-crop-reset");if(!v||!y||!x||!w){c(null);return}let M=v.getContext("2d"),_=y.getContext("2d");if(!M||!_){c(null);return}let S=s.naturalWidth,L=s.naturalHeight,R=Math.max(v.width/S,v.height/L),O=1,A=0,z=0,T=!1,D=0,$=0,ue=0,V=0,se=()=>{let N=R*O,Be=Math.max(0,(S*N-v.width)/2),Je=Math.max(0,(L*N-v.height)/2);A=Math.min(Be,Math.max(-Be,A)),z=Math.min(Je,Math.max(-Je,z))},oe=()=>{let N=R*O;M.clearRect(0,0,v.width,v.height);let Be=v.width/2-S*N/2+A,Je=v.height/2-L*N/2+z;if(M.drawImage(s,Be,Je,S*N,L*N),_.clearRect(0,0,y.width,y.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let et=Math.max(y.width/o.naturalWidth,y.height/o.naturalHeight),ai=y.width/2-o.naturalWidth*et/2,vt=y.height/2-o.naturalHeight*et/2;_.drawImage(o,ai,vt,o.naturalWidth*et,o.naturalHeight*et)}else _.fillStyle="rgba(255, 255, 255, 0.04)",_.fillRect(0,0,y.width,y.height),_.strokeStyle="rgba(255, 255, 255, 0.08)",_.strokeRect(4,4,y.width-8,y.height-8);let mt=y.width/v.width*(R*O),Qe=A*(y.width/v.width),zt=z*(y.height/v.height),ni=y.width/2-S*mt/2+Qe,ri=y.height/2-L*mt/2+zt;_.save(),_.globalAlpha=.7,_.drawImage(s,ni,ri,S*mt,L*mt),_.restore()},me=()=>{A=0,z=0,se(),oe()};x.addEventListener("input",()=>{O=Number(x.value),w.textContent=`${O.toFixed(2)}\xD7`,se(),oe()}),v.addEventListener("pointerdown",N=>{T=!0,D=N.clientX,$=N.clientY,ue=A,V=z,v.setPointerCapture(N.pointerId)}),v.addEventListener("pointermove",N=>{T&&(A=ue+(N.clientX-D),z=V+(N.clientY-$),se(),oe())}),v.addEventListener("pointerup",N=>{T=!1,v.releasePointerCapture(N.pointerId)}),v.addEventListener("pointerleave",()=>{T=!1});let bt=()=>{l.remove()},ii=()=>{bt(),c(null)},er=async()=>{let N=document.createElement("canvas");N.width=i.width,N.height=i.height;let Be=N.getContext("2d");if(!Be){bt(),c(null);return}let Je=O,Qe=Math.max(N.width/S,N.height/L)*Je,zt=N.width/v.width,ni=A*zt,ri=z*zt,et=N.width/2-S*Qe/2+ni,ai=N.height/2-L*Qe/2+ri;Be.drawImage(s,et,ai,S*Qe,L*Qe);let vt=await new Promise(tr=>{N.toBlob(ir=>tr(ir),t.type||"image/png")});if(bt(),!vt){c(null);return}c(new File([vt],t.name,{type:vt.type}))};C==null||C.addEventListener("click",ii),k==null||k.addEventListener("click",ii),P==null||P.addEventListener("click",me),E==null||E.addEventListener("click",()=>{er()}),l.addEventListener("click",N=>{N.target===l&&ii()}),document.body.appendChild(l),me()})}async loadImageForValue(t){let i=this.resolveAssetUrls(t);if(!i.length)return null;for(let n of i){let r=await this.loadImage(n);if(r)return r}return null}};var va=class{constructor(){this.root=null;this.options=null}render(){return`
923
+ `;let b=l.querySelector(".asset-crop-canvas"),y=l.querySelector(".asset-crop-preview"),x=l.querySelector(".asset-crop-zoom"),w=l.querySelector(".asset-crop-zoom-value"),A=l.querySelector(".asset-crop-close"),T=l.querySelector(".asset-crop-cancel"),E=l.querySelector(".asset-crop-apply"),M=l.querySelector(".asset-crop-reset");if(!b||!y||!x||!w){c(null);return}let I=b.getContext("2d"),_=y.getContext("2d");if(!I||!_){c(null);return}let S=s.naturalWidth,L=s.naturalHeight,R=Math.max(b.width/S,b.height/L),O=1,C=0,z=0,k=!1,D=0,$=0,ue=0,V=0,se=()=>{let N=R*O,Be=Math.max(0,(S*N-b.width)/2),Je=Math.max(0,(L*N-b.height)/2);C=Math.min(Be,Math.max(-Be,C)),z=Math.min(Je,Math.max(-Je,z))},oe=()=>{let N=R*O;I.clearRect(0,0,b.width,b.height);let Be=b.width/2-S*N/2+C,Je=b.height/2-L*N/2+z;if(I.drawImage(s,Be,Je,S*N,L*N),_.clearRect(0,0,y.width,y.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let et=Math.max(y.width/o.naturalWidth,y.height/o.naturalHeight),ai=y.width/2-o.naturalWidth*et/2,vt=y.height/2-o.naturalHeight*et/2;_.drawImage(o,ai,vt,o.naturalWidth*et,o.naturalHeight*et)}else _.fillStyle="rgba(255, 255, 255, 0.04)",_.fillRect(0,0,y.width,y.height),_.strokeStyle="rgba(255, 255, 255, 0.08)",_.strokeRect(4,4,y.width-8,y.height-8);let bt=y.width/b.width*(R*O),Qe=C*(y.width/b.width),zt=z*(y.height/b.height),ni=y.width/2-S*bt/2+Qe,ri=y.height/2-L*bt/2+zt;_.save(),_.globalAlpha=.7,_.drawImage(s,ni,ri,S*bt,L*bt),_.restore()},be=()=>{C=0,z=0,se(),oe()};x.addEventListener("input",()=>{O=Number(x.value),w.textContent=`${O.toFixed(2)}\xD7`,se(),oe()}),b.addEventListener("pointerdown",N=>{k=!0,D=N.clientX,$=N.clientY,ue=C,V=z,b.setPointerCapture(N.pointerId)}),b.addEventListener("pointermove",N=>{k&&(C=ue+(N.clientX-D),z=V+(N.clientY-$),se(),oe())}),b.addEventListener("pointerup",N=>{k=!1,b.releasePointerCapture(N.pointerId)}),b.addEventListener("pointerleave",()=>{k=!1});let mt=()=>{l.remove()},ii=()=>{mt(),c(null)},tr=async()=>{let N=document.createElement("canvas");N.width=i.width,N.height=i.height;let Be=N.getContext("2d");if(!Be){mt(),c(null);return}let Je=O,Qe=Math.max(N.width/S,N.height/L)*Je,zt=N.width/b.width,ni=C*zt,ri=z*zt,et=N.width/2-S*Qe/2+ni,ai=N.height/2-L*Qe/2+ri;Be.drawImage(s,et,ai,S*Qe,L*Qe);let vt=await new Promise(ir=>{N.toBlob(nr=>ir(nr),t.type||"image/png")});if(mt(),!vt){c(null);return}c(new File([vt],t.name,{type:vt.type}))};A==null||A.addEventListener("click",ii),T==null||T.addEventListener("click",ii),M==null||M.addEventListener("click",be),E==null||E.addEventListener("click",()=>{tr()}),l.addEventListener("click",N=>{N.target===l&&ii()}),document.body.appendChild(l),be()})}async loadImageForValue(t){let i=this.resolveAssetUrls(t);if(!i.length)return null;for(let n of i){let r=await this.loadImage(n);if(r)return r}return null}};var xa=class{constructor(){this.root=null;this.options=null}render(){return`
901
924
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
902
925
  <div class="scene-panel-header" data-panel-handle>
903
926
  <div class="panel-title">
@@ -963,10 +986,10 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
963
986
  </div>
964
987
  </div>
965
988
  </div>
966
- `}initialize(t,i){var v,y,x,w,C,k,E,P,M,_,S,L,R,O,A,z;this.options=i,this.root=t.querySelector('[data-panel="loading-screen"]');let r=(()=>{var D;let T=window.getEditableEngineConfig;if(typeof T=="function"){let $=T();return(D=$==null?void 0:$.loading)!=null?D:{}}return{}})(),a=(v=this.root)==null?void 0:v.querySelector("#loading-screen-type");a&&(a.value=r.type==="image"?"image":"color",a.addEventListener("change",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(y=this.root)==null?void 0:y.querySelector("#loading-background-color");s&&(s.value=r.background_color||"#160a17",s.addEventListener("input",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{background_color:s.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),c=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((C=r.overlay_alpha)!=null?C:1),c&&(c.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var D,$;let T=Number(o.value);c&&(c.textContent=T.toFixed(2)),($=(D=this.options)==null?void 0:D.onUpdateLoading)==null||$.call(D,{overlay_alpha:T})}));let l=(k=this.root)==null?void 0:k.querySelector("#loading-text");l&&(l.value=r.text||"",l.addEventListener("input",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{text:l.value})}));let d=(E=this.root)==null?void 0:E.querySelector("#loading-text-scale"),u=(P=this.root)==null?void 0:P.querySelector("#loading-text-scale-value");d&&(d.value=String((M=r.text_scale)!=null?M:.6),u&&(u.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var D,$;let T=Number(d.value);u&&(u.textContent=T.toFixed(2)),($=(D=this.options)==null?void 0:D.onUpdateLoading)==null||$.call(D,{text_scale:T})}));let p=(_=this.root)==null?void 0:_.querySelector("#loading-enabled");p&&(p.checked=r.enabled!==!1,p.addEventListener("change",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{enabled:p.checked})}));let f=(S=this.root)==null?void 0:S.querySelector("#loading-blur-enabled");f&&(f.checked=r.blur_enabled!==!1,f.addEventListener("change",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{blur_enabled:f.checked})}));let b=(L=this.root)==null?void 0:L.querySelector("#loading-blur-strength"),h=(R=this.root)==null?void 0:R.querySelector("#loading-blur-strength-value");b&&(b.value=String((O=r.blur_strength)!=null?O:8),h&&(h.textContent=b.value),b.addEventListener("input",()=>{var T,D;h&&(h.textContent=b.value),(D=(T=this.options)==null?void 0:T.onUpdateLoading)==null||D.call(T,{blur_strength:Number(b.value)})}));let g=(A=this.root)==null?void 0:A.querySelector("#loading-show-btn"),m=(z=this.root)==null?void 0:z.querySelector("#loading-hide-btn");g==null||g.addEventListener("click",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onShowLoadingScreen)==null||D.call(T)}),m==null||m.addEventListener("click",()=>{var T,D;(D=(T=this.options)==null?void 0:T.onHideLoadingScreen)==null||D.call(T)}),this.updateFieldVisibility(r.type==="image"?"image":"color")}updateFieldVisibility(t){var r,a;let i=(r=this.root)==null?void 0:r.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");t==="image"?(i&&(i.style.display="none"),n&&(n.style.display="none")):(i&&(i.style.display=""),n&&(n.style.display=""))}refresh(){}};import{Assets as ya}from"pixi.js";async function lh(e,t,i){var n,r;console.log("[LIBRARY] applyAssetChange called with:",t,i);try{let a=Date.now(),o=`/${`raw/library/${t}/${i}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let c=await ya.load(o);if(!c){console.error("[LIBRARY] Failed to load texture:",o);return}let l=window.CustomAssets,d=Object.keys(l||{}).filter(p=>{let f=t.replace(/s$/,"");return p.startsWith(f)||p.includes(f)});for(let p of d)He[p]=c,console.log("[LIBRARY] \u2705 Updated AssetTextures."+p),(n=l[p])!=null&&n.texture&&(l[p].texture=c,console.log("[LIBRARY] \u2705 Updated CustomAssets."+p+".texture"));let u=window.gameObjectManager;if(u)for(let p of d){let f=u.get(p);if(f){let b=((r=f.getDisplayObject)==null?void 0:r.call(f))||f.pixiObject||f;b!=null&&b.texture&&(b.texture=c,console.log("[LIBRARY] \u2705 Applied to display object:",p))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function ch(e,t){var i,n,r;console.log("[LIBRARY] resetAsset called for:",t);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(i=s==null?void 0:s.slots)==null?void 0:i.find(g=>g.category===t),c=o==null?void 0:o.defaultAsset;if(!c){console.warn("[LIBRARY] Could not find default asset for:",t);return}let l=Date.now(),d=`/raw/${c}?t=${l}`;console.log("[LIBRARY] Loading default texture from:",d);let u=await ya.load(d);if(!u){console.error("[LIBRARY] Failed to load default texture:",d);return}let p=window.CustomAssets,f=t.replace(/s$/,""),b=Object.keys(p||{}).filter(g=>g.startsWith(f)||g.includes(f));for(let g of b)He[g]=u,console.log("[LIBRARY] \u2705 Reset AssetTextures."+g),(n=p[g])!=null&&n.texture&&(p[g].texture=u,console.log("[LIBRARY] \u2705 Reset CustomAssets."+g+" to default"));let h=window.gameObjectManager;if(h)for(let g of b){let m=h.get(g);if(m){let v=((r=m.getDisplayObject)==null?void 0:r.call(m))||m.pixiObject||m;v!=null&&v.texture&&(v.texture=u,console.log("[LIBRARY] \u2705 Reset display object:",g))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function dh(e,t,i,n){var r,a,s,o,c,l,d,u,p,f,b,h,g,m,v;console.log("[LIBRARY] applySlotAsset:",{objectId:t,assetFilename:i,category:n});try{let y=t.startsWith("json.")?t.replace("json.",""):t;console.log("[LIBRARY] Asset key:",y);let x=Date.now(),w=`/raw/library/${n}/${i}?t=${x}`;console.log("[LIBRARY] Loading texture from:",w);let C=await ya.load(w);if(!C){console.error("[LIBRARY] Failed to load texture:",w);return}console.log("[LIBRARY] \u2705 Texture loaded"),He[y]=C,console.log("[LIBRARY] \u2705 Updated AssetTextures."+y);let k=window.CustomAssets;k!=null&&k[y]&&(k[y].texture=C,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+y));let E=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!E),E){let M=Array.from(((r=E.keys)==null?void 0:r.call(E))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",M);let _=E.get(y);if(console.log("[LIBRARY] gameObject for "+y+"?",!!_),_){let S=((a=_.getDisplayObject)==null?void 0:a.call(_))||_.pixiObject||_.pixi||_,L=(s=S==null?void 0:S.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",S),console.log("[LIBRARY] displayObject type:",L),console.log("[LIBRARY] has texture?",!!(S!=null&&S.texture)),S!=null&&S.texture)S.texture=C,console.log("[LIBRARY] \u2705 Applied to display object:",y);else if(L==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:R}=await import("pixi.js"),O=S.parent,A=(c=(o=O==null?void 0:O.getChildIndex)==null?void 0:o.call(O,S))!=null?c:0,z={x:S.x,y:S.y},T={x:(d=(l=S.anchor)==null?void 0:l.x)!=null?d:.5,y:(p=(u=S.anchor)==null?void 0:u.y)!=null?p:.5},D={x:(b=(f=S.scale)==null?void 0:f.x)!=null?b:1,y:(g=(h=S.scale)==null?void 0:h.y)!=null?g:1},$=(m=S.alpha)!=null?m:1,ue=(v=S.visible)!=null?v:!0,V=new R(C);V.anchor.set(T.x,T.y),V.position.set(z.x,z.y),V.scale.set(D.x,D.y),V.alpha=$,V.visible=ue,O&&(O.removeChild(S),O.addChildAt(V,A),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),_.pixiObject&&(_.pixiObject=V),_.pixi&&(_.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(S!=null&&S.children){let R=S.children.find(O=>O.texture);R?(R.texture=C,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let P=`raw/library/${n}/${i}`;en({objectId:y,path:"render.asset.path",value:P}),console.log("[LIBRARY] \u2705 Staged config override for:",y,"path:",P)}catch(y){console.error("[LIBRARY] Error applying slot asset:",y)}}async function uh(e,t,i,n){var r;console.log("[LIBRARY] resetSlotAsset:",{objectId:t,defaultAsset:i,category:n});try{let a=t.startsWith("json.")?t.replace("json.",""):t,s=Date.now(),o=`/raw/${i}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let c=await ya.load(o);if(!c){console.error("[LIBRARY] Failed to load default texture:",o);return}He[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let l=window.CustomAssets;l!=null&&l[a]&&(l[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let d=window.gameObjectManager;if(d){let u=d.get(a);if(u){let p=((r=u.getDisplayObject)==null?void 0:r.call(u))||u.pixiObject||u;p!=null&&p.texture&&(p.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}en({objectId:a,path:"render.asset.path",value:i}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}import{Graphics as bh,Point as Jy}from"pixi.js";import{Point as ph}from"pixi.js";var It=()=>window.debugConfig||{},fh=()=>window.resolveAnchorVec2||(e=>({x:.5,y:.5})),hh=()=>window.resolveScreenAnchorPoint||(()=>new ph),gh=()=>window.resolveScreenRatioPoint||(()=>new ph);function mh(e){xa(e)&&(e.objectDebugRaf||(e.objectDebugRaf=window.requestAnimationFrame(()=>wa(e))))}function vh(e){e.objectDebugRaf&&(window.cancelAnimationFrame(e.objectDebugRaf),e.objectDebugRaf=null),Bn(e)}function xa(e){return e.isDebugOpen}function wa(e){var a,s,o;if(!xa(e)){e.objectDebugRaf=null;return}e.objectDebugRaf=window.requestAnimationFrame(()=>wa(e));let t=Qo(e);if(!t){jn(e,null),Bn(e);return}let i=el(e,t);if(!i){jn(e,null),Bn(e);return}let n=new Jy;(a=i.getGlobalPosition)==null||a.call(i,n);let r=tl(e,i);jn(e,{instanceId:t,worldX:n.x,worldY:n.y,configX:(s=r==null?void 0:r.x)!=null?s:null,configY:(o=r==null?void 0:r.y)!=null?o:null}),e.highlightObject?al(e,i):ol(e),e.highlightAnchor&&r?sl(e,r):ll(e)}function Qo(e){var r;let t=e.selectedObjectId;if(!t)return null;let i=window.__editableObjectInstances,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return Array.isArray(n)&&n.length>0?n[0]:t}function el(e,t){var r,a;let i=window.gameObjectManager,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Fn(e){let t=e.selectedObjectId;if(!t)return null;let i=window.getEditableObjectConfig;return typeof i!="function"?null:i(t)}function tl(e,t){var s,o;let i=Fn(e);if(!i)return null;let n=(s=i.transform)!=null?s:{},r=il(e);if(!r)return null;if(n.position_ratio!=null)return gh()(r.width,r.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"center";return hh()(r.width,r.height,a)}function il(e){var a;let t=(a=e.container)==null?void 0:a.querySelector(".game-container"),i=Number(t==null?void 0:t.dataset.screenWidth),n=Number(t==null?void 0:t.dataset.screenHeight);if(Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0)return{width:i,height:n};let r=window.gameApp;return r!=null&&r.renderer?{width:r.renderer.width,height:r.renderer.height}:null}function nl(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectBoundsGfx&&e.objectBoundsGfx.parent!==t.stage&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectBoundsGfx||(e.objectBoundsGfx=new bh,e.objectBoundsGfx.zIndex=999999,t.stage.addChild(e.objectBoundsGfx)),e.objectBoundsGfx):null}function rl(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectAnchorGfx&&e.objectAnchorGfx.parent!==t.stage&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null),e.objectAnchorGfx||(e.objectAnchorGfx=new bh,e.objectAnchorGfx.zIndex=1e6,t.stage.addChild(e.objectAnchorGfx)),e.objectAnchorGfx):null}function al(e,t){var r;let i=nl(e);if(!i)return;let n=(r=t.getBounds)==null?void 0:r.call(t);n&&(i.clear(),i.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function sl(e,t){let i=rl(e);if(!i)return;let n=6;i.clear(),i.moveTo(t.x-n,t.y),i.lineTo(t.x+n,t.y),i.moveTo(t.x,t.y-n),i.lineTo(t.x,t.y+n),i.stroke({width:2,color:3066993,alpha:.9})}function ol(e){e.objectBoundsGfx&&e.objectBoundsGfx.clear()}function ll(e){e.objectAnchorGfx&&e.objectAnchorGfx.clear()}function Bn(e){e.objectBoundsGfx&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectAnchorGfx&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null)}function jn(e,t){e.sceneToolsPanel.updateInfo(t?{instanceId:t.instanceId,worldX:t.worldX,worldY:t.worldY,anchorX:t.configX,anchorY:t.configY}:null)}function yh(e,t){return t.split(".").reduce((i,n)=>i?i[n]:void 0,e)}function xh(e,t,i){var s;let n=t.split("."),r=n.pop(),a=e;for(let o of n)a[o]=(s=a[o])!=null?s:{},a=a[o];a[r]=i}function cl(e){var n,r,a,s,o;if(!e)return!1;if((n=e.transform)!=null&&n.offset)return!0;let t=((a=(r=e.identity)==null?void 0:r.category)!=null?a:"").toString().toLowerCase(),i=((o=(s=e.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return t.includes("ui")||i.startsWith("ui")||i.includes("label")}function Ea(e){let t=It();t.layout&&(t.layout.scale_multiplier=1,t.layout.position_offset={x:0,y:0},t.layout.debug_rect_visible=!0,t.layout.debug_rect_color=16711680,t.layout.debug_rect_thickness=4),t.engine&&(t.engine.scale=1,t.engine.background_scale=1.05,t.engine.label_pulse_speed=3,t.engine.label_pulse_intensity=.03),t.physics&&(t.physics.rope_length=420),window.location.reload()}function wh(e){window.location.reload()}function Sa(e){let t=JSON.stringify(It(),null,2);navigator.clipboard.writeText(t).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(t),alert("Config logged to console (clipboard not available)")})}async function _h(e,t){var i,n,r;if(!(!e.configViewer||!e.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(t):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:c}=await import("./config-44AFSRES.js"),u=(((i=(await o("scene.main")).scene)==null?void 0:i.objects)||[]).find(f=>f.object_config===t||f.instance_id===t);if(!u)return;let p=await c(u.object_config);console.log("[PREVIEW] Loaded object config (fallback)",t,p),_a(e,p),(n=e.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",t,s),_a(e,s),(r=e.configViewer)==null||r.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function _a(e,t){var u,p,f,b,h,g,m,v,y,x;if(!e.container)return;let i=e.container.querySelector("#config-pos-x"),n=e.container.querySelector("#config-pos-y"),r=e.container.querySelector("#config-scale"),a=e.container.querySelector("#config-anchor-x"),s=e.container.querySelector("#config-anchor-y"),c=cl(t)?(u=t.transform)==null?void 0:u.offset:(p=t.transform)==null?void 0:p.position;i&&(i.value=String((f=c==null?void 0:c.x)!=null?f:0)),n&&(n.value=String((b=c==null?void 0:c.y)!=null?b:0)),r&&(r.value=String((g=(h=t.transform)==null?void 0:h.scale)!=null?g:1));let l=(x=(y=(m=t.transform)==null?void 0:m.anchor)!=null?y:(v=t.render)==null?void 0:v.anchor)!=null?x:{x:.5,y:.5},d=fh()(l);a&&(a.value=String(d.x)),s&&(s.value=String(d.y))}function Eh(e){var c,l,d,u,p,f,b,h,g,m;let t=e.selectedObjectId;if(!t||!e.container)return;let i=(l=(c=e.container.querySelector("#config-pos-x"))==null?void 0:c.value)!=null?l:"0",n=(u=(d=e.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?u:"0",r=(f=(p=e.container.querySelector("#config-scale"))==null?void 0:p.value)!=null?f:"1",a=(h=(b=e.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?h:"0.5",s=(m=(g=e.container.querySelector("#config-anchor-y"))==null?void 0:g.value)!=null?m:"0.5",o=`${t}:
989
+ `}initialize(t,i){var b,y,x,w,A,T,E,M,I,_,S,L,R,O,C,z;this.options=i,this.root=t.querySelector('[data-panel="loading-screen"]');let r=(()=>{var D;let k=window.getEditableEngineConfig;if(typeof k=="function"){let $=k();return(D=$==null?void 0:$.loading)!=null?D:{}}return{}})(),a=(b=this.root)==null?void 0:b.querySelector("#loading-screen-type");a&&(a.value=r.type==="image"?"image":"color",a.addEventListener("change",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(y=this.root)==null?void 0:y.querySelector("#loading-background-color");s&&(s.value=r.background_color||"#160a17",s.addEventListener("input",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{background_color:s.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),c=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((A=r.overlay_alpha)!=null?A:1),c&&(c.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var D,$;let k=Number(o.value);c&&(c.textContent=k.toFixed(2)),($=(D=this.options)==null?void 0:D.onUpdateLoading)==null||$.call(D,{overlay_alpha:k})}));let l=(T=this.root)==null?void 0:T.querySelector("#loading-text");l&&(l.value=r.text||"",l.addEventListener("input",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{text:l.value})}));let d=(E=this.root)==null?void 0:E.querySelector("#loading-text-scale"),u=(M=this.root)==null?void 0:M.querySelector("#loading-text-scale-value");d&&(d.value=String((I=r.text_scale)!=null?I:.6),u&&(u.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var D,$;let k=Number(d.value);u&&(u.textContent=k.toFixed(2)),($=(D=this.options)==null?void 0:D.onUpdateLoading)==null||$.call(D,{text_scale:k})}));let p=(_=this.root)==null?void 0:_.querySelector("#loading-enabled");p&&(p.checked=r.enabled!==!1,p.addEventListener("change",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{enabled:p.checked})}));let f=(S=this.root)==null?void 0:S.querySelector("#loading-blur-enabled");f&&(f.checked=r.blur_enabled!==!1,f.addEventListener("change",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{blur_enabled:f.checked})}));let m=(L=this.root)==null?void 0:L.querySelector("#loading-blur-strength"),h=(R=this.root)==null?void 0:R.querySelector("#loading-blur-strength-value");m&&(m.value=String((O=r.blur_strength)!=null?O:8),h&&(h.textContent=m.value),m.addEventListener("input",()=>{var k,D;h&&(h.textContent=m.value),(D=(k=this.options)==null?void 0:k.onUpdateLoading)==null||D.call(k,{blur_strength:Number(m.value)})}));let g=(C=this.root)==null?void 0:C.querySelector("#loading-show-btn"),v=(z=this.root)==null?void 0:z.querySelector("#loading-hide-btn");g==null||g.addEventListener("click",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onShowLoadingScreen)==null||D.call(k)}),v==null||v.addEventListener("click",()=>{var k,D;(D=(k=this.options)==null?void 0:k.onHideLoadingScreen)==null||D.call(k)}),this.updateFieldVisibility(r.type==="image"?"image":"color")}updateFieldVisibility(t){var r,a;let i=(r=this.root)==null?void 0:r.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");t==="image"?(i&&(i.style.display="none"),n&&(n.style.display="none")):(i&&(i.style.display=""),n&&(n.style.display=""))}refresh(){}};import{Assets as wa}from"pixi.js";async function mh(e,t,i){var n,r;console.log("[LIBRARY] applyAssetChange called with:",t,i);try{let a=Date.now(),o=`/${`raw/library/${t}/${i}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let c=await wa.load(o);if(!c){console.error("[LIBRARY] Failed to load texture:",o);return}let l=window.CustomAssets,d=Object.keys(l||{}).filter(p=>{let f=t.replace(/s$/,"");return p.startsWith(f)||p.includes(f)});for(let p of d)He[p]=c,console.log("[LIBRARY] \u2705 Updated AssetTextures."+p),(n=l[p])!=null&&n.texture&&(l[p].texture=c,console.log("[LIBRARY] \u2705 Updated CustomAssets."+p+".texture"));let u=window.gameObjectManager;if(u)for(let p of d){let f=u.get(p);if(f){let m=((r=f.getDisplayObject)==null?void 0:r.call(f))||f.pixiObject||f;m!=null&&m.texture&&(m.texture=c,console.log("[LIBRARY] \u2705 Applied to display object:",p))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function bh(e,t){var i,n,r;console.log("[LIBRARY] resetAsset called for:",t);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(i=s==null?void 0:s.slots)==null?void 0:i.find(g=>g.category===t),c=o==null?void 0:o.defaultAsset;if(!c){console.warn("[LIBRARY] Could not find default asset for:",t);return}let l=Date.now(),d=`/raw/${c}?t=${l}`;console.log("[LIBRARY] Loading default texture from:",d);let u=await wa.load(d);if(!u){console.error("[LIBRARY] Failed to load default texture:",d);return}let p=window.CustomAssets,f=t.replace(/s$/,""),m=Object.keys(p||{}).filter(g=>g.startsWith(f)||g.includes(f));for(let g of m)He[g]=u,console.log("[LIBRARY] \u2705 Reset AssetTextures."+g),(n=p[g])!=null&&n.texture&&(p[g].texture=u,console.log("[LIBRARY] \u2705 Reset CustomAssets."+g+" to default"));let h=window.gameObjectManager;if(h)for(let g of m){let v=h.get(g);if(v){let b=((r=v.getDisplayObject)==null?void 0:r.call(v))||v.pixiObject||v;b!=null&&b.texture&&(b.texture=u,console.log("[LIBRARY] \u2705 Reset display object:",g))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function vh(e,t,i,n){var r,a,s,o,c,l,d,u,p,f,m,h,g,v,b;console.log("[LIBRARY] applySlotAsset:",{objectId:t,assetFilename:i,category:n});try{let y=t.startsWith("json.")?t.replace("json.",""):t;console.log("[LIBRARY] Asset key:",y);let x=Date.now(),w=`/raw/library/${n}/${i}?t=${x}`;console.log("[LIBRARY] Loading texture from:",w);let A=await wa.load(w);if(!A){console.error("[LIBRARY] Failed to load texture:",w);return}console.log("[LIBRARY] \u2705 Texture loaded"),He[y]=A,console.log("[LIBRARY] \u2705 Updated AssetTextures."+y);let T=window.CustomAssets;T!=null&&T[y]&&(T[y].texture=A,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+y));let E=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!E),E){let I=Array.from(((r=E.keys)==null?void 0:r.call(E))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",I);let _=E.get(y);if(console.log("[LIBRARY] gameObject for "+y+"?",!!_),_){let S=((a=_.getDisplayObject)==null?void 0:a.call(_))||_.pixiObject||_.pixi||_,L=(s=S==null?void 0:S.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",S),console.log("[LIBRARY] displayObject type:",L),console.log("[LIBRARY] has texture?",!!(S!=null&&S.texture)),S!=null&&S.texture)S.texture=A,console.log("[LIBRARY] \u2705 Applied to display object:",y);else if(L==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:R}=await import("pixi.js"),O=S.parent,C=(c=(o=O==null?void 0:O.getChildIndex)==null?void 0:o.call(O,S))!=null?c:0,z={x:S.x,y:S.y},k={x:(d=(l=S.anchor)==null?void 0:l.x)!=null?d:.5,y:(p=(u=S.anchor)==null?void 0:u.y)!=null?p:.5},D={x:(m=(f=S.scale)==null?void 0:f.x)!=null?m:1,y:(g=(h=S.scale)==null?void 0:h.y)!=null?g:1},$=(v=S.alpha)!=null?v:1,ue=(b=S.visible)!=null?b:!0,V=new R(A);V.anchor.set(k.x,k.y),V.position.set(z.x,z.y),V.scale.set(D.x,D.y),V.alpha=$,V.visible=ue,O&&(O.removeChild(S),O.addChildAt(V,C),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),_.pixiObject&&(_.pixiObject=V),_.pixi&&(_.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(S!=null&&S.children){let R=S.children.find(O=>O.texture);R?(R.texture=A,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let M=`raw/library/${n}/${i}`;en({objectId:y,path:"render.asset.path",value:M}),console.log("[LIBRARY] \u2705 Staged config override for:",y,"path:",M)}catch(y){console.error("[LIBRARY] Error applying slot asset:",y)}}async function yh(e,t,i,n){var r;console.log("[LIBRARY] resetSlotAsset:",{objectId:t,defaultAsset:i,category:n});try{let a=t.startsWith("json.")?t.replace("json.",""):t,s=Date.now(),o=`/raw/${i}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let c=await wa.load(o);if(!c){console.error("[LIBRARY] Failed to load default texture:",o);return}He[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let l=window.CustomAssets;l!=null&&l[a]&&(l[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let d=window.gameObjectManager;if(d){let u=d.get(a);if(u){let p=((r=u.getDisplayObject)==null?void 0:r.call(u))||u.pixiObject||u;p!=null&&p.texture&&(p.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}en({objectId:a,path:"render.asset.path",value:i}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}import{Graphics as Sh,Point as cx}from"pixi.js";import{Point as xh}from"pixi.js";var Pt=()=>window.debugConfig||{},wh=()=>window.resolveAnchorVec2||(e=>({x:.5,y:.5})),_h=()=>window.resolveScreenAnchorPoint||(()=>new xh),Eh=()=>window.resolveScreenRatioPoint||(()=>new xh);function Ah(e){_a(e)&&(e.objectDebugRaf||(e.objectDebugRaf=window.requestAnimationFrame(()=>Ea(e))))}function Ch(e){e.objectDebugRaf&&(window.cancelAnimationFrame(e.objectDebugRaf),e.objectDebugRaf=null),Fn(e)}function _a(e){return e.isDebugOpen}function Ea(e){var a,s,o;if(!_a(e)){e.objectDebugRaf=null;return}e.objectDebugRaf=window.requestAnimationFrame(()=>Ea(e));let t=tl(e);if(!t){Bn(e,null),Fn(e);return}let i=il(e,t);if(!i){Bn(e,null),Fn(e);return}let n=new cx;(a=i.getGlobalPosition)==null||a.call(i,n);let r=nl(e,i);Bn(e,{instanceId:t,worldX:n.x,worldY:n.y,configX:(s=r==null?void 0:r.x)!=null?s:null,configY:(o=r==null?void 0:r.y)!=null?o:null}),e.highlightObject?ol(e,i):cl(e),e.highlightAnchor&&r?ll(e,r):dl(e)}function tl(e){var r;let t=e.selectedObjectId;if(!t)return null;let i=window.__editableObjectInstances,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return Array.isArray(n)&&n.length>0?n[0]:t}function il(e,t){var r,a;let i=window.gameObjectManager,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Nn(e){let t=e.selectedObjectId;if(!t)return null;let i=window.getEditableObjectConfig;return typeof i!="function"?null:i(t)}function nl(e,t){var s,o;let i=Nn(e);if(!i)return null;let n=(s=i.transform)!=null?s:{},r=rl(e);if(!r)return null;if(n.position_ratio!=null)return Eh()(r.width,r.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"center";return _h()(r.width,r.height,a)}function rl(e){var a;let t=(a=e.container)==null?void 0:a.querySelector(".game-container"),i=Number(t==null?void 0:t.dataset.screenWidth),n=Number(t==null?void 0:t.dataset.screenHeight);if(Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0)return{width:i,height:n};let r=window.gameApp;return r!=null&&r.renderer?{width:r.renderer.width,height:r.renderer.height}:null}function al(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectBoundsGfx&&e.objectBoundsGfx.parent!==t.stage&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectBoundsGfx||(e.objectBoundsGfx=new Sh,e.objectBoundsGfx.zIndex=999999,t.stage.addChild(e.objectBoundsGfx)),e.objectBoundsGfx):null}function sl(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectAnchorGfx&&e.objectAnchorGfx.parent!==t.stage&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null),e.objectAnchorGfx||(e.objectAnchorGfx=new Sh,e.objectAnchorGfx.zIndex=1e6,t.stage.addChild(e.objectAnchorGfx)),e.objectAnchorGfx):null}function ol(e,t){var r;let i=al(e);if(!i)return;let n=(r=t.getBounds)==null?void 0:r.call(t);n&&(i.clear(),i.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function ll(e,t){let i=sl(e);if(!i)return;let n=6;i.clear(),i.moveTo(t.x-n,t.y),i.lineTo(t.x+n,t.y),i.moveTo(t.x,t.y-n),i.lineTo(t.x,t.y+n),i.stroke({width:2,color:3066993,alpha:.9})}function cl(e){e.objectBoundsGfx&&e.objectBoundsGfx.clear()}function dl(e){e.objectAnchorGfx&&e.objectAnchorGfx.clear()}function Fn(e){e.objectBoundsGfx&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectAnchorGfx&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null)}function Bn(e,t){e.sceneToolsPanel.updateInfo(t?{instanceId:t.instanceId,worldX:t.worldX,worldY:t.worldY,anchorX:t.configX,anchorY:t.configY}:null)}function Th(e,t){return t.split(".").reduce((i,n)=>i?i[n]:void 0,e)}function kh(e,t,i){var s;let n=t.split("."),r=n.pop(),a=e;for(let o of n)a[o]=(s=a[o])!=null?s:{},a=a[o];a[r]=i}function ul(e){var n,r,a,s,o;if(!e)return!1;if((n=e.transform)!=null&&n.offset)return!0;let t=((a=(r=e.identity)==null?void 0:r.category)!=null?a:"").toString().toLowerCase(),i=((o=(s=e.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return t.includes("ui")||i.startsWith("ui")||i.includes("label")}function Aa(e){let t=Pt();t.layout&&(t.layout.scale_multiplier=1,t.layout.position_offset={x:0,y:0},t.layout.debug_rect_visible=!0,t.layout.debug_rect_color=16711680,t.layout.debug_rect_thickness=4),t.engine&&(t.engine.scale=1,t.engine.background_scale=1.05,t.engine.label_pulse_speed=3,t.engine.label_pulse_intensity=.03),t.physics&&(t.physics.rope_length=420),window.location.reload()}function Lh(e){window.location.reload()}function Ca(e){let t=JSON.stringify(Pt(),null,2);navigator.clipboard.writeText(t).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(t),alert("Config logged to console (clipboard not available)")})}async function Rh(e,t){var i,n,r;if(!(!e.configViewer||!e.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(t):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:c}=await import("./config-44AFSRES.js"),u=(((i=(await o("scene.main")).scene)==null?void 0:i.objects)||[]).find(f=>f.object_config===t||f.instance_id===t);if(!u)return;let p=await c(u.object_config);console.log("[PREVIEW] Loaded object config (fallback)",t,p),Sa(e,p),(n=e.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",t,s),Sa(e,s),(r=e.configViewer)==null||r.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function Sa(e,t){var u,p,f,m,h,g,v,b,y,x;if(!e.container)return;let i=e.container.querySelector("#config-pos-x"),n=e.container.querySelector("#config-pos-y"),r=e.container.querySelector("#config-scale"),a=e.container.querySelector("#config-anchor-x"),s=e.container.querySelector("#config-anchor-y"),c=ul(t)?(u=t.transform)==null?void 0:u.offset:(p=t.transform)==null?void 0:p.position;i&&(i.value=String((f=c==null?void 0:c.x)!=null?f:0)),n&&(n.value=String((m=c==null?void 0:c.y)!=null?m:0)),r&&(r.value=String((g=(h=t.transform)==null?void 0:h.scale)!=null?g:1));let l=(x=(y=(v=t.transform)==null?void 0:v.anchor)!=null?y:(b=t.render)==null?void 0:b.anchor)!=null?x:{x:.5,y:.5},d=wh()(l);a&&(a.value=String(d.x)),s&&(s.value=String(d.y))}function Mh(e){var c,l,d,u,p,f,m,h,g,v;let t=e.selectedObjectId;if(!t||!e.container)return;let i=(l=(c=e.container.querySelector("#config-pos-x"))==null?void 0:c.value)!=null?l:"0",n=(u=(d=e.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?u:"0",r=(f=(p=e.container.querySelector("#config-scale"))==null?void 0:p.value)!=null?f:"1",a=(h=(m=e.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?h:"0.5",s=(v=(g=e.container.querySelector("#config-anchor-y"))==null?void 0:g.value)!=null?v:"0.5",o=`${t}:
967
990
  position: (${i}, ${n})
968
991
  scale: ${r}
969
- anchor: (${a}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(v=>console.error("[DEBUG] Failed to copy config values:",v))}async function dl(e,t){var u,p,f,b,h,g,m,v,y,x,w;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!e.container)return;let i=e.selectedObjectId;if(!i){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((p=(u=e.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?p:0),r=Number((b=(f=e.container.querySelector("#config-pos-y"))==null?void 0:f.value)!=null?b:0),a=Number((g=(h=e.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?g:1),s=Number((v=(m=e.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?v:.5),o=Number((x=(y=e.container.querySelector("#config-anchor-y"))==null?void 0:y.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",i,{posX:n,posY:r,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:c}=await import("./ConfigOverride-C26KK6X2.js");c({objectId:i,path:"transform.position",value:{x:n,y:r}},{silent:t==null?void 0:t.silent}),c({objectId:i,path:"transform.scale",value:a},{silent:t==null?void 0:t.silent}),c({objectId:i,path:"transform.anchor",value:{x:s,y:o}},{silent:t==null?void 0:t.silent});let l=Fn(e);cl(l)&&c({objectId:i,path:"transform.offset",value:{x:n,y:r}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let d=window.applyEditableObjectConfig;if(typeof d=="function"){let C=(w=window.getEditableObjectConfig)==null?void 0:w.call(window,i);C?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",i),d(i,C)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",i)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function Sh(e,t,i){let{applyConfigOverride:n}=await import("./ConfigOverride-C26KK6X2.js");Object.entries(t.assets).forEach(([c,l])=>{n({path:`assets.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.theme).forEach(([c,l])=>{n({path:`runtime.theme.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.ui).forEach(([c,l])=>{n({path:`runtime.ui.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.fonts).forEach(([c,l])=>{n({path:`runtime.fonts.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.audio).forEach(([c,l])=>{n({path:`runtime.audio.${c}`,value:l},{silent:!0})});let r=window.applyEditableEngineConfig;if(typeof r=="function"){let c={theme:t.runtime.theme,fonts:t.runtime.fonts,audio:t.runtime.audio},l={};Object.entries(t.runtime.ui).forEach(([d,u])=>{var p;if(d)if(d.includes(".")){let f=d.split("."),b=l;for(let h=0;h<f.length-1;h++){let g=f[h];b[g]=(p=b[g])!=null?p:{},b=b[g]}b[f[f.length-1]]=u}else l[d]=u}),c.ui=l,r({runtime:c,assets:t.assets})}let a=Object.values(t.assets).some(c=>/^(blob:|data:)/.test(c)),s=(i==null?void 0:i.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function Ah(e){e.selectedObjectId&&(e.objectAutoApplyTimer&&window.clearTimeout(e.objectAutoApplyTimer),e.objectAutoApplyTimer=window.setTimeout(()=>{e.objectAutoApplyTimer=null,dl(e,{silent:!0})},150))}var Qy=3e3;function Ch(e,t,i){let n=i!=null?i:e.offsetParent;if(!n)return;t.style.cursor="move";let r=0,a=0,s=0,o=0,c=!1,l=u=>{if(!c)return;let p=u.clientX-r,f=u.clientY-a;e.style.left=`${s+p}px`,e.style.top=`${o+f}px`},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",d))};t.addEventListener("pointerdown",u=>{if(u.button!==0)return;let p=u.target;if(p!=null&&p.closest("button, input, select, textarea"))return;u.preventDefault();let f=e.getBoundingClientRect(),b=n.getBoundingClientRect();s=Math.max(0,f.left-b.left),o=Math.max(0,f.top-b.top);let h=f.width,g=f.height,m=b.width,v=b.height;s=Math.min(s,m-h),o=Math.min(o,v-g),r=u.clientX,a=u.clientY,e.style.left=`${s}px`,e.style.top=`${o}px`,e.style.right="auto",e.style.bottom="auto",e.style.zIndex=String(++Qy);let y=e.getBoundingClientRect();(y.left<0||y.top<0||y.right>window.innerWidth||y.bottom>window.innerHeight)&&(e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto"),c=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",d)})}function kh(e,t,i){t.style.cursor="nwse-resize";let n=0,r=0,a=0,s=0,o=!1,c=d=>{if(!o)return;let u=d.clientX-a,p=d.clientY-s,f=Math.max(100,n+u),b=Math.max(100,r+p);e.style.width=`${f}px`,e.style.height=`${b}px`,i==null||i(f,b)},l=()=>{o&&(o=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",l))};t.addEventListener("pointerdown",d=>{if(d.button!==0)return;d.preventDefault(),d.stopPropagation();let u=e.getBoundingClientRect();n=u.width,r=u.height,a=d.clientX,s=d.clientY,o=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",l)})}function ul(e,t){var h,g,m;let i=(m=(g=(h=e.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?g:e.debugOverlay)!=null?m:t.offsetParent;if(!i)return;let n=i.getBoundingClientRect(),r=t.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));r.width>s&&(t.style.width=`${s}px`),r.height>o&&(t.style.height=`${o}px`);let c=t.getBoundingClientRect(),l=c.left-n.left,d=c.top-n.top,u=Math.max(a,n.width-c.width-a),p=Math.max(a,n.height-c.height-a),f=Math.min(Math.max(l,a),u),b=Math.min(Math.max(d,a),p);t.style.left=`${Math.round(f)}px`,t.style.top=`${Math.round(b)}px`,t.style.right="auto",t.style.bottom="auto"}function Jt(e){if(!e.container)return;let t=e.container.querySelector("#debug-workbench");if(!t)return;ul(e,t);let i={activeTab:e.activeTab,width:t.style.width,height:t.style.height,left:t.style.left,top:t.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(i))}function Aa(e){try{let t=localStorage.getItem("preview_workbench_state");if(!t)return;let i=JSON.parse(t);i.activeTab&&(e.activeTab=i.activeTab),window.requestAnimationFrame(()=>{var r;let n=(r=e.container)==null?void 0:r.querySelector("#debug-workbench");n&&(i.width&&(n.style.width=i.width),i.height&&(n.style.height=i.height),i.left&&(n.style.left=i.left,n.style.right="auto"),i.top&&(n.style.top=i.top,n.style.bottom="auto"),ul(e,n))})}catch(t){console.warn("[PREVIEW] Failed to load workbench state",t)}}function Th(e,t){let i=t.getBoundingClientRect();(i.left<0||i.top<0||i.right>window.innerWidth||i.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),t.style.left="16px",t.style.top="72px",t.style.right="auto",t.style.bottom="auto",ul(e,t),Jt(e))}function Lh(e){var r,a,s;if(!e.container)return;let t=e.container,i=t.querySelector("#debug-toggle");i||console.warn("[PREVIEW] Debug toggle not found in DOM"),i==null||i.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=e.toggleDebug)==null||o.call(e)}),(r=t.querySelector("#debug-close"))==null||r.addEventListener("click",()=>{var o;return(o=e.toggleDebug)==null?void 0:o.call(e,!1)}),(a=t.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>Ea(e)),(s=t.querySelector("#debug-export"))==null||s.addEventListener("click",()=>Sa(e)),t.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let c=o.dataset.tab;e.activeTab=c,pl(e),Jt(e)})}),hl(e,t),fl(e,t)}function pl(e){if(!e.container)return;let t=e.container;t.querySelectorAll(".workbench-tab").forEach(r=>{let a=r.dataset.tab;r.classList.toggle("active",a===e.activeTab)}),t.querySelectorAll(".workbench-tab-panel").forEach(r=>{let a=r.dataset.tabPanel;r.classList.toggle("active",a===e.activeTab)})}function fl(e,t){Te(e,t,"debug-scene-scale","engine.scale","#debug-scene-scale-value"),Te(e,t,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),Te(e,t,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),Te(e,t,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),Te(e,t,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),Te(e,t,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),Te(e,t,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),Te(e,t,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),Te(e,t,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),Te(e,t,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let i=t.querySelector("#debug-rect-visible");i==null||i.addEventListener("change",()=>{let r=It();r.layout&&(r.layout.debug_rect_visible=!!i.checked)});let n=t.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let r=n.value.replace("#",""),a=parseInt(r,16),s=It();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Rh(e){if(!e.container||!e.debugOverlay)return;let t=e.container.querySelector("#debug-workbench"),i=e.container.querySelector("#workbench-handle"),n=e.container.querySelector("#workbench-resize");t&&i&&(!t.style.left&&!t.style.right&&!t.style.top&&!t.style.bottom&&(t.style.right="16px",t.style.top="72px"),Ch(t,i,e.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{Jt(e),Th(e,t)},10)})),t&&n&&kh(t,n,()=>Jt(e)),Aa(e)}function hl(e,t){Array.from(t.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let r=n.closest(".scene-panel");r&&r.classList.toggle("collapsed")})})}function Te(e,t,i,n,r){let a=t.querySelector(`#${i}`),s=t.querySelector(r);if(!a||!s)return;let o=yh(It(),n);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let c=Number(a.value);s.textContent=String(c),xh(It(),n,c)})}var Ca=class{constructor(){this.container=null}initialize(t){this.container=t,window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let t=ac(),{hasChanges:i,overrideCount:n,overrides:r}=t,a={};for(let c of r){let l=c.objectId||"Engine";a[l]||(a[l]=[]),a[l].push(c)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never";return`
992
+ anchor: (${a}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(b=>console.error("[DEBUG] Failed to copy config values:",b))}async function pl(e,t){var u,p,f,m,h,g,v,b,y,x,w;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!e.container)return;let i=e.selectedObjectId;if(!i){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((p=(u=e.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?p:0),r=Number((m=(f=e.container.querySelector("#config-pos-y"))==null?void 0:f.value)!=null?m:0),a=Number((g=(h=e.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?g:1),s=Number((b=(v=e.container.querySelector("#config-anchor-x"))==null?void 0:v.value)!=null?b:.5),o=Number((x=(y=e.container.querySelector("#config-anchor-y"))==null?void 0:y.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",i,{posX:n,posY:r,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:c}=await import("./ConfigOverride-C26KK6X2.js");c({objectId:i,path:"transform.position",value:{x:n,y:r}},{silent:t==null?void 0:t.silent}),c({objectId:i,path:"transform.scale",value:a},{silent:t==null?void 0:t.silent}),c({objectId:i,path:"transform.anchor",value:{x:s,y:o}},{silent:t==null?void 0:t.silent});let l=Nn(e);ul(l)&&c({objectId:i,path:"transform.offset",value:{x:n,y:r}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let d=window.applyEditableObjectConfig;if(typeof d=="function"){let A=(w=window.getEditableObjectConfig)==null?void 0:w.call(window,i);A?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",i),d(i,A)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",i)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function Ph(e,t,i){let{applyConfigOverride:n}=await import("./ConfigOverride-C26KK6X2.js");Object.entries(t.assets).forEach(([c,l])=>{n({path:`assets.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.theme).forEach(([c,l])=>{n({path:`runtime.theme.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.ui).forEach(([c,l])=>{n({path:`runtime.ui.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.fonts).forEach(([c,l])=>{n({path:`runtime.fonts.${c}`,value:l},{silent:!0})}),Object.entries(t.runtime.audio).forEach(([c,l])=>{n({path:`runtime.audio.${c}`,value:l},{silent:!0})});let r=window.applyEditableEngineConfig;if(typeof r=="function"){let c={theme:t.runtime.theme,fonts:t.runtime.fonts,audio:t.runtime.audio},l={};Object.entries(t.runtime.ui).forEach(([d,u])=>{var p;if(d)if(d.includes(".")){let f=d.split("."),m=l;for(let h=0;h<f.length-1;h++){let g=f[h];m[g]=(p=m[g])!=null?p:{},m=m[g]}m[f[f.length-1]]=u}else l[d]=u}),c.ui=l,r({runtime:c,assets:t.assets})}let a=Object.values(t.assets).some(c=>/^(blob:|data:)/.test(c)),s=(i==null?void 0:i.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function Ih(e){e.selectedObjectId&&(e.objectAutoApplyTimer&&window.clearTimeout(e.objectAutoApplyTimer),e.objectAutoApplyTimer=window.setTimeout(()=>{e.objectAutoApplyTimer=null,pl(e,{silent:!0})},150))}var dx=3e3;function Oh(e,t,i){let n=i!=null?i:e.offsetParent;if(!n)return;t.style.cursor="move";let r=0,a=0,s=0,o=0,c=!1,l=u=>{if(!c)return;let p=u.clientX-r,f=u.clientY-a;e.style.left=`${s+p}px`,e.style.top=`${o+f}px`},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",d))};t.addEventListener("pointerdown",u=>{if(u.button!==0)return;let p=u.target;if(p!=null&&p.closest("button, input, select, textarea"))return;u.preventDefault();let f=e.getBoundingClientRect(),m=n.getBoundingClientRect();s=Math.max(0,f.left-m.left),o=Math.max(0,f.top-m.top);let h=f.width,g=f.height,v=m.width,b=m.height;s=Math.min(s,v-h),o=Math.min(o,b-g),r=u.clientX,a=u.clientY,e.style.left=`${s}px`,e.style.top=`${o}px`,e.style.right="auto",e.style.bottom="auto",e.style.zIndex=String(++dx);let y=e.getBoundingClientRect();(y.left<0||y.top<0||y.right>window.innerWidth||y.bottom>window.innerHeight)&&(e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto"),c=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",d)})}function Dh(e,t,i){t.style.cursor="nwse-resize";let n=0,r=0,a=0,s=0,o=!1,c=d=>{if(!o)return;let u=d.clientX-a,p=d.clientY-s,f=Math.max(100,n+u),m=Math.max(100,r+p);e.style.width=`${f}px`,e.style.height=`${m}px`,i==null||i(f,m)},l=()=>{o&&(o=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",l))};t.addEventListener("pointerdown",d=>{if(d.button!==0)return;d.preventDefault(),d.stopPropagation();let u=e.getBoundingClientRect();n=u.width,r=u.height,a=d.clientX,s=d.clientY,o=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",l)})}function fl(e,t){var h,g,v;let i=(v=(g=(h=e.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?g:e.debugOverlay)!=null?v:t.offsetParent;if(!i)return;let n=i.getBoundingClientRect(),r=t.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));r.width>s&&(t.style.width=`${s}px`),r.height>o&&(t.style.height=`${o}px`);let c=t.getBoundingClientRect(),l=c.left-n.left,d=c.top-n.top,u=Math.max(a,n.width-c.width-a),p=Math.max(a,n.height-c.height-a),f=Math.min(Math.max(l,a),u),m=Math.min(Math.max(d,a),p);t.style.left=`${Math.round(f)}px`,t.style.top=`${Math.round(m)}px`,t.style.right="auto",t.style.bottom="auto"}function Jt(e){if(!e.container)return;let t=e.container.querySelector("#debug-workbench");if(!t)return;fl(e,t);let i={activeTab:e.activeTab,width:t.style.width,height:t.style.height,left:t.style.left,top:t.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(i))}function Ta(e){try{let t=localStorage.getItem("preview_workbench_state");if(!t)return;let i=JSON.parse(t);i.activeTab&&(e.activeTab=i.activeTab),window.requestAnimationFrame(()=>{var r;let n=(r=e.container)==null?void 0:r.querySelector("#debug-workbench");n&&(i.width&&(n.style.width=i.width),i.height&&(n.style.height=i.height),i.left&&(n.style.left=i.left,n.style.right="auto"),i.top&&(n.style.top=i.top,n.style.bottom="auto"),fl(e,n))})}catch(t){console.warn("[PREVIEW] Failed to load workbench state",t)}}function zh(e,t){let i=t.getBoundingClientRect();(i.left<0||i.top<0||i.right>window.innerWidth||i.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),t.style.left="16px",t.style.top="72px",t.style.right="auto",t.style.bottom="auto",fl(e,t),Jt(e))}function jh(e){var r,a,s;if(!e.container)return;let t=e.container,i=t.querySelector("#debug-toggle");i||console.warn("[PREVIEW] Debug toggle not found in DOM"),i==null||i.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=e.toggleDebug)==null||o.call(e)}),(r=t.querySelector("#debug-close"))==null||r.addEventListener("click",()=>{var o;return(o=e.toggleDebug)==null?void 0:o.call(e,!1)}),(a=t.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>Aa(e)),(s=t.querySelector("#debug-export"))==null||s.addEventListener("click",()=>Ca(e)),t.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let c=o.dataset.tab;e.activeTab=c,hl(e),Jt(e)})}),ml(e,t),gl(e,t)}function hl(e){if(!e.container)return;let t=e.container;t.querySelectorAll(".workbench-tab").forEach(r=>{let a=r.dataset.tab;r.classList.toggle("active",a===e.activeTab)}),t.querySelectorAll(".workbench-tab-panel").forEach(r=>{let a=r.dataset.tabPanel;r.classList.toggle("active",a===e.activeTab)})}function gl(e,t){ke(e,t,"debug-scene-scale","engine.scale","#debug-scene-scale-value"),ke(e,t,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),ke(e,t,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),ke(e,t,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),ke(e,t,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),ke(e,t,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),ke(e,t,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),ke(e,t,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),ke(e,t,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),ke(e,t,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let i=t.querySelector("#debug-rect-visible");i==null||i.addEventListener("change",()=>{let r=Pt();r.layout&&(r.layout.debug_rect_visible=!!i.checked)});let n=t.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let r=n.value.replace("#",""),a=parseInt(r,16),s=Pt();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Bh(e){if(!e.container||!e.debugOverlay)return;let t=e.container.querySelector("#debug-workbench"),i=e.container.querySelector("#workbench-handle"),n=e.container.querySelector("#workbench-resize");t&&i&&(!t.style.left&&!t.style.right&&!t.style.top&&!t.style.bottom&&(t.style.right="16px",t.style.top="72px"),Oh(t,i,e.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{Jt(e),zh(e,t)},10)})),t&&n&&Dh(t,n,()=>Jt(e)),Ta(e)}function ml(e,t){Array.from(t.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let r=n.closest(".scene-panel");r&&r.classList.toggle("collapsed")})})}function ke(e,t,i,n,r){let a=t.querySelector(`#${i}`),s=t.querySelector(r);if(!a||!s)return;let o=Th(Pt(),n);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let c=Number(a.value);s.textContent=String(c),kh(Pt(),n,c)})}var ka=class{constructor(){this.container=null}initialize(t){this.container=t,window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let t=oc(),{hasChanges:i,overrideCount:n,overrides:r}=t,a={};for(let c of r){let l=c.objectId||"Engine";a[l]||(a[l]=[]),a[l].push(c)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never";return`
970
993
  <div class="config-persistence-panel">
971
994
  <div class="persistence-status-bar ${i?"has-changes":"no-changes"}">
972
995
  ${i?`
@@ -1045,13 +1068,13 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1045
1068
  <p><strong>Apply to Project</strong> writes the current preview state to your local .json files in /configs/ folder. This state will be used for the dashboard build.</p>
1046
1069
  </div>
1047
1070
  </div>
1048
- `}formatValue(t){return t===null?"null":typeof t=="string"?t.length>25?t.substring(0,22)+"...":t:typeof t=="object"?"{...}":String(t)}setupEventListeners(){if(!this.container)return;let t=this.container.querySelector("#apply-to-project-btn");t==null||t.addEventListener("click",async()=>{var o;if(!(t.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let c=localStorage.getItem("handler_last_version_name")||"",d=((o=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",c))!=null?o:"").trim();if(!d){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",d),t.textContent="\u23F3 Writing to disk...",t.setAttribute("disabled","true"),await sc(d),this.showSuccessNotification(),this.refreshPanel()}catch(c){console.error("[ConfigPersistence] Apply failed:",c),alert(`\u274C Apply failed: ${c.message}`),t.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",t.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(s=>{s.addEventListener("click",()=>{let o=s.dataset.removePath,c=s.dataset.removeId;rc(c||void 0,o)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Xa()});let r=this.container.querySelector("#reset-to-applied-btn");r==null||r.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Xa()});let a=this.container.querySelector("#reset-to-original-btn");a==null||a.addEventListener("click",async()=>{await oc()})}showSuccessNotification(){let t=document.createElement("div");t.className="persistence-notification success",t.innerHTML=`
1071
+ `}formatValue(t){return t===null?"null":typeof t=="string"?t.length>25?t.substring(0,22)+"...":t:typeof t=="object"?"{...}":String(t)}setupEventListeners(){if(!this.container)return;let t=this.container.querySelector("#apply-to-project-btn");t==null||t.addEventListener("click",async()=>{var o;if(!(t.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let c=localStorage.getItem("handler_last_version_name")||"",d=((o=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",c))!=null?o:"").trim();if(!d){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",d),t.textContent="\u23F3 Writing to disk...",t.setAttribute("disabled","true"),await lc(d),this.showSuccessNotification(),this.refreshPanel()}catch(c){console.error("[ConfigPersistence] Apply failed:",c),alert(`\u274C Apply failed: ${c.message}`),t.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",t.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(s=>{s.addEventListener("click",()=>{let o=s.dataset.removePath,c=s.dataset.removeId;sc(c||void 0,o)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Ja()});let r=this.container.querySelector("#reset-to-applied-btn");r==null||r.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Ja()});let a=this.container.querySelector("#reset-to-original-btn");a==null||a.addEventListener("click",async()=>{await cc()})}showSuccessNotification(){let t=document.createElement("div");t.className="persistence-notification success",t.innerHTML=`
1049
1072
  <div class="notify-icon">\u2705</div>
1050
1073
  <div class="notify-content">
1051
1074
  <strong>Changes Applied!</strong>
1052
1075
  <span>Project files updated.</span>
1053
1076
  </div>
1054
- `,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let t=this.container.querySelector(".config-persistence-panel");t?t.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}};var ka=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new cr;this.sceneToolsPanel=new dr;this.inspectorPanel=new _r;this.libraryPanel=new ur;this.brandVisionPanel=new ba;this.customizeSettingsPanel=new ma;this.configPersistencePanel=new Ca;this.loadingScreenPanel=new va}applyAssetChange(t,i){return lh(this,t,i)}resetAsset(t){return ch(this,t)}applySlotAsset(t,i,n){return dh(this,t,i,n)}resetSlotAsset(t,i,n){return uh(this,t,i,n)}startObjectVisuals(){return mh(this)}stopObjectVisuals(){return vh(this)}shouldRunObjectVisuals(){return xa(this)}updateObjectVisuals(){return wa(this)}getSelectedInstanceId(){return Qo(this)}getDisplayObjectById(t){return el(this,t)}getSelectedObjectConfig(){return Fn(this)}getConfigAnchorWorldPoint(t){return tl(this,t)}getScreenSize(){return il(this)}ensureBoundsGfx(){return nl(this)}ensureAnchorGfx(){return rl(this)}drawBounds(t){return al(this,t)}drawAnchor(t){return sl(this,t)}clearBounds(){return ol(this)}clearAnchor(){return ll(this)}clearObjectVisuals(){return Bn(this)}updateObjectInfo(t){return jn(this,t)}resetDebugConfig(){return Ea(this)}applyDebugConfig(){return wh(this)}exportDebugConfig(){return Sa(this)}loadObjectConfig(t){return _h(this,t)}fillConfigViewer(t){return _a(this,t)}copyConfigValues(){return Eh(this)}applyObjectConfig(t){return dl(this,t)}applyCustomizeSettings(t,i){return Sh(this,t,i)}scheduleObjectAutoApply(){return Ah(this)}setupDebugEventListeners(){return Lh(this)}setupDebugInputListeners(t){return fl(this,t)}setupPanelLayout(){return Rh(this)}setupCollapsiblePanels(t){return hl(this,t)}setupRangeInput(t,i,n,r){return Te(this,t,i,n,r)}updateWorkbenchTabs(){return pl(this)}saveWorkbenchState(){return Jt(this)}loadWorkbenchState(){return Aa(this)}initialize(t){var i;this.container=t,this.debugOverlay=t.querySelector(".debug-overlay"),this.configViewer=t.querySelector("#config-viewer");try{let n=localStorage.getItem("preview_workbench_state");if(n){let r=JSON.parse(n);r.activeTab&&(this.activeTab=r.activeTab)}}catch(n){console.warn("[PREVIEW] Failed to load workbench tab state",n)}this.sceneObjectsPanel.initialize(t,{onSelect:n=>this.handleObjectSelect(n)}),this.libraryPanel.initialize(t,{onApply:(n,r,a)=>this.applySlotAsset(n,r,a),onReset:(n,r,a)=>this.resetSlotAsset(n,r,a)}),this.inspectorPanel.initialize(t,{onPropertyChange:(n,r,a)=>{console.log("[Inspector] Property changed:",n,r,a)}}),this.brandVisionPanel.initialize(t,()=>{this.toggleDebug(!1);let n="/dashboard";window.location.pathname!==n&&(window.location.href=n)}),this.customizeSettingsPanel.initialize(t,{onApply:(n,r)=>this.applyCustomizeSettings(n,r)}),this.configPersistencePanel.initialize(t),this.loadingScreenPanel.initialize(t,{onShowLoadingScreen:()=>{let n=window;typeof n.__previewShowLoading=="function"?n.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let n=window;typeof n.__previewHideLoading=="function"?n.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:n=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({loading:n}),typeof r.__previewUpdateLoading=="function"?r.__previewUpdateLoading(n):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(n,r,a,s)=>{this.customizeSettingsPanel.openAiEditor(n,r,a,s)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=n=>this.selectObject(n),window.addEventListener("config:changed",n=>{var r,a;((r=n.detail)==null?void 0:r.action)!=="remove"&&((a=n.detail)==null?void 0:a.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(n,r,a)=>this.applySlotAsset(n,r,a),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var r;let n=window.getActiveConfig;if(typeof n=="function"){let a=n();return((r=a==null?void 0:a.engine)==null?void 0:r.splash)||null}return null},window.addAssetToRegistry=(n,r)=>{let a=window.getEditableAssets;if(typeof a=="function"){let s=a();if(s!=null&&s.libraryAssets&&(s.libraryAssets[n]||(s.libraryAssets[n]=[]),!s.libraryAssets[n].some(c=>c.filename===r))){let c=r.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");s.libraryAssets[n].unshift({filename:r,displayName:c}),console.log(`[DEBUG] Added ${r} to registry category ${n}`)}}}}selectObject(t){this.handleObjectSelect(t),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}highlightChangesTab(){var i;let t=(i=this.container)==null?void 0:i.querySelector('[data-tab="changes"]');t&&t.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1077
+ `,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let t=this.container.querySelector(".config-persistence-panel");t?t.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}};var La=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new dr;this.sceneToolsPanel=new ur;this.inspectorPanel=new Sr;this.libraryPanel=new pr;this.brandVisionPanel=new va;this.customizeSettingsPanel=new ya;this.configPersistencePanel=new ka;this.loadingScreenPanel=new xa}applyAssetChange(t,i){return mh(this,t,i)}resetAsset(t){return bh(this,t)}applySlotAsset(t,i,n){return vh(this,t,i,n)}resetSlotAsset(t,i,n){return yh(this,t,i,n)}startObjectVisuals(){return Ah(this)}stopObjectVisuals(){return Ch(this)}shouldRunObjectVisuals(){return _a(this)}updateObjectVisuals(){return Ea(this)}getSelectedInstanceId(){return tl(this)}getDisplayObjectById(t){return il(this,t)}getSelectedObjectConfig(){return Nn(this)}getConfigAnchorWorldPoint(t){return nl(this,t)}getScreenSize(){return rl(this)}ensureBoundsGfx(){return al(this)}ensureAnchorGfx(){return sl(this)}drawBounds(t){return ol(this,t)}drawAnchor(t){return ll(this,t)}clearBounds(){return cl(this)}clearAnchor(){return dl(this)}clearObjectVisuals(){return Fn(this)}updateObjectInfo(t){return Bn(this,t)}resetDebugConfig(){return Aa(this)}applyDebugConfig(){return Lh(this)}exportDebugConfig(){return Ca(this)}loadObjectConfig(t){return Rh(this,t)}fillConfigViewer(t){return Sa(this,t)}copyConfigValues(){return Mh(this)}applyObjectConfig(t){return pl(this,t)}applyCustomizeSettings(t,i){return Ph(this,t,i)}scheduleObjectAutoApply(){return Ih(this)}setupDebugEventListeners(){return jh(this)}setupDebugInputListeners(t){return gl(this,t)}setupPanelLayout(){return Bh(this)}setupCollapsiblePanels(t){return ml(this,t)}setupRangeInput(t,i,n,r){return ke(this,t,i,n,r)}updateWorkbenchTabs(){return hl(this)}saveWorkbenchState(){return Jt(this)}loadWorkbenchState(){return Ta(this)}initialize(t){var i;this.container=t,this.debugOverlay=t.querySelector(".debug-overlay"),this.configViewer=t.querySelector("#config-viewer");try{let n=localStorage.getItem("preview_workbench_state");if(n){let r=JSON.parse(n);r.activeTab&&(this.activeTab=r.activeTab)}}catch(n){console.warn("[PREVIEW] Failed to load workbench tab state",n)}this.sceneObjectsPanel.initialize(t,{onSelect:n=>this.handleObjectSelect(n)}),this.libraryPanel.initialize(t,{onApply:(n,r,a)=>this.applySlotAsset(n,r,a),onReset:(n,r,a)=>this.resetSlotAsset(n,r,a)}),this.inspectorPanel.initialize(t,{onPropertyChange:(n,r,a)=>{console.log("[Inspector] Property changed:",n,r,a)}}),this.brandVisionPanel.initialize(t,()=>{this.toggleDebug(!1);let n="/dashboard";window.location.pathname!==n&&(window.location.href=n)}),this.customizeSettingsPanel.initialize(t,{onApply:(n,r)=>this.applyCustomizeSettings(n,r)}),this.configPersistencePanel.initialize(t),this.loadingScreenPanel.initialize(t,{onShowLoadingScreen:()=>{let n=window;typeof n.__previewShowLoading=="function"?n.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let n=window;typeof n.__previewHideLoading=="function"?n.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:n=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({loading:n}),typeof r.__previewUpdateLoading=="function"?r.__previewUpdateLoading(n):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(n,r,a,s)=>{this.customizeSettingsPanel.openAiEditor(n,r,a,s)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=n=>this.selectObject(n),window.addEventListener("config:changed",n=>{var r,a;((r=n.detail)==null?void 0:r.action)!=="remove"&&((a=n.detail)==null?void 0:a.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(n,r,a)=>this.applySlotAsset(n,r,a),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var r;let n=window.getActiveConfig;if(typeof n=="function"){let a=n();return((r=a==null?void 0:a.engine)==null?void 0:r.splash)||null}return null},window.addAssetToRegistry=(n,r)=>{let a=window.getEditableAssets;if(typeof a=="function"){let s=a();if(s!=null&&s.libraryAssets&&(s.libraryAssets[n]||(s.libraryAssets[n]=[]),!s.libraryAssets[n].some(c=>c.filename===r))){let c=r.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");s.libraryAssets[n].unshift({filename:r,displayName:c}),console.log(`[DEBUG] Added ${r} to registry category ${n}`)}}}}selectObject(t){this.handleObjectSelect(t),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}highlightChangesTab(){var i;let t=(i=this.container)==null?void 0:i.querySelector('[data-tab="changes"]');t&&t.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1055
1078
  <div class="debug-overlay hidden" id="debug-overlay">
1056
1079
  <div class="debug-workbench" id="debug-workbench">
1057
1080
  <div class="workbench-header" id="workbench-handle">
@@ -1096,7 +1119,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1096
1119
  <div class="workbench-resize-handle" id="workbench-resize"></div>
1097
1120
  </div>
1098
1121
  </div>
1099
- `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(t){var i;this.isDebugOpen=t!=null?t:!this.isDebugOpen,(i=this.debugOverlay)==null||i.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let t=this.container.querySelector("#debug-badge");t&&t.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(t){this.selectedObjectId=t,this.sceneObjectsPanel.setSelected(t),this.inspectorPanel.loadObject(t),this.loadObjectConfig(t),this.startObjectVisuals()}nudgeSelectedObject(t,i){var u,p,f,b,h,g,m,v,y;if(!this.container||!this.selectedObjectId)return;let r=this.sceneToolsPanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),s=this.container.querySelector("#config-pos-y"),o=Number((u=a==null?void 0:a.value)!=null?u:0),c=Number((p=s==null?void 0:s.value)!=null?p:0);if(!Number.isFinite(o)||!Number.isFinite(c)){let x=this.getSelectedObjectConfig();o=(h=(b=(f=x==null?void 0:x.transform)==null?void 0:f.position)==null?void 0:b.x)!=null?h:0,c=(v=(m=(g=x==null?void 0:x.transform)==null?void 0:g.position)==null?void 0:m.y)!=null?v:0}let l=o+t*r,d=c+i*r;a&&(a.value=String(l)),s&&(s.value=String(d)),(y=this.configViewer)==null||y.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function ex(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function tx(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}function ix(e){return`
1122
+ `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(t){var i;this.isDebugOpen=t!=null?t:!this.isDebugOpen,(i=this.debugOverlay)==null||i.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let t=this.container.querySelector("#debug-badge");t&&t.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(t){this.selectedObjectId=t,this.sceneObjectsPanel.setSelected(t),this.inspectorPanel.loadObject(t),this.loadObjectConfig(t),this.startObjectVisuals()}nudgeSelectedObject(t,i){var u,p,f,m,h,g,v,b,y;if(!this.container||!this.selectedObjectId)return;let r=this.sceneToolsPanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),s=this.container.querySelector("#config-pos-y"),o=Number((u=a==null?void 0:a.value)!=null?u:0),c=Number((p=s==null?void 0:s.value)!=null?p:0);if(!Number.isFinite(o)||!Number.isFinite(c)){let x=this.getSelectedObjectConfig();o=(h=(m=(f=x==null?void 0:x.transform)==null?void 0:f.position)==null?void 0:m.x)!=null?h:0,c=(b=(v=(g=x==null?void 0:x.transform)==null?void 0:g.position)==null?void 0:v.y)!=null?b:0}let l=o+t*r,d=c+i*r;a&&(a.value=String(l)),s&&(s.value=String(d)),(y=this.configViewer)==null||y.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function ux(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function px(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}function fx(e){return`
1100
1123
  Analyze these screenshots of a brand or game and extract its "Brand DNA".
1101
1124
 
1102
1125
  Provide a concise summary (2-3 sentences) covering:
@@ -1113,9 +1136,9 @@ Palette: [#RRGGBB, #RRGGBB, ...]
1113
1136
  ${e?`
1114
1137
  ADDITIONAL RULES/NOTES:
1115
1138
  ${e}`:""}
1116
- `.trim()}function Ph(){let e=[],t="",i=null;return{async addSources(n){let r=[];for(let a of n){let s=await ex(a),o=tx(s),c={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};e.push(c),r.push(c)}return r},getSources(){return e.slice()},async analyze(n,r,a){if(e.length===0)throw new Error("No screenshots to analyze.");let s=ix(r),o=e.map(p=>({base64:p.base64,mimeType:p.mimeType})),c=await ga(n,s,o,{model:a}),l=t,d=[],u=c.split(`
1117
- `);for(let p of u)if(p.toLowerCase().startsWith("summary:"))l=p.slice(8).trim();else if(p.toLowerCase().includes("palette:")){let f=p.match(/#[0-9A-Fa-f]{6}/g);f&&f.forEach(b=>{d.includes(b.toUpperCase())||d.push(b.toUpperCase())})}return(!l||l===t)&&(l=c.split(`
1118
- Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:l,palette:d.slice(0,10)},i},setSummary(n){t=n,i&&(i={...i,summary:n})},getResult(){return i}}}var Qt="handler_api_key_";var Ni=class{static setKey(t,i,n){try{let r={key:this.encryptKey(i),created:Date.now(),lastUsed:Date.now(),label:n||t},a=`${Qt}${t}`;localStorage.setItem(a,JSON.stringify(r))}catch(r){console.error("[ApiKeyStorage] Failed to store API key:",r)}}static getKey(t){try{let i=`${Qt}${t}`,n=localStorage.getItem(i);if(!n)return null;let r=JSON.parse(n);return r.lastUsed=Date.now(),localStorage.setItem(i,JSON.stringify(r)),this.decryptKey(r.key)}catch(i){return console.error("[ApiKeyStorage] Failed to retrieve API key:",i),null}}static hasKey(t){let i=`${Qt}${t}`;return localStorage.getItem(i)!==null}static removeKey(t){try{let i=`${Qt}${t}`;localStorage.removeItem(i)}catch(i){console.error("[ApiKeyStorage] Failed to remove API key:",i)}}static getStoredServices(){let t=[];try{for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);if(n&&n.startsWith(Qt)){let r=n.substring(Qt.length),a=localStorage.getItem(n);if(a){let s=JSON.parse(a);t.push({service:r,label:s.label,created:s.created,lastUsed:s.lastUsed})}}}}catch(i){console.error("[ApiKeyStorage] Failed to get stored services:",i)}return t.sort((i,n)=>n.lastUsed-i.lastUsed)}static clearAll(){try{let t=[];for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);n&&n.startsWith(Qt)&&t.push(n)}t.forEach(i=>localStorage.removeItem(i))}catch(t){console.error("[ApiKeyStorage] Failed to clear API keys:",t)}}static encryptKey(t){try{let n="handler_preview_salt_2024"+t;return btoa(n)}catch(i){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",i),t}}static decryptKey(t){try{let i=atob(t),n="handler_preview_salt_2024";return i.startsWith(n)?i.substring(n.length):i}catch(i){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",i),t}}},gl=()=>Ni.getKey("gemini"),bl=(e,t)=>Ni.setKey("gemini",e,t),nx=()=>Ni.hasKey("gemini");window.ApiKeyStorage=Ni;window.getGeminiApiKey=gl;window.setGeminiApiKey=bl;window.hasGeminiApiKey=nx;var vl=class{constructor(){this.modal=null;this.options=null;this.analyzer=Ph();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(t){this.options=t,this.currentPrompt=t.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var i,n;(i=this.promptInput)==null||i.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var i;let t=document.createElement("div");t.className="ai-modal",t.innerHTML=`
1139
+ `.trim()}function Fh(){let e=[],t="",i=null;return{async addSources(n){let r=[];for(let a of n){let s=await ux(a),o=px(s),c={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};e.push(c),r.push(c)}return r},getSources(){return e.slice()},async analyze(n,r,a){if(e.length===0)throw new Error("No screenshots to analyze.");let s=fx(r),o=e.map(p=>({base64:p.base64,mimeType:p.mimeType})),c=await ba(n,s,o,{model:a}),l=t,d=[],u=c.split(`
1140
+ `);for(let p of u)if(p.toLowerCase().startsWith("summary:"))l=p.slice(8).trim();else if(p.toLowerCase().includes("palette:")){let f=p.match(/#[0-9A-Fa-f]{6}/g);f&&f.forEach(m=>{d.includes(m.toUpperCase())||d.push(m.toUpperCase())})}return(!l||l===t)&&(l=c.split(`
1141
+ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:l,palette:d.slice(0,10)},i},setSummary(n){t=n,i&&(i={...i,summary:n})},getResult(){return i}}}var Qt="handler_api_key_";var Ni=class{static setKey(t,i,n){try{let r={key:this.encryptKey(i),created:Date.now(),lastUsed:Date.now(),label:n||t},a=`${Qt}${t}`;localStorage.setItem(a,JSON.stringify(r))}catch(r){console.error("[ApiKeyStorage] Failed to store API key:",r)}}static getKey(t){try{let i=`${Qt}${t}`,n=localStorage.getItem(i);if(!n)return null;let r=JSON.parse(n);return r.lastUsed=Date.now(),localStorage.setItem(i,JSON.stringify(r)),this.decryptKey(r.key)}catch(i){return console.error("[ApiKeyStorage] Failed to retrieve API key:",i),null}}static hasKey(t){let i=`${Qt}${t}`;return localStorage.getItem(i)!==null}static removeKey(t){try{let i=`${Qt}${t}`;localStorage.removeItem(i)}catch(i){console.error("[ApiKeyStorage] Failed to remove API key:",i)}}static getStoredServices(){let t=[];try{for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);if(n&&n.startsWith(Qt)){let r=n.substring(Qt.length),a=localStorage.getItem(n);if(a){let s=JSON.parse(a);t.push({service:r,label:s.label,created:s.created,lastUsed:s.lastUsed})}}}}catch(i){console.error("[ApiKeyStorage] Failed to get stored services:",i)}return t.sort((i,n)=>n.lastUsed-i.lastUsed)}static clearAll(){try{let t=[];for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);n&&n.startsWith(Qt)&&t.push(n)}t.forEach(i=>localStorage.removeItem(i))}catch(t){console.error("[ApiKeyStorage] Failed to clear API keys:",t)}}static encryptKey(t){try{let n="handler_preview_salt_2024"+t;return btoa(n)}catch(i){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",i),t}}static decryptKey(t){try{let i=atob(t),n="handler_preview_salt_2024";return i.startsWith(n)?i.substring(n.length):i}catch(i){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",i),t}}},bl=()=>Ni.getKey("gemini"),vl=(e,t)=>Ni.setKey("gemini",e,t),hx=()=>Ni.hasKey("gemini");window.ApiKeyStorage=Ni;window.getGeminiApiKey=bl;window.setGeminiApiKey=vl;window.hasGeminiApiKey=hx;var xl=class{constructor(){this.modal=null;this.options=null;this.analyzer=Fh();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(t){this.options=t,this.currentPrompt=t.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var i,n;(i=this.promptInput)==null||i.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var i;let t=document.createElement("div");t.className="ai-modal",t.innerHTML=`
1119
1142
  <div class="ai-modal-card">
1120
1143
  <div class="ai-modal-header">
1121
1144
  <div class="ai-modal-actions">
@@ -1196,12 +1219,12 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:l,palette:d.slice(0
1196
1219
  </div>
1197
1220
  `,this.modal=t,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var n;if(!this.modal)return;this.promptInput=this.modal.querySelector(".ai-textarea"),this.generateBtn=this.modal.querySelector('[data-action="generate"]'),this.loadingEl=this.modal.querySelector("[data-loading]"),this.galleryEl=this.modal.querySelector("[data-gallery]"),this.previewEl=this.modal.querySelector("[data-preview]"),(n=this.promptInput)==null||n.addEventListener("input",()=>{var r;this.currentPrompt=((r=this.promptInput)==null?void 0:r.value)||"",this.updateGenerateButton()});let t=this.modal.querySelector('[data-strength="creativity"]'),i=this.modal.querySelector(".ai-strength-value");t==null||t.addEventListener("input",()=>{i.textContent=t.value}),this.modal.addEventListener("click",r=>{var o;let a=r.target;switch(a.dataset.action||((o=a.closest("[data-action]"))==null?void 0:o.getAttribute("data-action"))){case"generate":this.generateImage();break;case"apply":this.applySelectedImage();break;case"gallery":this.toggleGallery();break;case"close":case"cancel":this.close();break}}),this.modal.addEventListener("click",r=>{let a=r.target;if(a.classList.contains("ai-gallery-item")||a.closest(".ai-gallery-item")){let s=a.closest(".ai-gallery-item"),o=parseInt(s.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()}),this.updateGenerateButton()}updateGenerateButton(){if(!this.generateBtn)return;let t=this.currentPrompt.trim().length>0;this.generateBtn.disabled=!t||this.isGenerating}async updatePromptFromDna(){var i;let t=(i=this.modal)==null?void 0:i.querySelector("#ai-use-dna");if(t!=null&&t.checked)try{let n=this.analyzer.getResult();if(n!=null&&n.summary&&this.promptInput){let r=`${this.currentPrompt}
1198
1221
 
1199
- Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var t,i,n,r;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(t=this.loadingEl)==null||t.classList.remove("hidden"),(i=this.previewEl)==null||i.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let l=await ha(this.options.currentValue);l&&(s=[{base64:l.base64,mimeType:l.mimeType}])}catch(l){console.warn("[AiEditorModal] Failed to load current image:",l)}let o=await Fi(a,this.currentPrompt,s,{aspectRatio:"1:1"}),c=await Bi(o);this.generatedImages.push(c||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(r=this.previewEl)==null||r.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let t=this.galleryEl.querySelector("[data-gallery-grid]");t&&(t.innerHTML=this.generatedImages.map((i,n)=>`
1222
+ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var t,i,n,r;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(t=this.loadingEl)==null||t.classList.remove("hidden"),(i=this.previewEl)==null||i.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let l=await ma(this.options.currentValue);l&&(s=[{base64:l.base64,mimeType:l.mimeType}])}catch(l){console.warn("[AiEditorModal] Failed to load current image:",l)}let o=await Fi(a,this.currentPrompt,s,{aspectRatio:"1:1"}),c=await Bi(o);this.generatedImages.push(c||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(r=this.previewEl)==null||r.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let t=this.galleryEl.querySelector("[data-gallery-grid]");t&&(t.innerHTML=this.generatedImages.map((i,n)=>`
1200
1223
  <div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
1201
1224
  <img class="ai-gallery-thumb" src="${i}" alt="Generated ${n+1}" />
1202
1225
  <div class="ai-gallery-label">#${n+1}</div>
1203
1226
  </div>
1204
- `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let t=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${t}" alt="Selected image" />`}selectImage(t){t<0||t>=this.generatedImages.length||(this.selectedImageIndex=t,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var i;let t=(i=this.modal)==null?void 0:i.querySelector('[data-action="apply"]');t&&(t.disabled=this.selectedImageIndex<0)}applySelectedImage(){var i;if(this.selectedImageIndex<0||!((i=this.options)!=null&&i.onApply))return;let t=this.generatedImages[this.selectedImageIndex];this.options.onApply(t),this.close()}getApiKey(){let t=gl();if(t)return t;try{let i=this.analyzer.getResult();if(i&&i.apiKey)return bl(i.apiKey,"From Brand DNA"),i.apiKey}catch(i){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",i)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},ml=null;window.__openAiEditor=function(e,t,i,n){ml||(ml=new vl),ml.open({objectId:e,initialPrompt:t,currentValue:i,path:n==null?void 0:n.path,onApply:r=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(e,n.path,r);else{let s=window.getEditableObjectConfig,o=s==null?void 0:s(e);if(o){let c=n.path.split("."),l=o;for(let d=0;d<c.length-1;d++)l[c[d]]||(l[c[d]]={}),l=l[c[d]];l[c[c.length-1]]=r}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};var yl=class{constructor(){this.modal=null;this.options=null}open(t){this.options=t,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:t,assetType:i,objectId:n}=this.options,r=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1227
+ `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let t=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${t}" alt="Selected image" />`}selectImage(t){t<0||t>=this.generatedImages.length||(this.selectedImageIndex=t,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var i;let t=(i=this.modal)==null?void 0:i.querySelector('[data-action="apply"]');t&&(t.disabled=this.selectedImageIndex<0)}applySelectedImage(){var i;if(this.selectedImageIndex<0||!((i=this.options)!=null&&i.onApply))return;let t=this.generatedImages[this.selectedImageIndex];this.options.onApply(t),this.close()}getApiKey(){let t=bl();if(t)return t;try{let i=this.analyzer.getResult();if(i&&i.apiKey)return vl(i.apiKey,"From Brand DNA"),i.apiKey}catch(i){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",i)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},yl=null;window.__openAiEditor=function(e,t,i,n){yl||(yl=new xl),yl.open({objectId:e,initialPrompt:t,currentValue:i,path:n==null?void 0:n.path,onApply:r=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(e,n.path,r);else{let s=window.getEditableObjectConfig,o=s==null?void 0:s(e);if(o){let c=n.path.split("."),l=o;for(let d=0;d<c.length-1;d++)l[c[d]]||(l[c[d]]={}),l=l[c[d]];l[c[c.length-1]]=r}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};var wl=class{constructor(){this.modal=null;this.options=null}open(t){this.options=t,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:t,assetType:i,objectId:n}=this.options,r=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1205
1228
  <div class="asset-preview-card">
1206
1229
  <div class="asset-preview-header">
1207
1230
  <div class="asset-preview-title">${r}</div>
@@ -1228,7 +1251,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1228
1251
  <source src="${r}" type="audio/wav">
1229
1252
  Your browser does not support the audio element.
1230
1253
  </audio>
1231
- `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${t}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${i} assets</div>`}}resolveAssetUrl(t){return t.startsWith("data:")||t.startsWith("blob:")||t.startsWith("/")?t:`/raw/${t}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let r=n.target;(r.dataset.action==="close"||r===this.modal)&&this.close()});let t=this.modal.querySelector('[data-action="change"]');t&&t.addEventListener("click",()=>{this.openAssetEditor()});let i=this.modal.querySelector('[data-action="edit"]');i&&i.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&import("./AssetEditorModal-DBAGQINC.js").then(({AssetEditorModal:t})=>{new t().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var r;(r=this.options)!=null&&r.onChange&&this.options.onChange(n),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let t=window.__openAiEditor;typeof t=="function"&&t(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(e){new yl().open(e)};var xl=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(t){this.options=t,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let t=document.createElement("div");t.className="asset-crop-modal",t.innerHTML=`
1254
+ `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${t}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${i} assets</div>`}}resolveAssetUrl(t){return t.startsWith("data:")||t.startsWith("blob:")||t.startsWith("/")?t:`/raw/${t}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let r=n.target;(r.dataset.action==="close"||r===this.modal)&&this.close()});let t=this.modal.querySelector('[data-action="change"]');t&&t.addEventListener("click",()=>{this.openAssetEditor()});let i=this.modal.querySelector('[data-action="edit"]');i&&i.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&import("./AssetEditorModal-DBAGQINC.js").then(({AssetEditorModal:t})=>{new t().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var r;(r=this.options)!=null&&r.onChange&&this.options.onChange(n),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let t=window.__openAiEditor;typeof t=="function"&&t(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(e){new wl().open(e)};var _l=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(t){this.options=t,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let t=document.createElement("div");t.className="asset-crop-modal",t.innerHTML=`
1232
1255
  <div class="asset-crop-card">
1233
1256
  <div class="asset-crop-header">
1234
1257
  <div>
@@ -1279,7 +1302,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1279
1302
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
1280
1303
  </div>
1281
1304
  </div>
1282
- `,this.modal=t,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let t=this.image.width/this.image.height,i=this.canvas.width/this.canvas.height;t>i?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*i,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/i,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(t){if(!this.image)return;let i=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,r=this.cropY+this.cropHeight/2;t>i?(this.cropWidth=Math.min(this.image.width,this.cropHeight*t),this.cropHeight=this.cropWidth/t):(this.cropHeight=Math.min(this.image.height,this.cropWidth/t),this.cropWidth=this.cropHeight*t),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,r-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let t=this.canvas.width/this.cropWidth,i=this.canvas.height/this.cropHeight;this.scale=Math.min(t,i)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let t=this.panX,i=this.panY,n=this.cropWidth*this.scale,r=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(t,i,n,r),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(t,i,n,r),this.ctx.fillStyle="#ffffff";let a=8;[[t,i],[t+n-a,i],[t,i+r-a],[t+n-a,i+r-a]].forEach(([o,c])=>{var l;(l=this.ctx)==null||l.fillRect(o,c,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let t=this.modal.querySelector(".asset-crop-preview-canvas");if(!t)return;let i=t.getContext("2d");if(!i)return;let n=150;t.width=n,t.height=n;let r=n/this.cropWidth,a=n/this.cropHeight,s=Math.min(r,a),o=this.cropWidth*s,c=this.cropHeight*s,l=(n-o)/2,d=(n-c)/2;i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,l,d,o,c)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let t=this.modal.querySelector(".asset-crop-zoom-slider");t==null||t.addEventListener("input",n=>{let r=parseFloat(n.target.value);this.setZoom(r)});let i=this.modal.querySelector(".asset-crop-aspect-select");i==null||i.addEventListener("change",n=>{let r=n.target.value;this.setAspectRatio(r)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(t){this.isDragging=!0,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(t){if(!this.isDragging)return;let i=t.clientX-this.dragStartX,n=t.clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(t){t.preventDefault();let i=t.deltaY>0?.9:1.1;this.setZoom(this.scale*i)}handleTouchStart(t){t.touches.length===1&&(this.isDragging=!0,this.dragStartX=t.touches[0].clientX,this.dragStartY=t.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(t){if(!this.isDragging||t.touches.length!==1)return;t.preventDefault();let i=t.touches[0].clientX-this.dragStartX,n=t.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(t){this.scale=Math.max(.1,Math.min(3,t)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(t){let i;switch(t){case"1:1":i=1;break;case"4:3":i=4/3;break;case"16:9":i=16/9;break;case"3:2":i=3/2;break;default:i=void 0}i&&this.applyAspectRatio(i),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let t=this.modal.querySelector(".asset-crop-zoom-value"),i=this.modal.querySelector(".asset-crop-zoom-slider");t&&(t.textContent=`${this.scale.toFixed(1)}x`),i&&(i.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let t=this.cropWidth*this.scale,i=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-t,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-i,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var r;if(!this.image||!((r=this.options)!=null&&r.onCrop))return;let t=document.createElement("canvas"),i=t.getContext("2d");if(!i)return;t.width=this.cropWidth,t.height=this.cropHeight,i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=t.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let t=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,t!=null&&t.onCancel&&t.onCancel()}};window.openAssetCrop=function(e){new xl().open(e)};var wl=class{constructor(t={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[ci("playable-portrait"),ci("iphone-14"),ci("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.onWindowResize=t=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=t=>{if(!this.frameDragActive)return;let i=t.clientX-this.frameDragStartX,n=t.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+i,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd))};this.options=t,this.currentPreset=ci(t.defaultDevice||ns.id),this.debugPanel=new ka,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(t=document.body){t.innerHTML="",t.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}getGameContainer(){return this.gameContainer}getScreen(){let t=this.getEffectivePreset();return{width:t.width,height:t.height}}getEffectivePreset(){var t;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((t=this.currentPreset.ratio)==null?void 0:t.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(t,i={}){var r,a;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ci(t),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),i.suppressCallback||(a=(r=this.options).onDeviceChange)==null||a.call(r,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var i;let t=document.createElement("div");return t.className="preview-shell",t.innerHTML=`
1305
+ `,this.modal=t,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let t=this.image.width/this.image.height,i=this.canvas.width/this.canvas.height;t>i?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*i,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/i,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(t){if(!this.image)return;let i=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,r=this.cropY+this.cropHeight/2;t>i?(this.cropWidth=Math.min(this.image.width,this.cropHeight*t),this.cropHeight=this.cropWidth/t):(this.cropHeight=Math.min(this.image.height,this.cropWidth/t),this.cropWidth=this.cropHeight*t),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,r-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let t=this.canvas.width/this.cropWidth,i=this.canvas.height/this.cropHeight;this.scale=Math.min(t,i)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let t=this.panX,i=this.panY,n=this.cropWidth*this.scale,r=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(t,i,n,r),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(t,i,n,r),this.ctx.fillStyle="#ffffff";let a=8;[[t,i],[t+n-a,i],[t,i+r-a],[t+n-a,i+r-a]].forEach(([o,c])=>{var l;(l=this.ctx)==null||l.fillRect(o,c,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let t=this.modal.querySelector(".asset-crop-preview-canvas");if(!t)return;let i=t.getContext("2d");if(!i)return;let n=150;t.width=n,t.height=n;let r=n/this.cropWidth,a=n/this.cropHeight,s=Math.min(r,a),o=this.cropWidth*s,c=this.cropHeight*s,l=(n-o)/2,d=(n-c)/2;i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,l,d,o,c)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let t=this.modal.querySelector(".asset-crop-zoom-slider");t==null||t.addEventListener("input",n=>{let r=parseFloat(n.target.value);this.setZoom(r)});let i=this.modal.querySelector(".asset-crop-aspect-select");i==null||i.addEventListener("change",n=>{let r=n.target.value;this.setAspectRatio(r)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(t){this.isDragging=!0,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(t){if(!this.isDragging)return;let i=t.clientX-this.dragStartX,n=t.clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(t){t.preventDefault();let i=t.deltaY>0?.9:1.1;this.setZoom(this.scale*i)}handleTouchStart(t){t.touches.length===1&&(this.isDragging=!0,this.dragStartX=t.touches[0].clientX,this.dragStartY=t.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(t){if(!this.isDragging||t.touches.length!==1)return;t.preventDefault();let i=t.touches[0].clientX-this.dragStartX,n=t.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(t){this.scale=Math.max(.1,Math.min(3,t)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(t){let i;switch(t){case"1:1":i=1;break;case"4:3":i=4/3;break;case"16:9":i=16/9;break;case"3:2":i=3/2;break;default:i=void 0}i&&this.applyAspectRatio(i),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let t=this.modal.querySelector(".asset-crop-zoom-value"),i=this.modal.querySelector(".asset-crop-zoom-slider");t&&(t.textContent=`${this.scale.toFixed(1)}x`),i&&(i.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let t=this.cropWidth*this.scale,i=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-t,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-i,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var r;if(!this.image||!((r=this.options)!=null&&r.onCrop))return;let t=document.createElement("canvas"),i=t.getContext("2d");if(!i)return;t.width=this.cropWidth,t.height=this.cropHeight,i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=t.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let t=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,t!=null&&t.onCancel&&t.onCancel()}};window.openAssetCrop=function(e){new _l().open(e)};var El=class{constructor(t={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[ci("playable-portrait"),ci("iphone-14"),ci("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.onWindowResize=t=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=t=>{if(!this.frameDragActive)return;let i=t.clientX-this.frameDragStartX,n=t.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+i,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd))};this.options=t,this.currentPreset=ci(t.defaultDevice||as.id),this.debugPanel=new La,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(t=document.body){t.innerHTML="",t.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}getGameContainer(){return this.gameContainer}getScreen(){let t=this.getEffectivePreset();return{width:t.width,height:t.height}}getEffectivePreset(){var t;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((t=this.currentPreset.ratio)==null?void 0:t.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(t,i={}){var r,a;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ci(t),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),i.suppressCallback||(a=(r=this.options).onDeviceChange)==null||a.call(r,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var i;let t=document.createElement("div");return t.className="preview-shell",t.innerHTML=`
1283
1306
  <div class="preview-toolbar">
1284
1307
  <div class="preview-toolbar-left">
1285
1308
  <span class="preview-logo">PREVIEWER</span>
@@ -1288,7 +1311,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1288
1311
  <div class="preview-toolbar-center">
1289
1312
  <div class="device-selector-wrapper">
1290
1313
  <select class="device-dropdown" id="device-select">
1291
- ${Mc.map(n=>`
1314
+ ${Hc.map(n=>`
1292
1315
  <optgroup label="${n.label}">
1293
1316
  ${n.devices.map(r=>`
1294
1317
  <option value="${r.id}" ${r.id===this.currentPreset.id?"selected":""}>
@@ -1394,7 +1417,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1394
1417
  <div class="console-messages" id="console-messages"></div>
1395
1418
  </div>
1396
1419
  </div>
1397
- `,this.setupEventListeners(t),t}setupEventListeners(t){var r,a,s,o,c,l,d;let i=t.querySelector("#device-select");i==null||i.addEventListener("change",u=>{if(this.viewMode==="compare")return;let p=u.target.value;this.setDevice(p)}),Array.from(t.querySelectorAll("[data-view-toggle]")).forEach(u=>{u.addEventListener("click",()=>{let p=u.dataset.viewToggle;p&&this.setViewMode(p)})}),(r=t.querySelector("#rotate-btn"))==null||r.addEventListener("click",()=>this.toggleRotation()),(a=t.querySelector("#zoom-in-btn"))==null||a.addEventListener("click",()=>this.adjustUserZoom(.1)),(s=t.querySelector("#zoom-out-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=t.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(c=t.querySelector("#console-toggle"))==null||c.addEventListener("click",()=>this.toggleConsole()),(l=t.querySelector("#console-close"))==null||l.addEventListener("click",()=>this.toggleConsole(!1)),(d=t.querySelector("#console-clear"))==null||d.addEventListener("click",()=>this.clearConsole())}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"0 20px 50px rgba(0,0,0,0.5)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let t=this.getEffectivePreset(),i=`${t.width}px`,n=`${t.height}px`;this.deviceFrame.style.width=i,this.deviceFrame.style.height=n,this.gameContainer.style.width=i,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=i,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=i,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(t.width),this.gameContainer.dataset.screenHeight=String(t.height),this.container.style.setProperty("--preview-screen-width",String(t.width)),this.container.style.setProperty("--preview-screen-height",String(t.height))}fitToScreen(t){if(!this.previewContainer)return;let i=this.getEffectivePreset(),n=this.getFitBounds(),r=Math.max(0,n.width),a=Math.max(0,n.height);if(r<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=r/i.width,o=a/i.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let c=.6;this.userScaleMultiplier=c/this.autoScale}t!=null&&t.keepVisibleScale&&t.keepVisibleScale>0&&(this.userScaleMultiplier=t.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),this.emitScreenChange()}applyTransform(){let t=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${t})`;let i=this.container.querySelector("#zoom-label");i&&(i.textContent=`${Math.round(t*100)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",t=>{this.gameContainer.contains(t.target)||t.button===0&&(t.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=t.clientX,this.frameDragStartY=t.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}adjustUserZoom(t){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+t)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var i,n;if(this.viewMode==="compare")return;let t=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:t}),(n=(i=this.options).onDeviceChange)==null||n.call(i,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let t=this.getEffectivePreset(),i={width:t.width,height:t.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:t.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:i})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(t){var n;let i=new WeakSet;try{return JSON.stringify(t,(r,a)=>{if(typeof a=="object"&&a!==null){if(i.has(a))return"[Circular]";i.add(a)}return a},2)}catch{try{if(t&&((n=t.constructor)!=null&&n.name))return`[object ${t.constructor.name}]`}catch{}return String(t)}}setupConsoleInterceptor(){let t=console.log.bind(console),i=console.warn.bind(console),n=console.error.bind(console),r=console.info.bind(console),a=(s,...o)=>{let c=o.map(d=>typeof d=="object"?this.safeStringify(d):String(d)).join(" ");this.consoleMessages.push({type:s,message:c,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let l=this.container.querySelector("#console-badge");if(l){let d=this.consoleMessages.filter(u=>u.type==="error").length;l.textContent=d>0?`${d}!`:"0",l.classList.toggle("has-errors",d>0)}};console.log=(...s)=>{t(...s),a("log",...s)},console.warn=(...s)=>{i(...s),a("warn",...s)},console.error=(...s)=>{n(...s),a("error",...s)},console.info=(...s)=>{r(...s),a("info",...s)}}appendConsoleMessage(t){let i=this.container.querySelector("#console-messages");if(!i)return;let n=document.createElement("div");n.className=`console-msg type-${t.type}`;let r=t.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(r)}</span> <pre>${this.escapeHtml(t.message)}</pre>`,i.appendChild(n),i.scrollTop=i.scrollHeight}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(t){var i;this.isConsoleOpen=t!=null?t:!this.isConsoleOpen,(i=this.consolePanel)==null||i.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let t=this.container.querySelector("#console-messages");t&&(t.innerHTML="");let i=this.container.querySelector("#console-badge");i&&(i.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(i=>{let n=i.dataset.viewport;if(!n)return;let r=this.comparePresets.find(u=>u.id===n);if(!r)return;let a=i.querySelector("[data-compare-slot]"),s=i.querySelector("[data-compare-ghost]"),o=i.querySelector("[data-compare-wrapper]"),c=i.querySelector("[data-compare-frame]"),l=i.querySelector("[data-compare-snapshot]"),d=i.querySelector("[data-compare-focus]");!a||!s||!o||!c||(i.addEventListener("click",u=>{let p=u.target;if(p!=null&&p.closest("[data-compare-focus]")){u.preventDefault(),this.activateCompareViewport(n);return}i.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:r,root:i,slot:a,ghost:s,wrapper:o,frame:c,canvas:l,focus:d}))})}setViewMode(t){if(this.viewMode===t)return;this.viewMode=t,this.container.classList.toggle("compare-mode",t==="compare"),this.singleStage.classList.toggle("hidden",t!=="single"),this.compareStage.classList.toggle("hidden",t!=="compare");let i=this.container.querySelector("#device-select");i&&(i.disabled=t==="compare");let n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=t==="compare"),this.updateViewToggleUI(),t==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(i=>{i.classList.toggle("active",i.dataset.viewToggle===this.viewMode)})}activateCompareViewport(t){var a,s;let i=this.compareViewports.get(t);if(!i)return;let n=this.autoScale*this.userScaleMultiplier,r=this.activeCompareId;r&&r!==t&&this.captureCompareSnapshot(r),this.activeCompareId=t,this.currentPreset=i.preset,this.isLandscape=!1,i.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,c)=>{o.root.classList.toggle("is-active",c===t),o.ghost.classList.toggle("hidden",c===t),o.focus&&(o.focus.textContent=c===t?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(t=>{let i=t.preset,n=`${i.width}px`,r=`${i.height}px`;t.frame.style.width=n,t.frame.style.height=r,t.canvas&&(t.canvas.width=i.width,t.canvas.height=i.height)})}fitCompareGhosts(){this.compareViewports.forEach(t=>{let i=t.root.querySelector(".compare-body");if(!i)return;let n=Math.max(0,i.clientWidth-24),r=Math.max(0,i.clientHeight-24);if(n<=0||r<=0)return;let a=n/t.preset.width,s=r/t.preset.height,o=Math.max(.01,Math.min(a,s));t.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(t){let i=this.compareViewports.get(t);if(!(i!=null&&i.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let r=i.canvas.getContext("2d");if(!r)return;let a=i.canvas.width,s=i.canvas.height,o=Math.min(a/n.width,s/n.height),c=n.width*o,l=n.height*o,d=(a-c)/2,u=(s-l)/2;r.clearRect(0,0,a,s),r.drawImage(n,d,u,c,l)}refreshCompareSnapshots(){this.compareViewports.forEach((t,i)=>{i!==this.activeCompareId&&this.captureCompareSnapshot(i)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40};let t=this.compareViewports.get(this.activeCompareId),i=t==null?void 0:t.root.querySelector(".compare-body");return i?{width:i.clientWidth-24,height:i.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(t){let i=this.container.querySelector(t);if(!i)throw new Error(`PreviewShell missing element: ${t}`);return i}};function Ih(e={}){let t=new wl(e);return typeof window!="undefined"&&(window.__previewShell=t),t.mount(),t}import{Sprite as rx,Container as Mh}from"pixi.js";var ax=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",_l=ax;if(typeof window!="undefined")try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);t!=null&&t.buildMode&&(_l=t.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${_l}`))}}catch{}var Mt=class{static async create(t,i,n){var c,l,d,u,p,f,b;console.log(`[ObjectFactory] create() called for: ${t}, __BUILD_MODE__: ${_l}`);let r=(c=i==null?void 0:i.render)==null?void 0:c.asset;if(!r){console.log(`[ObjectFactory] No asset definition for: ${t}, returning empty container`);let h=new Mh;return this.applyTransform(h,i==null?void 0:i.transform),h}let a=(l=i==null?void 0:i.identity)==null?void 0:l.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${t}, configId: ${a}, type: ${r.type}, path: ${r.path}`);let s=await Wa.load(t,r,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${t}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(r.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",t),o=new rx(s),console.log("[ObjectFactory] Created object:",o,"type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name),this.applyTransform(o,i==null?void 0:i.transform);else if(r.type==="json")if(console.log("[ObjectFactory] JSON asset for",t,"rawAsset type:",(p=s==null?void 0:s.constructor)==null?void 0:p.name,s),s&&(((f=s.constructor)==null?void 0:f.name)==="Container"||s instanceof Mh)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[r.path,`/assets/${r.path}`,`assets/${r.path}`,`../assets/${r.path}`],g=!1;for(let m of h)try{let v=await fetch(m);if(v.ok){o=await v.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",m,"type:",(b=o==null?void 0:o.constructor)==null?void 0:b.name),g=!0;break}}catch{continue}g||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,i==null?void 0:i.transform);return o}static applyTransform(t,i){var n,r,a,s;!i||!t||(i.position&&("x"in t&&"y"in t?(t.x=(n=i.position.x)!=null?n:0,t.y=(r=i.position.y)!=null?r:0):"position"in t&&t.position&&t.position.set((a=i.position.x)!=null?a:0,(s=i.position.y)!=null?s:0)),i.scale!==void 0&&"scale"in t&&t.scale&&(typeof t.scale=="object"&&"set"in t.scale?t.scale.set(i.scale):t.scale=i.scale),i.rotation!==void 0&&"rotation"in t&&(t.rotation=i.rotation),i.anchor&&"anchor"in t&&t.anchor&&Array.isArray(i.anchor)&&("set"in t.anchor?t.anchor.set(i.anchor[0],i.anchor[1]):(t.anchor.x=i.anchor[0],t.anchor.y=i.anchor[1])))}};function El(e){try{if(e&&typeof e.keys=="function")return Array.from(e.keys())}catch{}return[]}function Oh(e){var t;return e?((t=e.getDisplayObject)==null?void 0:t.call(e))||e.pixiObject||e:null}function sx(e,t){if(!e||!(t!=null&&t.interaction))return;let i=t.interaction,n=i.enabled!==!1&&(i.draggable===!0||i.clickable===!0);e.eventMode=n?"static":"none",e.interactive=n,n&&(e.cursor=i.draggable?"move":"pointer")}function Dh(e,t){var c,l,d,u,p;if(!e||!t)return;let i=t.transform||{};sx(e,t);let n=i.position||{},r=i.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof r.x=="number"?r.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof r.y=="number"?r.y:0);(c=e.position)!=null&&c.set?e.position.set(a,s):(typeof e.x=="number"&&(e.x=a),typeof e.y=="number"&&(e.y=s)),typeof i.scale=="number"&&((l=e.scale)!=null&&l.set?e.scale.set(i.scale):e.scale&&(e.scale.x=i.scale,e.scale.y=i.scale));let o=(u=i.anchor)!=null?u:(d=t.render)==null?void 0:d.anchor;o&&((p=e.anchor)!=null&&p.set)&&typeof o.x=="number"&&typeof o.y=="number"&&e.anchor.set(o.x,o.y)}function zh(e){if(typeof window=="undefined")return;let t=e==null?void 0:e.objects,i=El(t),n=a=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return a;let o=window.__HANDLER_SCREEN_INDEX,c=o==null?void 0:o.instanceToScreen;return c?a.filter(l=>c[l]===s):a}catch{return a}};window.__editableObjectConfigs=t;let r=new Map;i.forEach(a=>r.set(a,[a])),window.__editableObjectInstances=r,window.refreshEditableConfigIndex=()=>zh(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(El((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return El((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var d,u,p,f,b;let s=(f=(p=(u=(d=window.__editableConfig)==null?void 0:d.objects)==null?void 0:u.get)==null?void 0:p.call(u,a))!=null?f:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let c=window.__HANDLER_SCREEN_INDEX,l=(b=c==null?void 0:c.instanceToScreen)==null?void 0:b[a];return l&&l===o?s:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function ox(){if(typeof window=="undefined")return;let e=i=>{let n=String(i||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},t=async(i,n)=>{var a,s,o;let r=e(n);if(r)try{let[{Assets:c},{AssetTextures:l}]=await Promise.all([import("pixi.js"),import("./AssetTextures-CWUQXU5Q.js")]),d=Date.now(),u=/^(data:|blob:)/.test(r)?r:r+(r.includes("?")?`&t=${d}`:`?t=${d}`),p=await c.load(u);if(!p)return;l[i]=p;let f=window.CustomAssets;(a=f==null?void 0:f[i])!=null&&a.texture&&(f[i].texture=p);let b=window.gameObjectManager,h=(s=b==null?void 0:b.get)==null?void 0:s.call(b,i);if(h){let g=((o=h.getDisplayObject)==null?void 0:o.call(h))||h.pixiObject||h.pixi||h;if(g!=null&&g.texture)g.texture=p;else if(g!=null&&g.children){let m=g.children.find(v=>v==null?void 0:v.texture);m!=null&&m.texture&&(m.texture=p)}}}catch(c){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",i,c)}};window.applyLiveEditOverrides=i=>{try{let n=Va();Array.isArray(n)&&n.length&&(window.__editableConfig=i,ar(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=i=>{try{let n=Va();Array.isArray(n)&&n.length&&(window.__editableConfig=i,ar(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=i=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let r=[];if(i.runtime)for(let[a,s]of Object.entries(i.runtime))r.push({path:`runtime.${a}`,value:s});if(i.assets)for(let[a,s]of Object.entries(i.assets))r.push({path:`assets.${a}`,value:s}),typeof s=="string"&&t(a,s);if(i.splash)for(let[a,s]of Object.entries(i.splash))r.push({path:`splash.${a}`,value:s});if(i.loading)for(let[a,s]of Object.entries(i.loading))r.push({path:`loading.${a}`,value:s});if(i.start)for(let[a,s]of Object.entries(i.start))r.push({path:`start.${a}`,value:s});r.length&&ar(r,{silent:!0,persist:!0,emitEvent:!0})}}function Sl(e){let{getConfig:t,gameObjectManager:i,onObjectConfigApplied:n}=e;i&&(i.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=i.get(a),c=o==null?void 0:o.pixiObject,l=c==null?void 0:c.parent,d=l==null?void 0:l.children.indexOf(c);o?i.remove(a):c&&c.destroy();let u=window.gameApp,p=await Mt.create(a,s,u);l&&(d!==void 0&&d!==-1?l.addChildAt(p,d):l.addChild(p));let f=i.create(a,p);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),f}),typeof window!="undefined"&&(ox(),window.applyEditableObjectConfig=(a,s)=>{var o,c,l;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let u=(c=i==null?void 0:i.get)==null?void 0:c.call(i,a);if(console.log("[LIVE-EDIT] gameObject found?",!!u),u&&(console.log("[LIVE-EDIT] gameObject type:",(l=u.constructor)==null?void 0:l.name),console.log("[LIVE-EDIT] has updateConfig?",typeof u.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof u.onConfigUpdate=="function")),u&&typeof u.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),u.updateConfig(s);else if(u&&typeof u.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),u.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let p=Oh(u);Dh(p,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let r={async applyObjectConfig(a,s){var d,u;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=t();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let c=(u=i==null?void 0:i.get)==null?void 0:u.call(i,a);if(console.log("[BRIDGE] gameObject found?",!!c),c&&(console.log("[BRIDGE] has updateConfig?",typeof c.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof c.onConfigUpdate=="function")),c&&typeof c.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),c.updateConfig(s);else if(c&&typeof c.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),c.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let p=Oh(c);Dh(p,s)}let l=[a];n==null||n(a,s,l)},rebuildIndexes(){let a=t();typeof window!="undefined"&&(window.__editableConfig=a,zh(a))}};return r.rebuildIndexes(),r}import lx from"lottie-web";Tl(Pc);typeof window!="undefined"&&!window.lottie&&(window.lottie=lx);var Hi=null,cx=async()=>{if(!Hi){let e=typeof window!="undefined"?window.INLINE_ASSETS:null,t=(e==null?void 0:e["handler.config"])||(e==null?void 0:e["handler.config.json"]);if(t)try{if(t.startsWith("data:")){let n=atob(t.split(",")[1]);Hi=JSON.parse(n)}else Hi=JSON.parse(t);return Hi}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}Hi=await(await fetch("./handler.config.json")).json()}return Hi},Ll,Hn,Fh,Ui,Cl,kl;function Z_(e){Ll=e.initGame,Hn=e.CustomAssets,Fh=e.updateScreenState,Ui=e.globalResponsiveMultipliers,Cl=e.layout,kl=e.clearResponsiveElements}var Ta="web_embed",Nn="https://example.com",jh={profile_id:Ta},Ot=null,Ke=null,Al={width:0,height:0},dx=!0,J_=async()=>{var l,d,u,p;document.title="Handler Pixi Game";let e=await cx();jh={...e.ids||{},profile_id:Ta},Nn=e.destination_url||((d=(l=e.export_profiles)==null?void 0:l[Ta])==null?void 0:d.destination_url)||Nn,pt.init({ids:jh,profile:Ta,destinationUrl:Nn});let t=pt.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ke=Ih({onDeviceChange:b=>{console.log(`[PREVIEW] Device switched to ${b.width}x${b.height}, restarting game...`),Bh()},onRefresh:Bh});let f=Ke.getGameContainer();f&&(t=f),window.addEventListener("handler-preview:screen",b=>{var y,x,w,C,k,E,P,M,_,S,L;let h=window.gameApp,g=window.gameObjectManager,{width:m,height:v}=b.detail;if(Al.width=m,Al.height=v,Fh(m,v),!(!h||!h.renderer)){g&&o(h,g);try{h.renderer.resize(m,v);let R=h.view;R&&(R.style.width="100%",R.style.height="100%",R.style.display="block")}catch(R){console.warn("[SCREEN] Error resizing renderer:",R);return}if(i&&g&&Cl)try{let R=(y=window.__mainContainer)!=null?y:h.stage,O=(P=(E=(C=window.__tutorialLabel)!=null?C:(w=(x=g.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:w.call(x))!=null?E:(k=g.get("label_1"))==null?void 0:k.pixiObject)!=null?P:g.get("label_1"),A=g.get("background_1"),z=(L=(S=(_=window.__background)!=null?_:(M=A==null?void 0:A.getDisplayObject)==null?void 0:M.call(A))!=null?S:A==null?void 0:A.pixiObject)!=null?L:A;if(R){let T=R===h.stage;Cl({mainContainer:R,label:O,background:z,backgroundTexture:(z==null?void 0:z.texture)||null,app:h},i,0,Al,g,{skipMainContainerTransform:T})}}catch(R){console.warn("[SCREEN] Error in layout:",R)}}})}let i=await sr("scene.main");window.__editableConfig=i,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=Ka(i),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(p=(u=i.engine.runtime)==null?void 0:u.layout)!=null&&p.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(f=>setTimeout(f,100)),i=await sr("scene.main"));let n=await Ll(t,i,Nn,Ke);Ot=n.app;let r=n.gameObjectManager;window.gameApp=Ot,window.gameObjectManager=r;try{window.__liveEditBridge=Sl({getConfig:()=>window.__editableConfig,gameObjectManager:r,assets:Hn})}catch(f){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",f)}Ke&&Ke.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(Ui.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Ot,r);async function s(){try{let f=async v=>{let y=v.startsWith("/")?v:`/${v}`,x=await fetch(y,{cache:"no-cache"});if(!x.ok)return null;let w=await x.text();try{return JSON.parse(w)}catch{return null}},b=await f("configs/flow/app.flow.json");if(!b||typeof b!="object")return;let h=b.screens;if(!h||typeof h!="object")return;let g={},m={};for(let[v,y]of Object.entries(h)){let x=y==null?void 0:y.source;if(typeof x!="string")continue;let w=await f(x),C=w==null?void 0:w.elements;if(!Array.isArray(C))continue;let k=C.map(E=>E==null?void 0:E.instance_id).filter(E=>typeof E=="string");g[v]=k;for(let E of k)m[E]||(m[E]=v)}window.__HANDLER_APP_FLOW=b,window.__HANDLER_SCREEN_INDEX={screenToInstances:g,instanceToScreen:m},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(f,b){if(dx){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${Ui.scale.toFixed(3)}`),f.stage){let g=function(m,v=0){if(!m||!m.children)return;let y=" ".repeat(v);m.children.forEach((x,w)=>{if(x&&x.zIndex===9999){console.log(`${y}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let C=x.scale.x||1,k=x.scale.y||1;x.__originalScale||(x.__originalScale={x:C,y:k},console.log(`${y}[RESPONSIVE] Stored original scale for child[${w}]: ${C.toFixed(3)}, ${k.toFixed(3)}`));let E=x.__originalScale.x*Ui.scale,P=x.__originalScale.y*Ui.scale;typeof x.scale.set=="function"?x.scale.set(E,P):(x.scale.x=E,x.scale.y=P),console.log(`${y}[RESPONSIVE] Child[${w}] scale: ${C.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),g(x,v+1)}else x&&console.log(`${y}[RESPONSIVE] Child[${w}] has no scale (type: ${x.constructor.name})`)})};var h=g;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),g(f.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function c(f){if(f!==void 0){Ui.scale=f,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${f.toFixed(3)}`);let b=window.gameApp,h=window.gameObjectManager;b&&h?(o(b,h),b.renderer&&(b.renderer.render(b.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!b}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=c,pt.start()},Bh=async()=>{var t,i,n,r;console.log("[PREVIEW] Restarting game in 1 seconds...");let e=(t=window.gameObjectManager)==null?void 0:t.get("character_1");if(e){let a=((i=e.getDisplayObject)==null?void 0:i.call(e))||e;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((r=a.scale.y)!=null?r:1).toFixed(3)}`)}if(Ke){Ke.notifyGameDestroyed();try{kl&&kl()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ke.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Ot){try{Ot.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Ot=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Hn.resetScene=="function"&&Hn.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{sr("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Ka(o)),Ll(a,o,Nn).then(c=>{Ot=c.app,window.gameApp=Ot,window.gameObjectManager=c.gameObjectManager;try{window.__liveEditBridge=Sl({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Hn})}catch(l){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",l)}Ke&&Ke.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{pt.start()}catch{}})})},100)},1e3)}};var Rl="0.3.1",ux=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]),Wh={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},Yh=Math.random().toString(36).slice(2),Gi=null,$i={...Wh},Vh="web_embed",Ol={},$n,Pl=!1,Un=!1,Gn=!1,Kh=!1,Bl=1,Ra=0,Ma=!1,ft=!1,qi="",Wi=Math.floor(window.innerWidth),Yi=Math.floor(window.innerHeight),Dl=Wi>Yi,ht=!1,qn=!1,Nh=!1,Hh=!1,Il=!1,Pa=null,ei=null,zl=!1,jl=!1,La=new Map;function Xh(){if(!ei)return null;let e=Date.now()-ei;return!Number.isFinite(e)||e<0?null:e}function Ml(e){if(zl)return;let t=Xh();t!==null&&(zl=!0,j("session_time",{duration_ms:t,reason:e}))}function Uh(){if(Gi)return Gi;let e=document.createElement("div");return e.id="handler-root",e.setAttribute("data-handler-root","true"),document.body.appendChild(e),Gi=e,e}function Ia(e){switch(e){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return e}}function Zh(e,t){return{event_name:e,ts:Date.now(),session_id:Yh,deployment_id:$i.deployment_id,variant_id:$i.variant_id,export_profile_id:$i.profile_id,instance_id:$i.instance_id||"default",env:Vh==="mraid"?"mraid":"web",attribution:$n,payload:t}}function j(e,t){let i=Ia(e),n=Zh(i,t);Ja(n,!!Ol.analytics),lr(i,n),i!==e&&lr(e,n)}function Wn(){Pa&&(Pa(Wi,Yi),Pa=null)}function Vi(e){Bl=e,j("volume",e)}function Ki(e){e&&(Kh=!0),!Gn&&(Gn=!0,j("pause"),Vi(0))}function Yn(e){!e&&Kh||Gn&&(Gn=!1,j("resume"),Vi(Bl))}function Dt(e,t){Wi=Math.floor(e||window.innerWidth),Yi=Math.floor(t||window.innerHeight),Dl=Wi>Yi,j("resize",{width:Wi,height:Yi})}function px(){if(Ec())try{let e=mraid.getMaxSize();Dt(e.width,e.height);let t=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Yn():Ki()};if(mraid.addEventListener("viewableChange",t),mraid.addEventListener("stateChange",t),mraid.addEventListener("sizeChange",()=>{let i=mraid.getMaxSize();Dt(i.width,i.height)}),mraid.getAudioVolume){let i=mraid.getAudioVolume();Vi(i?1:0)}if(mraid.addEventListener("audioVolumeChange",i=>{i!==null&&Vi(i>0?1:0)}),mraid.addEventListener("error",(i,n)=>{console.warn("mraid error:",i,"action:",n)}),Ma=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Wn();else{let i=()=>{ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Wn()};mraid.addEventListener("ready",i)}}catch(e){console.warn("MRAID hook skipped",e)}}function fx(){if(Sc())try{let e=dapi.getScreenSize();Dt(e.width,e.height),dapi.addEventListener("viewableChange",i=>{i.isViewable?Yn():Ki()}),dapi.addEventListener("adResized",i=>{let n=dapi.getScreenSize();Dt(i.width||n.width,i.height||n.height)});let t=dapi.getAudioVolume();if(Vi(t?1:0),dapi.addEventListener("audioVolumeChange",i=>Vi(i?1:0)),Ma=!0,dapi.isViewable())ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Wn();else{let i=()=>{ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Wn()};dapi.addEventListener("ready",i)}}catch(e){console.warn("DAPI hook skipped",e)}}function $h(){let e=()=>{ht||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Wn(),qn&&(qn=!1,Xe.start()))};window.addEventListener("resize",()=>Dt()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Yn(),e()):Ki()}),document.readyState==="complete"||document.readyState==="interactive"?e():window.addEventListener("load",e),Ma=!0}function hx(){let e=t=>{typeof TouchEvent!="undefined"&&t instanceof TouchEvent&&(Nh=!0),!(Nh&&t instanceof MouseEvent)&&(Ra+=1,jl||(jl=!0,j("first_interaction",{count:Ra})),j("interaction",Ra))};document.addEventListener("mousedown",e),document.addEventListener("touchstart",e)}function qh(e){var n,r,a,s,o,c,l,d,u,p,f,b;let t=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(t==="mraid"&&typeof mraid!="undefined")mraid.open(e||"");else if(t==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(li())(a=(r=window.TJ_API)==null?void 0:r.click)==null||a.call(r);else if(Ac())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(Lc())(l=(c=window.ScPlayableAd)==null?void 0:c.onCTAClick)==null||l.call(c);else if(Tc())try{(u=(d=window.smxTracking)==null?void 0:d.redirect)==null||u.call(d)}catch(h){console.warn("Smadex redirect failed",h)}else if(Cc()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(e||qi||""):e&&window.open(e)}else oi()?(p=window.install)==null||p.call(window):kc()?(f=window.openAppStore)==null||f.call(window):Qa()?(b=parent==null?void 0:parent.postMessage)==null||b.call(parent,"download","*"):e&&window.open(e)}function gx(){let e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",t=i=>{if(!i)return;let n=new Image;n.src=i};if(e==="bigabid"){let i=window.BIGABID_BIDTIMEMACROS;if(!i)return;_e("view",()=>t(i.mraid_viewable)),_e("start",()=>t(i.game_viewable)),_e("engagement",()=>t(i.engagement));let n=()=>t(i.complete);_e("complete",n),or("engagement",r=>{var a;((a=r==null?void 0:r.payload)==null?void 0:a.count)>3&&n()}),_e("cta_click",()=>t(i.click))}else if(e==="inmobi"){let i=window.INMOBI_DSPMACROS;if(!i)return;_e("view",()=>t(i.Ad_Load_Start)),_e("start",()=>t(i.Ad_Viewable)),_e("engagement",()=>t(i.First_Engagement)),_e("complete",()=>t(i.Gameplay_Complete)),_e("cta_click",()=>t(i.DSP_Click)),_e("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>t(i[`Spent_${n}_Seconds`]),n*1e3))})}}function bx(){if(!li())return;let e=window.TJ_API;e&&e.setPlayableAPI&&e.setPlayableAPI({skipAd:()=>{try{Xe.finish()}catch(t){console.warn("Tapjoy skip failed",t)}}})}function Gh(){var t,i,n;let e=window.TJ_API;(t=e==null?void 0:e.objectiveComplete)==null||t.call(e),(i=e==null?void 0:e.playableFinished)==null||i.call(e),(n=e==null?void 0:e.gameplayFinished)==null||n.call(e)}function mx(){oi()&&(window.mintGameStart=()=>{Yn(!0),Dt()},window.mintGameClose=()=>{Ki(!0)})}function vx(){if(!es())return;let e=window.NUC;!e||!e.trigger||(Xe.on("cta_click",()=>{var t,i;return(i=(t=e.trigger).convert)==null?void 0:i.call(t,qi)}),Xe.on("complete",()=>{var t,i;return(i=(t=e.trigger).tryAgain)==null?void 0:i.call(t)}))}var Xe={init(e={},t){var i;if(Vh=e.profile||"web_embed",Ol=e.consent||{},$i={...Wh,...e.ids||{}},Gi=e.rootEl||Gi,$n=void 0,dc((i=e.telemetry)!=null&&i.endpoint?e.telemetry:null),ei=null,zl=!1,jl=!1,La.clear(),qi=e.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),t&&(Pa=t),j("init"),document.body.oncontextmenu=()=>!1,Uh(),xx(Gi),Rc(),px(),fx(),!Ma){if(document.readyState==="complete")$h();else if(!Hh){Hh=!0;let n=()=>{$h(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}hx(),gx(),bx(),mx(),vx(),console.log(`%c @handler/playable-sdk %c v${Rl} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ht&&!ft&&(j("boot"),j("view"),j("ready"),qn&&(qn=!1,Xe.start()),ft=!0),ft=ht},getRoot(){return Uh()},get version(){return Rl},get maxWidth(){return Wi},get maxHeight(){return Yi},get isLandscape(){return Dl},get isReady(){return ft},get isStarted(){return Pl},get isPaused(){return Gn},get isFinished(){return Un},get volume(){return Bl},get interactions(){return Ra},on(e,t){or(Ia(e),t)},off(e,t){Za(Ia(e),t)},start(){var e,t;if(!Pl){if(!ht){qn=!0;return}if(Pl=!0,ei||(ei=Date.now()),j("start"),Dt(),oi())Ki(),(e=window.gameReady)==null||e.call(window);else if(li()){let i=window.TJ_API;(t=i==null?void 0:i.setPlayableBuild)==null||t.call(i,{orientation:Dl?"landscape":"portrait",buildID:Rl})}}},finish(){var e,t;Un||(Un=!0,j("complete"),Ml("complete"),oi()?(e=window.gameEnd)==null||e.call(window):Qa()?(t=parent==null?void 0:parent.postMessage)==null||t.call(parent,"complete","*"):li()&&Gh())},install(e){if(!Un){Un=!0,li()?(Gh(),setTimeout(()=>Xe.install(e),300)):(j("complete"),setTimeout(()=>Xe.install(e),0));return}Il||(Il=!0,setTimeout(()=>Il=!1,500),j("cta_click"),j("conversion"),Ml("cta"),qh(e||qi))},emit(e,t){let i=Ia(e);if(!ux.has(i)&&i!=="resize"&&i!=="volume"&&!i.startsWith("custom."))throw new Error(`Event ${e} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=Zh(i,t);Ja(n,!!Ol.analytics),lr(i,n)},gameStart(){Xe.start()},gameEnd(){Xe.finish()},ctaClick(e,t){j("cta_click",{url:e||qi,manual:!0}),(t==null?void 0:t.open)!==!1&&qh(e||qi)},ctaShow(e){j("cta_show",e)},ctaDismiss(e){j("cta_dismiss",e)},getGameTimeMs(){return Xh()},endSession(e="manual"){Ml(e)},setAttribution(e){$n=e},abTest(e,t){if(!e)throw new Error("abTest requires experimentId");if(!Array.isArray(t)||t.length<2)throw new Error("abTest requires at least 2 variants");let i=Math.abs(yx(`${Yh}:${e}`))%t.length,n=t[i];return $n={...$n||{},experiment_id:e},$i.variant_id=n,j("ab_assign",{experiment_id:e,variant_id:n}),n},levelStart(e,t){ei||(ei=Date.now()),j("level_start",{level_id:e,...t})},levelComplete(e,t){j("level_complete",{level_id:e,...t})},levelFail(e,t){j("level_fail",{level_id:e,...t})},checkpoint(e,t){j("checkpoint",{checkpoint_id:e,...t})},reward(e,t){j("reward",{reward_id:e,...t})},tutorialStart(e,t){j("tutorial_start",{step_id:e,...t})},tutorialComplete(e,t){j("tutorial_complete",{step_id:e,...t})},tutorialSkip(e,t){j("tutorial_skip",{step_id:e,...t})},timerStart(e){e&&La.set(e,Date.now())},timerEnd(e,t="custom",i){if(!e)return;let n=La.get(e);if(!n)return;La.delete(e);let r=Date.now()-n;if(!(!Number.isFinite(r)||r<0)){if(t==="custom"){j("engagement",{action:"timer",key:e,duration_ms:r,...i});return}j(t,{key:e,duration_ms:r,...i})}},fps(e,t){j("fps",{value:e,...t})},memory(e,t){j("memory",{bytes:e,...t})},assetLoadStart(e,t){j("asset_load_start",{asset_id:e,...t})},assetLoadComplete(e,t){j("asset_load_complete",{asset_id:e,...t})},reportError(e,t,i){j("error",{code:e,message:t,...i})},retry(){var e,t,i;if(oi())(e=window.gameRetry)==null||e.call(window);else if(es()){let n=window.NUC;(i=(t=n==null?void 0:n.trigger)==null?void 0:t.tryAgain)==null||i.call(t)}j("engagement",{action:"retry"})},pause(){Ki(!0)},resume(){Yn(!0)},resize(e,t){Dt(e,t)}},pt=Xe;function yx(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t|0}function xx(e){let t=document.createElement("script");t.type="text/javascript",t.textContent=`
1420
+ `,this.setupEventListeners(t),t}setupEventListeners(t){var r,a,s,o,c,l,d;let i=t.querySelector("#device-select");i==null||i.addEventListener("change",u=>{if(this.viewMode==="compare")return;let p=u.target.value;this.setDevice(p)}),Array.from(t.querySelectorAll("[data-view-toggle]")).forEach(u=>{u.addEventListener("click",()=>{let p=u.dataset.viewToggle;p&&this.setViewMode(p)})}),(r=t.querySelector("#rotate-btn"))==null||r.addEventListener("click",()=>this.toggleRotation()),(a=t.querySelector("#zoom-in-btn"))==null||a.addEventListener("click",()=>this.adjustUserZoom(.1)),(s=t.querySelector("#zoom-out-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=t.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(c=t.querySelector("#console-toggle"))==null||c.addEventListener("click",()=>this.toggleConsole()),(l=t.querySelector("#console-close"))==null||l.addEventListener("click",()=>this.toggleConsole(!1)),(d=t.querySelector("#console-clear"))==null||d.addEventListener("click",()=>this.clearConsole())}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"0 20px 50px rgba(0,0,0,0.5)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let t=this.getEffectivePreset(),i=`${t.width}px`,n=`${t.height}px`;this.deviceFrame.style.width=i,this.deviceFrame.style.height=n,this.gameContainer.style.width=i,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=i,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=i,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(t.width),this.gameContainer.dataset.screenHeight=String(t.height),this.container.style.setProperty("--preview-screen-width",String(t.width)),this.container.style.setProperty("--preview-screen-height",String(t.height))}fitToScreen(t){if(!this.previewContainer)return;let i=this.getEffectivePreset(),n=this.getFitBounds(),r=Math.max(0,n.width),a=Math.max(0,n.height);if(r<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=r/i.width,o=a/i.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let c=.6;this.userScaleMultiplier=c/this.autoScale}t!=null&&t.keepVisibleScale&&t.keepVisibleScale>0&&(this.userScaleMultiplier=t.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),this.emitScreenChange()}applyTransform(){let t=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${t})`;let i=this.container.querySelector("#zoom-label");i&&(i.textContent=`${Math.round(t*100)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",t=>{this.gameContainer.contains(t.target)||t.button===0&&(t.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=t.clientX,this.frameDragStartY=t.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}adjustUserZoom(t){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+t)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var i,n;if(this.viewMode==="compare")return;let t=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:t}),(n=(i=this.options).onDeviceChange)==null||n.call(i,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let t=this.getEffectivePreset(),i={width:t.width,height:t.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:t.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:i})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(t){var n;let i=new WeakSet;try{return JSON.stringify(t,(r,a)=>{if(typeof a=="object"&&a!==null){if(i.has(a))return"[Circular]";i.add(a)}return a},2)}catch{try{if(t&&((n=t.constructor)!=null&&n.name))return`[object ${t.constructor.name}]`}catch{}return String(t)}}setupConsoleInterceptor(){let t=console.log.bind(console),i=console.warn.bind(console),n=console.error.bind(console),r=console.info.bind(console),a=(s,...o)=>{let c=o.map(d=>typeof d=="object"?this.safeStringify(d):String(d)).join(" ");this.consoleMessages.push({type:s,message:c,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let l=this.container.querySelector("#console-badge");if(l){let d=this.consoleMessages.filter(u=>u.type==="error").length;l.textContent=d>0?`${d}!`:"0",l.classList.toggle("has-errors",d>0)}};console.log=(...s)=>{t(...s),a("log",...s)},console.warn=(...s)=>{i(...s),a("warn",...s)},console.error=(...s)=>{n(...s),a("error",...s)},console.info=(...s)=>{r(...s),a("info",...s)}}appendConsoleMessage(t){let i=this.container.querySelector("#console-messages");if(!i)return;let n=document.createElement("div");n.className=`console-msg type-${t.type}`;let r=t.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(r)}</span> <pre>${this.escapeHtml(t.message)}</pre>`,i.appendChild(n),i.scrollTop=i.scrollHeight}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(t){var i;this.isConsoleOpen=t!=null?t:!this.isConsoleOpen,(i=this.consolePanel)==null||i.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let t=this.container.querySelector("#console-messages");t&&(t.innerHTML="");let i=this.container.querySelector("#console-badge");i&&(i.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(i=>{let n=i.dataset.viewport;if(!n)return;let r=this.comparePresets.find(u=>u.id===n);if(!r)return;let a=i.querySelector("[data-compare-slot]"),s=i.querySelector("[data-compare-ghost]"),o=i.querySelector("[data-compare-wrapper]"),c=i.querySelector("[data-compare-frame]"),l=i.querySelector("[data-compare-snapshot]"),d=i.querySelector("[data-compare-focus]");!a||!s||!o||!c||(i.addEventListener("click",u=>{let p=u.target;if(p!=null&&p.closest("[data-compare-focus]")){u.preventDefault(),this.activateCompareViewport(n);return}i.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:r,root:i,slot:a,ghost:s,wrapper:o,frame:c,canvas:l,focus:d}))})}setViewMode(t){if(this.viewMode===t)return;this.viewMode=t,this.container.classList.toggle("compare-mode",t==="compare"),this.singleStage.classList.toggle("hidden",t!=="single"),this.compareStage.classList.toggle("hidden",t!=="compare");let i=this.container.querySelector("#device-select");i&&(i.disabled=t==="compare");let n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=t==="compare"),this.updateViewToggleUI(),t==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(i=>{i.classList.toggle("active",i.dataset.viewToggle===this.viewMode)})}activateCompareViewport(t){var a,s;let i=this.compareViewports.get(t);if(!i)return;let n=this.autoScale*this.userScaleMultiplier,r=this.activeCompareId;r&&r!==t&&this.captureCompareSnapshot(r),this.activeCompareId=t,this.currentPreset=i.preset,this.isLandscape=!1,i.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,c)=>{o.root.classList.toggle("is-active",c===t),o.ghost.classList.toggle("hidden",c===t),o.focus&&(o.focus.textContent=c===t?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(t=>{let i=t.preset,n=`${i.width}px`,r=`${i.height}px`;t.frame.style.width=n,t.frame.style.height=r,t.canvas&&(t.canvas.width=i.width,t.canvas.height=i.height)})}fitCompareGhosts(){this.compareViewports.forEach(t=>{let i=t.root.querySelector(".compare-body");if(!i)return;let n=Math.max(0,i.clientWidth-24),r=Math.max(0,i.clientHeight-24);if(n<=0||r<=0)return;let a=n/t.preset.width,s=r/t.preset.height,o=Math.max(.01,Math.min(a,s));t.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(t){let i=this.compareViewports.get(t);if(!(i!=null&&i.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let r=i.canvas.getContext("2d");if(!r)return;let a=i.canvas.width,s=i.canvas.height,o=Math.min(a/n.width,s/n.height),c=n.width*o,l=n.height*o,d=(a-c)/2,u=(s-l)/2;r.clearRect(0,0,a,s),r.drawImage(n,d,u,c,l)}refreshCompareSnapshots(){this.compareViewports.forEach((t,i)=>{i!==this.activeCompareId&&this.captureCompareSnapshot(i)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40};let t=this.compareViewports.get(this.activeCompareId),i=t==null?void 0:t.root.querySelector(".compare-body");return i?{width:i.clientWidth-24,height:i.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(t){let i=this.container.querySelector(t);if(!i)throw new Error(`PreviewShell missing element: ${t}`);return i}};function Nh(e={}){let t=new El(e);return typeof window!="undefined"&&(window.__previewShell=t),t.mount(),t}import{Sprite as gx,Container as Hh}from"pixi.js";var mx=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Sl=mx;if(typeof window!="undefined")try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);t!=null&&t.buildMode&&(Sl=t.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${Sl}`))}}catch{}var It=class{static async create(t,i,n){var c,l,d,u,p,f,m;console.log(`[ObjectFactory] create() called for: ${t}, __BUILD_MODE__: ${Sl}`);let r=(c=i==null?void 0:i.render)==null?void 0:c.asset;if(!r){console.log(`[ObjectFactory] No asset definition for: ${t}, returning empty container`);let h=new Hh;return this.applyTransform(h,i==null?void 0:i.transform),h}let a=(l=i==null?void 0:i.identity)==null?void 0:l.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${t}, configId: ${a}, type: ${r.type}, path: ${r.path}`);let s=await Va.load(t,r,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${t}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(r.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",t),o=new gx(s),console.log("[ObjectFactory] Created object:",o,"type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name),this.applyTransform(o,i==null?void 0:i.transform);else if(r.type==="json")if(console.log("[ObjectFactory] JSON asset for",t,"rawAsset type:",(p=s==null?void 0:s.constructor)==null?void 0:p.name,s),s&&(((f=s.constructor)==null?void 0:f.name)==="Container"||s instanceof Hh)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[r.path,`/assets/${r.path}`,`assets/${r.path}`,`../assets/${r.path}`],g=!1;for(let v of h)try{let b=await fetch(v);if(b.ok){o=await b.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",v,"type:",(m=o==null?void 0:o.constructor)==null?void 0:m.name),g=!0;break}}catch{continue}g||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,i==null?void 0:i.transform);return o}static applyTransform(t,i){var n,r,a,s;!i||!t||(i.position&&("x"in t&&"y"in t?(t.x=(n=i.position.x)!=null?n:0,t.y=(r=i.position.y)!=null?r:0):"position"in t&&t.position&&t.position.set((a=i.position.x)!=null?a:0,(s=i.position.y)!=null?s:0)),i.scale!==void 0&&"scale"in t&&t.scale&&(typeof t.scale=="object"&&"set"in t.scale?t.scale.set(i.scale):t.scale=i.scale),i.rotation!==void 0&&"rotation"in t&&(t.rotation=i.rotation),i.anchor&&"anchor"in t&&t.anchor&&Array.isArray(i.anchor)&&("set"in t.anchor?t.anchor.set(i.anchor[0],i.anchor[1]):(t.anchor.x=i.anchor[0],t.anchor.y=i.anchor[1])))}};function Al(e){try{if(e&&typeof e.keys=="function")return Array.from(e.keys())}catch{}return[]}function Uh(e){var t;return e?((t=e.getDisplayObject)==null?void 0:t.call(e))||e.pixiObject||e:null}function bx(e,t){if(!e||!(t!=null&&t.interaction))return;let i=t.interaction,n=i.enabled!==!1&&(i.draggable===!0||i.clickable===!0);e.eventMode=n?"static":"none",e.interactive=n,n&&(e.cursor=i.draggable?"move":"pointer")}function $h(e,t){var c,l,d,u,p;if(!e||!t)return;let i=t.transform||{};bx(e,t);let n=i.position||{},r=i.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof r.x=="number"?r.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof r.y=="number"?r.y:0);(c=e.position)!=null&&c.set?e.position.set(a,s):(typeof e.x=="number"&&(e.x=a),typeof e.y=="number"&&(e.y=s)),typeof i.scale=="number"&&((l=e.scale)!=null&&l.set?e.scale.set(i.scale):e.scale&&(e.scale.x=i.scale,e.scale.y=i.scale));let o=(u=i.anchor)!=null?u:(d=t.render)==null?void 0:d.anchor;o&&((p=e.anchor)!=null&&p.set)&&typeof o.x=="number"&&typeof o.y=="number"&&e.anchor.set(o.x,o.y)}function qh(e){if(typeof window=="undefined")return;let t=e==null?void 0:e.objects,i=Al(t),n=a=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return a;let o=window.__HANDLER_SCREEN_INDEX,c=o==null?void 0:o.instanceToScreen;return c?a.filter(l=>c[l]===s):a}catch{return a}};window.__editableObjectConfigs=t;let r=new Map;i.forEach(a=>r.set(a,[a])),window.__editableObjectInstances=r,window.refreshEditableConfigIndex=()=>qh(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(Al((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Al((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var d,u,p,f,m;let s=(f=(p=(u=(d=window.__editableConfig)==null?void 0:d.objects)==null?void 0:u.get)==null?void 0:p.call(u,a))!=null?f:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let c=window.__HANDLER_SCREEN_INDEX,l=(m=c==null?void 0:c.instanceToScreen)==null?void 0:m[a];return l&&l===o?s:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function vx(){if(typeof window=="undefined")return;let e=i=>{let n=String(i||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},t=async(i,n)=>{var a,s,o;let r=e(n);if(r)try{let[{Assets:c},{AssetTextures:l}]=await Promise.all([import("pixi.js"),import("./AssetTextures-CWUQXU5Q.js")]),d=Date.now(),u=/^(data:|blob:)/.test(r)?r:r+(r.includes("?")?`&t=${d}`:`?t=${d}`),p=await c.load(u);if(!p)return;l[i]=p;let f=window.CustomAssets;(a=f==null?void 0:f[i])!=null&&a.texture&&(f[i].texture=p);let m=window.gameObjectManager,h=(s=m==null?void 0:m.get)==null?void 0:s.call(m,i);if(h){let g=((o=h.getDisplayObject)==null?void 0:o.call(h))||h.pixiObject||h.pixi||h;if(g!=null&&g.texture)g.texture=p;else if(g!=null&&g.children){let v=g.children.find(b=>b==null?void 0:b.texture);v!=null&&v.texture&&(v.texture=p)}}}catch(c){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",i,c)}};window.applyLiveEditOverrides=i=>{try{let n=Xa();Array.isArray(n)&&n.length&&(window.__editableConfig=i,sr(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=i=>{try{let n=Xa();Array.isArray(n)&&n.length&&(window.__editableConfig=i,sr(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=i=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let r=[];if(i.runtime)for(let[a,s]of Object.entries(i.runtime))r.push({path:`runtime.${a}`,value:s});if(i.assets)for(let[a,s]of Object.entries(i.assets))r.push({path:`assets.${a}`,value:s}),typeof s=="string"&&t(a,s);if(i.splash)for(let[a,s]of Object.entries(i.splash))r.push({path:`splash.${a}`,value:s});if(i.loading)for(let[a,s]of Object.entries(i.loading))r.push({path:`loading.${a}`,value:s});if(i.start)for(let[a,s]of Object.entries(i.start))r.push({path:`start.${a}`,value:s});r.length&&sr(r,{silent:!0,persist:!0,emitEvent:!0})}}function Cl(e){let{getConfig:t,gameObjectManager:i,onObjectConfigApplied:n}=e;i&&(i.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=i.get(a),c=o==null?void 0:o.pixiObject,l=c==null?void 0:c.parent,d=l==null?void 0:l.children.indexOf(c);o?i.remove(a):c&&c.destroy();let u=window.gameApp,p=await It.create(a,s,u);l&&(d!==void 0&&d!==-1?l.addChildAt(p,d):l.addChild(p));let f=i.create(a,p);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),f}),typeof window!="undefined"&&(vx(),window.applyEditableObjectConfig=(a,s)=>{var o,c,l;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let u=(c=i==null?void 0:i.get)==null?void 0:c.call(i,a);if(console.log("[LIVE-EDIT] gameObject found?",!!u),u&&(console.log("[LIVE-EDIT] gameObject type:",(l=u.constructor)==null?void 0:l.name),console.log("[LIVE-EDIT] has updateConfig?",typeof u.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof u.onConfigUpdate=="function")),u&&typeof u.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),u.updateConfig(s);else if(u&&typeof u.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),u.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let p=Uh(u);$h(p,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let r={async applyObjectConfig(a,s){var d,u;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=t();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let c=(u=i==null?void 0:i.get)==null?void 0:u.call(i,a);if(console.log("[BRIDGE] gameObject found?",!!c),c&&(console.log("[BRIDGE] has updateConfig?",typeof c.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof c.onConfigUpdate=="function")),c&&typeof c.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),c.updateConfig(s);else if(c&&typeof c.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),c.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let p=Uh(c);$h(p,s)}let l=[a];n==null||n(a,s,l)},rebuildIndexes(){let a=t();typeof window!="undefined"&&(window.__editableConfig=a,qh(a))}};return r.rebuildIndexes(),r}import yx from"lottie-web";Rl(Fc);typeof window!="undefined"&&!window.lottie&&(window.lottie=yx);var Hi=null,xx=async()=>{if(!Hi){let e=typeof window!="undefined"?window.INLINE_ASSETS:null,t=(e==null?void 0:e["handler.config"])||(e==null?void 0:e["handler.config.json"]);if(t)try{if(t.startsWith("data:")){let n=atob(t.split(",")[1]);Hi=JSON.parse(n)}else Hi=JSON.parse(t);return Hi}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}Hi=await(await fetch("./handler.config.json")).json()}return Hi},Ml,Un,Yh,Ui,kl,Ll;function fE(e){Ml=e.initGame,Un=e.CustomAssets,Yh=e.updateScreenState,Ui=e.globalResponsiveMultipliers,kl=e.layout,Ll=e.clearResponsiveElements}var Ra="web_embed",Hn="https://example.com",Gh={profile_id:Ra},Ot=null,Ke=null,Tl={width:0,height:0},wx=!0,hE=async()=>{var l,d,u,p;document.title="Handler Pixi Game";let e=await xx();Gh={...e.ids||{},profile_id:Ra},Hn=e.destination_url||((d=(l=e.export_profiles)==null?void 0:l[Ra])==null?void 0:d.destination_url)||Hn,pt.init({ids:Gh,profile:Ra,destinationUrl:Hn});let t=pt.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ke=Nh({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),Wh()},onRefresh:Wh});let f=Ke.getGameContainer();f&&(t=f),window.addEventListener("handler-preview:screen",m=>{var y,x,w,A,T,E,M,I,_,S,L;let h=window.gameApp,g=window.gameObjectManager,{width:v,height:b}=m.detail;if(Tl.width=v,Tl.height=b,Yh(v,b),!(!h||!h.renderer)){g&&o(h,g);try{h.renderer.resize(v,b);let R=h.view;R&&(R.style.width="100%",R.style.height="100%",R.style.display="block")}catch(R){console.warn("[SCREEN] Error resizing renderer:",R);return}if(i&&g&&kl)try{let R=(y=window.__mainContainer)!=null?y:h.stage,O=(M=(E=(A=window.__tutorialLabel)!=null?A:(w=(x=g.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:w.call(x))!=null?E:(T=g.get("label_1"))==null?void 0:T.pixiObject)!=null?M:g.get("label_1"),C=g.get("background_1"),z=(L=(S=(_=window.__background)!=null?_:(I=C==null?void 0:C.getDisplayObject)==null?void 0:I.call(C))!=null?S:C==null?void 0:C.pixiObject)!=null?L:C;if(R){let k=R===h.stage;kl({mainContainer:R,label:O,background:z,backgroundTexture:(z==null?void 0:z.texture)||null,app:h},i,0,Tl,g,{skipMainContainerTransform:k})}}catch(R){console.warn("[SCREEN] Error in layout:",R)}}})}let i=await or("scene.main");window.__editableConfig=i,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=Za(i),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(p=(u=i.engine.runtime)==null?void 0:u.layout)!=null&&p.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(f=>setTimeout(f,100)),i=await or("scene.main"));let n=await Ml(t,i,Hn,Ke);Ot=n.app;let r=n.gameObjectManager;window.gameApp=Ot,window.gameObjectManager=r;try{window.__liveEditBridge=Cl({getConfig:()=>window.__editableConfig,gameObjectManager:r,assets:Un})}catch(f){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",f)}Ke&&Ke.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(Ui.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Ot,r);async function s(){try{let f=async b=>{let y=b.startsWith("/")?b:`/${b}`,x=await fetch(y,{cache:"no-cache"});if(!x.ok)return null;let w=await x.text();try{return JSON.parse(w)}catch{return null}},m=await f("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let h=m.screens;if(!h||typeof h!="object")return;let g={},v={};for(let[b,y]of Object.entries(h)){let x=y==null?void 0:y.source;if(typeof x!="string")continue;let w=await f(x),A=w==null?void 0:w.elements;if(!Array.isArray(A))continue;let T=A.map(E=>E==null?void 0:E.instance_id).filter(E=>typeof E=="string");g[b]=T;for(let E of T)v[E]||(v[E]=b)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:g,instanceToScreen:v},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(f,m){if(wx){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${Ui.scale.toFixed(3)}`),f.stage){let g=function(v,b=0){if(!v||!v.children)return;let y=" ".repeat(b);v.children.forEach((x,w)=>{if(x&&x.zIndex===9999){console.log(`${y}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let A=x.scale.x||1,T=x.scale.y||1;x.__originalScale||(x.__originalScale={x:A,y:T},console.log(`${y}[RESPONSIVE] Stored original scale for child[${w}]: ${A.toFixed(3)}, ${T.toFixed(3)}`));let E=x.__originalScale.x*Ui.scale,M=x.__originalScale.y*Ui.scale;typeof x.scale.set=="function"?x.scale.set(E,M):(x.scale.x=E,x.scale.y=M),console.log(`${y}[RESPONSIVE] Child[${w}] scale: ${A.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),g(x,b+1)}else x&&console.log(`${y}[RESPONSIVE] Child[${w}] has no scale (type: ${x.constructor.name})`)})};var h=g;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),g(f.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function c(f){if(f!==void 0){Ui.scale=f,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${f.toFixed(3)}`);let m=window.gameApp,h=window.gameObjectManager;m&&h?(o(m,h),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=c,pt.start()},Wh=async()=>{var t,i,n,r;console.log("[PREVIEW] Restarting game in 1 seconds...");let e=(t=window.gameObjectManager)==null?void 0:t.get("character_1");if(e){let a=((i=e.getDisplayObject)==null?void 0:i.call(e))||e;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((r=a.scale.y)!=null?r:1).toFixed(3)}`)}if(Ke){Ke.notifyGameDestroyed();try{Ll&&Ll()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ke.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Ot){try{Ot.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Ot=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Un.resetScene=="function"&&Un.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{or("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Za(o)),Ml(a,o,Hn).then(c=>{Ot=c.app,window.gameApp=Ot,window.gameObjectManager=c.gameObjectManager;try{window.__liveEditBridge=Cl({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Un})}catch(l){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",l)}Ke&&Ke.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{pt.start()}catch{}})})},100)},1e3)}};var Pl="0.3.12",_x=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);yc();var eg={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},tg=Math.random().toString(36).slice(2),Gi=null,$i={...eg},ig="web_embed",zl={},qn,Il=!1,$n=!1,Wn=!1,ng=!1,Nl=1,Pa=0,Da=!1,ft=!1,qi="",Wi=Math.floor(window.innerWidth),Yi=Math.floor(window.innerHeight),jl=Wi>Yi,ht=!1,Gn=!1,Vh=!1,Kh=!1,Ol=!1,Ia=null,ei=null,Bl=!1,Fl=!1,Ma=new Map;function rg(){if(!ei)return null;let e=Date.now()-ei;return!Number.isFinite(e)||e<0?null:e}function Dl(e){if(Bl)return;let t=rg();t!==null&&(Bl=!0,j("session_time",{duration_ms:t,reason:e}))}function Xh(){if(Gi)return Gi;let e=document.createElement("div");return e.id="handler-root",e.setAttribute("data-handler-root","true"),document.body.appendChild(e),Gi=e,e}function Oa(e){switch(e){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return e}}function ag(e,t){return{event_name:e,ts:Date.now(),session_id:tg,deployment_id:$i.deployment_id,variant_id:$i.variant_id,export_profile_id:$i.profile_id,instance_id:$i.instance_id||"default",env:ig==="mraid"?"mraid":"web",attribution:qn,payload:t}}function j(e,t){let i=Oa(e),n=ag(i,t);es(n,!!zl.analytics),cr(i,n),i!==e&&cr(e,n)}function Yn(){Ia&&(Ia(Wi,Yi),Ia=null)}function Vi(e){Nl=e,j("volume",e)}function Ki(e){e&&(ng=!0),!Wn&&(Wn=!0,j("pause"),Vi(0))}function Vn(e){!e&&ng||Wn&&(Wn=!1,j("resume"),Vi(Nl))}function Dt(e,t){Wi=Math.floor(e||window.innerWidth),Yi=Math.floor(t||window.innerHeight),jl=Wi>Yi,j("resize",{width:Wi,height:Yi})}function Ex(){if(Mc())try{let e=mraid.getMaxSize();Dt(e.width,e.height);let t=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Vn():Ki()};if(mraid.addEventListener("viewableChange",t),mraid.addEventListener("stateChange",t),mraid.addEventListener("sizeChange",()=>{let i=mraid.getMaxSize();Dt(i.width,i.height)}),mraid.getAudioVolume){let i=mraid.getAudioVolume();Vi(i?1:0)}if(mraid.addEventListener("audioVolumeChange",i=>{i!==null&&Vi(i>0?1:0)}),mraid.addEventListener("error",(i,n)=>{console.warn("mraid error:",i,"action:",n)}),Da=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Yn();else{let i=()=>{ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Yn()};mraid.addEventListener("ready",i)}}catch(e){console.warn("MRAID hook skipped",e)}}function Sx(){if(Pc())try{let e=dapi.getScreenSize();Dt(e.width,e.height),dapi.addEventListener("viewableChange",i=>{i.isViewable?Vn():Ki()}),dapi.addEventListener("adResized",i=>{let n=dapi.getScreenSize();Dt(i.width||n.width,i.height||n.height)});let t=dapi.getAudioVolume();if(Vi(t?1:0),dapi.addEventListener("audioVolumeChange",i=>Vi(i?1:0)),Da=!0,dapi.isViewable())ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Yn();else{let i=()=>{ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Yn()};dapi.addEventListener("ready",i)}}catch(e){console.warn("DAPI hook skipped",e)}}function Zh(){let e=()=>{ht||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ht=!0,j("boot"),j("view"),j("ready"),ft=!0,Yn(),Gn&&(Gn=!1,Xe.start()))};window.addEventListener("resize",()=>Dt()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Vn(),e()):Ki()}),document.readyState==="complete"||document.readyState==="interactive"?e():window.addEventListener("load",e),Da=!0}function Ax(){let e=t=>{typeof TouchEvent!="undefined"&&t instanceof TouchEvent&&(Vh=!0),!(Vh&&t instanceof MouseEvent)&&(Pa+=1,Fl||(Fl=!0,j("first_interaction",{count:Pa})),j("interaction",Pa))};document.addEventListener("mousedown",e),document.addEventListener("touchstart",e)}function Jh(e){var n,r,a,s,o,c,l,d,u,p,f,m;let t=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(t==="mraid"&&typeof mraid!="undefined")mraid.open(e||"");else if(t==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(li())(a=(r=window.TJ_API)==null?void 0:r.click)==null||a.call(r);else if(Ic())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(jc())(l=(c=window.ScPlayableAd)==null?void 0:c.onCTAClick)==null||l.call(c);else if(zc())try{(u=(d=window.smxTracking)==null?void 0:d.redirect)==null||u.call(d)}catch(h){console.warn("Smadex redirect failed",h)}else if(Oc()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(e||qi||""):e&&window.open(e)}else oi()?(p=window.install)==null||p.call(window):Dc()?(f=window.openAppStore)==null||f.call(window):ts()?(m=parent==null?void 0:parent.postMessage)==null||m.call(parent,"download","*"):e&&window.open(e)}function Cx(){let e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",t=i=>{if(!i)return;let n=new Image;n.src=i};if(e==="bigabid"){let i=window.BIGABID_BIDTIMEMACROS;if(!i)return;_e("view",()=>t(i.mraid_viewable)),_e("start",()=>t(i.game_viewable)),_e("engagement",()=>t(i.engagement));let n=()=>t(i.complete);_e("complete",n),lr("engagement",r=>{var a;((a=r==null?void 0:r.payload)==null?void 0:a.count)>3&&n()}),_e("cta_click",()=>t(i.click))}else if(e==="inmobi"){let i=window.INMOBI_DSPMACROS;if(!i)return;_e("view",()=>t(i.Ad_Load_Start)),_e("start",()=>t(i.Ad_Viewable)),_e("engagement",()=>t(i.First_Engagement)),_e("complete",()=>t(i.Gameplay_Complete)),_e("cta_click",()=>t(i.DSP_Click)),_e("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>t(i[`Spent_${n}_Seconds`]),n*1e3))})}}function Tx(){if(!li())return;let e=window.TJ_API;e&&e.setPlayableAPI&&e.setPlayableAPI({skipAd:()=>{try{Xe.finish()}catch(t){console.warn("Tapjoy skip failed",t)}}})}function Qh(){var t,i,n;let e=window.TJ_API;(t=e==null?void 0:e.objectiveComplete)==null||t.call(e),(i=e==null?void 0:e.playableFinished)==null||i.call(e),(n=e==null?void 0:e.gameplayFinished)==null||n.call(e)}function kx(){oi()&&(window.mintGameStart=()=>{Vn(!0),Dt()},window.mintGameClose=()=>{Ki(!0)})}function Lx(){if(!is())return;let e=window.NUC;!e||!e.trigger||(Xe.on("cta_click",()=>{var t,i;return(i=(t=e.trigger).convert)==null?void 0:i.call(t,qi)}),Xe.on("complete",()=>{var t,i;return(i=(t=e.trigger).tryAgain)==null?void 0:i.call(t)}))}var Xe={init(e={},t){var i;if(ig=e.profile||"web_embed",zl=e.consent||{},$i={...eg,...e.ids||{}},Gi=e.rootEl||Gi,qn=void 0,pc((i=e.telemetry)!=null&&i.endpoint?e.telemetry:null),ei=null,Bl=!1,Fl=!1,Ma.clear(),qi=e.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),t&&(Ia=t),j("init"),document.body.oncontextmenu=()=>!1,Xh(),Mx(Gi),Bc(),Ex(),Sx(),!Da){if(document.readyState==="complete")Zh();else if(!Kh){Kh=!0;let n=()=>{Zh(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}Ax(),Cx(),Tx(),kx(),Lx(),console.log(`%c @handler/playable-sdk %c v${Pl} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ht&&!ft&&(j("boot"),j("view"),j("ready"),Gn&&(Gn=!1,Xe.start()),ft=!0),ft=ht},getRoot(){return Xh()},get version(){return Pl},get maxWidth(){return Wi},get maxHeight(){return Yi},get isLandscape(){return jl},get isReady(){return ft},get isStarted(){return Il},get isPaused(){return Wn},get isFinished(){return $n},get volume(){return Nl},get interactions(){return Pa},on(e,t){lr(Oa(e),t)},off(e,t){Qa(Oa(e),t)},start(){var e,t;if(!Il){if(!ht){Gn=!0;return}if(Il=!0,ei||(ei=Date.now()),j("start"),Dt(),oi())Ki(),(e=window.gameReady)==null||e.call(window);else if(li()){let i=window.TJ_API;(t=i==null?void 0:i.setPlayableBuild)==null||t.call(i,{orientation:jl?"landscape":"portrait",buildID:Pl})}}},finish(){var e,t;$n||($n=!0,j("complete"),Dl("complete"),oi()?(e=window.gameEnd)==null||e.call(window):ts()?(t=parent==null?void 0:parent.postMessage)==null||t.call(parent,"complete","*"):li()&&Qh())},install(e){if(!$n){$n=!0,li()?(Qh(),setTimeout(()=>Xe.install(e),300)):(j("complete"),setTimeout(()=>Xe.install(e),0));return}Ol||(Ol=!0,setTimeout(()=>Ol=!1,500),j("cta_click"),j("conversion"),Dl("cta"),Jh(e||qi))},emit(e,t){let i=Oa(e);if(!_x.has(i)&&i!=="resize"&&i!=="volume"&&!i.startsWith("custom."))throw new Error(`Event ${e} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=ag(i,t);es(n,!!zl.analytics),cr(i,n)},gameStart(){Xe.start()},gameEnd(){Xe.finish()},ctaClick(e,t){j("cta_click",{url:e||qi,manual:!0}),(t==null?void 0:t.open)!==!1&&Jh(e||qi)},ctaShow(e){j("cta_show",e)},ctaDismiss(e){j("cta_dismiss",e)},getGameTimeMs(){return rg()},endSession(e="manual"){Dl(e)},setAttribution(e){qn=e},abTest(e,t){if(!e)throw new Error("abTest requires experimentId");if(!Array.isArray(t)||t.length<2)throw new Error("abTest requires at least 2 variants");let i=Math.abs(Rx(`${tg}:${e}`))%t.length,n=t[i];return qn={...qn||{},experiment_id:e},$i.variant_id=n,j("ab_assign",{experiment_id:e,variant_id:n}),n},levelStart(e,t){ei||(ei=Date.now()),j("level_start",{level_id:e,...t})},levelComplete(e,t){j("level_complete",{level_id:e,...t})},levelFail(e,t){j("level_fail",{level_id:e,...t})},checkpoint(e,t){j("checkpoint",{checkpoint_id:e,...t})},reward(e,t){j("reward",{reward_id:e,...t})},tutorialStart(e,t){j("tutorial_start",{step_id:e,...t})},tutorialComplete(e,t){j("tutorial_complete",{step_id:e,...t})},tutorialSkip(e,t){j("tutorial_skip",{step_id:e,...t})},timerStart(e){e&&Ma.set(e,Date.now())},timerEnd(e,t="custom",i){if(!e)return;let n=Ma.get(e);if(!n)return;Ma.delete(e);let r=Date.now()-n;if(!(!Number.isFinite(r)||r<0)){if(t==="custom"){j("engagement",{action:"timer",key:e,duration_ms:r,...i});return}j(t,{key:e,duration_ms:r,...i})}},fps(e,t){j("fps",{value:e,...t})},memory(e,t){j("memory",{bytes:e,...t})},assetLoadStart(e,t){j("asset_load_start",{asset_id:e,...t})},assetLoadComplete(e,t){j("asset_load_complete",{asset_id:e,...t})},reportError(e,t,i){j("error",{code:e,message:t,...i})},retry(){var e,t,i;if(oi())(e=window.gameRetry)==null||e.call(window);else if(is()){let n=window.NUC;(i=(t=n==null?void 0:n.trigger)==null?void 0:t.tryAgain)==null||i.call(t)}j("engagement",{action:"retry"})},pause(){Ki(!0)},resume(){Vn(!0)},resize(e,t){Dt(e,t)}},pt=Xe;function Rx(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t|0}function Mx(e){let t=document.createElement("script");t.type="text/javascript",t.textContent=`
1398
1421
  (function(){
1399
1422
  var events = ['touchstart','touchend','mousedown','keydown'];
1400
1423
  function unlock(){
@@ -1410,14 +1433,14 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1410
1433
  }
1411
1434
  events.forEach(function(e){ document.addEventListener(e, unlock, false); });
1412
1435
  })();
1413
- `,e.appendChild(t)}async function Fl(e,t={}){let i=new wx;await i.init({resizeTo:e,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0});let n=s=>{var u,p,f,b;if(!i.renderer)return;let o=(u=s==null?void 0:s.width)!=null?u:e.clientWidth,c=(p=s==null?void 0:s.height)!=null?p:e.clientHeight,l=o&&o>0?o:(f=window.innerWidth)!=null?f:320,d=c&&c>0?c:(b=window.innerHeight)!=null?b:480;i.renderer.resize(l,d)};e.innerHTML="",e.style.position="relative",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.width="100%",e.style.height="100dvh",e.style.minHeight="100vh",e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.boxSizing="border-box",e.style.overflow="hidden",t.background&&(e.style.background=t.background),e.appendChild(i.canvas),n();let r=document.createElement("div");return r.setAttribute("style",["position:absolute","inset:0","display:flex","flex-direction:column","align-items:center","justify-content:flex-start","gap:12px","pointer-events:none","font-family:Arial,sans-serif","padding:20px 16px","padding-bottom:clamp(24px, 6vh, 96px)","box-sizing:border-box","z-index:2"].join(";")),e.appendChild(r),pt.on("pause",()=>{i.ticker.stop(),document.querySelectorAll("audio").forEach(o=>o.pause())}),pt.on("resume",()=>{i.ticker.start(),document.querySelectorAll("audio").forEach(o=>{o.currentTime>0&&!o.ended&&o.play().catch(()=>{})})}),pt.on("resize",({payload:s})=>{n({width:s==null?void 0:s.width,height:s==null?void 0:s.height})}),window.addEventListener("resize",()=>n()),requestAnimationFrame(()=>n()),new ResizeObserver(s=>{let o=s[0];if(o&&o.contentRect.width>0&&o.contentRect.height>0){let c=Math.round(o.contentRect.width),l=Math.round(o.contentRect.height);if(n({width:c,height:l}),typeof window!="undefined"&&window.gameApp&&window.gameObjectManager){let d={width:c,height:l,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:"auto-resize",isLandscape:c>l};window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:d}))}}}).observe(e),{app:i,stage:i.stage,overlay:r,applySize:n}}import{BlurFilter as Nl,Ticker as Xi,ColorMatrixFilter as _x}from"pixi.js";var Oa=class{constructor(t){var r,a;let i=t==null?void 0:t.position,n=t==null?void 0:t.offset;this._basePosition={x:typeof(i==null?void 0:i.x)=="number"?i.x:0,y:typeof(i==null?void 0:i.y)=="number"?i.y:0},this._offset={x:typeof(n==null?void 0:n.x)=="number"?n.x:0,y:typeof(n==null?void 0:n.y)=="number"?n.y:0},this.position={x:this._basePosition.x+this._offset.x,y:this._basePosition.y+this._offset.y},this.scale=(r=t==null?void 0:t.scale)!=null?r:1,this.rotation=(a=t==null?void 0:t.rotation)!=null?a:0}update(t){let i=t.position,n=t.offset;i!==void 0&&(this._basePosition={x:typeof(i==null?void 0:i.x)=="number"?i.x:0,y:typeof(i==null?void 0:i.y)=="number"?i.y:0}),n!==void 0&&(this._offset={x:typeof(n==null?void 0:n.x)=="number"?n.x:0,y:typeof(n==null?void 0:n.y)=="number"?n.y:0}),(i!==void 0||n!==void 0)&&(this.position={x:this._basePosition.x+this._offset.x,y:this._basePosition.y+this._offset.y}),t.scale!==void 0&&(this.scale=t.scale),t.rotation!==void 0&&(this.rotation=t.rotation)}syncToPixi(t){t&&(t.position.set(this.position.x,this.position.y),t.scale.set(this.scale),t.rotation=this.rotation)}},Da=class{constructor(t){var i,n,r,a;this.z_index=(i=t==null?void 0:t.z_index)!=null?i:0,this.alpha=(n=t==null?void 0:t.alpha)!=null?n:1,this.visible=(r=t==null?void 0:t.visible)!=null?r:!0,this.tint=(a=t==null?void 0:t.tint)!=null?a:null}update(t){t.z_index!==void 0&&(this.z_index=t.z_index),t.alpha!==void 0&&(this.alpha=t.alpha),t.visible!==void 0&&(this.visible=t.visible),t.tint!==void 0&&(this.tint=t.tint)}syncToPixi(t,i){if(!t)return;if(t.zIndex=this.z_index,i!=null&&i.startsWith("ui_endgame_")||(t.alpha=this.alpha),t.visible=this.visible,this.tint!==null&&"tint"in t&&(t.tint=this.tint),i&&"texture"in t)try{let{AssetTextures:r}=Ne("handler-playable-sdk/pixi");if(r&&r[i]){let a=r[i];a&&(t.texture=a)}}catch{}}},za=class{constructor(t,i,n,r){this._tickerCleanup=null;this.onRebuildRequired=null;this.instanceId=t,this.objectConfig=i,this.pixiObject=n,this._config=r,this.transform=new Oa(r.transform),this.renderer=new Da(r.render),this.sync()}sync(){this.transform.syncToPixi(this.pixiObject),this.renderer.syncToPixi(this.pixiObject,this.instanceId),this.applyAnchor(),this.applyEffectsScale(),this.applyEffects(),this.syncTextProperties(),(!this._initialized||this._shouldReplayIntro)&&(this.applyIntro(),this._initialized=!0,this._shouldReplayIntro=!1),this.applyMotion()}syncTextProperties(){var i;if(!this.pixiObject||!("text"in this.pixiObject))return;let t=(i=this._config)==null?void 0:i.ui;t&&(t.text!==void 0&&this.pixiObject.text!==t.text&&(this.pixiObject.text=t.text),this.pixiObject.style&&(t.fontSize!==void 0&&(this.pixiObject.style.fontSize=t.fontSize),t.color!==void 0&&(this.pixiObject.style.fill=t.color),t.align!==void 0&&(this.pixiObject.style.align=t.align)))}destroy(){this._tickerCleanup&&(this._tickerCleanup(),this._tickerCleanup=null),this._introTicker&&(Xi.shared.remove(this._introTicker),this._introTicker=null),this.pixiObject&&this.pixiObject.parent&&this.pixiObject.parent.removeChild(this.pixiObject)}updateConfig(t){var c,l,d,u,p,f,b,h,g,m,v;let i=(l=(c=this._config)==null?void 0:c.motion)==null?void 0:l.intro,n=(d=t==null?void 0:t.motion)==null?void 0:d.intro;n!=null&&n.enabled&&JSON.stringify(i)!==JSON.stringify(n)&&(this._shouldReplayIntro=!0);let r=(f=(p=(u=this._config)==null?void 0:u.render)==null?void 0:p.asset)==null?void 0:f.type,a=(h=(b=t==null?void 0:t.render)==null?void 0:b.asset)==null?void 0:h.type,s=(m=(g=this._config)==null?void 0:g.ui)==null?void 0:m.renderMode,o=(v=t==null?void 0:t.ui)==null?void 0:v.renderMode;if((r!==a||s!==o)&&(console.log(`[GameObject] Rebuild required for ${this.instanceId}: type changed from ${r}/${s} to ${a}/${o}`),this.onRebuildRequired)){this.onRebuildRequired(this,t);return}this._config=t,t.transform&&this.transform.update(t.transform),t.render&&this.renderer.update(t.render),this.sync()}applyAnchor(){var r,a,s,o;if(!this.pixiObject||!("anchor"in this.pixiObject)||!this.pixiObject.anchor)return;let t=(a=(r=this._config)==null?void 0:r.render)==null?void 0:a.anchor,i=(o=(s=this._config)==null?void 0:s.transform)==null?void 0:o.anchor,n=t&&typeof t=="object"?t:i&&typeof i=="object"?i:null;n&&typeof n.x=="number"&&typeof n.y=="number"&&this.pixiObject.anchor.set(n.x,n.y)}applyEffectsScale(){var a,s,o;if(!((a=this.pixiObject)!=null&&a.scale))return;let t=(s=this._config)==null?void 0:s.effects,i=typeof(t==null?void 0:t.scale_x)=="number"?t.scale_x:1,n=typeof(t==null?void 0:t.scale_y)=="number"?t.scale_y:1;if(i===1&&n===1)return;let r=(o=this.transform.scale)!=null?o:1;typeof this.pixiObject.scale.set=="function"?this.pixiObject.scale.set(r*i,r*n):(this.pixiObject.scale.x=r*i,this.pixiObject.scale.y=r*n)}applyEffects(){var n,r,a,s,o,c,l,d,u;if(!this.pixiObject)return;let t=(n=this._config)==null?void 0:n.effects;if(!t||t.enabled===!1){this.pixiObject.filters=null;return}let i=[];if((r=t.blur)!=null&&r.enabled){let p=new Nl;p.blur=(a=t.blur.strength)!=null?a:4,i.push(p)}if((s=t.shadow)!=null&&s.enabled){let p=t.shadow,f=new Nl;f.blur=(o=p.blur)!=null?o:4,f.blendMode="multiply",i.push(f),(p.offsetX!==0||p.offsetY!==0)&&console.warn("[Effects] Drop shadow offset requires pixi-filters. Install: npm install pixi-filters")}if((c=t.glow)!=null&&c.enabled){let p=t.glow,f=new Nl;if(f.blur=(l=p.blur)!=null?l:8,i.push(f),p.color){let b=new _x,h=typeof p.color=="string"?parseInt(p.color.replace("#",""),16):p.color;b.tint(h),i.push(b)}}(d=t.stroke)!=null&&d.enabled&&console.warn("[Effects] Stroke/outline effect requires pixi-filters. Install: npm install pixi-filters"),(u=t.distortion)!=null&&u.enabled&&console.warn("[Effects] Distortion effect requires pixi-filters or a displacement map. Install: npm install pixi-filters"),this.pixiObject.filters=i.length>0?i:null}applyIntro(){var d,u,p,f,b,h,g;let t=(d=this._config)==null?void 0:d.motion;if(!t||!((u=t.intro)!=null&&u.enabled)||!this.pixiObject)return;let i=t.intro,n=(i.duration||0)/1e3,r=(i.delay||0)/1e3,a=this.transform.position.y,s=this.transform.scale*(((f=(p=this._config)==null?void 0:p.effects)==null?void 0:f.scale_x)||1),o=this.transform.scale*(((h=(b=this._config)==null?void 0:b.effects)==null?void 0:h.scale_y)||1);if(this.pixiObject.alpha=(g=i.startAlpha)!=null?g:0,i.startScale!==void 0&&this.pixiObject.scale.set(s*i.startScale,o*i.startScale),i.startYOffset!==void 0&&(this.pixiObject.y=a+(i.startYOffset||0)),this._introTicker&&Xi.shared.remove(this._introTicker),n<=0&&r<=0){this.pixiObject.alpha=this.renderer.alpha,this.pixiObject.y=this.transform.position.y,this.pixiObject.scale.set(s,o);return}let c=0,l=m=>{var P,M,_,S,L,R;if(c+=m.deltaTime/60,c<r)return;let v=n>0?Math.min(1,(c-r)/n):1,y=1-Math.pow(1-v,3),x=this.renderer.alpha,w=this.transform.scale*(((M=(P=this._config)==null?void 0:P.effects)==null?void 0:M.scale_x)||1),C=this.transform.scale*(((S=(_=this._config)==null?void 0:_.effects)==null?void 0:S.scale_y)||1),k=this.transform.position.y,E=this.transform.position.x;if(this.pixiObject.alpha=((L=i.startAlpha)!=null?L:0)+(x-((R=i.startAlpha)!=null?R:0))*y,i.startScale!==void 0){let O=i.startScale+(1-i.startScale)*y;this.pixiObject.scale.set(w*O,C*O)}i.startYOffset!==void 0&&(this.pixiObject.y=k+i.startYOffset+(k-(k+i.startYOffset))*y),v>=1&&(Xi.shared.remove(l),this._introTicker=null,this.pixiObject.alpha=x,this.pixiObject.x=E,this.pixiObject.y=k,this.pixiObject.scale.set(w,C))};this._introTicker=l,Xi.shared.add(l)}applyMotion(){var r,a,s;let t=(r=this._config)==null?void 0:r.motion,i=t&&t.enabled!==!1,n=JSON.stringify(t);if(!(this._lastMotionStr===n&&this._tickerCleanup)){if(this._lastMotionStr=n,!i){this._tickerCleanup&&(this._tickerCleanup(),this._tickerCleanup=null);return}if(this._tickerCleanup&&this._tickerCleanup(),(a=t.pulse)!=null&&a.enabled||(s=t.swing)!=null&&s.enabled){let o=0,c=l=>{var h,g,m,v,y,x,w,C,k,E,P;o+=l.deltaTime*.05;let d=this.transform.scale,u=d*(((g=(h=this._config)==null?void 0:h.effects)==null?void 0:g.scale_x)||1),p=d*(((v=(m=this._config)==null?void 0:m.effects)==null?void 0:v.scale_y)||1),f=this.transform.position.x,b=this.transform.position.y;if((y=t.pulse)!=null&&y.enabled){let M=(x=t.pulse.intensity)!=null?x:.1,_=(w=t.pulse.speed)!=null?w:1,L=1+Math.sin(o*_)*M;(C=this.pixiObject.scale)!=null&&C.set?this.pixiObject.scale.set(u*L,p*L):this.pixiObject.scale&&(this.pixiObject.scale.x=u*L,this.pixiObject.scale.y=p*L)}if((k=t.swing)!=null&&k.enabled){let M=(E=t.swing.amplitude)!=null?E:10,_=(P=t.swing.speed)!=null?P:1,S=Math.sin(o*_)*M;t.swing.axis==="vertical"?this.pixiObject.y=b+S:t.swing.axis==="both"?(this.pixiObject.x=f+S,this.pixiObject.y=b+S):this.pixiObject.x=f+S}};Xi.shared.add(c),this._tickerCleanup=()=>{var l,d,u,p,f;if(Xi.shared.remove(c),this.pixiObject){let b=this.transform.scale*(((d=(l=this._config)==null?void 0:l.effects)==null?void 0:d.scale_x)||1),h=this.transform.scale*(((p=(u=this._config)==null?void 0:u.effects)==null?void 0:p.scale_y)||1);this.pixiObject.x=this.transform.position.x,this.pixiObject.y=this.transform.position.y,(f=this.pixiObject.scale)!=null&&f.set?this.pixiObject.scale.set(b,h):this.pixiObject.scale&&(this.pixiObject.scale.x=b,this.pixiObject.scale.y=h)}}}}}getComponent(t){return this._config[t]}getPosition(){return{...this.transform.position}}setPosition(t,i){this.transform.position={x:t,y:i},this.transform.syncToPixi(this.pixiObject)}getAlpha(){return this.renderer.alpha}setAlpha(t){this.renderer.alpha=t,this.renderer.syncToPixi(this.pixiObject)}getVisible(){return this.renderer.visible}setVisible(t){this.renderer.visible=t,this.renderer.syncToPixi(this.pixiObject)}},Vn=class{constructor(t){this.objects=new Map;this.onObjectRebuildRequired=null;this.config=t}create(t,i){let n=this.config.objects.get(t);if(!n)throw new Error(`Object config not found: ${t}`);let r=new za(t,n.object_config||t,i,n);return this.objects.set(t,r),r.onRebuildRequired=async(a,s)=>{if(this.onObjectRebuildRequired){console.log(`[GameObjectManager] Triggering rebuild for ${t}`);let o=await this.onObjectRebuildRequired(t,s);o&&this.objects.get(t)===o&&console.log(`[GameObjectManager] \u2705 Rebuilt ${t} successfully`)}else console.warn(`[GameObjectManager] Rebuild required for ${t} but no factory provided`),a.updateConfig(s)},r}get(t){return this.objects.get(t)}updateConfig(t){this.config=t;for(let[i,n]of this.objects.entries()){let r=t.objects.get(i);r&&n.updateConfig(r)}}getAll(){return Array.from(this.objects.values())}remove(t){let i=this.objects.get(t);i&&i.destroy(),this.objects.delete(t)}clear(){for(let t of this.objects.values())t.destroy();this.objects.clear()}};var ja={"brand.primary":{family:"Arial, sans-serif",weight:"400"},"brand.warning":{family:"Arial Black, Arial, sans-serif",weight:"900"},"brand.heading":{family:"Arial Black, Arial, sans-serif",weight:"800"},"brand.body":{family:"Arial, sans-serif",weight:"400"}};function Ex(e){let t=ja[e];return t?t.family:(console.warn(`Font ID "${e}" not found in registry, using fallback`),"Arial, sans-serif")}function Sx(e){var i;let t=ja[e];return t&&(i=t.weight)!=null?i:"400"}function Ax(e,t){ja[e]=t}function Cx(){return Object.keys(ja)}var Zi=null;function kx(){return console.log("[LottieOverlay] getLottie called, lottieLib cached?",!!Zi),console.log("[LottieOverlay] window.lottie exists?",typeof window!="undefined"&&!!window.lottie),Zi||(typeof window!="undefined"&&window.lottie?(Zi=window.lottie,console.log("[LottieOverlay] \u2705 Found window.lottie, cached it")):(console.warn("[LottieOverlay] \u274C lottie-web is not available globally. Make sure it is loaded before using Lottie animations."),console.log("[LottieOverlay] window keys:",typeof window!="undefined"?Object.keys(window).filter(e=>e.toLowerCase().includes("lottie")):"no window"),Zi=null)),Zi}function Tx(e){return!e||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}function Lx(e){try{let t=new XMLHttpRequest;return t.open("GET",Tx(e),!1),t.send(null),t.status<200||t.status>=300||!t.responseText?null:JSON.parse(t.responseText)}catch{return null}}function Jh(e){return!e||typeof e!="object"||!Array.isArray(e.layers)?null:(Array.isArray(e.assets)||(e.assets=[]),Array.isArray(e.chars)||(e.chars=[]),e)}function Tl(e){Zi=e}function Rx(e,t,i,n){var C,k,E,P,M,_,S,L,R,O,A,z,T,D,$,ue,V,se,oe;let r=i.objects.get(e);if(!r)return console.warn(`[LottieOverlay] Object config not found: ${e}`),null;let a=((C=r.effects)==null?void 0:C.lottie)||{},s=r.transform||{},o=r.render||{};if(a.enabled===!1||o.visible===!1)return null;let c=n==null?void 0:n[e],l=Jh(c);if(!l){let me=(E=(k=r.render)==null?void 0:k.asset)==null?void 0:E.path;if(typeof me=="string"&&me.toLowerCase().endsWith(".json")){let bt=Lx(me);if(l=Jh(bt),l)try{n[e]=l}catch{}}}if(!l){let me=c&&typeof c=="object"?Object.prototype.toString.call(c):typeof c;return console.warn(`[LottieOverlay] Lottie JSON invalid for: ${e}`,{kind:me}),null}let d=kx();if(!d)return console.warn(`[LottieOverlay] lottie-web is not available. Cannot play animation: ${e}`),null;let u=(P=a.width)!=null?P:300,p=(M=a.height)!=null?M:300,f=(_=s.scale)!=null?_:1,b=((L=(S=s.position)==null?void 0:S.x)!=null?L:0)+((O=(R=s.offset)==null?void 0:R.x)!=null?O:0),h=((z=(A=s.position)==null?void 0:A.y)!=null?z:0)+((D=(T=s.offset)==null?void 0:T.y)!=null?D:0),g=($=s.rotation)!=null?$:0,m=(ue=o.z_index)!=null?ue:100,v=(V=o.alpha)!=null?V:1,y=document.createElement("div");y.style.cssText=`
1436
+ `,e.appendChild(t)}async function Hl(e,t={}){let i=new Px;await i.init({resizeTo:e,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0});let n=s=>{var u,p,f,m;if(!i.renderer)return;let o=(u=s==null?void 0:s.width)!=null?u:e.clientWidth,c=(p=s==null?void 0:s.height)!=null?p:e.clientHeight,l=o&&o>0?o:(f=window.innerWidth)!=null?f:320,d=c&&c>0?c:(m=window.innerHeight)!=null?m:480;i.renderer.resize(l,d)};e.innerHTML="",e.style.position="relative",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.width="100%",e.style.height="100dvh",e.style.minHeight="100vh",e.style.maxWidth="100%",e.style.maxHeight="100%",e.style.boxSizing="border-box",e.style.overflow="hidden",t.background&&(e.style.background=t.background),e.appendChild(i.canvas),n();let r=document.createElement("div");return r.setAttribute("style",["position:absolute","inset:0","display:flex","flex-direction:column","align-items:center","justify-content:flex-start","gap:12px","pointer-events:none","font-family:Arial,sans-serif","padding:20px 16px","padding-bottom:clamp(24px, 6vh, 96px)","box-sizing:border-box","z-index:2"].join(";")),e.appendChild(r),pt.on("pause",()=>{i.ticker.stop(),document.querySelectorAll("audio").forEach(o=>o.pause())}),pt.on("resume",()=>{i.ticker.start(),document.querySelectorAll("audio").forEach(o=>{o.currentTime>0&&!o.ended&&o.play().catch(()=>{})})}),pt.on("resize",({payload:s})=>{n({width:s==null?void 0:s.width,height:s==null?void 0:s.height})}),window.addEventListener("resize",()=>n()),requestAnimationFrame(()=>n()),new ResizeObserver(s=>{let o=s[0];if(o&&o.contentRect.width>0&&o.contentRect.height>0){let c=Math.round(o.contentRect.width),l=Math.round(o.contentRect.height);if(n({width:c,height:l}),typeof window!="undefined"&&window.gameApp&&window.gameObjectManager){let d={width:c,height:l,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:"auto-resize",isLandscape:c>l};window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:d}))}}}).observe(e),{app:i,stage:i.stage,overlay:r,applySize:n}}import{BlurFilter as Ul,Ticker as Xi,ColorMatrixFilter as Ix}from"pixi.js";var za=class{constructor(t){var r,a;let i=t==null?void 0:t.position,n=t==null?void 0:t.offset;this._basePosition={x:typeof(i==null?void 0:i.x)=="number"?i.x:0,y:typeof(i==null?void 0:i.y)=="number"?i.y:0},this._offset={x:typeof(n==null?void 0:n.x)=="number"?n.x:0,y:typeof(n==null?void 0:n.y)=="number"?n.y:0},this.position={x:this._basePosition.x+this._offset.x,y:this._basePosition.y+this._offset.y},this.scale=(r=t==null?void 0:t.scale)!=null?r:1,this.rotation=(a=t==null?void 0:t.rotation)!=null?a:0}update(t){let i=t.position,n=t.offset;i!==void 0&&(this._basePosition={x:typeof(i==null?void 0:i.x)=="number"?i.x:0,y:typeof(i==null?void 0:i.y)=="number"?i.y:0}),n!==void 0&&(this._offset={x:typeof(n==null?void 0:n.x)=="number"?n.x:0,y:typeof(n==null?void 0:n.y)=="number"?n.y:0}),(i!==void 0||n!==void 0)&&(this.position={x:this._basePosition.x+this._offset.x,y:this._basePosition.y+this._offset.y}),t.scale!==void 0&&(this.scale=t.scale),t.rotation!==void 0&&(this.rotation=t.rotation)}syncToPixi(t){t&&(t.position.set(this.position.x,this.position.y),t.scale.set(this.scale),t.rotation=this.rotation)}},ja=class{constructor(t){var i,n,r,a;this.z_index=(i=t==null?void 0:t.z_index)!=null?i:0,this.alpha=(n=t==null?void 0:t.alpha)!=null?n:1,this.visible=(r=t==null?void 0:t.visible)!=null?r:!0,this.tint=(a=t==null?void 0:t.tint)!=null?a:null}update(t){t.z_index!==void 0&&(this.z_index=t.z_index),t.alpha!==void 0&&(this.alpha=t.alpha),t.visible!==void 0&&(this.visible=t.visible),t.tint!==void 0&&(this.tint=t.tint)}syncToPixi(t,i){if(!t)return;if(t.zIndex=this.z_index,i!=null&&i.startsWith("ui_endgame_")||(t.alpha=this.alpha),t.visible=this.visible,this.tint!==null&&"tint"in t&&(t.tint=this.tint),i&&"texture"in t)try{let{AssetTextures:r}=Ne("handler-playable-sdk/pixi");if(r&&r[i]){let a=r[i];a&&(t.texture=a)}}catch{}}},Ba=class{constructor(t,i,n,r){this._tickerCleanup=null;this.onRebuildRequired=null;this.instanceId=t,this.objectConfig=i,this.pixiObject=n,this._config=r,this.transform=new za(r.transform),this.renderer=new ja(r.render),this.sync()}sync(){this.transform.syncToPixi(this.pixiObject),this.renderer.syncToPixi(this.pixiObject,this.instanceId),this.applyAnchor(),this.applyEffectsScale(),this.applyEffects(),this.syncTextProperties(),(!this._initialized||this._shouldReplayIntro)&&(this.applyIntro(),this._initialized=!0,this._shouldReplayIntro=!1),this.applyMotion()}syncTextProperties(){var i;if(!this.pixiObject||!("text"in this.pixiObject))return;let t=(i=this._config)==null?void 0:i.ui;t&&(t.text!==void 0&&this.pixiObject.text!==t.text&&(this.pixiObject.text=t.text),this.pixiObject.style&&(t.fontSize!==void 0&&(this.pixiObject.style.fontSize=t.fontSize),t.color!==void 0&&(this.pixiObject.style.fill=t.color),t.align!==void 0&&(this.pixiObject.style.align=t.align)))}destroy(){this._tickerCleanup&&(this._tickerCleanup(),this._tickerCleanup=null),this._introTicker&&(Xi.shared.remove(this._introTicker),this._introTicker=null),this.pixiObject&&this.pixiObject.parent&&this.pixiObject.parent.removeChild(this.pixiObject)}updateConfig(t){var c,l,d,u,p,f,m,h,g,v,b;let i=(l=(c=this._config)==null?void 0:c.motion)==null?void 0:l.intro,n=(d=t==null?void 0:t.motion)==null?void 0:d.intro;n!=null&&n.enabled&&JSON.stringify(i)!==JSON.stringify(n)&&(this._shouldReplayIntro=!0);let r=(f=(p=(u=this._config)==null?void 0:u.render)==null?void 0:p.asset)==null?void 0:f.type,a=(h=(m=t==null?void 0:t.render)==null?void 0:m.asset)==null?void 0:h.type,s=(v=(g=this._config)==null?void 0:g.ui)==null?void 0:v.renderMode,o=(b=t==null?void 0:t.ui)==null?void 0:b.renderMode;if((r!==a||s!==o)&&(console.log(`[GameObject] Rebuild required for ${this.instanceId}: type changed from ${r}/${s} to ${a}/${o}`),this.onRebuildRequired)){this.onRebuildRequired(this,t);return}this._config=t,t.transform&&this.transform.update(t.transform),t.render&&this.renderer.update(t.render),this.sync()}applyAnchor(){var r,a,s,o;if(!this.pixiObject||!("anchor"in this.pixiObject)||!this.pixiObject.anchor)return;let t=(a=(r=this._config)==null?void 0:r.render)==null?void 0:a.anchor,i=(o=(s=this._config)==null?void 0:s.transform)==null?void 0:o.anchor,n=t&&typeof t=="object"?t:i&&typeof i=="object"?i:null;n&&typeof n.x=="number"&&typeof n.y=="number"&&this.pixiObject.anchor.set(n.x,n.y)}applyEffectsScale(){var a,s,o;if(!((a=this.pixiObject)!=null&&a.scale))return;let t=(s=this._config)==null?void 0:s.effects,i=typeof(t==null?void 0:t.scale_x)=="number"?t.scale_x:1,n=typeof(t==null?void 0:t.scale_y)=="number"?t.scale_y:1;if(i===1&&n===1)return;let r=(o=this.transform.scale)!=null?o:1;typeof this.pixiObject.scale.set=="function"?this.pixiObject.scale.set(r*i,r*n):(this.pixiObject.scale.x=r*i,this.pixiObject.scale.y=r*n)}applyEffects(){var n,r,a,s,o,c,l,d,u;if(!this.pixiObject)return;let t=(n=this._config)==null?void 0:n.effects;if(!t||t.enabled===!1){this.pixiObject.filters=null;return}let i=[];if((r=t.blur)!=null&&r.enabled){let p=new Ul;p.blur=(a=t.blur.strength)!=null?a:4,i.push(p)}if((s=t.shadow)!=null&&s.enabled){let p=t.shadow,f=new Ul;f.blur=(o=p.blur)!=null?o:4,f.blendMode="multiply",i.push(f),(p.offsetX!==0||p.offsetY!==0)&&console.warn("[Effects] Drop shadow offset requires pixi-filters. Install: npm install pixi-filters")}if((c=t.glow)!=null&&c.enabled){let p=t.glow,f=new Ul;if(f.blur=(l=p.blur)!=null?l:8,i.push(f),p.color){let m=new Ix,h=typeof p.color=="string"?parseInt(p.color.replace("#",""),16):p.color;m.tint(h),i.push(m)}}(d=t.stroke)!=null&&d.enabled&&console.warn("[Effects] Stroke/outline effect requires pixi-filters. Install: npm install pixi-filters"),(u=t.distortion)!=null&&u.enabled&&console.warn("[Effects] Distortion effect requires pixi-filters or a displacement map. Install: npm install pixi-filters"),this.pixiObject.filters=i.length>0?i:null}applyIntro(){var d,u,p,f,m,h,g;let t=(d=this._config)==null?void 0:d.motion;if(!t||!((u=t.intro)!=null&&u.enabled)||!this.pixiObject)return;let i=t.intro,n=(i.duration||0)/1e3,r=(i.delay||0)/1e3,a=this.transform.position.y,s=this.transform.scale*(((f=(p=this._config)==null?void 0:p.effects)==null?void 0:f.scale_x)||1),o=this.transform.scale*(((h=(m=this._config)==null?void 0:m.effects)==null?void 0:h.scale_y)||1);if(this.pixiObject.alpha=(g=i.startAlpha)!=null?g:0,i.startScale!==void 0&&this.pixiObject.scale.set(s*i.startScale,o*i.startScale),i.startYOffset!==void 0&&(this.pixiObject.y=a+(i.startYOffset||0)),this._introTicker&&Xi.shared.remove(this._introTicker),n<=0&&r<=0){this.pixiObject.alpha=this.renderer.alpha,this.pixiObject.y=this.transform.position.y,this.pixiObject.scale.set(s,o);return}let c=0,l=v=>{var M,I,_,S,L,R;if(c+=v.deltaTime/60,c<r)return;let b=n>0?Math.min(1,(c-r)/n):1,y=1-Math.pow(1-b,3),x=this.renderer.alpha,w=this.transform.scale*(((I=(M=this._config)==null?void 0:M.effects)==null?void 0:I.scale_x)||1),A=this.transform.scale*(((S=(_=this._config)==null?void 0:_.effects)==null?void 0:S.scale_y)||1),T=this.transform.position.y,E=this.transform.position.x;if(this.pixiObject.alpha=((L=i.startAlpha)!=null?L:0)+(x-((R=i.startAlpha)!=null?R:0))*y,i.startScale!==void 0){let O=i.startScale+(1-i.startScale)*y;this.pixiObject.scale.set(w*O,A*O)}i.startYOffset!==void 0&&(this.pixiObject.y=T+i.startYOffset+(T-(T+i.startYOffset))*y),b>=1&&(Xi.shared.remove(l),this._introTicker=null,this.pixiObject.alpha=x,this.pixiObject.x=E,this.pixiObject.y=T,this.pixiObject.scale.set(w,A))};this._introTicker=l,Xi.shared.add(l)}applyMotion(){var r,a,s;let t=(r=this._config)==null?void 0:r.motion,i=t&&t.enabled!==!1,n=JSON.stringify(t);if(!(this._lastMotionStr===n&&this._tickerCleanup)){if(this._lastMotionStr=n,!i){this._tickerCleanup&&(this._tickerCleanup(),this._tickerCleanup=null);return}if(this._tickerCleanup&&this._tickerCleanup(),(a=t.pulse)!=null&&a.enabled||(s=t.swing)!=null&&s.enabled){let o=0,c=l=>{var h,g,v,b,y,x,w,A,T,E,M;o+=l.deltaTime*.05;let d=this.transform.scale,u=d*(((g=(h=this._config)==null?void 0:h.effects)==null?void 0:g.scale_x)||1),p=d*(((b=(v=this._config)==null?void 0:v.effects)==null?void 0:b.scale_y)||1),f=this.transform.position.x,m=this.transform.position.y;if((y=t.pulse)!=null&&y.enabled){let I=(x=t.pulse.intensity)!=null?x:.1,_=(w=t.pulse.speed)!=null?w:1,L=1+Math.sin(o*_)*I;(A=this.pixiObject.scale)!=null&&A.set?this.pixiObject.scale.set(u*L,p*L):this.pixiObject.scale&&(this.pixiObject.scale.x=u*L,this.pixiObject.scale.y=p*L)}if((T=t.swing)!=null&&T.enabled){let I=(E=t.swing.amplitude)!=null?E:10,_=(M=t.swing.speed)!=null?M:1,S=Math.sin(o*_)*I;t.swing.axis==="vertical"?this.pixiObject.y=m+S:t.swing.axis==="both"?(this.pixiObject.x=f+S,this.pixiObject.y=m+S):this.pixiObject.x=f+S}};Xi.shared.add(c),this._tickerCleanup=()=>{var l,d,u,p,f;if(Xi.shared.remove(c),this.pixiObject){let m=this.transform.scale*(((d=(l=this._config)==null?void 0:l.effects)==null?void 0:d.scale_x)||1),h=this.transform.scale*(((p=(u=this._config)==null?void 0:u.effects)==null?void 0:p.scale_y)||1);this.pixiObject.x=this.transform.position.x,this.pixiObject.y=this.transform.position.y,(f=this.pixiObject.scale)!=null&&f.set?this.pixiObject.scale.set(m,h):this.pixiObject.scale&&(this.pixiObject.scale.x=m,this.pixiObject.scale.y=h)}}}}}getComponent(t){return this._config[t]}getPosition(){return{...this.transform.position}}setPosition(t,i){this.transform.position={x:t,y:i},this.transform.syncToPixi(this.pixiObject)}getAlpha(){return this.renderer.alpha}setAlpha(t){this.renderer.alpha=t,this.renderer.syncToPixi(this.pixiObject)}getVisible(){return this.renderer.visible}setVisible(t){this.renderer.visible=t,this.renderer.syncToPixi(this.pixiObject)}},Kn=class{constructor(t){this.objects=new Map;this.onObjectRebuildRequired=null;this.config=t}create(t,i){let n=this.config.objects.get(t);if(!n)throw new Error(`Object config not found: ${t}`);let r=new Ba(t,n.object_config||t,i,n);return this.objects.set(t,r),r.onRebuildRequired=async(a,s)=>{if(this.onObjectRebuildRequired){console.log(`[GameObjectManager] Triggering rebuild for ${t}`);let o=await this.onObjectRebuildRequired(t,s);o&&this.objects.get(t)===o&&console.log(`[GameObjectManager] \u2705 Rebuilt ${t} successfully`)}else console.warn(`[GameObjectManager] Rebuild required for ${t} but no factory provided`),a.updateConfig(s)},r}get(t){return this.objects.get(t)}updateConfig(t){this.config=t;for(let[i,n]of this.objects.entries()){let r=t.objects.get(i);r&&n.updateConfig(r)}}getAll(){return Array.from(this.objects.values())}remove(t){let i=this.objects.get(t);i&&i.destroy(),this.objects.delete(t)}clear(){for(let t of this.objects.values())t.destroy();this.objects.clear()}};var Fa={"brand.primary":{family:"Arial, sans-serif",weight:"400"},"brand.warning":{family:"Arial Black, Arial, sans-serif",weight:"900"},"brand.heading":{family:"Arial Black, Arial, sans-serif",weight:"800"},"brand.body":{family:"Arial, sans-serif",weight:"400"}};function Ox(e){let t=Fa[e];return t?t.family:(console.warn(`Font ID "${e}" not found in registry, using fallback`),"Arial, sans-serif")}function Dx(e){var i;let t=Fa[e];return t&&(i=t.weight)!=null?i:"400"}function zx(e,t){Fa[e]=t}function jx(){return Object.keys(Fa)}var Zi=null;function Bx(){return console.log("[LottieOverlay] getLottie called, lottieLib cached?",!!Zi),console.log("[LottieOverlay] window.lottie exists?",typeof window!="undefined"&&!!window.lottie),Zi||(typeof window!="undefined"&&window.lottie?(Zi=window.lottie,console.log("[LottieOverlay] \u2705 Found window.lottie, cached it")):(console.warn("[LottieOverlay] \u274C lottie-web is not available globally. Make sure it is loaded before using Lottie animations."),console.log("[LottieOverlay] window keys:",typeof window!="undefined"?Object.keys(window).filter(e=>e.toLowerCase().includes("lottie")):"no window"),Zi=null)),Zi}function Fx(e){return!e||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}function Nx(e){try{let t=new XMLHttpRequest;return t.open("GET",Fx(e),!1),t.send(null),t.status<200||t.status>=300||!t.responseText?null:JSON.parse(t.responseText)}catch{return null}}function sg(e){return!e||typeof e!="object"||!Array.isArray(e.layers)?null:(Array.isArray(e.assets)||(e.assets=[]),Array.isArray(e.chars)||(e.chars=[]),e)}function Rl(e){Zi=e}function Hx(e,t,i,n){var A,T,E,M,I,_,S,L,R,O,C,z,k,D,$,ue,V,se,oe;let r=i.objects.get(e);if(!r)return console.warn(`[LottieOverlay] Object config not found: ${e}`),null;let a=((A=r.effects)==null?void 0:A.lottie)||{},s=r.transform||{},o=r.render||{};if(a.enabled===!1||o.visible===!1)return null;let c=n==null?void 0:n[e],l=sg(c);if(!l){let be=(E=(T=r.render)==null?void 0:T.asset)==null?void 0:E.path;if(typeof be=="string"&&be.toLowerCase().endsWith(".json")){let mt=Nx(be);if(l=sg(mt),l)try{n[e]=l}catch{}}}if(!l){let be=c&&typeof c=="object"?Object.prototype.toString.call(c):typeof c;return console.warn(`[LottieOverlay] Lottie JSON invalid for: ${e}`,{kind:be}),null}let d=Bx();if(!d)return console.warn(`[LottieOverlay] lottie-web is not available. Cannot play animation: ${e}`),null;let u=(M=a.width)!=null?M:300,p=(I=a.height)!=null?I:300,f=(_=s.scale)!=null?_:1,m=((L=(S=s.position)==null?void 0:S.x)!=null?L:0)+((O=(R=s.offset)==null?void 0:R.x)!=null?O:0),h=((z=(C=s.position)==null?void 0:C.y)!=null?z:0)+((D=(k=s.offset)==null?void 0:k.y)!=null?D:0),g=($=s.rotation)!=null?$:0,v=(ue=o.z_index)!=null?ue:100,b=(V=o.alpha)!=null?V:1,y=document.createElement("div");y.style.cssText=`
1414
1437
  position: absolute;
1415
1438
  top: calc(50% + ${h}px);
1416
- left: calc(50% + ${b}px);
1439
+ left: calc(50% + ${m}px);
1417
1440
  transform: translate(-50%, -50%) scale(${f}) rotate(${g}deg);
1418
1441
  width: ${u}px;
1419
1442
  height: ${p}px;
1420
1443
  pointer-events: none;
1421
- z-index: ${m};
1422
- opacity: ${v};
1423
- `,t.appendChild(y);let x;try{x=d.loadAnimation({container:y,renderer:a.renderer||"svg",loop:(se=a.loop)!=null?se:!1,autoplay:(oe=a.autoplay)!=null?oe:!0,animationData:l})}catch(me){return y.parentNode&&y.parentNode.removeChild(y),console.warn(`[LottieOverlay] Failed to start animation: ${e}`,me),null}a.speed!==void 0&&x.setSpeed(a.speed);let w=()=>{x.destroy(),y.parentNode&&y.parentNode.removeChild(y)};return a.loop||x.addEventListener("complete",w),{animation:x,cleanup:w}}var Hl=class{constructor(t,i,n){this.systems=[];this.totalTime=0;this.context=null;this.root=t,this.config=i,this.destinationUrl=n}async createApp(t){if(this.context)return{app:this.app,gameObjectManager:this.gameObjectManager};let{app:i,stage:n}=await Fl(this.root,{background:t.background_color,text:t.text_color,primary:t.cta_background,cta_text:t.cta_text});this.app=i,this.stage=n,this.gameObjectManager=new Vn(this.config),this.stage.eventMode="passive",this.stage.interactive=!1,this.stage.interactiveChildren=!0,this.stage.sortableChildren=!0,this.context={app:this.app,stage:this.stage,config:this.config,gameObjectManager:this.gameObjectManager,destinationUrl:this.destinationUrl,root:this.root,engine:this};for(let r of this.systems)r.setContext(this.context);return{app:this.app,gameObjectManager:this.gameObjectManager}}async initSystems(){if(!this.context)throw new Error("[GameEngine] createApp() must be called before initSystems()");for(let t of this.systems)t.init&&await t.init()}async init(t){return await this.createApp(t),await this.initSystems(),{app:this.app,gameObjectManager:this.gameObjectManager}}registerSystems(t){this.systems.push(...t)}async start(){for(let t of this.systems)t.onStart&&await t.onStart();this.app.ticker.add(this.update.bind(this)),window.addEventListener("handler-preview:screen",t=>{let{width:i,height:n}=t.detail;this.resize(i,n)})}update(t){let i=t.deltaTime/60;this.totalTime+=i;for(let n of this.systems)n.update&&n.update(i,this.totalTime)}resize(t,i){for(let n of this.systems)n.onResize&&n.onResize(t,i)}updateConfig(t){this.config=t;for(let i of this.systems)i.context.config=t,i.onConfigUpdate&&i.onConfigUpdate(t)}destroy(){for(let t of this.systems)t.onDestroy&&t.onDestroy();this.app.ticker.remove(this.update.bind(this)),this.app.destroy(!0,{children:!0,texture:!1})}getApp(){return this.app}getGameObjectManager(){return this.gameObjectManager}getTotalTime(){return this.totalTime}getSystem(t){let i=this.systems.find(n=>n instanceof t);if(!i)throw new Error(`System ${t.name} not found!`);return i}};var Kn=class{setContext(t){this.context=t}};var Xn=class{constructor(){this.config=null}init(t){this.config=t}get(t){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(t)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(t){return this.config?this.config.objects.has(t):!1}};import*as Qh from"pixi.js";var Px=Qh;typeof window!="undefined"&&(window.__basePixi=Qh);import{Sprite as Ix,Text as Mx,TextStyle as Ox,Texture as eg}from"pixi.js";var tg=e=>e*Math.PI/180;function Dx(e,t){var s,o,c,l,d;let i=t.ui;if(!(i!=null&&i.text))return null;let n="#ffffff";(s=t.render)!=null&&s.tint&&(n=t.render.tint);let r=new Ox({fontFamily:(o=i.font)!=null?o:"Arial",fontSize:(c=i.fontSize)!=null?c:16,fill:n,align:(l=i.align)!=null?l:"center",letterSpacing:(d=i.letterSpacing)!=null?d:0}),a=new Mx({text:i.text,style:r});return a.label=e,a}function zx(e){var d,u,p,f,b,h,g,m,v,y;let{stage:t,mainContainer:i,activeConfig:n,gameObjectManager:r,allowList:a,denyList:s}=e,o={},c={},l={};i.sortableChildren=!0;for(let[x,w]of n.objects.entries()){if(s!=null&&s.has(x)||a&&!a.has(x)||(w==null?void 0:w.enabled)===!1)continue;let C=(u=(d=w==null?void 0:w.render)==null?void 0:d.asset)==null?void 0:u.path,k=(f=(p=w==null?void 0:w.render)==null?void 0:p.asset)==null?void 0:f.type,E=!!(C&&k==="image"),P=!!((b=w==null?void 0:w.ui)!=null&&b.text),M=P?(h=w==null?void 0:w.ui)==null?void 0:h.renderMode:void 0,_;if(M==="png"&&E?_="png":M==="text"&&P?_="text":E?_="png":P?_="text":_="skip",_!=="skip"){if(_==="text"){let S=Dx(x,w);if(!S)continue;let L=w.render;S.alpha=typeof(L==null?void 0:L.alpha)=="number"?L.alpha:1,S.visible=(L==null?void 0:L.visible)!==!1,S.zIndex=typeof(L==null?void 0:L.z_index)=="number"?L.z_index:0,L!=null&&L.anchor&&typeof L.anchor.x=="number"&&typeof L.anchor.y=="number"?S.anchor.set(L.anchor.x,L.anchor.y):S.anchor.set(.5,.5);let R=w.transform,O=(R==null?void 0:R.position)||(R==null?void 0:R.offset);O&&S.position.set((g=O.x)!=null?g:0,(m=O.y)!=null?m:0);let A=typeof(R==null?void 0:R.scale)=="number"?R.scale:1;S.scale.set(A,A);let z=typeof(R==null?void 0:R.rotation)=="number"?R.rotation:0;S.rotation=tg(z),S.parent||i.addChild(S);try{r.create(x,S)}catch{}o[x]=S,l[x]=S}else if(_==="png"){let S=He[x]||(typeof eg!="undefined"?eg.EMPTY:void 0),L=new Ix(S);L.label=x;let R=w.render;L.alpha=typeof(R==null?void 0:R.alpha)=="number"?R.alpha:1,L.visible=(R==null?void 0:R.visible)!==!1,L.zIndex=typeof(R==null?void 0:R.z_index)=="number"?R.z_index:0,R!=null&&R.anchor&&typeof R.anchor.x=="number"&&typeof R.anchor.y=="number"&&L.anchor.set(R.anchor.x,R.anchor.y);let O=w.transform,A=(O==null?void 0:O.position)||(O==null?void 0:O.offset);A&&L.position.set((v=A.x)!=null?v:0,(y=A.y)!=null?y:0);let z=typeof(O==null?void 0:O.scale)=="number"?O.scale:1;L.scale.set(z,z);let T=typeof(O==null?void 0:O.rotation)=="number"?O.rotation:0;L.rotation=tg(T),L.parent||i.addChild(L);try{r.create(x,L)}catch{}o[x]=L,c[x]=L}}}return i.parent||t.addChild(i),{objects:o,sprites:c,texts:l}}var Ul=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Xn}init(t,i){this.registry.init(t),this.app=i}updateConfig(t){this.registry.init(t),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let i=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));if(i.length===0)return;let n=async r=>{r.length&&(console.log("[Assets] Loading objects:",r),await Promise.all(r.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let c=await Mt.create(a,s,this.app);this.instanceCache.set(a,c),console.log("[Assets] Loaded object:",a,(o=c==null?void 0:c.constructor)==null?void 0:o.name)}catch(c){console.error("[Assets] Failed to load object:",a,c)}})))};return this.readyPromise=(async()=>{await n(i);let r=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));r.length>0&&(console.warn("[Assets] Retrying missing assets:",r),await n(r)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(t){let i=this.registry.get(t);if(i){let n=await Mt.create(t,i,this.app);this.instanceCache.set(t,n)}}get(t){return this.instanceCache.get(t)}},ig=new Ul,jx=new Proxy(ig,{get(e,t){if(t in e&&typeof e[t]=="function")return e[t].bind(e);if(e.get(t))return e.get(t)}});function Bx(e,t){ig.init(e,t)}var $l=class extends Kn{async init(){Ya(this.context.config,this.context.app),await He.ready(),console.log("[AssetSystem] All assets preloaded and ready")}async onStart(){}onConfigUpdate(){console.log("[AssetSystem] Config updated - systems will refresh textures")}};import{Graphics as Fx,Point as Nx}from"pixi.js";var gt={width:400,height:600,designWidth:400,scaleFactor:1},Fa={scale:1,position:1},Na=[];function Hx(e,t,i,n,r,a,s){Na.push({element:e,originalScale:a,positionHelper:t,heightPercent:r}),t(e,i,n,r,a,s,!1)}function Ux(){Na.forEach(({element:e,originalScale:t,positionHelper:i,heightPercent:n})=>{let r=t*gt.scaleFactor;i(e,gt.width,gt.height,n,r,!0,!1)})}function $x(){Na.length=0,console.log("[LAYOUT] Cleared all responsive elements")}function ql(e,t){console.log(`[SCREEN] updateScreenState called: ${e}x${t}`),gt.width=e,gt.height=t,gt.scaleFactor=Math.min(e/gt.designWidth,1.15),Fa.scale=gt.scaleFactor,Fa.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Fa.scale.toFixed(3)}`),Ux()}var X={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function qx(e,t,i){let n=X[e];n&&n[t]!==void 0&&(n[t]=i,console.log(`Updated ${e}.${t} = ${i}`))}function Gx(){return X}var Wx={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Ba(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Ha(e,t={x:.5,y:.5}){var i;if(Array.isArray(e))return{x:Ba(e[0],t.x),y:Ba(e[1],t.y)};if(e&&typeof e=="object"){let n=e;return{x:Ba(n.x,t.x),y:Ba(n.y,t.y)}}if(typeof e=="string"){let n=e.trim().toLowerCase();return(i=Wx[n])!=null?i:t}return t}function Jn(e,t,i,n={}){var f,b,h,g,m,v;let r=Ha(i),a=(f=n.inset)!=null?f:{},s=(b=n.padding)!=null?b:{x:0,y:0},o=((h=a.left)!=null?h:0)+s.x,c=((g=a.right)!=null?g:0)+s.x,l=((m=a.top)!=null?m:0)+s.y,d=((v=a.bottom)!=null?v:0)+s.y,u=Math.max(0,e-o-c),p=Math.max(0,t-l-d);return{x:o+u*r.x,y:l+p*r.y}}function Qn(e,t,i,n={}){var h,g,m,v,y,x;let r=(h=n.inset)!=null?h:{},a=(g=n.padding)!=null?g:{x:0,y:0},s=((m=r.left)!=null?m:0)+a.x,o=((v=r.right)!=null?v:0)+a.x,c=((y=r.top)!=null?y:0)+a.y,l=((x=r.bottom)!=null?x:0)+a.y,d=Math.max(0,e-s-o),u=Math.max(0,t-c-l),p=Ha(i,{x:.5,y:.5}),f=Math.min(Math.max(p.x,0),1),b=Math.min(Math.max(p.y,0),1);return{x:s+d*f,y:c+u*b}}function Gl(e,t,i,n={}){var d,u,p;if(!e)return;let r=n.positionRatio?Qn(t,i,n.positionRatio,{inset:n.inset,padding:n.screenPadding}):Jn(t,i,n.anchor,{inset:n.inset,padding:n.screenPadding}),a=(d=n.offset)!=null?d:{x:0,y:0},s=r.x+a.x,o=r.y+a.y;e.anchor&&n.renderAnchor&&e.anchor.set(n.renderAnchor.x,n.renderAnchor.y),je(e,s,o);let c=(u=n.scale)!=null?u:1,l=(p=n.scaleMultiplier)!=null?p:1;(n.scale!==void 0||n.scaleMultiplier!==void 0)&&Ze(e,c*l)}if(typeof window!="undefined"){let e=window.innerWidth,t=window.innerHeight,i=()=>{let n=window.innerWidth,r=window.innerHeight;(n!==e||r!==t)&&(e=n,t=r,ql(n,r))};window.addEventListener("resize",i),window.addEventListener("orientationchange",()=>{setTimeout(i,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",i),window.mraid.addEventListener("sizeChange",i)),ql(window.innerWidth,window.innerHeight),window.updateDebugConfig=qx,window.getDebugConfig=Gx,window.copyConfig=n0,window.applyConfig=Zn,window.applyConfigForRatio=r0,window.positionAtBottom=ng,window.positionAtTop=Kx,window.positionAtCenter=Xx,window.positionAtLeft=Zx,window.positionAtRight=Jx,window.positionAtBottomLeft=Qx,window.positionAtBottomRight=e0,window.positionAtTopLeft=t0,window.positionAtTopRight=i0,window.applyPositionContract=Vx,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function Ua(e,t,i=0){return e*t+i}function $a(e,t,i=0){return e*(1-t)+i}function qa(e,t,i=0){return e*t+i}function Ga(e,t,i=0){return e*(1-t)+i}function Le(e,t=0){return e/2+t}function Yx(e,t){return e*t}function Vx(e,t,i,n){var s,o,c,l,d,u,p,f,b,h,g,m,v,y,x,w,C,k,E,P;let r=0,a=0;switch(n.type){case"top":r=Le(t,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),a=Ua(i,n.percent,(l=(c=n.offset)==null?void 0:c.y)!=null?l:0);break;case"bottom":r=Le(t,(u=(d=n.offset)==null?void 0:d.x)!=null?u:0),a=$a(i,n.percent,(f=(p=n.offset)==null?void 0:p.y)!=null?f:0);break;case"left":r=qa(t,n.percent,(h=(b=n.offset)==null?void 0:b.x)!=null?h:0),a=Le(i,(m=(g=n.offset)==null?void 0:g.y)!=null?m:0);break;case"right":r=Ga(t,n.percent,(y=(v=n.offset)==null?void 0:v.x)!=null?y:0),a=Le(i,(w=(x=n.offset)==null?void 0:x.y)!=null?w:0);break;case"center":r=Le(t,(k=(C=n.offset)==null?void 0:C.x)!=null?k:0),a=Le(i,(P=(E=n.offset)==null?void 0:E.y)!=null?P:0);break}e.position?e.position.set(r,a):(e.x=r,e.y=a),n.scale!==void 0&&n.scale!==1&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(n.scale,n.scale):(e.scale.x=n.scale,e.scale.y=n.scale))}function ng(e,t,i,n=.2,r=1,a=!0,s=!1){let o=Yx(i,n),c=$a(i,n/2);je(e,Le(t),c);let l=a?r*gt.scaleFactor:r;Ze(e,l),s&&!Na.find(d=>d.element===e)&&Hx(e,ng,t,i,n,r,a)}function Kx(e,t,i,n=.1,r=1){je(e,Le(t),Ua(i,n)),Ze(e,r)}function Xx(e,t,i,n=0,r=0,a=1){je(e,Le(t,n),Le(i,r)),Ze(e,a)}function Zx(e,t,i,n=.1,r=1){je(e,qa(t,n),Le(i)),Ze(e,r)}function Jx(e,t,i,n=.1,r=1){je(e,Ga(t,n),Le(i)),Ze(e,r)}function Qx(e,t,i,n=.05,r=.05,a=1){je(e,qa(t,r),$a(i,n)),Ze(e,a)}function e0(e,t,i,n=.05,r=.05,a=1){je(e,Ga(t,r),$a(i,n)),Ze(e,a)}function t0(e,t,i,n=.05,r=.05,a=1){je(e,qa(t,r),Ua(i,n)),Ze(e,a)}function i0(e,t,i,n=.05,r=.05,a=1){je(e,Ga(t,r),Ua(i,n)),Ze(e,a)}function je(e,t,i){e&&e.position?typeof e.position.set=="function"?e.position.set(t,i):(e.position.x=t,e.position.y=i):e&&(e.x=t,e.y=i)}function Ze(e,t){t!==1&&e&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(t,t):e.scale.x!==void 0&&e.scale.y!==void 0&&(e.scale.x=t,e.scale.y=t))}var ti={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function n0(e){return e&&ti[e]?JSON.parse(JSON.stringify(ti[e])):JSON.parse(JSON.stringify(X))}function Zn(e){Object.keys(e).forEach(t=>{let i=t;X[i]&&e[i]&&Object.assign(X[i],e[i])}),console.log("Config applied:",e)}function r0(e,t){let i=e/t;i>1.6?(Zn(ti.wide),console.log("Applied WIDE config for ratio:",i)):i<.7?(Zn(ti.tall),console.log("Applied TALL config for ratio:",i)):i>.8&&i<1.2?(Zn(ti.square),console.log("Applied SQUARE config for ratio:",i)):(Zn(ti.default),console.log("Applied DEFAULT config for ratio:",i))}if(typeof window!="undefined"){let e=window;e.configPresets=ti,e.resolveAnchorVec2=e.resolveAnchorVec2||Ha,e.resolveScreenAnchorPoint=e.resolveScreenAnchorPoint||Jn,e.resolveScreenRatioPoint=e.resolveScreenRatioPoint||Qn}var we=null;function a0(e,t,i,n,r,a={}){var z,T,D,$,ue,V,se,oe,me,bt,ii,er,N,Be,Je,mt,Qe,zt,ni,ri,et,ai,vt,tr,ir,Wl,Yl,Vl,Kl,Xl,Zl,Jl,Ql,ec,tc,ic,nc;let s=(z=a.enableDebugLogs)!=null?z:!1;s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== STARTING LAYOUT CALCULATION ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Screen dimensions:",{width:n.width,height:n.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Time:",i),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Options:",a));let{mainContainer:o,label:c,background:l,backgroundTexture:d,app:u}=e;if(!u||!u.renderer){s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] \u274C No app or renderer, skipping layout");return}s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] App renderer dimensions:",{width:u.renderer.width,height:u.renderer.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] App screen dimensions:",{width:u.screen.width,height:u.screen.height}));let p=n.width,f=n.height;s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Base dimensions:",{baseWidth:p,baseHeight:f});let b=p*X.layout.screen_scale_x,h=f*X.layout.screen_scale_y,g=p/2,m=t.engine.runtime||{},v=m.layout||{};s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug config:",{screen_scale_x:X.layout.screen_scale_x,screen_scale_y:X.layout.screen_scale_y}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Calculated dimensions:",{width:b,height:h,midX:g}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Engine runtime:",m),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Layout config:",v));let y=v.design_width_portrait||400,x=b/y;x=Math.min(x,1.15);let w=x*((T=X.engine.scale)!=null?T:1),C=(D=a.skipMainContainerTransform)!=null?D:!1;!C&&o&&o.scale&&(typeof o.scale.set=="function"?o.scale.set(w):(o.scale.x=w,o.scale.y=w));let k=($=v.main_container_anchor)!=null?$:"center",E=(ue=v.main_container_position_ratio)!=null?ue:{x:.5,y:.5},P=(V=v.main_container_offset)!=null?V:{x:0,y:0},M=v.main_container_position_ratio?Qn(p,f,E):Jn(p,f,k),_=M.x+P.x+X.layout.position_offset.x,S=M.y+P.y+X.layout.position_offset.y;if(!C&&o&&o.position&&(typeof o.position.set=="function"?o.position.set(_,S):(o.position.x=_,o.position.y=S)),r&&(o!=null&&o.toLocal))for(let[pe,fe]of t.objects.entries()){let Z=fe==null?void 0:fe.transform;if(!Z||((se=Z.position_mode)!=null?se:"static")!=="static")continue;let q=(oe=r.get)==null?void 0:oe.call(r,pe),Fe=((me=q==null?void 0:q.getDisplayObject)==null?void 0:me.call(q))||(q==null?void 0:q.pixiObject)||q;if(!Fe||Fe.parent!==o)continue;let Ji=Z.position_ratio!=null?Qn(p,f,Z.position_ratio):Jn(p,f,(bt=Z.anchor)!=null?bt:"center"),nr=o.toLocal(new Nx(Ji.x,Ji.y)),rr=(ii=Z.position)!=null?ii:{x:0,y:0},Qi=nr.x+rr.x,jt=nr.y+rr.y;typeof(q==null?void 0:q.setPosition)=="function"?q.setPosition(Qi,jt):(je(Fe,Qi,jt),(er=q==null?void 0:q.transform)!=null&&er.position&&(q.transform.position.x=Qi,q.transform.position.y=jt))}let L=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,O=((L==null?void 0:L.buildMode)||(typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"dev"))==="dev";if(X.layout.debug_rect_visible&&O){(!we||we.parent!==u.stage)&&(we==null||we.destroy(),we=new Fx,we.zIndex=9999,u.stage.addChild(we)),we.clear();let pe=X.layout.debug_rect_scale_x,fe=X.layout.debug_rect_scale_y,Z=(p-4)*pe,Re=(f-4)*fe,q=(p-Z)/2,Fe=(f-Re)/2;s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== DEBUG RECT POSITIONING ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect calculations:",{baseWidth:p,baseHeight:f,rectW:Z,rectH:Re,offsetX:q,offsetY:Fe}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect final position:",{x:2+q,y:2+Fe,width:Z,height:Re})),we.rect(2+q,2+Fe,Z,Re).stroke({width:X.layout.debug_rect_thickness,color:X.layout.debug_rect_color})}else we&&(we.destroy(),we=null);let A=((N=e.label)==null?void 0:N.config)||t.objects.get("label_1")||t.objects.get("ui_tutorial_1");if(c&&c.position&&A){let pe=(Be=A==null?void 0:A.render)==null?void 0:Be.anchor,fe=(mt=(Je=A==null?void 0:A.transform)==null?void 0:Je.anchor)!=null?mt:"center",Z=(Qe=A==null?void 0:A.transform)==null?void 0:Qe.position_ratio,Re=((zt=A==null?void 0:A.transform)==null?void 0:zt.offset)||{x:0,y:0};Gl(c,p,f,{anchor:fe,positionRatio:Z,offset:{x:Re.x*w,y:Re.y*w},renderAnchor:pe})}if(c&&c.alpha>0){let pe=1+Math.sin(i*X.engine.label_pulse_speed)*X.engine.label_pulse_intensity,fe=(ri=(ni=A==null?void 0:A.transform)==null?void 0:ni.scale)!=null?ri:1,Z=pe*w*fe;c.scale&&(typeof c.scale.set=="function"?c.scale.set(Z):(c.scale.x=Z,c.scale.y=Z))}if(s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== BACKGROUND POSITIONING ====="),l){s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background object exists:",!!l),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background type:",(et=l.constructor)==null?void 0:et.name)),l.alpha=((vt=(ai=m.background)==null?void 0:ai.alpha)!=null?vt:.98)*X.engine.background_alpha,s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background alpha set to:",l.alpha);let pe=t.objects.get("background_1");s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background config:",pe);let fe=(pe==null?void 0:pe.transform)||{};s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background transform:",fe);let Z=fe.offset||{x:0,y:0},Re=((ir=(tr=m.background)==null?void 0:tr.offset_y)!=null?ir:0)+X.engine.background_offset_y,q=(Yl=(Wl=pe==null?void 0:pe.render)==null?void 0:Wl.anchor)!=null?Yl:{x:.5,y:.5},Fe=(Vl=fe.anchor)!=null?Vl:"center",Ji=fe.position_ratio;if(s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background positioning params:",{bgOffset:Z,bgRuntimeOffsetY:Re,bgRenderAnchor:q,bgScreenAnchor:Fe,bgPositionRatio:Ji,baseWidth:p,baseHeight:f,finalScale:w}),Gl(l,p,f,{anchor:Fe,positionRatio:Ji,offset:{x:Z.x*w,y:Z.y*w+Re},renderAnchor:q}),s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background position after applyScreenAnchor:",{x:l.x,y:l.y,scaleX:(Kl=l.scale)==null?void 0:Kl.x,scaleY:(Xl=l.scale)==null?void 0:Xl.y,anchorX:(Zl=l.anchor)==null?void 0:Zl.x,anchorY:(Jl=l.anchor)==null?void 0:Jl.y,pivotX:(Ql=l.pivot)==null?void 0:Ql.x,pivotY:(ec=l.pivot)==null?void 0:ec.y,width:l.width,height:l.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background texture dimensions:",{textureWidth:d==null?void 0:d.width,textureHeight:d==null?void 0:d.height})),d){let nr=Math.max(b/d.width,h/d.height),rr=(ic=(tc=m.background)==null?void 0:tc.scale_multiplier)!=null?ic:1.05,Qi=(nc=fe.scale)!=null?nc:1,jt=nr*rr*X.engine.background_scale*Qi;l.scale&&(typeof l.scale.set=="function"?l.scale.set(jt):(l.scale.x=jt,l.scale.y=jt))}else l&&typeof l.clear=="function"&&(l.clear(),l.rect(-b/2,-h/2,b,h).fill({color:1444375}))}}function s0(e){var o,c,l;let{setState:t,updateLabelAlpha:i,updateHandAlpha:n,config:r,states:a}=e,s=((c=(o=r.engine)==null?void 0:o.runtime)==null?void 0:c.timeline)||{};t(a.showHook),setTimeout(()=>{i(1),n(1),t(a.waitInput),console.log("[GAME] \u23F3 Game ready for user input - tutorial shown")},(l=s.tutorial_delay_ms)!=null?l:1500)}export{Pc as a,Fl as b,Oa as c,Da as d,za as e,Vn as f,Ex as g,Sx as h,Ax as i,Cx as j,Tl as k,Rx as l,Mt as m,Hl as n,Kn as o,Xn as p,Px as q,zx as r,jx as s,Bx as t,$l as u,Fa as v,$x as w,ql as x,Ha as y,Jn as z,Qn as A,Gl as B,a0 as C,s0 as D,Ic as E,Mc as F,ns as G,ci as H,g0 as I,ka as J,wl as K,Ih as L,Sl as M,Z_ as N,J_ as O,Xe as P,pt as Q};
1444
+ z-index: ${v};
1445
+ opacity: ${b};
1446
+ `,t.appendChild(y);let x;try{x=d.loadAnimation({container:y,renderer:a.renderer||"svg",loop:(se=a.loop)!=null?se:!1,autoplay:(oe=a.autoplay)!=null?oe:!0,animationData:l})}catch(be){return y.parentNode&&y.parentNode.removeChild(y),console.warn(`[LottieOverlay] Failed to start animation: ${e}`,be),null}a.speed!==void 0&&x.setSpeed(a.speed);let w=()=>{x.destroy(),y.parentNode&&y.parentNode.removeChild(y)};return a.loop||x.addEventListener("complete",w),{animation:x,cleanup:w}}var $l=class{constructor(t,i,n){this.systems=[];this.totalTime=0;this.context=null;this.root=t,this.config=i,this.destinationUrl=n}async createApp(t){if(this.context)return{app:this.app,gameObjectManager:this.gameObjectManager};let{app:i,stage:n}=await Hl(this.root,{background:t.background_color,text:t.text_color,primary:t.cta_background,cta_text:t.cta_text});this.app=i,this.stage=n,this.gameObjectManager=new Kn(this.config),this.stage.eventMode="passive",this.stage.interactive=!1,this.stage.interactiveChildren=!0,this.stage.sortableChildren=!0,this.context={app:this.app,stage:this.stage,config:this.config,gameObjectManager:this.gameObjectManager,destinationUrl:this.destinationUrl,root:this.root,engine:this};for(let r of this.systems)r.setContext(this.context);return{app:this.app,gameObjectManager:this.gameObjectManager}}async initSystems(){if(!this.context)throw new Error("[GameEngine] createApp() must be called before initSystems()");for(let t of this.systems)t.init&&await t.init()}async init(t){return await this.createApp(t),await this.initSystems(),{app:this.app,gameObjectManager:this.gameObjectManager}}registerSystems(t){this.systems.push(...t)}async start(){for(let t of this.systems)t.onStart&&await t.onStart();this.app.ticker.add(this.update.bind(this)),window.addEventListener("handler-preview:screen",t=>{let{width:i,height:n}=t.detail;this.resize(i,n)})}update(t){let i=t.deltaTime/60;this.totalTime+=i;for(let n of this.systems)n.update&&n.update(i,this.totalTime)}resize(t,i){for(let n of this.systems)n.onResize&&n.onResize(t,i)}updateConfig(t){this.config=t;for(let i of this.systems)i.context.config=t,i.onConfigUpdate&&i.onConfigUpdate(t)}destroy(){for(let t of this.systems)t.onDestroy&&t.onDestroy();this.app.ticker.remove(this.update.bind(this)),this.app.destroy(!0,{children:!0,texture:!1})}getApp(){return this.app}getGameObjectManager(){return this.gameObjectManager}getTotalTime(){return this.totalTime}getSystem(t){let i=this.systems.find(n=>n instanceof t);if(!i)throw new Error(`System ${t.name} not found!`);return i}};var Xn=class{setContext(t){this.context=t}};var Zn=class{constructor(){this.config=null}init(t){this.config=t}get(t){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(t)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(t){return this.config?this.config.objects.has(t):!1}};import*as og from"pixi.js";var Ux=og;typeof window!="undefined"&&(window.__basePixi=og);import{Sprite as $x,Text as qx,TextStyle as Gx,Texture as lg}from"pixi.js";var cg=e=>e*Math.PI/180;function Wx(e,t){var s,o,c,l,d;let i=t.ui;if(!(i!=null&&i.text))return null;let n="#ffffff";(s=t.render)!=null&&s.tint&&(n=t.render.tint);let r=new Gx({fontFamily:(o=i.font)!=null?o:"Arial",fontSize:(c=i.fontSize)!=null?c:16,fill:n,align:(l=i.align)!=null?l:"center",letterSpacing:(d=i.letterSpacing)!=null?d:0}),a=new qx({text:i.text,style:r});return a.label=e,a}function Yx(e){var d,u,p,f,m,h,g,v,b,y;let{stage:t,mainContainer:i,activeConfig:n,gameObjectManager:r,allowList:a,denyList:s}=e,o={},c={},l={};i.sortableChildren=!0;for(let[x,w]of n.objects.entries()){if(s!=null&&s.has(x)||a&&!a.has(x)||(w==null?void 0:w.enabled)===!1)continue;let A=(u=(d=w==null?void 0:w.render)==null?void 0:d.asset)==null?void 0:u.path,T=(f=(p=w==null?void 0:w.render)==null?void 0:p.asset)==null?void 0:f.type,E=!!(A&&T==="image"),M=!!((m=w==null?void 0:w.ui)!=null&&m.text),I=M?(h=w==null?void 0:w.ui)==null?void 0:h.renderMode:void 0,_;if(I==="png"&&E?_="png":I==="text"&&M?_="text":E?_="png":M?_="text":_="skip",_!=="skip"){if(_==="text"){let S=Wx(x,w);if(!S)continue;let L=w.render;S.alpha=typeof(L==null?void 0:L.alpha)=="number"?L.alpha:1,S.visible=(L==null?void 0:L.visible)!==!1,S.zIndex=typeof(L==null?void 0:L.z_index)=="number"?L.z_index:0,L!=null&&L.anchor&&typeof L.anchor.x=="number"&&typeof L.anchor.y=="number"?S.anchor.set(L.anchor.x,L.anchor.y):S.anchor.set(.5,.5);let R=w.transform,O=(R==null?void 0:R.position)||(R==null?void 0:R.offset);O&&S.position.set((g=O.x)!=null?g:0,(v=O.y)!=null?v:0);let C=typeof(R==null?void 0:R.scale)=="number"?R.scale:1;S.scale.set(C,C);let z=typeof(R==null?void 0:R.rotation)=="number"?R.rotation:0;S.rotation=cg(z),S.parent||i.addChild(S);try{r.create(x,S)}catch{}o[x]=S,l[x]=S}else if(_==="png"){let S=He[x]||(typeof lg!="undefined"?lg.EMPTY:void 0),L=new $x(S);L.label=x;let R=w.render;L.alpha=typeof(R==null?void 0:R.alpha)=="number"?R.alpha:1,L.visible=(R==null?void 0:R.visible)!==!1,L.zIndex=typeof(R==null?void 0:R.z_index)=="number"?R.z_index:0,R!=null&&R.anchor&&typeof R.anchor.x=="number"&&typeof R.anchor.y=="number"&&L.anchor.set(R.anchor.x,R.anchor.y);let O=w.transform,C=(O==null?void 0:O.position)||(O==null?void 0:O.offset);C&&L.position.set((b=C.x)!=null?b:0,(y=C.y)!=null?y:0);let z=typeof(O==null?void 0:O.scale)=="number"?O.scale:1;L.scale.set(z,z);let k=typeof(O==null?void 0:O.rotation)=="number"?O.rotation:0;L.rotation=cg(k),L.parent||i.addChild(L);try{r.create(x,L)}catch{}o[x]=L,c[x]=L}}}return i.parent||t.addChild(i),{objects:o,sprites:c,texts:l}}var ql=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Zn}init(t,i){this.registry.init(t),this.app=i}updateConfig(t){this.registry.init(t),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let i=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));if(i.length===0)return;let n=async r=>{r.length&&(console.log("[Assets] Loading objects:",r),await Promise.all(r.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let c=await It.create(a,s,this.app);this.instanceCache.set(a,c),console.log("[Assets] Loaded object:",a,(o=c==null?void 0:c.constructor)==null?void 0:o.name)}catch(c){console.error("[Assets] Failed to load object:",a,c)}})))};return this.readyPromise=(async()=>{await n(i);let r=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));r.length>0&&(console.warn("[Assets] Retrying missing assets:",r),await n(r)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(t){let i=this.registry.get(t);if(i){let n=await It.create(t,i,this.app);this.instanceCache.set(t,n)}}get(t){return this.instanceCache.get(t)}},dg=new ql,Vx=new Proxy(dg,{get(e,t){if(t in e&&typeof e[t]=="function")return e[t].bind(e);if(e.get(t))return e.get(t)}});function Kx(e,t){dg.init(e,t)}var Gl=class extends Xn{async init(){Ka(this.context.config,this.context.app),await He.ready(),console.log("[AssetSystem] All assets preloaded and ready")}async onStart(){}onConfigUpdate(){console.log("[AssetSystem] Config updated - systems will refresh textures")}};import{Graphics as Xx,Point as Zx}from"pixi.js";var gt={width:400,height:600,designWidth:400,scaleFactor:1},Ha={scale:1,position:1},Ua=[];function Jx(e,t,i,n,r,a,s){Ua.push({element:e,originalScale:a,positionHelper:t,heightPercent:r}),t(e,i,n,r,a,s,!1)}function Qx(){Ua.forEach(({element:e,originalScale:t,positionHelper:i,heightPercent:n})=>{let r=t*gt.scaleFactor;i(e,gt.width,gt.height,n,r,!0,!1)})}function e0(){Ua.length=0,console.log("[LAYOUT] Cleared all responsive elements")}function Wl(e,t){console.log(`[SCREEN] updateScreenState called: ${e}x${t}`),gt.width=e,gt.height=t,gt.scaleFactor=Math.min(e/gt.designWidth,1.15),Ha.scale=gt.scaleFactor,Ha.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Ha.scale.toFixed(3)}`),Qx()}var X={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function t0(e,t,i){let n=X[e];n&&n[t]!==void 0&&(n[t]=i,console.log(`Updated ${e}.${t} = ${i}`))}function i0(){return X}var n0={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Na(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function $a(e,t={x:.5,y:.5}){var i;if(Array.isArray(e))return{x:Na(e[0],t.x),y:Na(e[1],t.y)};if(e&&typeof e=="object"){let n=e;return{x:Na(n.x,t.x),y:Na(n.y,t.y)}}if(typeof e=="string"){let n=e.trim().toLowerCase();return(i=n0[n])!=null?i:t}return t}function Qn(e,t,i,n={}){var f,m,h,g,v,b;let r=$a(i),a=(f=n.inset)!=null?f:{},s=(m=n.padding)!=null?m:{x:0,y:0},o=((h=a.left)!=null?h:0)+s.x,c=((g=a.right)!=null?g:0)+s.x,l=((v=a.top)!=null?v:0)+s.y,d=((b=a.bottom)!=null?b:0)+s.y,u=Math.max(0,e-o-c),p=Math.max(0,t-l-d);return{x:o+u*r.x,y:l+p*r.y}}function er(e,t,i,n={}){var h,g,v,b,y,x;let r=(h=n.inset)!=null?h:{},a=(g=n.padding)!=null?g:{x:0,y:0},s=((v=r.left)!=null?v:0)+a.x,o=((b=r.right)!=null?b:0)+a.x,c=((y=r.top)!=null?y:0)+a.y,l=((x=r.bottom)!=null?x:0)+a.y,d=Math.max(0,e-s-o),u=Math.max(0,t-c-l),p=$a(i,{x:.5,y:.5}),f=Math.min(Math.max(p.x,0),1),m=Math.min(Math.max(p.y,0),1);return{x:s+d*f,y:c+u*m}}function Yl(e,t,i,n={}){var d,u,p;if(!e)return;let r=n.positionRatio?er(t,i,n.positionRatio,{inset:n.inset,padding:n.screenPadding}):Qn(t,i,n.anchor,{inset:n.inset,padding:n.screenPadding}),a=(d=n.offset)!=null?d:{x:0,y:0},s=r.x+a.x,o=r.y+a.y;e.anchor&&n.renderAnchor&&e.anchor.set(n.renderAnchor.x,n.renderAnchor.y),je(e,s,o);let c=(u=n.scale)!=null?u:1,l=(p=n.scaleMultiplier)!=null?p:1;(n.scale!==void 0||n.scaleMultiplier!==void 0)&&Ze(e,c*l)}if(typeof window!="undefined"){let e=window.innerWidth,t=window.innerHeight,i=()=>{let n=window.innerWidth,r=window.innerHeight;(n!==e||r!==t)&&(e=n,t=r,Wl(n,r))};window.addEventListener("resize",i),window.addEventListener("orientationchange",()=>{setTimeout(i,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",i),window.mraid.addEventListener("sizeChange",i)),Wl(window.innerWidth,window.innerHeight),window.updateDebugConfig=t0,window.getDebugConfig=i0,window.copyConfig=h0,window.applyConfig=Jn,window.applyConfigForRatio=g0,window.positionAtBottom=ug,window.positionAtTop=s0,window.positionAtCenter=o0,window.positionAtLeft=l0,window.positionAtRight=c0,window.positionAtBottomLeft=d0,window.positionAtBottomRight=u0,window.positionAtTopLeft=p0,window.positionAtTopRight=f0,window.applyPositionContract=a0,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function qa(e,t,i=0){return e*t+i}function Ga(e,t,i=0){return e*(1-t)+i}function Wa(e,t,i=0){return e*t+i}function Ya(e,t,i=0){return e*(1-t)+i}function Le(e,t=0){return e/2+t}function r0(e,t){return e*t}function a0(e,t,i,n){var s,o,c,l,d,u,p,f,m,h,g,v,b,y,x,w,A,T,E,M;let r=0,a=0;switch(n.type){case"top":r=Le(t,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),a=qa(i,n.percent,(l=(c=n.offset)==null?void 0:c.y)!=null?l:0);break;case"bottom":r=Le(t,(u=(d=n.offset)==null?void 0:d.x)!=null?u:0),a=Ga(i,n.percent,(f=(p=n.offset)==null?void 0:p.y)!=null?f:0);break;case"left":r=Wa(t,n.percent,(h=(m=n.offset)==null?void 0:m.x)!=null?h:0),a=Le(i,(v=(g=n.offset)==null?void 0:g.y)!=null?v:0);break;case"right":r=Ya(t,n.percent,(y=(b=n.offset)==null?void 0:b.x)!=null?y:0),a=Le(i,(w=(x=n.offset)==null?void 0:x.y)!=null?w:0);break;case"center":r=Le(t,(T=(A=n.offset)==null?void 0:A.x)!=null?T:0),a=Le(i,(M=(E=n.offset)==null?void 0:E.y)!=null?M:0);break}e.position?e.position.set(r,a):(e.x=r,e.y=a),n.scale!==void 0&&n.scale!==1&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(n.scale,n.scale):(e.scale.x=n.scale,e.scale.y=n.scale))}function ug(e,t,i,n=.2,r=1,a=!0,s=!1){let o=r0(i,n),c=Ga(i,n/2);je(e,Le(t),c);let l=a?r*gt.scaleFactor:r;Ze(e,l),s&&!Ua.find(d=>d.element===e)&&Jx(e,ug,t,i,n,r,a)}function s0(e,t,i,n=.1,r=1){je(e,Le(t),qa(i,n)),Ze(e,r)}function o0(e,t,i,n=0,r=0,a=1){je(e,Le(t,n),Le(i,r)),Ze(e,a)}function l0(e,t,i,n=.1,r=1){je(e,Wa(t,n),Le(i)),Ze(e,r)}function c0(e,t,i,n=.1,r=1){je(e,Ya(t,n),Le(i)),Ze(e,r)}function d0(e,t,i,n=.05,r=.05,a=1){je(e,Wa(t,r),Ga(i,n)),Ze(e,a)}function u0(e,t,i,n=.05,r=.05,a=1){je(e,Ya(t,r),Ga(i,n)),Ze(e,a)}function p0(e,t,i,n=.05,r=.05,a=1){je(e,Wa(t,r),qa(i,n)),Ze(e,a)}function f0(e,t,i,n=.05,r=.05,a=1){je(e,Ya(t,r),qa(i,n)),Ze(e,a)}function je(e,t,i){e&&e.position?typeof e.position.set=="function"?e.position.set(t,i):(e.position.x=t,e.position.y=i):e&&(e.x=t,e.y=i)}function Ze(e,t){t!==1&&e&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(t,t):e.scale.x!==void 0&&e.scale.y!==void 0&&(e.scale.x=t,e.scale.y=t))}var ti={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function h0(e){return e&&ti[e]?JSON.parse(JSON.stringify(ti[e])):JSON.parse(JSON.stringify(X))}function Jn(e){Object.keys(e).forEach(t=>{let i=t;X[i]&&e[i]&&Object.assign(X[i],e[i])}),console.log("Config applied:",e)}function g0(e,t){let i=e/t;i>1.6?(Jn(ti.wide),console.log("Applied WIDE config for ratio:",i)):i<.7?(Jn(ti.tall),console.log("Applied TALL config for ratio:",i)):i>.8&&i<1.2?(Jn(ti.square),console.log("Applied SQUARE config for ratio:",i)):(Jn(ti.default),console.log("Applied DEFAULT config for ratio:",i))}if(typeof window!="undefined"){let e=window;e.configPresets=ti,e.resolveAnchorVec2=e.resolveAnchorVec2||$a,e.resolveScreenAnchorPoint=e.resolveScreenAnchorPoint||Qn,e.resolveScreenRatioPoint=e.resolveScreenRatioPoint||er}var we=null;function m0(e,t,i,n,r,a={}){var z,k,D,$,ue,V,se,oe,be,mt,ii,tr,N,Be,Je,bt,Qe,zt,ni,ri,et,ai,vt,ir,nr,Vl,Kl,Xl,Zl,Jl,Ql,ec,tc,ic,nc,rc,ac;let s=(z=a.enableDebugLogs)!=null?z:!1;s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== STARTING LAYOUT CALCULATION ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Screen dimensions:",{width:n.width,height:n.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Time:",i),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Options:",a));let{mainContainer:o,label:c,background:l,backgroundTexture:d,app:u}=e;if(!u||!u.renderer){s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] \u274C No app or renderer, skipping layout");return}s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] App renderer dimensions:",{width:u.renderer.width,height:u.renderer.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] App screen dimensions:",{width:u.screen.width,height:u.screen.height}));let p=n.width,f=n.height;s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Base dimensions:",{baseWidth:p,baseHeight:f});let m=p*X.layout.screen_scale_x,h=f*X.layout.screen_scale_y,g=p/2,v=t.engine.runtime||{},b=v.layout||{};s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug config:",{screen_scale_x:X.layout.screen_scale_x,screen_scale_y:X.layout.screen_scale_y}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Calculated dimensions:",{width:m,height:h,midX:g}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Engine runtime:",v),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Layout config:",b));let y=b.design_width_portrait||400,x=m/y;x=Math.min(x,1.15);let w=x*((k=X.engine.scale)!=null?k:1),A=(D=a.skipMainContainerTransform)!=null?D:!1;!A&&o&&o.scale&&(typeof o.scale.set=="function"?o.scale.set(w):(o.scale.x=w,o.scale.y=w));let T=($=b.main_container_anchor)!=null?$:"center",E=(ue=b.main_container_position_ratio)!=null?ue:{x:.5,y:.5},M=(V=b.main_container_offset)!=null?V:{x:0,y:0},I=b.main_container_position_ratio?er(p,f,E):Qn(p,f,T),_=I.x+M.x+X.layout.position_offset.x,S=I.y+M.y+X.layout.position_offset.y;if(!A&&o&&o.position&&(typeof o.position.set=="function"?o.position.set(_,S):(o.position.x=_,o.position.y=S)),r&&(o!=null&&o.toLocal))for(let[pe,fe]of t.objects.entries()){let Z=fe==null?void 0:fe.transform;if(!Z||((se=Z.position_mode)!=null?se:"static")!=="static")continue;let q=(oe=r.get)==null?void 0:oe.call(r,pe),Fe=((be=q==null?void 0:q.getDisplayObject)==null?void 0:be.call(q))||(q==null?void 0:q.pixiObject)||q;if(!Fe||Fe.parent!==o)continue;let Ji=Z.position_ratio!=null?er(p,f,Z.position_ratio):Qn(p,f,(mt=Z.anchor)!=null?mt:"center"),rr=o.toLocal(new Zx(Ji.x,Ji.y)),ar=(ii=Z.position)!=null?ii:{x:0,y:0},Qi=rr.x+ar.x,jt=rr.y+ar.y;typeof(q==null?void 0:q.setPosition)=="function"?q.setPosition(Qi,jt):(je(Fe,Qi,jt),(tr=q==null?void 0:q.transform)!=null&&tr.position&&(q.transform.position.x=Qi,q.transform.position.y=jt))}let L=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,O=((L==null?void 0:L.buildMode)||(typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"dev"))==="dev";if(X.layout.debug_rect_visible&&O){(!we||we.parent!==u.stage)&&(we==null||we.destroy(),we=new Xx,we.zIndex=9999,u.stage.addChild(we)),we.clear();let pe=X.layout.debug_rect_scale_x,fe=X.layout.debug_rect_scale_y,Z=(p-4)*pe,Re=(f-4)*fe,q=(p-Z)/2,Fe=(f-Re)/2;s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== DEBUG RECT POSITIONING ====="),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect calculations:",{baseWidth:p,baseHeight:f,rectW:Z,rectH:Re,offsetX:q,offsetY:Fe}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Debug rect final position:",{x:2+q,y:2+Fe,width:Z,height:Re})),we.rect(2+q,2+Fe,Z,Re).stroke({width:X.layout.debug_rect_thickness,color:X.layout.debug_rect_color})}else we&&(we.destroy(),we=null);let C=((N=e.label)==null?void 0:N.config)||t.objects.get("label_1")||t.objects.get("ui_tutorial_1");if(c&&c.position&&C){let pe=(Be=C==null?void 0:C.render)==null?void 0:Be.anchor,fe=(bt=(Je=C==null?void 0:C.transform)==null?void 0:Je.anchor)!=null?bt:"center",Z=(Qe=C==null?void 0:C.transform)==null?void 0:Qe.position_ratio,Re=((zt=C==null?void 0:C.transform)==null?void 0:zt.offset)||{x:0,y:0};Yl(c,p,f,{anchor:fe,positionRatio:Z,offset:{x:Re.x*w,y:Re.y*w},renderAnchor:pe})}if(c&&c.alpha>0){let pe=1+Math.sin(i*X.engine.label_pulse_speed)*X.engine.label_pulse_intensity,fe=(ri=(ni=C==null?void 0:C.transform)==null?void 0:ni.scale)!=null?ri:1,Z=pe*w*fe;c.scale&&(typeof c.scale.set=="function"?c.scale.set(Z):(c.scale.x=Z,c.scale.y=Z))}if(s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] ===== BACKGROUND POSITIONING ====="),l){s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background object exists:",!!l),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background type:",(et=l.constructor)==null?void 0:et.name)),l.alpha=((vt=(ai=v.background)==null?void 0:ai.alpha)!=null?vt:.98)*X.engine.background_alpha,s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background alpha set to:",l.alpha);let pe=t.objects.get("background_1");s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background config:",pe);let fe=(pe==null?void 0:pe.transform)||{};s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background transform:",fe);let Z=fe.offset||{x:0,y:0},Re=((nr=(ir=v.background)==null?void 0:ir.offset_y)!=null?nr:0)+X.engine.background_offset_y,q=(Kl=(Vl=pe==null?void 0:pe.render)==null?void 0:Vl.anchor)!=null?Kl:{x:.5,y:.5},Fe=(Xl=fe.anchor)!=null?Xl:"center",Ji=fe.position_ratio;if(s&&console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background positioning params:",{bgOffset:Z,bgRuntimeOffsetY:Re,bgRenderAnchor:q,bgScreenAnchor:Fe,bgPositionRatio:Ji,baseWidth:p,baseHeight:f,finalScale:w}),Yl(l,p,f,{anchor:Fe,positionRatio:Ji,offset:{x:Z.x*w,y:Z.y*w+Re},renderAnchor:q}),s&&(console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background position after applyScreenAnchor:",{x:l.x,y:l.y,scaleX:(Zl=l.scale)==null?void 0:Zl.x,scaleY:(Jl=l.scale)==null?void 0:Jl.y,anchorX:(Ql=l.anchor)==null?void 0:Ql.x,anchorY:(ec=l.anchor)==null?void 0:ec.y,pivotX:(tc=l.pivot)==null?void 0:tc.x,pivotY:(ic=l.pivot)==null?void 0:ic.y,width:l.width,height:l.height}),console.log("\u{1F3AF} [LAYOUT_DEBUGS] Background texture dimensions:",{textureWidth:d==null?void 0:d.width,textureHeight:d==null?void 0:d.height})),d){let rr=Math.max(m/d.width,h/d.height),ar=(rc=(nc=v.background)==null?void 0:nc.scale_multiplier)!=null?rc:1.05,Qi=(ac=fe.scale)!=null?ac:1,jt=rr*ar*X.engine.background_scale*Qi;l.scale&&(typeof l.scale.set=="function"?l.scale.set(jt):(l.scale.x=jt,l.scale.y=jt))}else l&&typeof l.clear=="function"&&(l.clear(),l.rect(-m/2,-h/2,m,h).fill({color:1444375}))}}function b0(e){var o,c,l;let{setState:t,updateLabelAlpha:i,updateHandAlpha:n,config:r,states:a}=e,s=((c=(o=r.engine)==null?void 0:o.runtime)==null?void 0:c.timeline)||{};t(a.showHook),setTimeout(()=>{i(1),n(1),t(a.waitInput),console.log("[GAME] \u23F3 Game ready for user input - tutorial shown")},(l=s.tutorial_delay_ms)!=null?l:1500)}export{Fc as a,Hl as b,za as c,ja as d,Ba as e,Kn as f,Ox as g,Dx as h,zx as i,jx as j,Rl as k,Hx as l,It as m,$l as n,Xn as o,Zn as p,Ux as q,Yx as r,Vx as s,Kx as t,Gl as u,Ha as v,e0 as w,Wl as x,$a as y,Qn as z,er as A,Yl as B,m0 as C,b0 as D,Nc as E,Hc as F,as as G,ci as H,L0 as I,La as J,El as K,Nh as L,Cl as M,fE as N,hE as O,Xe as P,pt as Q};