diff --git a/CHANGELOG.md b/CHANGELOG.md index 4eeeb80c..744745e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -118,6 +118,7 @@ - 계산식에 날짜·숫자 서식을 함께 걸면 원본 값이 바뀌어도 처음 계산된 값이 계속 표시되던 문제를 수정했습니다. - 목록 칸이나 합계 행 안에서 번역 문구가 문장 중간에 들어간 경우 번역되지 않고 원본 키가 그대로 보이던 문제, 그리고 일부 표시 값에 `{{ }}` 기호가 섞여 나오던 문제를 수정했습니다. - 목록 칸이나 합계 행에서 '번역하지 않고 원문 그대로 표시'로 지정한 값에 보이지 않는 특수문자가 함께 출력되던 문제를 수정했습니다. 화면에서는 빈칸이나 깨진 글자로 보였고, 값을 복사해 붙여넣을 때 따라붙었습니다. +- 목록 표·카드의 셀에서 `true`/`false` 같은 값을 직접 쓴 자리가 비어 보이던 문제를 수정했습니다. 같은 값을 표시 조건에 쓰면 정상 동작해서, 같은 작성이 놓인 자리에 따라 갈렸습니다. - 목록 화면에서 글이나 항목을 열어 보고 돌아올 때 보고 있던 페이지·검색어·필터가 사라지던 문제를 화면 엔진 차원에서 함께 수정했습니다. '현재 주소의 조건을 유지한다'고 지정해도 덧붙일 값이 없으면 유지가 아예 동작하지 않아 조건이 통째로 사라지던 동작을 바로잡았습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.) #### 확장·데이터베이스 안정성 diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index d8c3eb32..a9626fc3 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,20 +1,20 @@ -var ET=Object.defineProperty;var _T=(Qt,Xr,Jr)=>Xr in Qt?ET(Qt,Xr,{enumerable:!0,configurable:!0,writable:!0,value:Jr}):Qt[Xr]=Jr;var $=(Qt,Xr,Jr)=>_T(Qt,typeof Xr!="symbol"?Xr+"":Xr,Jr);(function(Qt){"use strict";function Xr(o,e){for(var n=0;na[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Jr(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var td={exports:{}},Ye={};var Vg;function YS(){if(Vg)return Ye;Vg=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),S=Symbol.iterator;function v(N){return N===null||typeof N!="object"?null:(N=S&&N[S]||N["@@iterator"],typeof N=="function"?N:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,x={};function O(N,R,de){this.props=N,this.context=R,this.refs=x,this.updater=de||_}O.prototype.isReactComponent={},O.prototype.setState=function(N,R){if(typeof N!="object"&&typeof N!="function"&&N!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,N,R,"setState")},O.prototype.forceUpdate=function(N){this.updater.enqueueForceUpdate(this,N,"forceUpdate")};function M(){}M.prototype=O.prototype;function T(N,R,de){this.props=N,this.context=R,this.refs=x,this.updater=de||_}var D=T.prototype=new M;D.constructor=T,A(D,O.prototype),D.isPureReactComponent=!0;var z=Array.isArray;function P(){}var q={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function he(N,R,de){var fe=de.ref;return{$$typeof:o,type:N,key:R,ref:fe!==void 0?fe:null,props:de}}function Ee(N,R){return he(N.type,R,N.props)}function be(N){return typeof N=="object"&&N!==null&&N.$$typeof===o}function Ue(N){var R={"=":"=0",":":"=2"};return"$"+N.replace(/[=:]/g,function(de){return R[de]})}var Fe=/\/+/g;function Ge(N,R){return typeof N=="object"&&N!==null&&N.key!=null?Ue(""+N.key):R.toString(36)}function wt(N){switch(N.status){case"fulfilled":return N.value;case"rejected":throw N.reason;default:switch(typeof N.status=="string"?N.then(P,P):(N.status="pending",N.then(function(R){N.status==="pending"&&(N.status="fulfilled",N.value=R)},function(R){N.status==="pending"&&(N.status="rejected",N.reason=R)})),N.status){case"fulfilled":return N.value;case"rejected":throw N.reason}}throw N}function J(N,R,de,fe,xe){var ee=typeof N;(ee==="undefined"||ee==="boolean")&&(N=null);var _e=!1;if(N===null)_e=!0;else switch(ee){case"bigint":case"string":case"number":_e=!0;break;case"object":switch(N.$$typeof){case o:case e:_e=!0;break;case m:return _e=N._init,J(_e(N._payload),R,de,fe,xe)}}if(_e)return xe=xe(N),_e=fe===""?"."+Ge(N,0):fe,z(xe)?(de="",_e!=null&&(de=_e.replace(Fe,"$&/")+"/"),J(xe,R,de,"",function(Ie){return Ie})):xe!=null&&(be(xe)&&(xe=Ee(xe,de+(xe.key==null||N&&N.key===xe.key?"":(""+xe.key).replace(Fe,"$&/")+"/")+_e)),R.push(xe)),1;_e=0;var Be=fe===""?".":fe+":";if(z(N))for(var ke=0;ke>>1,pe=J[te];if(0>>1;tei(de,Me))fei(xe,de)?(J[te]=xe,J[fe]=Me,te=fe):(J[te]=de,J[R]=Me,te=R);else if(fei(xe,Me))J[te]=xe,J[fe]=Me,te=fe;else break e}}return ue}function i(J,ue){var Me=J.sortIndex-ue.sortIndex;return Me!==0?Me:J.id-ue.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();o.unstable_now=function(){return c.now()-d}}var f=[],g=[],m=1,y=null,S=3,v=!1,_=!1,A=!1,x=!1,O=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function D(J){for(var ue=n(g);ue!==null;){if(ue.callback===null)a(g);else if(ue.startTime<=J)a(g),ue.sortIndex=ue.expirationTime,e(f,ue);else break;ue=n(g)}}function z(J){if(A=!1,D(J),!_)if(n(f)!==null)_=!0,P||(P=!0,Ue());else{var ue=n(g);ue!==null&&wt(z,ue.startTime-J)}}var P=!1,q=-1,W=5,he=-1;function Ee(){return x?!0:!(o.unstable_now()-heJ&&Ee());){var te=y.callback;if(typeof te=="function"){y.callback=null,S=y.priorityLevel;var pe=te(y.expirationTime<=J);if(J=o.unstable_now(),typeof pe=="function"){y.callback=pe,D(J),ue=!0;break t}y===n(f)&&a(f),D(J)}else a(f);y=n(f)}if(y!==null)ue=!0;else{var N=n(g);N!==null&&wt(z,N.startTime-J),ue=!1}}break e}finally{y=null,S=Me,v=!1}ue=void 0}}finally{ue?Ue():P=!1}}}var Ue;if(typeof T=="function")Ue=function(){T(be)};else if(typeof MessageChannel<"u"){var Fe=new MessageChannel,Ge=Fe.port2;Fe.port1.onmessage=be,Ue=function(){Ge.postMessage(null)}}else Ue=function(){O(be,0)};function wt(J,ue){q=O(function(){J(o.unstable_now())},ue)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(J){J.callback=null},o.unstable_forceFrameRate=function(J){0>J||125te?(J.sortIndex=Me,e(g,J),n(f)===null&&J===n(g)&&(A?(M(q),q=-1):A=!0,wt(z,Me-te))):(J.sortIndex=pe,e(f,J),_||v||(_=!0,P||(P=!0,Ue()))),J},o.unstable_shouldYield=Ee,o.unstable_wrapCallback=function(J){var ue=S;return function(){var Me=S;S=ue;try{return J.apply(this,arguments)}finally{S=Me}}}})(id)),id}var Wg;function JS(){return Wg||(Wg=1,ad.exports=XS()),ad.exports}var sd={exports:{}},_n={};var Yg;function QS(){if(Yg)return _n;Yg=1;var o=nd();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),sd.exports=QS(),sd.exports}var Qg;function ZS(){if(Qg)return Zs;Qg=1;var o=JS(),e=nd(),n=Jg();function a(t){var r="https://react.dev/errors/"+t;if(1pe||(t.current=te[pe],te[pe]=null,pe--)}function de(t,r){pe++,te[pe]=t.current,t.current=r}var fe=N(null),xe=N(null),ee=N(null),_e=N(null);function Be(t,r){switch(de(ee,r),de(xe,t),de(fe,null),r.nodeType){case 9:case 11:t=(t=r.documentElement)&&(t=t.namespaceURI)?mS(t):0;break;default:if(t=r.tagName,r=r.namespaceURI)r=mS(r),t=yS(r,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}R(fe),de(fe,t)}function ke(){R(fe),R(xe),R(ee)}function Ie(t){t.memoizedState!==null&&de(_e,t);var r=fe.current,s=yS(r,t.type);r!==s&&(de(xe,t),de(fe,s))}function Ct(t){xe.current===t&&(R(fe),R(xe)),_e.current===t&&(R(_e),Ol._currentValue=Me)}var ot,Ot;function vt(t){if(ot===void 0)try{throw Error()}catch(s){var r=s.stack.trim().match(/\n( *(at )?)/);ot=r&&r[1]||"",Ot=-1Xr in Qt?ET(Qt,Xr,{enumerable:!0,configurable:!0,writable:!0,value:Jr}):Qt[Xr]=Jr;var $=(Qt,Xr,Jr)=>_T(Qt,typeof Xr!="symbol"?Xr+"":Xr,Jr);(function(Qt){"use strict";function Xr(o,e){for(var n=0;na[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Jr(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var td={exports:{}},Ye={};var Fg;function WS(){if(Fg)return Ye;Fg=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),S=Symbol.iterator;function v(N){return N===null||typeof N!="object"?null:(N=S&&N[S]||N["@@iterator"],typeof N=="function"?N:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,x={};function O(N,R,de){this.props=N,this.context=R,this.refs=x,this.updater=de||_}O.prototype.isReactComponent={},O.prototype.setState=function(N,R){if(typeof N!="object"&&typeof N!="function"&&N!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,N,R,"setState")},O.prototype.forceUpdate=function(N){this.updater.enqueueForceUpdate(this,N,"forceUpdate")};function M(){}M.prototype=O.prototype;function T(N,R,de){this.props=N,this.context=R,this.refs=x,this.updater=de||_}var D=T.prototype=new M;D.constructor=T,A(D,O.prototype),D.isPureReactComponent=!0;var z=Array.isArray;function P(){}var q={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function he(N,R,de){var fe=de.ref;return{$$typeof:o,type:N,key:R,ref:fe!==void 0?fe:null,props:de}}function Ee(N,R){return he(N.type,R,N.props)}function be(N){return typeof N=="object"&&N!==null&&N.$$typeof===o}function Ue(N){var R={"=":"=0",":":"=2"};return"$"+N.replace(/[=:]/g,function(de){return R[de]})}var Fe=/\/+/g;function Ge(N,R){return typeof N=="object"&&N!==null&&N.key!=null?Ue(""+N.key):R.toString(36)}function wt(N){switch(N.status){case"fulfilled":return N.value;case"rejected":throw N.reason;default:switch(typeof N.status=="string"?N.then(P,P):(N.status="pending",N.then(function(R){N.status==="pending"&&(N.status="fulfilled",N.value=R)},function(R){N.status==="pending"&&(N.status="rejected",N.reason=R)})),N.status){case"fulfilled":return N.value;case"rejected":throw N.reason}}throw N}function J(N,R,de,fe,xe){var ee=typeof N;(ee==="undefined"||ee==="boolean")&&(N=null);var _e=!1;if(N===null)_e=!0;else switch(ee){case"bigint":case"string":case"number":_e=!0;break;case"object":switch(N.$$typeof){case o:case e:_e=!0;break;case m:return _e=N._init,J(_e(N._payload),R,de,fe,xe)}}if(_e)return xe=xe(N),_e=fe===""?"."+Ge(N,0):fe,z(xe)?(de="",_e!=null&&(de=_e.replace(Fe,"$&/")+"/"),J(xe,R,de,"",function(Ie){return Ie})):xe!=null&&(be(xe)&&(xe=Ee(xe,de+(xe.key==null||N&&N.key===xe.key?"":(""+xe.key).replace(Fe,"$&/")+"/")+_e)),R.push(xe)),1;_e=0;var Be=fe===""?".":fe+":";if(z(N))for(var ke=0;ke>>1,pe=J[te];if(0>>1;tei(de,Me))fei(xe,de)?(J[te]=xe,J[fe]=Me,te=fe):(J[te]=de,J[R]=Me,te=R);else if(fei(xe,Me))J[te]=xe,J[fe]=Me,te=fe;else break e}}return ue}function i(J,ue){var Me=J.sortIndex-ue.sortIndex;return Me!==0?Me:J.id-ue.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();o.unstable_now=function(){return c.now()-d}}var f=[],g=[],m=1,y=null,S=3,v=!1,_=!1,A=!1,x=!1,O=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function D(J){for(var ue=n(g);ue!==null;){if(ue.callback===null)a(g);else if(ue.startTime<=J)a(g),ue.sortIndex=ue.expirationTime,e(f,ue);else break;ue=n(g)}}function z(J){if(A=!1,D(J),!_)if(n(f)!==null)_=!0,P||(P=!0,Ue());else{var ue=n(g);ue!==null&&wt(z,ue.startTime-J)}}var P=!1,q=-1,W=5,he=-1;function Ee(){return x?!0:!(o.unstable_now()-heJ&&Ee());){var te=y.callback;if(typeof te=="function"){y.callback=null,S=y.priorityLevel;var pe=te(y.expirationTime<=J);if(J=o.unstable_now(),typeof pe=="function"){y.callback=pe,D(J),ue=!0;break t}y===n(f)&&a(f),D(J)}else a(f);y=n(f)}if(y!==null)ue=!0;else{var N=n(g);N!==null&&wt(z,N.startTime-J),ue=!1}}break e}finally{y=null,S=Me,v=!1}ue=void 0}}finally{ue?Ue():P=!1}}}var Ue;if(typeof T=="function")Ue=function(){T(be)};else if(typeof MessageChannel<"u"){var Fe=new MessageChannel,Ge=Fe.port2;Fe.port1.onmessage=be,Ue=function(){Ge.postMessage(null)}}else Ue=function(){O(be,0)};function wt(J,ue){q=O(function(){J(o.unstable_now())},ue)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(J){J.callback=null},o.unstable_forceFrameRate=function(J){0>J||125te?(J.sortIndex=Me,e(g,J),n(f)===null&&J===n(g)&&(A?(M(q),q=-1):A=!0,wt(z,Me-te))):(J.sortIndex=pe,e(f,J),_||v||(_=!0,P||(P=!0,Ue()))),J},o.unstable_shouldYield=Ee,o.unstable_wrapCallback=function(J){var ue=S;return function(){var Me=S;S=ue;try{return J.apply(this,arguments)}finally{S=Me}}}})(id)),id}var Yg;function XS(){return Yg||(Yg=1,ad.exports=YS()),ad.exports}var sd={exports:{}},_n={};var Xg;function JS(){if(Xg)return _n;Xg=1;var o=nd();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),sd.exports=JS(),sd.exports}var Zg;function QS(){if(Zg)return Zs;Zg=1;var o=XS(),e=nd(),n=Qg();function a(t){var r="https://react.dev/errors/"+t;if(1pe||(t.current=te[pe],te[pe]=null,pe--)}function de(t,r){pe++,te[pe]=t.current,t.current=r}var fe=N(null),xe=N(null),ee=N(null),_e=N(null);function Be(t,r){switch(de(ee,r),de(xe,t),de(fe,null),r.nodeType){case 9:case 11:t=(t=r.documentElement)&&(t=t.namespaceURI)?pS(t):0;break;default:if(t=r.tagName,r=r.namespaceURI)r=pS(r),t=mS(r,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}R(fe),de(fe,t)}function ke(){R(fe),R(xe),R(ee)}function Ie(t){t.memoizedState!==null&&de(_e,t);var r=fe.current,s=mS(r,t.type);r!==s&&(de(xe,t),de(fe,s))}function Ct(t){xe.current===t&&(R(fe),R(xe)),_e.current===t&&(R(_e),Ol._currentValue=Me)}var ot,Ot;function vt(t){if(ot===void 0)try{throw Error()}catch(s){var r=s.stack.trim().match(/\n( *(at )?)/);ot=r&&r[1]||"",Ot=-1)":-1h||U[u]!==X[h]){var ae=` `+U[u].replace(" at new "," at ");return t.displayName&&ae.includes("")&&(ae=ae.replace("",t.displayName)),ae}while(1<=u&&0<=h);break}}}finally{_t=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?vt(s):""}function nt(t,r){switch(t.tag){case 26:case 27:case 5:return vt(t.type);case 16:return vt("Lazy");case 13:return t.child!==r&&r!==null?vt("Suspense Fallback"):vt("Suspense");case 19:return vt("SuspenseList");case 0:case 15:return Oe(t.type,!1);case 11:return Oe(t.type.render,!1);case 1:return Oe(t.type,!0);case 31:return vt("Activity");default:return""}}function sn(t){try{var r="",s=null;do r+=nt(t,s),s=t,t=t.return;while(t);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Mt=Object.prototype.hasOwnProperty,Vt=o.unstable_scheduleCallback,on=o.unstable_cancelCallback,ln=o.unstable_shouldYield,Br=o.unstable_requestPaint,Ft=o.unstable_now,Ci=o.unstable_getCurrentPriorityLevel,na=o.unstable_ImmediatePriority,yn=o.unstable_UserBlockingPriority,On=o.unstable_NormalPriority,rt=o.unstable_LowPriority,jn=o.unstable_IdlePriority,bn=o.log,ra=o.unstable_setDisableYieldValue,sr=null,cn=null;function Tn(t){if(typeof bn=="function"&&ra(t),cn&&typeof cn.setStrictMode=="function")try{cn.setStrictMode(sr,t)}catch{}}var un=Math.clz32?Math.clz32:ce,V=Math.log,se=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(V(t)/se|0)|0}var Z=256,ve=262144,ge=4194304;function we(t){var r=t&42;if(r!==0)return r;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Ae(t,r,s){var u=t.pendingLanes;if(u===0)return 0;var h=0,p=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~p,u!==0?h=we(u):(C&=k,C!==0?h=we(C):s||(s=k&~t,s!==0&&(h=we(s))))):(k=u&~p,k!==0?h=we(k):C!==0?h=we(C):s||(s=u&~t,s!==0&&(h=we(s)))),h===0?0:r!==0&&r!==h&&(r&p)===0&&(p=h&-h,s=r&-r,p>=s||p===32&&(s&4194048)!==0)?r:h}function Ke(t,r){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&r)===0}function Te(t,r){switch(t){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $e(){var t=ge;return ge<<=1,(ge&62914560)===0&&(ge=4194304),t}function Re(t){for(var r=[],s=0;31>s;s++)r.push(t);return r}function et(t,r){t.pendingLanes|=r,r!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function je(t,r,s,u,h,p){var C=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var k=t.entanglements,U=t.expirationTimes,X=t.hiddenUpdates;for(s=C&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Of=/[\n"\\]/g;function Un(t){return t.replace(Of,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function vs(t,r,s,u,h,p,C,k){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),r!=null?C==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+kn(r)):t.value!==""+kn(r)&&(t.value=""+kn(r)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),r!=null?ia(t,C,kn(r)):s!=null?ia(t,C,kn(s)):u!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+kn(k):t.removeAttribute("name")}function Ai(t,r,s,u,h,p,C,k){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),r!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||r!=null)){Uo(t);return}s=s!=null?""+kn(s):"",r=r!=null?""+kn(r):s,k||r===t.value||(t.value=r),t.defaultValue=r}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),Uo(t)}function ia(t,r,s){r==="number"&&ja(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function za(t,r,s,u){if(t=t.options,r){r={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Vo=!1;if(kr)try{var Ti={};Object.defineProperty(Ti,"passive",{get:function(){Vo=!0}}),window.addEventListener("test",Ti,Ti),window.removeEventListener("test",Ti,Ti)}catch{Vo=!1}var Vr=null,Fo=null,ws=null;function Pc(){if(ws)return ws;var t,r=Fo,s=r.length,u,h="value"in Vr?Vr.value:Vr.textContent,p=h.length;for(t=0;t=re),We=" ",dt=!1;function pt(t,r){switch(t){case"keyup":return L.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Or=!1;function Yf(t,r){switch(t){case"compositionend":return Pt(r);case"keypress":return r.which!==32?null:(dt=!0,We);case"textInput":return t=r.data,t===We&&dt?null:t;default:return null}}function Wc(t,r){if(Or)return t==="compositionend"||!I&&pt(t,r)?(t=Pc(),ws=Fo=Vr=null,Or=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:s,offset:r-t};t=u}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=$y(s)}}function Iy(t,r){return t&&r?t===r?!0:t&&t.nodeType===3?!1:r&&r.nodeType===3?Iy(t,r.parentNode):"contains"in t?t.contains(r):t.compareDocumentPosition?!!(t.compareDocumentPosition(r)&16):!1:!1}function Hy(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var r=ja(t.document);r instanceof t.HTMLIFrameElement;){try{var s=typeof r.contentWindow.location.href=="string"}catch{s=!1}if(s)t=r.contentWindow;else break;r=ja(t.document)}return r}function eh(t){var r=t&&t.nodeName&&t.nodeName.toLowerCase();return r&&(r==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||r==="textarea"||t.contentEditable==="true")}var nx=kr&&"documentMode"in document&&11>=document.documentMode,As=null,th=null,nl=null,nh=!1;function jy(t,r,s){var u=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;nh||As==null||As!==ja(u)||(u=As,"selectionStart"in u&&eh(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),nl&&tl(nl,u)||(nl=u,u=Uu(th,"onSelect"),0>=C,h-=C,Fr=1<<32-un(r)+h|s<Qe?(ct=Ne,Ne=null):ct=Ne.sibling;var yt=Q(K,Ne,Y[Qe],oe);if(yt===null){Ne===null&&(Ne=ct);break}t&&Ne&&yt.alternate===null&&r(K,Ne),G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt,Ne=ct}if(Qe===Y.length)return s(K,Ne),ft&&ca(K,Qe),Pe;if(Ne===null){for(;QeQe?(ct=Ne,Ne=null):ct=Ne.sibling;var di=Q(K,Ne,yt.value,oe);if(di===null){Ne===null&&(Ne=ct);break}t&&Ne&&di.alternate===null&&r(K,Ne),G=p(di,G,Qe),mt===null?Pe=di:mt.sibling=di,mt=di,Ne=ct}if(yt.done)return s(K,Ne),ft&&ca(K,Qe),Pe;if(Ne===null){for(;!yt.done;Qe++,yt=Y.next())yt=le(K,yt.value,oe),yt!==null&&(G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt);return ft&&ca(K,Qe),Pe}for(Ne=u(Ne);!yt.done;Qe++,yt=Y.next())yt=ne(Ne,K,Qe,yt.value,oe),yt!==null&&(t&&yt.alternate!==null&&Ne.delete(yt.key===null?Qe:yt.key),G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt);return t&&Ne.forEach(function(CT){return r(K,CT)}),ft&&ca(K,Qe),Pe}function Dt(K,G,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===A&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case v:e:{for(var Pe=Y.key;G!==null;){if(G.key===Pe){if(Pe=Y.type,Pe===A){if(G.tag===7){s(K,G.sibling),oe=h(G,Y.props.children),oe.return=K,K=oe;break e}}else if(G.elementType===Pe||typeof Pe=="object"&&Pe!==null&&Pe.$$typeof===W&&qi(Pe)===G.type){s(K,G.sibling),oe=h(G,Y.props),ll(oe,Y),oe.return=K,K=oe;break e}s(K,G);break}else r(K,G);G=G.sibling}Y.type===A?(oe=ji(Y.props.children,K.mode,oe,Y.key),oe.return=K,K=oe):(oe=ru(Y.type,Y.key,Y.props,null,K.mode,oe),ll(oe,Y),oe.return=K,K=oe)}return C(K);case _:e:{for(Pe=Y.key;G!==null;){if(G.key===Pe)if(G.tag===4&&G.stateNode.containerInfo===Y.containerInfo&&G.stateNode.implementation===Y.implementation){s(K,G.sibling),oe=h(G,Y.children||[]),oe.return=K,K=oe;break e}else{s(K,G);break}else r(K,G);G=G.sibling}oe=ch(Y,K.mode,oe),oe.return=K,K=oe}return C(K);case W:return Y=qi(Y),Dt(K,G,Y,oe)}if(wt(Y))return De(K,G,Y,oe);if(Ue(Y)){if(Pe=Ue(Y),typeof Pe!="function")throw Error(a(150));return Y=Pe.call(Y),qe(K,G,Y,oe)}if(typeof Y.then=="function")return Dt(K,G,uu(Y),oe);if(Y.$$typeof===T)return Dt(K,G,su(K,Y),oe);du(K,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,G!==null&&G.tag===6?(s(K,G.sibling),oe=h(G,Y),oe.return=K,K=oe):(s(K,G),oe=lh(Y,K.mode,oe),oe.return=K,K=oe),C(K)):s(K,G)}return function(K,G,Y,oe){try{ol=0;var Pe=Dt(K,G,Y,oe);return Is=null,Pe}catch(Ne){if(Ne===Ns||Ne===lu)throw Ne;var mt=Xn(29,Ne,null,K.mode);return mt.lanes=oe,mt.return=K,mt}}}var Vi=ob(!0),lb=ob(!1),Wa=!1;function wh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ch(t,r){t=t.updateQueue,r.updateQueue===t&&(r.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Ya(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Xa(t,r,s){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(St&2)!==0){var h=u.pending;return h===null?r.next=r:(r.next=h.next,h.next=r),u.pending=r,r=nu(t),Vy(t,null,s),r}return tu(t,u,r,s),nu(t)}function cl(t,r,s){if(r=r.updateQueue,r!==null&&(r=r.shared,(s&4194048)!==0)){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,Se(t,s)}}function Eh(t,r){var s=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,s===u)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var C={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=C:p=p.next=C,s=s.next}while(s!==null);p===null?h=p=r:p=p.next=r}else h=p=r;s={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:u.shared,callbacks:u.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=r:t.next=r,s.lastBaseUpdate=r}var _h=!1;function ul(){if(_h){var t=$s;if(t!==null)throw t}}function dl(t,r,s,u){_h=!1;var h=t.updateQueue;Wa=!1;var p=h.firstBaseUpdate,C=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var U=k,X=U.next;U.next=null,C===null?p=X:C.next=X,C=U;var ae=t.alternate;ae!==null&&(ae=ae.updateQueue,k=ae.lastBaseUpdate,k!==C&&(k===null?ae.firstBaseUpdate=X:k.next=X,ae.lastBaseUpdate=U))}if(p!==null){var le=h.baseState;C=0,ae=X=U=null,k=p;do{var Q=k.lane&-536870913,ne=Q!==k.lane;if(ne?(lt&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ms&&(_h=!0),ae!==null&&(ae=ae.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var De=t,qe=k;Q=r;var Dt=s;switch(qe.tag){case 1:if(De=qe.payload,typeof De=="function"){le=De.call(Dt,le,Q);break e}le=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=qe.payload,Q=typeof De=="function"?De.call(Dt,le,Q):De,Q==null)break e;le=y({},le,Q);break e;case 2:Wa=!0}}Q=k.callback,Q!==null&&(t.flags|=64,ne&&(t.flags|=8192),ne=h.callbacks,ne===null?h.callbacks=[Q]:ne.push(Q))}else ne={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ae===null?(X=ae=ne,U=le):ae=ae.next=ne,C|=Q;if(k=k.next,k===null){if(k=h.shared.pending,k===null)break;ne=k,k=ne.next,ne.next=null,h.lastBaseUpdate=ne,h.shared.pending=null}}while(!0);ae===null&&(U=le),h.baseState=U,h.firstBaseUpdate=X,h.lastBaseUpdate=ae,p===null&&(h.shared.lanes=0),ti|=C,t.lanes=C,t.memoizedState=le}}function cb(t,r){if(typeof t!="function")throw Error(a(191,t));t.call(r)}function ub(t,r){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var C=J.T,k={};J.T=k,qh(t,!1,r,s);try{var U=h(),X=J.S;if(X!==null&&X(k,U),U!==null&&typeof U=="object"&&typeof U.then=="function"){var ae=dx(U,u);gl(t,r,ae,tr(t))}else gl(t,r,u,tr(t))}catch(le){gl(t,r,{then:function(){},status:"rejected",reason:le},tr())}finally{ue.p=p,C!==null&&k.types!==null&&(C.types=k.types),J.T=C}}function yx(){}function Ph(t,r,s,u){if(t.tag!==5)throw Error(a(476));var h=Bb(t).queue;Pb(t,h,r,Me,s===null?yx:function(){return qb(t),s(u)})}function Bb(t){var r=t.memoizedState;if(r!==null)return r;r={memoizedState:Me,baseState:Me,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:Me},next:null};var s={};return r.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:s},next:null},t.memoizedState=r,t=t.alternate,t!==null&&(t.memoizedState=r),r}function qb(t){var r=Bb(t);r.next===null&&(r=t.alternate.memoizedState),gl(t,r.next.queue,{},tr())}function Bh(){return wn(Ol)}function Gb(){return Jt().memoizedState}function Vb(){return Jt().memoizedState}function bx(t){for(var r=t.return;r!==null;){switch(r.tag){case 24:case 3:var s=tr();t=Ya(s);var u=Xa(r,t,s);u!==null&&(Vn(u,r,s),cl(u,r,s)),r={cache:yh()},t.payload=r;return}r=r.return}}function vx(t,r,s){var u=tr();s={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},wu(t)?Kb(r,s):(s=sh(t,r,s,u),s!==null&&(Vn(s,t,u),Wb(s,r,u)))}function Fb(t,r,s){var u=tr();gl(t,r,s,u)}function gl(t,r,s,u){var h={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(wu(t))Kb(r,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=r.lastRenderedReducer,p!==null))try{var C=r.lastRenderedState,k=p(C,s);if(h.hasEagerState=!0,h.eagerState=k,Yn(k,C))return tu(t,r,h,0),Lt===null&&eu(),!1}catch{}if(s=sh(t,r,h,u),s!==null)return Vn(s,t,u),Wb(s,r,u),!0}return!1}function qh(t,r,s,u){if(u={lane:2,revertLane:wg(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},wu(t)){if(r)throw Error(a(479))}else r=sh(t,s,u,2),r!==null&&Vn(r,t,2)}function wu(t){var r=t.alternate;return t===Je||r!==null&&r===Je}function Kb(t,r){js=gu=!0;var s=t.pending;s===null?r.next=r:(r.next=s.next,s.next=r),t.pending=r}function Wb(t,r,s){if((s&4194048)!==0){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,Se(t,s)}}var pl={readContext:wn,use:yu,useCallback:Kt,useContext:Kt,useEffect:Kt,useImperativeHandle:Kt,useLayoutEffect:Kt,useInsertionEffect:Kt,useMemo:Kt,useReducer:Kt,useRef:Kt,useState:Kt,useDebugValue:Kt,useDeferredValue:Kt,useTransition:Kt,useSyncExternalStore:Kt,useId:Kt,useHostTransitionStatus:Kt,useFormState:Kt,useActionState:Kt,useOptimistic:Kt,useMemoCache:Kt,useCacheRefresh:Kt};pl.useEffectEvent=Kt;var Yb={readContext:wn,use:yu,useCallback:function(t,r){return Mn().memoizedState=[t,r===void 0?null:r],t},useContext:wn,useEffect:Lb,useImperativeHandle:function(t,r,s){s=s!=null?s.concat([t]):null,vu(4194308,4,Ib.bind(null,r,t),s)},useLayoutEffect:function(t,r){return vu(4194308,4,t,r)},useInsertionEffect:function(t,r){vu(4,2,t,r)},useMemo:function(t,r){var s=Mn();r=r===void 0?null:r;var u=t();if(Fi){Tn(!0);try{t()}finally{Tn(!1)}}return s.memoizedState=[u,r],u},useReducer:function(t,r,s){var u=Mn();if(s!==void 0){var h=s(r);if(Fi){Tn(!0);try{s(r)}finally{Tn(!1)}}}else h=r;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=vx.bind(null,Je,t),[u.memoizedState,t]},useRef:function(t){var r=Mn();return t={current:t},r.memoizedState=t},useState:function(t){t=Ih(t);var r=t.queue,s=Fb.bind(null,Je,r);return r.dispatch=s,[t.memoizedState,s]},useDebugValue:zh,useDeferredValue:function(t,r){var s=Mn();return Uh(s,t,r)},useTransition:function(){var t=Ih(!1);return t=Pb.bind(null,Je,t.queue,!0,!1),Mn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,r,s){var u=Je,h=Mn();if(ft){if(s===void 0)throw Error(a(407));s=s()}else{if(s=r(),Lt===null)throw Error(a(349));(lt&127)!==0||mb(u,r,s)}h.memoizedState=s;var p={value:s,getSnapshot:r};return h.queue=p,Lb(bb.bind(null,u,p,t),[t]),u.flags|=2048,Us(9,{destroy:void 0},yb.bind(null,u,p,s,r),null),s},useId:function(){var t=Mn(),r=Lt.identifierPrefix;if(ft){var s=Kr,u=Fr;s=(u&~(1<<32-un(u)-1)).toString(32)+s,r="_"+r+"R_"+s,s=pu++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?p.multiple=!0:u.size&&(p.size=u.size);break;default:p=typeof u.is=="string"?C.createElement(h,{is:u.is}):C.createElement(h)}}p[Ut]=r,p[Rn]=u;e:for(C=r.child;C!==null;){if(C.tag===5||C.tag===6)p.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===r)break e;for(;C.sibling===null;){if(C.return===null||C.return===r)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}r.stateNode=p;e:switch(En(p,h,u),h){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&pa(r)}}return Nt(r),rg(r,r.type,t===null?null:t.memoizedProps,r.pendingProps,s),null;case 6:if(t&&r.stateNode!=null)t.memoizedProps!==u&&pa(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(a(166));if(t=ee.current,Os(r)){if(t=r.stateNode,s=r.memoizedProps,u=null,h=Sn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[Ut]=r,t=!!(t.nodeValue===s||u!==null&&u.suppressHydrationWarning===!0||gS(t.nodeValue,s)),t||Fa(r,!0)}else t=Pu(t).createTextNode(u),t[Ut]=r,r.stateNode=t}return Nt(r),null;case 31:if(s=r.memoizedState,t===null||t.memoizedState!==null){if(u=Os(r),s!==null){if(t===null){if(!u)throw Error(a(318));if(t=r.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[Ut]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Nt(r),t=!1}else s=hh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return r.flags&256?(Qn(r),r):(Qn(r),null);if((r.flags&128)!==0)throw Error(a(558))}return Nt(r),null;case 13:if(u=r.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Os(r),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=r.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[Ut]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Nt(r),h=!1}else h=hh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return r.flags&256?(Qn(r),r):(Qn(r),null)}return Qn(r),(r.flags&128)!==0?(r.lanes=s,r):(s=u!==null,t=t!==null&&t.memoizedState!==null,s&&(u=r.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),p=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(p=u.memoizedState.cachePool.pool),p!==h&&(u.flags|=2048)),s!==t&&s&&(r.child.flags|=8192),xu(r,r.updateQueue),Nt(r),null);case 4:return ke(),t===null&&Ag(r.stateNode.containerInfo),Nt(r),null;case 10:return da(r.type),Nt(r),null;case 19:if(R(Xt),u=r.memoizedState,u===null)return Nt(r),null;if(h=(r.flags&128)!==0,p=u.rendering,p===null)if(h)yl(u,!1);else{if(Wt!==0||t!==null&&(t.flags&128)!==0)for(t=r.child;t!==null;){if(p=hu(t),p!==null){for(r.flags|=128,yl(u,!1),t=p.updateQueue,r.updateQueue=t,xu(r,t),r.subtreeFlags=0,t=s,s=r.child;s!==null;)Fy(s,t),s=s.sibling;return de(Xt,Xt.current&1|2),ft&&ca(r,u.treeForkCount),r.child}t=t.sibling}u.tail!==null&&Ft()>Ou&&(r.flags|=128,h=!0,yl(u,!1),r.lanes=4194304)}else{if(!h)if(t=hu(p),t!==null){if(r.flags|=128,h=!0,t=t.updateQueue,r.updateQueue=t,xu(r,t),yl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!p.alternate&&!ft)return Nt(r),null}else 2*Ft()-u.renderingStartTime>Ou&&s!==536870912&&(r.flags|=128,h=!0,yl(u,!1),r.lanes=4194304);u.isBackwards?(p.sibling=r.child,r.child=p):(t=u.last,t!==null?t.sibling=p:r.child=p,u.last=p)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ft(),t.sibling=null,s=Xt.current,de(Xt,h?s&1|2:s&1),ft&&ca(r,u.treeForkCount),t):(Nt(r),null);case 22:case 23:return Qn(r),xh(),u=r.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(s&536870912)!==0&&(r.flags&128)===0&&(Nt(r),r.subtreeFlags&6&&(r.flags|=8192)):Nt(r),s=r.updateQueue,s!==null&&xu(r,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==s&&(r.flags|=2048),t!==null&&R(Bi),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),r.memoizedState.cache!==s&&(r.flags|=2048),da(en),Nt(r),null;case 25:return null;case 30:return null}throw Error(a(156,r.tag))}function _x(t,r){switch(dh(r),r.tag){case 1:return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 3:return da(en),ke(),t=r.flags,(t&65536)!==0&&(t&128)===0?(r.flags=t&-65537|128,r):null;case 26:case 27:case 5:return Ct(r),null;case 31:if(r.memoizedState!==null){if(Qn(r),r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 13:if(Qn(r),t=r.memoizedState,t!==null&&t.dehydrated!==null){if(r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 19:return R(Xt),null;case 4:return ke(),null;case 10:return da(r.type),null;case 22:case 23:return Qn(r),xh(),t!==null&&R(Bi),t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 24:return da(en),null;case 25:return null;default:return null}}function vv(t,r){switch(dh(r),r.tag){case 3:da(en),ke();break;case 26:case 27:case 5:Ct(r);break;case 4:ke();break;case 31:r.memoizedState!==null&&Qn(r);break;case 13:Qn(r);break;case 19:R(Xt);break;case 10:da(r.type);break;case 22:case 23:Qn(r),xh(),t!==null&&R(Bi);break;case 24:da(en)}}function bl(t,r){try{var s=r.updateQueue,u=s!==null?s.lastEffect:null;if(u!==null){var h=u.next;s=h;do{if((s.tag&t)===t){u=void 0;var p=s.create,C=s.inst;u=p(),C.destroy=u}s=s.next}while(s!==h)}}catch(k){xt(r,r.return,k)}}function Za(t,r,s){try{var u=r.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var p=h.next;u=p;do{if((u.tag&t)===t){var C=u.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,h=r;var U=s,X=k;try{X()}catch(ae){xt(h,U,ae)}}}u=u.next}while(u!==p)}}catch(ae){xt(r,r.return,ae)}}function Sv(t){var r=t.updateQueue;if(r!==null){var s=t.stateNode;try{ub(r,s)}catch(u){xt(t,t.return,u)}}}function wv(t,r,s){s.props=Ki(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(u){xt(t,r,u)}}function vl(t,r){try{var s=t.ref;if(s!==null){switch(t.tag){case 26:case 27:case 5:var u=t.stateNode;break;case 30:u=t.stateNode;break;default:u=t.stateNode}typeof s=="function"?t.refCleanup=s(u):s.current=u}}catch(h){xt(t,r,h)}}function Wr(t,r){var s=t.ref,u=t.refCleanup;if(s!==null)if(typeof u=="function")try{u()}catch(h){xt(t,r,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){xt(t,r,h)}else s.current=null}function Cv(t){var r=t.type,s=t.memoizedProps,u=t.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":s.autoFocus&&u.focus();break e;case"img":s.src?u.src=s.src:s.srcSet&&(u.srcset=s.srcSet)}}catch(h){xt(t,t.return,h)}}function ag(t,r,s){try{var u=t.stateNode;Fx(u,t.type,s,r),u[Rn]=r}catch(h){xt(t,t.return,h)}}function Ev(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&si(t.type)||t.tag===4}function ig(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Ev(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&si(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function sg(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,r):(r=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,r.appendChild(t),s=s._reactRootContainer,s!=null||r.onclick!==null||(r.onclick=Rr));else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode,r=null),t=t.child,t!==null))for(sg(t,r,s),t=t.sibling;t!==null;)sg(t,r,s),t=t.sibling}function Tu(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?s.insertBefore(t,r):s.appendChild(t);else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(Tu(t,r,s),t=t.sibling;t!==null;)Tu(t,r,s),t=t.sibling}function _v(t){var r=t.stateNode,s=t.memoizedProps;try{for(var u=t.type,h=r.attributes;h.length;)r.removeAttributeNode(h[0]);En(r,u,s),r[Ut]=t,r[Rn]=s}catch(p){xt(t,t.return,p)}}var ma=!1,rn=!1,og=!1,Av=typeof WeakSet=="function"?WeakSet:Set,pn=null;function Ax(t,r){if(t=t.containerInfo,Rg=Wu,t=Hy(t),eh(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var u=s.getSelection&&s.getSelection();if(u&&u.rangeCount!==0){s=u.anchorNode;var h=u.anchorOffset,p=u.focusNode;u=u.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var C=0,k=-1,U=-1,X=0,ae=0,le=t,Q=null;t:for(;;){for(var ne;le!==s||h!==0&&le.nodeType!==3||(k=C+h),le!==p||u!==0&&le.nodeType!==3||(U=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(ne=le.firstChild)!==null;)Q=le,le=ne;for(;;){if(le===t)break t;if(Q===s&&++X===h&&(k=C),Q===p&&++ae===u&&(U=C),(ne=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=ne}s=k===-1||U===-1?null:{start:k,end:U}}else s=null}s=s||{start:0,end:0}}else s=null;for(kg={focusedElem:t,selectionRange:s},Wu=!1,pn=r;pn!==null;)if(r=pn,t=r.child,(r.subtreeFlags&1028)!==0&&t!==null)t.return=r,pn=t;else for(;pn!==null;){switch(r=pn,p=r.alternate,t=r.flags,r.tag){case 0:if((t&4)!==0&&(t=r.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),En(p,u,s),p[Ut]=t,Zt(p),u=p;break e;case"link":var C=OS("link","href",h).get(u+(s.href||""));if(C){for(var k=0;kDt&&(C=Dt,Dt=qe,qe=C);var K=Ny(k,qe),G=Ny(k,Dt);if(K&&G&&(ne.rangeCount!==1||ne.anchorNode!==K.node||ne.anchorOffset!==K.offset||ne.focusNode!==G.node||ne.focusOffset!==G.offset)){var Y=le.createRange();Y.setStart(K.node,K.offset),ne.removeAllRanges(),qe>Dt?(ne.addRange(Y),ne.extend(G.node,G.offset)):(Y.setEnd(G.node,G.offset),ne.addRange(Y))}}}}for(le=[],ne=k;ne=ne.parentNode;)ne.nodeType===1&&le.push({element:ne,left:ne.scrollLeft,top:ne.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;ks?32:s,J.T=null,s=gg,gg=null;var p=ri,C=wa;if(fn=0,Vs=ri=null,wa=0,(St&6)!==0)throw Error(a(331));var k=St;if(St|=4,Iv(p.current),Mv(p,p.current,C,s),St=k,Al(0,!1),cn&&typeof cn.onPostCommitFiberRoot=="function")try{cn.onPostCommitFiberRoot(sr,p)}catch{}return!0}finally{ue.p=h,J.T=u,eS(t,r)}}function nS(t,r,s){r=cr(s,r),r=Kh(t.stateNode,r,2),t=Xa(t,r,2),t!==null&&(et(t,2),Yr(t))}function xt(t,r,s){if(t.tag===3)nS(t,t,s);else for(;r!==null;){if(r.tag===3){nS(r,t,s);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ni===null||!ni.has(u))){t=cr(s,t),s=rv(2),u=Xa(r,s,2),u!==null&&(av(s,u,r,t),et(u,2),Yr(u));break}}r=r.return}}function bg(t,r,s){var u=t.pingCache;if(u===null){u=t.pingCache=new Rx;var h=new Set;u.set(r,h)}else h=u.get(r),h===void 0&&(h=new Set,u.set(r,h));h.has(s)||(ug=!0,h.add(s),t=Mx.bind(null,t,r,s),r.then(t,t))}function Mx(t,r,s){var u=t.pingCache;u!==null&&u.delete(r),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,Lt===t&&(lt&s)===s&&(Wt===4||Wt===3&&(lt&62914560)===lt&&300>Ft()-Du?(St&2)===0&&Fs(t,0):dg|=s,Gs===lt&&(Gs=0)),Yr(t)}function rS(t,r){r===0&&(r=$e()),t=Hi(t,r),t!==null&&(et(t,r),Yr(t))}function $x(t){var r=t.memoizedState,s=0;r!==null&&(s=r.retryLane),rS(t,s)}function Nx(t,r){var s=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(r),rS(t,s)}function Ix(t,r){return Vt(t,r)}var Hu=null,Ws=null,vg=!1,ju=!1,Sg=!1,ii=0;function Yr(t){t!==Ws&&t.next===null&&(Ws===null?Hu=Ws=t:Ws=Ws.next=t),ju=!0,vg||(vg=!0,jx())}function Al(t,r){if(!Sg&&ju){Sg=!0;do for(var s=!1,u=Hu;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var p=0;else{var C=u.suspendedLanes,k=u.pingedLanes;p=(1<<31-un(42|t)+1)-1,p&=h&~(C&~k),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,oS(u,p))}else p=lt,p=Ae(u,u===Lt?p:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(p&3)===0||Ke(u,p)||(s=!0,oS(u,p));u=u.next}while(s);Sg=!1}}function Hx(){aS()}function aS(){ju=vg=!1;var t=0;ii!==0&&Wx()&&(t=ii);for(var r=Ft(),s=null,u=Hu;u!==null;){var h=u.next,p=iS(u,r);p===0?(u.next=null,s===null?Hu=h:s.next=h,h===null&&(Ws=s)):(s=u,(t!==0||(p&3)!==0)&&(ju=!0)),u=h}fn!==0&&fn!==5||Al(t),ii!==0&&(ii=0)}function iS(t,r){for(var s=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0k)break;var ae=U.transferSize,le=U.initiatorType;ae&&pS(le)&&(U=U.responseEnd,C+=ae*(U"u"?null:document;function TS(t,r,s){var u=Ys;if(u&&typeof r=="string"&&r){var h=Un(r);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),xS.has(h)||(xS.add(h),t={rel:t,crossOrigin:s,href:r},u.querySelector(h)===null&&(r=u.createElement("link"),En(r,"link",t),Zt(r),u.head.appendChild(r)))}}function rT(t){Ca.D(t),TS("dns-prefetch",t,null)}function aT(t,r){Ca.C(t,r),TS("preconnect",t,r)}function iT(t,r,s){Ca.L(t,r,s);var u=Ys;if(u&&t&&r){var h='link[rel="preload"][as="'+Un(r)+'"]';r==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+Un(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+Un(s.imageSizes)+'"]')):h+='[href="'+Un(t)+'"]';var p=h;switch(r){case"style":p=Xs(t);break;case"script":p=Js(t)}pr.has(p)||(t=y({rel:"preload",href:r==="image"&&s&&s.imageSrcSet?void 0:t,as:r},s),pr.set(p,t),u.querySelector(h)!==null||r==="style"&&u.querySelector(kl(p))||r==="script"&&u.querySelector(Dl(p))||(r=u.createElement("link"),En(r,"link",t),Zt(r),u.head.appendChild(r)))}}function sT(t,r){Ca.m(t,r);var s=Ys;if(s&&t){var u=r&&typeof r.as=="string"?r.as:"script",h='link[rel="modulepreload"][as="'+Un(u)+'"][href="'+Un(t)+'"]',p=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=Js(t)}if(!pr.has(p)&&(t=y({rel:"modulepreload",href:t},r),pr.set(p,t),s.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Dl(p)))return}u=s.createElement("link"),En(u,"link",t),Zt(u),s.head.appendChild(u)}}}function oT(t,r,s){Ca.S(t,r,s);var u=Ys;if(u&&t){var h=Ia(u).hoistableStyles,p=Xs(t);r=r||"default";var C=h.get(p);if(!C){var k={loading:0,preload:null};if(C=u.querySelector(kl(p)))k.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":r},s),(s=pr.get(p))&&Ig(t,s);var U=C=u.createElement("link");Zt(U),En(U,"link",t),U._p=new Promise(function(X,ae){U.onload=X,U.onerror=ae}),U.addEventListener("load",function(){k.loading|=1}),U.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qu(C,r,u)}C={type:"stylesheet",instance:C,count:1,state:k},h.set(p,C)}}}function lT(t,r){Ca.X(t,r);var s=Ys;if(s&&t){var u=Ia(s).hoistableScripts,h=Js(t),p=u.get(h);p||(p=s.querySelector(Dl(h)),p||(t=y({src:t,async:!0},r),(r=pr.get(h))&&Hg(t,r),p=s.createElement("script"),Zt(p),En(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function cT(t,r){Ca.M(t,r);var s=Ys;if(s&&t){var u=Ia(s).hoistableScripts,h=Js(t),p=u.get(h);p||(p=s.querySelector(Dl(h)),p||(t=y({src:t,async:!0,type:"module"},r),(r=pr.get(h))&&Hg(t,r),p=s.createElement("script"),Zt(p),En(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function RS(t,r,s,u){var h=(h=ee.current)?Bu(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(r=Xs(s.href),s=Ia(h).hoistableStyles,u=s.get(r),u||(u={type:"style",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Xs(s.href);var p=Ia(h).hoistableStyles,C=p.get(t);if(C||(h=h.ownerDocument||h,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,C),(p=h.querySelector(kl(t)))&&!p._p&&(C.instance=p,C.state.loading=5),pr.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},pr.set(t,s),p||uT(h,t,s,C.state))),r&&u===null)throw Error(a(528,""));return C}if(r&&u!==null)throw Error(a(529,""));return null;case"script":return r=s.async,s=s.src,typeof s=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Js(s),s=Ia(h).hoistableScripts,u=s.get(r),u||(u={type:"script",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function Xs(t){return'href="'+Un(t)+'"'}function kl(t){return'link[rel="stylesheet"]['+t+"]"}function kS(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function uT(t,r,s,u){t.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=t.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),En(r,"link",s),Zt(r),t.head.appendChild(r))}function Js(t){return'[src="'+Un(t)+'"]'}function Dl(t){return"script[async]"+t}function DS(t,r,s){if(r.count++,r.instance===null)switch(r.type){case"style":var u=t.querySelector('style[data-href~="'+Un(s.href)+'"]');if(u)return r.instance=u,Zt(u),u;var h=y({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Zt(u),En(u,"style",h),qu(u,s.precedence,t),r.instance=u;case"stylesheet":h=Xs(s.href);var p=t.querySelector(kl(h));if(p)return r.state.loading|=4,r.instance=p,Zt(p),p;u=kS(s),(h=pr.get(h))&&Ig(u,h),p=(t.ownerDocument||t).createElement("link"),Zt(p);var C=p;return C._p=new Promise(function(k,U){C.onload=k,C.onerror=U}),En(p,"link",u),r.state.loading|=4,qu(p,s.precedence,t),r.instance=p;case"script":return p=Js(s.src),(h=t.querySelector(Dl(p)))?(r.instance=h,Zt(h),h):(u=s,(h=pr.get(p))&&(u=y({},s),Hg(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Zt(h),En(h,"link",u),t.head.appendChild(h),r.instance=h);case"void":return null;default:throw Error(a(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,qu(u,s.precedence,t));return r.instance}function qu(t,r,s){for(var u=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,p=h,C=0;C title"):null)}function dT(t,r,s){if(s===1||r.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;return r.rel==="stylesheet"?(t=r.disabled,typeof r.precedence=="string"&&t==null):!0;case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function MS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function fT(t,r,s,u){if(s.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Xs(u.href),p=r.querySelector(kl(h));if(p){r=p._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(t.count++,t=Vu.bind(t),r.then(t,t)),s.state.loading|=4,s.instance=p,Zt(p);return}p=r.ownerDocument||r,u=kS(u),(h=pr.get(h))&&Ig(u,h),p=p.createElement("link"),Zt(p);var C=p;C._p=new Promise(function(k,U){C.onload=k,C.onerror=U}),En(p,"link",u),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,r),(r=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=Vu.bind(t),r.addEventListener("load",s),r.addEventListener("error",s))}}var jg=0;function hT(t,r){return t.stylesheets&&t.count===0&&Ku(t,t.stylesheets),0jg?50:800)+r);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function Vu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ku(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Fu=null;function Ku(t,r){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Fu=new Map,r.forEach(gT,t),Fu=null,Vu.call(t))}function gT(t,r){if(!(r.state.loading&4)){var s=Fu.get(t);if(s)var u=s.get(null);else{s=new Map,Fu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),rd.exports=ZS(),rd.exports}var od=ew();const ld=Jr(od),eo=[],tw=50;let cd=!1;function ep(){try{return window.G7Core?.devTools}catch{return}}function Xi(o,e,n){const a=ep();if(cd&&a?.isEnabled?.()){a.trackLog?.(o,e,n);return}cd||(o==="error"||o==="warn")&&eo.length{n.isDebugEnabled()&&console.log(e,...a),Xi("log",o,a)},warn:(...a)=>{n.isDebugEnabled()&&console.warn(e,...a),Xi("warn",o,a)},error:(...a)=>{n.isDebugEnabled()&&console.error(e,...a),Xi("error",o,a)}}}to.getInstance();const Ji=ht("networkResilience"),tp=2,np=300,rp=2e3,nw=15e3;function dd(o){return o?.name==="AbortError"}function ap(o){return dd(o)?!1:o instanceof TypeError}let Nl=!1,ip=!1;function fd(){return Nl}function rw(){typeof window>"u"||ip||(ip=!0,window.addEventListener("pagehide",()=>{Nl=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(Nl=!1)}),window.addEventListener("beforeunload",()=>{Nl=!0}))}function sp(o,e,n){const a=Math.min(e*Math.pow(2,o),n),i=a*.25*(Math.random()*2-1);return Math.max(0,Math.round(a+i))}function op(o){return new Promise(e=>setTimeout(e,o))}async function Il(o,e={}){const{retries:n=tp,baseDelayMs:a=np,maxDelayMs:i=rp,timeoutMs:l=nw,label:c=o,init:d}=e,f=n+1;let g;for(let m=0;m0?new AbortController:null;try{const _={...d};if(v){const x=d?.signal;x&&(x.aborted?v.abort():x.addEventListener("abort",()=>v.abort(),{once:!0})),_.signal=v.signal,S=setTimeout(()=>{y=!0,v.abort()},l)}return await fetch(o,_)}catch(_){if(g=_,dd(_)&&!y||!(y||ap(_)))throw _;if(fd())throw Ji.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw Ji.warn(`All ${f} attempts failed: ${c}`,_),_;const O=sp(m,a,i);Ji.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${O}ms: ${c}`),await op(O)}finally{S!==void 0&&clearTimeout(S)}}throw g}async function lp(o,e={},n={}){const{retries:a=tp,baseDelayMs:i=np,maxDelayMs:l=rp,label:c=o}=n,d=a+1;for(let f=0;f{const i=document.createElement("script");i.src=o,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>n(),i.onerror=()=>a(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const cp="extension",Qi="extensionless",iw="file";function sw(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Qi)return Qi;const n=o?.assetUrlMode;return n===Qi||n===cp?n:o?.settings?.general?.asset_url_mode===Qi?Qi:cp}function up(){return sw()===Qi}function Nr(o,e,n,a){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=up()?i:`${i}.${l}`,d=[];return a&&d.push(a.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Ea(o){if(!o||!up())return o;const e=globalThis?.location?.origin,n=e&&o.startsWith(e)?o.slice(e.length):o;if(!n.startsWith("/api/"))return o;const[a,i]=ow(n),l=a.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return dp(`/api/${l[1]}/bundle/${l[2]}`,i);const c=a.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,g,m]=c,y=`${iw}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${y}${i?`&${i}`:""}`}const d=a.match(/^(\/api\/.+)\.(json|js|css)$/);return d?dp(d[1],i):o}function ow(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function dp(o,e){return e?`${o}?${e}`:o}const Ir=ht("ComponentRegistry");class hn extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="ComponentRegistryError"}}const Wn=class Wn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Wn.instance||(Wn.instance=new Wn),Wn.instance}static createIsolatedInstance(){return new Wn}static resetInstance(){Wn.instance=null}async loadComponents(e,n){if(this.loadingState==="loading")throw new hn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Ir.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Ir.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new hn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Wn.manifestCache.has(e)){this.manifest=Wn.manifestCache.get(e),Ir.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Nr(`/api/templates/${this.templateId}/components`,"json"),a=await Il(n,{label:"components.json"});if(!a.ok)throw new hn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,Wn.manifestCache.set(e,i),Ir.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof hn?e:new hn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new hn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new hn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new hn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const a of n){if(!Array.isArray(e.components[a]))throw new hn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new hn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new hn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i})})}Ir.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new hn(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(n),Ir.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof hn?e:new hn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new hn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const a of n){const i=this.manifest.components[a]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Ir.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,a){this.registry[e]&&Ir.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:a},Ir.log(`[ComponentRegistry] Registered component: ${e} (${a.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,a])=>a.metadata.type===e).map(([n,a])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,a]of Object.entries(this.registry))e[n]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Ir.log("Registry cleared")}};$(Wn,"instance",null),$(Wn,"manifestCache",new Map);let mr=Wn;const fp=ht("TranslationEngine");class hd extends Error{constructor(n,a,i){super(n);$(this,"key");$(this,"locale");this.key=a,this.locale=i,this.name="TranslationError"}}const Hn=class Hn{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return Hn.instance||(Hn.instance=new Hn(e)),Hn.instance}static resetInstance(){Hn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(fp.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,a="/api",i=!1){const l=`${e}:${n}`;if(!i){const c=this.getFromCache(l);if(c)return this.translations.set(l,c),c}try{const c=[];i&&c.push(`_=${Date.now()}`);const d=Nr(`${a}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new hd(`Failed to load translations: ${f.statusText}`,void 0,n);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(c){throw new hd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,a){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,a)),i===d)break;c++}return i.replace(Hn.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(g);return this.translate(f,n,m,a)+y})}translate(e,n,a,i){const l=this.getTranslation(e,n),c=a&&this.cleanParamsStr(a);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:a,locale:i}=n,l=`${a}:${i}`,c=this.translations.get(l);if(c){const d=this.getNestedValue(c,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${a}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,n){const a=n.split(".");let i=e;for(const l of a){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,a,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=a.split(".");let f=c;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(Hn.PARAM_PATTERN);for(const f of d){const[,g,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(S,v)=>l[parseInt(v,10)]);a[g.trim()]=this.resolveParamValue(y.trim(),n)}return a}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&n)try{const l=vd.evaluateExpression(a,n);return String(l??"")}catch(l){return fp.error("Expression evaluation failed:",a,l),""}else{const l=this.getNestedDataValue(n,a);return String(l??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let a=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");a=a.replace(d,String(l))}return a}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(a);for(const a of n)this.cache.delete(a)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$(Hn,"instance",null),$(Hn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(Hn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(Hn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let _a=Hn,gd=null;function lw(o){return gd||(gd=new _a(o)),gd}const hp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:_a,TranslationError:hd,getTranslationEngine:lw},Symbol.toStringTag,{value:"Module"})),Zi=ht("PipeRegistry");function gp(o,e){const n=o.getFullYear(),a=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),c=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",a).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",c).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function cw(o,e="ko"){const a=new Date().getTime()-o.getTime(),i=Math.floor(a/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),g=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:c<24?`${c}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:g<12?`${g}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function pd(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const no={date:{fn:(o,e="YYYY-MM-DD")=>{const n=pd(o);return n?gp(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const n=pd(o);return n?gp(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const n=pd(o);return n?cw(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const n=Number(o);if(isNaN(n))return String(o??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),n.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,n="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,n)=>Array.isArray(o)?Array.isArray(e)?o.filter(a=>{const i=n?a?.[n]:a;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},es=new Map,Si=class Si{static getInstance(){return Si.instance||(Si.instance=new Si),Si.instance}register(e,n,a){if(no[e]){Zi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}es.set(e,{fn:n,description:a}),Zi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(no[e])return Zi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=es.delete(e);return n&&Zi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=no[e];return n?n.fn:es.get(e)?.fn}has(e){return!!no[e]||es.has(e)}execute(e,n,a=[]){const i=this.get(e);if(!i)return Zi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...a)}catch(l){return Zi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,a]of Object.entries(no))e.push({name:n,description:a.description,type:"built-in"});for(const[n,a]of es.entries())e.push({name:n,description:a.description,type:"custom"});return e.sort((n,a)=>n.name.localeCompare(a.name))}clearCustomPipes(){es.clear()}};$(Si,"instance",null);let Hl=Si;Hl.getInstance();function uw(o){const e=o.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const a=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:a,args:[]};const l=[];let c="",d=null,f=0;for(let g=0;g0?i[g-1]:"")==="\\"){c+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){c+=m;continue}if(m==="("||m==="["||m==="{"){f++,c+=m;continue}if(m===")"||m==="]"||m==="}"){f--,c+=m;continue}if(m===","&&f===0){l.push(pp(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(pp(c.trim())),{name:a,args:l}}function pp(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function dw(o){const e=[];let n="",a=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[a-1]:"",c=a0){a--;continue}return null}}return a===0?e.trim():null}function hw(o){const e=[];if(typeof o!="string")return e;for(let n=0;n0){i--;continue}if(o[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:o.slice(n+2,l)}),n=l+1)}return e}function ro(o){return/[?:|&!+\-*/<>=()[\]{}]/.test(o)}function mp(o){const e=typeof o=="string"?o.trim():"";return e===""?"empty":md.has(e)?"literal":$n(e)?"pipe":ro(e)?"expression":"path"}function yp(o,e,n,a){const i=typeof o=="string"?o.trim():"",l=mp(i),c=a?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){a?.onEmpty?.(o);return}if(l==="literal")return md.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,a?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,a?.trackingInfo):n.resolve(i,e,c,a?.trackingInfo)}catch(d){if(a?.onError)return a.onError(d,i);throw d}}const nr="raw:";function bp(o){return o.startsWith(nr)?o.slice(nr.length):o}const ao="﷐",fi="﷑",xa="﷒";function io(o){return ao+o+fi}function jl(o){return o.length>=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function zl(o){return o.includes(ao)}function yd(o){return o.slice(1,-1)}function ts(o){if(typeof o=="string")return io(o);if(Array.isArray(o))return o.map(ts);if(o&&typeof o=="object"){const e={};for(const[n,a]of Object.entries(o))e[n]=ts(a);return e}return o}function Ta(o){if(typeof o=="string")return jl(o)?yd(o):zl(o)||o.includes(fi)?o.split(ao).join("").split(fi).join(""):o;if(Array.isArray(o)){let e=!1;const n=o.map(a=>{const i=Ta(a);return i!==a&&(e=!0),i});return e?n:o}if(o&&typeof o=="object"){if(o.$$typeof!==void 0)return o;let e=!1;const n={};for(const[a,i]of Object.entries(o)){const l=Ta(i);l!==i&&(e=!0),n[a]=l}return e?n:o}return o}const Ra=ht("DataBindingEngine"),gw=/^[$A-Za-z_][$A-Za-z0-9_]*$/,pw=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","arguments","eval"]);function so(){try{return window.G7Core?.devTools}catch{return}}class bd extends Error{constructor(n,a,i){super(n);$(this,"path");$(this,"context");this.path=a,this.context=i,this.name="DataBindingError"}}const ta=class ta{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(S,v)=>{const _=v.trim();let A=!1,x=_;if(_.startsWith(nr)&&(A=!0,x=_.slice(nr.length)),$n(x))try{const q=this.evaluatePipeExpression(x,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),W=this.formatValue(q);return A?io(W):W}catch(q){return Ra.error("Pipe expression evaluation failed:",x,q),S}if(ro(x)){const q=c?.isEnabled()?performance.now():0;try{let W,he=!1;if(l.skipCache)W=this.evaluateExpression(x,d);else{const be=`expr:${x}`,Ue=this.getFromRenderCycleCache(be);Ue!==void 0?(W=Ue,he=!0):(W=this.evaluateExpression(x,d),this.saveToRenderCycleCache(be,W))}if(c?.isEnabled()){const be=performance.now()-q;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:he,duration:be,method:"resolveBindings",skipCache:l.skipCache})}const Ee=this.formatValue(W);return A?io(Ee):Ee}catch(W){return Ra.error("Expression evaluation failed:",x,W),S}}if(l.skipCache){const q=c?.isEnabled()?performance.now():0,W=this.resolvePath(x,d,l);if(c?.isEnabled()){const Ee=performance.now()-q;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:Ee,method:"resolveBindings",skipCache:!0})}const he=this.formatValue(W);return A?io(he):he}const M=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),T=c?.isEnabled()?performance.now():0;let D,z=!1;if(M){const q=this.getFromRenderCycleCache(x);q!==void 0?(D=q,z=!0):(D=this.resolvePath(x,d,l),this.saveToRenderCycleCache(x,D))}else{const q=this.getFromCache(x);q!==void 0?(D=q,z=!0):(D=this.resolvePath(x,d,l),this.saveToCache(x,D))}if(c?.isEnabled()){const q=performance.now()-T;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:z,duration:q,method:"resolveBindings",skipCache:l.skipCache})}const P=this.formatValue(D);return A?io(P):P},g=hw(e);if(g.length===0)return e;let m="",y=0;for(const S of g)m+=e.slice(y,S.start),m+=f(e.slice(S.start,S.end),S.expr),y=S.end;return m+e.slice(y)}evaluatePipeExpression(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[g,m]=dw(e);let y,S=!1;const v=ro(g),_=g.startsWith("_global")||g.startsWith("_local")||g.startsWith("_isolated")||g.startsWith("$parent");if(l.skipCache)v?y=this.evaluateExpression(g,f):y=this.resolvePath(g,f,l);else if(v){const x=this.getFromRenderCycleCache(`expr:${g}`);x!==void 0?(y=x,S=!0):(y=this.evaluateExpression(g,f),this.saveToRenderCycleCache(`expr:${g}`,y))}else if(_){const x=this.getFromRenderCycleCache(g);x!==void 0?(y=x,S=!0):(y=this.resolvePath(g,f,l),this.saveToRenderCycleCache(g,y))}else{const x=this.getFromCache(g);x!==void 0?(y=x,S=!0):(y=this.resolvePath(g,f,l),this.saveToCache(g,y))}const A=fw(y,m);if(c?.isEnabled()){const x=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(A),resultType:this.getResultType(A),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:S,duration:x,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return A}resolve(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,n,l);return c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),y}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let g=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,a,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Ra.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new bd(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,n);return a.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fta.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}resolveObject(e,n,a){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,a)}catch(g){Ra.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,g),i[d]=void 0}}return i}resolveObjectEntry(e,n,a,i,l){if(typeof a=="string"){const c=Aa(a);if(c!==null){const d=c.trim();let f=!1,g=d;d.startsWith(nr)&&(f=!0,g=d.slice(nr.length));let m;switch(mp(g)){case"empty":Ra.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=md.get(g);break;case"pipe":m=this.evaluatePipeExpression(g,i,l);break;case"expression":m=this.evaluateExpression(g,i,l);break;default:m=this.resolve(g,i,l)}e[n]=f&&m!=null?ts(m):m}else e[n]=this.resolveBindings(a,i,l)}else Array.isArray(a)?e[n]=a.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):a&&typeof a=="object"?e[n]=this.resolveObject(a,i,l):e[n]=a}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const a of e)if(n===a||n.startsWith(`${a}.`)||n.startsWith(`${a}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,a]of this.cache.entries())e-a.timestamp>ta.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>ta.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,a){const i=so(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let c=this.preprocessOptionalChaining(e);c=this.preprocessTranslationTokens(c);const d=this.extractVariablesFromExpression(c),f={...n};for(const D of d)D in f||(f[D]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let g=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!g||!m)){const D=window.__templateApp?.getConfig?.();g??(g=D?.templateId),m??(m=D?.locale)}const y=m||"ko";f.$localized=(D,z)=>{if(D==null&&!z)return"";if(typeof D=="string")return D;if(D&&typeof D=="object"&&D[y])return D[y];if(z&&typeof z=="string"){const P=f.$t?f.$t(z):z;if(P&&P!==z)return P}return D&&typeof D=="object"?D.ko||D.en||Object.values(D)[0]||"":D==null?"":String(D)};const S=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>S?.uuid?S.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const z=Math.random()*16|0;return(D==="x"?z:z&3|8).toString(16)});const v={templateId:g||"",locale:y};f.$t=D=>{if(!D||typeof D!="string")return"";try{return _a.getInstance().translate(D,v)}catch(z){return Ra.warn("$t() translation failed for key:",D,z),D}},f.$get=(D,z,P=void 0)=>{if(D==null)return P;const q=Array.isArray(z)?z:[z];if(q.length===0)return D;let W=D;for(const he of q){if(W==null||he==null)return P;W=W[he]}return W??P};const _=[],A=[];for(const[D,z]of Object.entries(f))!gw.test(D)||pw.has(D)||(_.push(D),A.push(z));const x=`${c}|${_.join(",")}`;let O=this.expressionFnCache.get(x);const M=!!O;O||(O=new Function(..._,`return (${c});`),this.expressionFnCache.set(x,O));const T=O(...A);if(i?.isEnabled()){const D=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(T),resultType:this.getResultType(T),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:M,duration:D,method:"evaluateExpression",skipCache:a?.skipCache})}return T}catch(c){throw new Error(`Failed to evaluate expression "${e}": ${c instanceof Error?c.message:String(c)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const n=Object.keys(e);return n.length>20?`{Object(${n.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(n,a,i,l)=>`$t('${l}')`),e.replace(/(?(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),a}extractVariablesFromExpression(e){const n=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),a=/(?{n!==null&&clearTimeout(n),n=setTimeout(()=>{o(...a)},e)})}class yw{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=mw(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(Pl.has(e))return Pl.get(e)??null;let n=null;if(Ul[e])n={...Ul[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,l]=a,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(n={min:c,max:d})}}return Pl.set(e,n),n}getMatchingKey(e,n){const a=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&a.push({key:i,range:l,isPreset:!!Ul[i]})}return a.length===0?null:(a.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const c=i.range.max-i.range.min,d=l.range.max-l.range.min;return c-d}),a[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),Pl.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const hi=new yw,oo=ht("ConditionEvaluator");function bw(o,e,n,a){return yp(bp(o),e,n,{skipCache:!0,onEmpty:()=>{oo.warn(`${a}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function vp(o,e,n){if(!o)return!0;try{const a=Aa(o);let i;if(a!==null?i=bw(a,e,n,"evaluateStringCondition"):i=n.resolveBindings(o,e,{skipCache:!0}),typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(a){return oo.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,a),!1}}function Bl(o,e,n){if(typeof o=="string")return vp(o,e,n);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return oo.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of o.and)if(!Bl(a,e,n))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return oo.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of o.or)if(Bl(a,e,n))return!0;return!1}return oo.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function Sp(o,e,n){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a{rr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${a||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(o,e,{skipCache:!0}),typeof l=="string"){const c=l.toLowerCase().trim();if(c==="false"||c==="0"||c===""||c==="null"||c==="undefined")return!1}return!!l}catch(i){return rr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function ns(o,e,n,a){if(o.if!==void 0)return Ap(o.if,e,n,a);if(o.condition!==void 0)return Ap(o.condition,e,n,a);if(o.conditions===void 0)return!0;const i=o.conditions;try{return vw(i)?Bl(i,e,n):Sw(i)?Sp(i,e,n).matched:(rr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(l){return rr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,l),!1}}function xp(o){if(!o.responsive)return o;const e=hi.getWidth(),n=hi.getMatchingKey(o.responsive,e);if(!n)return o;const a=o.responsive[n];return{...o,props:{...o.props,...a.props},children:a.children??o.children,text:a.text??o.text,if:a.if??o.if,iteration:a.iteration??o.iteration}}function lo(o,e,n,a,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new Dn,c=i?.translationEngine??_a.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=ww(e,i?.componentContext),g=(v,_)=>{if(typeof v=="string")return jl(v)||zl(v)||!/\$t:[a-zA-Z0-9._-]+/.test(v)?v:c.resolveTranslations(v,d,_);if(Array.isArray(v))return v.map(A=>g(A,_));if(v&&typeof v=="object"){const A={};for(const[x,O]of Object.entries(v))A[x]=g(O,_);return A}return v},m=(v,_)=>{if(typeof v=="string"){if(jl(v))return yd(v);if(zl(v)){const x=[],O=v.replace(new RegExp(`${ao}([^${fi}]*)${fi}`,"g"),(T,D)=>(x.push(D),`${xa}${x.length-1}${xa}`));let M=O;return/\$t:[a-zA-Z0-9._-]+/.test(O)&&(M=c.resolveTranslations(O,d,_)),M.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(T,D)=>x[parseInt(D)])}if(v.startsWith("$t:defer:")){const x="$t:"+v.slice(9);return c.resolveTranslations(x,d,_)}if(v.startsWith("$t:"))return c.resolveTranslations(v,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(v)){const x=v.trim();if(!(x.startsWith("{")&&x.endsWith("}")||x.startsWith("[")&&x.endsWith("]"))&&!v.includes("{{"))return c.resolveTranslations(v,d,_)}const A=_p(v);if(A!==null){let x=!1,O=A;A.startsWith(nr)&&(x=!0,O=A.slice(nr.length));let M;if($n(O))try{M=l.evaluatePipeExpression(O,_,{skipCache:!0})}catch(T){rr.warn("renderItemChildren: 파이프 표현식 평가 실패:",T);return}else if(Ep(O))try{M=l.evaluateExpression(O,_)}catch(T){rr.warn("renderItemChildren: 표현식 평가 실패:",T);return}else M=l.resolve(O,_,{skipCache:!0});return x||(M=g(M,_)),x&&M!=null?ts(M):M}if(v.includes("{{")){const x=l.resolveBindings(v,_,{skipCache:!0});return typeof x=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(x)?c.resolveTranslations(x,d,_):x}return v}if(Array.isArray(v))return v.map(A=>m(A,_));if(v&&typeof v=="object"){if(l.isSwitchExpression(v))return l.resolveSwitch(v,_,{skipCache:!0});if(l.isActionDefinition(v))return{...v};const A={};for(const[x,O]of Object.entries(v))A[x]=m(O,_);return A}return v},y=(v,_)=>{if(!v)return{};const A={};for(const[x,O]of Object.entries(v))A[x]=m(O,_);return A},S=(v,_,A)=>{const x=xp(v),O=x.iteration;if(!O)return[];const M=Sd(O.source,A,l);if(!Array.isArray(M))return rr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${O.source}`),[];const T=wp();if(T?.isEnabled()){const z=`${_}-iteration`;T.trackIteration(z,O.source,O.item_var,O.index_var,M.length)}const D=n[x.name];return D?M.flatMap((z,P)=>{const q={...A,[O.item_var]:z,[`${O.item_var}_index`]:P,...O.index_var?{[O.index_var]:P}:{}},W=ns({if:x.if,condition:x.condition,conditions:x.conditions},q,l,x.id);if(x.if&&T?.isEnabled()){const wt=`${_}-iter-${P}-if`;T.trackIfCondition(wt,x.if,W,x.name)}if(!W)return[];const he=x.id?String(Ta(m(x.id,q))):void 0,Ee=`${_}-iter-${P}`,be=i?.getRemountKey?i.getRemountKey(he,Ee):Ee,Ue=y(x.props,q),Fe=wd(Ue,x.actions,q,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let Ge=null;return x.text!==void 0?Ge=m(x.text,q):x.children&&x.children.length>0&&(Ge=lo(x.children,q,n,be,i)),T?.isEnabled()&&T.trackRender(x.name),[Xe.createElement(D,{key:be,...Ta(Fe)},Ta(Ge))]}):(rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[])};return o.flatMap((v,_)=>{const A=xp(v),x=A.id?String(Ta(m(A.id,f))):void 0,O=a?`${a}-${x||_}`:x||`child-${_}`,M=i?.getRemountKey?i.getRemountKey(x,O):O;if(A.iteration)return S(A,M,f);const T=ns({if:A.if,condition:A.condition,conditions:A.conditions},f,l,A.id),D=wp();if(A.if&&D?.isEnabled()){const he=`${M}-if`;D.trackIfCondition(he,A.if,T,A.name)}if(!T)return[];const z=n[A.name];if(!z)return rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[];const P=y(A.props,f),q=wd(P,A.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let W=null;return A.text!==void 0?W=m(A.text,f):A.children&&A.children.length>0&&(W=lo(A.children,f,n,M,i)),D?.isEnabled()&&D.trackRender(A.name),[Xe.createElement(z,{key:M,...Ta(q)},Ta(W))]})}function rs(o,e,n,a){let i,l;return n instanceof Dn?(i=n,l=a):(i=Cp,l=n),i.resolveBindings(o,e,l)}function Cw(o,e,n,a){const i=n??Cp,l={skipCache:!0,...a};let c;try{c=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){rr.warn("resolveClassMap: key 평가 실패:",o.key,g),c=""}let d="";c&&o.variants&&c in o.variants?d=o.variants[c]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function Tp(o,e){return function(){return o.apply(e,arguments)}}const{toString:Ew}=Object.prototype,{getPrototypeOf:as}=Object,{iterator:co,toStringTag:Rp}=Symbol,ql=(({hasOwnProperty:o})=>(e,n)=>o.call(e,n))(Object.prototype),uo=(o,e)=>{let n=o;const a=[];for(;n!=null&&n!==Object.prototype;){if(a.indexOf(n)!==-1)return!1;if(a.push(n),ql(n,e))return!0;n=as(n)}return!1},_w=(o,e)=>o!=null&&uo(o,e)?o[e]:void 0,Cd=(o=>e=>{const n=Ew.call(e);return o[n]||(o[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),yr=o=>(o=o.toLowerCase(),e=>Cd(e)===o),Gl=o=>e=>typeof e===o,{isArray:gi}=Array,is=Gl("undefined");function ss(o){return o!==null&&!is(o)&&o.constructor!==null&&!is(o.constructor)&&Nn(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const kp=yr("ArrayBuffer");function Aw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&kp(o.buffer),e}const xw=Gl("string"),Nn=Gl("function"),Dp=Gl("number"),os=o=>o!==null&&typeof o=="object",Tw=o=>o===!0||o===!1,Vl=o=>{if(!os(o))return!1;const e=as(o);return(e===null||e===Object.prototype||as(e)===null)&&!uo(o,Rp)&&!uo(o,co)},Rw=o=>{if(!os(o)||ss(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},kw=yr("Date"),Dw=yr("File"),Ow=o=>!!(o&&typeof o.uri<"u"),Lw=o=>o&&typeof o.getParts<"u",Mw=yr("Blob"),$w=yr("FileList"),Nw=o=>os(o)&&Nn(o.pipe);function Iw(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Op=Iw(),Lp=typeof Op.FormData<"u"?Op.FormData:void 0,Hw=o=>{if(!o)return!1;if(Lp&&o instanceof Lp)return!0;const e=as(o);if(!e||e===Object.prototype||!Nn(o.append))return!1;const n=Cd(o);return n==="formdata"||n==="object"&&Nn(o.toString)&&o.toString()==="[object FormData]"},jw=yr("URLSearchParams"),[zw,Uw,Pw,Bw]=["ReadableStream","Request","Response","Headers"].map(yr),qw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fo(o,e,{allOwnKeys:n=!1}={}){if(o===null||typeof o>"u")return;let a,i;if(typeof o!="object"&&(o=[o]),gi(o))for(a=0,i=o.length;a0;)if(i=n[a],e===i.toLowerCase())return i;return null}const pi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$p=o=>!is(o)&&o!==pi;function Ed(...o){const{caseless:e,skipUndefined:n}=$p(this)&&this||{},a={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&typeof c=="string"&&Mp(a,c)||c,f=ql(a,d)?a[d]:void 0;Vl(f)&&Vl(l)?a[d]=Ed(f,l):Vl(l)?a[d]=Ed({},l):gi(l)?a[d]=l.slice():(!n||!is(l))&&(a[d]=l)};for(let l=0,c=o.length;l(fo(e,(i,l)=>{n&&Nn(i)?Object.defineProperty(o,l,{__proto__:null,value:Tp(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(o,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:a}),o),Vw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),Fw=(o,e,n,a)=>{o.prototype=Object.create(e.prototype,a),Object.defineProperty(o.prototype,"constructor",{__proto__:null,value:o,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(o,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(o.prototype,n)},Kw=(o,e,n,a)=>{let i,l,c;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)c=i[l],(!a||a(c,o,e))&&!d[c]&&(e[c]=o[c],d[c]=!0);o=n!==!1&&as(o)}while(o&&(!n||n(o,e))&&o!==Object.prototype);return e},Ww=(o,e,n)=>{o=String(o),(n===void 0||n>o.length)&&(n=o.length),n-=e.length;const a=o.indexOf(e,n);return a!==-1&&a===n},Yw=o=>{if(!o)return null;if(gi(o))return o;let e=o.length;if(!Dp(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=o[e];return n},Xw=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&as(Uint8Array)),Jw=(o,e)=>{const a=(o&&o[co]).call(o);let i;for(;(i=a.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Qw=(o,e)=>{let n;const a=[];for(;(n=o.exec(e))!==null;)a.push(n);return a},Zw=yr("HTMLFormElement"),e0=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,a,i){return a.toUpperCase()+i}),{propertyIsEnumerable:t0}=Object.prototype,n0=yr("RegExp"),Np=(o,e)=>{const n=Object.getOwnPropertyDescriptors(o),a={};fo(n,(i,l)=>{let c;(c=e(i,l,o))!==!1&&(a[l]=c||i)}),Object.defineProperties(o,a)},r0=o=>{Np(o,(e,n)=>{if(Nn(o)&&["arguments","caller","callee"].includes(n))return!1;const a=o[n];if(Nn(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},a0=(o,e)=>{const n={},a=i=>{i.forEach(l=>{n[l]=!0})};return gi(o)?a(o):a(String(o).split(e)),n},i0=()=>{},s0=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function o0(o){return!!(o&&Nn(o.append)&&o[Rp]==="FormData"&&o[co])}const l0=o=>{const e=new WeakSet,n=a=>{if(os(a)){if(e.has(a))return;if(ss(a))return a;if(!("toJSON"in a)){e.add(a);const i=gi(a)?[]:{};return fo(a,(l,c)=>{const d=n(l);!is(d)&&(i[c]=d)}),e.delete(a),i}}return a};return n(o)},c0=yr("AsyncFunction"),u0=o=>o&&(os(o)||Nn(o))&&Nn(o.then)&&Nn(o.catch),Ip=((o,e)=>o?setImmediate:e?((n,a)=>(pi.addEventListener("message",({source:i,data:l})=>{i===pi&&l===n&&a.length&&a.shift()()},!1),i=>{a.push(i),pi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Nn(pi.postMessage)),d0=typeof queueMicrotask<"u"?queueMicrotask.bind(pi):typeof process<"u"&&process.nextTick||Ip,Hp=o=>o!=null&&Nn(o[co]),F={isArray:gi,isArrayBuffer:kp,isBuffer:ss,isFormData:Hw,isArrayBufferView:Aw,isString:xw,isNumber:Dp,isBoolean:Tw,isObject:os,isPlainObject:Vl,isEmptyObject:Rw,isReadableStream:zw,isRequest:Uw,isResponse:Pw,isHeaders:Bw,isUndefined:is,isDate:kw,isFile:Dw,isReactNativeBlob:Ow,isReactNative:Lw,isBlob:Mw,isRegExp:n0,isFunction:Nn,isStream:Nw,isURLSearchParams:jw,isTypedArray:Xw,isFileList:$w,forEach:fo,merge:Ed,extend:Gw,trim:qw,stripBOM:Vw,inherits:Fw,toFlatObject:Kw,kindOf:Cd,kindOfTest:yr,endsWith:Ww,toArray:Yw,forEachEntry:Jw,matchAll:Qw,isHTMLForm:Zw,hasOwnProperty:ql,hasOwnProp:ql,hasOwnInPrototypeChain:uo,getSafeProp:_w,reduceDescriptors:Np,freezeMethods:r0,toObjectSet:a0,toCamelCase:e0,noop:i0,toFiniteNumber:s0,findKey:Mp,global:pi,isContextDefined:$p,isSpecCompliantForm:o0,toJSONObject:l0,isAsyncFn:c0,isThenable:u0,setImmediate:Ip,asap:d0,isIterable:Hp,isSafeIterable:o=>o!=null&&uo(o,co)&&Hp(o)},f0=F.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),h0=o=>{const e={};let n,a,i;return o&&o.split(` -`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),a=c.substring(i+1).trim(),!(!n||e[n]&&f0[n])&&(n==="set-cookie"?e[n]?e[n].push(a):e[n]=[a]:e[n]=e[n]?e[n]+", "+a:a)}),e};function g0(o){let e=0,n=o.length;for(;ee;){const a=o.charCodeAt(n-1);if(a!==9&&a!==32)break;n-=1}return e===0&&n===o.length?o:o.slice(e,n)}const p0=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),m0=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function _d(o,e){return F.isArray(o)?o.map(n=>_d(n,e)):g0(String(o).replace(e,""))}const y0=o=>_d(o,p0),b0=o=>_d(o,m0);function jp(o){const e=Object.create(null);return F.forEach(o.toJSON(),(n,a)=>{e[a]=b0(n)}),e}const zp=Symbol("internals");function ho(o){return o&&String(o).trim().toLowerCase()}function Fl(o){return o===!1||o==null?o:F.isArray(o)?o.map(Fl):y0(String(o))}function v0(o){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=n.exec(o);)e[a[1]]=a[2];return e}const S0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function Ad(o,e,n,a,i){if(F.isFunction(a))return a.call(this,e,n);if(i&&(e=n),!!F.isString(e)){if(F.isString(a))return e.indexOf(a)!==-1;if(F.isRegExp(a))return a.test(e)}}function w0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,a)=>n.toUpperCase()+a)}function C0(o,e){const n=F.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(o,a+n,{__proto__:null,value:function(i,l,c){return this[a].call(this,e,i,l,c)},configurable:!0})})}let An=class{constructor(e){e&&this.set(e)}set(e,n,a){const i=this;function l(d,f,g){const m=ho(f);if(!m)return;const y=F.findKey(i,m);(!y||i[y]===void 0||g===!0||g===void 0&&i[y]!==!1)&&(i[y||f]=Fl(d))}const c=(d,f)=>F.forEach(d,(g,m)=>l(g,m,f));if(F.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(F.isString(e)&&(e=e.trim())&&!S0(e))c(h0(e),n);else if(F.isObject(e)&&F.isSafeIterable(e)){let d=Object.create(null),f,g;for(const m of e){if(!F.isArray(m))throw new TypeError("Object iterator must return a key-value pair");g=m[0],F.hasOwnProp(d,g)?(f=d[g],d[g]=F.isArray(f)?[...f,m[1]]:[f,m[1]]):d[g]=m[1]}c(d,n)}else e!=null&&l(n,e,a);return this}get(e,n){if(e=ho(e),e){const a=F.findKey(this,e);if(a){const i=this[a];if(!n)return i;if(n===!0)return v0(i);if(F.isFunction(n))return n.call(this,i,a);if(F.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ho(e),e){const a=F.findKey(this,e);return!!(a&&this[a]!==void 0&&(!n||Ad(this,this[a],a,n)))}return!1}delete(e,n){const a=this;let i=!1;function l(c){if(c=ho(c),c){const d=F.findKey(a,c);d&&(!n||Ad(a,a[d],d,n))&&(delete a[d],i=!0)}}return F.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let a=n.length,i=!1;for(;a--;){const l=n[a];(!e||Ad(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,a={};return F.forEach(this,(i,l)=>{const c=F.findKey(a,l);if(c){n[c]=Fl(i),delete n[l];return}const d=e?w0(l):String(l).trim();d!==l&&delete n[l],n[d]=Fl(i),a[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return F.forEach(this,(a,i)=>{a!=null&&a!==!1&&(n[i]=e&&F.isArray(a)?a.join(", "):a)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const a=new this(e);return n.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[zp]=this[zp]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ho(c);a[d]||(C0(i,c),a[d]=!0)}return F.isArray(e)?e.forEach(l):l(e),this}};An.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),F.reduceDescriptors(An.prototype,({value:o},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(a){this[n]=a}}}),F.freezeMethods(An);const E0="[REDACTED ****]";function _0(o){if(F.hasOwnProp(o,"toJSON"))return!0;let e=Object.getPrototypeOf(o);for(;e&&e!==Object.prototype;){if(F.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function A0(o,e){const n=new Set(e.map(l=>String(l).toLowerCase())),a=[],i=l=>{if(l===null||typeof l!="object"||F.isBuffer(l))return l;if(a.indexOf(l)!==-1)return;l instanceof An&&(l=l.toJSON()),a.push(l);let c;if(F.isArray(l))c=[],l.forEach((d,f)=>{const g=i(d);F.isUndefined(g)||(c[f]=g)});else{if(!F.isPlainObject(l)&&_0(l))return a.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const g=n.has(d.toLowerCase())?E0:i(f);F.isUndefined(g)||(c[d]=g)}}return a.pop(),c};return i(o)}let Ce=class KS extends Error{static from(e,n,a,i,l,c){const d=new KS(e.message,n||e.code,a,i,l);return Object.defineProperty(d,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),d.name=e.name,e.status!=null&&d.status==null&&(d.status=e.status),c&&Object.assign(d,c),d}constructor(e,n,a,i,l){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),a&&(this.config=a),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&F.hasOwnProp(e,"redact")?e.redact:void 0,a=F.isArray(n)&&n.length>0?A0(e,n):F.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a,code:this.code,status:this.status}}};Ce.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Ce.ERR_BAD_OPTION="ERR_BAD_OPTION",Ce.ECONNABORTED="ECONNABORTED",Ce.ETIMEDOUT="ETIMEDOUT",Ce.ECONNREFUSED="ECONNREFUSED",Ce.ERR_NETWORK="ERR_NETWORK",Ce.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Ce.ERR_DEPRECATED="ERR_DEPRECATED",Ce.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Ce.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Ce.ERR_CANCELED="ERR_CANCELED",Ce.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Ce.ERR_INVALID_URL="ERR_INVALID_URL",Ce.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const x0=null,Up=100;function xd(o){return F.isPlainObject(o)||F.isArray(o)}function Pp(o){return F.endsWith(o,"[]")?o.slice(0,-2):o}function Td(o,e,n){return o?o.concat(e).map(function(i,l){return i=Pp(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function T0(o){return F.isArray(o)&&!o.some(xd)}const R0=F.toFlatObject(F,{},null,function(e){return/^is[A-Z]/.test(e)});function Kl(o,e,n){if(!F.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,n=F.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(M,T){return!F.isUndefined(T[M])});const a=n.metaTokens,i=n.visitor||_,l=n.dots,c=n.indexes,d=n.Blob||typeof Blob<"u"&&Blob,f=n.maxDepth===void 0?Up:n.maxDepth,g=d&&F.isSpecCompliantForm(e),m=[];if(!F.isFunction(i))throw new TypeError("visitor must be a function");function y(O){if(O===null)return"";if(F.isDate(O))return O.toISOString();if(F.isBoolean(O))return O.toString();if(!g&&F.isBlob(O))throw new Ce("Blob is not supported. Use a Buffer instead.");if(F.isArrayBuffer(O)||F.isTypedArray(O)){if(g&&typeof d=="function")return new d([O]);if(typeof Buffer<"u")return Buffer.from(O);throw new Ce("Blob is not supported. Use a Buffer instead.",Ce.ERR_NOT_SUPPORT)}return O}function S(O){if(O>f)throw new Ce("Object is too deeply nested ("+O+" levels). Max depth: "+f,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function v(O,M){if(f===1/0)return JSON.stringify(O);const T=[];return JSON.stringify(O,function(z,P){if(!F.isObject(P))return P;for(;T.length&&T[T.length-1]!==this;)T.pop();return T.push(P),S(M+T.length-1),P})}function _(O,M,T){let D=O;if(F.isReactNative(e)&&F.isReactNativeBlob(O))return e.append(Td(T,M,l),y(O)),!1;if(O&&!T&&typeof O=="object"){if(F.endsWith(M,"{}"))M=a?M:M.slice(0,-2),O=v(O,1);else if(F.isArray(O)&&T0(O)||(F.isFileList(O)||F.endsWith(M,"[]"))&&(D=F.toArray(O)))return M=Pp(M),D.forEach(function(P,q){!(F.isUndefined(P)||P===null)&&e.append(c===!0?Td([M],q,l):c===null?M:M+"[]",y(P))}),!1}return xd(O)?!0:(e.append(Td(T,M,l),y(O)),!1)}const A=Object.assign(R0,{defaultVisitor:_,convertValue:y,isVisitable:xd});function x(O,M,T=0){if(!F.isUndefined(O)){if(S(T),m.indexOf(O)!==-1)throw new Error("Circular reference detected in "+M.join("."));m.push(O),F.forEach(O,function(z,P){(!(F.isUndefined(z)||z===null)&&i.call(e,z,F.isString(P)?P.trim():P,M,A))===!0&&x(z,M?M.concat(P):[P],T+1)}),m.pop()}}if(!F.isObject(o))throw new TypeError("data must be an object");return x(o),e}function Bp(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(o).replace(/[!'()~]|%20/g,function(a){return e[a]})}function Rd(o,e){this._pairs=[],o&&Kl(o,this,e)}const qp=Rd.prototype;qp.append=function(e,n){this._pairs.push([e,n])},qp.toString=function(e){const n=e?a=>e.call(this,a,Bp):Bp;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function k0(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Gp(o,e,n){if(!e)return o;o=o||"";const a=F.isFunction(n)?{serialize:n}:n,i=F.getSafeProp(a,"encode")||k0,l=F.getSafeProp(a,"serialize");let c;if(l?c=l(e,a):c=F.isURLSearchParams(e)?e.toString():new Rd(e,a).toString(i),c){const d=o.indexOf("#");d!==-1&&(o=o.slice(0,d)),o+=(o.indexOf("?")===-1?"?":"&")+c}return o}class Vp{constructor(){this.handlers=[]}use(e,n,a){return this.handlers.push({fulfilled:e,rejected:n,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){F.forEach(this.handlers,function(a){a!==null&&e(a)})}}const kd={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},D0={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Rd,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Dd=typeof window<"u"&&typeof document<"u",Od=typeof navigator=="object"&&navigator||void 0,O0=Dd&&(!Od||["ReactNative","NativeScript","NS"].indexOf(Od.product)<0),L0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",M0=Dd&&window.location.href||"http://localhost",mn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Dd,hasStandardBrowserEnv:O0,hasStandardBrowserWebWorkerEnv:L0,navigator:Od,origin:M0},Symbol.toStringTag,{value:"Module"})),...D0};function $0(o,e){return Kl(o,new mn.classes.URLSearchParams,{visitor:function(n,a,i,l){return mn.isNode&&F.isBuffer(n)?(this.append(a,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Fp=Up;function Kp(o){if(o>Fp)throw new Ce("FormData field is too deeply nested ("+o+" levels). Max depth: "+Fp,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function N0(o){const e=[],n=/\w+|\[(\w*)]/g;let a;for(;(a=n.exec(o))!==null;)Kp(e.length),e.push(a[0]==="[]"?"":a[1]||a[0]);return e}function I0(o){const e={},n=Object.keys(o);let a;const i=n.length;let l;for(a=0;a=n.length;return c=!c&&F.isArray(i)?i.length:c,f?(F.hasOwnProp(i,c)?i[c]=F.isArray(i[c])?i[c].concat(a):[i[c],a]:i[c]=a,!d):((!F.hasOwnProp(i,c)||!F.isObject(i[c]))&&(i[c]=[]),e(n,a,i[c],l)&&F.isArray(i[c])&&(i[c]=I0(i[c])),!d)}if(F.isFormData(o)&&F.isFunction(o.entries)){const n={};return F.forEachEntry(o,(a,i)=>{e(N0(a),i,n,0)}),n}return null}const ls=(o,e)=>o!=null&&F.hasOwnProp(o,e)?o[e]:void 0;function H0(o,e,n){if(F.isString(o))try{return(e||JSON.parse)(o),F.trim(o)}catch(a){if(a.name!=="SyntaxError")throw a}return(n||JSON.stringify)(o)}const go={transitional:kd,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const a=n.getContentType()||"",i=a.indexOf("application/json")>-1,l=F.isObject(e);if(l&&F.isHTMLForm(e)&&(e=new FormData(e)),F.isFormData(e))return i?JSON.stringify(Wp(e)):e;if(F.isArrayBuffer(e)||F.isBuffer(e)||F.isStream(e)||F.isFile(e)||F.isBlob(e)||F.isReadableStream(e))return e;if(F.isArrayBufferView(e))return e.buffer;if(F.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=ls(this,"formSerializer");if(a.indexOf("application/x-www-form-urlencoded")>-1)return $0(e,f).toString();if((d=F.isFileList(e))||a.indexOf("multipart/form-data")>-1){const g=ls(this,"env"),m=g&&g.FormData;return Kl(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),H0(e)):e}],transformResponse:[function(e){const n=ls(this,"transitional")||go.transitional,a=n&&n.forcedJSONParsing,i=ls(this,"responseType"),l=i==="json";if(F.isResponse(e)||F.isReadableStream(e))return e;if(e&&F.isString(e)&&(a&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,ls(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?Ce.from(f,Ce.ERR_BAD_RESPONSE,this,null,ls(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:mn.classes.FormData,Blob:mn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};F.forEach(["delete","get","head","post","put","patch","query"],o=>{go.headers[o]={}});function Ld(o,e){const n=this||go,a=e||n,i=An.from(a.headers);let l=a.data;return F.forEach(o,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Yp(o){return!!(o&&o.__CANCEL__)}let po=class extends Ce{constructor(e,n,a){super(e??"canceled",Ce.ERR_CANCELED,n,a),this.name="CanceledError",this.__CANCEL__=!0}};function Xp(o,e,n){const a=n.config.validateStatus;!n.status||!a||a(n.status)?o(n):e(new Ce("Request failed with status code "+n.status,n.status>=400&&n.status<500?Ce.ERR_BAD_REQUEST:Ce.ERR_BAD_RESPONSE,n.config,n.request,n))}function j0(o){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(o);return e&&e[1]||""}function z0(o,e){o=o||10;const n=new Array(o),a=new Array(o);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=a[l];c||(c=g),n[i]=f,a[i]=g;let y=l,S=0;for(;y!==i;)S+=n[y++],y=y%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-c{n=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),y=m-n;y>=a?c(g,m):(i=g,l||(l=setTimeout(()=>{l=null,c(i)},a-y)))},()=>i&&c(i)]}const Wl=(o,e,n=3)=>{let a=0;const i=z0(50,250);return U0(l=>{if(!l||typeof l.loaded!="number")return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=d!=null?Math.min(c,d):c,g=Math.max(0,f-a),m=i(g);a=Math.max(a,f);const y={loaded:f,total:d,progress:d?f/d:void 0,bytes:g,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(y)},n)},Jp=(o,e)=>{const n=o!=null;return[a=>e[0]({lengthComputable:n,total:o,loaded:a}),e[1]]},Qp=o=>(...e)=>F.asap(()=>o(...e)),P0=mn.hasStandardBrowserEnv?((o,e)=>n=>(n=new URL(n,mn.origin),o.protocol===n.protocol&&o.host===n.host&&(e||o.port===n.port)))(new URL(mn.origin),mn.navigator&&/(msie|trident)/i.test(mn.navigator.userAgent)):()=>!0,B0=mn.hasStandardBrowserEnv?{write(o,e,n,a,i,l,c){if(typeof document>"u")return;const d=[`${o}=${encodeURIComponent(e)}`];F.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),F.isString(a)&&d.push(`path=${a}`),F.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),F.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(o){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;no instanceof An?{...o}:o;function mi(o,e){o=o||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function a(m,y,S,v){return F.isPlainObject(m)&&F.isPlainObject(y)?F.merge.call({caseless:v},m,y):F.isPlainObject(y)?F.merge({},y):F.isArray(y)?y.slice():y}function i(m,y,S,v){if(F.isUndefined(y)){if(!F.isUndefined(m))return a(void 0,m,S,v)}else return a(m,y,S,v)}function l(m,y){if(!F.isUndefined(y))return a(void 0,y)}function c(m,y){if(F.isUndefined(y)){if(!F.isUndefined(m))return a(void 0,m)}else return a(void 0,y)}function d(m){const y=F.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!F.isUndefined(y))if(F.isPlainObject(y)){if(F.hasOwnProp(y,m))return y[m]}else return;const S=F.hasOwnProp(o,"transitional")?o.transitional:void 0;if(F.isPlainObject(S)&&F.hasOwnProp(S,m))return S[m]}function f(m,y,S){if(F.hasOwnProp(e,S))return a(m,y);if(F.hasOwnProp(o,S))return a(void 0,m)}const g={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,allowedSocketPaths:c,responseEncoding:c,validateStatus:f,headers:(m,y,S)=>i(tm(m),tm(y),S,!0)};return F.forEach(Object.keys({...o,...e}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const S=F.hasOwnProp(g,y)?g[y]:i,v=F.hasOwnProp(o,y)?o[y]:void 0,_=F.hasOwnProp(e,y)?e[y]:void 0,A=S(v,_,y);F.isUndefined(A)&&S!==f||(n[y]=A)}),F.hasOwnProp(e,"validateStatus")&&F.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(F.hasOwnProp(o,"validateStatus")?n.validateStatus=a(void 0,o.validateStatus):delete n.validateStatus),n}const Y0=["content-type","content-length"];function X0(o,e,n){if(n!=="content-only"){o.set(e);return}Object.entries(e||{}).forEach(([a,i])=>{Y0.includes(a.toLowerCase())&&o.set(a,i)})}const J0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function nm(o){const e=mi({},o),n=S=>F.hasOwnProp(e,S)?e[S]:void 0,a=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),g=n("baseURL"),m=n("allowAbsoluteUrls"),y=n("url");if(e.headers=d=An.from(d),e.url=Gp(em(g,y,m,e),n("params"),n("paramsSerializer")),f){const S=F.getSafeProp(f,"username")||"",v=F.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(S+":"+(v?J0(v):"")))}catch(_){throw Ce.from(_,Ce.ERR_BAD_OPTION_VALUE,o)}}if(F.isFormData(a)&&(mn.hasStandardBrowserEnv||mn.hasStandardBrowserWebWorkerEnv||F.isReactNative(a)?d.setContentType(void 0):F.isFunction(a.getHeaders)&&X0(d,a.getHeaders(),n("formDataHeaderPolicy"))),mn.hasStandardBrowserEnv&&(F.isFunction(i)&&(i=i(e)),i===!0||i==null&&P0(e.url))){const v=l&&c&&B0.read(c);v&&d.set(l,v)}return e}const Q0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(n,a){const i=nm(o);let l=i.data;const c=An.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,y,S,v,_;function A(){v&&v(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function O(){if(!x)return;const T=An.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),z={data:!d||d==="text"||d==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:T,config:o,request:x};Xp(function(q){n(q),A()},function(q){a(q),A()},z),x=null}"onloadend"in x?x.onloadend=O:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.startsWith("file:"))||setTimeout(O)},x.onabort=function(){x&&(a(new Ce("Request aborted",Ce.ECONNABORTED,o,x)),A(),x=null)},x.onerror=function(D){const z=D&&D.message?D.message:"Network Error",P=new Ce(z,Ce.ERR_NETWORK,o,x);P.event=D||null,a(P),A(),x=null},x.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const z=i.transitional||kd;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),a(new Ce(D,z.clarifyTimeoutError?Ce.ETIMEDOUT:Ce.ECONNABORTED,o,x)),A(),x=null},l===void 0&&c.setContentType(null),"setRequestHeader"in x&&F.forEach(jp(c),function(D,z){x.setRequestHeader(z,D)}),F.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),d&&d!=="json"&&(x.responseType=i.responseType),g&&([S,_]=Wl(g,!0),x.addEventListener("progress",S)),f&&x.upload&&([y,v]=Wl(f),x.upload.addEventListener("progress",y),x.upload.addEventListener("loadend",v)),(i.cancelToken||i.signal)&&(m=T=>{x&&(a(!T||T.type?new po(null,o,x):T),x.abort(),A(),x=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=j0(i.url);if(M&&!mn.protocols.includes(M)){a(new Ce("Unsupported protocol "+M+":",Ce.ERR_BAD_REQUEST,o)),A();return}x.send(l||null)})},Z0=(o,e)=>{if(o=o?o.filter(Boolean):[],!e&&!o.length)return;const n=new AbortController;let a=!1;const i=function(f){if(!a){a=!0,c();const g=f instanceof Error?f:this.reason;n.abort(g instanceof Ce?g:new po(g instanceof Error?g.message:g))}};let l=e&&setTimeout(()=>{l=null,i(new Ce(`timeout of ${e}ms exceeded`,Ce.ETIMEDOUT))},e);const c=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),o=null)};o.forEach(f=>f.addEventListener("abort",i,{once:!0}));const{signal:d}=n;return d.unsubscribe=()=>F.asap(c),d},eC=function*(o,e){let n=o.byteLength;if(n{const i=tC(o,e);let l=0,c,d=f=>{c||(c=!0,a&&a(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let y=m.byteLength;if(n){let S=l+=y;n(S)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},Yl=o=>o>=48&&o<=57||o>=65&&o<=70||o>=97&&o<=102,rC=(o,e,n)=>e+2v>=2&&a.charCodeAt(v-2)===37&&a.charCodeAt(v-1)===51&&(a.charCodeAt(v)===68||a.charCodeAt(v)===100);g>=0&&(a.charCodeAt(g)===61?(f++,g--):m(g)&&(f++,g-=3)),f===1&&g>=0&&(a.charCodeAt(g)===61||m(g))&&f++;const S=Math.floor(c/4)*3-(f||0);return S>0?S:0}let l=0;for(let c=0,d=a.length;c=55296&&f<=56319&&c+1=56320&&g<=57343?(l+=4,c++):l+=3}else l+=3}return l}const Md="1.18.1",am=64*1024,{isFunction:Xl}=F,iC=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),im=o=>{if(!F.isString(o))return o;try{return decodeURIComponent(o)}catch{return o}},sm=(o,...e)=>{try{return!!o(...e)}catch{return!1}},sC=o=>{const e=o.indexOf("://");let n=o;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},oC=o=>{const e=F.global!==void 0&&F.global!==null?F.global:globalThis,{ReadableStream:n,TextEncoder:a}=e;o=F.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},o);const{fetch:i,Request:l,Response:c}=o,d=i?Xl(i):typeof fetch=="function",f=Xl(l),g=Xl(c);if(!d)return!1;const m=d&&Xl(n),y=d&&(typeof a=="function"?(O=>M=>O.encode(M))(new a):async O=>new Uint8Array(await new l(O).arrayBuffer())),S=f&&m&&sm(()=>{let O=!1;const M=new l(mn.origin,{body:new n,method:"POST",get duplex(){return O=!0,"half"}}),T=M.headers.has("Content-Type");return M.body!=null&&M.body.cancel(),O&&!T}),v=g&&m&&sm(()=>F.isReadableStream(new c("").body)),_={stream:v&&(O=>O.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(O=>{!_[O]&&(_[O]=(M,T)=>{let D=M&&M[O];if(D)return D.call(M);throw new Ce(`Response type '${O}' is not supported`,Ce.ERR_NOT_SUPPORT,T)})});const A=async O=>{if(O==null)return 0;if(F.isBlob(O))return O.size;if(F.isSpecCompliantForm(O))return(await new l(mn.origin,{method:"POST",body:O}).arrayBuffer()).byteLength;if(F.isArrayBufferView(O)||F.isArrayBuffer(O))return O.byteLength;if(F.isURLSearchParams(O)&&(O=O+""),F.isString(O))return(await y(O)).byteLength},x=async(O,M)=>{const T=F.toFiniteNumber(O.getContentLength());return T??A(M)};return async O=>{let{url:M,method:T,data:D,signal:z,cancelToken:P,timeout:q,onDownloadProgress:W,onUploadProgress:he,responseType:Ee,headers:be,withCredentials:Ue="same-origin",fetchOptions:Fe,maxContentLength:Ge,maxBodyLength:wt}=nm(O);const J=F.isNumber(Ge)&&Ge>-1,ue=F.isNumber(wt)&&wt>-1,Me=ee=>F.hasOwnProp(O,ee)?O[ee]:void 0;let te=i||fetch;Ee=Ee?(Ee+"").toLowerCase():"text";let pe=Z0([z,P&&P.toAbortSignal()],q),N=null;const R=pe&&pe.unsubscribe&&(()=>{pe.unsubscribe()});let de,fe=null;const xe=()=>new Ce("Request body larger than maxBodyLength limit",Ce.ERR_BAD_REQUEST,O,N);try{let ee;const _e=Me("auth");if(_e){const Oe=F.getSafeProp(_e,"username")||"",nt=F.getSafeProp(_e,"password")||"";ee={username:Oe,password:nt}}if(sC(M)){const Oe=new URL(M,mn.origin);if(!ee&&(Oe.username||Oe.password)){const nt=im(Oe.username),sn=im(Oe.password);ee={username:nt,password:sn}}(Oe.username||Oe.password)&&(Oe.username="",Oe.password="",M=Oe.href)}if(ee&&(be.delete("authorization"),be.set("Authorization","Basic "+btoa(iC((ee.username||"")+":"+(ee.password||""))))),J&&typeof M=="string"&&M.startsWith("data:")&&aC(M)>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N);if(ue&&T!=="get"&&T!=="head"){const Oe=await A(D);if(typeof Oe=="number"&&isFinite(Oe)&&(de=Oe,Oe>wt))throw xe()}const Be=ue&&(F.isReadableStream(D)||F.isStream(D)),ke=(Oe,nt,sn)=>rm(Oe,am,Mt=>{if(ue&&Mt>wt)throw fe=xe();nt&&nt(Mt)},sn);if(S&&T!=="get"&&T!=="head"&&(he||Be)){if(de=de??await x(be,D),de!==0||Be){let Oe=new l(M,{method:"POST",body:D,duplex:"half"}),nt;if(F.isFormData(D)&&(nt=Oe.headers.get("content-type"))&&be.setContentType(nt),Oe.body){const[sn,Mt]=he&&Jp(de,Wl(Qp(he)))||[];D=ke(Oe.body,sn,Mt)}}}else if(Be&&!f&&m&&T!=="get"&&T!=="head")D=ke(D);else if(Be&&f&&!S&&T!=="get"&&T!=="head")throw new Ce("Stream request bodies are not supported by the current fetch implementation",Ce.ERR_NOT_SUPPORT,O,N);F.isString(Ue)||(Ue=Ue?"include":"omit");const Ie=f&&"credentials"in l.prototype;if(F.isFormData(D)){const Oe=be.getContentType();Oe&&/^multipart\/form-data/i.test(Oe)&&!/boundary=/i.test(Oe)&&be.delete("content-type")}be.set("User-Agent","axios/"+Md,!1);const Ct={...Fe,signal:pe,method:T.toUpperCase(),headers:jp(be.normalize()),body:D,duplex:"half",credentials:Ie?Ue:void 0};N=f&&new l(M,Ct);let ot=await(f?te(N,Fe):te(M,Ct));const Ot=An.from(ot.headers);if(J){const Oe=F.toFiniteNumber(Ot.getContentLength());if(Oe!=null&&Oe>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N)}const vt=v&&(Ee==="stream"||Ee==="response");if(v&&ot.body&&(W||J||vt&&R)){const Oe={};["status","statusText","headers"].forEach(ln=>{Oe[ln]=ot[ln]});const nt=F.toFiniteNumber(Ot.getContentLength()),[sn,Mt]=W&&Jp(nt,Wl(Qp(W),!0))||[];let Vt=0;const on=ln=>{if(J&&(Vt=ln,Vt>Ge))throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N);sn&&sn(ln)};ot=new c(rm(ot.body,am,on,()=>{Mt&&Mt(),R&&R()}),Oe)}Ee=Ee||"text";let _t=await _[F.findKey(_,Ee)||"text"](ot,O);if(J&&!v&&!vt){let Oe;if(_t!=null&&(typeof _t.byteLength=="number"?Oe=_t.byteLength:typeof _t.size=="number"?Oe=_t.size:typeof _t=="string"&&(Oe=typeof a=="function"?new a().encode(_t).byteLength:_t.length)),typeof Oe=="number"&&Oe>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N)}return!vt&&R&&R(),await new Promise((Oe,nt)=>{Xp(Oe,nt,{data:_t,headers:An.from(ot.headers),status:ot.status,statusText:ot.statusText,config:O,request:N})})}catch(ee){if(R&&R(),pe&&pe.aborted&&pe.reason instanceof Ce){const _e=pe.reason;throw _e.config=O,N&&(_e.request=N),ee!==_e&&Object.defineProperty(_e,"cause",{__proto__:null,value:ee,writable:!0,enumerable:!1,configurable:!0}),_e}if(fe)throw N&&!fe.request&&(fe.request=N),fe;if(ee instanceof Ce)throw N&&!ee.request&&(ee.request=N),ee;if(ee&&ee.name==="TypeError"&&/Load failed|fetch/i.test(ee.message)){const _e=new Ce("Network Error",Ce.ERR_NETWORK,O,N,ee&&ee.response);throw Object.defineProperty(_e,"cause",{__proto__:null,value:ee.cause||ee,writable:!0,enumerable:!1,configurable:!0}),_e}throw Ce.from(ee,ee&&ee.code,O,N,ee&&ee.response)}}},lC=new Map,om=o=>{let e=o&&o.env||{};const{fetch:n,Request:a,Response:i}=e,l=[a,i,n];let c=l.length,d=c,f,g,m=lC;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:oC(e)),m=g;return g};om();const $d={http:x0,xhr:Q0,fetch:{get:om}};F.forEach($d,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(o,"adapterName",{__proto__:null,value:e})}});const lm=o=>`- ${o}`,cC=o=>F.isFunction(o)||o===null||o===!1;function uC(o,e){o=F.isArray(o)?o:[o];const{length:n}=o;let a,i;const l={};for(let c=0;c`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : -`+c.map(lm).join(` -`):" "+lm(c[0]):"as no adapter specified";throw new Ce("There is no suitable adapter to dispatch the request "+d,Ce.ERR_NOT_SUPPORT)}return i}const cm={getAdapter:uC,adapters:$d};function Nd(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new po(null,o)}function um(o){return Nd(o),o.headers=An.from(o.headers),o.data=Ld.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),cm.getAdapter(o.adapter||go.adapter,o)(o).then(function(a){Nd(o),o.response=a;try{a.data=Ld.call(o,o.transformResponse,a)}finally{delete o.response}return a.headers=An.from(a.headers),a},function(a){if(!Yp(a)&&(Nd(o),a&&a.response)){o.response=a.response;try{a.response.data=Ld.call(o,o.transformResponse,a.response)}finally{delete o.response}a.response.headers=An.from(a.response.headers)}return Promise.reject(a)})}const Jl={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{Jl[o]=function(a){return typeof a===o||"a"+(e<1?"n ":" ")+o}});const dm={};Jl.transitional=function(e,n,a){function i(l,c){return"[Axios v"+Md+"] Transitional option '"+l+"'"+c+(a?". "+a:"")}return(l,c,d)=>{if(e===!1)throw new Ce(i(c," has been removed"+(n?" in "+n:"")),Ce.ERR_DEPRECATED);return n&&!dm[c]&&(dm[c]=!0,console.warn(i(c," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,c,d):!0}},Jl.spelling=function(e){return(n,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function dC(o,e,n){if(typeof o!="object"||o===null)throw new Ce("options must be an object",Ce.ERR_BAD_OPTION_VALUE);const a=Object.keys(o);let i=a.length;for(;i-- >0;){const l=a[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=o[l],f=d===void 0||c(d,l,o);if(f!==!0)throw new Ce("option "+l+" must be "+f,Ce.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ce("Unknown option "+l,Ce.ERR_BAD_OPTION)}}const Ql={assertOptions:dC,validators:Jl},xn=Ql.validators;let yi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Vp,response:new Vp}}async request(e,n){try{return await this._request(e,n)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(` +`+u.stack}}var Mt=Object.prototype.hasOwnProperty,Vt=o.unstable_scheduleCallback,on=o.unstable_cancelCallback,ln=o.unstable_shouldYield,Br=o.unstable_requestPaint,Ft=o.unstable_now,Ci=o.unstable_getCurrentPriorityLevel,na=o.unstable_ImmediatePriority,yn=o.unstable_UserBlockingPriority,On=o.unstable_NormalPriority,rt=o.unstable_LowPriority,Hn=o.unstable_IdlePriority,bn=o.log,ra=o.unstable_setDisableYieldValue,sr=null,cn=null;function Tn(t){if(typeof bn=="function"&&ra(t),cn&&typeof cn.setStrictMode=="function")try{cn.setStrictMode(sr,t)}catch{}}var un=Math.clz32?Math.clz32:ce,V=Math.log,se=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(V(t)/se|0)|0}var Z=256,ve=262144,ge=4194304;function we(t){var r=t&42;if(r!==0)return r;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Ae(t,r,s){var u=t.pendingLanes;if(u===0)return 0;var h=0,p=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~p,u!==0?h=we(u):(C&=k,C!==0?h=we(C):s||(s=k&~t,s!==0&&(h=we(s))))):(k=u&~p,k!==0?h=we(k):C!==0?h=we(C):s||(s=u&~t,s!==0&&(h=we(s)))),h===0?0:r!==0&&r!==h&&(r&p)===0&&(p=h&-h,s=r&-r,p>=s||p===32&&(s&4194048)!==0)?r:h}function Ke(t,r){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&r)===0}function Te(t,r){switch(t){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $e(){var t=ge;return ge<<=1,(ge&62914560)===0&&(ge=4194304),t}function Re(t){for(var r=[],s=0;31>s;s++)r.push(t);return r}function et(t,r){t.pendingLanes|=r,r!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function je(t,r,s,u,h,p){var C=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var k=t.entanglements,U=t.expirationTimes,X=t.hiddenUpdates;for(s=C&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Lf=/[\n"\\]/g;function zn(t){return t.replace(Lf,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function vs(t,r,s,u,h,p,C,k){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),r!=null?C==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+kn(r)):t.value!==""+kn(r)&&(t.value=""+kn(r)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),r!=null?ia(t,C,kn(r)):s!=null?ia(t,C,kn(s)):u!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+kn(k):t.removeAttribute("name")}function Ai(t,r,s,u,h,p,C,k){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),r!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||r!=null)){Uo(t);return}s=s!=null?""+kn(s):"",r=r!=null?""+kn(r):s,k||r===t.value||(t.value=r),t.defaultValue=r}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),Uo(t)}function ia(t,r,s){r==="number"&&ja(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function za(t,r,s,u){if(t=t.options,r){r={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Vo=!1;if(kr)try{var Ti={};Object.defineProperty(Ti,"passive",{get:function(){Vo=!0}}),window.addEventListener("test",Ti,Ti),window.removeEventListener("test",Ti,Ti)}catch{Vo=!1}var Vr=null,Fo=null,ws=null;function Pc(){if(ws)return ws;var t,r=Fo,s=r.length,u,h="value"in Vr?Vr.value:Vr.textContent,p=h.length;for(t=0;t=re),We=" ",dt=!1;function pt(t,r){switch(t){case"keyup":return L.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Or=!1;function Xf(t,r){switch(t){case"compositionend":return Pt(r);case"keypress":return r.which!==32?null:(dt=!0,We);case"textInput":return t=r.data,t===We&&dt?null:t;default:return null}}function Wc(t,r){if(Or)return t==="compositionend"||!I&&pt(t,r)?(t=Pc(),ws=Fo=Vr=null,Or=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:s,offset:r-t};t=u}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=My(s)}}function Ny(t,r){return t&&r?t===r?!0:t&&t.nodeType===3?!1:r&&r.nodeType===3?Ny(t,r.parentNode):"contains"in t?t.contains(r):t.compareDocumentPosition?!!(t.compareDocumentPosition(r)&16):!1:!1}function Iy(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var r=ja(t.document);r instanceof t.HTMLIFrameElement;){try{var s=typeof r.contentWindow.location.href=="string"}catch{s=!1}if(s)t=r.contentWindow;else break;r=ja(t.document)}return r}function th(t){var r=t&&t.nodeName&&t.nodeName.toLowerCase();return r&&(r==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||r==="textarea"||t.contentEditable==="true")}var nx=kr&&"documentMode"in document&&11>=document.documentMode,As=null,nh=null,nl=null,rh=!1;function Hy(t,r,s){var u=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;rh||As==null||As!==ja(u)||(u=As,"selectionStart"in u&&th(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),nl&&tl(nl,u)||(nl=u,u=Uu(nh,"onSelect"),0>=C,h-=C,Fr=1<<32-un(r)+h|s<Qe?(ct=Ne,Ne=null):ct=Ne.sibling;var yt=Q(K,Ne,Y[Qe],oe);if(yt===null){Ne===null&&(Ne=ct);break}t&&Ne&&yt.alternate===null&&r(K,Ne),G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt,Ne=ct}if(Qe===Y.length)return s(K,Ne),ft&&ca(K,Qe),Pe;if(Ne===null){for(;QeQe?(ct=Ne,Ne=null):ct=Ne.sibling;var di=Q(K,Ne,yt.value,oe);if(di===null){Ne===null&&(Ne=ct);break}t&&Ne&&di.alternate===null&&r(K,Ne),G=p(di,G,Qe),mt===null?Pe=di:mt.sibling=di,mt=di,Ne=ct}if(yt.done)return s(K,Ne),ft&&ca(K,Qe),Pe;if(Ne===null){for(;!yt.done;Qe++,yt=Y.next())yt=le(K,yt.value,oe),yt!==null&&(G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt);return ft&&ca(K,Qe),Pe}for(Ne=u(Ne);!yt.done;Qe++,yt=Y.next())yt=ne(Ne,K,Qe,yt.value,oe),yt!==null&&(t&&yt.alternate!==null&&Ne.delete(yt.key===null?Qe:yt.key),G=p(yt,G,Qe),mt===null?Pe=yt:mt.sibling=yt,mt=yt);return t&&Ne.forEach(function(CT){return r(K,CT)}),ft&&ca(K,Qe),Pe}function Dt(K,G,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===A&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case v:e:{for(var Pe=Y.key;G!==null;){if(G.key===Pe){if(Pe=Y.type,Pe===A){if(G.tag===7){s(K,G.sibling),oe=h(G,Y.props.children),oe.return=K,K=oe;break e}}else if(G.elementType===Pe||typeof Pe=="object"&&Pe!==null&&Pe.$$typeof===W&&qi(Pe)===G.type){s(K,G.sibling),oe=h(G,Y.props),ll(oe,Y),oe.return=K,K=oe;break e}s(K,G);break}else r(K,G);G=G.sibling}Y.type===A?(oe=ji(Y.props.children,K.mode,oe,Y.key),oe.return=K,K=oe):(oe=ru(Y.type,Y.key,Y.props,null,K.mode,oe),ll(oe,Y),oe.return=K,K=oe)}return C(K);case _:e:{for(Pe=Y.key;G!==null;){if(G.key===Pe)if(G.tag===4&&G.stateNode.containerInfo===Y.containerInfo&&G.stateNode.implementation===Y.implementation){s(K,G.sibling),oe=h(G,Y.children||[]),oe.return=K,K=oe;break e}else{s(K,G);break}else r(K,G);G=G.sibling}oe=uh(Y,K.mode,oe),oe.return=K,K=oe}return C(K);case W:return Y=qi(Y),Dt(K,G,Y,oe)}if(wt(Y))return De(K,G,Y,oe);if(Ue(Y)){if(Pe=Ue(Y),typeof Pe!="function")throw Error(a(150));return Y=Pe.call(Y),qe(K,G,Y,oe)}if(typeof Y.then=="function")return Dt(K,G,uu(Y),oe);if(Y.$$typeof===T)return Dt(K,G,su(K,Y),oe);du(K,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,G!==null&&G.tag===6?(s(K,G.sibling),oe=h(G,Y),oe.return=K,K=oe):(s(K,G),oe=ch(Y,K.mode,oe),oe.return=K,K=oe),C(K)):s(K,G)}return function(K,G,Y,oe){try{ol=0;var Pe=Dt(K,G,Y,oe);return Is=null,Pe}catch(Ne){if(Ne===Ns||Ne===lu)throw Ne;var mt=Xn(29,Ne,null,K.mode);return mt.lanes=oe,mt.return=K,mt}}}var Vi=sb(!0),ob=sb(!1),Wa=!1;function Ch(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Eh(t,r){t=t.updateQueue,r.updateQueue===t&&(r.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Ya(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Xa(t,r,s){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(St&2)!==0){var h=u.pending;return h===null?r.next=r:(r.next=h.next,h.next=r),u.pending=r,r=nu(t),Gy(t,null,s),r}return tu(t,u,r,s),nu(t)}function cl(t,r,s){if(r=r.updateQueue,r!==null&&(r=r.shared,(s&4194048)!==0)){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,Se(t,s)}}function _h(t,r){var s=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,s===u)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var C={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=C:p=p.next=C,s=s.next}while(s!==null);p===null?h=p=r:p=p.next=r}else h=p=r;s={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:u.shared,callbacks:u.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=r:t.next=r,s.lastBaseUpdate=r}var Ah=!1;function ul(){if(Ah){var t=$s;if(t!==null)throw t}}function dl(t,r,s,u){Ah=!1;var h=t.updateQueue;Wa=!1;var p=h.firstBaseUpdate,C=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var U=k,X=U.next;U.next=null,C===null?p=X:C.next=X,C=U;var ae=t.alternate;ae!==null&&(ae=ae.updateQueue,k=ae.lastBaseUpdate,k!==C&&(k===null?ae.firstBaseUpdate=X:k.next=X,ae.lastBaseUpdate=U))}if(p!==null){var le=h.baseState;C=0,ae=X=U=null,k=p;do{var Q=k.lane&-536870913,ne=Q!==k.lane;if(ne?(lt&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ms&&(Ah=!0),ae!==null&&(ae=ae.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var De=t,qe=k;Q=r;var Dt=s;switch(qe.tag){case 1:if(De=qe.payload,typeof De=="function"){le=De.call(Dt,le,Q);break e}le=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=qe.payload,Q=typeof De=="function"?De.call(Dt,le,Q):De,Q==null)break e;le=y({},le,Q);break e;case 2:Wa=!0}}Q=k.callback,Q!==null&&(t.flags|=64,ne&&(t.flags|=8192),ne=h.callbacks,ne===null?h.callbacks=[Q]:ne.push(Q))}else ne={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ae===null?(X=ae=ne,U=le):ae=ae.next=ne,C|=Q;if(k=k.next,k===null){if(k=h.shared.pending,k===null)break;ne=k,k=ne.next,ne.next=null,h.lastBaseUpdate=ne,h.shared.pending=null}}while(!0);ae===null&&(U=le),h.baseState=U,h.firstBaseUpdate=X,h.lastBaseUpdate=ae,p===null&&(h.shared.lanes=0),ti|=C,t.lanes=C,t.memoizedState=le}}function lb(t,r){if(typeof t!="function")throw Error(a(191,t));t.call(r)}function cb(t,r){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var C=J.T,k={};J.T=k,Gh(t,!1,r,s);try{var U=h(),X=J.S;if(X!==null&&X(k,U),U!==null&&typeof U=="object"&&typeof U.then=="function"){var ae=dx(U,u);gl(t,r,ae,tr(t))}else gl(t,r,u,tr(t))}catch(le){gl(t,r,{then:function(){},status:"rejected",reason:le},tr())}finally{ue.p=p,C!==null&&k.types!==null&&(C.types=k.types),J.T=C}}function yx(){}function Bh(t,r,s,u){if(t.tag!==5)throw Error(a(476));var h=Pb(t).queue;Ub(t,h,r,Me,s===null?yx:function(){return Bb(t),s(u)})}function Pb(t){var r=t.memoizedState;if(r!==null)return r;r={memoizedState:Me,baseState:Me,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:Me},next:null};var s={};return r.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:s},next:null},t.memoizedState=r,t=t.alternate,t!==null&&(t.memoizedState=r),r}function Bb(t){var r=Pb(t);r.next===null&&(r=t.alternate.memoizedState),gl(t,r.next.queue,{},tr())}function qh(){return wn(Ol)}function qb(){return Jt().memoizedState}function Gb(){return Jt().memoizedState}function bx(t){for(var r=t.return;r!==null;){switch(r.tag){case 24:case 3:var s=tr();t=Ya(s);var u=Xa(r,t,s);u!==null&&(Gn(u,r,s),cl(u,r,s)),r={cache:bh()},t.payload=r;return}r=r.return}}function vx(t,r,s){var u=tr();s={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},wu(t)?Fb(r,s):(s=oh(t,r,s,u),s!==null&&(Gn(s,t,u),Kb(s,r,u)))}function Vb(t,r,s){var u=tr();gl(t,r,s,u)}function gl(t,r,s,u){var h={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(wu(t))Fb(r,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=r.lastRenderedReducer,p!==null))try{var C=r.lastRenderedState,k=p(C,s);if(h.hasEagerState=!0,h.eagerState=k,Yn(k,C))return tu(t,r,h,0),Lt===null&&eu(),!1}catch{}if(s=oh(t,r,h,u),s!==null)return Gn(s,t,u),Kb(s,r,u),!0}return!1}function Gh(t,r,s,u){if(u={lane:2,revertLane:Cg(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},wu(t)){if(r)throw Error(a(479))}else r=oh(t,s,u,2),r!==null&&Gn(r,t,2)}function wu(t){var r=t.alternate;return t===Je||r!==null&&r===Je}function Fb(t,r){js=gu=!0;var s=t.pending;s===null?r.next=r:(r.next=s.next,s.next=r),t.pending=r}function Kb(t,r,s){if((s&4194048)!==0){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,Se(t,s)}}var pl={readContext:wn,use:yu,useCallback:Kt,useContext:Kt,useEffect:Kt,useImperativeHandle:Kt,useLayoutEffect:Kt,useInsertionEffect:Kt,useMemo:Kt,useReducer:Kt,useRef:Kt,useState:Kt,useDebugValue:Kt,useDeferredValue:Kt,useTransition:Kt,useSyncExternalStore:Kt,useId:Kt,useHostTransitionStatus:Kt,useFormState:Kt,useActionState:Kt,useOptimistic:Kt,useMemoCache:Kt,useCacheRefresh:Kt};pl.useEffectEvent=Kt;var Wb={readContext:wn,use:yu,useCallback:function(t,r){return Mn().memoizedState=[t,r===void 0?null:r],t},useContext:wn,useEffect:Ob,useImperativeHandle:function(t,r,s){s=s!=null?s.concat([t]):null,vu(4194308,4,Nb.bind(null,r,t),s)},useLayoutEffect:function(t,r){return vu(4194308,4,t,r)},useInsertionEffect:function(t,r){vu(4,2,t,r)},useMemo:function(t,r){var s=Mn();r=r===void 0?null:r;var u=t();if(Fi){Tn(!0);try{t()}finally{Tn(!1)}}return s.memoizedState=[u,r],u},useReducer:function(t,r,s){var u=Mn();if(s!==void 0){var h=s(r);if(Fi){Tn(!0);try{s(r)}finally{Tn(!1)}}}else h=r;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=vx.bind(null,Je,t),[u.memoizedState,t]},useRef:function(t){var r=Mn();return t={current:t},r.memoizedState=t},useState:function(t){t=Hh(t);var r=t.queue,s=Vb.bind(null,Je,r);return r.dispatch=s,[t.memoizedState,s]},useDebugValue:Uh,useDeferredValue:function(t,r){var s=Mn();return Ph(s,t,r)},useTransition:function(){var t=Hh(!1);return t=Ub.bind(null,Je,t.queue,!0,!1),Mn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,r,s){var u=Je,h=Mn();if(ft){if(s===void 0)throw Error(a(407));s=s()}else{if(s=r(),Lt===null)throw Error(a(349));(lt&127)!==0||pb(u,r,s)}h.memoizedState=s;var p={value:s,getSnapshot:r};return h.queue=p,Ob(yb.bind(null,u,p,t),[t]),u.flags|=2048,Us(9,{destroy:void 0},mb.bind(null,u,p,s,r),null),s},useId:function(){var t=Mn(),r=Lt.identifierPrefix;if(ft){var s=Kr,u=Fr;s=(u&~(1<<32-un(u)-1)).toString(32)+s,r="_"+r+"R_"+s,s=pu++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?p.multiple=!0:u.size&&(p.size=u.size);break;default:p=typeof u.is=="string"?C.createElement(h,{is:u.is}):C.createElement(h)}}p[Ut]=r,p[Rn]=u;e:for(C=r.child;C!==null;){if(C.tag===5||C.tag===6)p.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===r)break e;for(;C.sibling===null;){if(C.return===null||C.return===r)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}r.stateNode=p;e:switch(En(p,h,u),h){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&pa(r)}}return Nt(r),ag(r,r.type,t===null?null:t.memoizedProps,r.pendingProps,s),null;case 6:if(t&&r.stateNode!=null)t.memoizedProps!==u&&pa(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(a(166));if(t=ee.current,Os(r)){if(t=r.stateNode,s=r.memoizedProps,u=null,h=Sn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[Ut]=r,t=!!(t.nodeValue===s||u!==null&&u.suppressHydrationWarning===!0||hS(t.nodeValue,s)),t||Fa(r,!0)}else t=Pu(t).createTextNode(u),t[Ut]=r,r.stateNode=t}return Nt(r),null;case 31:if(s=r.memoizedState,t===null||t.memoizedState!==null){if(u=Os(r),s!==null){if(t===null){if(!u)throw Error(a(318));if(t=r.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[Ut]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Nt(r),t=!1}else s=gh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return r.flags&256?(Qn(r),r):(Qn(r),null);if((r.flags&128)!==0)throw Error(a(558))}return Nt(r),null;case 13:if(u=r.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Os(r),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=r.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[Ut]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Nt(r),h=!1}else h=gh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return r.flags&256?(Qn(r),r):(Qn(r),null)}return Qn(r),(r.flags&128)!==0?(r.lanes=s,r):(s=u!==null,t=t!==null&&t.memoizedState!==null,s&&(u=r.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),p=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(p=u.memoizedState.cachePool.pool),p!==h&&(u.flags|=2048)),s!==t&&s&&(r.child.flags|=8192),xu(r,r.updateQueue),Nt(r),null);case 4:return ke(),t===null&&xg(r.stateNode.containerInfo),Nt(r),null;case 10:return da(r.type),Nt(r),null;case 19:if(R(Xt),u=r.memoizedState,u===null)return Nt(r),null;if(h=(r.flags&128)!==0,p=u.rendering,p===null)if(h)yl(u,!1);else{if(Wt!==0||t!==null&&(t.flags&128)!==0)for(t=r.child;t!==null;){if(p=hu(t),p!==null){for(r.flags|=128,yl(u,!1),t=p.updateQueue,r.updateQueue=t,xu(r,t),r.subtreeFlags=0,t=s,s=r.child;s!==null;)Vy(s,t),s=s.sibling;return de(Xt,Xt.current&1|2),ft&&ca(r,u.treeForkCount),r.child}t=t.sibling}u.tail!==null&&Ft()>Ou&&(r.flags|=128,h=!0,yl(u,!1),r.lanes=4194304)}else{if(!h)if(t=hu(p),t!==null){if(r.flags|=128,h=!0,t=t.updateQueue,r.updateQueue=t,xu(r,t),yl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!p.alternate&&!ft)return Nt(r),null}else 2*Ft()-u.renderingStartTime>Ou&&s!==536870912&&(r.flags|=128,h=!0,yl(u,!1),r.lanes=4194304);u.isBackwards?(p.sibling=r.child,r.child=p):(t=u.last,t!==null?t.sibling=p:r.child=p,u.last=p)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ft(),t.sibling=null,s=Xt.current,de(Xt,h?s&1|2:s&1),ft&&ca(r,u.treeForkCount),t):(Nt(r),null);case 22:case 23:return Qn(r),Th(),u=r.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(s&536870912)!==0&&(r.flags&128)===0&&(Nt(r),r.subtreeFlags&6&&(r.flags|=8192)):Nt(r),s=r.updateQueue,s!==null&&xu(r,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==s&&(r.flags|=2048),t!==null&&R(Bi),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),r.memoizedState.cache!==s&&(r.flags|=2048),da(en),Nt(r),null;case 25:return null;case 30:return null}throw Error(a(156,r.tag))}function _x(t,r){switch(fh(r),r.tag){case 1:return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 3:return da(en),ke(),t=r.flags,(t&65536)!==0&&(t&128)===0?(r.flags=t&-65537|128,r):null;case 26:case 27:case 5:return Ct(r),null;case 31:if(r.memoizedState!==null){if(Qn(r),r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 13:if(Qn(r),t=r.memoizedState,t!==null&&t.dehydrated!==null){if(r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 19:return R(Xt),null;case 4:return ke(),null;case 10:return da(r.type),null;case 22:case 23:return Qn(r),Th(),t!==null&&R(Bi),t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 24:return da(en),null;case 25:return null;default:return null}}function bv(t,r){switch(fh(r),r.tag){case 3:da(en),ke();break;case 26:case 27:case 5:Ct(r);break;case 4:ke();break;case 31:r.memoizedState!==null&&Qn(r);break;case 13:Qn(r);break;case 19:R(Xt);break;case 10:da(r.type);break;case 22:case 23:Qn(r),Th(),t!==null&&R(Bi);break;case 24:da(en)}}function bl(t,r){try{var s=r.updateQueue,u=s!==null?s.lastEffect:null;if(u!==null){var h=u.next;s=h;do{if((s.tag&t)===t){u=void 0;var p=s.create,C=s.inst;u=p(),C.destroy=u}s=s.next}while(s!==h)}}catch(k){xt(r,r.return,k)}}function Za(t,r,s){try{var u=r.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var p=h.next;u=p;do{if((u.tag&t)===t){var C=u.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,h=r;var U=s,X=k;try{X()}catch(ae){xt(h,U,ae)}}}u=u.next}while(u!==p)}}catch(ae){xt(r,r.return,ae)}}function vv(t){var r=t.updateQueue;if(r!==null){var s=t.stateNode;try{cb(r,s)}catch(u){xt(t,t.return,u)}}}function Sv(t,r,s){s.props=Ki(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(u){xt(t,r,u)}}function vl(t,r){try{var s=t.ref;if(s!==null){switch(t.tag){case 26:case 27:case 5:var u=t.stateNode;break;case 30:u=t.stateNode;break;default:u=t.stateNode}typeof s=="function"?t.refCleanup=s(u):s.current=u}}catch(h){xt(t,r,h)}}function Wr(t,r){var s=t.ref,u=t.refCleanup;if(s!==null)if(typeof u=="function")try{u()}catch(h){xt(t,r,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){xt(t,r,h)}else s.current=null}function wv(t){var r=t.type,s=t.memoizedProps,u=t.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":s.autoFocus&&u.focus();break e;case"img":s.src?u.src=s.src:s.srcSet&&(u.srcset=s.srcSet)}}catch(h){xt(t,t.return,h)}}function ig(t,r,s){try{var u=t.stateNode;Fx(u,t.type,s,r),u[Rn]=r}catch(h){xt(t,t.return,h)}}function Cv(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&si(t.type)||t.tag===4}function sg(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Cv(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&si(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function og(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,r):(r=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,r.appendChild(t),s=s._reactRootContainer,s!=null||r.onclick!==null||(r.onclick=Rr));else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode,r=null),t=t.child,t!==null))for(og(t,r,s),t=t.sibling;t!==null;)og(t,r,s),t=t.sibling}function Tu(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?s.insertBefore(t,r):s.appendChild(t);else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(Tu(t,r,s),t=t.sibling;t!==null;)Tu(t,r,s),t=t.sibling}function Ev(t){var r=t.stateNode,s=t.memoizedProps;try{for(var u=t.type,h=r.attributes;h.length;)r.removeAttributeNode(h[0]);En(r,u,s),r[Ut]=t,r[Rn]=s}catch(p){xt(t,t.return,p)}}var ma=!1,rn=!1,lg=!1,_v=typeof WeakSet=="function"?WeakSet:Set,pn=null;function Ax(t,r){if(t=t.containerInfo,kg=Wu,t=Iy(t),th(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var u=s.getSelection&&s.getSelection();if(u&&u.rangeCount!==0){s=u.anchorNode;var h=u.anchorOffset,p=u.focusNode;u=u.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var C=0,k=-1,U=-1,X=0,ae=0,le=t,Q=null;t:for(;;){for(var ne;le!==s||h!==0&&le.nodeType!==3||(k=C+h),le!==p||u!==0&&le.nodeType!==3||(U=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(ne=le.firstChild)!==null;)Q=le,le=ne;for(;;){if(le===t)break t;if(Q===s&&++X===h&&(k=C),Q===p&&++ae===u&&(U=C),(ne=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=ne}s=k===-1||U===-1?null:{start:k,end:U}}else s=null}s=s||{start:0,end:0}}else s=null;for(Dg={focusedElem:t,selectionRange:s},Wu=!1,pn=r;pn!==null;)if(r=pn,t=r.child,(r.subtreeFlags&1028)!==0&&t!==null)t.return=r,pn=t;else for(;pn!==null;){switch(r=pn,p=r.alternate,t=r.flags,r.tag){case 0:if((t&4)!==0&&(t=r.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),En(p,u,s),p[Ut]=t,Zt(p),u=p;break e;case"link":var C=DS("link","href",h).get(u+(s.href||""));if(C){for(var k=0;kDt&&(C=Dt,Dt=qe,qe=C);var K=$y(k,qe),G=$y(k,Dt);if(K&&G&&(ne.rangeCount!==1||ne.anchorNode!==K.node||ne.anchorOffset!==K.offset||ne.focusNode!==G.node||ne.focusOffset!==G.offset)){var Y=le.createRange();Y.setStart(K.node,K.offset),ne.removeAllRanges(),qe>Dt?(ne.addRange(Y),ne.extend(G.node,G.offset)):(Y.setEnd(G.node,G.offset),ne.addRange(Y))}}}}for(le=[],ne=k;ne=ne.parentNode;)ne.nodeType===1&&le.push({element:ne,left:ne.scrollLeft,top:ne.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;ks?32:s,J.T=null,s=pg,pg=null;var p=ri,C=wa;if(fn=0,Vs=ri=null,wa=0,(St&6)!==0)throw Error(a(331));var k=St;if(St|=4,Nv(p.current),Lv(p,p.current,C,s),St=k,Al(0,!1),cn&&typeof cn.onPostCommitFiberRoot=="function")try{cn.onPostCommitFiberRoot(sr,p)}catch{}return!0}finally{ue.p=h,J.T=u,Zv(t,r)}}function tS(t,r,s){r=cr(s,r),r=Wh(t.stateNode,r,2),t=Xa(t,r,2),t!==null&&(et(t,2),Yr(t))}function xt(t,r,s){if(t.tag===3)tS(t,t,s);else for(;r!==null;){if(r.tag===3){tS(r,t,s);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ni===null||!ni.has(u))){t=cr(s,t),s=nv(2),u=Xa(r,s,2),u!==null&&(rv(s,u,r,t),et(u,2),Yr(u));break}}r=r.return}}function vg(t,r,s){var u=t.pingCache;if(u===null){u=t.pingCache=new Rx;var h=new Set;u.set(r,h)}else h=u.get(r),h===void 0&&(h=new Set,u.set(r,h));h.has(s)||(dg=!0,h.add(s),t=Mx.bind(null,t,r,s),r.then(t,t))}function Mx(t,r,s){var u=t.pingCache;u!==null&&u.delete(r),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,Lt===t&&(lt&s)===s&&(Wt===4||Wt===3&&(lt&62914560)===lt&&300>Ft()-Du?(St&2)===0&&Fs(t,0):fg|=s,Gs===lt&&(Gs=0)),Yr(t)}function nS(t,r){r===0&&(r=$e()),t=Hi(t,r),t!==null&&(et(t,r),Yr(t))}function $x(t){var r=t.memoizedState,s=0;r!==null&&(s=r.retryLane),nS(t,s)}function Nx(t,r){var s=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(r),nS(t,s)}function Ix(t,r){return Vt(t,r)}var Hu=null,Ws=null,Sg=!1,ju=!1,wg=!1,ii=0;function Yr(t){t!==Ws&&t.next===null&&(Ws===null?Hu=Ws=t:Ws=Ws.next=t),ju=!0,Sg||(Sg=!0,jx())}function Al(t,r){if(!wg&&ju){wg=!0;do for(var s=!1,u=Hu;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var p=0;else{var C=u.suspendedLanes,k=u.pingedLanes;p=(1<<31-un(42|t)+1)-1,p&=h&~(C&~k),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,sS(u,p))}else p=lt,p=Ae(u,u===Lt?p:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(p&3)===0||Ke(u,p)||(s=!0,sS(u,p));u=u.next}while(s);wg=!1}}function Hx(){rS()}function rS(){ju=Sg=!1;var t=0;ii!==0&&Wx()&&(t=ii);for(var r=Ft(),s=null,u=Hu;u!==null;){var h=u.next,p=aS(u,r);p===0?(u.next=null,s===null?Hu=h:s.next=h,h===null&&(Ws=s)):(s=u,(t!==0||(p&3)!==0)&&(ju=!0)),u=h}fn!==0&&fn!==5||Al(t),ii!==0&&(ii=0)}function aS(t,r){for(var s=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0k)break;var ae=U.transferSize,le=U.initiatorType;ae&&gS(le)&&(U=U.responseEnd,C+=ae*(U"u"?null:document;function xS(t,r,s){var u=Ys;if(u&&typeof r=="string"&&r){var h=zn(r);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),AS.has(h)||(AS.add(h),t={rel:t,crossOrigin:s,href:r},u.querySelector(h)===null&&(r=u.createElement("link"),En(r,"link",t),Zt(r),u.head.appendChild(r)))}}function rT(t){Ca.D(t),xS("dns-prefetch",t,null)}function aT(t,r){Ca.C(t,r),xS("preconnect",t,r)}function iT(t,r,s){Ca.L(t,r,s);var u=Ys;if(u&&t&&r){var h='link[rel="preload"][as="'+zn(r)+'"]';r==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+zn(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+zn(s.imageSizes)+'"]')):h+='[href="'+zn(t)+'"]';var p=h;switch(r){case"style":p=Xs(t);break;case"script":p=Js(t)}pr.has(p)||(t=y({rel:"preload",href:r==="image"&&s&&s.imageSrcSet?void 0:t,as:r},s),pr.set(p,t),u.querySelector(h)!==null||r==="style"&&u.querySelector(kl(p))||r==="script"&&u.querySelector(Dl(p))||(r=u.createElement("link"),En(r,"link",t),Zt(r),u.head.appendChild(r)))}}function sT(t,r){Ca.m(t,r);var s=Ys;if(s&&t){var u=r&&typeof r.as=="string"?r.as:"script",h='link[rel="modulepreload"][as="'+zn(u)+'"][href="'+zn(t)+'"]',p=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=Js(t)}if(!pr.has(p)&&(t=y({rel:"modulepreload",href:t},r),pr.set(p,t),s.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Dl(p)))return}u=s.createElement("link"),En(u,"link",t),Zt(u),s.head.appendChild(u)}}}function oT(t,r,s){Ca.S(t,r,s);var u=Ys;if(u&&t){var h=Ia(u).hoistableStyles,p=Xs(t);r=r||"default";var C=h.get(p);if(!C){var k={loading:0,preload:null};if(C=u.querySelector(kl(p)))k.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":r},s),(s=pr.get(p))&&Hg(t,s);var U=C=u.createElement("link");Zt(U),En(U,"link",t),U._p=new Promise(function(X,ae){U.onload=X,U.onerror=ae}),U.addEventListener("load",function(){k.loading|=1}),U.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qu(C,r,u)}C={type:"stylesheet",instance:C,count:1,state:k},h.set(p,C)}}}function lT(t,r){Ca.X(t,r);var s=Ys;if(s&&t){var u=Ia(s).hoistableScripts,h=Js(t),p=u.get(h);p||(p=s.querySelector(Dl(h)),p||(t=y({src:t,async:!0},r),(r=pr.get(h))&&jg(t,r),p=s.createElement("script"),Zt(p),En(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function cT(t,r){Ca.M(t,r);var s=Ys;if(s&&t){var u=Ia(s).hoistableScripts,h=Js(t),p=u.get(h);p||(p=s.querySelector(Dl(h)),p||(t=y({src:t,async:!0,type:"module"},r),(r=pr.get(h))&&jg(t,r),p=s.createElement("script"),Zt(p),En(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function TS(t,r,s,u){var h=(h=ee.current)?Bu(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(r=Xs(s.href),s=Ia(h).hoistableStyles,u=s.get(r),u||(u={type:"style",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Xs(s.href);var p=Ia(h).hoistableStyles,C=p.get(t);if(C||(h=h.ownerDocument||h,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,C),(p=h.querySelector(kl(t)))&&!p._p&&(C.instance=p,C.state.loading=5),pr.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},pr.set(t,s),p||uT(h,t,s,C.state))),r&&u===null)throw Error(a(528,""));return C}if(r&&u!==null)throw Error(a(529,""));return null;case"script":return r=s.async,s=s.src,typeof s=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Js(s),s=Ia(h).hoistableScripts,u=s.get(r),u||(u={type:"script",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function Xs(t){return'href="'+zn(t)+'"'}function kl(t){return'link[rel="stylesheet"]['+t+"]"}function RS(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function uT(t,r,s,u){t.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=t.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),En(r,"link",s),Zt(r),t.head.appendChild(r))}function Js(t){return'[src="'+zn(t)+'"]'}function Dl(t){return"script[async]"+t}function kS(t,r,s){if(r.count++,r.instance===null)switch(r.type){case"style":var u=t.querySelector('style[data-href~="'+zn(s.href)+'"]');if(u)return r.instance=u,Zt(u),u;var h=y({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Zt(u),En(u,"style",h),qu(u,s.precedence,t),r.instance=u;case"stylesheet":h=Xs(s.href);var p=t.querySelector(kl(h));if(p)return r.state.loading|=4,r.instance=p,Zt(p),p;u=RS(s),(h=pr.get(h))&&Hg(u,h),p=(t.ownerDocument||t).createElement("link"),Zt(p);var C=p;return C._p=new Promise(function(k,U){C.onload=k,C.onerror=U}),En(p,"link",u),r.state.loading|=4,qu(p,s.precedence,t),r.instance=p;case"script":return p=Js(s.src),(h=t.querySelector(Dl(p)))?(r.instance=h,Zt(h),h):(u=s,(h=pr.get(p))&&(u=y({},s),jg(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Zt(h),En(h,"link",u),t.head.appendChild(h),r.instance=h);case"void":return null;default:throw Error(a(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,qu(u,s.precedence,t));return r.instance}function qu(t,r,s){for(var u=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,p=h,C=0;C title"):null)}function dT(t,r,s){if(s===1||r.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;return r.rel==="stylesheet"?(t=r.disabled,typeof r.precedence=="string"&&t==null):!0;case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function LS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function fT(t,r,s,u){if(s.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Xs(u.href),p=r.querySelector(kl(h));if(p){r=p._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(t.count++,t=Vu.bind(t),r.then(t,t)),s.state.loading|=4,s.instance=p,Zt(p);return}p=r.ownerDocument||r,u=RS(u),(h=pr.get(h))&&Hg(u,h),p=p.createElement("link"),Zt(p);var C=p;C._p=new Promise(function(k,U){C.onload=k,C.onerror=U}),En(p,"link",u),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,r),(r=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=Vu.bind(t),r.addEventListener("load",s),r.addEventListener("error",s))}}var zg=0;function hT(t,r){return t.stylesheets&&t.count===0&&Ku(t,t.stylesheets),0zg?50:800)+r);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function Vu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ku(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Fu=null;function Ku(t,r){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Fu=new Map,r.forEach(gT,t),Fu=null,Vu.call(t))}function gT(t,r){if(!(r.state.loading&4)){var s=Fu.get(t);if(s)var u=s.get(null);else{s=new Map,Fu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),rd.exports=QS(),rd.exports}var od=ZS();const ld=Jr(od),eo=[],ew=50;let cd=!1;function tp(){try{return window.G7Core?.devTools}catch{return}}function Xi(o,e,n){const a=tp();if(cd&&a?.isEnabled?.()){a.trackLog?.(o,e,n);return}cd||(o==="error"||o==="warn")&&eo.length{n.isDebugEnabled()&&console.log(e,...a),Xi("log",o,a)},warn:(...a)=>{n.isDebugEnabled()&&console.warn(e,...a),Xi("warn",o,a)},error:(...a)=>{n.isDebugEnabled()&&console.error(e,...a),Xi("error",o,a)}}}to.getInstance();const Ji=ht("networkResilience"),np=2,rp=300,ap=2e3,tw=15e3;function dd(o){return o?.name==="AbortError"}function ip(o){return dd(o)?!1:o instanceof TypeError}let Nl=!1,sp=!1;function fd(){return Nl}function nw(){typeof window>"u"||sp||(sp=!0,window.addEventListener("pagehide",()=>{Nl=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(Nl=!1)}),window.addEventListener("beforeunload",()=>{Nl=!0}))}function op(o,e,n){const a=Math.min(e*Math.pow(2,o),n),i=a*.25*(Math.random()*2-1);return Math.max(0,Math.round(a+i))}function lp(o){return new Promise(e=>setTimeout(e,o))}async function Il(o,e={}){const{retries:n=np,baseDelayMs:a=rp,maxDelayMs:i=ap,timeoutMs:l=tw,label:c=o,init:d}=e,f=n+1;let g;for(let m=0;m0?new AbortController:null;try{const _={...d};if(v){const x=d?.signal;x&&(x.aborted?v.abort():x.addEventListener("abort",()=>v.abort(),{once:!0})),_.signal=v.signal,S=setTimeout(()=>{y=!0,v.abort()},l)}return await fetch(o,_)}catch(_){if(g=_,dd(_)&&!y||!(y||ip(_)))throw _;if(fd())throw Ji.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw Ji.warn(`All ${f} attempts failed: ${c}`,_),_;const O=op(m,a,i);Ji.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${O}ms: ${c}`),await lp(O)}finally{S!==void 0&&clearTimeout(S)}}throw g}async function cp(o,e={},n={}){const{retries:a=np,baseDelayMs:i=rp,maxDelayMs:l=ap,label:c=o}=n,d=a+1;for(let f=0;f{const i=document.createElement("script");i.src=o,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>n(),i.onerror=()=>a(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const up="extension",Qi="extensionless",aw="file";function iw(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Qi)return Qi;const n=o?.assetUrlMode;return n===Qi||n===up?n:o?.settings?.general?.asset_url_mode===Qi?Qi:up}function dp(){return iw()===Qi}function Nr(o,e,n,a){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=dp()?i:`${i}.${l}`,d=[];return a&&d.push(a.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Ea(o){if(!o||!dp())return o;const e=globalThis?.location?.origin,n=e&&o.startsWith(e)?o.slice(e.length):o;if(!n.startsWith("/api/"))return o;const[a,i]=sw(n),l=a.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return fp(`/api/${l[1]}/bundle/${l[2]}`,i);const c=a.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,g,m]=c,y=`${aw}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${y}${i?`&${i}`:""}`}const d=a.match(/^(\/api\/.+)\.(json|js|css)$/);return d?fp(d[1],i):o}function sw(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function fp(o,e){return e?`${o}?${e}`:o}const Ir=ht("ComponentRegistry");class hn extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="ComponentRegistryError"}}const Wn=class Wn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Wn.instance||(Wn.instance=new Wn),Wn.instance}static createIsolatedInstance(){return new Wn}static resetInstance(){Wn.instance=null}async loadComponents(e,n){if(this.loadingState==="loading")throw new hn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Ir.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Ir.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new hn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Wn.manifestCache.has(e)){this.manifest=Wn.manifestCache.get(e),Ir.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Nr(`/api/templates/${this.templateId}/components`,"json"),a=await Il(n,{label:"components.json"});if(!a.ok)throw new hn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,Wn.manifestCache.set(e,i),Ir.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof hn?e:new hn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new hn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new hn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new hn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const a of n){if(!Array.isArray(e.components[a]))throw new hn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new hn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new hn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i})})}Ir.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new hn(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(n),Ir.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof hn?e:new hn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new hn("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new hn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const a of n){const i=this.manifest.components[a]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Ir.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,a){this.registry[e]&&Ir.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:a},Ir.log(`[ComponentRegistry] Registered component: ${e} (${a.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,a])=>a.metadata.type===e).map(([n,a])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,a]of Object.entries(this.registry))e[n]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Ir.log("Registry cleared")}};$(Wn,"instance",null),$(Wn,"manifestCache",new Map);let mr=Wn;const hp=ht("TranslationEngine");class hd extends Error{constructor(n,a,i){super(n);$(this,"key");$(this,"locale");this.key=a,this.locale=i,this.name="TranslationError"}}const In=class In{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return In.instance||(In.instance=new In(e)),In.instance}static resetInstance(){In.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(hp.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,a="/api",i=!1){const l=`${e}:${n}`;if(!i){const c=this.getFromCache(l);if(c)return this.translations.set(l,c),c}try{const c=[];i&&c.push(`_=${Date.now()}`);const d=Nr(`${a}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new hd(`Failed to load translations: ${f.statusText}`,void 0,n);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(c){throw new hd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,a){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,a)),i===d)break;c++}return i.replace(In.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(g);return this.translate(f,n,m,a)+y})}translate(e,n,a,i){const l=this.getTranslation(e,n),c=a&&this.cleanParamsStr(a);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:a,locale:i}=n,l=`${a}:${i}`,c=this.translations.get(l);if(c){const d=this.getNestedValue(c,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${a}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,n){const a=n.split(".");let i=e;for(const l of a){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,a,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=a.split(".");let f=c;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(In.PARAM_PATTERN);for(const f of d){const[,g,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(S,v)=>l[parseInt(v,10)]);a[g.trim()]=this.resolveParamValue(y.trim(),n)}return a}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&n)try{const l=Sd.evaluateExpression(a,n);return String(l??"")}catch(l){return hp.error("Expression evaluation failed:",a,l),""}else{const l=this.getNestedDataValue(n,a);return String(l??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let a=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");a=a.replace(d,String(l))}return a}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(a);for(const a of n)this.cache.delete(a)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$(In,"instance",null),$(In,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(In,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(In,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let _a=In,gd=null;function ow(o){return gd||(gd=new _a(o)),gd}const gp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:_a,TranslationError:hd,getTranslationEngine:ow},Symbol.toStringTag,{value:"Module"})),Zi=ht("PipeRegistry");function pp(o,e){const n=o.getFullYear(),a=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),c=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",a).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",c).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function lw(o,e="ko"){const a=new Date().getTime()-o.getTime(),i=Math.floor(a/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),g=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:c<24?`${c}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:g<12?`${g}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function pd(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const no={date:{fn:(o,e="YYYY-MM-DD")=>{const n=pd(o);return n?pp(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const n=pd(o);return n?pp(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const n=pd(o);return n?lw(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const n=Number(o);if(isNaN(n))return String(o??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),n.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,n="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,n)=>Array.isArray(o)?Array.isArray(e)?o.filter(a=>{const i=n?a?.[n]:a;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},es=new Map,Si=class Si{static getInstance(){return Si.instance||(Si.instance=new Si),Si.instance}register(e,n,a){if(no[e]){Zi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}es.set(e,{fn:n,description:a}),Zi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(no[e])return Zi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=es.delete(e);return n&&Zi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=no[e];return n?n.fn:es.get(e)?.fn}has(e){return!!no[e]||es.has(e)}execute(e,n,a=[]){const i=this.get(e);if(!i)return Zi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...a)}catch(l){return Zi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,a]of Object.entries(no))e.push({name:n,description:a.description,type:"built-in"});for(const[n,a]of es.entries())e.push({name:n,description:a.description,type:"custom"});return e.sort((n,a)=>n.name.localeCompare(a.name))}clearCustomPipes(){es.clear()}};$(Si,"instance",null);let Hl=Si;Hl.getInstance();function cw(o){const e=o.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const a=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:a,args:[]};const l=[];let c="",d=null,f=0;for(let g=0;g0?i[g-1]:"")==="\\"){c+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){c+=m;continue}if(m==="("||m==="["||m==="{"){f++,c+=m;continue}if(m===")"||m==="]"||m==="}"){f--,c+=m;continue}if(m===","&&f===0){l.push(mp(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(mp(c.trim())),{name:a,args:l}}function mp(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function uw(o){const e=[];let n="",a=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[a-1]:"",c=a0){a--;continue}return null}}return a===0?e.trim():null}function fw(o){const e=[];if(typeof o!="string")return e;for(let n=0;n0){i--;continue}if(o[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:o.slice(n+2,l)}),n=l+1)}return e}function ro(o){return/[?:|&!+\-*/<>=()[\]{}]/.test(o)}function yp(o){const e=typeof o=="string"?o.trim():"";return e===""?"empty":md.has(e)?"literal":Vn(e)?"pipe":ro(e)?"expression":"path"}function yd(o,e,n,a){const i=typeof o=="string"?o.trim():"",l=yp(i),c=a?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){a?.onEmpty?.(o);return}if(l==="literal")return md.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,a?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,a?.trackingInfo):n.resolve(i,e,c,a?.trackingInfo)}catch(d){if(a?.onError)return a.onError(d,i);throw d}}const nr="raw:";function bp(o){return o.startsWith(nr)?o.slice(nr.length):o}const ao="﷐",fi="﷑",xa="﷒";function io(o){return ao+o+fi}function jl(o){return o.length>=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function zl(o){return o.includes(ao)}function bd(o){return o.slice(1,-1)}function ts(o){if(typeof o=="string")return io(o);if(Array.isArray(o))return o.map(ts);if(o&&typeof o=="object"){const e={};for(const[n,a]of Object.entries(o))e[n]=ts(a);return e}return o}function Ta(o){if(typeof o=="string")return jl(o)?bd(o):zl(o)||o.includes(fi)?o.split(ao).join("").split(fi).join(""):o;if(Array.isArray(o)){let e=!1;const n=o.map(a=>{const i=Ta(a);return i!==a&&(e=!0),i});return e?n:o}if(o&&typeof o=="object"){if(o.$$typeof!==void 0)return o;let e=!1;const n={};for(const[a,i]of Object.entries(o)){const l=Ta(i);l!==i&&(e=!0),n[a]=l}return e?n:o}return o}const Ra=ht("DataBindingEngine"),hw=/^[$A-Za-z_][$A-Za-z0-9_]*$/,gw=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","arguments","eval"]);function so(){try{return window.G7Core?.devTools}catch{return}}class vd extends Error{constructor(n,a,i){super(n);$(this,"path");$(this,"context");this.path=a,this.context=i,this.name="DataBindingError"}}const ta=class ta{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(S,v)=>{const _=v.trim();let A=!1,x=_;if(_.startsWith(nr)&&(A=!0,x=_.slice(nr.length)),Vn(x))try{const q=this.evaluatePipeExpression(x,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),W=this.formatValue(q);return A?io(W):W}catch(q){return Ra.error("Pipe expression evaluation failed:",x,q),S}if(ro(x)){const q=c?.isEnabled()?performance.now():0;try{let W,he=!1;if(l.skipCache)W=this.evaluateExpression(x,d);else{const be=`expr:${x}`,Ue=this.getFromRenderCycleCache(be);Ue!==void 0?(W=Ue,he=!0):(W=this.evaluateExpression(x,d),this.saveToRenderCycleCache(be,W))}if(c?.isEnabled()){const be=performance.now()-q;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:he,duration:be,method:"resolveBindings",skipCache:l.skipCache})}const Ee=this.formatValue(W);return A?io(Ee):Ee}catch(W){return Ra.error("Expression evaluation failed:",x,W),S}}if(l.skipCache){const q=c?.isEnabled()?performance.now():0,W=this.resolvePath(x,d,l);if(c?.isEnabled()){const Ee=performance.now()-q;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:Ee,method:"resolveBindings",skipCache:!0})}const he=this.formatValue(W);return A?io(he):he}const M=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),T=c?.isEnabled()?performance.now():0;let D,z=!1;if(M){const q=this.getFromRenderCycleCache(x);q!==void 0?(D=q,z=!0):(D=this.resolvePath(x,d,l),this.saveToRenderCycleCache(x,D))}else{const q=this.getFromCache(x);q!==void 0?(D=q,z=!0):(D=this.resolvePath(x,d,l),this.saveToCache(x,D))}if(c?.isEnabled()){const q=performance.now()-T;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:z,duration:q,method:"resolveBindings",skipCache:l.skipCache})}const P=this.formatValue(D);return A?io(P):P},g=fw(e);if(g.length===0)return e;let m="",y=0;for(const S of g)m+=e.slice(y,S.start),m+=f(e.slice(S.start,S.end),S.expr),y=S.end;return m+e.slice(y)}evaluatePipeExpression(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[g,m]=uw(e);let y,S=!1;const v=ro(g),_=g.startsWith("_global")||g.startsWith("_local")||g.startsWith("_isolated")||g.startsWith("$parent");if(l.skipCache)v?y=this.evaluateExpression(g,f):y=this.resolvePath(g,f,l);else if(v){const x=this.getFromRenderCycleCache(`expr:${g}`);x!==void 0?(y=x,S=!0):(y=this.evaluateExpression(g,f),this.saveToRenderCycleCache(`expr:${g}`,y))}else if(_){const x=this.getFromRenderCycleCache(g);x!==void 0?(y=x,S=!0):(y=this.resolvePath(g,f,l),this.saveToRenderCycleCache(g,y))}else{const x=this.getFromCache(g);x!==void 0?(y=x,S=!0):(y=this.resolvePath(g,f,l),this.saveToCache(g,y))}const A=dw(y,m);if(c?.isEnabled()){const x=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(A),resultType:this.getResultType(A),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:S,duration:x,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return A}resolve(e,n,a,i){const l={...this.defaultOptions,...a},c=so(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,n,l);return c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),y}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let g=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(y),resultType:this.getResultType(y),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),y}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,a,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Ra.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new vd(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,n);return a.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fta.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}resolveObject(e,n,a){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,a)}catch(g){Ra.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,g),i[d]=void 0}}return i}resolveObjectEntry(e,n,a,i,l){if(typeof a=="string"){const c=Aa(a);if(c!==null){const d=c.trim();let f=!1,g=d;d.startsWith(nr)&&(f=!0,g=d.slice(nr.length));let m;switch(yp(g)){case"empty":Ra.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=md.get(g);break;case"pipe":m=this.evaluatePipeExpression(g,i,l);break;case"expression":m=this.evaluateExpression(g,i,l);break;default:m=this.resolve(g,i,l)}e[n]=f&&m!=null?ts(m):m}else e[n]=this.resolveBindings(a,i,l)}else Array.isArray(a)?e[n]=a.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):a&&typeof a=="object"?e[n]=this.resolveObject(a,i,l):e[n]=a}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const a of e)if(n===a||n.startsWith(`${a}.`)||n.startsWith(`${a}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,a]of this.cache.entries())e-a.timestamp>ta.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>ta.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,a){const i=so(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let c=this.preprocessOptionalChaining(e);c=this.preprocessTranslationTokens(c);const d=this.extractVariablesFromExpression(c),f={...n};for(const D of d)D in f||(f[D]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let g=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!g||!m)){const D=window.__templateApp?.getConfig?.();g??(g=D?.templateId),m??(m=D?.locale)}const y=m||"ko";f.$localized=(D,z)=>{if(D==null&&!z)return"";if(typeof D=="string")return D;if(D&&typeof D=="object"&&D[y])return D[y];if(z&&typeof z=="string"){const P=f.$t?f.$t(z):z;if(P&&P!==z)return P}return D&&typeof D=="object"?D.ko||D.en||Object.values(D)[0]||"":D==null?"":String(D)};const S=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>S?.uuid?S.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const z=Math.random()*16|0;return(D==="x"?z:z&3|8).toString(16)});const v={templateId:g||"",locale:y};f.$t=D=>{if(!D||typeof D!="string")return"";try{return _a.getInstance().translate(D,v)}catch(z){return Ra.warn("$t() translation failed for key:",D,z),D}},f.$get=(D,z,P=void 0)=>{if(D==null)return P;const q=Array.isArray(z)?z:[z];if(q.length===0)return D;let W=D;for(const he of q){if(W==null||he==null)return P;W=W[he]}return W??P};const _=[],A=[];for(const[D,z]of Object.entries(f))!hw.test(D)||gw.has(D)||(_.push(D),A.push(z));const x=`${c}|${_.join(",")}`;let O=this.expressionFnCache.get(x);const M=!!O;O||(O=new Function(..._,`return (${c});`),this.expressionFnCache.set(x,O));const T=O(...A);if(i?.isEnabled()){const D=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(T),resultType:this.getResultType(T),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:M,duration:D,method:"evaluateExpression",skipCache:a?.skipCache})}return T}catch(c){throw new Error(`Failed to evaluate expression "${e}": ${c instanceof Error?c.message:String(c)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const n=Object.keys(e);return n.length>20?`{Object(${n.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(n,a,i,l)=>`$t('${l}')`),e.replace(/(?(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),a}extractVariablesFromExpression(e){const n=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),a=/(?{n!==null&&clearTimeout(n),n=setTimeout(()=>{o(...a)},e)})}class mw{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=pw(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(Pl.has(e))return Pl.get(e)??null;let n=null;if(Ul[e])n={...Ul[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,l]=a,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(n={min:c,max:d})}}return Pl.set(e,n),n}getMatchingKey(e,n){const a=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&a.push({key:i,range:l,isPreset:!!Ul[i]})}return a.length===0?null:(a.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const c=i.range.max-i.range.min,d=l.range.max-l.range.min;return c-d}),a[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),Pl.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const hi=new mw,oo=ht("ConditionEvaluator");function yw(o,e,n,a){return yd(bp(o),e,n,{skipCache:!0,onEmpty:()=>{oo.warn(`${a}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function vp(o,e,n){if(!o)return!0;try{const a=Aa(o);let i;if(a!==null?i=yw(a,e,n,"evaluateStringCondition"):i=n.resolveBindings(o,e,{skipCache:!0}),typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(a){return oo.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,a),!1}}function Bl(o,e,n){if(typeof o=="string")return vp(o,e,n);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return oo.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of o.and)if(!Bl(a,e,n))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return oo.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of o.or)if(Bl(a,e,n))return!0;return!1}return oo.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function Sp(o,e,n){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a{rr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${a||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(o,e,{skipCache:!0}),typeof l=="string"){const c=l.toLowerCase().trim();if(c==="false"||c==="0"||c===""||c==="null"||c==="undefined")return!1}return!!l}catch(i){return rr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function ns(o,e,n,a){if(o.if!==void 0)return _p(o.if,e,n,a);if(o.condition!==void 0)return _p(o.condition,e,n,a);if(o.conditions===void 0)return!0;const i=o.conditions;try{return bw(i)?Bl(i,e,n):vw(i)?Sp(i,e,n).matched:(rr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(l){return rr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,l),!1}}function Ap(o){if(!o.responsive)return o;const e=hi.getWidth(),n=hi.getMatchingKey(o.responsive,e);if(!n)return o;const a=o.responsive[n];return{...o,props:{...o.props,...a.props},children:a.children??o.children,text:a.text??o.text,if:a.if??o.if,iteration:a.iteration??o.iteration}}function lo(o,e,n,a,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new Dn,c=i?.translationEngine??_a.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=ww(e,i?.componentContext),g=(v,_)=>{if(typeof v=="string")return jl(v)||zl(v)||!/\$t:[a-zA-Z0-9._-]+/.test(v)?v:c.resolveTranslations(v,d,_);if(Array.isArray(v))return v.map(A=>g(A,_));if(v&&typeof v=="object"){const A={};for(const[x,O]of Object.entries(v))A[x]=g(O,_);return A}return v},m=(v,_)=>{if(typeof v=="string"){if(jl(v))return bd(v);if(zl(v)){const x=[],O=v.replace(new RegExp(`${ao}([^${fi}]*)${fi}`,"g"),(T,D)=>(x.push(D),`${xa}${x.length-1}${xa}`));let M=O;return/\$t:[a-zA-Z0-9._-]+/.test(O)&&(M=c.resolveTranslations(O,d,_)),M.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(T,D)=>x[parseInt(D)])}if(v.startsWith("$t:defer:")){const x="$t:"+v.slice(9);return c.resolveTranslations(x,d,_)}if(v.startsWith("$t:"))return c.resolveTranslations(v,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(v)){const x=v.trim();if(!(x.startsWith("{")&&x.endsWith("}")||x.startsWith("[")&&x.endsWith("]"))&&!v.includes("{{"))return c.resolveTranslations(v,d,_)}const A=Ep(v);if(A!==null){let x=!1,O=A;A.startsWith(nr)&&(x=!0,O=A.slice(nr.length));let M=!1,T=yd(O,_,l,{skipCache:!0,onError:D=>{rr.warn("renderItemChildren: 표현식 평가 실패:",D),M=!0},onEmpty:()=>{rr.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return M?void 0:(x||(T=g(T,_)),x&&T!=null?ts(T):T)}if(v.includes("{{")){const x=l.resolveBindings(v,_,{skipCache:!0});return typeof x=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(x)?c.resolveTranslations(x,d,_):x}return v}if(Array.isArray(v))return v.map(A=>m(A,_));if(v&&typeof v=="object"){if(l.isSwitchExpression(v))return l.resolveSwitch(v,_,{skipCache:!0});if(l.isActionDefinition(v))return{...v};const A={};for(const[x,O]of Object.entries(v))A[x]=m(O,_);return A}return v},y=(v,_)=>{if(!v)return{};const A={};for(const[x,O]of Object.entries(v))A[x]=m(O,_);return A},S=(v,_,A)=>{const x=Ap(v),O=x.iteration;if(!O)return[];const M=wd(O.source,A,l);if(!Array.isArray(M))return rr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${O.source}`),[];const T=wp();if(T?.isEnabled()){const z=`${_}-iteration`;T.trackIteration(z,O.source,O.item_var,O.index_var,M.length)}const D=n[x.name];return D?M.flatMap((z,P)=>{const q={...A,[O.item_var]:z,[`${O.item_var}_index`]:P,...O.index_var?{[O.index_var]:P}:{}},W=ns({if:x.if,condition:x.condition,conditions:x.conditions},q,l,x.id);if(x.if&&T?.isEnabled()){const wt=`${_}-iter-${P}-if`;T.trackIfCondition(wt,x.if,W,x.name)}if(!W)return[];const he=x.id?String(Ta(m(x.id,q))):void 0,Ee=`${_}-iter-${P}`,be=i?.getRemountKey?i.getRemountKey(he,Ee):Ee,Ue=y(x.props,q),Fe=Cd(Ue,x.actions,q,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let Ge=null;return x.text!==void 0?Ge=m(x.text,q):x.children&&x.children.length>0&&(Ge=lo(x.children,q,n,be,i)),T?.isEnabled()&&T.trackRender(x.name),[Xe.createElement(D,{key:be,...Ta(Fe)},Ta(Ge))]}):(rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[])};return o.flatMap((v,_)=>{const A=Ap(v),x=A.id?String(Ta(m(A.id,f))):void 0,O=a?`${a}-${x||_}`:x||`child-${_}`,M=i?.getRemountKey?i.getRemountKey(x,O):O;if(A.iteration)return S(A,M,f);const T=ns({if:A.if,condition:A.condition,conditions:A.conditions},f,l,A.id),D=wp();if(A.if&&D?.isEnabled()){const he=`${M}-if`;D.trackIfCondition(he,A.if,T,A.name)}if(!T)return[];const z=n[A.name];if(!z)return rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[];const P=y(A.props,f),q=Cd(P,A.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let W=null;return A.text!==void 0?W=m(A.text,f):A.children&&A.children.length>0&&(W=lo(A.children,f,n,M,i)),D?.isEnabled()&&D.trackRender(A.name),[Xe.createElement(z,{key:M,...Ta(q)},Ta(W))]})}function rs(o,e,n,a){let i,l;return n instanceof Dn?(i=n,l=a):(i=Cp,l=n),i.resolveBindings(o,e,l)}function Cw(o,e,n,a){const i=n??Cp,l={skipCache:!0,...a};let c;try{c=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){rr.warn("resolveClassMap: key 평가 실패:",o.key,g),c=""}let d="";c&&o.variants&&c in o.variants?d=o.variants[c]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function xp(o,e){return function(){return o.apply(e,arguments)}}const{toString:Ew}=Object.prototype,{getPrototypeOf:as}=Object,{iterator:co,toStringTag:Tp}=Symbol,ql=(({hasOwnProperty:o})=>(e,n)=>o.call(e,n))(Object.prototype),uo=(o,e)=>{let n=o;const a=[];for(;n!=null&&n!==Object.prototype;){if(a.indexOf(n)!==-1)return!1;if(a.push(n),ql(n,e))return!0;n=as(n)}return!1},_w=(o,e)=>o!=null&&uo(o,e)?o[e]:void 0,Ed=(o=>e=>{const n=Ew.call(e);return o[n]||(o[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),yr=o=>(o=o.toLowerCase(),e=>Ed(e)===o),Gl=o=>e=>typeof e===o,{isArray:gi}=Array,is=Gl("undefined");function ss(o){return o!==null&&!is(o)&&o.constructor!==null&&!is(o.constructor)&&$n(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const Rp=yr("ArrayBuffer");function Aw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&Rp(o.buffer),e}const xw=Gl("string"),$n=Gl("function"),kp=Gl("number"),os=o=>o!==null&&typeof o=="object",Tw=o=>o===!0||o===!1,Vl=o=>{if(!os(o))return!1;const e=as(o);return(e===null||e===Object.prototype||as(e)===null)&&!uo(o,Tp)&&!uo(o,co)},Rw=o=>{if(!os(o)||ss(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},kw=yr("Date"),Dw=yr("File"),Ow=o=>!!(o&&typeof o.uri<"u"),Lw=o=>o&&typeof o.getParts<"u",Mw=yr("Blob"),$w=yr("FileList"),Nw=o=>os(o)&&$n(o.pipe);function Iw(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Dp=Iw(),Op=typeof Dp.FormData<"u"?Dp.FormData:void 0,Hw=o=>{if(!o)return!1;if(Op&&o instanceof Op)return!0;const e=as(o);if(!e||e===Object.prototype||!$n(o.append))return!1;const n=Ed(o);return n==="formdata"||n==="object"&&$n(o.toString)&&o.toString()==="[object FormData]"},jw=yr("URLSearchParams"),[zw,Uw,Pw,Bw]=["ReadableStream","Request","Response","Headers"].map(yr),qw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function fo(o,e,{allOwnKeys:n=!1}={}){if(o===null||typeof o>"u")return;let a,i;if(typeof o!="object"&&(o=[o]),gi(o))for(a=0,i=o.length;a0;)if(i=n[a],e===i.toLowerCase())return i;return null}const pi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Mp=o=>!is(o)&&o!==pi;function _d(...o){const{caseless:e,skipUndefined:n}=Mp(this)&&this||{},a={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&typeof c=="string"&&Lp(a,c)||c,f=ql(a,d)?a[d]:void 0;Vl(f)&&Vl(l)?a[d]=_d(f,l):Vl(l)?a[d]=_d({},l):gi(l)?a[d]=l.slice():(!n||!is(l))&&(a[d]=l)};for(let l=0,c=o.length;l(fo(e,(i,l)=>{n&&$n(i)?Object.defineProperty(o,l,{__proto__:null,value:xp(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(o,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:a}),o),Vw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),Fw=(o,e,n,a)=>{o.prototype=Object.create(e.prototype,a),Object.defineProperty(o.prototype,"constructor",{__proto__:null,value:o,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(o,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(o.prototype,n)},Kw=(o,e,n,a)=>{let i,l,c;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)c=i[l],(!a||a(c,o,e))&&!d[c]&&(e[c]=o[c],d[c]=!0);o=n!==!1&&as(o)}while(o&&(!n||n(o,e))&&o!==Object.prototype);return e},Ww=(o,e,n)=>{o=String(o),(n===void 0||n>o.length)&&(n=o.length),n-=e.length;const a=o.indexOf(e,n);return a!==-1&&a===n},Yw=o=>{if(!o)return null;if(gi(o))return o;let e=o.length;if(!kp(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=o[e];return n},Xw=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&as(Uint8Array)),Jw=(o,e)=>{const a=(o&&o[co]).call(o);let i;for(;(i=a.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Qw=(o,e)=>{let n;const a=[];for(;(n=o.exec(e))!==null;)a.push(n);return a},Zw=yr("HTMLFormElement"),e0=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,a,i){return a.toUpperCase()+i}),{propertyIsEnumerable:t0}=Object.prototype,n0=yr("RegExp"),$p=(o,e)=>{const n=Object.getOwnPropertyDescriptors(o),a={};fo(n,(i,l)=>{let c;(c=e(i,l,o))!==!1&&(a[l]=c||i)}),Object.defineProperties(o,a)},r0=o=>{$p(o,(e,n)=>{if($n(o)&&["arguments","caller","callee"].includes(n))return!1;const a=o[n];if($n(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},a0=(o,e)=>{const n={},a=i=>{i.forEach(l=>{n[l]=!0})};return gi(o)?a(o):a(String(o).split(e)),n},i0=()=>{},s0=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function o0(o){return!!(o&&$n(o.append)&&o[Tp]==="FormData"&&o[co])}const l0=o=>{const e=new WeakSet,n=a=>{if(os(a)){if(e.has(a))return;if(ss(a))return a;if(!("toJSON"in a)){e.add(a);const i=gi(a)?[]:{};return fo(a,(l,c)=>{const d=n(l);!is(d)&&(i[c]=d)}),e.delete(a),i}}return a};return n(o)},c0=yr("AsyncFunction"),u0=o=>o&&(os(o)||$n(o))&&$n(o.then)&&$n(o.catch),Np=((o,e)=>o?setImmediate:e?((n,a)=>(pi.addEventListener("message",({source:i,data:l})=>{i===pi&&l===n&&a.length&&a.shift()()},!1),i=>{a.push(i),pi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",$n(pi.postMessage)),d0=typeof queueMicrotask<"u"?queueMicrotask.bind(pi):typeof process<"u"&&process.nextTick||Np,Ip=o=>o!=null&&$n(o[co]),F={isArray:gi,isArrayBuffer:Rp,isBuffer:ss,isFormData:Hw,isArrayBufferView:Aw,isString:xw,isNumber:kp,isBoolean:Tw,isObject:os,isPlainObject:Vl,isEmptyObject:Rw,isReadableStream:zw,isRequest:Uw,isResponse:Pw,isHeaders:Bw,isUndefined:is,isDate:kw,isFile:Dw,isReactNativeBlob:Ow,isReactNative:Lw,isBlob:Mw,isRegExp:n0,isFunction:$n,isStream:Nw,isURLSearchParams:jw,isTypedArray:Xw,isFileList:$w,forEach:fo,merge:_d,extend:Gw,trim:qw,stripBOM:Vw,inherits:Fw,toFlatObject:Kw,kindOf:Ed,kindOfTest:yr,endsWith:Ww,toArray:Yw,forEachEntry:Jw,matchAll:Qw,isHTMLForm:Zw,hasOwnProperty:ql,hasOwnProp:ql,hasOwnInPrototypeChain:uo,getSafeProp:_w,reduceDescriptors:$p,freezeMethods:r0,toObjectSet:a0,toCamelCase:e0,noop:i0,toFiniteNumber:s0,findKey:Lp,global:pi,isContextDefined:Mp,isSpecCompliantForm:o0,toJSONObject:l0,isAsyncFn:c0,isThenable:u0,setImmediate:Np,asap:d0,isIterable:Ip,isSafeIterable:o=>o!=null&&uo(o,co)&&Ip(o)},f0=F.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),h0=o=>{const e={};let n,a,i;return o&&o.split(` +`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),a=c.substring(i+1).trim(),!(!n||e[n]&&f0[n])&&(n==="set-cookie"?e[n]?e[n].push(a):e[n]=[a]:e[n]=e[n]?e[n]+", "+a:a)}),e};function g0(o){let e=0,n=o.length;for(;ee;){const a=o.charCodeAt(n-1);if(a!==9&&a!==32)break;n-=1}return e===0&&n===o.length?o:o.slice(e,n)}const p0=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),m0=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Ad(o,e){return F.isArray(o)?o.map(n=>Ad(n,e)):g0(String(o).replace(e,""))}const y0=o=>Ad(o,p0),b0=o=>Ad(o,m0);function Hp(o){const e=Object.create(null);return F.forEach(o.toJSON(),(n,a)=>{e[a]=b0(n)}),e}const jp=Symbol("internals");function ho(o){return o&&String(o).trim().toLowerCase()}function Fl(o){return o===!1||o==null?o:F.isArray(o)?o.map(Fl):y0(String(o))}function v0(o){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=n.exec(o);)e[a[1]]=a[2];return e}const S0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function xd(o,e,n,a,i){if(F.isFunction(a))return a.call(this,e,n);if(i&&(e=n),!!F.isString(e)){if(F.isString(a))return e.indexOf(a)!==-1;if(F.isRegExp(a))return a.test(e)}}function w0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,a)=>n.toUpperCase()+a)}function C0(o,e){const n=F.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(o,a+n,{__proto__:null,value:function(i,l,c){return this[a].call(this,e,i,l,c)},configurable:!0})})}let An=class{constructor(e){e&&this.set(e)}set(e,n,a){const i=this;function l(d,f,g){const m=ho(f);if(!m)return;const y=F.findKey(i,m);(!y||i[y]===void 0||g===!0||g===void 0&&i[y]!==!1)&&(i[y||f]=Fl(d))}const c=(d,f)=>F.forEach(d,(g,m)=>l(g,m,f));if(F.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(F.isString(e)&&(e=e.trim())&&!S0(e))c(h0(e),n);else if(F.isObject(e)&&F.isSafeIterable(e)){let d=Object.create(null),f,g;for(const m of e){if(!F.isArray(m))throw new TypeError("Object iterator must return a key-value pair");g=m[0],F.hasOwnProp(d,g)?(f=d[g],d[g]=F.isArray(f)?[...f,m[1]]:[f,m[1]]):d[g]=m[1]}c(d,n)}else e!=null&&l(n,e,a);return this}get(e,n){if(e=ho(e),e){const a=F.findKey(this,e);if(a){const i=this[a];if(!n)return i;if(n===!0)return v0(i);if(F.isFunction(n))return n.call(this,i,a);if(F.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ho(e),e){const a=F.findKey(this,e);return!!(a&&this[a]!==void 0&&(!n||xd(this,this[a],a,n)))}return!1}delete(e,n){const a=this;let i=!1;function l(c){if(c=ho(c),c){const d=F.findKey(a,c);d&&(!n||xd(a,a[d],d,n))&&(delete a[d],i=!0)}}return F.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let a=n.length,i=!1;for(;a--;){const l=n[a];(!e||xd(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,a={};return F.forEach(this,(i,l)=>{const c=F.findKey(a,l);if(c){n[c]=Fl(i),delete n[l];return}const d=e?w0(l):String(l).trim();d!==l&&delete n[l],n[d]=Fl(i),a[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return F.forEach(this,(a,i)=>{a!=null&&a!==!1&&(n[i]=e&&F.isArray(a)?a.join(", "):a)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const a=new this(e);return n.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[jp]=this[jp]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ho(c);a[d]||(C0(i,c),a[d]=!0)}return F.isArray(e)?e.forEach(l):l(e),this}};An.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),F.reduceDescriptors(An.prototype,({value:o},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(a){this[n]=a}}}),F.freezeMethods(An);const E0="[REDACTED ****]";function _0(o){if(F.hasOwnProp(o,"toJSON"))return!0;let e=Object.getPrototypeOf(o);for(;e&&e!==Object.prototype;){if(F.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function A0(o,e){const n=new Set(e.map(l=>String(l).toLowerCase())),a=[],i=l=>{if(l===null||typeof l!="object"||F.isBuffer(l))return l;if(a.indexOf(l)!==-1)return;l instanceof An&&(l=l.toJSON()),a.push(l);let c;if(F.isArray(l))c=[],l.forEach((d,f)=>{const g=i(d);F.isUndefined(g)||(c[f]=g)});else{if(!F.isPlainObject(l)&&_0(l))return a.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const g=n.has(d.toLowerCase())?E0:i(f);F.isUndefined(g)||(c[d]=g)}}return a.pop(),c};return i(o)}let Ce=class FS extends Error{static from(e,n,a,i,l,c){const d=new FS(e.message,n||e.code,a,i,l);return Object.defineProperty(d,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),d.name=e.name,e.status!=null&&d.status==null&&(d.status=e.status),c&&Object.assign(d,c),d}constructor(e,n,a,i,l){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),a&&(this.config=a),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&F.hasOwnProp(e,"redact")?e.redact:void 0,a=F.isArray(n)&&n.length>0?A0(e,n):F.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a,code:this.code,status:this.status}}};Ce.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Ce.ERR_BAD_OPTION="ERR_BAD_OPTION",Ce.ECONNABORTED="ECONNABORTED",Ce.ETIMEDOUT="ETIMEDOUT",Ce.ECONNREFUSED="ECONNREFUSED",Ce.ERR_NETWORK="ERR_NETWORK",Ce.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Ce.ERR_DEPRECATED="ERR_DEPRECATED",Ce.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Ce.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Ce.ERR_CANCELED="ERR_CANCELED",Ce.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Ce.ERR_INVALID_URL="ERR_INVALID_URL",Ce.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const x0=null,zp=100;function Td(o){return F.isPlainObject(o)||F.isArray(o)}function Up(o){return F.endsWith(o,"[]")?o.slice(0,-2):o}function Rd(o,e,n){return o?o.concat(e).map(function(i,l){return i=Up(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function T0(o){return F.isArray(o)&&!o.some(Td)}const R0=F.toFlatObject(F,{},null,function(e){return/^is[A-Z]/.test(e)});function Kl(o,e,n){if(!F.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,n=F.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(M,T){return!F.isUndefined(T[M])});const a=n.metaTokens,i=n.visitor||_,l=n.dots,c=n.indexes,d=n.Blob||typeof Blob<"u"&&Blob,f=n.maxDepth===void 0?zp:n.maxDepth,g=d&&F.isSpecCompliantForm(e),m=[];if(!F.isFunction(i))throw new TypeError("visitor must be a function");function y(O){if(O===null)return"";if(F.isDate(O))return O.toISOString();if(F.isBoolean(O))return O.toString();if(!g&&F.isBlob(O))throw new Ce("Blob is not supported. Use a Buffer instead.");if(F.isArrayBuffer(O)||F.isTypedArray(O)){if(g&&typeof d=="function")return new d([O]);if(typeof Buffer<"u")return Buffer.from(O);throw new Ce("Blob is not supported. Use a Buffer instead.",Ce.ERR_NOT_SUPPORT)}return O}function S(O){if(O>f)throw new Ce("Object is too deeply nested ("+O+" levels). Max depth: "+f,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function v(O,M){if(f===1/0)return JSON.stringify(O);const T=[];return JSON.stringify(O,function(z,P){if(!F.isObject(P))return P;for(;T.length&&T[T.length-1]!==this;)T.pop();return T.push(P),S(M+T.length-1),P})}function _(O,M,T){let D=O;if(F.isReactNative(e)&&F.isReactNativeBlob(O))return e.append(Rd(T,M,l),y(O)),!1;if(O&&!T&&typeof O=="object"){if(F.endsWith(M,"{}"))M=a?M:M.slice(0,-2),O=v(O,1);else if(F.isArray(O)&&T0(O)||(F.isFileList(O)||F.endsWith(M,"[]"))&&(D=F.toArray(O)))return M=Up(M),D.forEach(function(P,q){!(F.isUndefined(P)||P===null)&&e.append(c===!0?Rd([M],q,l):c===null?M:M+"[]",y(P))}),!1}return Td(O)?!0:(e.append(Rd(T,M,l),y(O)),!1)}const A=Object.assign(R0,{defaultVisitor:_,convertValue:y,isVisitable:Td});function x(O,M,T=0){if(!F.isUndefined(O)){if(S(T),m.indexOf(O)!==-1)throw new Error("Circular reference detected in "+M.join("."));m.push(O),F.forEach(O,function(z,P){(!(F.isUndefined(z)||z===null)&&i.call(e,z,F.isString(P)?P.trim():P,M,A))===!0&&x(z,M?M.concat(P):[P],T+1)}),m.pop()}}if(!F.isObject(o))throw new TypeError("data must be an object");return x(o),e}function Pp(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(o).replace(/[!'()~]|%20/g,function(a){return e[a]})}function kd(o,e){this._pairs=[],o&&Kl(o,this,e)}const Bp=kd.prototype;Bp.append=function(e,n){this._pairs.push([e,n])},Bp.toString=function(e){const n=e?a=>e.call(this,a,Pp):Pp;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function k0(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function qp(o,e,n){if(!e)return o;o=o||"";const a=F.isFunction(n)?{serialize:n}:n,i=F.getSafeProp(a,"encode")||k0,l=F.getSafeProp(a,"serialize");let c;if(l?c=l(e,a):c=F.isURLSearchParams(e)?e.toString():new kd(e,a).toString(i),c){const d=o.indexOf("#");d!==-1&&(o=o.slice(0,d)),o+=(o.indexOf("?")===-1?"?":"&")+c}return o}class Gp{constructor(){this.handlers=[]}use(e,n,a){return this.handlers.push({fulfilled:e,rejected:n,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){F.forEach(this.handlers,function(a){a!==null&&e(a)})}}const Dd={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},D0={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:kd,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Od=typeof window<"u"&&typeof document<"u",Ld=typeof navigator=="object"&&navigator||void 0,O0=Od&&(!Ld||["ReactNative","NativeScript","NS"].indexOf(Ld.product)<0),L0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",M0=Od&&window.location.href||"http://localhost",mn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Od,hasStandardBrowserEnv:O0,hasStandardBrowserWebWorkerEnv:L0,navigator:Ld,origin:M0},Symbol.toStringTag,{value:"Module"})),...D0};function $0(o,e){return Kl(o,new mn.classes.URLSearchParams,{visitor:function(n,a,i,l){return mn.isNode&&F.isBuffer(n)?(this.append(a,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Vp=zp;function Fp(o){if(o>Vp)throw new Ce("FormData field is too deeply nested ("+o+" levels). Max depth: "+Vp,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function N0(o){const e=[],n=/\w+|\[(\w*)]/g;let a;for(;(a=n.exec(o))!==null;)Fp(e.length),e.push(a[0]==="[]"?"":a[1]||a[0]);return e}function I0(o){const e={},n=Object.keys(o);let a;const i=n.length;let l;for(a=0;a=n.length;return c=!c&&F.isArray(i)?i.length:c,f?(F.hasOwnProp(i,c)?i[c]=F.isArray(i[c])?i[c].concat(a):[i[c],a]:i[c]=a,!d):((!F.hasOwnProp(i,c)||!F.isObject(i[c]))&&(i[c]=[]),e(n,a,i[c],l)&&F.isArray(i[c])&&(i[c]=I0(i[c])),!d)}if(F.isFormData(o)&&F.isFunction(o.entries)){const n={};return F.forEachEntry(o,(a,i)=>{e(N0(a),i,n,0)}),n}return null}const ls=(o,e)=>o!=null&&F.hasOwnProp(o,e)?o[e]:void 0;function H0(o,e,n){if(F.isString(o))try{return(e||JSON.parse)(o),F.trim(o)}catch(a){if(a.name!=="SyntaxError")throw a}return(n||JSON.stringify)(o)}const go={transitional:Dd,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const a=n.getContentType()||"",i=a.indexOf("application/json")>-1,l=F.isObject(e);if(l&&F.isHTMLForm(e)&&(e=new FormData(e)),F.isFormData(e))return i?JSON.stringify(Kp(e)):e;if(F.isArrayBuffer(e)||F.isBuffer(e)||F.isStream(e)||F.isFile(e)||F.isBlob(e)||F.isReadableStream(e))return e;if(F.isArrayBufferView(e))return e.buffer;if(F.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=ls(this,"formSerializer");if(a.indexOf("application/x-www-form-urlencoded")>-1)return $0(e,f).toString();if((d=F.isFileList(e))||a.indexOf("multipart/form-data")>-1){const g=ls(this,"env"),m=g&&g.FormData;return Kl(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),H0(e)):e}],transformResponse:[function(e){const n=ls(this,"transitional")||go.transitional,a=n&&n.forcedJSONParsing,i=ls(this,"responseType"),l=i==="json";if(F.isResponse(e)||F.isReadableStream(e))return e;if(e&&F.isString(e)&&(a&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,ls(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?Ce.from(f,Ce.ERR_BAD_RESPONSE,this,null,ls(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:mn.classes.FormData,Blob:mn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};F.forEach(["delete","get","head","post","put","patch","query"],o=>{go.headers[o]={}});function Md(o,e){const n=this||go,a=e||n,i=An.from(a.headers);let l=a.data;return F.forEach(o,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Wp(o){return!!(o&&o.__CANCEL__)}let po=class extends Ce{constructor(e,n,a){super(e??"canceled",Ce.ERR_CANCELED,n,a),this.name="CanceledError",this.__CANCEL__=!0}};function Yp(o,e,n){const a=n.config.validateStatus;!n.status||!a||a(n.status)?o(n):e(new Ce("Request failed with status code "+n.status,n.status>=400&&n.status<500?Ce.ERR_BAD_REQUEST:Ce.ERR_BAD_RESPONSE,n.config,n.request,n))}function j0(o){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(o);return e&&e[1]||""}function z0(o,e){o=o||10;const n=new Array(o),a=new Array(o);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=a[l];c||(c=g),n[i]=f,a[i]=g;let y=l,S=0;for(;y!==i;)S+=n[y++],y=y%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-c{n=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),y=m-n;y>=a?c(g,m):(i=g,l||(l=setTimeout(()=>{l=null,c(i)},a-y)))},()=>i&&c(i)]}const Wl=(o,e,n=3)=>{let a=0;const i=z0(50,250);return U0(l=>{if(!l||typeof l.loaded!="number")return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=d!=null?Math.min(c,d):c,g=Math.max(0,f-a),m=i(g);a=Math.max(a,f);const y={loaded:f,total:d,progress:d?f/d:void 0,bytes:g,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(y)},n)},Xp=(o,e)=>{const n=o!=null;return[a=>e[0]({lengthComputable:n,total:o,loaded:a}),e[1]]},Jp=o=>(...e)=>F.asap(()=>o(...e)),P0=mn.hasStandardBrowserEnv?((o,e)=>n=>(n=new URL(n,mn.origin),o.protocol===n.protocol&&o.host===n.host&&(e||o.port===n.port)))(new URL(mn.origin),mn.navigator&&/(msie|trident)/i.test(mn.navigator.userAgent)):()=>!0,B0=mn.hasStandardBrowserEnv?{write(o,e,n,a,i,l,c){if(typeof document>"u")return;const d=[`${o}=${encodeURIComponent(e)}`];F.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),F.isString(a)&&d.push(`path=${a}`),F.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),F.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(o){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;no instanceof An?{...o}:o;function mi(o,e){o=o||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function a(m,y,S,v){return F.isPlainObject(m)&&F.isPlainObject(y)?F.merge.call({caseless:v},m,y):F.isPlainObject(y)?F.merge({},y):F.isArray(y)?y.slice():y}function i(m,y,S,v){if(F.isUndefined(y)){if(!F.isUndefined(m))return a(void 0,m,S,v)}else return a(m,y,S,v)}function l(m,y){if(!F.isUndefined(y))return a(void 0,y)}function c(m,y){if(F.isUndefined(y)){if(!F.isUndefined(m))return a(void 0,m)}else return a(void 0,y)}function d(m){const y=F.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!F.isUndefined(y))if(F.isPlainObject(y)){if(F.hasOwnProp(y,m))return y[m]}else return;const S=F.hasOwnProp(o,"transitional")?o.transitional:void 0;if(F.isPlainObject(S)&&F.hasOwnProp(S,m))return S[m]}function f(m,y,S){if(F.hasOwnProp(e,S))return a(m,y);if(F.hasOwnProp(o,S))return a(void 0,m)}const g={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,allowedSocketPaths:c,responseEncoding:c,validateStatus:f,headers:(m,y,S)=>i(em(m),em(y),S,!0)};return F.forEach(Object.keys({...o,...e}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const S=F.hasOwnProp(g,y)?g[y]:i,v=F.hasOwnProp(o,y)?o[y]:void 0,_=F.hasOwnProp(e,y)?e[y]:void 0,A=S(v,_,y);F.isUndefined(A)&&S!==f||(n[y]=A)}),F.hasOwnProp(e,"validateStatus")&&F.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(F.hasOwnProp(o,"validateStatus")?n.validateStatus=a(void 0,o.validateStatus):delete n.validateStatus),n}const Y0=["content-type","content-length"];function X0(o,e,n){if(n!=="content-only"){o.set(e);return}Object.entries(e||{}).forEach(([a,i])=>{Y0.includes(a.toLowerCase())&&o.set(a,i)})}const J0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function tm(o){const e=mi({},o),n=S=>F.hasOwnProp(e,S)?e[S]:void 0,a=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),g=n("baseURL"),m=n("allowAbsoluteUrls"),y=n("url");if(e.headers=d=An.from(d),e.url=qp(Zp(g,y,m,e),n("params"),n("paramsSerializer")),f){const S=F.getSafeProp(f,"username")||"",v=F.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(S+":"+(v?J0(v):"")))}catch(_){throw Ce.from(_,Ce.ERR_BAD_OPTION_VALUE,o)}}if(F.isFormData(a)&&(mn.hasStandardBrowserEnv||mn.hasStandardBrowserWebWorkerEnv||F.isReactNative(a)?d.setContentType(void 0):F.isFunction(a.getHeaders)&&X0(d,a.getHeaders(),n("formDataHeaderPolicy"))),mn.hasStandardBrowserEnv&&(F.isFunction(i)&&(i=i(e)),i===!0||i==null&&P0(e.url))){const v=l&&c&&B0.read(c);v&&d.set(l,v)}return e}const Q0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(n,a){const i=tm(o);let l=i.data;const c=An.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,y,S,v,_;function A(){v&&v(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function O(){if(!x)return;const T=An.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),z={data:!d||d==="text"||d==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:T,config:o,request:x};Yp(function(q){n(q),A()},function(q){a(q),A()},z),x=null}"onloadend"in x?x.onloadend=O:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.startsWith("file:"))||setTimeout(O)},x.onabort=function(){x&&(a(new Ce("Request aborted",Ce.ECONNABORTED,o,x)),A(),x=null)},x.onerror=function(D){const z=D&&D.message?D.message:"Network Error",P=new Ce(z,Ce.ERR_NETWORK,o,x);P.event=D||null,a(P),A(),x=null},x.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const z=i.transitional||Dd;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),a(new Ce(D,z.clarifyTimeoutError?Ce.ETIMEDOUT:Ce.ECONNABORTED,o,x)),A(),x=null},l===void 0&&c.setContentType(null),"setRequestHeader"in x&&F.forEach(Hp(c),function(D,z){x.setRequestHeader(z,D)}),F.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),d&&d!=="json"&&(x.responseType=i.responseType),g&&([S,_]=Wl(g,!0),x.addEventListener("progress",S)),f&&x.upload&&([y,v]=Wl(f),x.upload.addEventListener("progress",y),x.upload.addEventListener("loadend",v)),(i.cancelToken||i.signal)&&(m=T=>{x&&(a(!T||T.type?new po(null,o,x):T),x.abort(),A(),x=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=j0(i.url);if(M&&!mn.protocols.includes(M)){a(new Ce("Unsupported protocol "+M+":",Ce.ERR_BAD_REQUEST,o)),A();return}x.send(l||null)})},Z0=(o,e)=>{if(o=o?o.filter(Boolean):[],!e&&!o.length)return;const n=new AbortController;let a=!1;const i=function(f){if(!a){a=!0,c();const g=f instanceof Error?f:this.reason;n.abort(g instanceof Ce?g:new po(g instanceof Error?g.message:g))}};let l=e&&setTimeout(()=>{l=null,i(new Ce(`timeout of ${e}ms exceeded`,Ce.ETIMEDOUT))},e);const c=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),o=null)};o.forEach(f=>f.addEventListener("abort",i,{once:!0}));const{signal:d}=n;return d.unsubscribe=()=>F.asap(c),d},eC=function*(o,e){let n=o.byteLength;if(n{const i=tC(o,e);let l=0,c,d=f=>{c||(c=!0,a&&a(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let y=m.byteLength;if(n){let S=l+=y;n(S)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},Yl=o=>o>=48&&o<=57||o>=65&&o<=70||o>=97&&o<=102,rC=(o,e,n)=>e+2v>=2&&a.charCodeAt(v-2)===37&&a.charCodeAt(v-1)===51&&(a.charCodeAt(v)===68||a.charCodeAt(v)===100);g>=0&&(a.charCodeAt(g)===61?(f++,g--):m(g)&&(f++,g-=3)),f===1&&g>=0&&(a.charCodeAt(g)===61||m(g))&&f++;const S=Math.floor(c/4)*3-(f||0);return S>0?S:0}let l=0;for(let c=0,d=a.length;c=55296&&f<=56319&&c+1=56320&&g<=57343?(l+=4,c++):l+=3}else l+=3}return l}const $d="1.18.1",rm=64*1024,{isFunction:Xl}=F,iC=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),am=o=>{if(!F.isString(o))return o;try{return decodeURIComponent(o)}catch{return o}},im=(o,...e)=>{try{return!!o(...e)}catch{return!1}},sC=o=>{const e=o.indexOf("://");let n=o;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},oC=o=>{const e=F.global!==void 0&&F.global!==null?F.global:globalThis,{ReadableStream:n,TextEncoder:a}=e;o=F.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},o);const{fetch:i,Request:l,Response:c}=o,d=i?Xl(i):typeof fetch=="function",f=Xl(l),g=Xl(c);if(!d)return!1;const m=d&&Xl(n),y=d&&(typeof a=="function"?(O=>M=>O.encode(M))(new a):async O=>new Uint8Array(await new l(O).arrayBuffer())),S=f&&m&&im(()=>{let O=!1;const M=new l(mn.origin,{body:new n,method:"POST",get duplex(){return O=!0,"half"}}),T=M.headers.has("Content-Type");return M.body!=null&&M.body.cancel(),O&&!T}),v=g&&m&&im(()=>F.isReadableStream(new c("").body)),_={stream:v&&(O=>O.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(O=>{!_[O]&&(_[O]=(M,T)=>{let D=M&&M[O];if(D)return D.call(M);throw new Ce(`Response type '${O}' is not supported`,Ce.ERR_NOT_SUPPORT,T)})});const A=async O=>{if(O==null)return 0;if(F.isBlob(O))return O.size;if(F.isSpecCompliantForm(O))return(await new l(mn.origin,{method:"POST",body:O}).arrayBuffer()).byteLength;if(F.isArrayBufferView(O)||F.isArrayBuffer(O))return O.byteLength;if(F.isURLSearchParams(O)&&(O=O+""),F.isString(O))return(await y(O)).byteLength},x=async(O,M)=>{const T=F.toFiniteNumber(O.getContentLength());return T??A(M)};return async O=>{let{url:M,method:T,data:D,signal:z,cancelToken:P,timeout:q,onDownloadProgress:W,onUploadProgress:he,responseType:Ee,headers:be,withCredentials:Ue="same-origin",fetchOptions:Fe,maxContentLength:Ge,maxBodyLength:wt}=tm(O);const J=F.isNumber(Ge)&&Ge>-1,ue=F.isNumber(wt)&&wt>-1,Me=ee=>F.hasOwnProp(O,ee)?O[ee]:void 0;let te=i||fetch;Ee=Ee?(Ee+"").toLowerCase():"text";let pe=Z0([z,P&&P.toAbortSignal()],q),N=null;const R=pe&&pe.unsubscribe&&(()=>{pe.unsubscribe()});let de,fe=null;const xe=()=>new Ce("Request body larger than maxBodyLength limit",Ce.ERR_BAD_REQUEST,O,N);try{let ee;const _e=Me("auth");if(_e){const Oe=F.getSafeProp(_e,"username")||"",nt=F.getSafeProp(_e,"password")||"";ee={username:Oe,password:nt}}if(sC(M)){const Oe=new URL(M,mn.origin);if(!ee&&(Oe.username||Oe.password)){const nt=am(Oe.username),sn=am(Oe.password);ee={username:nt,password:sn}}(Oe.username||Oe.password)&&(Oe.username="",Oe.password="",M=Oe.href)}if(ee&&(be.delete("authorization"),be.set("Authorization","Basic "+btoa(iC((ee.username||"")+":"+(ee.password||""))))),J&&typeof M=="string"&&M.startsWith("data:")&&aC(M)>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N);if(ue&&T!=="get"&&T!=="head"){const Oe=await A(D);if(typeof Oe=="number"&&isFinite(Oe)&&(de=Oe,Oe>wt))throw xe()}const Be=ue&&(F.isReadableStream(D)||F.isStream(D)),ke=(Oe,nt,sn)=>nm(Oe,rm,Mt=>{if(ue&&Mt>wt)throw fe=xe();nt&&nt(Mt)},sn);if(S&&T!=="get"&&T!=="head"&&(he||Be)){if(de=de??await x(be,D),de!==0||Be){let Oe=new l(M,{method:"POST",body:D,duplex:"half"}),nt;if(F.isFormData(D)&&(nt=Oe.headers.get("content-type"))&&be.setContentType(nt),Oe.body){const[sn,Mt]=he&&Xp(de,Wl(Jp(he)))||[];D=ke(Oe.body,sn,Mt)}}}else if(Be&&!f&&m&&T!=="get"&&T!=="head")D=ke(D);else if(Be&&f&&!S&&T!=="get"&&T!=="head")throw new Ce("Stream request bodies are not supported by the current fetch implementation",Ce.ERR_NOT_SUPPORT,O,N);F.isString(Ue)||(Ue=Ue?"include":"omit");const Ie=f&&"credentials"in l.prototype;if(F.isFormData(D)){const Oe=be.getContentType();Oe&&/^multipart\/form-data/i.test(Oe)&&!/boundary=/i.test(Oe)&&be.delete("content-type")}be.set("User-Agent","axios/"+$d,!1);const Ct={...Fe,signal:pe,method:T.toUpperCase(),headers:Hp(be.normalize()),body:D,duplex:"half",credentials:Ie?Ue:void 0};N=f&&new l(M,Ct);let ot=await(f?te(N,Fe):te(M,Ct));const Ot=An.from(ot.headers);if(J){const Oe=F.toFiniteNumber(Ot.getContentLength());if(Oe!=null&&Oe>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N)}const vt=v&&(Ee==="stream"||Ee==="response");if(v&&ot.body&&(W||J||vt&&R)){const Oe={};["status","statusText","headers"].forEach(ln=>{Oe[ln]=ot[ln]});const nt=F.toFiniteNumber(Ot.getContentLength()),[sn,Mt]=W&&Xp(nt,Wl(Jp(W),!0))||[];let Vt=0;const on=ln=>{if(J&&(Vt=ln,Vt>Ge))throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N);sn&&sn(ln)};ot=new c(nm(ot.body,rm,on,()=>{Mt&&Mt(),R&&R()}),Oe)}Ee=Ee||"text";let _t=await _[F.findKey(_,Ee)||"text"](ot,O);if(J&&!v&&!vt){let Oe;if(_t!=null&&(typeof _t.byteLength=="number"?Oe=_t.byteLength:typeof _t.size=="number"?Oe=_t.size:typeof _t=="string"&&(Oe=typeof a=="function"?new a().encode(_t).byteLength:_t.length)),typeof Oe=="number"&&Oe>Ge)throw new Ce("maxContentLength size of "+Ge+" exceeded",Ce.ERR_BAD_RESPONSE,O,N)}return!vt&&R&&R(),await new Promise((Oe,nt)=>{Yp(Oe,nt,{data:_t,headers:An.from(ot.headers),status:ot.status,statusText:ot.statusText,config:O,request:N})})}catch(ee){if(R&&R(),pe&&pe.aborted&&pe.reason instanceof Ce){const _e=pe.reason;throw _e.config=O,N&&(_e.request=N),ee!==_e&&Object.defineProperty(_e,"cause",{__proto__:null,value:ee,writable:!0,enumerable:!1,configurable:!0}),_e}if(fe)throw N&&!fe.request&&(fe.request=N),fe;if(ee instanceof Ce)throw N&&!ee.request&&(ee.request=N),ee;if(ee&&ee.name==="TypeError"&&/Load failed|fetch/i.test(ee.message)){const _e=new Ce("Network Error",Ce.ERR_NETWORK,O,N,ee&&ee.response);throw Object.defineProperty(_e,"cause",{__proto__:null,value:ee.cause||ee,writable:!0,enumerable:!1,configurable:!0}),_e}throw Ce.from(ee,ee&&ee.code,O,N,ee&&ee.response)}}},lC=new Map,sm=o=>{let e=o&&o.env||{};const{fetch:n,Request:a,Response:i}=e,l=[a,i,n];let c=l.length,d=c,f,g,m=lC;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:oC(e)),m=g;return g};sm();const Nd={http:x0,xhr:Q0,fetch:{get:sm}};F.forEach(Nd,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(o,"adapterName",{__proto__:null,value:e})}});const om=o=>`- ${o}`,cC=o=>F.isFunction(o)||o===null||o===!1;function uC(o,e){o=F.isArray(o)?o:[o];const{length:n}=o;let a,i;const l={};for(let c=0;c`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : +`+c.map(om).join(` +`):" "+om(c[0]):"as no adapter specified";throw new Ce("There is no suitable adapter to dispatch the request "+d,Ce.ERR_NOT_SUPPORT)}return i}const lm={getAdapter:uC,adapters:Nd};function Id(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new po(null,o)}function cm(o){return Id(o),o.headers=An.from(o.headers),o.data=Md.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),lm.getAdapter(o.adapter||go.adapter,o)(o).then(function(a){Id(o),o.response=a;try{a.data=Md.call(o,o.transformResponse,a)}finally{delete o.response}return a.headers=An.from(a.headers),a},function(a){if(!Wp(a)&&(Id(o),a&&a.response)){o.response=a.response;try{a.response.data=Md.call(o,o.transformResponse,a.response)}finally{delete o.response}a.response.headers=An.from(a.response.headers)}return Promise.reject(a)})}const Jl={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{Jl[o]=function(a){return typeof a===o||"a"+(e<1?"n ":" ")+o}});const um={};Jl.transitional=function(e,n,a){function i(l,c){return"[Axios v"+$d+"] Transitional option '"+l+"'"+c+(a?". "+a:"")}return(l,c,d)=>{if(e===!1)throw new Ce(i(c," has been removed"+(n?" in "+n:"")),Ce.ERR_DEPRECATED);return n&&!um[c]&&(um[c]=!0,console.warn(i(c," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,c,d):!0}},Jl.spelling=function(e){return(n,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function dC(o,e,n){if(typeof o!="object"||o===null)throw new Ce("options must be an object",Ce.ERR_BAD_OPTION_VALUE);const a=Object.keys(o);let i=a.length;for(;i-- >0;){const l=a[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=o[l],f=d===void 0||c(d,l,o);if(f!==!0)throw new Ce("option "+l+" must be "+f,Ce.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ce("Unknown option "+l,Ce.ERR_BAD_OPTION)}}const Ql={assertOptions:dC,validators:Jl},xn=Ql.validators;let yi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Gp,response:new Gp}}async request(e,n){try{return await this._request(e,n)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(` `);return c===-1?"":i.stack.slice(c+1)})();try{if(!a.stack)a.stack=l;else if(l){const c=l.indexOf(` `),d=c===-1?-1:l.indexOf(` `,c+1),f=d===-1?"":l.slice(d+1);String(a.stack).endsWith(f)||(a.stack+=` -`+l)}}catch{}}throw a}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=mi(this.defaults,n);const{transitional:a,paramsSerializer:i,headers:l}=n;a!==void 0&&Ql.assertOptions(a,{silentJSONParsing:xn.transitional(xn.boolean),forcedJSONParsing:xn.transitional(xn.boolean),clarifyTimeoutError:xn.transitional(xn.boolean),legacyInterceptorReqResOrdering:xn.transitional(xn.boolean),advertiseZstdAcceptEncoding:xn.transitional(xn.boolean),validateStatusUndefinedResolves:xn.transitional(xn.boolean)},!1),i!=null&&(F.isFunction(i)?n.paramsSerializer={serialize:i}:Ql.assertOptions(i,{encode:xn.function,serialize:xn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ql.assertOptions(n,{baseUrl:xn.spelling("baseURL"),withXsrfToken:xn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let c=l&&F.merge(l.common,l[n.method]);l&&F.forEach(["delete","get","head","post","put","patch","query","common"],_=>{delete l[_]}),n.headers=An.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(n)===!1)return;f=f&&A.synchronous;const x=n.transitional||kd;x&&x.legacyInterceptorReqResOrdering?d.unshift(A.fulfilled,A.rejected):d.push(A.fulfilled,A.rejected)});const g=[];this.interceptors.response.forEach(function(A){g.push(A.fulfilled,A.rejected)});let m,y=0,S;if(!f){const _=[um.bind(this),void 0];for(_.unshift(...d),_.push(...g),S=_.length,m=Promise.resolve(n);y{if(!a._listeners)return;let l=a._listeners.length;for(;l-- >0;)a._listeners[l](i);a._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{a.subscribe(d),l=d}).then(i);return c.cancel=function(){a.unsubscribe(l)},c},e(function(l,c,d){a.reason||(a.reason=new po(l,c,d),n(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=a=>{e.abort(a)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new WS(function(i){e=i}),cancel:e}}};function hC(o){return function(n){return o.apply(null,n)}}function gC(o){return F.isObject(o)&&o.isAxiosError===!0}const Id={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Id).forEach(([o,e])=>{Id[e]=o});function fm(o){const e=new yi(o),n=Tp(yi.prototype.request,e);return F.extend(n,yi.prototype,e,{allOwnKeys:!0}),F.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return fm(mi(o,i))},n}const Yt=fm(go);Yt.Axios=yi,Yt.CanceledError=po,Yt.CancelToken=fC,Yt.isCancel=Yp,Yt.VERSION=Md,Yt.toFormData=Kl,Yt.AxiosError=Ce,Yt.Cancel=Yt.CanceledError,Yt.all=function(e){return Promise.all(e)},Yt.spread=hC,Yt.isAxiosError=gC,Yt.mergeConfig=mi,Yt.AxiosHeaders=An,Yt.formToJSON=o=>Wp(F.isHTMLForm(o)?new FormData(o):o),Yt.getAdapter=cm.getAdapter,Yt.HttpStatusCode=Id,Yt.default=Yt;const{Axios:OT,AxiosError:LT,CanceledError:MT,isCancel:$T,CancelToken:NT,VERSION:IT,all:HT,Cancel:jT,isAxiosError:zT,spread:UT,toFormData:PT,AxiosHeaders:BT,HttpStatusCode:qT,formToJSON:GT,getAdapter:VT,mergeConfig:FT,create:KT}=Yt,Hd="g7.identity.redirectStash",Zl=ht("IdentityGuardInterceptor");class Et{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){Zl.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,a){this.domainNoticeShown=!1;const i=this.launcher??mC,c=!!(a&&(a.email||a.phone))?{...e.verification,target:a}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const g=pC(f.url,d.token);return fetch(g,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return Zl.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const a={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Hd,JSON.stringify(a))}catch(i){Zl.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(Et,"launcher",null),$(Et,"deferredResolver",null),$(Et,"domainNoticeShown",!1);function pC(o,e){if(!e)return o;try{const n=typeof window<"u"?window.location.origin:"http://localhost",a=new URL(o,n);return a.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?a.toString():`${a.pathname}${a.search}${a.hash}`}catch{const n=o.includes("?")?"&":"?";return`${o}${n}verification_token=${encodeURIComponent(e)}`}}const mC=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return Et.redirectExternally(o);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,a={return_url:n,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Hd,JSON.stringify(a))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){Zl.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},yC=ht("ApiClient");function jd(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class bC{constructor(e={}){$(this,"client");$(this,"config");$(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Yt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const a=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const n=this.getToken();if(n&&e.headers&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=jd();if(a?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=a.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,a=n._devToolsRequestId;if(a){const i=jd();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,a=n?.url||"",l=["/auth/","/layouts/"].some(c=>a.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await br.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(Et.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[S,v]of Object.entries(d))typeof v=="string"&&(c[S]=v);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),c["Content-Type"]=c["Content-Type"]??"application/json");const g=n?.identity_target,m=await Et.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},g);if(!m)return Promise.reject(e);let y=null;try{y=await m.json()}catch{y=null}return m.ok?{...e.response,status:m.status,data:y}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:y}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,a){return(await this.client.post(e,n,a)).data}async put(e,n,a){return(await this.client.put(e,n,a)).data}async patch(e,n,a){return(await this.client.patch(e,n,a)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const a=jd();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?a.completeRequest(i,n.response.status,n.response.data):n.request?a.failRequest(i,n.message||"Network error"):a.failRequest(i,n.message||"Request error")}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const a=e.params,i=[];for(const[l,c]of Object.entries(a))if(c!=null)if(Array.isArray(c)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of c)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(c))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(n)}catch(a){yC.error("Error in onError handler:",a)}}}let zd=null;function Hr(){return zd||(zd=new bC),zd}const mo=ht("AuthManager");function cs(o,e,n,a){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,n,a)}catch{}}const ec={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},Ar=class Ar{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",ec.admin),this.config.set("user",ec.user)}static getInstance(){return Ar.instance||(Ar.instance=new Ar),Ar.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Hr();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return mo.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return mo.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,a){const i=Hr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?ec.admin.loginEndpoint:ec.user.loginEndpoint;try{const d=a?.headers?{headers:a.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(Ar.LOCALE_STORAGE_KEY),y=g&&g!==m;if(g)try{localStorage.setItem(Ar.LOCALE_STORAGE_KEY,g)}catch(S){mo.warn("Failed to save user language to localStorage:",S)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),cs("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,cs("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=Hr(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(a){mo.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),cs("logout",!0,void 0,{previousType:a.type}),n&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const n=this.config.get(e);if(!n)return!1;const a=Hr();try{const i=await a.post(n.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),cs("token-refresh",!0,void 0,{type:e}),!0):(cs("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return mo.error("Token refresh failed:",i),cs("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,a){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return a&&(c+=`&reason=${encodeURIComponent(a)}`),c}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const a=this.config.get(e);a&&this.config.set(e,{...a,...n})}getRedirectUrl(e){const a=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const c=decodeURIComponent(l);if(c.startsWith("/"))return c}catch{}return a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Ar.instance=null}};$(Ar,"instance"),$(Ar,"LOCALE_STORAGE_KEY","g7_locale");let br=Ar;const hm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},Qr={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,n){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?n:a;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},vr=ht("ErrorHandlingResolver"),Ma=class Ma{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Ma.instance||(Ma.instance=new Ma),Ma.instance}static resetInstance(){Ma.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,vr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,vr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:a,onError:i}=n;vr.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Qr.findHandler(a,e);if(l){const c=this.getMatchedKey(a,e);return{handler:Qr.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=Qr.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=Qr.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=Qr.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=Qr.findHandler(hm,e),l){const c=this.getMatchedKey(hm,e);return{handler:Qr.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){vr.error("Action executor is not set");return}vr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(a){throw vr.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,n,a={}){const i=this.resolve(e,a);if(vr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return vr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return vr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,vr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,vr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Ma,"instance",null);let Ud=Ma;function Sr(){return Ud.getInstance()}var Pd={exports:{}},yo={};var gm;function vC(){if(gm)return yo;gm=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(a,i,l){var c=null;if(l!==void 0&&(c=""+l),i.key!==void 0&&(c=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:o,type:a,key:c,ref:i!==void 0?i:null,props:l}}return yo.Fragment=e,yo.jsx=n,yo.jsxs=n,yo}var pm;function SC(){return pm||(pm=1,Pd.exports=vC()),Pd.exports}var gt=SC();const wC=Xr({__proto__:null,default:Jr(gt)},[gt]),Bd=ht("ParentContextProvider"),mm=H.createContext(null);let tc=null;function qd(){tc?(Bd.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),tc()):Bd.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const ym=({children:o})=>{const[e,n]=H.useState(0),a=H.useRef(!0),i=H.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);H.useEffect(()=>(a.current=!0,tc=()=>{a.current&&(n(c=>c+1),Bd.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,tc=null}),[]);const l={version:e,getParentDataContext:i};return gt.jsx(mm.Provider,{value:l,children:o})};function CC(){return H.useContext(mm)}const j=ht("ActionDispatcher");function EC(o,e,n,a){return n||(ap(o)||dd(o)?"$t:core.errors.network_request_failed":a||`Failed to execute action: ${e}`)}const bm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),_C=new Set(["redirect"]);function Fn(){try{return window.G7Core?.devTools}catch{return}}class Bt extends Error{constructor(n,a,i){super(n);$(this,"action");$(this,"originalError");$(this,"unknownHandler",!1);this.action=a,this.originalError=i,this.name="ActionError"}}const bs=class bs{constructor(e={},n,a){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"intervals",new Map);this.bindingEngine=new Dn,this.translationEngine=n,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Fn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),j.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,j.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return bm}static getPreviewSuppressedLayoutFeatures(){return _C}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return j.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=Fn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,g={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(g.key=c),d!==void 0&&(g.event=d),g}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=rs(c,n,{skipCache:!0});d!=null&&d!==""&&(a[l]=String(d))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;Sr().setActionExecutor(async(n,a)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,a)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){j.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...a.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},g=a.data?._local||a.state||{},m={...f,...g},y=a.isolatedContext?.state;j.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...y?{isolatedStateOverride:y}:{}})}else j.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,a)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){j.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){j.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){j.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else j.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,a)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){j.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){j.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(j.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):j.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,a)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:y=0,retryInterval:S=50,scrollContainer:v}=n.params||{};if(!i){j.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){j.warn("scrollIntoView: window/document is not available");return}let _=null;if(f){if(_=await new Promise(A=>{const x=document.querySelector(i);if(x){A(x);return}const O=setTimeout(()=>{M.disconnect(),A(null)},g),M=new MutationObserver(()=>{const T=document.querySelector(i);T&&(clearTimeout(O),M.disconnect(),A(T))});M.observe(document.body,{childList:!0,subtree:!0})}),!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(x=>setTimeout(x,m)),_=document.querySelector(i);let A=0;for(;!_&&AsetTimeout(x,S)),_=document.querySelector(i),A++;if(!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${A+1} attempts`);return}}if(v){const A=document.querySelector(v);if(!A){j.warn(`scrollIntoView: container not found for selector "${v}"`);return}const x=_.getBoundingClientRect(),O=A.getBoundingClientRect(),M=x.top-O.top+A.scrollTop,T=M+x.height;let D;switch(c){case"start":D=M;break;case"center":D=M-A.clientHeight/2+x.height/2;break;case"end":D=T-A.clientHeight;break;default:const z=x.topO.bottom;if(z)D=M;else if(P)D=T-A.clientHeight;else return;break}A.scrollTo({top:Math.max(0,D),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,a)=>{if(typeof window>"u"){j.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw j.error("reloadExtensions: reloadExtensionState failed",d),d}else j.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},a)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},a)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,a)=>{if(typeof window>"u"){j.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw j.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),j.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,a)=>{if(typeof window>"u"){j.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,a)=>{const{componentId:i}=n.params||{};if(!i){j.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){j.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),j.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,a)=>{if(typeof window>"u"){j.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw j.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,a)=>{if(typeof window>"u"){j.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`module-${f}`;if(document.getElementById(m)){j.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((S,v)=>{y.onload=()=>{j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),S()},y.onerror=()=>{j.error(`reloadModuleHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const S=c.assets.css,v=`module-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),j.log(`reloadModuleHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],j.log(`reloadModuleHandlers: Removed assets for ${f}`));const g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,S=document.getElementById(y);S&&(S.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(n,a)=>{if(typeof window>"u"){j.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){j.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((S,v)=>{y.onload=()=>{j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),S()},y.onerror=()=>{j.error(`reloadPluginHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const S=c.assets.css,v=`plugin-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),j.log(`reloadPluginHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],j.log(`reloadPluginHandlers: Removed assets for ${f}`));const g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,S=document.getElementById(y);S&&(S.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(n,a)=>{if(e){j.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,j.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,j.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,j.warn("showErrorPage: ErrorPageHandler not available");return}const c=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),j.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const g=(m,y=6e4)=>new Promise((S,v)=>{const _=document.getElementById(m);if(_){S(_);return}j.log(`showErrorPage: Waiting for container #${m}...`);let A;const x=new MutationObserver((O,M)=>{const T=document.getElementById(m);T&&(j.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(A),S(T))});x.observe(document.body,{childList:!0,subtree:!0}),A=setTimeout(()=>{x.disconnect(),v(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await g(f);const m=Sr(),y=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||j.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(y)}}catch(m){throw j.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,a)=>{const i=n.params?.event,l=n.params?.data;if(!i){j.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){j.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){j.warn("emitEvent: G7Core.componentEvent is not available");return}try{j.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:a.data,state:a.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?j.warn(`emitEvent: No listeners found for "${i}"`):j.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const g=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const y=a.state&&typeof a.state=="object"&&!Array.isArray(a.state)?a.state:g;window.__g7SequenceLocalSync={...y,_eventResult:m}}}catch(d){if(j.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=c?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,a)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){j.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){j.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){j.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(S=>S.id===i?{...S,[l]:c,_modified:!0}:S),y=new Set(f._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(y)}}),j.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw j.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,a)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){j.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){j.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){j.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const g=f.state.get()||{},y=(g.products?.data?.data||[]).map(v=>{if(v.id===i&&v.options){const _=v.options.map(A=>A.id===l?{...A,[c]:d,_modified:!0}:A);return{...v,options:_,_modified:!0}}return v}),S=new Set(g._local?.modifiedProductIds||[]);S.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:y}},_local:{...g._local,modifiedProductIds:Array.from(S)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(g){throw j.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(n,a)=>{const i=n.target;if(!i||typeof i!="string"){j.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),j.log("setLocale: Locale changed to",i)}catch(c){j.error("setLocale: Failed to change locale:",c),window.location.reload()}else{j.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{j.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Fn();if(!e?.isEnabled())return;const n=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const a of n)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,n,a){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=a?.state?{...a.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(j.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??a?.state??{},y=Date.now()-l;for(const S of Object.keys(c)){const v=c[S],_=m[S];v!==_&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${S}`,capturedValue:v,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${S} changed after handler creation:`,`captured="${v}" → current="${_}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const S=f.target;new FormData(S).forEach((_,A)=>{g[A]=_})}const m={...this.defaultContext,data:{...n,form:g,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let S=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext,m.data)),!confirm(S))return}const y=window.__g7ActionContext;window.__g7ActionContext={...a,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(g){if(j.error("Action execution failed:",g),e.onError){const m=g instanceof Bt&&g.originalError?g.originalError:g,y={...this.defaultContext,data:{...n,error:m,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState}},S=Array.isArray(e.onError)?e.onError:[e.onError];for(const v of S)await this.executeAction(v,y)}}}}generateActionId(e,n){const a=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${a}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const a=Fn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,g),!g)return i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return j.error("[executeAction] if condition error:",e.handler,f),i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(c=this.sanitizeForDevTools(f));const g=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,g);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&bm.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const y=f.path||g;m=await this.handleNavigate(y,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const _=f.path||g;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const _=window.G7Core,A={};if(_?.state?.get){const x=_.state.get();A._global=x}n.state&&(A._local=n.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],A)}const S=e.auth_mode??(e.auth_required?"required":"none"),v=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(g,f,n,S,v);break;case"login":m=await this.handleLogin(g,f,n);break;case"logout":m=await this.handleLogout(g,n);break;case"setState":j.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(g,f,n);break;case"openModal":m=await this.handleOpenModal(g,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(g,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:g,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:S,merge:v}=e.resultTo,_=this.resolveValue(S,n.data),A=v==="replace"?"replace":v==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const x=this.buildNestedUpdate(_,m),O=A!=="deep"?{...x,__mergeMode:A}:x;n.setState(O),j.log(`[resultTo] Saved to _local.${_} (merge=${A}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},T=this.buildNestedUpdate(_,m);let D;A==="replace"?D=T:A==="shallow"?D={...M,...T}:D=this.deepMergeWithState(T,M),this.globalStateUpdater({_local:D}),j.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${A}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const x=this.buildNestedUpdate(_,m);this.globalStateUpdater(x),j.log(`[resultTo] Saved to _global.${_}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const x=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(x,A),j.log(`[resultTo] Saved to _isolated.${_} (merge=${A}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const v=window.G7Core,_={};v?.state?.get&&(_._global=v.state.get()),n.state&&(_._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},S=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];S.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:S},y):S.length===1&&await this.executeAction(S[0],y)}return i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const g=f instanceof Bt?f:new Bt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},y=m.data||{},S=g.originalError?.status||m.status||500;let v=EC(g.originalError??f,e.handler,y.message,g.message);this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext));const _={status:S,message:v,errors:y.errors||m.errors,data:y,statusText:g.originalError?.statusText,error_code:y.error_code??m.error_code};if(g.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const x=Sr().resolve(S,{errorHandling:e.errorHandling,onError:e.onError});if(x.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,T={};M?.state?.get&&(T._global=M.state.get()),n.state&&(T._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,T,"callback-state-capture",i)}const O={...n,data:{...n.data,error:_}};try{const M={type:"click",handler:x.handler.handler,target:x.handler.target,params:x.handler.params,actions:x.handler.actions};return await this.executeAction(M,O),{success:!1,error:g}}catch(M){return j.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:g,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,a){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const c=new URLSearchParams;for(const[f,g]of Object.entries(n.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of g)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(g));const d=c.toString();d&&(i=`${e}?${d}`)}if(j.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await c.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),j.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}j.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){j.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},a),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!a.navigate)throw new Bt("Navigate function is not provided in context");a.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const a=n.fallback;if(a===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const c=e.split("?")[0];return l.match(c)?null:this.resolveNavigateFallback(a,e,n)}resolveNavigateFallback(e,n,a){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(j.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,a){const i=e===void 0?a:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const S=y;return"container"in S||"to"in S||"block"in S||"offset"in S},d=(y,S,v=0)=>{y===window?window.scrollTo({top:S,left:v,behavior:l}):y.scrollTo({top:S,left:v,behavior:l})},f=(y,S,v,_)=>{if(S===window){y.scrollIntoView({behavior:l,block:v}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const A=S,x=y.getBoundingClientRect(),O=A.getBoundingClientRect(),M=A.scrollTop+(x.top-O.top);let T;v==="center"?T=M-(A.clientHeight-y.clientHeight)/2:v==="end"?T=M-(A.clientHeight-y.clientHeight):T=M,T-=_,A.scrollTo({top:Math.max(0,T),left:0,behavior:l})},g=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(v=>{if(v.scrollTop===0&&v.scrollLeft===0)return;const _=window.getComputedStyle(v),A=_.overflowY,x=_.overflowX;(A==="auto"||A==="scroll"||x==="auto"||x==="scroll")&&v.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,S=y.block??"start",v=typeof y.offset=="number"?y.offset:0;let _=window;if(typeof y.container=="string"&&y.container.length>0){const x=document.querySelector(y.container);if(!x){j.warn(`applyScrollOption: container not found: ${y.container}`);return}_=x}const A=y.to??"top";if(A==="top"){_===window?g():d(_,0);return}if(typeof A=="number"){d(_,A-v);return}if(typeof A=="object"&&A!==null&&("x"in A||"y"in A)){const{x=0,y:O=0}=A;d(_,O-v,x);return}if(typeof A=="string"&&(A.startsWith("#")||A.startsWith("."))){const x=document.querySelector(A);x?f(x,_,S,v):j.warn(`applyScrollOption: target element not found: ${A}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',A);return}if(i==="top"){g();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:S=0}=i;window.scrollTo({top:S,left:y,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:l,block:"start"});return}}catch(y){j.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let a=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(a=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:n,finalPath:a,windowTarget:i}),i==="_self"?window.location.assign(a):window.open(a,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let a=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)a=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(c,String(d));const l=i.toString();l&&(a=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:n,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const a=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")a.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;a.delete(c),a.delete(f);for(const g of d)g!=null&&g!==""&&a.append(f,String(g))}else a.set(c,String(d));const i=a.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Bt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${a}[]`,String(l));else typeof i=="object"?n.append(a,JSON.stringify(i)):n.append(a,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",a=e.target&&typeof e.target=="object"?e.target:void 0;return await Et.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,a)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let a;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),a={status:"failed",failureCode:"MISSING_TOKEN"};break}a={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){j.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),a={status:"failed",failureCode:"MALFORMED_PENDING"};break}a={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":a={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:a={status:"cancelled"};break}return Et.resolveDeferred(a),!0}async handleApiCall(e,n,a,i="none",l){const{method:c="GET",body:d,headers:f,contentType:g}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const W=Hr().getToken();W&&(y={Authorization:`Bearer ${W}`})}let S=e;const v=n.query||(c==="GET"?d:null);if(v&&typeof v=="object"){const q=this.buildQueryString(v);if(q){const W=e.includes("?")?"&":"?";S=`${e}${W}${q}`}}const _=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},A=window.G7Core?.state?.getLocal?.()||a.state?._local||{},x={_global:_,_local:A},O=this.getMatchingGlobalHeaders(e,x),M={};if(typeof window<"u"){const q=localStorage.getItem("g7_locale");q&&(M["Accept-Language"]=q)}const T=g==="multipart/form-data",D={method:c,headers:{...T?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...y,...O,...f},credentials:"include"};if(d&&c!=="GET")if(T){const q=new FormData;for(const[W,he]of Object.entries(d))he instanceof File||he instanceof Blob?q.append(W,he):he!=null&&q.append(W,typeof he=="object"?JSON.stringify(he):String(he));D.body=q}else D.body=JSON.stringify(d);const z=Fn();let P=null;z?.isEnabled()&&(P=z.trackRequest(S,c));try{let q=await fetch(S,D),W;try{W=await q.json()}catch{W=null}if(Et.isIdentityRequired(q.status,W)){const he=await Et.handle(W,{body:D.body,headers:D.headers,credentials:D.credentials},l);if(he){q=he;try{W=await q.json()}catch{W=null}}}if(P&&z?.isEnabled()&&(z.completeRequest(P,q.status,W),P=null),!q.ok){const he=W||{},Ee=new Error(he.message||`API call failed: ${q.statusText}`);throw Ee.response=he,Ee.status=q.status,Ee.statusText=q.statusText,new Bt(he.message||`API call failed: ${q.statusText}`,void 0,Ee)}return W}catch(q){throw P&&z?.isEnabled()&&z.failRequest(P,q instanceof Error?q.message:String(q)),q}}async handleLogin(e,n,a){const{body:i}=n;if(!i||!i.email||!i.password)throw new Bt("Login requires email and password in body params");const l=e==="user"?"user":"admin",c=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},f=window.G7Core?.state?.getLocal?.()||a.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,g),y=br.getInstance();try{const S=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},S)}}catch(S){const v=S.message||"Login failed",_=new Error(v);throw _.response=S.response?.data||{},_.status=S.status||S.response?.status||500,new Bt(v,void 0,_)}}async handleLogout(e,n){await br.getInstance().logout()}async handleSetState(e,n){j.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:l,__render:c,...d}=e,f=Fn(),g=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:g?.state?.get()||{},y=a==="global"?"_global":a.startsWith("_local.")?a:"_local",S=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,v=f?.isEnabled()?f.startStateChange(y,S,d,{actionId:n.actionId,handlerType:"setState",source:`target=${a}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",A=_!=="deep"?{...d,__mergeMode:_,...v?{__setStateId:v}:{}}:{...d,...v?{__setStateId:v}:{}};if(a==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),v&&f&&f.completeStateChange(v);return}const x=g?.state?.get()||{},{__setStateId:O,__mergeMode:M,...T}=A,D=_==="deep"?this.deepMergeWithState(T,x):T,z={...D,...v?{__setStateId:v}:{},..._!=="deep"?{__mergeMode:_}:{}};return j.log("setState global:",z),this.globalStateUpdater(z,{render:c}),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...D}}else if(a==="isolated"){const x=n.isolatedContext;if(x){const{__mergeMode:O,__setStateId:M,...T}=A;return x.mergeState(T,_),j.log("[handleSetState] isolated state updated:",T,"mergeMode:",_),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"isolated",...T}}else if(j.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(A,M):A;return n.setState(T),v&&f&&setTimeout(()=>f.completeStateChange(v),0),T}else throw v&&f&&f.completeStateChange(v),new Bt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const O=window.__g7LayoutContextStack||[];if(O.length>0){const M=i==="parent"?O[O.length-1]:O[0];if(M?.setState){const{__mergeMode:T,__setStateId:D,...z}=A,P=_==="deep"?this.deepMergeWithState(z,M.state||{}):z;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,P),M.setState(P),v&&f&&setTimeout(()=>f.completeStateChange(v),0),P}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const x=n.setState&&!n._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",x,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),x){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",A),j.log("[handleSetState] context.state:",n.state),j.log("[handleSetState] mergeMode:",_);const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(A,{}):A;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",T),n.setState(T);const D=_==="deep"?this.deepMergeWithState(A,M):_==="shallow"?{...n.state||{},...A}:A,{__mergeMode:z,__setStateId:P,...q}=D;window.__g7PendingLocalState=q,j.log("[handleSetState] __g7PendingLocalState updated:",q),this.globalStateUpdater&&(this.globalStateUpdater({_local:q},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",q));const{__mergeMode:W,__setStateId:he,...Ee}=A;if(_==="replace")window.__g7ForcedLocalFields=Ee;else{const be=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ee,be)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ee),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...D}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",M);const T=_==="deep"?this.deepMergeWithState(A,M):A;return j.log("[handleSetState] finalLocal (merged):",T),this.globalStateUpdater({_local:T},{render:c}),window.__g7PendingLocalState=T,j.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...T}}else throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const x=a.slice(7),{__mergeMode:O,__setStateId:M,...T}=A,D=T.value!==void 0?T.value:Object.values(T)[0];if(n.setState){const P=window.__g7PendingLocalState||n.state||{},q=this.createNestedUpdate(x,D,P),W={...P,...q};return n.setState(q),v&&f&&setTimeout(()=>f.completeStateChange(v),0),W}else throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context")}else{if(!n.setState)throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context");const O=window.__g7PendingLocalState||n.state||{},M=_==="deep"?this.deepMergeWithState(A,O):A;return n.setState(M),v&&f&&setTimeout(()=>f.completeStateChange(v),0),M}}async handleParentScopeSetState(e,n,a,i){const l=Fn(),c=window.G7Core,d=a==="replace"?"replace":a==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let y,S;if(m==="_local"||m==="_global")y=m,S=void 0;else if(m.startsWith("_local."))y="_local",S=m.slice(7);else if(m.startsWith("_global."))y="_global",S=m.slice(8);else{j.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const v=window.__g7LayoutContextStack||[];if(v.length===0){j.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?v[v.length-1]:v[0];if(!_){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const A=y==="_global"?_.state?._global:_.state?._local,x=l?.isEnabled()?l.startStateChange(e,A,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:O,__setStateId:M,...T}=n;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),x&&l&&l.completeStateChange(x);return}const D=c?.state?.get()||{};if(S){const z=T.value!==void 0?T.value:Object.values(T)[0],P=this.createNestedUpdate(S,z,D),q={...D,...P};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,q),this.globalStateUpdater(q)}else{const z=d==="deep"?this.deepMergeWithState(T,D):T;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,z),this.globalStateUpdater(d!=="deep"?{...z,__mergeMode:d}:z)}return x&&l&&setTimeout(()=>l.completeStateChange(x),0),{__target:e,...T}}else{if(!_.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),x&&l&&l.completeStateChange(x);return}const D=_.state||{};if(S){const z=T.value!==void 0?T.value:Object.values(T)[0],P=this.createNestedUpdate(S,z,D),q={...D,...P};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,P),_.setState(P),_.state=q,_.dataContext&&(_.dataContext._local=q),qd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),q}else{const z=d!=="deep"?{...T,__mergeMode:d}:T,P=d==="replace"?T:d==="shallow"?{...D,...T}:this.deepMergeWithState(T,D);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,P),_.setState(z),_.state=P,_.dataContext&&(_.dataContext._local=P),qd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),P}}}deepMergeWithState(e,n){const a=["errors"];let i=e;if("..."in e){const c=e["..."];if(c&&typeof c=="object"&&!Array.isArray(c)){const{"...":d,...f}=e;i={...c,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[c,d]of Object.entries(i)){if(a.includes(c)){l[c]=d;continue}if(c.includes(".")&&c!=="..."){const f=this.createNestedUpdate(c,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[c]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[c]!==null&&typeof n[c]=="object"&&!Array.isArray(n[c])?l[c]=this.deepMergeWithState(d,n[c]):l[c]=d}return l}deepMergeInto(e,n,a){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,a[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...l}:e[i]=l}}createNestedUpdate(e,n,a){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=a;for(let f=0;f{this.globalStateUpdater({_local:v})};m.push({state:y,setState:S,dataContext:{_local:y||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,j.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else j.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...a,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=Fn();if(g?.isEnabled()){const m=a.length>0?a[a.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){j.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],a=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,c=window.__g7LayoutContextStack||[];if(c.length>0){const d=c[c.length-1];d&&(d.dataContext=void 0),c.pop(),window.__g7LayoutContextStack=c,j.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(a){const d=Fn();d?.isEnabled()&&d.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(a)}async handleToast(e,n){const{type:a="info",message:i,icon:l,duration:c}=e;if(a==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&Et.consumeDomainNoticeShown()){j.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:d,...l&&{icon:l},...c&&{duration:c}},v=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:v})}else j.log(`[Toast ${a}] ${d}`)}async handleSwitch(e,n){const{cases:a}=e;if(!a){j.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,j.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],j.log("switch handler: using $args[0] as case key:",l)),l==null){if(a.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,n);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=a[c];if(!d&&a.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=a.default),!d){j.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:a}=e;if(!a||!Array.isArray(a)){j.warn("conditions handler requires conditions array");return}const i=n.data||{},l=Sp(a,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=a[l.branchIndex];if(j.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){j.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(c.then)?await this.handleSequence({...e,actions:c.then},n):await this.executeAction(c.then,n)}handleStartInterval(e,n){const a=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(a===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(a);c&&(clearInterval(c),this.intervals.delete(a));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(g=>{j.error(`[startInterval:${a}] tick action failed`,g)})},i);return this.intervals.set(a,d),{success:!0,id:a}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return j.warn("stopInterval requires id parameter"),{success:!1};const a=this.intervals.get(n);return a&&(clearInterval(a),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Fn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},g=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,S=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let v=0;v0){const T={},D={...n.data,_local:f,_computed:T,$computed:T,_isolated:g};for(const[z,P]of Object.entries(M))if(typeof P=="string"){const q=P.trim();if(q.startsWith("{{")&&q.endsWith("}}"))try{const W=q.slice(2,-2).trim();T[z]=$n(W)?this.bindingEngine.evaluatePipeExpression(W,D,{skipCache:!0}):this.bindingEngine.evaluateExpression(W,D,{skipCache:!0})}catch{T[z]=m[z]}}m=T,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const T=n.data?._computedDefinitions;if(T&&Object.keys(T).length>0){const D={},z={...n.data,_local:f,_computed:D,$computed:D,_isolated:g};for(const[P,q]of Object.entries(T))if(typeof q=="string"){const W=q.trim();if(W.startsWith("{{")&&W.endsWith("}}"))try{const he=W.slice(2,-2).trim();D[P]=$n(he)?this.bindingEngine.evaluatePipeExpression(he,z,{skipCache:!0}):this.bindingEngine.evaluateExpression(he,z,{skipCache:!0})}catch{D[P]=m[P]}}m=D,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,O.data)}catch(O){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,void 0,O),i.endSequenceExecution?.(l,O)),j.error(`sequence handler: action[${v}] failed:`,O),O}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${a.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=a.map((f,g)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${g}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${a.length} actions failed`),c}async handleLoadScript(e,n,a){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new Bt('loadScript handler requires "src" parameter',n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return bs.loadedScripts.has(f)?(j.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,a),!0):document.getElementById(f)?(j.log(`loadScript: script element already exists: ${f}`),bs.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,a),!0):(j.log(`loadScript: loading script: ${i}`),new Promise((m,y)=>{const S=document.createElement("script");S.id=f,S.src=i,S.async=c,S.defer=d,S.onload=async()=>{if(j.log(`loadScript: script loaded successfully: ${f}`),bs.loadedScripts.add(f),n.onLoad)try{await this.executeAction(n.onLoad,a)}catch(v){j.error("loadScript: onLoad action failed:",v)}m(!0)},S.onerror=v=>{j.error(`loadScript: failed to load script: ${i}`,v),y(new Bt(`Failed to load script: ${i}`,n))},document.head.appendChild(S)}))}async handleCallExternal(e,n,a){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new Bt('callExternal handler requires "constructor" parameter',n);const S=this.getNestedProperty(window,i);if(!S||typeof S!="function")throw new Bt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);j.log(`callExternal: calling constructor ${i}`);const v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=O=>{if(j.log(`callExternal: callback triggered for ${A}`,O),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,O),m&&a.setState){const M=z=>{const P={};for(const[q,W]of Object.entries(z))typeof W=="string"?P[q]=this.getNestedProperty(O,W):typeof W=="object"&&W!==null&&(P[q]=M(W));return P},T=M(m);j.log("callExternal: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,a.state||{});j.log("callExternal: merged with existing state",D),a.setState(D)}else f&&a.setState&&a.setState({[`${f.replace(/:/g,"_")}_result`]:O});if(y){const M={...a,data:{...a.data,$event:O}},T=Array.isArray(y)?y:[y];for(const D of T)try{this.executeAction(D,M)}catch(z){j.error("callExternal: callbackAction failed:",z)}}});const _=new S(v);if(c&&typeof _[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&g){const A=document.querySelector(g);if(A)return _[c](A,...d);throw new Bt(`Embed target element not found: ${g}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,a){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=e.callbackAction;if(!i)throw new Bt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new Bt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:S}=this.createEmbedLayer(f),v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=O=>{if(j.log(`callExternalEmbed: callback triggered for ${A}`,O),S(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,O),c&&a.setState){const M=z=>{const P={};for(const[q,W]of Object.entries(z))typeof W=="string"?P[q]=this.getNestedProperty(O,W):typeof W=="object"&&W!==null&&(P[q]=M(W));return P},T=M(c);j.log("callExternalEmbed: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,a.state||{});j.log("callExternalEmbed: merged with existing state",D),a.setState(D)}if(g){const M={...a,data:{...a.data,$event:O}},T=Array.isArray(g)?g:[g];for(const D of T)try{this.executeAction(D,M)}catch(z){j.error("callExternalEmbed: callbackAction failed:",z)}}});const _=new m(v);if(typeof _.embed=="function")_.embed(y),j.log("callExternalEmbed: embedded in layer");else throw S(),new Bt(`Constructor ${i} does not have embed method`,n);return _}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` +`+l)}}catch{}}throw a}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=mi(this.defaults,n);const{transitional:a,paramsSerializer:i,headers:l}=n;a!==void 0&&Ql.assertOptions(a,{silentJSONParsing:xn.transitional(xn.boolean),forcedJSONParsing:xn.transitional(xn.boolean),clarifyTimeoutError:xn.transitional(xn.boolean),legacyInterceptorReqResOrdering:xn.transitional(xn.boolean),advertiseZstdAcceptEncoding:xn.transitional(xn.boolean),validateStatusUndefinedResolves:xn.transitional(xn.boolean)},!1),i!=null&&(F.isFunction(i)?n.paramsSerializer={serialize:i}:Ql.assertOptions(i,{encode:xn.function,serialize:xn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ql.assertOptions(n,{baseUrl:xn.spelling("baseURL"),withXsrfToken:xn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let c=l&&F.merge(l.common,l[n.method]);l&&F.forEach(["delete","get","head","post","put","patch","query","common"],_=>{delete l[_]}),n.headers=An.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(n)===!1)return;f=f&&A.synchronous;const x=n.transitional||Dd;x&&x.legacyInterceptorReqResOrdering?d.unshift(A.fulfilled,A.rejected):d.push(A.fulfilled,A.rejected)});const g=[];this.interceptors.response.forEach(function(A){g.push(A.fulfilled,A.rejected)});let m,y=0,S;if(!f){const _=[cm.bind(this),void 0];for(_.unshift(...d),_.push(...g),S=_.length,m=Promise.resolve(n);y{if(!a._listeners)return;let l=a._listeners.length;for(;l-- >0;)a._listeners[l](i);a._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{a.subscribe(d),l=d}).then(i);return c.cancel=function(){a.unsubscribe(l)},c},e(function(l,c,d){a.reason||(a.reason=new po(l,c,d),n(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=a=>{e.abort(a)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new KS(function(i){e=i}),cancel:e}}};function hC(o){return function(n){return o.apply(null,n)}}function gC(o){return F.isObject(o)&&o.isAxiosError===!0}const Hd={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Hd).forEach(([o,e])=>{Hd[e]=o});function dm(o){const e=new yi(o),n=xp(yi.prototype.request,e);return F.extend(n,yi.prototype,e,{allOwnKeys:!0}),F.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return dm(mi(o,i))},n}const Yt=dm(go);Yt.Axios=yi,Yt.CanceledError=po,Yt.CancelToken=fC,Yt.isCancel=Wp,Yt.VERSION=$d,Yt.toFormData=Kl,Yt.AxiosError=Ce,Yt.Cancel=Yt.CanceledError,Yt.all=function(e){return Promise.all(e)},Yt.spread=hC,Yt.isAxiosError=gC,Yt.mergeConfig=mi,Yt.AxiosHeaders=An,Yt.formToJSON=o=>Kp(F.isHTMLForm(o)?new FormData(o):o),Yt.getAdapter=lm.getAdapter,Yt.HttpStatusCode=Hd,Yt.default=Yt;const{Axios:OT,AxiosError:LT,CanceledError:MT,isCancel:$T,CancelToken:NT,VERSION:IT,all:HT,Cancel:jT,isAxiosError:zT,spread:UT,toFormData:PT,AxiosHeaders:BT,HttpStatusCode:qT,formToJSON:GT,getAdapter:VT,mergeConfig:FT,create:KT}=Yt,jd="g7.identity.redirectStash",Zl=ht("IdentityGuardInterceptor");class Et{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){Zl.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,a){this.domainNoticeShown=!1;const i=this.launcher??mC,c=!!(a&&(a.email||a.phone))?{...e.verification,target:a}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const g=pC(f.url,d.token);return fetch(g,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return Zl.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const a={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(jd,JSON.stringify(a))}catch(i){Zl.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(Et,"launcher",null),$(Et,"deferredResolver",null),$(Et,"domainNoticeShown",!1);function pC(o,e){if(!e)return o;try{const n=typeof window<"u"?window.location.origin:"http://localhost",a=new URL(o,n);return a.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?a.toString():`${a.pathname}${a.search}${a.hash}`}catch{const n=o.includes("?")?"&":"?";return`${o}${n}verification_token=${encodeURIComponent(e)}`}}const mC=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return Et.redirectExternally(o);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,a={return_url:n,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem(jd,JSON.stringify(a))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){Zl.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},yC=ht("ApiClient");function zd(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class bC{constructor(e={}){$(this,"client");$(this,"config");$(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Yt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const a=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const n=this.getToken();if(n&&e.headers&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=zd();if(a?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=a.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,a=n._devToolsRequestId;if(a){const i=zd();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,a=n?.url||"",l=["/auth/","/layouts/"].some(c=>a.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await br.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(Et.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[S,v]of Object.entries(d))typeof v=="string"&&(c[S]=v);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),c["Content-Type"]=c["Content-Type"]??"application/json");const g=n?.identity_target,m=await Et.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},g);if(!m)return Promise.reject(e);let y=null;try{y=await m.json()}catch{y=null}return m.ok?{...e.response,status:m.status,data:y}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:y}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,a){return(await this.client.post(e,n,a)).data}async put(e,n,a){return(await this.client.put(e,n,a)).data}async patch(e,n,a){return(await this.client.patch(e,n,a)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const a=zd();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?a.completeRequest(i,n.response.status,n.response.data):n.request?a.failRequest(i,n.message||"Network error"):a.failRequest(i,n.message||"Request error")}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const a=e.params,i=[];for(const[l,c]of Object.entries(a))if(c!=null)if(Array.isArray(c)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of c)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(c))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(n)}catch(a){yC.error("Error in onError handler:",a)}}}let Ud=null;function Hr(){return Ud||(Ud=new bC),Ud}const mo=ht("AuthManager");function cs(o,e,n,a){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,n,a)}catch{}}const ec={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},Ar=class Ar{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",ec.admin),this.config.set("user",ec.user)}static getInstance(){return Ar.instance||(Ar.instance=new Ar),Ar.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Hr();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return mo.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return mo.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,a){const i=Hr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?ec.admin.loginEndpoint:ec.user.loginEndpoint;try{const d=a?.headers?{headers:a.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(Ar.LOCALE_STORAGE_KEY),y=g&&g!==m;if(g)try{localStorage.setItem(Ar.LOCALE_STORAGE_KEY,g)}catch(S){mo.warn("Failed to save user language to localStorage:",S)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),cs("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,cs("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=Hr(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(a){mo.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),cs("logout",!0,void 0,{previousType:a.type}),n&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const n=this.config.get(e);if(!n)return!1;const a=Hr();try{const i=await a.post(n.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),cs("token-refresh",!0,void 0,{type:e}),!0):(cs("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return mo.error("Token refresh failed:",i),cs("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,a){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return a&&(c+=`&reason=${encodeURIComponent(a)}`),c}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const a=this.config.get(e);a&&this.config.set(e,{...a,...n})}getRedirectUrl(e){const a=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const c=decodeURIComponent(l);if(c.startsWith("/"))return c}catch{}return a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Ar.instance=null}};$(Ar,"instance"),$(Ar,"LOCALE_STORAGE_KEY","g7_locale");let br=Ar;const fm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},Qr={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,n){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?n:a;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},vr=ht("ErrorHandlingResolver"),Ma=class Ma{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Ma.instance||(Ma.instance=new Ma),Ma.instance}static resetInstance(){Ma.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,vr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,vr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:a,onError:i}=n;vr.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Qr.findHandler(a,e);if(l){const c=this.getMatchedKey(a,e);return{handler:Qr.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=Qr.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=Qr.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=Qr.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=Qr.findHandler(fm,e),l){const c=this.getMatchedKey(fm,e);return{handler:Qr.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){vr.error("Action executor is not set");return}vr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(a){throw vr.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,n,a={}){const i=this.resolve(e,a);if(vr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return vr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return vr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,vr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,vr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Ma,"instance",null);let Pd=Ma;function Sr(){return Pd.getInstance()}var Bd={exports:{}},yo={};var hm;function vC(){if(hm)return yo;hm=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(a,i,l){var c=null;if(l!==void 0&&(c=""+l),i.key!==void 0&&(c=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:o,type:a,key:c,ref:i!==void 0?i:null,props:l}}return yo.Fragment=e,yo.jsx=n,yo.jsxs=n,yo}var gm;function SC(){return gm||(gm=1,Bd.exports=vC()),Bd.exports}var gt=SC();const wC=Xr({__proto__:null,default:Jr(gt)},[gt]),qd=ht("ParentContextProvider"),pm=H.createContext(null);let tc=null;function Gd(){tc?(qd.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),tc()):qd.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const mm=({children:o})=>{const[e,n]=H.useState(0),a=H.useRef(!0),i=H.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);H.useEffect(()=>(a.current=!0,tc=()=>{a.current&&(n(c=>c+1),qd.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,tc=null}),[]);const l={version:e,getParentDataContext:i};return gt.jsx(pm.Provider,{value:l,children:o})};function CC(){return H.useContext(pm)}const j=ht("ActionDispatcher");function EC(o,e,n,a){return n||(ip(o)||dd(o)?"$t:core.errors.network_request_failed":a||`Failed to execute action: ${e}`)}const ym=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),_C=new Set(["redirect"]);function Fn(){try{return window.G7Core?.devTools}catch{return}}class Bt extends Error{constructor(n,a,i){super(n);$(this,"action");$(this,"originalError");$(this,"unknownHandler",!1);this.action=a,this.originalError=i,this.name="ActionError"}}const bs=class bs{constructor(e={},n,a){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"intervals",new Map);this.bindingEngine=new Dn,this.translationEngine=n,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Fn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),j.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,j.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return ym}static getPreviewSuppressedLayoutFeatures(){return _C}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return j.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=Fn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,g={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(g.key=c),d!==void 0&&(g.event=d),g}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=rs(c,n,{skipCache:!0});d!=null&&d!==""&&(a[l]=String(d))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;Sr().setActionExecutor(async(n,a)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,a)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){j.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...a.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},g=a.data?._local||a.state||{},m={...f,...g},y=a.isolatedContext?.state;j.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...y?{isolatedStateOverride:y}:{}})}else j.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,a)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){j.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){j.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){j.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else j.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,a)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){j.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){j.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(j.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):j.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,a)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:y=0,retryInterval:S=50,scrollContainer:v}=n.params||{};if(!i){j.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){j.warn("scrollIntoView: window/document is not available");return}let _=null;if(f){if(_=await new Promise(A=>{const x=document.querySelector(i);if(x){A(x);return}const O=setTimeout(()=>{M.disconnect(),A(null)},g),M=new MutationObserver(()=>{const T=document.querySelector(i);T&&(clearTimeout(O),M.disconnect(),A(T))});M.observe(document.body,{childList:!0,subtree:!0})}),!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(x=>setTimeout(x,m)),_=document.querySelector(i);let A=0;for(;!_&&AsetTimeout(x,S)),_=document.querySelector(i),A++;if(!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${A+1} attempts`);return}}if(v){const A=document.querySelector(v);if(!A){j.warn(`scrollIntoView: container not found for selector "${v}"`);return}const x=_.getBoundingClientRect(),O=A.getBoundingClientRect(),M=x.top-O.top+A.scrollTop,T=M+x.height;let D;switch(c){case"start":D=M;break;case"center":D=M-A.clientHeight/2+x.height/2;break;case"end":D=T-A.clientHeight;break;default:const z=x.topO.bottom;if(z)D=M;else if(P)D=T-A.clientHeight;else return;break}A.scrollTo({top:Math.max(0,D),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,a)=>{if(typeof window>"u"){j.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw j.error("reloadExtensions: reloadExtensionState failed",d),d}else j.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},a)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},a)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,a)=>{if(typeof window>"u"){j.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw j.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),j.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,a)=>{if(typeof window>"u"){j.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,a)=>{const{componentId:i}=n.params||{};if(!i){j.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){j.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),j.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,a)=>{if(typeof window>"u"){j.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw j.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,a)=>{if(typeof window>"u"){j.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`module-${f}`;if(document.getElementById(m)){j.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((S,v)=>{y.onload=()=>{j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),S()},y.onerror=()=>{j.error(`reloadModuleHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const S=c.assets.css,v=`module-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),j.log(`reloadModuleHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],j.log(`reloadModuleHandlers: Removed assets for ${f}`));const g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,S=document.getElementById(y);S&&(S.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(n,a)=>{if(typeof window>"u"){j.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){j.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((S,v)=>{y.onload=()=>{j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),S()},y.onerror=()=>{j.error(`reloadPluginHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const S=c.assets.css,v=`plugin-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),j.log(`reloadPluginHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],j.log(`reloadPluginHandlers: Removed assets for ${f}`));const g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,S=document.getElementById(y);S&&(S.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(n,a)=>{if(e){j.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,j.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,j.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,j.warn("showErrorPage: ErrorPageHandler not available");return}const c=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),j.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const g=(m,y=6e4)=>new Promise((S,v)=>{const _=document.getElementById(m);if(_){S(_);return}j.log(`showErrorPage: Waiting for container #${m}...`);let A;const x=new MutationObserver((O,M)=>{const T=document.getElementById(m);T&&(j.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(A),S(T))});x.observe(document.body,{childList:!0,subtree:!0}),A=setTimeout(()=>{x.disconnect(),v(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await g(f);const m=Sr(),y=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||j.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(y)}}catch(m){throw j.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,a)=>{const i=n.params?.event,l=n.params?.data;if(!i){j.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){j.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){j.warn("emitEvent: G7Core.componentEvent is not available");return}try{j.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:a.data,state:a.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?j.warn(`emitEvent: No listeners found for "${i}"`):j.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const g=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const y=a.state&&typeof a.state=="object"&&!Array.isArray(a.state)?a.state:g;window.__g7SequenceLocalSync={...y,_eventResult:m}}}catch(d){if(j.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=c?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,a)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){j.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){j.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){j.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(S=>S.id===i?{...S,[l]:c,_modified:!0}:S),y=new Set(f._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(y)}}),j.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw j.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,a)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){j.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){j.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){j.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const g=f.state.get()||{},y=(g.products?.data?.data||[]).map(v=>{if(v.id===i&&v.options){const _=v.options.map(A=>A.id===l?{...A,[c]:d,_modified:!0}:A);return{...v,options:_,_modified:!0}}return v}),S=new Set(g._local?.modifiedProductIds||[]);S.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:y}},_local:{...g._local,modifiedProductIds:Array.from(S)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(g){throw j.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(n,a)=>{const i=n.target;if(!i||typeof i!="string"){j.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),j.log("setLocale: Locale changed to",i)}catch(c){j.error("setLocale: Failed to change locale:",c),window.location.reload()}else{j.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{j.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Fn();if(!e?.isEnabled())return;const n=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const a of n)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,n,a){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=a?.state?{...a.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(j.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??a?.state??{},y=Date.now()-l;for(const S of Object.keys(c)){const v=c[S],_=m[S];v!==_&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${S}`,capturedValue:v,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${S} changed after handler creation:`,`captured="${v}" → current="${_}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const S=f.target;new FormData(S).forEach((_,A)=>{g[A]=_})}const m={...this.defaultContext,data:{...n,form:g,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let S=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext,m.data)),!confirm(S))return}const y=window.__g7ActionContext;window.__g7ActionContext={...a,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(g){if(j.error("Action execution failed:",g),e.onError){const m=g instanceof Bt&&g.originalError?g.originalError:g,y={...this.defaultContext,data:{...n,error:m,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState}},S=Array.isArray(e.onError)?e.onError:[e.onError];for(const v of S)await this.executeAction(v,y)}}}}generateActionId(e,n){const a=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${a}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const a=Fn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,g),!g)return i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return j.error("[executeAction] if condition error:",e.handler,f),i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(c=this.sanitizeForDevTools(f));const g=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,g);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&ym.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&a&&a.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const y=f.path||g;m=await this.handleNavigate(y,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const _=f.path||g;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const _=window.G7Core,A={};if(_?.state?.get){const x=_.state.get();A._global=x}n.state&&(A._local=n.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],A)}const S=e.auth_mode??(e.auth_required?"required":"none"),v=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(g,f,n,S,v);break;case"login":m=await this.handleLogin(g,f,n);break;case"logout":m=await this.handleLogout(g,n);break;case"setState":j.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(g,f,n);break;case"openModal":m=await this.handleOpenModal(g,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(g,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:g,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:S,merge:v}=e.resultTo,_=this.resolveValue(S,n.data),A=v==="replace"?"replace":v==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const x=this.buildNestedUpdate(_,m),O=A!=="deep"?{...x,__mergeMode:A}:x;n.setState(O),j.log(`[resultTo] Saved to _local.${_} (merge=${A}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},T=this.buildNestedUpdate(_,m);let D;A==="replace"?D=T:A==="shallow"?D={...M,...T}:D=this.deepMergeWithState(T,M),this.globalStateUpdater({_local:D}),j.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${A}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const x=this.buildNestedUpdate(_,m);this.globalStateUpdater(x),j.log(`[resultTo] Saved to _global.${_}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const x=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(x,A),j.log(`[resultTo] Saved to _isolated.${_} (merge=${A}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const v=window.G7Core,_={};v?.state?.get&&(_._global=v.state.get()),n.state&&(_._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},S=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];S.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:S},y):S.length===1&&await this.executeAction(S[0],y)}return i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const g=f instanceof Bt?f:new Bt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},y=m.data||{},S=g.originalError?.status||m.status||500;let v=EC(g.originalError??f,e.handler,y.message,g.message);this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext));const _={status:S,message:v,errors:y.errors||m.errors,data:y,statusText:g.originalError?.statusText,error_code:y.error_code??m.error_code};if(g.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const x=Sr().resolve(S,{errorHandling:e.errorHandling,onError:e.onError});if(x.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,T={};M?.state?.get&&(T._global=M.state.get()),n.state&&(T._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,T,"callback-state-capture",i)}const O={...n,data:{...n.data,error:_}};try{const M={type:"click",handler:x.handler.handler,target:x.handler.target,params:x.handler.params,actions:x.handler.actions};return await this.executeAction(M,O),{success:!1,error:g}}catch(M){return j.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:g,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,a){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const c=new URLSearchParams;for(const[f,g]of Object.entries(n.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of g)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(g));const d=c.toString();d&&(i=`${e}?${d}`)}if(j.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await c.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),j.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}j.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){j.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},a),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!a.navigate)throw new Bt("Navigate function is not provided in context");a.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const a=n.fallback;if(a===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const c=e.split("?")[0];return l.match(c)?null:this.resolveNavigateFallback(a,e,n)}resolveNavigateFallback(e,n,a){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(j.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,a){const i=e===void 0?a:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const S=y;return"container"in S||"to"in S||"block"in S||"offset"in S},d=(y,S,v=0)=>{y===window?window.scrollTo({top:S,left:v,behavior:l}):y.scrollTo({top:S,left:v,behavior:l})},f=(y,S,v,_)=>{if(S===window){y.scrollIntoView({behavior:l,block:v}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const A=S,x=y.getBoundingClientRect(),O=A.getBoundingClientRect(),M=A.scrollTop+(x.top-O.top);let T;v==="center"?T=M-(A.clientHeight-y.clientHeight)/2:v==="end"?T=M-(A.clientHeight-y.clientHeight):T=M,T-=_,A.scrollTo({top:Math.max(0,T),left:0,behavior:l})},g=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(v=>{if(v.scrollTop===0&&v.scrollLeft===0)return;const _=window.getComputedStyle(v),A=_.overflowY,x=_.overflowX;(A==="auto"||A==="scroll"||x==="auto"||x==="scroll")&&v.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,S=y.block??"start",v=typeof y.offset=="number"?y.offset:0;let _=window;if(typeof y.container=="string"&&y.container.length>0){const x=document.querySelector(y.container);if(!x){j.warn(`applyScrollOption: container not found: ${y.container}`);return}_=x}const A=y.to??"top";if(A==="top"){_===window?g():d(_,0);return}if(typeof A=="number"){d(_,A-v);return}if(typeof A=="object"&&A!==null&&("x"in A||"y"in A)){const{x=0,y:O=0}=A;d(_,O-v,x);return}if(typeof A=="string"&&(A.startsWith("#")||A.startsWith("."))){const x=document.querySelector(A);x?f(x,_,S,v):j.warn(`applyScrollOption: target element not found: ${A}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',A);return}if(i==="top"){g();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:S=0}=i;window.scrollTo({top:S,left:y,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:l,block:"start"});return}}catch(y){j.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let a=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(a=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:n,finalPath:a,windowTarget:i}),i==="_self"?window.location.assign(a):window.open(a,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let a=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)a=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(c,String(d));const l=i.toString();l&&(a=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:n,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const a=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")a.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;a.delete(c),a.delete(f);for(const g of d)g!=null&&g!==""&&a.append(f,String(g))}else a.set(c,String(d));const i=a.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Bt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${a}[]`,String(l));else typeof i=="object"?n.append(a,JSON.stringify(i)):n.append(a,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",a=e.target&&typeof e.target=="object"?e.target:void 0;return await Et.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,a)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let a;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),a={status:"failed",failureCode:"MISSING_TOKEN"};break}a={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){j.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),a={status:"failed",failureCode:"MALFORMED_PENDING"};break}a={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":a={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:a={status:"cancelled"};break}return Et.resolveDeferred(a),!0}async handleApiCall(e,n,a,i="none",l){const{method:c="GET",body:d,headers:f,contentType:g}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const W=Hr().getToken();W&&(y={Authorization:`Bearer ${W}`})}let S=e;const v=n.query||(c==="GET"?d:null);if(v&&typeof v=="object"){const q=this.buildQueryString(v);if(q){const W=e.includes("?")?"&":"?";S=`${e}${W}${q}`}}const _=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},A=window.G7Core?.state?.getLocal?.()||a.state?._local||{},x={_global:_,_local:A},O=this.getMatchingGlobalHeaders(e,x),M={};if(typeof window<"u"){const q=localStorage.getItem("g7_locale");q&&(M["Accept-Language"]=q)}const T=g==="multipart/form-data",D={method:c,headers:{...T?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...y,...O,...f},credentials:"include"};if(d&&c!=="GET")if(T){const q=new FormData;for(const[W,he]of Object.entries(d))he instanceof File||he instanceof Blob?q.append(W,he):he!=null&&q.append(W,typeof he=="object"?JSON.stringify(he):String(he));D.body=q}else D.body=JSON.stringify(d);const z=Fn();let P=null;z?.isEnabled()&&(P=z.trackRequest(S,c));try{let q=await fetch(S,D),W;try{W=await q.json()}catch{W=null}if(Et.isIdentityRequired(q.status,W)){const he=await Et.handle(W,{body:D.body,headers:D.headers,credentials:D.credentials},l);if(he){q=he;try{W=await q.json()}catch{W=null}}}if(P&&z?.isEnabled()&&(z.completeRequest(P,q.status,W),P=null),!q.ok){const he=W||{},Ee=new Error(he.message||`API call failed: ${q.statusText}`);throw Ee.response=he,Ee.status=q.status,Ee.statusText=q.statusText,new Bt(he.message||`API call failed: ${q.statusText}`,void 0,Ee)}return W}catch(q){throw P&&z?.isEnabled()&&z.failRequest(P,q instanceof Error?q.message:String(q)),q}}async handleLogin(e,n,a){const{body:i}=n;if(!i||!i.email||!i.password)throw new Bt("Login requires email and password in body params");const l=e==="user"?"user":"admin",c=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},f=window.G7Core?.state?.getLocal?.()||a.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,g),y=br.getInstance();try{const S=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},S)}}catch(S){const v=S.message||"Login failed",_=new Error(v);throw _.response=S.response?.data||{},_.status=S.status||S.response?.status||500,new Bt(v,void 0,_)}}async handleLogout(e,n){await br.getInstance().logout()}async handleSetState(e,n){j.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:l,__render:c,...d}=e,f=Fn(),g=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:g?.state?.get()||{},y=a==="global"?"_global":a.startsWith("_local.")?a:"_local",S=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,v=f?.isEnabled()?f.startStateChange(y,S,d,{actionId:n.actionId,handlerType:"setState",source:`target=${a}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",A=_!=="deep"?{...d,__mergeMode:_,...v?{__setStateId:v}:{}}:{...d,...v?{__setStateId:v}:{}};if(a==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),v&&f&&f.completeStateChange(v);return}const x=g?.state?.get()||{},{__setStateId:O,__mergeMode:M,...T}=A,D=_==="deep"?this.deepMergeWithState(T,x):T,z={...D,...v?{__setStateId:v}:{},..._!=="deep"?{__mergeMode:_}:{}};return j.log("setState global:",z),this.globalStateUpdater(z,{render:c}),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...D}}else if(a==="isolated"){const x=n.isolatedContext;if(x){const{__mergeMode:O,__setStateId:M,...T}=A;return x.mergeState(T,_),j.log("[handleSetState] isolated state updated:",T,"mergeMode:",_),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"isolated",...T}}else if(j.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(A,M):A;return n.setState(T),v&&f&&setTimeout(()=>f.completeStateChange(v),0),T}else throw v&&f&&f.completeStateChange(v),new Bt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const O=window.__g7LayoutContextStack||[];if(O.length>0){const M=i==="parent"?O[O.length-1]:O[0];if(M?.setState){const{__mergeMode:T,__setStateId:D,...z}=A,P=_==="deep"?this.deepMergeWithState(z,M.state||{}):z;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,P),M.setState(P),v&&f&&setTimeout(()=>f.completeStateChange(v),0),P}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const x=n.setState&&!n._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",x,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),x){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",A),j.log("[handleSetState] context.state:",n.state),j.log("[handleSetState] mergeMode:",_);const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(A,{}):A;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",T),n.setState(T);const D=_==="deep"?this.deepMergeWithState(A,M):_==="shallow"?{...n.state||{},...A}:A,{__mergeMode:z,__setStateId:P,...q}=D;window.__g7PendingLocalState=q,j.log("[handleSetState] __g7PendingLocalState updated:",q),this.globalStateUpdater&&(this.globalStateUpdater({_local:q},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",q));const{__mergeMode:W,__setStateId:he,...Ee}=A;if(_==="replace")window.__g7ForcedLocalFields=Ee;else{const be=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ee,be)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ee),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...D}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",M);const T=_==="deep"?this.deepMergeWithState(A,M):A;return j.log("[handleSetState] finalLocal (merged):",T),this.globalStateUpdater({_local:T},{render:c}),window.__g7PendingLocalState=T,j.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...T}}else throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const x=a.slice(7),{__mergeMode:O,__setStateId:M,...T}=A,D=T.value!==void 0?T.value:Object.values(T)[0];if(n.setState){const P=window.__g7PendingLocalState||n.state||{},q=this.createNestedUpdate(x,D,P),W={...P,...q};return n.setState(q),v&&f&&setTimeout(()=>f.completeStateChange(v),0),W}else throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context")}else{if(!n.setState)throw v&&f&&f.completeStateChange(v),new Bt("setState function is not provided in context");const O=window.__g7PendingLocalState||n.state||{},M=_==="deep"?this.deepMergeWithState(A,O):A;return n.setState(M),v&&f&&setTimeout(()=>f.completeStateChange(v),0),M}}async handleParentScopeSetState(e,n,a,i){const l=Fn(),c=window.G7Core,d=a==="replace"?"replace":a==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let y,S;if(m==="_local"||m==="_global")y=m,S=void 0;else if(m.startsWith("_local."))y="_local",S=m.slice(7);else if(m.startsWith("_global."))y="_global",S=m.slice(8);else{j.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const v=window.__g7LayoutContextStack||[];if(v.length===0){j.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?v[v.length-1]:v[0];if(!_){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const A=y==="_global"?_.state?._global:_.state?._local,x=l?.isEnabled()?l.startStateChange(e,A,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:O,__setStateId:M,...T}=n;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),x&&l&&l.completeStateChange(x);return}const D=c?.state?.get()||{};if(S){const z=T.value!==void 0?T.value:Object.values(T)[0],P=this.createNestedUpdate(S,z,D),q={...D,...P};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,q),this.globalStateUpdater(q)}else{const z=d==="deep"?this.deepMergeWithState(T,D):T;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,z),this.globalStateUpdater(d!=="deep"?{...z,__mergeMode:d}:z)}return x&&l&&setTimeout(()=>l.completeStateChange(x),0),{__target:e,...T}}else{if(!_.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),x&&l&&l.completeStateChange(x);return}const D=_.state||{};if(S){const z=T.value!==void 0?T.value:Object.values(T)[0],P=this.createNestedUpdate(S,z,D),q={...D,...P};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,P),_.setState(P),_.state=q,_.dataContext&&(_.dataContext._local=q),Gd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),q}else{const z=d!=="deep"?{...T,__mergeMode:d}:T,P=d==="replace"?T:d==="shallow"?{...D,...T}:this.deepMergeWithState(T,D);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,P),_.setState(z),_.state=P,_.dataContext&&(_.dataContext._local=P),Gd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),P}}}deepMergeWithState(e,n){const a=["errors"];let i=e;if("..."in e){const c=e["..."];if(c&&typeof c=="object"&&!Array.isArray(c)){const{"...":d,...f}=e;i={...c,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[c,d]of Object.entries(i)){if(a.includes(c)){l[c]=d;continue}if(c.includes(".")&&c!=="..."){const f=this.createNestedUpdate(c,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[c]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[c]!==null&&typeof n[c]=="object"&&!Array.isArray(n[c])?l[c]=this.deepMergeWithState(d,n[c]):l[c]=d}return l}deepMergeInto(e,n,a){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,a[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...l}:e[i]=l}}createNestedUpdate(e,n,a){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=a;for(let f=0;f{this.globalStateUpdater({_local:v})};m.push({state:y,setState:S,dataContext:{_local:y||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,j.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else j.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...a,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=Fn();if(g?.isEnabled()){const m=a.length>0?a[a.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){j.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],a=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,c=window.__g7LayoutContextStack||[];if(c.length>0){const d=c[c.length-1];d&&(d.dataContext=void 0),c.pop(),window.__g7LayoutContextStack=c,j.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(a){const d=Fn();d?.isEnabled()&&d.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(a)}async handleToast(e,n){const{type:a="info",message:i,icon:l,duration:c}=e;if(a==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&Et.consumeDomainNoticeShown()){j.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:d,...l&&{icon:l},...c&&{duration:c}},v=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:v})}else j.log(`[Toast ${a}] ${d}`)}async handleSwitch(e,n){const{cases:a}=e;if(!a){j.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,j.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],j.log("switch handler: using $args[0] as case key:",l)),l==null){if(a.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,n);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=a[c];if(!d&&a.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=a.default),!d){j.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:a}=e;if(!a||!Array.isArray(a)){j.warn("conditions handler requires conditions array");return}const i=n.data||{},l=Sp(a,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=a[l.branchIndex];if(j.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){j.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(c.then)?await this.handleSequence({...e,actions:c.then},n):await this.executeAction(c.then,n)}handleStartInterval(e,n){const a=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(a===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(a);c&&(clearInterval(c),this.intervals.delete(a));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(g=>{j.error(`[startInterval:${a}] tick action failed`,g)})},i);return this.intervals.set(a,d),{success:!0,id:a}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return j.warn("stopInterval requires id parameter"),{success:!1};const a=this.intervals.get(n);return a&&(clearInterval(a),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Fn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},g=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,S=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let v=0;v0){const T={},D={...n.data,_local:f,_computed:T,$computed:T,_isolated:g};for(const[z,P]of Object.entries(M))if(typeof P=="string"){const q=P.trim();if(q.startsWith("{{")&&q.endsWith("}}"))try{const W=q.slice(2,-2).trim();T[z]=Vn(W)?this.bindingEngine.evaluatePipeExpression(W,D,{skipCache:!0}):this.bindingEngine.evaluateExpression(W,D,{skipCache:!0})}catch{T[z]=m[z]}}m=T,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const T=n.data?._computedDefinitions;if(T&&Object.keys(T).length>0){const D={},z={...n.data,_local:f,_computed:D,$computed:D,_isolated:g};for(const[P,q]of Object.entries(T))if(typeof q=="string"){const W=q.trim();if(W.startsWith("{{")&&W.endsWith("}}"))try{const he=W.slice(2,-2).trim();D[P]=Vn(he)?this.bindingEngine.evaluatePipeExpression(he,z,{skipCache:!0}):this.bindingEngine.evaluateExpression(he,z,{skipCache:!0})}catch{D[P]=m[P]}}m=D,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,O.data)}catch(O){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,void 0,O),i.endSequenceExecution?.(l,O)),j.error(`sequence handler: action[${v}] failed:`,O),O}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${a.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=a.map((f,g)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${g}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${a.length} actions failed`),c}async handleLoadScript(e,n,a){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new Bt('loadScript handler requires "src" parameter',n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return bs.loadedScripts.has(f)?(j.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,a),!0):document.getElementById(f)?(j.log(`loadScript: script element already exists: ${f}`),bs.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,a),!0):(j.log(`loadScript: loading script: ${i}`),new Promise((m,y)=>{const S=document.createElement("script");S.id=f,S.src=i,S.async=c,S.defer=d,S.onload=async()=>{if(j.log(`loadScript: script loaded successfully: ${f}`),bs.loadedScripts.add(f),n.onLoad)try{await this.executeAction(n.onLoad,a)}catch(v){j.error("loadScript: onLoad action failed:",v)}m(!0)},S.onerror=v=>{j.error(`loadScript: failed to load script: ${i}`,v),y(new Bt(`Failed to load script: ${i}`,n))},document.head.appendChild(S)}))}async handleCallExternal(e,n,a){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new Bt('callExternal handler requires "constructor" parameter',n);const S=this.getNestedProperty(window,i);if(!S||typeof S!="function")throw new Bt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);j.log(`callExternal: calling constructor ${i}`);const v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=O=>{if(j.log(`callExternal: callback triggered for ${A}`,O),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,O),m&&a.setState){const M=z=>{const P={};for(const[q,W]of Object.entries(z))typeof W=="string"?P[q]=this.getNestedProperty(O,W):typeof W=="object"&&W!==null&&(P[q]=M(W));return P},T=M(m);j.log("callExternal: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,a.state||{});j.log("callExternal: merged with existing state",D),a.setState(D)}else f&&a.setState&&a.setState({[`${f.replace(/:/g,"_")}_result`]:O});if(y){const M={...a,data:{...a.data,$event:O}},T=Array.isArray(y)?y:[y];for(const D of T)try{this.executeAction(D,M)}catch(z){j.error("callExternal: callbackAction failed:",z)}}});const _=new S(v);if(c&&typeof _[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&g){const A=document.querySelector(g);if(A)return _[c](A,...d);throw new Bt(`Embed target element not found: ${g}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,a){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=e.callbackAction;if(!i)throw new Bt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new Bt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:S}=this.createEmbedLayer(f),v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=O=>{if(j.log(`callExternalEmbed: callback triggered for ${A}`,O),S(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,O),c&&a.setState){const M=z=>{const P={};for(const[q,W]of Object.entries(z))typeof W=="string"?P[q]=this.getNestedProperty(O,W):typeof W=="object"&&W!==null&&(P[q]=M(W));return P},T=M(c);j.log("callExternalEmbed: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,a.state||{});j.log("callExternalEmbed: merged with existing state",D),a.setState(D)}if(g){const M={...a,data:{...a.data,$event:O}},T=Array.isArray(g)?g:[g];for(const D of T)try{this.executeAction(D,M)}catch(z){j.error("callExternalEmbed: callbackAction failed:",z)}}});const _=new m(v);if(typeof _.embed=="function")_.embed(y),j.log("callExternalEmbed: embedded in layer");else throw S(),new Bt(`Constructor ${i} does not have embed method`,n);return _}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); @@ -47,11 +47,11 @@ Error generating stack: `+u.message+` justify-content: center; color: #666; transition: background-color 0.2s; - `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),n.onclick=d=>{d.target===n&&l()},a.appendChild(i),n.appendChild(a),document.body.appendChild(n),{overlay:n,layer:a,closeLayer:l}}getNestedProperty(e,n){return n.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,n){const{key:a,value:i}=e;if(!a)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,l),j.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:a,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:a,target:i,stateKey:l,defaultValue:c}=e;if(!a)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(a);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${a}, using default`),l&&n.setState&&n.setState({[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${a}`,f),l&&n.setState&&n.setState({[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:a,error:d}),c}}async handleCustomAction(e,n){const a=this.customHandlers.get(e.handler);if(!a){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new Bt(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await a(e,n)}resolveParams(e,n){if(!e)return{};const a={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="string"?a[i]=l:Array.isArray(l)?a[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,n):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?a[i]=l:typeof l=="object"&&l!==null?a[i]=this.resolveParams(l,n):a[i]=l;return a}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let a={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,n)),c&&typeof c=="object"&&!Array.isArray(c)&&(a={...a,...c})}else typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?a[i]=this.evaluateExpressions(l,n):a[i]=l;return a}evaluateExpressionsIfNeeded(e,n){const a={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):a[i]=l;return a}evaluateExpression(e,n){if(!n)return e;const a=Aa(e);if(a===null){let c=n;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...n,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(c={...c,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,c,{skipCache:!0})}let i=a;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=n;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...n,_global:d})}if(i.includes("_computed")||i.includes("$computed")){const d=window.__g7ActionContext?.computedRef?.current;d&&Object.keys(d).length>0&&(l={...l,_computed:d,$computed:d})}i.includes("_global.modules")&&(j.log("[evaluateExpression] expression:",i),j.log("[evaluateExpression] dataContext._global:",l._global),j.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=$n(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&j.log("[evaluateExpression] result:",c),typeof c=="string"&&c.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(c,this.translationContext,n):c}catch(c){return j.error("Expression evaluation failed:",e,c),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const a={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof Bt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...a,data:{...a.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,c)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,a){this.customHandlers.set(e,n);const i=Fn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Fn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,a,i,l){const c={...a,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,a,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(n),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const A={..._};for(const x of m)A[x]=g.target.value[x];g.target.value=A}this.debounceAccumulatedValues.set(f,g.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const S=Fn();S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const v=!this.debounceTimers.has(f+"_leading");if(d.leading&&v&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,g,a,i,c),S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const _=()=>{this.executeDebouncedAction(e,g,a,i,c),S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},A=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,A),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,a]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(a),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,a]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,a){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const y=this.resolveActionRef(m),S=y.event||this.getEventHandlerName(y.type);l.has(S)||l.set(S,[]),l.get(S).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...S)=>{for(const v of y){const _=S[0],A=_&&typeof _=="object"&&"preventDefault"in _;if(A&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),A&&v.key&&"key"in _){if(this.isImeComposing(_)){j.log("Key filter skipped (IME composing):",v.key);continue}if(_.key!==v.key){j.log("Key filter not matched:",v.key,"actual:",_.key);continue}j.log("Key filter matched:",v.key)}if(v.debounce){const x=`${c}-${v.handler}-${m}`,O=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let M;if(A)M=_;else if(O){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(D._changedKeys=_._changedKeys),M=D}else M=new Event("custom");const T=v.event?{...n,$args:S}:n;this.handleDebouncedAction(v,M,T,a,x,S)}else if(this.flushPendingDebounceTimers(),v.event){const x={...n,$args:S},O=A?_:new Event("custom");this.createHandler(v,x,a)(O)}else if(A)this.createHandler(v,n,a)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const O={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(v,n,a)(O)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,n=5){const a=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(a.has(l))return"[Circular Array]";a.add(l);const d=l.slice(0,10).map(f=>i(f,c+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(a.has(l))return"[Circular Reference]";a.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)try{d[m]=i(l[m],c+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(bs,"loadedScripts",new Set);let bo=bs,nc=null;function vm(o){return nc||(nc=new bo(o)),nc}function AC(o){nc=o}const Sm=ht("TransitionManager");class xC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Sm.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){Sm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const jr=new xC,rc=ht("TransitionContext"),wm=H.createContext({isTransitioning:!1}),Gd=({children:o})=>{const[e,n]=H.useState(()=>{const i=jr.getIsPending();return rc.log("Initial state:",i),i});H.useEffect(()=>{rc.log("Subscribing to TransitionManager");const i=jr.subscribe(l=>{rc.log("Received isPending update:",l),n(l)});return()=>{rc.log("Unsubscribing from TransitionManager"),i()}},[]);const a=H.useMemo(()=>({isTransitioning:e}),[e]);return gt.jsx(wm.Provider,{value:a,children:o})},Cm=()=>H.useContext(wm),ac="__g7LocalInitTracking";function Vd(){const o=globalThis;return o[ac]||(o[ac]={hash:"",timestamp:void 0,consumed:void 0}),o[ac]}function TC(){const o=globalThis;o[ac]={hash:"",timestamp:void 0,consumed:void 0}}function RC(o){Vd().consumed=o}function kC(o){return Vd().consumed===o}function DC(o){return o.globalTrackedKey!==o.trackingKey?"apply":o.instanceHandledKey===o.trackingKey?"skip":"prune"}function OC(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function LC(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!kC(o)))return e;const{_forceLocalInit:a,...i}=o,{_forceLocalInit:l,...c}=e,d={...i,...c},f=OC(a,l);return f!==void 0&&(d._forceLocalInit=f),d}function MC(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function Em(o){const e=MC(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Fd=H.createContext(Em(1024)),ic=({children:o,overrideWidth:e})=>{const[n,a]=H.useState(()=>hi.getWidth());H.useEffect(()=>{const c=hi.subscribe(d=>{a(d)});return()=>{c()}},[]);const i=e??n,l=H.useMemo(()=>Em(i),[i]);return gt.jsx(Fd.Provider,{value:l,children:o})},Kd=()=>H.useContext(Fd);window.G7Core?.createLogger?.("Core:State");function $C(o,e,n,a){const{syncOnControlledChange:i=!0,isEqual:l}=a??{},c=o!==void 0;H.useRef(c);const[d,f]=H.useState(o!==void 0?o:e),g=d,m=H.useRef(o),y=H.useRef(!1);H.useEffect(()=>{if(y.current){m.current=o;return}i&&c&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,c,i,l,d]);const S=H.useCallback(v=>{const _=typeof v=="function"?v(g):v;(l?l(g,_):g===_)||(y.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{y.current=!1}))},[g,c,n,l]);return[g,S]}function NC(o,e){return o===e?!0:o.length!==e.length?!1:o.every((n,a)=>n===e[a])}function _m(o,e){if(o===e)return!0;const n=Object.keys(o),a=Object.keys(e);return n.length!==a.length?!1:n.every(i=>o[i]===e[i])}const Am=H.createContext({}),IC=({children:o,value:e})=>gt.jsx(Am.Provider,{value:e,children:o}),HC=()=>H.useContext(Am),jC=(o,e)=>{if(!o)return;const n=e.split(".");let a=o;for(const i of n){if(a==null)return;a=a[i]}return a},zC=(o,e,n)=>{const a=e.split(".");if(a.length===1)return{...o,[a[0]]:n};const i={...o};let l=i;for(let c=0;c{us.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{us.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},xm=H.createContext(UC);let PC=0;function BC(){return`isolated-${++PC}-${Date.now().toString(36)}`}function Tm(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const n={...o};for(const a of Object.keys(e)){const i=e[a],l=o?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[a]=Tm(l,i):n[a]=i}return n}function qC(o,e){return e?e.split(".").reduce((n,a)=>n?.[a],o):o}function GC(o,e,n){const a=e.split("."),i={...o};let l=i;for(let c=0;c{const i=H.useRef(e||BC()).current,[l,c]=H.useState(o),d=H.useRef(l);d.current=l;const f=H.useCallback(v=>qC(d.current,v),[]),g=H.useCallback((v,_)=>{c(A=>{const x=GC(A,v,_);return us.log(`[${i}] setState: ${v} =`,_),x})},[i]),m=H.useCallback((v,_="deep")=>{c(A=>{let x;return _==="replace"?x=v:_==="shallow"?x={...A,...v}:x=Tm(A,v),us.log(`[${i}] mergeState (${_}):`,v),x})},[i]),y=H.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),S=H.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return H.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=S,v&&(v._isolatedStates||(v._isolatedStates={}),v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:created",{id:i,state:l}),us.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],v?._isolatedStates&&delete v._isolatedStates[i],v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:destroyed",{id:i}),us.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,S]),H.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),v?._isolatedStates&&(v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),gt.jsx(xm.Provider,{value:y,children:n})},FC=()=>{const o=H.useContext(xm);return o.scopeId?o:null};var ka=Jg();function KC(){for(var o=arguments.length,e=new Array(o),n=0;na=>{e.forEach(i=>i(a))},e)}const sc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ds(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function Wd(o){return"nodeType"in o}function In(o){var e,n;return o?ds(o)?o:Wd(o)&&(e=(n=o.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Yd(o){const{Document:e}=In(o);return o instanceof e}function vo(o){return ds(o)?!1:o instanceof In(o).HTMLElement}function Rm(o){return o instanceof In(o).SVGElement}function fs(o){return o?ds(o)?o.document:Wd(o)?Yd(o)?o:vo(o)||Rm(o)?o.ownerDocument:document:document:document}const zr=sc?H.useLayoutEffect:H.useEffect;function Xd(o){const e=H.useRef(o);return zr(()=>{e.current=o}),H.useCallback(function(){for(var n=arguments.length,a=new Array(n),i=0;i{o.current=setInterval(a,i)},[]),n=H.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,n]}function So(o,e){e===void 0&&(e=[o]);const n=H.useRef(o);return zr(()=>{n.current!==o&&(n.current=o)},e),n}function wo(o,e){const n=H.useRef();return H.useMemo(()=>{const a=o(n.current);return n.current=a,a},[...e])}function oc(o){const e=Xd(o),n=H.useRef(null),a=H.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,a]}function Jd(o){const e=H.useRef();return H.useEffect(()=>{e.current=o},[o]),e.current}let Qd={};function Co(o,e){return H.useMemo(()=>{if(e)return e;const n=Qd[o]==null?0:Qd[o]+1;return Qd[o]=n,o+"-"+n},[o,e])}function km(o){return function(e){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const hs=km(1),Eo=km(-1);function YC(o){return"clientX"in o&&"clientY"in o}function Zd(o){if(!o)return!1;const{KeyboardEvent:e}=In(o.target);return e&&o instanceof e}function XC(o){if(!o)return!1;const{TouchEvent:e}=In(o.target);return e&&o instanceof e}function ef(o){if(XC(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:n}=o.touches[0];return{x:e,y:n}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:n}=o.changedTouches[0];return{x:e,y:n}}}return YC(o)?{x:o.clientX,y:o.clientY}:null}const _o=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:n}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:n}=o;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(o){if(o)return[_o.Translate.toString(o),_o.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:n,easing:a}=o;return e+" "+n+"ms "+a}}}),Dm="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function JC(o){return o.matches(Dm)?o:o.querySelector(Dm)}const QC={display:"none"};function ZC(o){let{id:e,value:n}=o;return Xe.createElement("div",{id:e,style:QC},n)}function eE(o){let{id:e,announcement:n,ariaLiveType:a="assertive"}=o;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Xe.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},n)}function tE(){const[o,e]=H.useState("");return{announce:H.useCallback(a=>{a!=null&&e(a)},[]),announcement:o}}const Om=H.createContext(null);function nE(o){const e=H.useContext(Om);H.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function rE(){const[o]=H.useState(()=>new Set),e=H.useCallback(a=>(o.add(a),()=>o.delete(a)),[o]);return[H.useCallback(a=>{let{type:i,event:l}=a;o.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[o]),e]}const aE={draggable:` + `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),n.onclick=d=>{d.target===n&&l()},a.appendChild(i),n.appendChild(a),document.body.appendChild(n),{overlay:n,layer:a,closeLayer:l}}getNestedProperty(e,n){return n.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,n){const{key:a,value:i}=e;if(!a)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,l),j.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:a,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:a,target:i,stateKey:l,defaultValue:c}=e;if(!a)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(a);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${a}, using default`),l&&n.setState&&n.setState({[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${a}`,f),l&&n.setState&&n.setState({[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:a,error:d}),c}}async handleCustomAction(e,n){const a=this.customHandlers.get(e.handler);if(!a){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new Bt(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await a(e,n)}resolveParams(e,n){if(!e)return{};const a={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="string"?a[i]=l:Array.isArray(l)?a[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,n):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?a[i]=l:typeof l=="object"&&l!==null?a[i]=this.resolveParams(l,n):a[i]=l;return a}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let a={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,n)),c&&typeof c=="object"&&!Array.isArray(c)&&(a={...a,...c})}else typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?a[i]=this.evaluateExpressions(l,n):a[i]=l;return a}evaluateExpressionsIfNeeded(e,n){const a={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):a[i]=l;return a}evaluateExpression(e,n){if(!n)return e;const a=Aa(e);if(a===null){let c=n;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...n,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(c={...c,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,c,{skipCache:!0})}let i=a;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=n;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...n,_global:d})}if(i.includes("_computed")||i.includes("$computed")){const d=window.__g7ActionContext?.computedRef?.current;d&&Object.keys(d).length>0&&(l={...l,_computed:d,$computed:d})}i.includes("_global.modules")&&(j.log("[evaluateExpression] expression:",i),j.log("[evaluateExpression] dataContext._global:",l._global),j.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=Vn(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&j.log("[evaluateExpression] result:",c),typeof c=="string"&&c.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(c,this.translationContext,n):c}catch(c){return j.error("Expression evaluation failed:",e,c),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const a={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof Bt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...a,data:{...a.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,c)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,a){this.customHandlers.set(e,n);const i=Fn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Fn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,a,i,l){const c={...a,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,a,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(n),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const A={..._};for(const x of m)A[x]=g.target.value[x];g.target.value=A}this.debounceAccumulatedValues.set(f,g.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const S=Fn();S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const v=!this.debounceTimers.has(f+"_leading");if(d.leading&&v&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,g,a,i,c),S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const _=()=>{this.executeDebouncedAction(e,g,a,i,c),S?.isEnabled()&&S.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},A=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,A),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,a]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(a),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,a]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,a){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const y=this.resolveActionRef(m),S=y.event||this.getEventHandlerName(y.type);l.has(S)||l.set(S,[]),l.get(S).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...S)=>{for(const v of y){const _=S[0],A=_&&typeof _=="object"&&"preventDefault"in _;if(A&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),A&&v.key&&"key"in _){if(this.isImeComposing(_)){j.log("Key filter skipped (IME composing):",v.key);continue}if(_.key!==v.key){j.log("Key filter not matched:",v.key,"actual:",_.key);continue}j.log("Key filter matched:",v.key)}if(v.debounce){const x=`${c}-${v.handler}-${m}`,O=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let M;if(A)M=_;else if(O){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(D._changedKeys=_._changedKeys),M=D}else M=new Event("custom");const T=v.event?{...n,$args:S}:n;this.handleDebouncedAction(v,M,T,a,x,S)}else if(this.flushPendingDebounceTimers(),v.event){const x={...n,$args:S},O=A?_:new Event("custom");this.createHandler(v,x,a)(O)}else if(A)this.createHandler(v,n,a)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const O={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(v,n,a)(O)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,n=5){const a=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(a.has(l))return"[Circular Array]";a.add(l);const d=l.slice(0,10).map(f=>i(f,c+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(a.has(l))return"[Circular Reference]";a.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)try{d[m]=i(l[m],c+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(bs,"loadedScripts",new Set);let bo=bs,nc=null;function bm(o){return nc||(nc=new bo(o)),nc}function AC(o){nc=o}const vm=ht("TransitionManager");class xC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(vm.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){vm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const jr=new xC,rc=ht("TransitionContext"),Sm=H.createContext({isTransitioning:!1}),Vd=({children:o})=>{const[e,n]=H.useState(()=>{const i=jr.getIsPending();return rc.log("Initial state:",i),i});H.useEffect(()=>{rc.log("Subscribing to TransitionManager");const i=jr.subscribe(l=>{rc.log("Received isPending update:",l),n(l)});return()=>{rc.log("Unsubscribing from TransitionManager"),i()}},[]);const a=H.useMemo(()=>({isTransitioning:e}),[e]);return gt.jsx(Sm.Provider,{value:a,children:o})},wm=()=>H.useContext(Sm),ac="__g7LocalInitTracking";function Fd(){const o=globalThis;return o[ac]||(o[ac]={hash:"",timestamp:void 0,consumed:void 0}),o[ac]}function TC(){const o=globalThis;o[ac]={hash:"",timestamp:void 0,consumed:void 0}}function RC(o){Fd().consumed=o}function kC(o){return Fd().consumed===o}function DC(o){return o.globalTrackedKey!==o.trackingKey?"apply":o.instanceHandledKey===o.trackingKey?"skip":"prune"}function OC(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function LC(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!kC(o)))return e;const{_forceLocalInit:a,...i}=o,{_forceLocalInit:l,...c}=e,d={...i,...c},f=OC(a,l);return f!==void 0&&(d._forceLocalInit=f),d}function MC(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function Cm(o){const e=MC(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Kd=H.createContext(Cm(1024)),ic=({children:o,overrideWidth:e})=>{const[n,a]=H.useState(()=>hi.getWidth());H.useEffect(()=>{const c=hi.subscribe(d=>{a(d)});return()=>{c()}},[]);const i=e??n,l=H.useMemo(()=>Cm(i),[i]);return gt.jsx(Kd.Provider,{value:l,children:o})},Wd=()=>H.useContext(Kd);window.G7Core?.createLogger?.("Core:State");function $C(o,e,n,a){const{syncOnControlledChange:i=!0,isEqual:l}=a??{},c=o!==void 0;H.useRef(c);const[d,f]=H.useState(o!==void 0?o:e),g=d,m=H.useRef(o),y=H.useRef(!1);H.useEffect(()=>{if(y.current){m.current=o;return}i&&c&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,c,i,l,d]);const S=H.useCallback(v=>{const _=typeof v=="function"?v(g):v;(l?l(g,_):g===_)||(y.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{y.current=!1}))},[g,c,n,l]);return[g,S]}function NC(o,e){return o===e?!0:o.length!==e.length?!1:o.every((n,a)=>n===e[a])}function Em(o,e){if(o===e)return!0;const n=Object.keys(o),a=Object.keys(e);return n.length!==a.length?!1:n.every(i=>o[i]===e[i])}const _m=H.createContext({}),IC=({children:o,value:e})=>gt.jsx(_m.Provider,{value:e,children:o}),HC=()=>H.useContext(_m),jC=(o,e)=>{if(!o)return;const n=e.split(".");let a=o;for(const i of n){if(a==null)return;a=a[i]}return a},zC=(o,e,n)=>{const a=e.split(".");if(a.length===1)return{...o,[a[0]]:n};const i={...o};let l=i;for(let c=0;c{us.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{us.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},Am=H.createContext(UC);let PC=0;function BC(){return`isolated-${++PC}-${Date.now().toString(36)}`}function xm(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const n={...o};for(const a of Object.keys(e)){const i=e[a],l=o?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[a]=xm(l,i):n[a]=i}return n}function qC(o,e){return e?e.split(".").reduce((n,a)=>n?.[a],o):o}function GC(o,e,n){const a=e.split("."),i={...o};let l=i;for(let c=0;c{const i=H.useRef(e||BC()).current,[l,c]=H.useState(o),d=H.useRef(l);d.current=l;const f=H.useCallback(v=>qC(d.current,v),[]),g=H.useCallback((v,_)=>{c(A=>{const x=GC(A,v,_);return us.log(`[${i}] setState: ${v} =`,_),x})},[i]),m=H.useCallback((v,_="deep")=>{c(A=>{let x;return _==="replace"?x=v:_==="shallow"?x={...A,...v}:x=xm(A,v),us.log(`[${i}] mergeState (${_}):`,v),x})},[i]),y=H.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),S=H.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return H.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=S,v&&(v._isolatedStates||(v._isolatedStates={}),v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:created",{id:i,state:l}),us.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],v?._isolatedStates&&delete v._isolatedStates[i],v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:destroyed",{id:i}),us.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,S]),H.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),v?._isolatedStates&&(v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),gt.jsx(Am.Provider,{value:y,children:n})},FC=()=>{const o=H.useContext(Am);return o.scopeId?o:null};var ka=Qg();function KC(){for(var o=arguments.length,e=new Array(o),n=0;na=>{e.forEach(i=>i(a))},e)}const sc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ds(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function Yd(o){return"nodeType"in o}function Nn(o){var e,n;return o?ds(o)?o:Yd(o)&&(e=(n=o.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Xd(o){const{Document:e}=Nn(o);return o instanceof e}function vo(o){return ds(o)?!1:o instanceof Nn(o).HTMLElement}function Tm(o){return o instanceof Nn(o).SVGElement}function fs(o){return o?ds(o)?o.document:Yd(o)?Xd(o)?o:vo(o)||Tm(o)?o.ownerDocument:document:document:document}const zr=sc?H.useLayoutEffect:H.useEffect;function Jd(o){const e=H.useRef(o);return zr(()=>{e.current=o}),H.useCallback(function(){for(var n=arguments.length,a=new Array(n),i=0;i{o.current=setInterval(a,i)},[]),n=H.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,n]}function So(o,e){e===void 0&&(e=[o]);const n=H.useRef(o);return zr(()=>{n.current!==o&&(n.current=o)},e),n}function wo(o,e){const n=H.useRef();return H.useMemo(()=>{const a=o(n.current);return n.current=a,a},[...e])}function oc(o){const e=Jd(o),n=H.useRef(null),a=H.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,a]}function Qd(o){const e=H.useRef();return H.useEffect(()=>{e.current=o},[o]),e.current}let Zd={};function Co(o,e){return H.useMemo(()=>{if(e)return e;const n=Zd[o]==null?0:Zd[o]+1;return Zd[o]=n,o+"-"+n},[o,e])}function Rm(o){return function(e){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const hs=Rm(1),Eo=Rm(-1);function YC(o){return"clientX"in o&&"clientY"in o}function ef(o){if(!o)return!1;const{KeyboardEvent:e}=Nn(o.target);return e&&o instanceof e}function XC(o){if(!o)return!1;const{TouchEvent:e}=Nn(o.target);return e&&o instanceof e}function tf(o){if(XC(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:n}=o.touches[0];return{x:e,y:n}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:n}=o.changedTouches[0];return{x:e,y:n}}}return YC(o)?{x:o.clientX,y:o.clientY}:null}const _o=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:n}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:n}=o;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(o){if(o)return[_o.Translate.toString(o),_o.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:n,easing:a}=o;return e+" "+n+"ms "+a}}}),km="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function JC(o){return o.matches(km)?o:o.querySelector(km)}const QC={display:"none"};function ZC(o){let{id:e,value:n}=o;return Xe.createElement("div",{id:e,style:QC},n)}function eE(o){let{id:e,announcement:n,ariaLiveType:a="assertive"}=o;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Xe.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},n)}function tE(){const[o,e]=H.useState("");return{announce:H.useCallback(a=>{a!=null&&e(a)},[]),announcement:o}}const Dm=H.createContext(null);function nE(o){const e=H.useContext(Dm);H.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function rE(){const[o]=H.useState(()=>new Set),e=H.useCallback(a=>(o.add(a),()=>o.delete(a)),[o]);return[H.useCallback(a=>{let{type:i,event:l}=a;o.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[o]),e]}const aE={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. - `},iE={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function sE(o){let{announcements:e=iE,container:n,hiddenTextDescribedById:a,screenReaderInstructions:i=aE}=o;const{announce:l,announcement:c}=tE(),d=Co("DndLiveRegion"),[f,g]=H.useState(!1);if(H.useEffect(()=>{g(!0)},[]),nE(H.useMemo(()=>({onDragStart(y){let{active:S}=y;l(e.onDragStart({active:S}))},onDragMove(y){let{active:S,over:v}=y;e.onDragMove&&l(e.onDragMove({active:S,over:v}))},onDragOver(y){let{active:S,over:v}=y;l(e.onDragOver({active:S,over:v}))},onDragEnd(y){let{active:S,over:v}=y;l(e.onDragEnd({active:S,over:v}))},onDragCancel(y){let{active:S,over:v}=y;l(e.onDragCancel({active:S,over:v}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(ZC,{id:a,value:i.draggable}),Xe.createElement(eE,{id:d,announcement:c}));return n?ka.createPortal(m,n):m}var an;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(an||(an={}));function lc(){}function Lm(o,e){return H.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function oE(){for(var o=arguments.length,e=new Array(o),n=0;n[...e].filter(a=>a!=null),[...e])}const wr=Object.freeze({x:0,y:0});function Mm(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function $m(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return n-a}function lE(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return a-n}function Nm(o){let{left:e,top:n,height:a,width:i}=o;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+a},{x:e+i,y:n+a}]}function Im(o,e){if(!o||o.length===0)return null;const[n]=o;return n[e]}function Hm(o,e,n){return e===void 0&&(e=o.left),n===void 0&&(n=o.top),{x:e+o.width*.5,y:n+o.height*.5}}const cE=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=Hm(e,e.left,e.top),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=Mm(Hm(f),i);l.push({id:d,data:{droppableContainer:c,value:g}})}}return l.sort($m)},uE=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=Nm(e),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=Nm(f),m=i.reduce((S,v,_)=>S+Mm(g[_],v),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort($m)};function dE(o,e){const n=Math.max(e.top,o.top),a=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),c=i-a,d=l-n;if(a{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=[];for(const l of a){const{id:c}=l,d=n.get(c);if(d){const f=dE(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(lE)};function hE(o,e,n){return{...o,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function jm(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:wr}function gE(o){return function(n){for(var a=arguments.length,i=new Array(a>1?a-1:0),l=1;l({...c,top:c.top+o*d.y,bottom:c.bottom+o*d.y,left:c.left+o*d.x,right:c.right+o*d.x}),{...n})}}const pE=gE(1);function mE(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function yE(o,e,n){const a=mE(e);if(!a)return o;const{scaleX:i,scaleY:l,x:c,y:d}=a,f=o.left-c-(1-i)*parseFloat(n),g=o.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?o.width/i:o.width,y=l?o.height/l:o.height;return{width:m,height:y,top:g,right:f+m,bottom:g+y,left:f}}const bE={ignoreTransform:!1};function gs(o,e){e===void 0&&(e=bE);let n=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=In(o).getComputedStyle(o);g&&(n=yE(n,g,m))}const{top:a,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:a,left:i,width:l,height:c,bottom:d,right:f}}function zm(o){return gs(o,{ignoreTransform:!0})}function vE(o){const e=o.innerWidth,n=o.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function SE(o,e){return e===void 0&&(e=In(o).getComputedStyle(o)),e.position==="fixed"}function wE(o,e){e===void 0&&(e=In(o).getComputedStyle(o));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function cc(o,e){const n=[];function a(i){if(e!=null&&n.length>=e||!i)return n;if(Yd(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!vo(i)||Rm(i)||n.includes(i))return n;const l=In(o).getComputedStyle(i);return i!==o&&wE(i,l)&&n.push(i),SE(i,l)?n:a(i.parentNode)}return o?a(o):n}function Um(o){const[e]=cc(o,1);return e??null}function tf(o){return!sc||!o?null:ds(o)?o:Wd(o)?Yd(o)||o===fs(o).scrollingElement?window:vo(o)?o:null:null}function Pm(o){return ds(o)?o.scrollX:o.scrollLeft}function Bm(o){return ds(o)?o.scrollY:o.scrollTop}function nf(o){return{x:Pm(o),y:Bm(o)}}var gn;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(gn||(gn={}));function qm(o){return!sc||!o?!1:o===document.scrollingElement}function Gm(o){const e={x:0,y:0},n=qm(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},a={x:o.scrollWidth-n.width,y:o.scrollHeight-n.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,c=o.scrollTop>=a.y,d=o.scrollLeft>=a.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:a,minScroll:e}}const CE={x:.2,y:.2};function EE(o,e,n,a,i){let{top:l,left:c,right:d,bottom:f}=n;a===void 0&&(a=10),i===void 0&&(i=CE);const{isTop:g,isBottom:m,isLeft:y,isRight:S}=Gm(o),v={x:0,y:0},_={x:0,y:0},A={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+A.height?(v.y=gn.Backward,_.y=a*Math.abs((e.top+A.height-l)/A.height)):!m&&f>=e.bottom-A.height&&(v.y=gn.Forward,_.y=a*Math.abs((e.bottom-A.height-f)/A.height)),!S&&d>=e.right-A.width?(v.x=gn.Forward,_.x=a*Math.abs((e.right-A.width-d)/A.width)):!y&&c<=e.left+A.width&&(v.x=gn.Backward,_.x=a*Math.abs((e.left+A.width-c)/A.width)),{direction:v,speed:_}}function _E(o){if(o===document.scrollingElement){const{innerWidth:l,innerHeight:c}=window;return{top:0,left:0,right:l,bottom:c,width:l,height:c}}const{top:e,left:n,right:a,bottom:i}=o.getBoundingClientRect();return{top:e,left:n,right:a,bottom:i,width:o.clientWidth,height:o.clientHeight}}function Vm(o){return o.reduce((e,n)=>hs(e,nf(n)),wr)}function AE(o){return o.reduce((e,n)=>e+Pm(n),0)}function xE(o){return o.reduce((e,n)=>e+Bm(n),0)}function TE(o,e){if(e===void 0&&(e=gs),!o)return;const{top:n,left:a,bottom:i,right:l}=e(o);Um(o)&&(i<=0||l<=0||n>=window.innerHeight||a>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const RE=[["x",["left","right"],AE],["y",["top","bottom"],xE]];class rf{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const a=cc(n),i=Vm(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of RE)for(const f of c)Object.defineProperty(this,f,{get:()=>{const g=d(a),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ao{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...n)})},this.target=e}add(e,n,a){var i;(i=this.target)==null||i.addEventListener(e,n,a),this.listeners.push([e,n,a])}}function kE(o){const{EventTarget:e}=In(o);return o instanceof e?o:fs(o)}function af(o,e){const n=Math.abs(o.x),a=Math.abs(o.y);return typeof e=="number"?Math.sqrt(n**2+a**2)>e:"x"in e&&"y"in e?n>e.x&&a>e.y:"x"in e?n>e.x:"y"in e?a>e.y:!1}var ar;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(ar||(ar={}));function Fm(o){o.preventDefault()}function DE(o){o.stopPropagation()}var ut;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(ut||(ut={}));const Km={start:[ut.Space,ut.Enter],cancel:[ut.Esc],end:[ut.Space,ut.Enter,ut.Tab]},OE=(o,e)=>{let{currentCoordinates:n}=e;switch(o.code){case ut.Right:return{...n,x:n.x+25};case ut.Left:return{...n,x:n.x-25};case ut.Down:return{...n,y:n.y+25};case ut.Up:return{...n,y:n.y-25}}};class sf{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new Ao(fs(n)),this.windowListeners=new Ao(In(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ar.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,a=e.node.current;a&&TE(a),n(wr)}handleKeyDown(e){if(Zd(e)){const{active:n,context:a,options:i}=this.props,{keyboardCodes:l=Km,coordinateGetter:c=OE,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:g}=a.current,m=g?{x:g.left,y:g.top}:wr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:a.current,currentCoordinates:m});if(y){const S=Eo(y,m),v={x:0,y:0},{scrollableAncestors:_}=a.current;for(const A of _){const x=e.code,{isTop:O,isRight:M,isLeft:T,isBottom:D,maxScroll:z,minScroll:P}=Gm(A),q=_E(A),W={x:Math.min(x===ut.Right?q.right-q.width/2:q.right,Math.max(x===ut.Right?q.left:q.left+q.width/2,y.x)),y:Math.min(x===ut.Down?q.bottom-q.height/2:q.bottom,Math.max(x===ut.Down?q.top:q.top+q.height/2,y.y))},he=x===ut.Right&&!M||x===ut.Left&&!T,Ee=x===ut.Down&&!D||x===ut.Up&&!O;if(he&&W.x!==y.x){const be=A.scrollLeft+S.x,Ue=x===ut.Right&&be<=z.x||x===ut.Left&&be>=P.x;if(Ue&&!S.y){A.scrollTo({left:be,behavior:d});return}Ue?v.x=A.scrollLeft-be:v.x=x===ut.Right?A.scrollLeft-z.x:A.scrollLeft-P.x,v.x&&A.scrollBy({left:-v.x,behavior:d});break}else if(Ee&&W.y!==y.y){const be=A.scrollTop+S.y,Ue=x===ut.Down&&be<=z.y||x===ut.Up&&be>=P.y;if(Ue&&!S.x){A.scrollTo({top:be,behavior:d});return}Ue?v.y=A.scrollTop-be:v.y=x===ut.Down?A.scrollTop-z.y:A.scrollTop-P.y,v.y&&A.scrollBy({top:-v.y,behavior:d});break}}this.handleMove(e,hs(Eo(y,this.referenceCoordinates),v))}}}handleMove(e,n){const{onMove:a}=this.props;e.preventDefault(),a(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}sf.activators=[{eventName:"onKeyDown",handler:(o,e,n)=>{let{keyboardCodes:a=Km,onActivation:i}=e,{active:l}=n;const{code:c}=o.nativeEvent;if(a.start.includes(c)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function Wm(o){return!!(o&&"distance"in o)}function Ym(o){return!!(o&&"delay"in o)}class of{constructor(e,n,a){var i;a===void 0&&(a=kE(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:l}=e,{target:c}=l;this.props=e,this.events=n,this.document=fs(c),this.documentListeners=new Ao(this.document),this.listeners=new Ao(a),this.windowListeners=new Ao(In(c)),this.initialCoordinates=(i=ef(l))!=null?i:wr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.DragStart,Fm),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),this.windowListeners.add(ar.ContextMenu,Fm),this.documentListeners.add(ar.Keydown,this.handleKeydown),n){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ym(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Wm(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ar.Click,DE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ar.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:a,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=ef(e))!=null?n:wr,g=Eo(i,f);if(!a&&d){if(Wm(d)){if(d.tolerance!=null&&af(g,d.tolerance))return this.handleCancel();if(af(g,d.distance))return this.handleStart()}if(Ym(d)&&af(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===ut.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const LE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class lf extends of{constructor(e){const{event:n}=e,a=fs(n.target);super(e,LE,a)}}lf.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return!n.isPrimary||n.button!==0?!1:(a?.({event:n}),!0)}}];const ME={move:{name:"mousemove"},end:{name:"mouseup"}};var cf;(function(o){o[o.RightClick=2]="RightClick"})(cf||(cf={}));class $E extends of{constructor(e){super(e,ME,fs(e.event.target))}}$E.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return n.button===cf.RightClick?!1:(a?.({event:n}),!0)}}];const uf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class NE extends of{constructor(e){super(e,uf)}static setup(){return window.addEventListener(uf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(uf.move.name,e)};function e(){}}}NE.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;const{touches:i}=n;return i.length>1?!1:(a?.({event:n}),!0)}}];var xo;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(xo||(xo={}));var uc;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(uc||(uc={}));function IE(o){let{acceleration:e,activator:n=xo.Pointer,canScroll:a,draggingRect:i,enabled:l,interval:c=5,order:d=uc.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:y,threshold:S}=o;const v=jE({delta:y,disabled:!l}),[_,A]=WC(),x=H.useRef({x:0,y:0}),O=H.useRef({x:0,y:0}),M=H.useMemo(()=>{switch(n){case xo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case xo.DraggableRect:return i}},[n,i,f]),T=H.useRef(null),D=H.useCallback(()=>{const P=T.current;if(!P)return;const q=x.current.x*O.current.x,W=x.current.y*O.current.y;P.scrollBy(q,W)},[]),z=H.useMemo(()=>d===uc.TreeOrder?[...g].reverse():g,[d,g]);H.useEffect(()=>{if(!l||!g.length||!M){A();return}for(const P of z){if(a?.(P)===!1)continue;const q=g.indexOf(P),W=m[q];if(!W)continue;const{direction:he,speed:Ee}=EE(P,W,M,e,S);for(const be of["x","y"])v[be][he[be]]||(Ee[be]=0,he[be]=0);if(Ee.x>0||Ee.y>0){A(),T.current=P,_(D,c),x.current=Ee,O.current=he;return}}x.current={x:0,y:0},O.current={x:0,y:0},A()},[e,D,a,A,l,c,JSON.stringify(M),JSON.stringify(v),_,g,z,m,JSON.stringify(S)])}const HE={x:{[gn.Backward]:!1,[gn.Forward]:!1},y:{[gn.Backward]:!1,[gn.Forward]:!1}};function jE(o){let{delta:e,disabled:n}=o;const a=Jd(e);return wo(i=>{if(n||!a||!i)return HE;const l={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[gn.Backward]:i.x[gn.Backward]||l.x===-1,[gn.Forward]:i.x[gn.Forward]||l.x===1},y:{[gn.Backward]:i.y[gn.Backward]||l.y===-1,[gn.Forward]:i.y[gn.Forward]||l.y===1}}},[n,e,a])}function zE(o,e){const n=e!=null?o.get(e):void 0,a=n?n.node.current:null;return wo(i=>{var l;return e==null?null:(l=a??i)!=null?l:null},[a,e])}function UE(o,e){return H.useMemo(()=>o.reduce((n,a)=>{const{sensor:i}=a,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,a)}));return[...n,...l]},[]),[o,e])}var To;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(To||(To={}));var df;(function(o){o.Optimized="optimized"})(df||(df={}));const Xm=new Map;function PE(o,e){let{dragging:n,dependencies:a,config:i}=e;const[l,c]=H.useState(null),{frequency:d,measure:f,strategy:g}=i,m=H.useRef(o),y=x(),S=So(y),v=H.useCallback(function(O){O===void 0&&(O=[]),!S.current&&c(M=>M===null?O:M.concat(O.filter(T=>!M.includes(T))))},[S]),_=H.useRef(null),A=wo(O=>{if(y&&!n)return Xm;if(!O||O===Xm||m.current!==o||l!=null){const M=new Map;for(let T of o){if(!T)continue;if(l&&l.length>0&&!l.includes(T.id)&&T.rect.current){M.set(T.id,T.rect.current);continue}const D=T.node.current,z=D?new rf(f(D),D):null;T.rect.current=z,z&&M.set(T.id,z)}return M}return O},[o,l,n,y,f]);return H.useEffect(()=>{m.current=o},[o]),H.useEffect(()=>{y||v()},[n,y]),H.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),H.useEffect(()=>{y||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{v(),_.current=null},d))},[d,y,v,...a]),{droppableRects:A,measureDroppableContainers:v,measuringScheduled:l!=null};function x(){switch(g){case To.Always:return!1;case To.BeforeDragging:return n;default:return!n}}}function Jm(o,e){return wo(n=>o?n||(typeof e=="function"?e(o):o):null,[e,o])}function BE(o,e){return Jm(o,e)}function qE(o){let{callback:e,disabled:n}=o;const a=Xd(e),i=H.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(a)},[a,n]);return H.useEffect(()=>()=>i?.disconnect(),[i]),i}function dc(o){let{callback:e,disabled:n}=o;const a=Xd(e),i=H.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(a)},[n]);return H.useEffect(()=>()=>i?.disconnect(),[i]),i}function GE(o){return new rf(gs(o),o)}function Qm(o,e,n){e===void 0&&(e=GE);const[a,i]=H.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??n)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=qE({callback(f){if(o)for(const g of f){const{type:m,target:y}=g;if(m==="childList"&&y instanceof HTMLElement&&y.contains(o)){l();break}}}}),d=dc({callback:l});return zr(()=>{l(),o?(d?.observe(o),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[o]),a}function VE(o){const e=Jm(o);return jm(o,e)}const Zm=[];function FE(o){const e=H.useRef(o),n=wo(a=>o?a&&a!==Zm&&o&&e.current&&o.parentNode===e.current.parentNode?a:cc(o):Zm,[o]);return H.useEffect(()=>{e.current=o},[o]),n}function KE(o){const[e,n]=H.useState(null),a=H.useRef(o),i=H.useCallback(l=>{const c=tf(l.target);c&&n(d=>d?(d.set(c,nf(c)),new Map(d)):null)},[]);return H.useEffect(()=>{const l=a.current;if(o!==l){c(l);const d=o.map(f=>{const g=tf(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,nf(g)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),a.current=o}return()=>{c(o),c(l)};function c(d){d.forEach(f=>{const g=tf(f);g?.removeEventListener("scroll",i)})}},[i,o]),H.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,c)=>hs(l,c),wr):Vm(o):wr,[o,e])}function ey(o,e){e===void 0&&(e=[]);const n=H.useRef(null);return H.useEffect(()=>{n.current=null},e),H.useEffect(()=>{const a=o!==wr;a&&!n.current&&(n.current=o),!a&&n.current&&(n.current=null)},[o]),n.current?Eo(o,n.current):wr}function WE(o){H.useEffect(()=>{if(!sc)return;const e=o.map(n=>{let{sensor:a}=n;return a.setup==null?void 0:a.setup()});return()=>{for(const n of e)n?.()}},o.map(e=>{let{sensor:n}=e;return n}))}function YE(o,e){return H.useMemo(()=>o.reduce((n,a)=>{let{eventName:i,handler:l}=a;return n[i]=c=>{l(c,e)},n},{}),[o,e])}function ty(o){return H.useMemo(()=>o?vE(o):null,[o])}const ny=[];function XE(o,e){e===void 0&&(e=gs);const[n]=o,a=ty(n?In(n):null),[i,l]=H.useState(ny);function c(){l(()=>o.length?o.map(f=>qm(f)?a:new rf(e(f),f)):ny)}const d=dc({callback:c});return zr(()=>{d?.disconnect(),c(),o.forEach(f=>d?.observe(f))},[o]),i}function JE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return vo(e)?e:o}function QE(o){let{measure:e}=o;const[n,a]=H.useState(null),i=H.useCallback(g=>{for(const{target:m}of g)if(vo(m)){a(y=>{const S=e(m);return y?{...y,width:S.width,height:S.height}:S});break}},[e]),l=dc({callback:i}),c=H.useCallback(g=>{const m=JE(g);l?.disconnect(),m&&l?.observe(m),a(m?e(m):null)},[e,l]),[d,f]=oc(c);return H.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const ZE=[{sensor:lf,options:{}},{sensor:sf,options:{}}],e_={current:{}},fc={draggable:{measure:zm},droppable:{measure:zm,strategy:To.WhileDragging,frequency:df.Optimized},dragOverlay:{measure:gs}};class Ro extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,a;return(n=(a=this.get(e))==null?void 0:a.node.current)!=null?n:void 0}}const t_={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ro,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:lc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:fc,measureDroppableContainers:lc,windowRect:null,measuringScheduled:!1},n_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:lc,draggableNodes:new Map,over:null,measureDroppableContainers:lc},hc=H.createContext(n_),ry=H.createContext(t_);function r_(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ro}}}function a_(o,e){switch(e.type){case an.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case an.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case an.DragEnd:case an.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case an.RegisterDroppable:{const{element:n}=e,{id:a}=n,i=new Ro(o.droppable.containers);return i.set(a,n),{...o,droppable:{...o.droppable,containers:i}}}case an.SetDroppableDisabled:{const{id:n,key:a,disabled:i}=e,l=o.droppable.containers.get(n);if(!l||a!==l.key)return o;const c=new Ro(o.droppable.containers);return c.set(n,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:c}}}case an.UnregisterDroppable:{const{id:n,key:a}=e,i=o.droppable.containers.get(n);if(!i||a!==i.key)return o;const l=new Ro(o.droppable.containers);return l.delete(n),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function i_(o){let{disabled:e}=o;const{active:n,activatorEvent:a,draggableNodes:i}=H.useContext(hc),l=Jd(a),c=Jd(n?.id);return H.useEffect(()=>{if(!e&&!a&&l&&c!=null){if(!Zd(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const y=JC(m);if(y){y.focus();break}}})}},[a,e,i,c,l]),null}function s_(o,e){let{transform:n,...a}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...a}),n):n}function o_(o){return H.useMemo(()=>({draggable:{...fc.draggable,...o?.draggable},droppable:{...fc.droppable,...o?.droppable},dragOverlay:{...fc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function l_(o){let{activeNode:e,measure:n,initialRect:a,config:i=!0}=o;const l=H.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;zr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!a)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=n(g),y=jm(m,a);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const S=Um(g);S&&S.scrollBy({top:y.y,left:y.x})}},[e,c,d,a,n])}const ay=H.createContext({...wr,scaleX:1,scaleY:1});var Da;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(Da||(Da={}));const c_=H.memo(function(e){var n,a,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:g,sensors:m=ZE,collisionDetection:y=fE,measuring:S,modifiers:v,..._}=e;const A=H.useReducer(a_,void 0,r_),[x,O]=A,[M,T]=rE(),[D,z]=H.useState(Da.Uninitialized),P=D===Da.Initialized,{draggable:{active:q,nodes:W,translate:he},droppable:{containers:Ee}}=x,be=q!=null?W.get(q):null,Ue=H.useRef({initial:null,translated:null}),Fe=H.useMemo(()=>{var ge;return q!=null?{id:q,data:(ge=be?.data)!=null?ge:e_,rect:Ue}:null},[q,be]),Ge=H.useRef(null),[wt,J]=H.useState(null),[ue,Me]=H.useState(null),te=So(_,Object.values(_)),pe=Co("DndDescribedBy",c),N=H.useMemo(()=>Ee.getEnabled(),[Ee]),R=o_(S),{droppableRects:de,measureDroppableContainers:fe,measuringScheduled:xe}=PE(N,{dragging:P,dependencies:[he.x,he.y],config:R.droppable}),ee=zE(W,q),_e=H.useMemo(()=>ue?ef(ue):null,[ue]),Be=ve(),ke=BE(ee,R.draggable.measure);l_({activeNode:q!=null?W.get(q):null,config:Be.layoutShiftCompensation,initialRect:ke,measure:R.draggable.measure});const Ie=Qm(ee,R.draggable.measure,ke),Ct=Qm(ee?ee.parentElement:null),ot=H.useRef({activatorEvent:null,active:null,activeNode:ee,collisionRect:null,collisions:null,droppableRects:de,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ot=Ee.getNodeFor((n=ot.current.over)==null?void 0:n.id),vt=QE({measure:R.dragOverlay.measure}),_t=(a=vt.nodeRef.current)!=null?a:ee,Oe=P?(i=vt.rect)!=null?i:Ie:null,nt=!!(vt.nodeRef.current&&vt.rect),sn=VE(nt?null:Ie),Mt=ty(_t?In(_t):null),Vt=FE(P?Ot??ee:null),on=XE(Vt),ln=s_(v,{transform:{x:he.x-sn.x,y:he.y-sn.y,scaleX:1,scaleY:1},activatorEvent:ue,active:Fe,activeNodeRect:Ie,containerNodeRect:Ct,draggingNodeRect:Oe,over:ot.current.over,overlayNodeRect:vt.rect,scrollableAncestors:Vt,scrollableAncestorRects:on,windowRect:Mt}),Br=_e?hs(_e,he):null,Ft=KE(Vt),Ci=ey(Ft),na=ey(Ft,[Ie]),yn=hs(ln,Ci),On=Oe?pE(Oe,ln):null,rt=Fe&&On?y({active:Fe,collisionRect:On,droppableRects:de,droppableContainers:N,pointerCoordinates:Br}):null,jn=Im(rt,"id"),[bn,ra]=H.useState(null),sr=nt?ln:hs(ln,na),cn=hE(sr,(l=bn?.rect)!=null?l:null,Ie),Tn=H.useRef(null),un=H.useCallback((ge,we)=>{let{sensor:Ae,options:Ke}=we;if(Ge.current==null)return;const Te=W.get(Ge.current);if(!Te)return;const $e=ge.nativeEvent,Re=new Ae({active:Ge.current,activeNode:Te,event:$e,options:Ke,context:ot,onAbort(je){if(!W.get(je))return;const{onDragAbort:Se}=te.current,He={id:je};Se?.(He),M({type:"onDragAbort",event:He})},onPending(je,Ve,Se,He){if(!W.get(je))return;const{onDragPending:Tt}=te.current,It={id:je,constraint:Ve,initialCoordinates:Se,offset:He};Tt?.(It),M({type:"onDragPending",event:It})},onStart(je){const Ve=Ge.current;if(Ve==null)return;const Se=W.get(Ve);if(!Se)return;const{onDragStart:He}=te.current,tt={activatorEvent:$e,active:{id:Ve,data:Se.data,rect:Ue}};ka.unstable_batchedUpdates(()=>{He?.(tt),z(Da.Initializing),O({type:an.DragStart,initialCoordinates:je,active:Ve}),M({type:"onDragStart",event:tt}),J(Tn.current),Me($e)})},onMove(je){O({type:an.DragMove,coordinates:je})},onEnd:et(an.DragEnd),onCancel:et(an.DragCancel)});Tn.current=Re;function et(je){return async function(){const{active:Se,collisions:He,over:tt,scrollAdjustedTranslate:Tt}=ot.current;let It=null;if(Se&&Tt){const{cancelDrop:Ln}=te.current;It={activatorEvent:$e,active:Se,collisions:He,delta:Tt,over:tt},je===an.DragEnd&&typeof Ln=="function"&&await Promise.resolve(Ln(It))&&(je=an.DragCancel)}Ge.current=null,ka.unstable_batchedUpdates(()=>{O({type:je}),z(Da.Uninitialized),ra(null),J(null),Me(null),Tn.current=null;const Ln=je===an.DragEnd?"onDragEnd":"onDragCancel";if(It){const zt=te.current[Ln];zt?.(It),M({type:Ln,event:It})}})}}},[W]),V=H.useCallback((ge,we)=>(Ae,Ke)=>{const Te=Ae.nativeEvent,$e=W.get(Ke);if(Ge.current!==null||!$e||Te.dndKit||Te.defaultPrevented)return;const Re={active:$e};ge(Ae,we.options,Re)===!0&&(Te.dndKit={capturedBy:we.sensor},Ge.current=Ke,un(Ae,we))},[W,un]),se=UE(m,V);WE(m),zr(()=>{Ie&&D===Da.Initializing&&z(Da.Initialized)},[Ie,D]),H.useEffect(()=>{const{onDragMove:ge}=te.current,{active:we,activatorEvent:Ae,collisions:Ke,over:Te}=ot.current;if(!we||!Ae)return;const $e={active:we,activatorEvent:Ae,collisions:Ke,delta:{x:yn.x,y:yn.y},over:Te};ka.unstable_batchedUpdates(()=>{ge?.($e),M({type:"onDragMove",event:$e})})},[yn.x,yn.y]),H.useEffect(()=>{const{active:ge,activatorEvent:we,collisions:Ae,droppableContainers:Ke,scrollAdjustedTranslate:Te}=ot.current;if(!ge||Ge.current==null||!we||!Te)return;const{onDragOver:$e}=te.current,Re=Ke.get(jn),et=Re&&Re.rect.current?{id:Re.id,rect:Re.rect.current,data:Re.data,disabled:Re.disabled}:null,je={active:ge,activatorEvent:we,collisions:Ae,delta:{x:Te.x,y:Te.y},over:et};ka.unstable_batchedUpdates(()=>{ra(et),$e?.(je),M({type:"onDragOver",event:je})})},[jn]),zr(()=>{ot.current={activatorEvent:ue,active:Fe,activeNode:ee,collisionRect:On,collisions:rt,droppableRects:de,draggableNodes:W,draggingNode:_t,draggingNodeRect:Oe,droppableContainers:Ee,over:bn,scrollableAncestors:Vt,scrollAdjustedTranslate:yn},Ue.current={initial:Oe,translated:On}},[Fe,ee,rt,On,W,_t,Oe,de,Ee,bn,Vt,yn]),IE({...Be,delta:he,draggingRect:On,pointerCoordinates:Br,scrollableAncestors:Vt,scrollableAncestorRects:on});const ce=H.useMemo(()=>({active:Fe,activeNode:ee,activeNodeRect:Ie,activatorEvent:ue,collisions:rt,containerNodeRect:Ct,dragOverlay:vt,draggableNodes:W,droppableContainers:Ee,droppableRects:de,over:bn,measureDroppableContainers:fe,scrollableAncestors:Vt,scrollableAncestorRects:on,measuringConfiguration:R,measuringScheduled:xe,windowRect:Mt}),[Fe,ee,Ie,ue,rt,Ct,vt,W,Ee,de,bn,fe,Vt,on,R,xe,Mt]),Z=H.useMemo(()=>({activatorEvent:ue,activators:se,active:Fe,activeNodeRect:Ie,ariaDescribedById:{draggable:pe},dispatch:O,draggableNodes:W,over:bn,measureDroppableContainers:fe}),[ue,se,Fe,Ie,O,pe,W,bn,fe]);return Xe.createElement(Om.Provider,{value:T},Xe.createElement(hc.Provider,{value:Z},Xe.createElement(ry.Provider,{value:ce},Xe.createElement(ay.Provider,{value:cn},g)),Xe.createElement(i_,{disabled:d?.restoreFocus===!1})),Xe.createElement(sE,{...d,hiddenTextDescribedById:pe}));function ve(){const ge=wt?.autoScrollEnabled===!1,we=typeof f=="object"?f.enabled===!1:f===!1,Ae=P&&!ge&&!we;return typeof f=="object"?{...f,enabled:Ae}:{enabled:Ae}}}),u_=H.createContext(null),iy="button",d_="Draggable";function f_(o){let{id:e,data:n,disabled:a=!1,attributes:i}=o;const l=Co(d_),{activators:c,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:y,over:S}=H.useContext(hc),{role:v=iy,roleDescription:_="draggable",tabIndex:A=0}=i??{},x=f?.id===e,O=H.useContext(x?ay:u_),[M,T]=oc(),[D,z]=oc(),P=YE(c,e),q=So(n);zr(()=>(y.set(e,{id:e,key:l,node:M,activatorNode:D,data:q}),()=>{const he=y.get(e);he&&he.key===l&&y.delete(e)}),[y,e]);const W=H.useMemo(()=>({role:v,tabIndex:A,"aria-disabled":a,"aria-pressed":x&&v===iy?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[a,v,A,x,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:W,isDragging:x,listeners:a?void 0:P,node:M,over:S,setNodeRef:T,setActivatorNodeRef:z,transform:O}}function h_(){return H.useContext(ry)}const g_="Droppable",p_={timeout:25};function m_(o){let{data:e,disabled:n=!1,id:a,resizeObserverConfig:i}=o;const l=Co(g_),{active:c,dispatch:d,over:f,measureDroppableContainers:g}=H.useContext(hc),m=H.useRef({disabled:n}),y=H.useRef(!1),S=H.useRef(null),v=H.useRef(null),{disabled:_,updateMeasurementsFor:A,timeout:x}={...p_,...i},O=So(A??a),M=H.useCallback(()=>{if(!y.current){y.current=!0;return}v.current!=null&&clearTimeout(v.current),v.current=setTimeout(()=>{g(Array.isArray(O.current)?O.current:[O.current]),v.current=null},x)},[x]),T=dc({callback:M,disabled:_||!c}),D=H.useCallback((W,he)=>{T&&(he&&(T.unobserve(he),y.current=!1),W&&T.observe(W))},[T]),[z,P]=oc(D),q=So(e);return H.useEffect(()=>{!T||!z.current||(T.disconnect(),y.current=!1,T.observe(z.current))},[z,T]),H.useEffect(()=>(d({type:an.RegisterDroppable,element:{id:a,key:l,disabled:n,node:z,rect:S,data:q}}),()=>d({type:an.UnregisterDroppable,key:l,id:a})),[a]),H.useEffect(()=>{n!==m.current.disabled&&(d({type:an.SetDroppableDisabled,id:a,key:l,disabled:n}),m.current.disabled=n)},[a,l,n,d]),{active:c,rect:S,isOver:f?.id===a,node:z,over:f,setNodeRef:P}}function ff(o,e,n){const a=o.slice();return a.splice(n<0?a.length+n:n,0,a.splice(e,1)[0]),a}function y_(o,e){return o.reduce((n,a,i)=>{const l=e.get(a);return l&&(n[i]=l),n},Array(o.length))}function gc(o){return o!==null&&o>=0}function b_(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:a,activeIndex:i,overIndex:l,index:c}=o;const d=(e=n[i])!=null?e:a;if(!d)return null;const f=w_(n,c,i);if(c===i){const g=n[l];return g?{x:ii&&c<=l?{x:-d.width-f,y:0,...pc}:c=l?{x:d.width+f,y:0,...pc}:{x:0,y:0,...pc}};function w_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return!a||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:a,index:i}=o;const l=ff(e,a,n),c=e[i],d=l[i];return!d||!c?null:{x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height}},mc={scaleX:1,scaleY:1},C_=o=>{var e;let{activeIndex:n,activeNodeRect:a,index:i,rects:l,overIndex:c}=o;const d=(e=l[n])!=null?e:a;if(!d)return null;if(i===n){const g=l[c];return g?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...mc}:i=c?{x:0,y:d.height+f,...mc}:{x:0,y:0,...mc}};function E_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return a?na.map(P=>typeof P=="object"&&"id"in P?P.id:P),[a]),_=c!=null,A=c?v.indexOf(c.id):-1,x=g?v.indexOf(g.id):-1,O=H.useRef(v),M=!b_(v,O.current),T=x!==-1&&A===-1||M,D=v_(l);zr(()=>{M&&_&&m(v)},[M,v,_,m]),H.useEffect(()=>{O.current=v},[v]);const z=H.useMemo(()=>({activeIndex:A,containerId:y,disabled:D,disableTransforms:T,items:v,overIndex:x,useDragOverlay:S,sortedRects:y_(v,f),strategy:i}),[A,y,D.draggable,D.droppable,T,v,x,f,S,i]);return Xe.createElement(oy.Provider,{value:z},e)}const A_=o=>{let{id:e,items:n,activeIndex:a,overIndex:i}=o;return ff(n,a,i).indexOf(e)},x_=o=>{let{containerId:e,isSorting:n,wasDragging:a,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!a||d!==l&&i===c?!1:n?!0:c!==i&&e===f},T_={duration:200,easing:"ease"},ly="transform",R_=_o.Transition.toString({property:ly,duration:0,easing:"linear"}),k_={roleDescription:"sortable"};function D_(o){let{disabled:e,index:n,node:a,rect:i}=o;const[l,c]=H.useState(null),d=H.useRef(n);return zr(()=>{if(!e&&n!==d.current&&a.current){const f=i.current;if(f){const g=gs(a.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,a,i]),H.useEffect(()=>{l&&c(null)},[l]),l}function O_(o){let{animateLayoutChanges:e=x_,attributes:n,disabled:a,data:i,getNewIndex:l=A_,id:c,strategy:d,resizeObserverConfig:f,transition:g=T_}=o;const{items:m,containerId:y,activeIndex:S,disabled:v,disableTransforms:_,sortedRects:A,overIndex:x,useDragOverlay:O,strategy:M}=H.useContext(oy),T=L_(a,v),D=m.indexOf(c),z=H.useMemo(()=>({sortable:{containerId:y,index:D,items:m},...i}),[y,i,D,m]),P=H.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:q,node:W,isOver:he,setNodeRef:Ee}=m_({id:c,data:z,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:P,...f}}),{active:be,activatorEvent:Ue,activeNodeRect:Fe,attributes:Ge,setNodeRef:wt,listeners:J,isDragging:ue,over:Me,setActivatorNodeRef:te,transform:pe}=f_({id:c,data:z,attributes:{...k_,...n},disabled:T.draggable}),N=KC(Ee,wt),R=!!be,de=R&&!_&&gc(S)&&gc(x),fe=!O&&ue,xe=fe&&de?pe:null,_e=de?xe??(d??M)({rects:A,activeNodeRect:Fe,activeIndex:S,overIndex:x,index:D}):null,Be=gc(S)&&gc(x)?l({id:c,items:m,activeIndex:S,overIndex:x}):D,ke=be?.id,Ie=H.useRef({activeId:ke,items:m,newIndex:Be,containerId:y}),Ct=m!==Ie.current.items,ot=e({active:be,containerId:y,isDragging:ue,isSorting:R,id:c,index:D,items:m,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:g,wasDragging:Ie.current.activeId!=null}),Ot=D_({disabled:!ot,index:D,node:W,rect:q});return H.useEffect(()=>{R&&Ie.current.newIndex!==Be&&(Ie.current.newIndex=Be),y!==Ie.current.containerId&&(Ie.current.containerId=y),m!==Ie.current.items&&(Ie.current.items=m)},[R,Be,y,m]),H.useEffect(()=>{if(ke===Ie.current.activeId)return;if(ke!=null&&Ie.current.activeId==null){Ie.current.activeId=ke;return}const _t=setTimeout(()=>{Ie.current.activeId=ke},50);return()=>clearTimeout(_t)},[ke]),{active:be,activeIndex:S,attributes:Ge,data:z,rect:q,index:D,newIndex:Be,items:m,isOver:he,isSorting:R,isDragging:ue,listeners:J,node:W,overIndex:x,over:Me,setNodeRef:N,setActivatorNodeRef:te,setDroppableNodeRef:Ee,setDraggableNodeRef:wt,transform:Ot??_e,transition:vt()};function vt(){if(Ot||Ct&&Ie.current.newIndex===D)return R_;if(!(fe&&!Zd(Ue)||!g)&&(R||ot))return _o.Transition.toString({...g,property:ly})}}function L_(o,e){var n,a;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(n=o?.draggable)!=null?n:e.draggable,droppable:(a=o?.droppable)!=null?a:e.droppable}}function yc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const M_=[ut.Down,ut.Right,ut.Up,ut.Left],$_=(o,e)=>{let{context:{active:n,collisionRect:a,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(M_.includes(o.code)){if(o.preventDefault(),!n||!a)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const S=i.get(y.id);if(S)switch(o.code){case ut.Down:a.topS.top&&f.push(y);break;case ut.Left:a.left>S.left&&f.push(y);break;case ut.Right:a.left1&&(m=g[1].id),m!=null){const y=l.get(n.id),S=l.get(m),v=S?i.get(S.id):null,_=S?.node.current;if(_&&v&&y&&S){const x=cc(_).some((P,q)=>d[q]!==P),O=cy(y,S),M=N_(y,S),T=x||!O?{x:0,y:0}:{x:M?a.width-v.width:0,y:M?a.height-v.height:0},D={x:v.left,y:v.top};return T.x&&T.y?D:Eo(D,T)}}}};function cy(o,e){return!yc(o)||!yc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function N_(o,e){return!yc(o)||!yc(e)||!cy(o,e)?!1:o.data.current.sortable.index{const d=H.useId(),f=H.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=oE(Lm(lf,{activationConstraint:{distance:5}}),Lm(sf,{coordinateGetter:$_})),m=H.useCallback(v=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:v.active.id},l?.({activeId:v.active.id})},[l]),y=H.useCallback(v=>{const{active:_,over:A}=v,x=Date.now();if(!A||_.id===A.id){f.current.inProgress=!1;return}const{lastSortTime:O,lastActiveId:M,inProgress:T}=f.current;if(M===_.id&&x-O<500&&!T)return;f.current={inProgress:!1,lastSortTime:x,lastActiveId:_.id};const D=o.findIndex(P=>String(P[e])===String(_.id)),z=o.findIndex(P=>String(P[e])===String(A.id));if(D!==-1&&z!==-1&&D!==z){const P=ff(o,D,z);i?.(P,{oldIndex:D,newIndex:z})}},[o,e,i]),S=o.map(v=>String(v[e]));return gt.jsx(c_,{id:d,sensors:g,collisionDetection:cE,onDragStart:m,onDragEnd:y,children:gt.jsx(__,{items:S,strategy:I_[n],children:a})},c!==void 0?`${d}-v${c}`:d)},uy=H.createContext(null),j_=({value:o,children:e})=>gt.jsx(uy.Provider,{value:o,children:e}),z_=()=>H.useContext(uy),U_=({id:o,handle:e,as:n="div",children:a})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:g}=O_({id:o}),m={transform:_o.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return gt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:gt.jsx(j_,{value:{listeners:l,handle:e,isDragging:g},children:a})})},st=ht("DynamicRenderer");function Zr(){try{return window.G7Core?.devTools}catch{return}}function gf(o,e,n,a){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,n,a)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>gf(i,e,n,a));if(o&&typeof o=="object"){const i={};for(const[l,c]of Object.entries(o))i[l]=gf(c,e,n,a);return i}return o}function P_(o){const e=Object.keys(o);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const Cr=(o,e)=>{const n=["errors"],a={...o};for(const i of Object.keys(e)){const l=e[i],c=o[i];if(l===null){a[i]=null;continue}if(n.includes(i)){a[i]=l;continue}if(Array.isArray(l)){a[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&P_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)a[i]={...l};else{const g=[...c];for(const[m,y]of Object.entries(l)){const S=parseInt(m,10);S>=0&&S=g.length&&(g[S]=y)}a[i]=g}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?a[i]=Cr(c,l):a[i]=l}return a},bc=(o,e)=>{let n=null;const a=()=>(n===null&&(n={...o}),n);for(const i of Object.keys(e)){if(!(i in o))continue;const l=e[i],c=o[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=bc(c,l);if(d===c)continue;Object.keys(d).length===0?delete a()[i]:a()[i]=d}else delete a()[i]}return n??o},B_=o=>{const e={},n=o.split(";").filter(a=>a.trim());for(const a of n){const i=a.indexOf(":");if(i===-1)continue;const l=a.substring(0,i).trim(),c=a.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=c}}return e};class q_ extends H.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){st.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:gt.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[gt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),gt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&>.jsxs("details",{className:"mt-2",children:[gt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),gt.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Ur=H.memo(({componentDef:o,dataContext:e,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:S=!1,onComponentSelect:v,onComponentHover:_,onDragStart:A,onDragEnd:x,componentPath:O,layoutKey:M})=>{const[T,D]=H.useState({loadingActions:{}});H.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const z=H.useRef(null);H.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:se,...ce}=e._localInit,Z=`${JSON.stringify(ce)}:${V||"no-force"}`;if(z.current!==Z){z.current=Z;const ve=se||"shallow",we=window.G7Core?.state?.get?.()?._local||{},Ae=window.__g7PendingLocalState||{},Ke={...we,...Ae};ve==="replace"?window.__g7PendingLocalState={loadingActions:Ke.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=Cr(Ke,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Ke,...ce,hasChanges:!1};const Te=window.__g7SetLocalOverrideKeys;Te&&typeof Te=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=Cr(Te,{...ce,hasChanges:!1}))}}}),H.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){D(ve=>bc(ve,V));const se=V,ce=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===se&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const P=H.useRef(M);H.useEffect(()=>{o._fromBase&&M&&P.current!==M&&(P.current=M,D({loadingActions:{}}))},[M,o._fromBase]);const q=H.useRef(""),W=H.useRef(!1),he=H.useRef(null),Ee=H.useRef(null),be=H.useRef({}),Ue=H.useRef({}),Fe=H.useRef(g),Ge=FC(),wt=CC(),J=wt?.getParentDataContext()??g;H.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...se}=e._localInit,ce=JSON.stringify(se),Z=V!==void 0,ve=Vd(),ge=`${ce}:${V||"no-force"}`,we=DC({globalTrackedKey:ve.hash,instanceHandledKey:Ee.current,trackingKey:ge});if(we==="apply"){Ee.current=ge,ve.hash=ge,ve.timestamp=V,q.current=ce,Z&&(W.current=!0);const{_merge:Ke,...Te}=se,$e=Ke||"shallow";D(Re=>$e==="replace"?{loadingActions:Re.loadingActions||{},...Te,hasChanges:!1}:$e==="deep"?Cr(Re,{...Te,hasChanges:!1}):{...Re,...Te,hasChanges:!1}),e._globalSetState&&e._globalSetState(Re=>{const et=Re?._local||{};let je;return $e==="replace"?je={...Te,hasChanges:!1}:$e==="deep"?je=Cr(et,{...Te,hasChanges:!1}):je={...et,...Te,hasChanges:!1},{...Re,_local:je}}),i.invalidateCacheByKeys(["_local"]),st.log("_localInit applied (data changed):",Object.keys(se))}else if(we==="prune"){Ee.current=ge;const{_merge:Ke,...Te}=se;D(Re=>bc(Re,Te)),bc(T,Te)!==T&&(i.invalidateCacheByKeys(["_local"]),st.log("_localInit pruned (applied by another renderer):",Object.keys(Te)))}he.current=e._localInit,RC(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:ue}=Cm(),Me=HC(),te=f??Me,{width:pe}=Kd(),N=z_(),R=H.useMemo(()=>{let V=o;if(o.type==="iterator"&&o.data){const{data:Z,itemName:ve,indexName:ge,...we}=o;V={...we,iteration:{source:Z,item_var:ve||"item",index_var:ge}}}if(!V.responsive)return V;const se=hi.getMatchingKey(V.responsive,pe);if(!se)return V;const ce=V.responsive[se];return{...V,props:{...V.props,...ce.props},children:ce.children??V.children,text:ce.text??V.text,if:ce.if??V.if,iteration:ce.iteration??V.iteration,__responsiveChildrenKey:ce.children!==void 0?se:void 0}},[o,pe]),de=H.useCallback(V=>{const se=V?.__setStateId;if(D(ce=>{const Z=window.__g7PendingLocalState,ge=window.__g7SetLocalOverrideKeys||Z,we=ge?Cr(ce,ge):ce;if(typeof V=="function"){const Re=V(we);return Cr(we,Re)}const{__mergeMode:Ae,__setStateId:Ke,...Te}=V;let $e;if(Ae==="replace"?$e=Te:Ae==="shallow"?$e={...we,...Te}:$e=Cr(we,Te),Ae!==void 0){const Re=window.__g7ForcedLocalFields;Re&&(window.__g7ForcedLocalFields={...Re,...Te})}return $e}),se){const ce=Zr();if(ce?.isEnabled()){const Z=R.id||"unknown",ve=R.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(Z,ve,0,["_local"],[]),ce.completeStateChange?.(se)},0)}}},[R.id,R.name]),fe=d?.state??T,xe=d?.setState??de,ee=H.useMemo(()=>{const V=e._localInit&&e._localInit!==he.current;let se;V&&e._local?se=e._local:se=e._local?Cr(e._local,fe):fe;const ce=window.__g7ForcedLocalFields;ce&&(se=Cr(se,ce));const Z={...e,_local:se},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const ge=new Dn,we={...Z,...Ge?{_isolated:Ge.state}:{}},Ae={},Ke=Zr(),Te=Ke?.isEnabled()??!1;for(const[$e,Re]of Object.entries(ve)){const et=Te?Date.now():0,je=Te?e._computed?.[$e]:void 0;let Ve;try{if(typeof Re=="string")if(Re.startsWith("{{")&&Re.endsWith("}}")){const Se=Re.slice(2,-2).trim(),He=$n(Se)?ge.evaluatePipeExpression(Se,we,{skipCache:!0}):ge.evaluateExpression(Se,we,{skipCache:!0});Ae[$e]=He}else Ae[$e]=Re;else if(Re&&typeof Re=="object"&&"$switch"in Re){const Se=ge.resolveSwitch(Re,we,{skipCache:!0});Ae[$e]=Se}}catch(Se){st.warn(`Failed to recalculate computed value: ${$e}`,Se),Ae[$e]=e._computed?.[$e],Ve=Se instanceof Error?Se.message:String(Se)}if(Te&&(Ve||je!==Ae[$e])){const He=Date.now()-et;Ke.trackComputedProperty?.($e,typeof Re=="string"?Re:JSON.stringify(Re),[{type:"_local",path:"_local",value:Z._local}],Ae[$e],He,R.id,Ve),je!==Ae[$e]&&Ke.trackComputedRecalc?.($e,"dependency-change",je,Ae[$e],He,{type:"_local",path:"_local"},R.id)}}Z._computed=Ae}if(Ge&&(Z._isolated=Ge.state),J&&(Z.$parent=J),o.extensionPointProps){const ge=i.resolveObject(o.extensionPointProps,Z,y?{skipCache:!0}:void 0);Z.extensionPointProps=S&&l?gf(ge,l,n,Z):ge}return o.extensionPointCallbacks&&(Z.extensionPointCallbacks=o.extensionPointCallbacks),S&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,fe,Ge?.state,J,wt?.version,o.extensionPointProps,o.extensionPointCallbacks]);be.current=ee._local,Ue.current=ee._computed||{},Fe.current=J,H.useEffect(()=>{const V=Zr();if(!V?.isEnabled())return;const se=ee._local;se&&V.updateLocalState(se);const ce=ee._computed;ce&&V.updateComputedState(ce),J&&V.updateParentContext?.(J);const Z=R.id||`comp-${Date.now()}`,ve=R.name||"Unknown",ge={global:Object.keys(e._global||{}),local:Object.keys(se||{}),context:d?Object.keys(d.state||{}):[]},we={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(Z,ve,ge,we),fe&&Object.keys(fe).length>0&&V.trackDynamicState?.(Z,fe);const Ae=!!(R.expandChildren||R.props?.expandChildren);V.trackContextFlow?.(Z,ve,!!d,Ae,!0)},[ee._local,e,R.id,R.name,d,fe,R.expandChildren,R.props?.expandChildren,J]);const _e=H.useMemo(()=>({state:{...ee._local},setState:xe,stateRef:be,computedRef:Ue,isolatedContext:Ge,parentDataContext:ee}),[ee._local,xe,T,Ge,ee]),Be=H.useMemo(()=>{const V=ns({if:R.if,condition:R.condition,conditions:R.conditions},ee,i,R.id);if(R.if||R.condition!==void 0||R.conditions){const ce=Zr();ce?.isEnabled()&&R.if&&ce.trackIfCondition(R.id||`if-${Date.now()}`,R.if,V)}return V},[R.if,R.conditions,ee,i,R.id]),ke=H.useMemo(()=>{if(!R.slot)return null;const V=R.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const se=V.slice(2,-2).trim();try{const ce={componentId:R.id,componentName:R.name,propName:"slot"},Z=$n(se)?i.evaluatePipeExpression(se,ee,void 0,ce):i.evaluateExpression(se,ee,ce);return st.log(`[Slot] 표현식 평가: "${se}" => "${Z}" (컴포넌트: ${R.id})`),typeof Z=="string"?Z:null}catch(ce){return st.warn(`slot 표현식 평가 실패 (컴포넌트: ${R.id}):`,ce),null}}return st.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${R.id})`),V},[R.slot,R.id,ee,i]),Ie=H.useMemo(()=>!ke||!R.id?"":`${R.id}-${ke}-${JSON.stringify(R.slotOrder??0)}`,[ke,R.id,R.slotOrder]),Ct=H.useRef(null);H.useEffect(()=>{const V=window.__slotContextValue,se=V?.isEnabled??!1;if(R.slot&&st.log(`[Slot Registration] 컴포넌트: ${R.id}, isSlotEnabled: ${se}, shouldRender: ${Be}, resolvedSlotId: ${ke}`),!se||!Be){R.slot&&st.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${se}, shouldRender: ${Be}`),Ct.current&&R.id&&V&&(V.unregisterFromSlot(Ct.current,R.id),Ct.current=null);return}if(!ke||!R.id){R.slot&&st.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${ke}, id: ${R.id}`),Ct.current&&R.id&&V&&(V.unregisterFromSlot(Ct.current,R.id),Ct.current=null);return}Ct.current&&Ct.current!==ke&&V.unregisterFromSlot(Ct.current,R.id);const ce={...R,slot:void 0,slotOrder:void 0};return V.registerToSlot(ke,R.id,{componentDef:ce,dataContext:e,order:R.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>_e,translationContext:n,registrationKey:Ie}),Ct.current=ke,()=>{const Z=window.__slotContextValue;ke&&R.id&&Z&&Z.unregisterFromSlot(ke,R.id)}},[Be,ke,R,e,f,_e,n,Ie]);const ot=H.useCallback(V=>{if(typeof V=="string"){if(jl(V))return yd(V);if(zl(V)){const se=[],ce=V.replace(new RegExp(`${ao}([^${fi}]*)${fi}`,"g"),(ve,ge)=>(se.push(ge),`${xa}${se.length-1}${xa}`));let Z=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(Z=l.resolveTranslations(ce,n,ee)),Z.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(ve,ge)=>se[parseInt(ge)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const se=V.trim();return se.startsWith("{")&&se.endsWith("}")||se.startsWith("[")&&se.endsWith("]")?V:l.resolveTranslations(V,n,ee)}return V}if(Array.isArray(V))return V.map(se=>ot(se));if(V&&typeof V=="object"){const se={};for(const[ce,Z]of Object.entries(V))se[ce]=ot(Z);return se}return V},[l,n,ee]),Ot=H.useCallback(V=>ro(V),[]),vt=H.useCallback(V=>Aa(V),[]),_t=H.useMemo(()=>{let V={...R.props||{}};const se=["cellChildren","expandChildren","expandContext","render"],Z=a.getMetadata(R.name)?.skipBindingKeys||[],ve=[...new Set([...se,...Z])],ge=y?{skipCache:!0}:void 0,we={...ge??{},skipBindingKeys:ve},Ae=Se=>{if(ge)return ge;if(Se.startsWith("_computed")||Se.startsWith("$computed"))return{skipCache:!0}};for(const[Se,He]of Object.entries(V))if(!ve.includes(Se))if(typeof He=="string"){const tt=vt(He);if(tt!==null){let Tt=!1,It=tt;tt.startsWith(nr)&&(Tt=!0,It=tt.slice(nr.length));const Ln={componentId:R.id,componentName:R.name,propName:Se};let zt;if($n(It))try{zt=i.evaluatePipeExpression(It,ee,Ae(It),Ln)}catch(Ut){st.warn(`파이프 표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${Se}):`,Ut),zt=void 0}else if(Ot(It))try{zt=i.evaluateExpression(It,ee,Ln)}catch(Ut){st.warn(`표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${Se}):`,Ut),zt=void 0}else zt=i.resolve(It,ee,Ae(It),Ln);V[Se]=Tt&&zt!=null?ts(zt):zt}else{const Tt={componentId:R.id,componentName:R.name,propName:Se};V[Se]=i.resolveBindings(He,ee,ge,Tt)}}else Array.isArray(He)?V[Se]=He.map(tt=>typeof tt=="string"?i.resolveBindings(tt,ee,ge):typeof tt=="object"&&tt!==null?i.resolveObject(tt,ee,we):tt):He&&typeof He=="object"&&(V[Se]=i.resolveObject(He,ee,we));for(const[Se,He]of Object.entries(V))V[Se]=ot(He);if(typeof V.style=="string"&&(V.style=B_(V.style)),V=wd(V,S?void 0:R.actions,ee,{componentContext:_e,actionDispatcher:c}),R.classMap){const Se=Cw(R.classMap,ee,i,{skipCache:!0});if(Se){const He=V.className||"";V.className=He?`${He} ${Se}`:Se}}R.style&&(V.style=R.style),R.actions&&R.actions.length>0&&R.type==="composite"&&Object.assign(V,fe),R.component_layout&&(V.__componentLayoutDefs=R.component_layout);const Ke=R.expandChildren||R.props?.expandChildren,Te=R.props?.cellChildren,$e=R.children&&R.children.length>0,Re=R.component_layout,et=R.slot,je=R.props?.modalId,Ve=R.type==="composite";return(Ke||Te||$e||Re||et||je||Ve)&&(V.__componentContext=_e),V},[R.props,R.actions,R.style,R.classMap,R.id,ee,n,i,l,_e,fe,ot,Ot,vt,y]),Oe=H.useRef(null),nt=H.useMemo(()=>Oe.current&&_m(Oe.current,_t)?Oe.current:(Oe.current=_t,_t),[_t]),sn=H.useMemo(()=>{const V=R.id;if(typeof V!="string"||!V.includes("{{"))return V;const se=i.resolveBindings(V,ee,{skipCache:!0});return typeof se=="string"?se:V},[R.id,ee,i]),Mt=H.useMemo(()=>{const V=R.dataKey,se=R.trackChanges,ce=R.debounce;if(V){const Z=V.startsWith("_global."),ve=Z?V.slice(8):V,ge=Z?e._global:ee._local;return{dataKey:ve,trackChanges:se??!1,debounce:ce,setState:Z?Ae=>{e._globalSetState?e._globalSetState(Ae):st.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:xe,state:ge??{},_isGlobal:Z}}if(te.dataKey)return te},[R.dataKey,R.trackChanges,R.debounce,R.id,xe,ee._local,e._global,e._globalSetState,te]),Vt=H.useRef(new Set);H.useEffect(()=>{Vt.current.clear()},[e._global?._remountKeys]);const on=H.useCallback((V,se)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!Vt.current.has(V)?(Vt.current.add(V),`${V}-remount-${ce[V]}`):V||se},[e._global?._remountKeys]),ln=H.useMemo(()=>{if(R.text!==void 0){if(typeof R.text=="string"){const V=R.text;let se=V;const ce={componentId:R.id,componentName:R.name,propName:"text",skipCache:!0},Z=vt(V);if(Z!==null){let ve=!1,ge=Z;if(Z.startsWith(nr)&&(ve=!0,ge=Z.slice(nr.length)),$n(ge))try{se=i.evaluatePipeExpression(ge,ee,{skipCache:!0},ce)}catch(we){st.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${R.id}):`,we),se=""}else if(Ot(ge))try{se=i.evaluateExpression(ge,ee,ce)}catch(we){st.warn(`text 표현식 평가 실패 (컴포넌트: ${R.id}):`,we),se=""}else se=i.resolve(ge,ee,{skipCache:!0},ce);ve&&se!=null&&(se=ts(se))}else V.includes("{{")&&(se=i.resolveBindings(V,ee,{skipCache:!0},ce));return se=ot(se),se??""}return R.text}return!R.children||R.children.length===0?null:R.children.map((V,se)=>{if(typeof V=="string")return V;const ce=R.__responsiveChildrenKey,Z=ce?`responsive.${ce}.children`:"children",ve=O?`${O}.${Z}.${se}`:`${se}`,ge=V._fromBase?V.id||`child-${se}`:on(V.id,`child-${se}`),we=!V._fromBase&&M?`${ge}_${M}`:ge;return gt.jsx(Ur,{componentDef:V,dataContext:ee,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:Mt,isInsideIteration:y,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:ve,onDragStart:A,onDragEnd:x,layoutKey:M},we)})},[R.text,R.children,R.id,e,ee,n,a,i,l,c,_e,Mt,vt,Ot,ot,on,y,S,v,_,O,A,x,M]),Br=H.useMemo(()=>{if(!R.iteration)return null;try{const V=Sd(R.iteration.source,ee,i);if(!Array.isArray(V))return st.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,V),null;const se=Zr();return se?.isEnabled()&&se.trackIteration(R.id||`iteration-${Date.now()}`,R.iteration.source,R.iteration.item_var,R.iteration.index_var,V.length),V.map((ce,Z)=>{const ve={...ee,[R.iteration.item_var]:ce,[`${R.iteration.item_var}_index`]:Z};R.iteration.index_var&&(ve[R.iteration.index_var]=Z);const ge=Z===0||Z===V.length-1;se?.isEnabled()&&ge&&se.trackNestedContext?.({componentId:`${R.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(ee),values:{}},ownContext:{added:[R.iteration.item_var,...R.iteration.index_var?[R.iteration.index_var]:[]],values:{[R.iteration.item_var]:ce,...R.iteration.index_var?{[R.iteration.index_var]:Z}:{}}},depth:1});const we={...R,iteration:void 0,responsive:void 0},Ae=O?`${O}.iteration.${Z}`:`iteration.${Z}`,Ke=`${on(R.id,"item")}-${Z}`;return gt.jsx(Ur,{componentDef:we,dataContext:ve,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:Mt,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:Ae,onDragStart:A,onDragEnd:x,layoutKey:M},Ke)})}catch(V){return st.error(`iteration 렌더링 실패 (컴포넌트: ${R.id}):`,V),null}},[R.iteration,R.children,R.id,e,ee,n,a,i,l,c,_e,Mt,on,S,v,_,O,A,x,M]),[Ft,Ci]=H.useState(0),na=H.useMemo(()=>{if(!R.sortable||!R.itemTemplate)return null;const{sortable:V,itemTemplate:se}=R;try{const ce=Sd(V.source,ee,i);if(!Array.isArray(ce))return st.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,ce),null;if(ce.length===0)return null;const Z=V.itemKey||"id",ve=V.strategy||"verticalList",ge=V.itemVar||"$item",we=V.indexVar||"$index",Ae=V.handle,Ke=V.wrapperElement,Te=(et,je)=>{const Ve=R.actions?.filter(Se=>Se.event==="onSortEnd"||Se.type==="onSortEnd");if(Ci(Se=>Se+1),Ve&&Ve.length>0&&c){const Se={...ee,$sortedItems:et,$sortEvent:je};Ve.forEach(He=>{try{const tt=c.createHandler(He,Se,_e),Tt=new Event("sortend");tt(Tt)}catch(tt){st.error(`onSortEnd action failed: ${He.handler}`,tt)}})}},$e=et=>{const je=R.actions?.filter(Ve=>Ve.event==="onSortStart"||Ve.type==="onSortStart");if(je&&je.length>0&&c){const Ve={...ee,$activeId:et.activeId};je.forEach(Se=>{try{const He=c.createHandler(Se,Ve,_e),tt=new Event("sortstart");He(tt)}catch(He){st.error(`onSortStart action failed: ${Se.handler}`,He)}})}},Re=ce.map((et,je)=>{const Ve=String(et[Z]),Se={...ee,[ge]:et,[we]:je},He=O?`${O}.sortable.${je}`:`sortable.${je}`,tt=`${on(R.id,"sortable-item")}-v${Ft}-${Ve}`;return gt.jsx(U_,{id:Ve,handle:Ae,...Ke?{as:Ke}:{},children:(Ke&&se.children?se.children:[se]).map((Tt,It)=>gt.jsx(Ur,{componentDef:Tt,dataContext:Se,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:He,onDragStart:A,onDragEnd:x,layoutKey:M},`${tt}-child-${It}`))},tt)});return gt.jsx(H_,{items:ce,itemKey:Z,strategy:ve,onSortEnd:Te,onSortStart:$e,sortVersion:Ft,children:Re})}catch(ce){return st.error(`sortable 렌더링 실패 (컴포넌트: ${R.id}):`,ce),null}},[R.sortable,R.itemTemplate,R.actions,R.id,e,ee,n,a,i,l,c,_e,on,S,v,_,O,A,x,Ft,M]),yn=H.useRef(!1);H.useEffect(()=>{if(yn.current)return;yn.current=!0;const V=Zr();if(V?.isEnabled()&&V.trackMount(o.id,{name:o.name,type:o.type||"component",props:nt}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const ce of o.lifecycle.onMount)try{const Z=c.createHandler(ce,ee,_e),ve=new Event("mount");Z(ve),st.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${o.id})`)}catch(Z){st.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${o.id})`,Z)}const se=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const Z of o.onComponentEvent){if(!Z.event){st.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const ve=async we=>{try{const Ae={...ee,_eventData:we},Te=await c.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},Ae,_e)(new CustomEvent(Z.event,{detail:we}));return st.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${o.id})`,{eventData:we,result:Te}),Te}catch(Ae){throw st.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${o.id})`,Ae),Ae}},ge=ce.componentEvent.on(Z.event,ve);se.push(ge),st.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${o.id})`)}else st.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const ce=Zr();ce?.isEnabled()&&ce.trackUnmount(o.id);for(const Z of se)try{Z()}catch(ve){st.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,ve)}if(se.length>0&&st.log(`onComponentEvent: Unsubscribed ${se.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const Z of o.lifecycle.onUnmount)try{const ve=c.createHandler(Z,ee,_e),ge=new Event("unmount");ve(ge),st.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${o.id})`)}catch(ve){st.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${o.id})`,ve)}}},[]);const On=H.useMemo(()=>{const V=nt.dataKey,se=nt.trackChanges,ce=nt.debounce;return V?{dataKey:V,trackChanges:se??!1,debounce:ce,setState:xe,state:fe}:null},[nt.dataKey,nt.trackChanges,nt.debounce,xe,fe]);H.useEffect(()=>{const V=R.dataKey||nt.dataKey;if(!V)return;const se=Zr();if(!se?.isEnabled())return;const ce=[],Z=ge=>{if(ge)for(const we of ge){const Ae=we?.props?.name;if(Ae&&ce.push({name:Ae,type:we.name||we.type||"unknown"}),we?.children&&Z(we.children),we?.slots)for(const Ke of Object.values(we.slots))Array.isArray(Ke)&&Z(Ke)}};if(o.children&&Z(o.children),o.slots)for(const ge of Object.values(o.slots))Array.isArray(ge)&&Z(ge);const ve=o.id||`form-${V}`;return se.trackForm(ve,V,ce),()=>{se.untrackForm(ve)}},[R,nt.dataKey,o.id,o.children]);const rt=H.useRef(null),jn=H.useRef(void 0);H.useEffect(()=>{const V=nt?.name;if(!V||!te.dataKey||!te.setState||nt?.autoBinding===!1)return;const se=`${te.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(se,(ce.get(se)??0)+1),()=>{const Z=ce.get(se)??0;Z<=1?ce.delete(se):ce.set(se,Z-1)}},[nt?.name,nt?.autoBinding,te.dataKey,te.setState]);const bn=H.useMemo(()=>{const{dataKey:V,trackChanges:se,debounce:ce,...Z}=nt,ve=Z.name;if(!ve||!te.dataKey||!te.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ve,...Se}=Z;return Se}const ge=`${te.dataKey}.${ve}`,we=jC(te.state,ge),Ae=we!==void 0?we:Z.value,Te=a.getMetadata(o.name)?.bindingType,$e=typeof Ae=="boolean"&&(Te==="checked"||Te==="checkable"&&["checkbox","radio"].includes(Z?.type)),Re=te.debounce,et=Ve=>{const Se=te.state||{},He=zC(Se,ge,Ve);if(te.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=He,te.setState(He),te._isGlobal)return;const tt=window.G7Core,Tt={[ge]:Ve};te.trackChanges&&(Tt.hasChanges=!0),tt?.state?.setLocal?.(Tt,{render:!1})},je=(Ve,Se)=>{Re&&Re>0?(rt.current&&clearTimeout(rt.current),rt.current=setTimeout(()=>{et(Ve),rt.current=null,Se&&(Se(),window.__g7PendingLocalState=null)},Re)):(et(Ve),Se&&(Se(),window.__g7PendingLocalState=null))};if($e)return{...Z,checked:Ae,onChange:Se=>{const He=Se.target.checked;et(He),Z.onChange&&Z.onChange(Se)}};{const Ve=He=>{const tt=He?.target?.value!==void 0?He.target.value:He;Re&&Re>0&&(jn.current=tt);const Tt=He?.target?{target:{value:tt,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:tt,name:He.currentTarget.name}:void 0}:He;je(tt,()=>{Z.onChange&&Z.onChange(Tt)})};let Se;return jn.current!==void 0?rt.current!==null?Se=jn.current:String(Ae??"")===String(jn.current)?(jn.current=void 0,Se=Ae??""):Se=jn.current:Se=Ae??"",{...Z,value:Se,onChange:Ve}}},[nt,te,te.state,te.debounce]),ra=H.useMemo(()=>{const V=Zr();if(V?.isEnabled()&&V.trackRender(o.name),!Be)return R.iteration?Br:null;if(R.sortable&&R.itemTemplate)return na;if(R.iteration)return Br;if(R.type==="extension_point"){const{layout:Te,columns:$e,gap:Re,className:et,...je}=R.props||{};let Ve=et||"";return Te==="grid"&&$e?Ve=`${Ve} grid grid-cols-${$e} gap-${Re||4}`.trim():Te==="flex"&&(Ve=`${Ve} flex flex-col gap-${Re||4}`.trim()),gt.jsx("div",{id:sn,className:Ve||void 0,...je,children:ln})}const se=a.getComponent(R.name);if(!se)return st.error(`컴포넌트를 찾을 수 없습니다: ${R.name} (ID: ${R.id})`,"componentDef:",JSON.stringify(R,null,2)),null;const ce=e._global?._remountKeys,Z={...bn,id:bn.id??sn,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(N?.listeners&&N.handle&&bn["data-drag-handle"]!==void 0&&(Object.assign(Z,N.listeners),Z.style={...Z.style,cursor:N.isDragging?"grabbing":"grab"}),S){const Te=R.id||`auto_${R.name||R.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,$e=je=>{typeof je.preventDefault=="function"&&je.preventDefault(),v&&(je.stopPropagation(),v(Te,je))},Re={"data-editor-id":Te,"data-editor-name":R.name,"data-editor-type":R.type,onClick:$e};O&&(Re["data-editor-path"]=O);const et=R.__editorSlotName??R.slot;typeof et=="string"&&(Re["data-editor-slot"]=et),_&&(Re.onMouseMove=je=>{je.stopPropagation(),_(Te,je)},Re.onMouseLeave=je=>{_(null,je)}),Object.assign(Z,Re),Z.editorAttrs=Re}const ve=R.type==="basic",ge=R.type==="layout",Ae=ve||ge?(()=>{const Te={};for(const[$e,Re]of Object.entries(Z))$e.startsWith("__")||$e==="editorAttrs"&&ve||(Te[$e]=Re);return Te})():Z;let Ke=gt.jsx(se,{...Ae,children:ln});if(Mt&&(Ke=gt.jsx(IC,{value:Mt,children:Ke})),R.isolatedState){const Te=typeof R.isolatedState=="object"?R.isolatedState:{},$e=e?._isolatedInit,Re=$e?{...Te,...$e}:Te;Ke=gt.jsx(VC,{initialState:Re,scopeId:R.isolatedScopeId,children:Ke})}return Ke},[Be,R.iteration,R.sortable,R.itemTemplate,R.type,R.name,R.id,R.props,R.isolatedState,R.isolatedScopeId,a,bn,ln,Br,na,N,On,S,v,_,A,x,O,e._global?._remountKeys]),sr=H.useMemo(()=>{const V=R.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const Z=vt(V);if(Z!==null)try{const ve={componentId:R.id,componentName:R.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,ee,ve)}catch(ve){return st.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${R.id}):`,ve),!1}return!1}if(typeof V=="object"&&V!==null){if(!V.enabled)return!1;if(V.data_sources)return(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).some(we=>e[we]===void 0);if(ue)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ge=>!Z.includes(ge)&&!ge.startsWith("_")).some(ge=>e[ge]===void 0)}if(ue)return!0;const se=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!se.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[R.blur_until_loaded,R.id,ue,e,ee,i,vt]);if(sr){const V=R.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const ce=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((ve,ge)=>(ve[ge]=e[ge]===void 0?"UNDEFINED":"LOADED",ve),{}),Z=Object.keys(e).filter(ve=>!ve.startsWith("_"));st.log(`[BLUR APPLIED] Component: ${R.id}, data_sources status:`,ce,"Available keys:",Z)}else st.log(`[BLUR APPLIED] Component: ${R.id}, blur_until_loaded:`,V)}const cn=H.useMemo(()=>{if(!R.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=_t?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const se=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],ce=V.split(/\s+/).filter(Boolean),Z=[],ve=[];for(const ge of ce)se.some(Ae=>Ae.test(ge))?Z.push(ge):ve.push(ge);return{wrapperClasses:Z.join(" "),innerClasses:ve.join(" ")}},[R.blur_until_loaded,_t?.className]),Tn=window.__slotContextValue;return ke&&Tn?.isEnabled?null:gt.jsx(q_,{componentId:o.id,componentName:o.name,children:R.blur_until_loaded?gt.jsx("div",{className:[cn.wrapperClasses,sr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:ra}):ra})});Ur.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Ur);function G_(o){const e={};try{const a=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of a.keys()){if(i.has(l))continue;i.add(l);const c=a.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function V_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const wi=class wi{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return wi.instance||(wi.instance=new wi),wi.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const n={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const a=this.findMismatchedLeafPaths(e,n);return{hasMismatch:a.length>0,mismatchedPaths:a,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,a=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=a?`${a}.${c}`:c,f=e?.[c],g=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=g&&typeof g=="object"&&!Array.isArray(g);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const S=f===void 0?"__undefined__":JSON.stringify(f),v=g===void 0?"__undefined__":JSON.stringify(g);S!==v&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(a=>{try{a(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const a=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,n,a=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=a?`${a}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=a?`${a}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(a=>a.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),a={};for(const l of this.actionHistory)a[l.type]=(a[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const n={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(n),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let n=0,a=0,i=0,l=0;const c={},d={};for(const g of e)g.decision==="cache_hit"?n++:g.decision==="cache_miss"?a++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,c[g.reason]=(c[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=n+a+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:a,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let a=[...this.cacheDecisions];return n&&(a=a.filter(i=>i.decision===n)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},a=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!a.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?n[i]=`{${c.join(", ")}}`:n[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const a=this.summarizePropsForLifecycle(n.props),i={...n,props:a,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(l=>l.type===n);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,a]of this.eventListeners)this.mountedComponents.has(n)||e.push(...a.map(i=>({...i,componentId:n})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(g=>g.type==="render"),a=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of n)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const c=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,S)=>y+S,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of a)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:a.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,a){if(!this.config.enabled)return"";const i=this.generateId(),l=V_(e),c=G_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,a){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(a)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:n,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,n,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,a,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:a,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,n,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==a&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:a,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],a=this.getState();return n.push({name:"_global",value:a._global,source:"global"}),n.push({name:"_local",value:a._local,source:"local"}),n.push({name:"_computed",value:a._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,n,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:a,trackedAt:Date.now()})}trackFormChange(e,n,a){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:a,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,n,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,a,i){const l=a.map(f=>{const g=[];let m=!0;return f.name||(g.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(g.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:g}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const c={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=c:this.formBindingValidations.push(c),c}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const a=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:n,topIssues:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,g={id:f,name:e,expression:n,componentId:c,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(a)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:g,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(f);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=l)}analyzeComputedDependencyChain(e,n){const a=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),a.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};a.add(m),i.push(m);const S=this.computedProperties.get(`computed-${m}-${n||"global"}`),v=[];if(S)for(const _ of S.dependencies)_.type==="computed"?v.push(f(_.path,y+1)):v.push({name:_.path,type:_.type,children:[],depth:y+1});return i.pop(),a.delete(m),{name:m,type:"computed",children:v,depth:y}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),a=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},a={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,n[g.computedName]=(n[g.computedName]||0)+1,a[g.computedName]||(a[g.computedName]=[]),a[g.computedName].push(g.computationTime),i+=g.computationTime;const c=Object.entries(n).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(a).map(([g,m])=>({name:g,avgTime:m.reduce((y,S)=>y+S,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:c,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,n),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,n){if(!this.config.enabled)return;const a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),n&&(a.currentState={...n}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,n){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const a=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const a=e.initialState[n],i=e.currentState[n];if(a!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:a})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},a={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,a[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(n)}detectExpressionWarning(e){const{expression:n,result:a,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(a);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(a).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(g=>g.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(c&&c>10)return{type:"slow-evaluation",message:`표현식 평가에 ${c.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(a=>a.expression.toLowerCase().includes(n)||a.componentName?.toLowerCase().includes(n)||a.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),a=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),c={};for(const f of e)c[f.resultType]=(c[f.resultType]||0)+1;const d={};for(const f of a)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,0)/l.length:0,byType:c,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],n)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,n){if(!n)return e;const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const n=[...this.stateHistory].reverse().find(a=>a.timestamp<=e);if(n)return{_global:n.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,n,a){if(!this.config.enabled)return;const i=a.map(c=>{if(typeof c=="string")return c;try{return JSON.stringify(c)}catch{return String(c)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(a),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(a=>a.handler.includes(e.handler))),e?.status&&(n=n.filter(a=>a.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(a=>a.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(n=n.filter(a=>a.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)a[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:a,byPrefix:i,recentErrors:l,recentWarnings:c}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=a;n&&(Array.isArray(n)?(l=n.length,c=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,c=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,c=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):c=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"error",error:n,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let n=this.dataPathTransforms.find(a=>a.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let a=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,a+=c.warnings.length;for(const d of c.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([c,d])=>({warning:c,count:d})).sort((c,d)=>d.count-c.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:a,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,a=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:a,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const a=this.nestedContexts.find(i=>i.id===e);a&&a.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let a=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>a&&(a=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const c=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:a,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),a=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,a,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:a,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(c),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((n,a)=>n+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,n,a,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const c={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(a),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(c),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,a,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:a,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=n.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),a={};for(const[i,l]of this.stateToComponentMap)a[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),a=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),c=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:a,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:a,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,a,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:a,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),c){const f=this.contextFlowNodes.get(c);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),a=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const c=Object.keys(e);return`{${c.slice(0,5).join(", ")}${c.length>5?`, ... +${c.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(c=>this.summarizeValues(c,n,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,a+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[l,c]of this.dynamicStates)c&&Object.keys(c).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:c,priority:2});const i=this.computeEffectiveState(a._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,a]of this.dynamicStates)a._local&&Object.assign(n,a._local);return n}detectStateConflicts(e){const n=[],a=e.find(l=>l.type==="global"&&l.path==="_local");if(!a)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const c=l.values._local||l.values;for(const[d,f]of Object.entries(c)){const g=a.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],y=[];for(const S of this.componentStateSources.values())S.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(S.stateProvider.type==="dynamicState"?m.push(S.componentName):S.stateProvider.type==="globalState"&&y.push(S.componentName));n.push({path:`_local.${d}`,globalValue:g,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)n.delete(i.componentId);for(const a of n){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,n,a,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(a),c={componentId:e,componentName:n,classes:a,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],a=[],i=[],l=[],c=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const g of c)if(f.startsWith(g)){a.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:a,computedStyles:i,tailwindAnalysis:l}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:n,componentName:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const c=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));c.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:a,property:"background-color",currentValue:c.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${c[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:a,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,a,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:a,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,a,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:a,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(c),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=n?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=a?.getUser?.();if(d&&(c="AuthManager"),!d){const v=e?.state?.get?.();d=v?._global?.user||v?._global?.currentUser||v?.user||v?.currentUser,d&&(c="G7Core.state")}const f=a?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="sessionStorage");const m=!!i&&(!!d||f);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const S=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.guard_name}),permissions:d.permissions?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:S,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,accessTokenPreview:y},lastActivity:Date.now(),source:c}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,a,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(a),loadedAt:l,version:a.version,layoutName:a.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:a.version};this.layoutHistory.push(c),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const n=`exec_${++this.executionIdCounter}_${Date.now()}`,a={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,a),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(c=>this.executionDetails.delete(c))}return n}endHandlerExecution(e,n,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=a,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${a||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=a,l.exitDescription=i)}recordStateChange(e,n,a,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:a,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(c)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),c.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,a,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:a,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(c)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,a){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of a.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of a.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const a={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const a=this.getValueType(e),i=this.getValueType(n),l=a!==i;let c=!1,d;return!l&&(a==="object"||a==="array")?(c=this.deepEqual(e,n),!c&&a==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:a,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const a=Object.keys(e),i=Object.keys(n);if(a.length!==i.length)return!1;for(const l of a)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const a=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||a.push(l);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:n,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const n of this.changeAlerts)e[n.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,n){let a=[...this.changeAlerts];return n&&(a=a.filter(i=>i.severity===n)),a.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,a={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),n}captureSequenceActionBefore(e,n,a,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:a,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};c.actions.push(d)}captureSequenceActionAfter(e,n,a,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(c=>c.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(a,1)}computeStateDiff(e,n){const a=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||a.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const g=e[f],m=n[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:a,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,a=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),c=n>0?e.reduce((g,m)=>g+m.totalDuration,0)/n:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:n,successCount:a,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,a){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(a[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,a,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[g,m]of c){const y=this.getValueByPath(a,g),S=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&S>0){const v=this.createStaleClosureWarning(i,n,g,m.value,m.capturedAt,y,d,S,l);f.push(v),this.addStaleClosureWarning(v)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,n,a,i,l,c,d,f,g,m){const y=this.getStaleClosureSeverity(e,f),{description:S,suggestion:v,docLink:_}=this.getStaleClosureMessages(e,a,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:a,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:S,suggestion:v,docLink:_,actionId:g,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,n,a){const i=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const a={info:0,warning:0,error:0};for(const f of e)a[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:a,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let a=[...this.staleClosureWarnings];return n&&(a=a.filter(i=>i.severity===n)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const n={};for(const a of Object.keys(e))try{n[a]=JSON.parse(JSON.stringify(e[a]))}catch{n[a]="[Unserializable]"}return n}}};$(wi,"instance");let Oa=wi;const Kn=ht("LayoutLoader");class Er extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="LayoutLoaderError"}}class pf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Kn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const a=`${e}:${n}`;if(this.layoutCache.has(a)){Kn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(a),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Oa.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(a,i),i.catch(()=>{this.layoutCache.get(a)===i&&this.layoutCache.delete(a)}),i}async fetchLayout(e,n,a=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const S=n.replace("__preview__/","");l=Nr(`/api/layouts/preview/${S}`,"json",i)}else l=Nr(`/api/layouts/${e}/${n}`,"json",i);Kn.log("Fetching layout from API:",l);const c=Hr(),d=a?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await Il(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!a&&d){Kn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(v){throw v instanceof Er&&v.details?.status===401?new Er(v.message,v.code,{...v.details,hadToken:!0}):v}}const S=m?.message||m?.error;throw new Er(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:S})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,Oa.getInstance().trackLayoutLoad(n,e,y,"api"),Kn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Er?i:new Er("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Er("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Er("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Er('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Kn.log("Layout data validation passed")}renderLayout(e,n){try{const a=n||this.currentLayout;if(!a)throw new Er("No layout data to render","NO_LAYOUT_DATA");Kn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Kn.log("Layout rendered successfully")}catch(a){Kn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,n){for(const a of n){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Kn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(n){return Kn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=` + `},iE={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function sE(o){let{announcements:e=iE,container:n,hiddenTextDescribedById:a,screenReaderInstructions:i=aE}=o;const{announce:l,announcement:c}=tE(),d=Co("DndLiveRegion"),[f,g]=H.useState(!1);if(H.useEffect(()=>{g(!0)},[]),nE(H.useMemo(()=>({onDragStart(y){let{active:S}=y;l(e.onDragStart({active:S}))},onDragMove(y){let{active:S,over:v}=y;e.onDragMove&&l(e.onDragMove({active:S,over:v}))},onDragOver(y){let{active:S,over:v}=y;l(e.onDragOver({active:S,over:v}))},onDragEnd(y){let{active:S,over:v}=y;l(e.onDragEnd({active:S,over:v}))},onDragCancel(y){let{active:S,over:v}=y;l(e.onDragCancel({active:S,over:v}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(ZC,{id:a,value:i.draggable}),Xe.createElement(eE,{id:d,announcement:c}));return n?ka.createPortal(m,n):m}var an;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(an||(an={}));function lc(){}function Om(o,e){return H.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function oE(){for(var o=arguments.length,e=new Array(o),n=0;n[...e].filter(a=>a!=null),[...e])}const wr=Object.freeze({x:0,y:0});function Lm(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function Mm(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return n-a}function lE(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return a-n}function $m(o){let{left:e,top:n,height:a,width:i}=o;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+a},{x:e+i,y:n+a}]}function Nm(o,e){if(!o||o.length===0)return null;const[n]=o;return n[e]}function Im(o,e,n){return e===void 0&&(e=o.left),n===void 0&&(n=o.top),{x:e+o.width*.5,y:n+o.height*.5}}const cE=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=Im(e,e.left,e.top),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=Lm(Im(f),i);l.push({id:d,data:{droppableContainer:c,value:g}})}}return l.sort(Mm)},uE=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=$m(e),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=$m(f),m=i.reduce((S,v,_)=>S+Lm(g[_],v),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(Mm)};function dE(o,e){const n=Math.max(e.top,o.top),a=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),c=i-a,d=l-n;if(a{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=[];for(const l of a){const{id:c}=l,d=n.get(c);if(d){const f=dE(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(lE)};function hE(o,e,n){return{...o,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Hm(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:wr}function gE(o){return function(n){for(var a=arguments.length,i=new Array(a>1?a-1:0),l=1;l({...c,top:c.top+o*d.y,bottom:c.bottom+o*d.y,left:c.left+o*d.x,right:c.right+o*d.x}),{...n})}}const pE=gE(1);function mE(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function yE(o,e,n){const a=mE(e);if(!a)return o;const{scaleX:i,scaleY:l,x:c,y:d}=a,f=o.left-c-(1-i)*parseFloat(n),g=o.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?o.width/i:o.width,y=l?o.height/l:o.height;return{width:m,height:y,top:g,right:f+m,bottom:g+y,left:f}}const bE={ignoreTransform:!1};function gs(o,e){e===void 0&&(e=bE);let n=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=Nn(o).getComputedStyle(o);g&&(n=yE(n,g,m))}const{top:a,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:a,left:i,width:l,height:c,bottom:d,right:f}}function jm(o){return gs(o,{ignoreTransform:!0})}function vE(o){const e=o.innerWidth,n=o.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function SE(o,e){return e===void 0&&(e=Nn(o).getComputedStyle(o)),e.position==="fixed"}function wE(o,e){e===void 0&&(e=Nn(o).getComputedStyle(o));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function cc(o,e){const n=[];function a(i){if(e!=null&&n.length>=e||!i)return n;if(Xd(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!vo(i)||Tm(i)||n.includes(i))return n;const l=Nn(o).getComputedStyle(i);return i!==o&&wE(i,l)&&n.push(i),SE(i,l)?n:a(i.parentNode)}return o?a(o):n}function zm(o){const[e]=cc(o,1);return e??null}function nf(o){return!sc||!o?null:ds(o)?o:Yd(o)?Xd(o)||o===fs(o).scrollingElement?window:vo(o)?o:null:null}function Um(o){return ds(o)?o.scrollX:o.scrollLeft}function Pm(o){return ds(o)?o.scrollY:o.scrollTop}function rf(o){return{x:Um(o),y:Pm(o)}}var gn;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(gn||(gn={}));function Bm(o){return!sc||!o?!1:o===document.scrollingElement}function qm(o){const e={x:0,y:0},n=Bm(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},a={x:o.scrollWidth-n.width,y:o.scrollHeight-n.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,c=o.scrollTop>=a.y,d=o.scrollLeft>=a.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:a,minScroll:e}}const CE={x:.2,y:.2};function EE(o,e,n,a,i){let{top:l,left:c,right:d,bottom:f}=n;a===void 0&&(a=10),i===void 0&&(i=CE);const{isTop:g,isBottom:m,isLeft:y,isRight:S}=qm(o),v={x:0,y:0},_={x:0,y:0},A={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+A.height?(v.y=gn.Backward,_.y=a*Math.abs((e.top+A.height-l)/A.height)):!m&&f>=e.bottom-A.height&&(v.y=gn.Forward,_.y=a*Math.abs((e.bottom-A.height-f)/A.height)),!S&&d>=e.right-A.width?(v.x=gn.Forward,_.x=a*Math.abs((e.right-A.width-d)/A.width)):!y&&c<=e.left+A.width&&(v.x=gn.Backward,_.x=a*Math.abs((e.left+A.width-c)/A.width)),{direction:v,speed:_}}function _E(o){if(o===document.scrollingElement){const{innerWidth:l,innerHeight:c}=window;return{top:0,left:0,right:l,bottom:c,width:l,height:c}}const{top:e,left:n,right:a,bottom:i}=o.getBoundingClientRect();return{top:e,left:n,right:a,bottom:i,width:o.clientWidth,height:o.clientHeight}}function Gm(o){return o.reduce((e,n)=>hs(e,rf(n)),wr)}function AE(o){return o.reduce((e,n)=>e+Um(n),0)}function xE(o){return o.reduce((e,n)=>e+Pm(n),0)}function TE(o,e){if(e===void 0&&(e=gs),!o)return;const{top:n,left:a,bottom:i,right:l}=e(o);zm(o)&&(i<=0||l<=0||n>=window.innerHeight||a>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const RE=[["x",["left","right"],AE],["y",["top","bottom"],xE]];class af{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const a=cc(n),i=Gm(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of RE)for(const f of c)Object.defineProperty(this,f,{get:()=>{const g=d(a),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ao{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...n)})},this.target=e}add(e,n,a){var i;(i=this.target)==null||i.addEventListener(e,n,a),this.listeners.push([e,n,a])}}function kE(o){const{EventTarget:e}=Nn(o);return o instanceof e?o:fs(o)}function sf(o,e){const n=Math.abs(o.x),a=Math.abs(o.y);return typeof e=="number"?Math.sqrt(n**2+a**2)>e:"x"in e&&"y"in e?n>e.x&&a>e.y:"x"in e?n>e.x:"y"in e?a>e.y:!1}var ar;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(ar||(ar={}));function Vm(o){o.preventDefault()}function DE(o){o.stopPropagation()}var ut;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(ut||(ut={}));const Fm={start:[ut.Space,ut.Enter],cancel:[ut.Esc],end:[ut.Space,ut.Enter,ut.Tab]},OE=(o,e)=>{let{currentCoordinates:n}=e;switch(o.code){case ut.Right:return{...n,x:n.x+25};case ut.Left:return{...n,x:n.x-25};case ut.Down:return{...n,y:n.y+25};case ut.Up:return{...n,y:n.y-25}}};class of{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new Ao(fs(n)),this.windowListeners=new Ao(Nn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ar.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,a=e.node.current;a&&TE(a),n(wr)}handleKeyDown(e){if(ef(e)){const{active:n,context:a,options:i}=this.props,{keyboardCodes:l=Fm,coordinateGetter:c=OE,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:g}=a.current,m=g?{x:g.left,y:g.top}:wr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:a.current,currentCoordinates:m});if(y){const S=Eo(y,m),v={x:0,y:0},{scrollableAncestors:_}=a.current;for(const A of _){const x=e.code,{isTop:O,isRight:M,isLeft:T,isBottom:D,maxScroll:z,minScroll:P}=qm(A),q=_E(A),W={x:Math.min(x===ut.Right?q.right-q.width/2:q.right,Math.max(x===ut.Right?q.left:q.left+q.width/2,y.x)),y:Math.min(x===ut.Down?q.bottom-q.height/2:q.bottom,Math.max(x===ut.Down?q.top:q.top+q.height/2,y.y))},he=x===ut.Right&&!M||x===ut.Left&&!T,Ee=x===ut.Down&&!D||x===ut.Up&&!O;if(he&&W.x!==y.x){const be=A.scrollLeft+S.x,Ue=x===ut.Right&&be<=z.x||x===ut.Left&&be>=P.x;if(Ue&&!S.y){A.scrollTo({left:be,behavior:d});return}Ue?v.x=A.scrollLeft-be:v.x=x===ut.Right?A.scrollLeft-z.x:A.scrollLeft-P.x,v.x&&A.scrollBy({left:-v.x,behavior:d});break}else if(Ee&&W.y!==y.y){const be=A.scrollTop+S.y,Ue=x===ut.Down&&be<=z.y||x===ut.Up&&be>=P.y;if(Ue&&!S.x){A.scrollTo({top:be,behavior:d});return}Ue?v.y=A.scrollTop-be:v.y=x===ut.Down?A.scrollTop-z.y:A.scrollTop-P.y,v.y&&A.scrollBy({top:-v.y,behavior:d});break}}this.handleMove(e,hs(Eo(y,this.referenceCoordinates),v))}}}handleMove(e,n){const{onMove:a}=this.props;e.preventDefault(),a(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}of.activators=[{eventName:"onKeyDown",handler:(o,e,n)=>{let{keyboardCodes:a=Fm,onActivation:i}=e,{active:l}=n;const{code:c}=o.nativeEvent;if(a.start.includes(c)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function Km(o){return!!(o&&"distance"in o)}function Wm(o){return!!(o&&"delay"in o)}class lf{constructor(e,n,a){var i;a===void 0&&(a=kE(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:l}=e,{target:c}=l;this.props=e,this.events=n,this.document=fs(c),this.documentListeners=new Ao(this.document),this.listeners=new Ao(a),this.windowListeners=new Ao(Nn(c)),this.initialCoordinates=(i=tf(l))!=null?i:wr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.DragStart,Vm),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),this.windowListeners.add(ar.ContextMenu,Vm),this.documentListeners.add(ar.Keydown,this.handleKeydown),n){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Wm(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Km(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ar.Click,DE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ar.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:a,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=tf(e))!=null?n:wr,g=Eo(i,f);if(!a&&d){if(Km(d)){if(d.tolerance!=null&&sf(g,d.tolerance))return this.handleCancel();if(sf(g,d.distance))return this.handleStart()}if(Wm(d)&&sf(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===ut.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const LE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class cf extends lf{constructor(e){const{event:n}=e,a=fs(n.target);super(e,LE,a)}}cf.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return!n.isPrimary||n.button!==0?!1:(a?.({event:n}),!0)}}];const ME={move:{name:"mousemove"},end:{name:"mouseup"}};var uf;(function(o){o[o.RightClick=2]="RightClick"})(uf||(uf={}));class $E extends lf{constructor(e){super(e,ME,fs(e.event.target))}}$E.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return n.button===uf.RightClick?!1:(a?.({event:n}),!0)}}];const df={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class NE extends lf{constructor(e){super(e,df)}static setup(){return window.addEventListener(df.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(df.move.name,e)};function e(){}}}NE.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;const{touches:i}=n;return i.length>1?!1:(a?.({event:n}),!0)}}];var xo;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(xo||(xo={}));var uc;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(uc||(uc={}));function IE(o){let{acceleration:e,activator:n=xo.Pointer,canScroll:a,draggingRect:i,enabled:l,interval:c=5,order:d=uc.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:y,threshold:S}=o;const v=jE({delta:y,disabled:!l}),[_,A]=WC(),x=H.useRef({x:0,y:0}),O=H.useRef({x:0,y:0}),M=H.useMemo(()=>{switch(n){case xo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case xo.DraggableRect:return i}},[n,i,f]),T=H.useRef(null),D=H.useCallback(()=>{const P=T.current;if(!P)return;const q=x.current.x*O.current.x,W=x.current.y*O.current.y;P.scrollBy(q,W)},[]),z=H.useMemo(()=>d===uc.TreeOrder?[...g].reverse():g,[d,g]);H.useEffect(()=>{if(!l||!g.length||!M){A();return}for(const P of z){if(a?.(P)===!1)continue;const q=g.indexOf(P),W=m[q];if(!W)continue;const{direction:he,speed:Ee}=EE(P,W,M,e,S);for(const be of["x","y"])v[be][he[be]]||(Ee[be]=0,he[be]=0);if(Ee.x>0||Ee.y>0){A(),T.current=P,_(D,c),x.current=Ee,O.current=he;return}}x.current={x:0,y:0},O.current={x:0,y:0},A()},[e,D,a,A,l,c,JSON.stringify(M),JSON.stringify(v),_,g,z,m,JSON.stringify(S)])}const HE={x:{[gn.Backward]:!1,[gn.Forward]:!1},y:{[gn.Backward]:!1,[gn.Forward]:!1}};function jE(o){let{delta:e,disabled:n}=o;const a=Qd(e);return wo(i=>{if(n||!a||!i)return HE;const l={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[gn.Backward]:i.x[gn.Backward]||l.x===-1,[gn.Forward]:i.x[gn.Forward]||l.x===1},y:{[gn.Backward]:i.y[gn.Backward]||l.y===-1,[gn.Forward]:i.y[gn.Forward]||l.y===1}}},[n,e,a])}function zE(o,e){const n=e!=null?o.get(e):void 0,a=n?n.node.current:null;return wo(i=>{var l;return e==null?null:(l=a??i)!=null?l:null},[a,e])}function UE(o,e){return H.useMemo(()=>o.reduce((n,a)=>{const{sensor:i}=a,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,a)}));return[...n,...l]},[]),[o,e])}var To;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(To||(To={}));var ff;(function(o){o.Optimized="optimized"})(ff||(ff={}));const Ym=new Map;function PE(o,e){let{dragging:n,dependencies:a,config:i}=e;const[l,c]=H.useState(null),{frequency:d,measure:f,strategy:g}=i,m=H.useRef(o),y=x(),S=So(y),v=H.useCallback(function(O){O===void 0&&(O=[]),!S.current&&c(M=>M===null?O:M.concat(O.filter(T=>!M.includes(T))))},[S]),_=H.useRef(null),A=wo(O=>{if(y&&!n)return Ym;if(!O||O===Ym||m.current!==o||l!=null){const M=new Map;for(let T of o){if(!T)continue;if(l&&l.length>0&&!l.includes(T.id)&&T.rect.current){M.set(T.id,T.rect.current);continue}const D=T.node.current,z=D?new af(f(D),D):null;T.rect.current=z,z&&M.set(T.id,z)}return M}return O},[o,l,n,y,f]);return H.useEffect(()=>{m.current=o},[o]),H.useEffect(()=>{y||v()},[n,y]),H.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),H.useEffect(()=>{y||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{v(),_.current=null},d))},[d,y,v,...a]),{droppableRects:A,measureDroppableContainers:v,measuringScheduled:l!=null};function x(){switch(g){case To.Always:return!1;case To.BeforeDragging:return n;default:return!n}}}function Xm(o,e){return wo(n=>o?n||(typeof e=="function"?e(o):o):null,[e,o])}function BE(o,e){return Xm(o,e)}function qE(o){let{callback:e,disabled:n}=o;const a=Jd(e),i=H.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(a)},[a,n]);return H.useEffect(()=>()=>i?.disconnect(),[i]),i}function dc(o){let{callback:e,disabled:n}=o;const a=Jd(e),i=H.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(a)},[n]);return H.useEffect(()=>()=>i?.disconnect(),[i]),i}function GE(o){return new af(gs(o),o)}function Jm(o,e,n){e===void 0&&(e=GE);const[a,i]=H.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??n)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=qE({callback(f){if(o)for(const g of f){const{type:m,target:y}=g;if(m==="childList"&&y instanceof HTMLElement&&y.contains(o)){l();break}}}}),d=dc({callback:l});return zr(()=>{l(),o?(d?.observe(o),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[o]),a}function VE(o){const e=Xm(o);return Hm(o,e)}const Qm=[];function FE(o){const e=H.useRef(o),n=wo(a=>o?a&&a!==Qm&&o&&e.current&&o.parentNode===e.current.parentNode?a:cc(o):Qm,[o]);return H.useEffect(()=>{e.current=o},[o]),n}function KE(o){const[e,n]=H.useState(null),a=H.useRef(o),i=H.useCallback(l=>{const c=nf(l.target);c&&n(d=>d?(d.set(c,rf(c)),new Map(d)):null)},[]);return H.useEffect(()=>{const l=a.current;if(o!==l){c(l);const d=o.map(f=>{const g=nf(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,rf(g)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),a.current=o}return()=>{c(o),c(l)};function c(d){d.forEach(f=>{const g=nf(f);g?.removeEventListener("scroll",i)})}},[i,o]),H.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,c)=>hs(l,c),wr):Gm(o):wr,[o,e])}function Zm(o,e){e===void 0&&(e=[]);const n=H.useRef(null);return H.useEffect(()=>{n.current=null},e),H.useEffect(()=>{const a=o!==wr;a&&!n.current&&(n.current=o),!a&&n.current&&(n.current=null)},[o]),n.current?Eo(o,n.current):wr}function WE(o){H.useEffect(()=>{if(!sc)return;const e=o.map(n=>{let{sensor:a}=n;return a.setup==null?void 0:a.setup()});return()=>{for(const n of e)n?.()}},o.map(e=>{let{sensor:n}=e;return n}))}function YE(o,e){return H.useMemo(()=>o.reduce((n,a)=>{let{eventName:i,handler:l}=a;return n[i]=c=>{l(c,e)},n},{}),[o,e])}function ey(o){return H.useMemo(()=>o?vE(o):null,[o])}const ty=[];function XE(o,e){e===void 0&&(e=gs);const[n]=o,a=ey(n?Nn(n):null),[i,l]=H.useState(ty);function c(){l(()=>o.length?o.map(f=>Bm(f)?a:new af(e(f),f)):ty)}const d=dc({callback:c});return zr(()=>{d?.disconnect(),c(),o.forEach(f=>d?.observe(f))},[o]),i}function JE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return vo(e)?e:o}function QE(o){let{measure:e}=o;const[n,a]=H.useState(null),i=H.useCallback(g=>{for(const{target:m}of g)if(vo(m)){a(y=>{const S=e(m);return y?{...y,width:S.width,height:S.height}:S});break}},[e]),l=dc({callback:i}),c=H.useCallback(g=>{const m=JE(g);l?.disconnect(),m&&l?.observe(m),a(m?e(m):null)},[e,l]),[d,f]=oc(c);return H.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const ZE=[{sensor:cf,options:{}},{sensor:of,options:{}}],e_={current:{}},fc={draggable:{measure:jm},droppable:{measure:jm,strategy:To.WhileDragging,frequency:ff.Optimized},dragOverlay:{measure:gs}};class Ro extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,a;return(n=(a=this.get(e))==null?void 0:a.node.current)!=null?n:void 0}}const t_={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ro,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:lc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:fc,measureDroppableContainers:lc,windowRect:null,measuringScheduled:!1},n_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:lc,draggableNodes:new Map,over:null,measureDroppableContainers:lc},hc=H.createContext(n_),ny=H.createContext(t_);function r_(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ro}}}function a_(o,e){switch(e.type){case an.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case an.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case an.DragEnd:case an.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case an.RegisterDroppable:{const{element:n}=e,{id:a}=n,i=new Ro(o.droppable.containers);return i.set(a,n),{...o,droppable:{...o.droppable,containers:i}}}case an.SetDroppableDisabled:{const{id:n,key:a,disabled:i}=e,l=o.droppable.containers.get(n);if(!l||a!==l.key)return o;const c=new Ro(o.droppable.containers);return c.set(n,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:c}}}case an.UnregisterDroppable:{const{id:n,key:a}=e,i=o.droppable.containers.get(n);if(!i||a!==i.key)return o;const l=new Ro(o.droppable.containers);return l.delete(n),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function i_(o){let{disabled:e}=o;const{active:n,activatorEvent:a,draggableNodes:i}=H.useContext(hc),l=Qd(a),c=Qd(n?.id);return H.useEffect(()=>{if(!e&&!a&&l&&c!=null){if(!ef(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const y=JC(m);if(y){y.focus();break}}})}},[a,e,i,c,l]),null}function s_(o,e){let{transform:n,...a}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...a}),n):n}function o_(o){return H.useMemo(()=>({draggable:{...fc.draggable,...o?.draggable},droppable:{...fc.droppable,...o?.droppable},dragOverlay:{...fc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function l_(o){let{activeNode:e,measure:n,initialRect:a,config:i=!0}=o;const l=H.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;zr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!a)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=n(g),y=Hm(m,a);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const S=zm(g);S&&S.scrollBy({top:y.y,left:y.x})}},[e,c,d,a,n])}const ry=H.createContext({...wr,scaleX:1,scaleY:1});var Da;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(Da||(Da={}));const c_=H.memo(function(e){var n,a,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:g,sensors:m=ZE,collisionDetection:y=fE,measuring:S,modifiers:v,..._}=e;const A=H.useReducer(a_,void 0,r_),[x,O]=A,[M,T]=rE(),[D,z]=H.useState(Da.Uninitialized),P=D===Da.Initialized,{draggable:{active:q,nodes:W,translate:he},droppable:{containers:Ee}}=x,be=q!=null?W.get(q):null,Ue=H.useRef({initial:null,translated:null}),Fe=H.useMemo(()=>{var ge;return q!=null?{id:q,data:(ge=be?.data)!=null?ge:e_,rect:Ue}:null},[q,be]),Ge=H.useRef(null),[wt,J]=H.useState(null),[ue,Me]=H.useState(null),te=So(_,Object.values(_)),pe=Co("DndDescribedBy",c),N=H.useMemo(()=>Ee.getEnabled(),[Ee]),R=o_(S),{droppableRects:de,measureDroppableContainers:fe,measuringScheduled:xe}=PE(N,{dragging:P,dependencies:[he.x,he.y],config:R.droppable}),ee=zE(W,q),_e=H.useMemo(()=>ue?tf(ue):null,[ue]),Be=ve(),ke=BE(ee,R.draggable.measure);l_({activeNode:q!=null?W.get(q):null,config:Be.layoutShiftCompensation,initialRect:ke,measure:R.draggable.measure});const Ie=Jm(ee,R.draggable.measure,ke),Ct=Jm(ee?ee.parentElement:null),ot=H.useRef({activatorEvent:null,active:null,activeNode:ee,collisionRect:null,collisions:null,droppableRects:de,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ot=Ee.getNodeFor((n=ot.current.over)==null?void 0:n.id),vt=QE({measure:R.dragOverlay.measure}),_t=(a=vt.nodeRef.current)!=null?a:ee,Oe=P?(i=vt.rect)!=null?i:Ie:null,nt=!!(vt.nodeRef.current&&vt.rect),sn=VE(nt?null:Ie),Mt=ey(_t?Nn(_t):null),Vt=FE(P?Ot??ee:null),on=XE(Vt),ln=s_(v,{transform:{x:he.x-sn.x,y:he.y-sn.y,scaleX:1,scaleY:1},activatorEvent:ue,active:Fe,activeNodeRect:Ie,containerNodeRect:Ct,draggingNodeRect:Oe,over:ot.current.over,overlayNodeRect:vt.rect,scrollableAncestors:Vt,scrollableAncestorRects:on,windowRect:Mt}),Br=_e?hs(_e,he):null,Ft=KE(Vt),Ci=Zm(Ft),na=Zm(Ft,[Ie]),yn=hs(ln,Ci),On=Oe?pE(Oe,ln):null,rt=Fe&&On?y({active:Fe,collisionRect:On,droppableRects:de,droppableContainers:N,pointerCoordinates:Br}):null,Hn=Nm(rt,"id"),[bn,ra]=H.useState(null),sr=nt?ln:hs(ln,na),cn=hE(sr,(l=bn?.rect)!=null?l:null,Ie),Tn=H.useRef(null),un=H.useCallback((ge,we)=>{let{sensor:Ae,options:Ke}=we;if(Ge.current==null)return;const Te=W.get(Ge.current);if(!Te)return;const $e=ge.nativeEvent,Re=new Ae({active:Ge.current,activeNode:Te,event:$e,options:Ke,context:ot,onAbort(je){if(!W.get(je))return;const{onDragAbort:Se}=te.current,He={id:je};Se?.(He),M({type:"onDragAbort",event:He})},onPending(je,Ve,Se,He){if(!W.get(je))return;const{onDragPending:Tt}=te.current,It={id:je,constraint:Ve,initialCoordinates:Se,offset:He};Tt?.(It),M({type:"onDragPending",event:It})},onStart(je){const Ve=Ge.current;if(Ve==null)return;const Se=W.get(Ve);if(!Se)return;const{onDragStart:He}=te.current,tt={activatorEvent:$e,active:{id:Ve,data:Se.data,rect:Ue}};ka.unstable_batchedUpdates(()=>{He?.(tt),z(Da.Initializing),O({type:an.DragStart,initialCoordinates:je,active:Ve}),M({type:"onDragStart",event:tt}),J(Tn.current),Me($e)})},onMove(je){O({type:an.DragMove,coordinates:je})},onEnd:et(an.DragEnd),onCancel:et(an.DragCancel)});Tn.current=Re;function et(je){return async function(){const{active:Se,collisions:He,over:tt,scrollAdjustedTranslate:Tt}=ot.current;let It=null;if(Se&&Tt){const{cancelDrop:Ln}=te.current;It={activatorEvent:$e,active:Se,collisions:He,delta:Tt,over:tt},je===an.DragEnd&&typeof Ln=="function"&&await Promise.resolve(Ln(It))&&(je=an.DragCancel)}Ge.current=null,ka.unstable_batchedUpdates(()=>{O({type:je}),z(Da.Uninitialized),ra(null),J(null),Me(null),Tn.current=null;const Ln=je===an.DragEnd?"onDragEnd":"onDragCancel";if(It){const zt=te.current[Ln];zt?.(It),M({type:Ln,event:It})}})}}},[W]),V=H.useCallback((ge,we)=>(Ae,Ke)=>{const Te=Ae.nativeEvent,$e=W.get(Ke);if(Ge.current!==null||!$e||Te.dndKit||Te.defaultPrevented)return;const Re={active:$e};ge(Ae,we.options,Re)===!0&&(Te.dndKit={capturedBy:we.sensor},Ge.current=Ke,un(Ae,we))},[W,un]),se=UE(m,V);WE(m),zr(()=>{Ie&&D===Da.Initializing&&z(Da.Initialized)},[Ie,D]),H.useEffect(()=>{const{onDragMove:ge}=te.current,{active:we,activatorEvent:Ae,collisions:Ke,over:Te}=ot.current;if(!we||!Ae)return;const $e={active:we,activatorEvent:Ae,collisions:Ke,delta:{x:yn.x,y:yn.y},over:Te};ka.unstable_batchedUpdates(()=>{ge?.($e),M({type:"onDragMove",event:$e})})},[yn.x,yn.y]),H.useEffect(()=>{const{active:ge,activatorEvent:we,collisions:Ae,droppableContainers:Ke,scrollAdjustedTranslate:Te}=ot.current;if(!ge||Ge.current==null||!we||!Te)return;const{onDragOver:$e}=te.current,Re=Ke.get(Hn),et=Re&&Re.rect.current?{id:Re.id,rect:Re.rect.current,data:Re.data,disabled:Re.disabled}:null,je={active:ge,activatorEvent:we,collisions:Ae,delta:{x:Te.x,y:Te.y},over:et};ka.unstable_batchedUpdates(()=>{ra(et),$e?.(je),M({type:"onDragOver",event:je})})},[Hn]),zr(()=>{ot.current={activatorEvent:ue,active:Fe,activeNode:ee,collisionRect:On,collisions:rt,droppableRects:de,draggableNodes:W,draggingNode:_t,draggingNodeRect:Oe,droppableContainers:Ee,over:bn,scrollableAncestors:Vt,scrollAdjustedTranslate:yn},Ue.current={initial:Oe,translated:On}},[Fe,ee,rt,On,W,_t,Oe,de,Ee,bn,Vt,yn]),IE({...Be,delta:he,draggingRect:On,pointerCoordinates:Br,scrollableAncestors:Vt,scrollableAncestorRects:on});const ce=H.useMemo(()=>({active:Fe,activeNode:ee,activeNodeRect:Ie,activatorEvent:ue,collisions:rt,containerNodeRect:Ct,dragOverlay:vt,draggableNodes:W,droppableContainers:Ee,droppableRects:de,over:bn,measureDroppableContainers:fe,scrollableAncestors:Vt,scrollableAncestorRects:on,measuringConfiguration:R,measuringScheduled:xe,windowRect:Mt}),[Fe,ee,Ie,ue,rt,Ct,vt,W,Ee,de,bn,fe,Vt,on,R,xe,Mt]),Z=H.useMemo(()=>({activatorEvent:ue,activators:se,active:Fe,activeNodeRect:Ie,ariaDescribedById:{draggable:pe},dispatch:O,draggableNodes:W,over:bn,measureDroppableContainers:fe}),[ue,se,Fe,Ie,O,pe,W,bn,fe]);return Xe.createElement(Dm.Provider,{value:T},Xe.createElement(hc.Provider,{value:Z},Xe.createElement(ny.Provider,{value:ce},Xe.createElement(ry.Provider,{value:cn},g)),Xe.createElement(i_,{disabled:d?.restoreFocus===!1})),Xe.createElement(sE,{...d,hiddenTextDescribedById:pe}));function ve(){const ge=wt?.autoScrollEnabled===!1,we=typeof f=="object"?f.enabled===!1:f===!1,Ae=P&&!ge&&!we;return typeof f=="object"?{...f,enabled:Ae}:{enabled:Ae}}}),u_=H.createContext(null),ay="button",d_="Draggable";function f_(o){let{id:e,data:n,disabled:a=!1,attributes:i}=o;const l=Co(d_),{activators:c,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:y,over:S}=H.useContext(hc),{role:v=ay,roleDescription:_="draggable",tabIndex:A=0}=i??{},x=f?.id===e,O=H.useContext(x?ry:u_),[M,T]=oc(),[D,z]=oc(),P=YE(c,e),q=So(n);zr(()=>(y.set(e,{id:e,key:l,node:M,activatorNode:D,data:q}),()=>{const he=y.get(e);he&&he.key===l&&y.delete(e)}),[y,e]);const W=H.useMemo(()=>({role:v,tabIndex:A,"aria-disabled":a,"aria-pressed":x&&v===ay?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[a,v,A,x,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:W,isDragging:x,listeners:a?void 0:P,node:M,over:S,setNodeRef:T,setActivatorNodeRef:z,transform:O}}function h_(){return H.useContext(ny)}const g_="Droppable",p_={timeout:25};function m_(o){let{data:e,disabled:n=!1,id:a,resizeObserverConfig:i}=o;const l=Co(g_),{active:c,dispatch:d,over:f,measureDroppableContainers:g}=H.useContext(hc),m=H.useRef({disabled:n}),y=H.useRef(!1),S=H.useRef(null),v=H.useRef(null),{disabled:_,updateMeasurementsFor:A,timeout:x}={...p_,...i},O=So(A??a),M=H.useCallback(()=>{if(!y.current){y.current=!0;return}v.current!=null&&clearTimeout(v.current),v.current=setTimeout(()=>{g(Array.isArray(O.current)?O.current:[O.current]),v.current=null},x)},[x]),T=dc({callback:M,disabled:_||!c}),D=H.useCallback((W,he)=>{T&&(he&&(T.unobserve(he),y.current=!1),W&&T.observe(W))},[T]),[z,P]=oc(D),q=So(e);return H.useEffect(()=>{!T||!z.current||(T.disconnect(),y.current=!1,T.observe(z.current))},[z,T]),H.useEffect(()=>(d({type:an.RegisterDroppable,element:{id:a,key:l,disabled:n,node:z,rect:S,data:q}}),()=>d({type:an.UnregisterDroppable,key:l,id:a})),[a]),H.useEffect(()=>{n!==m.current.disabled&&(d({type:an.SetDroppableDisabled,id:a,key:l,disabled:n}),m.current.disabled=n)},[a,l,n,d]),{active:c,rect:S,isOver:f?.id===a,node:z,over:f,setNodeRef:P}}function hf(o,e,n){const a=o.slice();return a.splice(n<0?a.length+n:n,0,a.splice(e,1)[0]),a}function y_(o,e){return o.reduce((n,a,i)=>{const l=e.get(a);return l&&(n[i]=l),n},Array(o.length))}function gc(o){return o!==null&&o>=0}function b_(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:a,activeIndex:i,overIndex:l,index:c}=o;const d=(e=n[i])!=null?e:a;if(!d)return null;const f=w_(n,c,i);if(c===i){const g=n[l];return g?{x:ii&&c<=l?{x:-d.width-f,y:0,...pc}:c=l?{x:d.width+f,y:0,...pc}:{x:0,y:0,...pc}};function w_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return!a||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:a,index:i}=o;const l=hf(e,a,n),c=e[i],d=l[i];return!d||!c?null:{x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height}},mc={scaleX:1,scaleY:1},C_=o=>{var e;let{activeIndex:n,activeNodeRect:a,index:i,rects:l,overIndex:c}=o;const d=(e=l[n])!=null?e:a;if(!d)return null;if(i===n){const g=l[c];return g?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...mc}:i=c?{x:0,y:d.height+f,...mc}:{x:0,y:0,...mc}};function E_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return a?na.map(P=>typeof P=="object"&&"id"in P?P.id:P),[a]),_=c!=null,A=c?v.indexOf(c.id):-1,x=g?v.indexOf(g.id):-1,O=H.useRef(v),M=!b_(v,O.current),T=x!==-1&&A===-1||M,D=v_(l);zr(()=>{M&&_&&m(v)},[M,v,_,m]),H.useEffect(()=>{O.current=v},[v]);const z=H.useMemo(()=>({activeIndex:A,containerId:y,disabled:D,disableTransforms:T,items:v,overIndex:x,useDragOverlay:S,sortedRects:y_(v,f),strategy:i}),[A,y,D.draggable,D.droppable,T,v,x,f,S,i]);return Xe.createElement(sy.Provider,{value:z},e)}const A_=o=>{let{id:e,items:n,activeIndex:a,overIndex:i}=o;return hf(n,a,i).indexOf(e)},x_=o=>{let{containerId:e,isSorting:n,wasDragging:a,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!a||d!==l&&i===c?!1:n?!0:c!==i&&e===f},T_={duration:200,easing:"ease"},oy="transform",R_=_o.Transition.toString({property:oy,duration:0,easing:"linear"}),k_={roleDescription:"sortable"};function D_(o){let{disabled:e,index:n,node:a,rect:i}=o;const[l,c]=H.useState(null),d=H.useRef(n);return zr(()=>{if(!e&&n!==d.current&&a.current){const f=i.current;if(f){const g=gs(a.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,a,i]),H.useEffect(()=>{l&&c(null)},[l]),l}function O_(o){let{animateLayoutChanges:e=x_,attributes:n,disabled:a,data:i,getNewIndex:l=A_,id:c,strategy:d,resizeObserverConfig:f,transition:g=T_}=o;const{items:m,containerId:y,activeIndex:S,disabled:v,disableTransforms:_,sortedRects:A,overIndex:x,useDragOverlay:O,strategy:M}=H.useContext(sy),T=L_(a,v),D=m.indexOf(c),z=H.useMemo(()=>({sortable:{containerId:y,index:D,items:m},...i}),[y,i,D,m]),P=H.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:q,node:W,isOver:he,setNodeRef:Ee}=m_({id:c,data:z,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:P,...f}}),{active:be,activatorEvent:Ue,activeNodeRect:Fe,attributes:Ge,setNodeRef:wt,listeners:J,isDragging:ue,over:Me,setActivatorNodeRef:te,transform:pe}=f_({id:c,data:z,attributes:{...k_,...n},disabled:T.draggable}),N=KC(Ee,wt),R=!!be,de=R&&!_&&gc(S)&&gc(x),fe=!O&&ue,xe=fe&&de?pe:null,_e=de?xe??(d??M)({rects:A,activeNodeRect:Fe,activeIndex:S,overIndex:x,index:D}):null,Be=gc(S)&&gc(x)?l({id:c,items:m,activeIndex:S,overIndex:x}):D,ke=be?.id,Ie=H.useRef({activeId:ke,items:m,newIndex:Be,containerId:y}),Ct=m!==Ie.current.items,ot=e({active:be,containerId:y,isDragging:ue,isSorting:R,id:c,index:D,items:m,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:g,wasDragging:Ie.current.activeId!=null}),Ot=D_({disabled:!ot,index:D,node:W,rect:q});return H.useEffect(()=>{R&&Ie.current.newIndex!==Be&&(Ie.current.newIndex=Be),y!==Ie.current.containerId&&(Ie.current.containerId=y),m!==Ie.current.items&&(Ie.current.items=m)},[R,Be,y,m]),H.useEffect(()=>{if(ke===Ie.current.activeId)return;if(ke!=null&&Ie.current.activeId==null){Ie.current.activeId=ke;return}const _t=setTimeout(()=>{Ie.current.activeId=ke},50);return()=>clearTimeout(_t)},[ke]),{active:be,activeIndex:S,attributes:Ge,data:z,rect:q,index:D,newIndex:Be,items:m,isOver:he,isSorting:R,isDragging:ue,listeners:J,node:W,overIndex:x,over:Me,setNodeRef:N,setActivatorNodeRef:te,setDroppableNodeRef:Ee,setDraggableNodeRef:wt,transform:Ot??_e,transition:vt()};function vt(){if(Ot||Ct&&Ie.current.newIndex===D)return R_;if(!(fe&&!ef(Ue)||!g)&&(R||ot))return _o.Transition.toString({...g,property:oy})}}function L_(o,e){var n,a;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(n=o?.draggable)!=null?n:e.draggable,droppable:(a=o?.droppable)!=null?a:e.droppable}}function yc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const M_=[ut.Down,ut.Right,ut.Up,ut.Left],$_=(o,e)=>{let{context:{active:n,collisionRect:a,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(M_.includes(o.code)){if(o.preventDefault(),!n||!a)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const S=i.get(y.id);if(S)switch(o.code){case ut.Down:a.topS.top&&f.push(y);break;case ut.Left:a.left>S.left&&f.push(y);break;case ut.Right:a.left1&&(m=g[1].id),m!=null){const y=l.get(n.id),S=l.get(m),v=S?i.get(S.id):null,_=S?.node.current;if(_&&v&&y&&S){const x=cc(_).some((P,q)=>d[q]!==P),O=ly(y,S),M=N_(y,S),T=x||!O?{x:0,y:0}:{x:M?a.width-v.width:0,y:M?a.height-v.height:0},D={x:v.left,y:v.top};return T.x&&T.y?D:Eo(D,T)}}}};function ly(o,e){return!yc(o)||!yc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function N_(o,e){return!yc(o)||!yc(e)||!ly(o,e)?!1:o.data.current.sortable.index{const d=H.useId(),f=H.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=oE(Om(cf,{activationConstraint:{distance:5}}),Om(of,{coordinateGetter:$_})),m=H.useCallback(v=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:v.active.id},l?.({activeId:v.active.id})},[l]),y=H.useCallback(v=>{const{active:_,over:A}=v,x=Date.now();if(!A||_.id===A.id){f.current.inProgress=!1;return}const{lastSortTime:O,lastActiveId:M,inProgress:T}=f.current;if(M===_.id&&x-O<500&&!T)return;f.current={inProgress:!1,lastSortTime:x,lastActiveId:_.id};const D=o.findIndex(P=>String(P[e])===String(_.id)),z=o.findIndex(P=>String(P[e])===String(A.id));if(D!==-1&&z!==-1&&D!==z){const P=hf(o,D,z);i?.(P,{oldIndex:D,newIndex:z})}},[o,e,i]),S=o.map(v=>String(v[e]));return gt.jsx(c_,{id:d,sensors:g,collisionDetection:cE,onDragStart:m,onDragEnd:y,children:gt.jsx(__,{items:S,strategy:I_[n],children:a})},c!==void 0?`${d}-v${c}`:d)},cy=H.createContext(null),j_=({value:o,children:e})=>gt.jsx(cy.Provider,{value:o,children:e}),z_=()=>H.useContext(cy),U_=({id:o,handle:e,as:n="div",children:a})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:g}=O_({id:o}),m={transform:_o.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return gt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:gt.jsx(j_,{value:{listeners:l,handle:e,isDragging:g},children:a})})},st=ht("DynamicRenderer");function Zr(){try{return window.G7Core?.devTools}catch{return}}function pf(o,e,n,a){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,n,a)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>pf(i,e,n,a));if(o&&typeof o=="object"){const i={};for(const[l,c]of Object.entries(o))i[l]=pf(c,e,n,a);return i}return o}function P_(o){const e=Object.keys(o);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const Cr=(o,e)=>{const n=["errors"],a={...o};for(const i of Object.keys(e)){const l=e[i],c=o[i];if(l===null){a[i]=null;continue}if(n.includes(i)){a[i]=l;continue}if(Array.isArray(l)){a[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&P_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)a[i]={...l};else{const g=[...c];for(const[m,y]of Object.entries(l)){const S=parseInt(m,10);S>=0&&S=g.length&&(g[S]=y)}a[i]=g}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?a[i]=Cr(c,l):a[i]=l}return a},bc=(o,e)=>{let n=null;const a=()=>(n===null&&(n={...o}),n);for(const i of Object.keys(e)){if(!(i in o))continue;const l=e[i],c=o[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=bc(c,l);if(d===c)continue;Object.keys(d).length===0?delete a()[i]:a()[i]=d}else delete a()[i]}return n??o},B_=o=>{const e={},n=o.split(";").filter(a=>a.trim());for(const a of n){const i=a.indexOf(":");if(i===-1)continue;const l=a.substring(0,i).trim(),c=a.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=c}}return e};class q_ extends H.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){st.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:gt.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[gt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),gt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&>.jsxs("details",{className:"mt-2",children:[gt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),gt.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Ur=H.memo(({componentDef:o,dataContext:e,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:S=!1,onComponentSelect:v,onComponentHover:_,onDragStart:A,onDragEnd:x,componentPath:O,layoutKey:M})=>{const[T,D]=H.useState({loadingActions:{}});H.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const z=H.useRef(null);H.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:se,...ce}=e._localInit,Z=`${JSON.stringify(ce)}:${V||"no-force"}`;if(z.current!==Z){z.current=Z;const ve=se||"shallow",we=window.G7Core?.state?.get?.()?._local||{},Ae=window.__g7PendingLocalState||{},Ke={...we,...Ae};ve==="replace"?window.__g7PendingLocalState={loadingActions:Ke.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=Cr(Ke,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Ke,...ce,hasChanges:!1};const Te=window.__g7SetLocalOverrideKeys;Te&&typeof Te=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=Cr(Te,{...ce,hasChanges:!1}))}}}),H.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){D(ve=>bc(ve,V));const se=V,ce=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===se&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const P=H.useRef(M);H.useEffect(()=>{o._fromBase&&M&&P.current!==M&&(P.current=M,D({loadingActions:{}}))},[M,o._fromBase]);const q=H.useRef(""),W=H.useRef(!1),he=H.useRef(null),Ee=H.useRef(null),be=H.useRef({}),Ue=H.useRef({}),Fe=H.useRef(g),Ge=FC(),wt=CC(),J=wt?.getParentDataContext()??g;H.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...se}=e._localInit,ce=JSON.stringify(se),Z=V!==void 0,ve=Fd(),ge=`${ce}:${V||"no-force"}`,we=DC({globalTrackedKey:ve.hash,instanceHandledKey:Ee.current,trackingKey:ge});if(we==="apply"){Ee.current=ge,ve.hash=ge,ve.timestamp=V,q.current=ce,Z&&(W.current=!0);const{_merge:Ke,...Te}=se,$e=Ke||"shallow";D(Re=>$e==="replace"?{loadingActions:Re.loadingActions||{},...Te,hasChanges:!1}:$e==="deep"?Cr(Re,{...Te,hasChanges:!1}):{...Re,...Te,hasChanges:!1}),e._globalSetState&&e._globalSetState(Re=>{const et=Re?._local||{};let je;return $e==="replace"?je={...Te,hasChanges:!1}:$e==="deep"?je=Cr(et,{...Te,hasChanges:!1}):je={...et,...Te,hasChanges:!1},{...Re,_local:je}}),i.invalidateCacheByKeys(["_local"]),st.log("_localInit applied (data changed):",Object.keys(se))}else if(we==="prune"){Ee.current=ge;const{_merge:Ke,...Te}=se;D(Re=>bc(Re,Te)),bc(T,Te)!==T&&(i.invalidateCacheByKeys(["_local"]),st.log("_localInit pruned (applied by another renderer):",Object.keys(Te)))}he.current=e._localInit,RC(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:ue}=wm(),Me=HC(),te=f??Me,{width:pe}=Wd(),N=z_(),R=H.useMemo(()=>{let V=o;if(o.type==="iterator"&&o.data){const{data:Z,itemName:ve,indexName:ge,...we}=o;V={...we,iteration:{source:Z,item_var:ve||"item",index_var:ge}}}if(!V.responsive)return V;const se=hi.getMatchingKey(V.responsive,pe);if(!se)return V;const ce=V.responsive[se];return{...V,props:{...V.props,...ce.props},children:ce.children??V.children,text:ce.text??V.text,if:ce.if??V.if,iteration:ce.iteration??V.iteration,__responsiveChildrenKey:ce.children!==void 0?se:void 0}},[o,pe]),de=H.useCallback(V=>{const se=V?.__setStateId;if(D(ce=>{const Z=window.__g7PendingLocalState,ge=window.__g7SetLocalOverrideKeys||Z,we=ge?Cr(ce,ge):ce;if(typeof V=="function"){const Re=V(we);return Cr(we,Re)}const{__mergeMode:Ae,__setStateId:Ke,...Te}=V;let $e;if(Ae==="replace"?$e=Te:Ae==="shallow"?$e={...we,...Te}:$e=Cr(we,Te),Ae!==void 0){const Re=window.__g7ForcedLocalFields;Re&&(window.__g7ForcedLocalFields={...Re,...Te})}return $e}),se){const ce=Zr();if(ce?.isEnabled()){const Z=R.id||"unknown",ve=R.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(Z,ve,0,["_local"],[]),ce.completeStateChange?.(se)},0)}}},[R.id,R.name]),fe=d?.state??T,xe=d?.setState??de,ee=H.useMemo(()=>{const V=e._localInit&&e._localInit!==he.current;let se;V&&e._local?se=e._local:se=e._local?Cr(e._local,fe):fe;const ce=window.__g7ForcedLocalFields;ce&&(se=Cr(se,ce));const Z={...e,_local:se},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const ge=new Dn,we={...Z,...Ge?{_isolated:Ge.state}:{}},Ae={},Ke=Zr(),Te=Ke?.isEnabled()??!1;for(const[$e,Re]of Object.entries(ve)){const et=Te?Date.now():0,je=Te?e._computed?.[$e]:void 0;let Ve;try{if(typeof Re=="string")if(Re.startsWith("{{")&&Re.endsWith("}}")){const Se=Re.slice(2,-2).trim(),He=Vn(Se)?ge.evaluatePipeExpression(Se,we,{skipCache:!0}):ge.evaluateExpression(Se,we,{skipCache:!0});Ae[$e]=He}else Ae[$e]=Re;else if(Re&&typeof Re=="object"&&"$switch"in Re){const Se=ge.resolveSwitch(Re,we,{skipCache:!0});Ae[$e]=Se}}catch(Se){st.warn(`Failed to recalculate computed value: ${$e}`,Se),Ae[$e]=e._computed?.[$e],Ve=Se instanceof Error?Se.message:String(Se)}if(Te&&(Ve||je!==Ae[$e])){const He=Date.now()-et;Ke.trackComputedProperty?.($e,typeof Re=="string"?Re:JSON.stringify(Re),[{type:"_local",path:"_local",value:Z._local}],Ae[$e],He,R.id,Ve),je!==Ae[$e]&&Ke.trackComputedRecalc?.($e,"dependency-change",je,Ae[$e],He,{type:"_local",path:"_local"},R.id)}}Z._computed=Ae}if(Ge&&(Z._isolated=Ge.state),J&&(Z.$parent=J),o.extensionPointProps){const ge=i.resolveObject(o.extensionPointProps,Z,y?{skipCache:!0}:void 0);Z.extensionPointProps=S&&l?pf(ge,l,n,Z):ge}return o.extensionPointCallbacks&&(Z.extensionPointCallbacks=o.extensionPointCallbacks),S&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,fe,Ge?.state,J,wt?.version,o.extensionPointProps,o.extensionPointCallbacks]);be.current=ee._local,Ue.current=ee._computed||{},Fe.current=J,H.useEffect(()=>{const V=Zr();if(!V?.isEnabled())return;const se=ee._local;se&&V.updateLocalState(se);const ce=ee._computed;ce&&V.updateComputedState(ce),J&&V.updateParentContext?.(J);const Z=R.id||`comp-${Date.now()}`,ve=R.name||"Unknown",ge={global:Object.keys(e._global||{}),local:Object.keys(se||{}),context:d?Object.keys(d.state||{}):[]},we={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(Z,ve,ge,we),fe&&Object.keys(fe).length>0&&V.trackDynamicState?.(Z,fe);const Ae=!!(R.expandChildren||R.props?.expandChildren);V.trackContextFlow?.(Z,ve,!!d,Ae,!0)},[ee._local,e,R.id,R.name,d,fe,R.expandChildren,R.props?.expandChildren,J]);const _e=H.useMemo(()=>({state:{...ee._local},setState:xe,stateRef:be,computedRef:Ue,isolatedContext:Ge,parentDataContext:ee}),[ee._local,xe,T,Ge,ee]),Be=H.useMemo(()=>{const V=ns({if:R.if,condition:R.condition,conditions:R.conditions},ee,i,R.id);if(R.if||R.condition!==void 0||R.conditions){const ce=Zr();ce?.isEnabled()&&R.if&&ce.trackIfCondition(R.id||`if-${Date.now()}`,R.if,V)}return V},[R.if,R.conditions,ee,i,R.id]),ke=H.useMemo(()=>{if(!R.slot)return null;const V=R.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const se=V.slice(2,-2).trim();try{const ce={componentId:R.id,componentName:R.name,propName:"slot"},Z=Vn(se)?i.evaluatePipeExpression(se,ee,void 0,ce):i.evaluateExpression(se,ee,ce);return st.log(`[Slot] 표현식 평가: "${se}" => "${Z}" (컴포넌트: ${R.id})`),typeof Z=="string"?Z:null}catch(ce){return st.warn(`slot 표현식 평가 실패 (컴포넌트: ${R.id}):`,ce),null}}return st.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${R.id})`),V},[R.slot,R.id,ee,i]),Ie=H.useMemo(()=>!ke||!R.id?"":`${R.id}-${ke}-${JSON.stringify(R.slotOrder??0)}`,[ke,R.id,R.slotOrder]),Ct=H.useRef(null);H.useEffect(()=>{const V=window.__slotContextValue,se=V?.isEnabled??!1;if(R.slot&&st.log(`[Slot Registration] 컴포넌트: ${R.id}, isSlotEnabled: ${se}, shouldRender: ${Be}, resolvedSlotId: ${ke}`),!se||!Be){R.slot&&st.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${se}, shouldRender: ${Be}`),Ct.current&&R.id&&V&&(V.unregisterFromSlot(Ct.current,R.id),Ct.current=null);return}if(!ke||!R.id){R.slot&&st.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${ke}, id: ${R.id}`),Ct.current&&R.id&&V&&(V.unregisterFromSlot(Ct.current,R.id),Ct.current=null);return}Ct.current&&Ct.current!==ke&&V.unregisterFromSlot(Ct.current,R.id);const ce={...R,slot:void 0,slotOrder:void 0};return V.registerToSlot(ke,R.id,{componentDef:ce,dataContext:e,order:R.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>_e,translationContext:n,registrationKey:Ie}),Ct.current=ke,()=>{const Z=window.__slotContextValue;ke&&R.id&&Z&&Z.unregisterFromSlot(ke,R.id)}},[Be,ke,R,e,f,_e,n,Ie]);const ot=H.useCallback(V=>{if(typeof V=="string"){if(jl(V))return bd(V);if(zl(V)){const se=[],ce=V.replace(new RegExp(`${ao}([^${fi}]*)${fi}`,"g"),(ve,ge)=>(se.push(ge),`${xa}${se.length-1}${xa}`));let Z=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(Z=l.resolveTranslations(ce,n,ee)),Z.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(ve,ge)=>se[parseInt(ge)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const se=V.trim();return se.startsWith("{")&&se.endsWith("}")||se.startsWith("[")&&se.endsWith("]")?V:l.resolveTranslations(V,n,ee)}return V}if(Array.isArray(V))return V.map(se=>ot(se));if(V&&typeof V=="object"){const se={};for(const[ce,Z]of Object.entries(V))se[ce]=ot(Z);return se}return V},[l,n,ee]),Ot=H.useCallback(V=>ro(V),[]),vt=H.useCallback(V=>Aa(V),[]),_t=H.useMemo(()=>{let V={...R.props||{}};const se=["cellChildren","expandChildren","expandContext","render"],Z=a.getMetadata(R.name)?.skipBindingKeys||[],ve=[...new Set([...se,...Z])],ge=y?{skipCache:!0}:void 0,we={...ge??{},skipBindingKeys:ve},Ae=Se=>{if(ge)return ge;if(Se.startsWith("_computed")||Se.startsWith("$computed"))return{skipCache:!0}};for(const[Se,He]of Object.entries(V))if(!ve.includes(Se))if(typeof He=="string"){const tt=vt(He);if(tt!==null){let Tt=!1,It=tt;tt.startsWith(nr)&&(Tt=!0,It=tt.slice(nr.length));const Ln={componentId:R.id,componentName:R.name,propName:Se};let zt;if(Vn(It))try{zt=i.evaluatePipeExpression(It,ee,Ae(It),Ln)}catch(Ut){st.warn(`파이프 표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${Se}):`,Ut),zt=void 0}else if(Ot(It))try{zt=i.evaluateExpression(It,ee,Ln)}catch(Ut){st.warn(`표현식 평가 실패 (컴포넌트: ${R.id}, prop: ${Se}):`,Ut),zt=void 0}else zt=i.resolve(It,ee,Ae(It),Ln);V[Se]=Tt&&zt!=null?ts(zt):zt}else{const Tt={componentId:R.id,componentName:R.name,propName:Se};V[Se]=i.resolveBindings(He,ee,ge,Tt)}}else Array.isArray(He)?V[Se]=He.map(tt=>typeof tt=="string"?i.resolveBindings(tt,ee,ge):typeof tt=="object"&&tt!==null?i.resolveObject(tt,ee,we):tt):He&&typeof He=="object"&&(V[Se]=i.resolveObject(He,ee,we));for(const[Se,He]of Object.entries(V))V[Se]=ot(He);if(typeof V.style=="string"&&(V.style=B_(V.style)),V=Cd(V,S?void 0:R.actions,ee,{componentContext:_e,actionDispatcher:c}),R.classMap){const Se=Cw(R.classMap,ee,i,{skipCache:!0});if(Se){const He=V.className||"";V.className=He?`${He} ${Se}`:Se}}R.style&&(V.style=R.style),R.actions&&R.actions.length>0&&R.type==="composite"&&Object.assign(V,fe),R.component_layout&&(V.__componentLayoutDefs=R.component_layout);const Ke=R.expandChildren||R.props?.expandChildren,Te=R.props?.cellChildren,$e=R.children&&R.children.length>0,Re=R.component_layout,et=R.slot,je=R.props?.modalId,Ve=R.type==="composite";return(Ke||Te||$e||Re||et||je||Ve)&&(V.__componentContext=_e),V},[R.props,R.actions,R.style,R.classMap,R.id,ee,n,i,l,_e,fe,ot,Ot,vt,y]),Oe=H.useRef(null),nt=H.useMemo(()=>Oe.current&&Em(Oe.current,_t)?Oe.current:(Oe.current=_t,_t),[_t]),sn=H.useMemo(()=>{const V=R.id;if(typeof V!="string"||!V.includes("{{"))return V;const se=i.resolveBindings(V,ee,{skipCache:!0});return typeof se=="string"?se:V},[R.id,ee,i]),Mt=H.useMemo(()=>{const V=R.dataKey,se=R.trackChanges,ce=R.debounce;if(V){const Z=V.startsWith("_global."),ve=Z?V.slice(8):V,ge=Z?e._global:ee._local;return{dataKey:ve,trackChanges:se??!1,debounce:ce,setState:Z?Ae=>{e._globalSetState?e._globalSetState(Ae):st.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:xe,state:ge??{},_isGlobal:Z}}if(te.dataKey)return te},[R.dataKey,R.trackChanges,R.debounce,R.id,xe,ee._local,e._global,e._globalSetState,te]),Vt=H.useRef(new Set);H.useEffect(()=>{Vt.current.clear()},[e._global?._remountKeys]);const on=H.useCallback((V,se)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!Vt.current.has(V)?(Vt.current.add(V),`${V}-remount-${ce[V]}`):V||se},[e._global?._remountKeys]),ln=H.useMemo(()=>{if(R.text!==void 0){if(typeof R.text=="string"){const V=R.text;let se=V;const ce={componentId:R.id,componentName:R.name,propName:"text",skipCache:!0},Z=vt(V);if(Z!==null){let ve=!1,ge=Z;if(Z.startsWith(nr)&&(ve=!0,ge=Z.slice(nr.length)),Vn(ge))try{se=i.evaluatePipeExpression(ge,ee,{skipCache:!0},ce)}catch(we){st.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${R.id}):`,we),se=""}else if(Ot(ge))try{se=i.evaluateExpression(ge,ee,ce)}catch(we){st.warn(`text 표현식 평가 실패 (컴포넌트: ${R.id}):`,we),se=""}else se=i.resolve(ge,ee,{skipCache:!0},ce);ve&&se!=null&&(se=ts(se))}else V.includes("{{")&&(se=i.resolveBindings(V,ee,{skipCache:!0},ce));return se=ot(se),se??""}return R.text}return!R.children||R.children.length===0?null:R.children.map((V,se)=>{if(typeof V=="string")return V;const ce=R.__responsiveChildrenKey,Z=ce?`responsive.${ce}.children`:"children",ve=O?`${O}.${Z}.${se}`:`${se}`,ge=V._fromBase?V.id||`child-${se}`:on(V.id,`child-${se}`),we=!V._fromBase&&M?`${ge}_${M}`:ge;return gt.jsx(Ur,{componentDef:V,dataContext:ee,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:Mt,isInsideIteration:y,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:ve,onDragStart:A,onDragEnd:x,layoutKey:M},we)})},[R.text,R.children,R.id,e,ee,n,a,i,l,c,_e,Mt,vt,Ot,ot,on,y,S,v,_,O,A,x,M]),Br=H.useMemo(()=>{if(!R.iteration)return null;try{const V=wd(R.iteration.source,ee,i);if(!Array.isArray(V))return st.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,V),null;const se=Zr();return se?.isEnabled()&&se.trackIteration(R.id||`iteration-${Date.now()}`,R.iteration.source,R.iteration.item_var,R.iteration.index_var,V.length),V.map((ce,Z)=>{const ve={...ee,[R.iteration.item_var]:ce,[`${R.iteration.item_var}_index`]:Z};R.iteration.index_var&&(ve[R.iteration.index_var]=Z);const ge=Z===0||Z===V.length-1;se?.isEnabled()&&ge&&se.trackNestedContext?.({componentId:`${R.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(ee),values:{}},ownContext:{added:[R.iteration.item_var,...R.iteration.index_var?[R.iteration.index_var]:[]],values:{[R.iteration.item_var]:ce,...R.iteration.index_var?{[R.iteration.index_var]:Z}:{}}},depth:1});const we={...R,iteration:void 0,responsive:void 0},Ae=O?`${O}.iteration.${Z}`:`iteration.${Z}`,Ke=`${on(R.id,"item")}-${Z}`;return gt.jsx(Ur,{componentDef:we,dataContext:ve,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:Mt,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:Ae,onDragStart:A,onDragEnd:x,layoutKey:M},Ke)})}catch(V){return st.error(`iteration 렌더링 실패 (컴포넌트: ${R.id}):`,V),null}},[R.iteration,R.children,R.id,e,ee,n,a,i,l,c,_e,Mt,on,S,v,_,O,A,x,M]),[Ft,Ci]=H.useState(0),na=H.useMemo(()=>{if(!R.sortable||!R.itemTemplate)return null;const{sortable:V,itemTemplate:se}=R;try{const ce=wd(V.source,ee,i);if(!Array.isArray(ce))return st.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${R.id}):`,ce),null;if(ce.length===0)return null;const Z=V.itemKey||"id",ve=V.strategy||"verticalList",ge=V.itemVar||"$item",we=V.indexVar||"$index",Ae=V.handle,Ke=V.wrapperElement,Te=(et,je)=>{const Ve=R.actions?.filter(Se=>Se.event==="onSortEnd"||Se.type==="onSortEnd");if(Ci(Se=>Se+1),Ve&&Ve.length>0&&c){const Se={...ee,$sortedItems:et,$sortEvent:je};Ve.forEach(He=>{try{const tt=c.createHandler(He,Se,_e),Tt=new Event("sortend");tt(Tt)}catch(tt){st.error(`onSortEnd action failed: ${He.handler}`,tt)}})}},$e=et=>{const je=R.actions?.filter(Ve=>Ve.event==="onSortStart"||Ve.type==="onSortStart");if(je&&je.length>0&&c){const Ve={...ee,$activeId:et.activeId};je.forEach(Se=>{try{const He=c.createHandler(Se,Ve,_e),tt=new Event("sortstart");He(tt)}catch(He){st.error(`onSortStart action failed: ${Se.handler}`,He)}})}},Re=ce.map((et,je)=>{const Ve=String(et[Z]),Se={...ee,[ge]:et,[we]:je},He=O?`${O}.sortable.${je}`:`sortable.${je}`,tt=`${on(R.id,"sortable-item")}-v${Ft}-${Ve}`;return gt.jsx(U_,{id:Ve,handle:Ae,...Ke?{as:Ke}:{},children:(Ke&&se.children?se.children:[se]).map((Tt,It)=>gt.jsx(Ur,{componentDef:Tt,dataContext:Se,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:_e,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:He,onDragStart:A,onDragEnd:x,layoutKey:M},`${tt}-child-${It}`))},tt)});return gt.jsx(H_,{items:ce,itemKey:Z,strategy:ve,onSortEnd:Te,onSortStart:$e,sortVersion:Ft,children:Re})}catch(ce){return st.error(`sortable 렌더링 실패 (컴포넌트: ${R.id}):`,ce),null}},[R.sortable,R.itemTemplate,R.actions,R.id,e,ee,n,a,i,l,c,_e,on,S,v,_,O,A,x,Ft,M]),yn=H.useRef(!1);H.useEffect(()=>{if(yn.current)return;yn.current=!0;const V=Zr();if(V?.isEnabled()&&V.trackMount(o.id,{name:o.name,type:o.type||"component",props:nt}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const ce of o.lifecycle.onMount)try{const Z=c.createHandler(ce,ee,_e),ve=new Event("mount");Z(ve),st.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${o.id})`)}catch(Z){st.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${o.id})`,Z)}const se=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const Z of o.onComponentEvent){if(!Z.event){st.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const ve=async we=>{try{const Ae={...ee,_eventData:we},Te=await c.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},Ae,_e)(new CustomEvent(Z.event,{detail:we}));return st.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${o.id})`,{eventData:we,result:Te}),Te}catch(Ae){throw st.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${o.id})`,Ae),Ae}},ge=ce.componentEvent.on(Z.event,ve);se.push(ge),st.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${o.id})`)}else st.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const ce=Zr();ce?.isEnabled()&&ce.trackUnmount(o.id);for(const Z of se)try{Z()}catch(ve){st.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,ve)}if(se.length>0&&st.log(`onComponentEvent: Unsubscribed ${se.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const Z of o.lifecycle.onUnmount)try{const ve=c.createHandler(Z,ee,_e),ge=new Event("unmount");ve(ge),st.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${o.id})`)}catch(ve){st.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${o.id})`,ve)}}},[]);const On=H.useMemo(()=>{const V=nt.dataKey,se=nt.trackChanges,ce=nt.debounce;return V?{dataKey:V,trackChanges:se??!1,debounce:ce,setState:xe,state:fe}:null},[nt.dataKey,nt.trackChanges,nt.debounce,xe,fe]);H.useEffect(()=>{const V=R.dataKey||nt.dataKey;if(!V)return;const se=Zr();if(!se?.isEnabled())return;const ce=[],Z=ge=>{if(ge)for(const we of ge){const Ae=we?.props?.name;if(Ae&&ce.push({name:Ae,type:we.name||we.type||"unknown"}),we?.children&&Z(we.children),we?.slots)for(const Ke of Object.values(we.slots))Array.isArray(Ke)&&Z(Ke)}};if(o.children&&Z(o.children),o.slots)for(const ge of Object.values(o.slots))Array.isArray(ge)&&Z(ge);const ve=o.id||`form-${V}`;return se.trackForm(ve,V,ce),()=>{se.untrackForm(ve)}},[R,nt.dataKey,o.id,o.children]);const rt=H.useRef(null),Hn=H.useRef(void 0);H.useEffect(()=>{const V=nt?.name;if(!V||!te.dataKey||!te.setState||nt?.autoBinding===!1)return;const se=`${te.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(se,(ce.get(se)??0)+1),()=>{const Z=ce.get(se)??0;Z<=1?ce.delete(se):ce.set(se,Z-1)}},[nt?.name,nt?.autoBinding,te.dataKey,te.setState]);const bn=H.useMemo(()=>{const{dataKey:V,trackChanges:se,debounce:ce,...Z}=nt,ve=Z.name;if(!ve||!te.dataKey||!te.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ve,...Se}=Z;return Se}const ge=`${te.dataKey}.${ve}`,we=jC(te.state,ge),Ae=we!==void 0?we:Z.value,Te=a.getMetadata(o.name)?.bindingType,$e=typeof Ae=="boolean"&&(Te==="checked"||Te==="checkable"&&["checkbox","radio"].includes(Z?.type)),Re=te.debounce,et=Ve=>{const Se=te.state||{},He=zC(Se,ge,Ve);if(te.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=He,te.setState(He),te._isGlobal)return;const tt=window.G7Core,Tt={[ge]:Ve};te.trackChanges&&(Tt.hasChanges=!0),tt?.state?.setLocal?.(Tt,{render:!1})},je=(Ve,Se)=>{Re&&Re>0?(rt.current&&clearTimeout(rt.current),rt.current=setTimeout(()=>{et(Ve),rt.current=null,Se&&(Se(),window.__g7PendingLocalState=null)},Re)):(et(Ve),Se&&(Se(),window.__g7PendingLocalState=null))};if($e)return{...Z,checked:Ae,onChange:Se=>{const He=Se.target.checked;et(He),Z.onChange&&Z.onChange(Se)}};{const Ve=He=>{const tt=He?.target?.value!==void 0?He.target.value:He;Re&&Re>0&&(Hn.current=tt);const Tt=He?.target?{target:{value:tt,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:tt,name:He.currentTarget.name}:void 0}:He;je(tt,()=>{Z.onChange&&Z.onChange(Tt)})};let Se;return Hn.current!==void 0?rt.current!==null?Se=Hn.current:String(Ae??"")===String(Hn.current)?(Hn.current=void 0,Se=Ae??""):Se=Hn.current:Se=Ae??"",{...Z,value:Se,onChange:Ve}}},[nt,te,te.state,te.debounce]),ra=H.useMemo(()=>{const V=Zr();if(V?.isEnabled()&&V.trackRender(o.name),!Be)return R.iteration?Br:null;if(R.sortable&&R.itemTemplate)return na;if(R.iteration)return Br;if(R.type==="extension_point"){const{layout:Te,columns:$e,gap:Re,className:et,...je}=R.props||{};let Ve=et||"";return Te==="grid"&&$e?Ve=`${Ve} grid grid-cols-${$e} gap-${Re||4}`.trim():Te==="flex"&&(Ve=`${Ve} flex flex-col gap-${Re||4}`.trim()),gt.jsx("div",{id:sn,className:Ve||void 0,...je,children:ln})}const se=a.getComponent(R.name);if(!se)return st.error(`컴포넌트를 찾을 수 없습니다: ${R.name} (ID: ${R.id})`,"componentDef:",JSON.stringify(R,null,2)),null;const ce=e._global?._remountKeys,Z={...bn,id:bn.id??sn,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(N?.listeners&&N.handle&&bn["data-drag-handle"]!==void 0&&(Object.assign(Z,N.listeners),Z.style={...Z.style,cursor:N.isDragging?"grabbing":"grab"}),S){const Te=R.id||`auto_${R.name||R.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,$e=je=>{typeof je.preventDefault=="function"&&je.preventDefault(),v&&(je.stopPropagation(),v(Te,je))},Re={"data-editor-id":Te,"data-editor-name":R.name,"data-editor-type":R.type,onClick:$e};O&&(Re["data-editor-path"]=O);const et=R.__editorSlotName??R.slot;typeof et=="string"&&(Re["data-editor-slot"]=et),_&&(Re.onMouseMove=je=>{je.stopPropagation(),_(Te,je)},Re.onMouseLeave=je=>{_(null,je)}),Object.assign(Z,Re),Z.editorAttrs=Re}const ve=R.type==="basic",ge=R.type==="layout",Ae=ve||ge?(()=>{const Te={};for(const[$e,Re]of Object.entries(Z))$e.startsWith("__")||$e==="editorAttrs"&&ve||(Te[$e]=Re);return Te})():Z;let Ke=gt.jsx(se,{...Ae,children:ln});if(Mt&&(Ke=gt.jsx(IC,{value:Mt,children:Ke})),R.isolatedState){const Te=typeof R.isolatedState=="object"?R.isolatedState:{},$e=e?._isolatedInit,Re=$e?{...Te,...$e}:Te;Ke=gt.jsx(VC,{initialState:Re,scopeId:R.isolatedScopeId,children:Ke})}return Ke},[Be,R.iteration,R.sortable,R.itemTemplate,R.type,R.name,R.id,R.props,R.isolatedState,R.isolatedScopeId,a,bn,ln,Br,na,N,On,S,v,_,A,x,O,e._global?._remountKeys]),sr=H.useMemo(()=>{const V=R.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const Z=vt(V);if(Z!==null)try{const ve={componentId:R.id,componentName:R.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,ee,ve)}catch(ve){return st.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${R.id}):`,ve),!1}return!1}if(typeof V=="object"&&V!==null){if(!V.enabled)return!1;if(V.data_sources)return(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).some(we=>e[we]===void 0);if(ue)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ge=>!Z.includes(ge)&&!ge.startsWith("_")).some(ge=>e[ge]===void 0)}if(ue)return!0;const se=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!se.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[R.blur_until_loaded,R.id,ue,e,ee,i,vt]);if(sr){const V=R.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const ce=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((ve,ge)=>(ve[ge]=e[ge]===void 0?"UNDEFINED":"LOADED",ve),{}),Z=Object.keys(e).filter(ve=>!ve.startsWith("_"));st.log(`[BLUR APPLIED] Component: ${R.id}, data_sources status:`,ce,"Available keys:",Z)}else st.log(`[BLUR APPLIED] Component: ${R.id}, blur_until_loaded:`,V)}const cn=H.useMemo(()=>{if(!R.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=_t?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const se=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],ce=V.split(/\s+/).filter(Boolean),Z=[],ve=[];for(const ge of ce)se.some(Ae=>Ae.test(ge))?Z.push(ge):ve.push(ge);return{wrapperClasses:Z.join(" "),innerClasses:ve.join(" ")}},[R.blur_until_loaded,_t?.className]),Tn=window.__slotContextValue;return ke&&Tn?.isEnabled?null:gt.jsx(q_,{componentId:o.id,componentName:o.name,children:R.blur_until_loaded?gt.jsx("div",{className:[cn.wrapperClasses,sr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:ra}):ra})});Ur.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Ur);function G_(o){const e={};try{const a=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of a.keys()){if(i.has(l))continue;i.add(l);const c=a.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function V_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const wi=class wi{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return wi.instance||(wi.instance=new wi),wi.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const n={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const a=this.findMismatchedLeafPaths(e,n);return{hasMismatch:a.length>0,mismatchedPaths:a,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,a=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=a?`${a}.${c}`:c,f=e?.[c],g=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=g&&typeof g=="object"&&!Array.isArray(g);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const S=f===void 0?"__undefined__":JSON.stringify(f),v=g===void 0?"__undefined__":JSON.stringify(g);S!==v&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(a=>{try{a(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const a=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,n,a=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=a?`${a}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=a?`${a}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(a=>a.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),a={};for(const l of this.actionHistory)a[l.type]=(a[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const n={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(n),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let n=0,a=0,i=0,l=0;const c={},d={};for(const g of e)g.decision==="cache_hit"?n++:g.decision==="cache_miss"?a++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,c[g.reason]=(c[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=n+a+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:a,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let a=[...this.cacheDecisions];return n&&(a=a.filter(i=>i.decision===n)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},a=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!a.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?n[i]=`{${c.join(", ")}}`:n[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const a=this.summarizePropsForLifecycle(n.props),i={...n,props:a,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(l=>l.type===n);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,a]of this.eventListeners)this.mountedComponents.has(n)||e.push(...a.map(i=>({...i,componentId:n})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(g=>g.type==="render"),a=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of n)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const c=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,S)=>y+S,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of a)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:a.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,a){if(!this.config.enabled)return"";const i=this.generateId(),l=V_(e),c=G_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,a){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(a)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:n,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,n,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,a,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:a,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,n,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==a&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:a,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],a=this.getState();return n.push({name:"_global",value:a._global,source:"global"}),n.push({name:"_local",value:a._local,source:"local"}),n.push({name:"_computed",value:a._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,n,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:a,trackedAt:Date.now()})}trackFormChange(e,n,a){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:a,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,n,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,a,i){const l=a.map(f=>{const g=[];let m=!0;return f.name||(g.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(g.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:g}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const c={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=c:this.formBindingValidations.push(c),c}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const a=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:n,topIssues:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,g={id:f,name:e,expression:n,componentId:c,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(a)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:g,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(f);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=l)}analyzeComputedDependencyChain(e,n){const a=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),a.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};a.add(m),i.push(m);const S=this.computedProperties.get(`computed-${m}-${n||"global"}`),v=[];if(S)for(const _ of S.dependencies)_.type==="computed"?v.push(f(_.path,y+1)):v.push({name:_.path,type:_.type,children:[],depth:y+1});return i.pop(),a.delete(m),{name:m,type:"computed",children:v,depth:y}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),a=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},a={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,n[g.computedName]=(n[g.computedName]||0)+1,a[g.computedName]||(a[g.computedName]=[]),a[g.computedName].push(g.computationTime),i+=g.computationTime;const c=Object.entries(n).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(a).map(([g,m])=>({name:g,avgTime:m.reduce((y,S)=>y+S,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:c,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,n),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,n){if(!this.config.enabled)return;const a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),n&&(a.currentState={...n}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,n){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const a=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const a=e.initialState[n],i=e.currentState[n];if(a!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:a})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},a={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,a[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(n)}detectExpressionWarning(e){const{expression:n,result:a,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(a);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(a).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(g=>g.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(c&&c>10)return{type:"slow-evaluation",message:`표현식 평가에 ${c.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(a=>a.expression.toLowerCase().includes(n)||a.componentName?.toLowerCase().includes(n)||a.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),a=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),c={};for(const f of e)c[f.resultType]=(c[f.resultType]||0)+1;const d={};for(const f of a)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,0)/l.length:0,byType:c,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],n)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,n){if(!n)return e;const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const n=[...this.stateHistory].reverse().find(a=>a.timestamp<=e);if(n)return{_global:n.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,n,a){if(!this.config.enabled)return;const i=a.map(c=>{if(typeof c=="string")return c;try{return JSON.stringify(c)}catch{return String(c)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(a),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(a=>a.handler.includes(e.handler))),e?.status&&(n=n.filter(a=>a.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(a=>a.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(n=n.filter(a=>a.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)a[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:a,byPrefix:i,recentErrors:l,recentWarnings:c}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=a;n&&(Array.isArray(n)?(l=n.length,c=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,c=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,c=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):c=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"error",error:n,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let n=this.dataPathTransforms.find(a=>a.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let a=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,a+=c.warnings.length;for(const d of c.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([c,d])=>({warning:c,count:d})).sort((c,d)=>d.count-c.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:a,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,a=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:a,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const a=this.nestedContexts.find(i=>i.id===e);a&&a.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let a=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>a&&(a=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const c=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:a,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),a=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,a,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:a,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(c),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((n,a)=>n+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,n,a,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const c={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(a),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(c),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,a,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:a,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=n.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),a={};for(const[i,l]of this.stateToComponentMap)a[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),a=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),c=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:a,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:a,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,a,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:a,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),c){const f=this.contextFlowNodes.get(c);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),a=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const c=Object.keys(e);return`{${c.slice(0,5).join(", ")}${c.length>5?`, ... +${c.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(c=>this.summarizeValues(c,n,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,a+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[l,c]of this.dynamicStates)c&&Object.keys(c).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:c,priority:2});const i=this.computeEffectiveState(a._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,a]of this.dynamicStates)a._local&&Object.assign(n,a._local);return n}detectStateConflicts(e){const n=[],a=e.find(l=>l.type==="global"&&l.path==="_local");if(!a)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const c=l.values._local||l.values;for(const[d,f]of Object.entries(c)){const g=a.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],y=[];for(const S of this.componentStateSources.values())S.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(S.stateProvider.type==="dynamicState"?m.push(S.componentName):S.stateProvider.type==="globalState"&&y.push(S.componentName));n.push({path:`_local.${d}`,globalValue:g,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)n.delete(i.componentId);for(const a of n){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,n,a,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(a),c={componentId:e,componentName:n,classes:a,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],a=[],i=[],l=[],c=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const g of c)if(f.startsWith(g)){a.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:a,computedStyles:i,tailwindAnalysis:l}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:n,componentName:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const c=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));c.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:a,property:"background-color",currentValue:c.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${c[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:a,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,a,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:a,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,a,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:a,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(c),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=n?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=a?.getUser?.();if(d&&(c="AuthManager"),!d){const v=e?.state?.get?.();d=v?._global?.user||v?._global?.currentUser||v?.user||v?.currentUser,d&&(c="G7Core.state")}const f=a?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="sessionStorage");const m=!!i&&(!!d||f);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const S=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.guard_name}),permissions:d.permissions?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:S,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,accessTokenPreview:y},lastActivity:Date.now(),source:c}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,a,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(a),loadedAt:l,version:a.version,layoutName:a.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:a.version};this.layoutHistory.push(c),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const n=`exec_${++this.executionIdCounter}_${Date.now()}`,a={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,a),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(c=>this.executionDetails.delete(c))}return n}endHandlerExecution(e,n,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=a,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${a||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=a,l.exitDescription=i)}recordStateChange(e,n,a,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:a,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(c)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),c.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,a,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:a,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(c)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,a){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of a.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of a.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const a={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const a=this.getValueType(e),i=this.getValueType(n),l=a!==i;let c=!1,d;return!l&&(a==="object"||a==="array")?(c=this.deepEqual(e,n),!c&&a==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:a,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const a=Object.keys(e),i=Object.keys(n);if(a.length!==i.length)return!1;for(const l of a)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const a=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||a.push(l);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:n,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const n of this.changeAlerts)e[n.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,n){let a=[...this.changeAlerts];return n&&(a=a.filter(i=>i.severity===n)),a.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,a={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),n}captureSequenceActionBefore(e,n,a,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:a,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};c.actions.push(d)}captureSequenceActionAfter(e,n,a,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(c=>c.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(a,1)}computeStateDiff(e,n){const a=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||a.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const g=e[f],m=n[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:a,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,a=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),c=n>0?e.reduce((g,m)=>g+m.totalDuration,0)/n:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:n,successCount:a,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,a){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(a[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,a,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[g,m]of c){const y=this.getValueByPath(a,g),S=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&S>0){const v=this.createStaleClosureWarning(i,n,g,m.value,m.capturedAt,y,d,S,l);f.push(v),this.addStaleClosureWarning(v)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,n,a,i,l,c,d,f,g,m){const y=this.getStaleClosureSeverity(e,f),{description:S,suggestion:v,docLink:_}=this.getStaleClosureMessages(e,a,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:a,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:S,suggestion:v,docLink:_,actionId:g,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,n,a){const i=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const a={info:0,warning:0,error:0};for(const f of e)a[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:a,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let a=[...this.staleClosureWarnings];return n&&(a=a.filter(i=>i.severity===n)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const n={};for(const a of Object.keys(e))try{n[a]=JSON.parse(JSON.stringify(e[a]))}catch{n[a]="[Unserializable]"}return n}}};$(wi,"instance");let Oa=wi;const Kn=ht("LayoutLoader");class Er extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="LayoutLoaderError"}}class mf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Kn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const a=`${e}:${n}`;if(this.layoutCache.has(a)){Kn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(a),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Oa.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(a,i),i.catch(()=>{this.layoutCache.get(a)===i&&this.layoutCache.delete(a)}),i}async fetchLayout(e,n,a=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const S=n.replace("__preview__/","");l=Nr(`/api/layouts/preview/${S}`,"json",i)}else l=Nr(`/api/layouts/${e}/${n}`,"json",i);Kn.log("Fetching layout from API:",l);const c=Hr(),d=a?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await Il(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!a&&d){Kn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(v){throw v instanceof Er&&v.details?.status===401?new Er(v.message,v.code,{...v.details,hadToken:!0}):v}}const S=m?.message||m?.error;throw new Er(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:S})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,Oa.getInstance().trackLayoutLoad(n,e,y,"api"),Kn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Er?i:new Er("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Er("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Er("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Er('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Kn.log("Layout data validation passed")}renderLayout(e,n){try{const a=n||this.currentLayout;if(!a)throw new Er("No layout data to render","NO_LAYOUT_DATA");Kn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Kn.log("Layout rendered successfully")}catch(a){Kn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,n){for(const a of n){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Kn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(n){return Kn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=`

Component not found: ${e}

@@ -102,8 +102,8 @@ Error generating stack: `+u.message+` " >페이지 새로고침 - `,Kn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Kn.log("Layout data and cache cleared")}}const F_=ht("TranslationContext"),mf=H.createContext(null),vc=({children:o,translationEngine:e,translationContext:n})=>{const a=H.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=H.useMemo(()=>({translationEngine:e,translationContext:n,t:a}),[e,n,a]);return gt.jsx(mf.Provider,{value:i,children:o})},dy=()=>{const o=H.useContext(mf);return o||(F_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},La=ht("SlotContext"),K_={registerToSlot:()=>{La.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{La.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},W_=H.createContext(K_),yf=({children:o})=>{const e=H.useRef(new Map),n=H.useRef(new Map),a=H.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(S=>{try{S()}catch(v){La.error(`Slot subscriber error (slotId: ${m}):`,v)}})},[]),i=H.useCallback((m,y,S)=>{if(!m||!y){La.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const v=e.current.get(m),_=v.get(y);_&&_.registrationKey===S.registrationKey||(v.set(y,S),La.log(`Component registered to slot: ${y} -> ${m} (order: ${S.order})`),a(m))},[a]),l=H.useCallback((m,y)=>{const S=e.current.get(m);S&&S.has(y)&&(S.delete(y),La.log(`Component unregistered from slot: ${y} <- ${m}`),S.size===0&&e.current.delete(m),a(m))},[a]),c=H.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((S,v)=>S.order-v.order):[]},[]),d=H.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const S=n.current.get(m);return S.add(y),()=>{S.delete(y),S.size===0&&n.current.delete(m)}},[]),f=H.useCallback(()=>{e.current.forEach((m,y)=>{a(y)}),e.current.clear(),n.current.clear(),La.log("All slots cleared")},[a]),g=H.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return H.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,La.log("SlotContext exposed to window.__slotContextValue"))},[g]),gt.jsx(W_.Provider,{value:g,children:o})};class bf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}class fy{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function Y_(o){try{return Reflect.construct(String,[],o),!0}catch{return!1}}class vf extends bf{constructor(e,n,a){super(),this.name=n,this.pusher=e,this.options=a,this.eventFormatter=new fy(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,a)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,a)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class hy extends vf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class X_ extends vf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class J_ extends hy{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(a=>n.members[a]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class gy extends bf{constructor(e,n,a){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=a,this.eventFormatter=new fy(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(a,i)=>{this.name===a&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(a=>a!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class py extends gy{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class Q_ extends py{here(e){return this.on("presence:subscribed",n=>{e(n.map(a=>a.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class Sc extends bf{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class my extends Sc{whisper(e,n){return this}}class Z_ extends Sc{whisper(e,n){return this}}class eA extends my{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Tc=class Tc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Tc._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){return typeof window<"u"&&window.Laravel?.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")??null:null}};Tc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let ko=Tc;class wc extends ko{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,n,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new vf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new hy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new X_(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new J_(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},a=["state_change","connected","disconnected"];return a.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{a.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class tA extends ko{constructor(){super(...arguments),this.channels={}}connect(){const e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(n=>{n.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,n,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new gy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new py(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Q_(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},a=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return a.forEach(i=>{this.socket.on(i,n)}),()=>{a.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class yy extends ko{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,a){return new Sc}channel(e){return new Sc}privateChannel(e){return new my}encryptedPrivateChannel(e){return new Z_}presenceChannel(e){return new eA}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class nA{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new wc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new wc(this.options);else if(this.options.broadcaster==="ably")this.connector=new wc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new tA(this.options);else if(this.options.broadcaster==="null")this.connector=new yy(this.options);else if(typeof this.options.broadcaster=="function"&&Y_(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,n,a){return this.connector.listen(e,n,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof wc||e instanceof yy}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&Vue?.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var Sf={exports:{}};var by;function rA(){return by||(by=1,(function(o,e){(function(a,i){o.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var M=function(T,D){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(z,P){z.__proto__=P}||function(z,P){for(var q in P)P.hasOwnProperty(q)&&(z[q]=P[q])},M(T,D)};return function(T,D){M(T,D);function z(){this.constructor=T}T.prototype=D===null?Object.create(D):(z.prototype=D.prototype,new z)}})();Object.defineProperty(d,"__esModule",{value:!0});var g=256,m=(function(){function M(T){T===void 0&&(T="="),this._paddingCharacter=T}return M.prototype.encodedLength=function(T){return this._paddingCharacter?(T+2)/3*4|0:(T*8+5)/6|0},M.prototype.encode=function(T){for(var D="",z=0;z>>18&63),D+=this._encodeByte(P>>>12&63),D+=this._encodeByte(P>>>6&63),D+=this._encodeByte(P>>>0&63)}var q=T.length-z;if(q>0){var P=T[z]<<16|(q===2?T[z+1]<<8:0);D+=this._encodeByte(P>>>18&63),D+=this._encodeByte(P>>>12&63),q===2?D+=this._encodeByte(P>>>6&63):D+=this._paddingCharacter||"",D+=this._paddingCharacter||""}return D},M.prototype.maxDecodedLength=function(T){return this._paddingCharacter?T/4*3|0:(T*6+7)/8|0},M.prototype.decodedLength=function(T){return this.maxDecodedLength(T.length-this._getPaddingLength(T))},M.prototype.decode=function(T){if(T.length===0)return new Uint8Array(0);for(var D=this._getPaddingLength(T),z=T.length-D,P=new Uint8Array(this.maxDecodedLength(z)),q=0,W=0,he=0,Ee=0,be=0,Ue=0,Fe=0;W>>4,P[q++]=be<<4|Ue>>>2,P[q++]=Ue<<6|Fe,he|=Ee&g,he|=be&g,he|=Ue&g,he|=Fe&g;if(W>>4,he|=Ee&g,he|=be&g),W>>2,he|=Ue&g),W>>8&6,D+=51-T>>>8&-75,D+=61-T>>>8&-15,D+=62-T>>>8&3,String.fromCharCode(D)},M.prototype._decodeChar=function(T){var D=g;return D+=(42-T&T-44)>>>8&-g+T-43+62,D+=(46-T&T-48)>>>8&-g+T-47+63,D+=(47-T&T-58)>>>8&-g+T-48+52,D+=(64-T&T-91)>>>8&-g+T-65+0,D+=(96-T&T-123)>>>8&-g+T-97+26,D},M.prototype._getPaddingLength=function(T){var D=0;if(this._paddingCharacter){for(var z=T.length-1;z>=0&&T[z]===this._paddingCharacter;z--)D++;if(T.length<4||D>2)throw new Error("Base64Coder: incorrect padding")}return D},M})();d.Coder=m;var y=new m;function S(M){return y.encode(M)}d.encode=S;function v(M){return y.decode(M)}d.decode=v;var _=(function(M){f(T,M);function T(){return M!==null&&M.apply(this,arguments)||this}return T.prototype._encodeByte=function(D){var z=D;return z+=65,z+=25-D>>>8&6,z+=51-D>>>8&-75,z+=61-D>>>8&-13,z+=62-D>>>8&49,String.fromCharCode(z)},T.prototype._decodeChar=function(D){var z=g;return z+=(44-D&D-46)>>>8&-g+D-45+62,z+=(94-D&D-96)>>>8&-g+D-95+63,z+=(47-D&D-58)>>>8&-g+D-48+52,z+=(64-D&D-91)>>>8&-g+D-65+0,z+=(96-D&D-123)>>>8&-g+D-97+26,z},T})(m);d.URLSafeCoder=_;var A=new _;function x(M){return A.encode(M)}d.encodeURLSafe=x;function O(M){return A.decode(M)}d.decodeURLSafe=O,d.encodedLength=function(M){return y.encodedLength(M)},d.maxDecodedLength=function(M){return y.maxDecodedLength(M)},d.decodedLength=function(M){return y.decodedLength(M)}},978(c,d){var f="utf8: invalid source encoding";function g(m){for(var y=[],S=0;S=m.length)throw new Error(f);var A=m[++S];if((A&192)!==128)throw new Error(f);v=(v&31)<<6|A&63,_=128}else if(v<240){if(S>=m.length-1)throw new Error(f);var A=m[++S],x=m[++S];if((A&192)!==128||(x&192)!==128)throw new Error(f);v=(v&15)<<12|(A&63)<<6|x&63,_=2048}else if(v<248){if(S>=m.length-2)throw new Error(f);var A=m[++S],x=m[++S],O=m[++S];if((A&192)!==128||(x&192)!==128||(O&192)!==128)throw new Error(f);v=(v&15)<<18|(A&63)<<12|(x&63)<<6|O&63,_=65536}else throw new Error(f);if(v<_||v>=55296&&v<=57343)throw new Error(f);if(v>=65536){if(v>1114111)throw new Error(f);v-=65536,y.push(String.fromCharCode(55296|v>>10)),v=56320|v&1023}}y.push(String.fromCharCode(v))}return y.join("")}d.D4=g},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>_s});class g{constructor(b,w){this.lastId=0,this.prefix=b,this.name=w}create(b){this.lastId++;var w=this.lastId,L=this.prefix+w,I=this.name+"["+w+"]",re=!1,me=function(){re||(b.apply(null,arguments),re=!0)};return this[w]=me,{number:w,id:L,name:I,callback:me}}remove(b){delete this[b.number]}}var m=new g("_pusher_script_","Pusher.ScriptReceivers"),y={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};const S=y;class v{constructor(b){this.options=b,this.receivers=b.receivers||m,this.loading={}}load(b,w,L){var I=this;if(I.loading[b]&&I.loading[b].length>0)I.loading[b].push(L);else{I.loading[b]=[L];var re=ze.createScriptRequest(I.getPath(b,w)),me=I.receivers.create(function(Le){if(I.receivers.remove(me),I.loading[b]){var We=I.loading[b];delete I.loading[b];for(var dt=function(Pt){Pt||re.cleanup()},pt=0;pt>>6)+J(128|b&63):J(224|b>>>12&15)+J(128|b>>>6&63)+J(128|b&63)},te=function(E){return E.replace(/[^\x00-\x7F]/g,Me)},pe=function(E){var b=[0,2,1][E.length%3],w=E.charCodeAt(0)<<16|(E.length>1?E.charCodeAt(1):0)<<8|(E.length>2?E.charCodeAt(2):0),L=[ue.charAt(w>>>18),ue.charAt(w>>>12&63),b>=2?"=":ue.charAt(w>>>6&63),b>=1?"=":ue.charAt(w&63)];return L.join("")},N=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,pe)};class R{constructor(b,w,L,I){this.clear=w,this.timer=b(()=>{this.timer&&(this.timer=I(this.timer))},L)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const de=R;function fe(E){window.clearTimeout(E)}function xe(E){window.clearInterval(E)}class ee extends de{constructor(b,w){super(setTimeout,fe,b,function(L){return w(),null})}}class _e extends de{constructor(b,w){super(setInterval,xe,b,function(L){return w(),L})}}var Be={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new ee(0,E)},method(E,...b){var w=Array.prototype.slice.call(arguments,1);return function(L){return L[E].apply(L,w.concat(arguments))}}};const ke=Be;function Ie(E,...b){for(var w=0;w{window.console&&window.console.log&&window.console.log(b)}}debug(...b){this.log(this.globalLog,b)}warn(...b){this.log(this.globalLogWarn,b)}error(...b){this.log(this.globalLogError,b)}globalLogWarn(b){window.console&&window.console.warn?window.console.warn(b):this.globalLog(b)}globalLogError(b){window.console&&window.console.error?window.console.error(b):this.globalLogWarn(b)}log(b,...w){var L=Ct.apply(this,arguments);_s.log?_s.log(L):_s.logToConsole&&b.bind(this)(L)}}const rt=new On;var jn=function(E,b,w,L,I){(w.headers!==void 0||w.headersProvider!=null)&&rt.warn(`To send headers with the ${L.toString()} request, you must use AJAX, rather than JSONP.`);var re=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var me=E.getDocument(),Le=me.createElement("script");E.auth_callbacks[re]=function(pt){I(null,pt)};var We="Pusher.auth_callbacks['"+re+"']";Le.src=w.endpoint+"?callback="+encodeURIComponent(We)+"&"+b;var dt=me.getElementsByTagName("head")[0]||me.documentElement;dt.insertBefore(Le,dt.firstChild)};const bn=jn;class ra{constructor(b){this.src=b}send(b){var w=this,L="Error loading "+w.src;w.script=document.createElement("script"),w.script.id=b.id,w.script.src=w.src,w.script.type="text/javascript",w.script.charset="UTF-8",w.script.addEventListener?(w.script.onerror=function(){b.callback(L)},w.script.onload=function(){b.callback(null)}):w.script.onreadystatechange=function(){(w.script.readyState==="loaded"||w.script.readyState==="complete")&&b.callback(null)},w.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(w.errorScript=document.createElement("script"),w.errorScript.id=b.id+"_error",w.errorScript.text=b.name+"('"+L+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(w.script,I.firstChild),w.errorScript&&I.insertBefore(w.errorScript,w.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class sr{constructor(b,w){this.url=b,this.data=w}send(b){if(!this.request){var w=Ci(this.data),L=this.url+"/"+b.number+"?"+w;this.request=ze.createScriptRequest(L),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var cn=function(E,b){return function(w,L){var I="http"+(b?"s":"")+"://",re=I+(E.host||E.options.host)+E.options.path,me=ze.createJSONPRequest(re,w),Le=ze.ScriptReceivers.create(function(We,dt){m.remove(Le),me.cleanup(),dt&&dt.host&&(E.host=dt.host),L&&L(We,dt)});me.send(Le)}},Tn={name:"jsonp",getAgent:cn};const un=Tn;function V(E,b,w){var L=E+(b.useTLS?"s":""),I=b.useTLS?b.hostTLS:b.hostNonTLS;return L+"://"+I+w}function se(E,b){var w="/app/"+E,L="?protocol="+S.PROTOCOL+"&client=js&version="+S.VERSION+(b?"&"+b:"");return w+L}var ce={getInitial:function(E,b){var w=(b.httpPath||"")+se(E,"flash=false");return V("ws",b,w)}},Z={getInitial:function(E,b){var w=(b.httpPath||"/pusher")+se(E);return V("http",b,w)}},ve={getInitial:function(E,b){return V("http",b,b.httpPath||"/pusher")},getPath:function(E,b){return se(E)}};class ge{constructor(){this._callbacks={}}get(b){return this._callbacks[we(b)]}add(b,w,L){var I=we(b);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:w,context:L})}remove(b,w,L){if(!b&&!w&&!L){this._callbacks={};return}var I=b?[we(b)]:vt(this._callbacks);w||L?this.removeCallback(I,w,L):this.removeAllCallbacks(I)}removeCallback(b,w,L){Oe(b,function(I){this._callbacks[I]=Mt(this._callbacks[I]||[],function(re){return w&&w!==re.fn||L&&L!==re.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(b){Oe(b,function(w){delete this._callbacks[w]},this)}}function we(E){return"_"+E}class Ae{constructor(b){this.callbacks=new ge,this.global_callbacks=[],this.failThrough=b}bind(b,w,L){return this.callbacks.add(b,w,L),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,w,L){return this.callbacks.remove(b,w,L),this}unbind_global(b){return b?(this.global_callbacks=Mt(this.global_callbacks||[],w=>w!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,w,L){for(var I=0;I0)for(var I=0;I{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),rt.debug("Connecting",{transport:this.name,url:b}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(b){return this.state==="open"?(ke.defer(()=>{this.socket&&this.socket.send(b)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(b){this.emit("error",{type:"WebSocketError",error:b}),this.timeline.error(this.buildTimelineMessage({error:b.toString()}))}onClose(b){b?this.changeState("closed",{code:b.code,reason:b.reason,wasClean:b.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(b){this.emit("message",b)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=b=>{this.onError(b)},this.socket.onclose=b=>{this.onClose(b)},this.socket.onmessage=b=>{this.onMessage(b)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(b,w){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:w})),this.emit(b,w)}buildTimelineMessage(b){return Ie({cid:this.id},b)}}class Te{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,w,L,I){return new Ke(this.hooks,b,w,L,I)}}var $e=new Te({urls:ce,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!ze.getWebSocketAPI()},isSupported:function(){return!!ze.getWebSocketAPI()},getSocket:function(E){return ze.createWebSocket(E)}}),Re={urls:Z,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},et=Ie({getSocket:function(E){return ze.HTTPFactory.createStreamingSocket(E)}},Re),je=Ie({getSocket:function(E){return ze.HTTPFactory.createPollingSocket(E)}},Re),Ve={isSupported:function(){return ze.isXHRSupported()}},Se=new Te(Ie({},et,Ve)),He=new Te(Ie({},je,Ve)),tt={ws:$e,xhr_streaming:Se,xhr_polling:He};const Tt=tt;var It=new Te({file:"sockjs",urls:ve,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(E,b){return new window.SockJS(E,null,{js_path:A.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(E,b){E.send(JSON.stringify({path:b}))}}),Ln={isSupported:function(E){var b=ze.isXDRSupported(E.useTLS);return b}},zt=new Te(Ie({},et,Ln)),Ut=new Te(Ie({},je,Ln));Tt.xdr_streaming=zt,Tt.xdr_polling=Ut,Tt.sockjs=It;const Rn=Tt;class $a extends Ae{constructor(){super();var b=this;typeof window<"u"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){b.emit("online")},!1),window.addEventListener("offline",function(){b.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var jo=new $a;class Tf{constructor(b,w,L){this.manager=b,this.transport=w,this.minPingDelay=L.minPingDelay,this.maxPingDelay=L.maxPingDelay,this.pingDelay=void 0}createConnection(b,w,L,I){I=Ie({},I,{activityTimeout:this.pingDelay});var re=this.transport.createConnection(b,w,L,I),me=null,Le=function(){re.unbind("open",Le),re.bind("closed",We),me=ke.now()},We=dt=>{if(re.unbind("closed",We),dt.code===1002||dt.code===1003)this.manager.reportDeath();else if(!dt.wasClean&&me){var pt=ke.now()-me;pt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(pt/2,this.minPingDelay))}};return re.bind("open",Le),re}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const kc={decodeMessage:function(E){try{var b=JSON.parse(E.data),w=b.data;if(typeof w=="string")try{w=JSON.parse(b.data)}catch{}var L={event:b.event,channel:b.channel,data:w};return b.user_id&&(L.user_id=b.user_id),L}catch(I){throw{type:"MessageParseError",error:I,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var b=kc.decodeMessage(E);if(b.event==="pusher:connection_established"){if(!b.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:b.data.socket_id,activityTimeout:b.data.activity_timeout*1e3}}else{if(b.event==="pusher:error")return{action:this.getCloseAction(b.data),error:this.getCloseError(b.data)};throw"Invalid handshake"}},getCloseAction:function(E){return E.code<4e3?E.code>=1002&&E.code<=1004?"backoff":null:E.code===4e3?"tls_only":E.code<4100?"refused":E.code<4200?"backoff":E.code<4300?"retry":"refused"},getCloseError:function(E){return E.code!==1e3&&E.code!==1001?{type:"PusherError",data:{code:E.code,message:E.reason||E.message}}:null}},qr=kc;class Ei extends Ae{constructor(b,w){super(),this.id=b,this.transport=w,this.activityTimeout=w.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,w,L){var I={event:b,data:w};return L&&(I.channel=L),rt.debug("Event sent",I),this.send(qr.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:L=>{var I;try{I=qr.decodeMessage(L)}catch(re){this.emit("error",{type:"MessageParseError",error:re,data:L.data})}if(I!==void 0){switch(rt.debug("Event recd",I),I.event){case"pusher:error":this.emit("error",{type:"PusherError",data:I.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",I)}},activity:()=>{this.emit("activity")},error:L=>{this.emit("error",L)},closed:L=>{w(),L&&L.code&&this.handleCloseEvent(L),this.transport=null,this.emit("closed")}},w=()=>{Ot(b,(L,I)=>{this.transport.unbind(I,L)})};Ot(b,(L,I)=>{this.transport.bind(I,L)})}handleCloseEvent(b){var w=qr.getCloseAction(b),L=qr.getCloseError(b);L&&this.emit("error",L),w&&this.emit(w,{action:w,error:L})}}class zo{constructor(b,w){this.transport=b,this.callback=w,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var w;try{w=qr.processHandshake(b)}catch(L){this.finish("error",{error:L}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new Ei(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var w=qr.getCloseAction(b)||"backoff",L=qr.getCloseError(b);this.finish(w,{error:L})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(b,w){this.callback(Ie({transport:this.transport,action:b},w))}}class Na{constructor(b,w){this.timeline=b,this.options=w||{}}send(b,w){this.timeline.isEmpty()||this.timeline.send(ze.TimelineTransport.getAgent(this,b),w)}}class Gr extends Ae{constructor(b,w){super(function(L,I){rt.debug("No callbacks on "+b+" for "+L)}),this.name=b,this.pusher=w,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,w){return w(null,{auth:""})}trigger(b,w){if(b.indexOf("client-")!==0)throw new D("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var L=M.buildLogSuffix("triggeringClientEvents");rt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${L}`)}return this.pusher.send_event(b,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var w=b.event,L=b.data;if(w==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(w==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(w.indexOf("pusher_internal:")!==0){var I={};this.emit(w,L,I)}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",b.data)}handleSubscriptionCountEvent(b){b.data.subscription_count&&(this.subscriptionCount=b.data.subscription_count),this.emit("pusher:subscription_count",b.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(b,w)=>{b?(this.subscriptionPending=!1,rt.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof Ue?{status:b.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:w.auth,channel_data:w.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class aa extends Gr{authorize(b,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},w)}}class Ia{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){Ot(this.members,(w,L)=>{b(this.get(L))})}setMyID(b){this.myID=b}onSubscription(b){this.members=b.presence.hash,this.count=b.presence.count,this.me=this.get(this.myID)}addMember(b){return this.get(b.user_id)===null&&this.count++,this.members[b.user_id]=b.user_info,this.get(b.user_id)}removeMember(b){var w=this.get(b.user_id);return w&&(delete this.members[b.user_id],this.count--),w}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Zt=function(E,b,w,L){function I(re){return re instanceof w?re:new w(function(me){me(re)})}return new(w||(w=Promise))(function(re,me){function Le(pt){try{dt(L.next(pt))}catch(Pt){me(Pt)}}function We(pt){try{dt(L.throw(pt))}catch(Pt){me(Pt)}}function dt(pt){pt.done?re(pt.value):I(pt.value).then(Le,We)}dt((L=L.apply(E,b||[])).next())})};class Dc extends aa{constructor(b,w){super(b,w),this.members=new Ia}authorize(b,w){super.authorize(b,(L,I)=>Zt(this,void 0,void 0,function*(){if(!L)if(I=I,I.channel_data!=null){var re=JSON.parse(I.channel_data);this.members.setMyID(re.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let me=M.buildLogSuffix("authorizationEndpoint");rt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${me}, or the user should be signed in.`),w("Invalid auth response");return}w(L,I)}))}handleEvent(b){var w=b.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var L=b.data,I={};b.user_id&&(I.user_id=b.user_id),this.emit(w,L,I)}}handleInternalEvent(b){var w=b.event,L=b.data;switch(w){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(b);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(b);break;case"pusher_internal:member_added":var I=this.members.addMember(L);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var re=this.members.removeMember(L);re&&this.emit("pusher:member_removed",re);break}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(b.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Oc=f(978),Tr=f(594);class Ha extends aa{constructor(b,w,L){super(b,w),this.key=null,this.nacl=L}authorize(b,w){super.authorize(b,(L,I)=>{if(L){w(L,I);return}let re=I.shared_secret;if(!re){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Tr.decode)(re),delete I.shared_secret,w(null,I)})}trigger(b,w){throw new he("Client events are not currently supported for encrypted channels")}handleEvent(b){var w=b.event,L=b.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(w,L)}handleEncryptedEvent(b,w){if(!this.key){rt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){rt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let L=(0,Tr.decode)(w.ciphertext);if(L.length{if(me){rt.error(`Failed to make a request to the authEndpoint: ${Le}. Unable to fetch new key, so dropping encrypted event`);return}if(re=this.nacl.secretbox.open(L,I,this.key),re===null){rt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(re))});return}this.emit(b,this.getDataToEmit(re))}getDataToEmit(b){let w=(0,Oc.D4)(b);try{return JSON.parse(w)}catch{return w}}}class Rf extends Ae{constructor(b,w){super(),this.state="initialized",this.connection=null,this.key=b,this.options=w,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var L=ze.getNetwork();L.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),L.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(b){this.key=b,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(b){return this.connection?this.connection.send(b):!1}send_event(b,w,L){return this.connection?this.connection.send_event(b,w,L):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(w,L)=>{w?this.runner=this.strategy.connect(0,b):L.action==="error"?(this.emit("error",{type:"HandshakeError",error:L.error}),this.timeline.error({handshakeError:L.error})):(this.abortConnecting(),this.handshakeCallbacks[L.action](L))};this.runner=this.strategy.connect(0,b)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var b=this.abandonConnection();b.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(b){this.timeline.info({action:"retry",delay:b}),b>0&&this.emit("connecting_in",Math.round(b/1e3)),this.retryTimer=new ee(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new ee(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new ee(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new ee(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return Ie({},b,{message:w=>{this.resetActivityCheck(),this.emit("message",w)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:w=>{this.emit("error",w)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(b){return Ie({},b,{connected:w=>{this.activityTimeout=Math.min(this.options.activityTimeout,w.activityTimeout,w.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(w.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let b=w=>L=>{L.error&&this.emit("error",{type:"WebSocketError",error:L.error}),w(L)};return{tls_only:b(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:b(()=>{this.disconnect()}),backoff:b(()=>{this.retryIn(1e3)}),retry:b(()=>{this.retryIn(0)})}}setConnection(b){this.connection=b;for(var w in this.connectionCallbacks)this.connection.bind(w,this.connectionCallbacks[w]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var w=this.connection;return this.connection=null,w}}updateState(b,w){var L=this.state;if(this.state=b,L!==b){var I=b;I==="connected"&&(I+=" with new socket ID "+w.socket_id),rt.debug("State changed",L+" -> "+I),this.timeline.info({state:b,params:w}),this.emit("state_change",{previous:L,current:b}),this.emit(b,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Lc{constructor(){this.channels={}}add(b,w){return this.channels[b]||(this.channels[b]=Mc(b,w)),this.channels[b]}all(){return _t(this.channels)}find(b){return this.channels[b]}remove(b){var w=this.channels[b];return delete this.channels[b],w}disconnect(){Ot(this.channels,function(b){b.disconnect()})}}function Mc(E,b){if(E.indexOf("private-encrypted-")===0){if(b.config.nacl)return zn.createEncryptedChannel(E,b,b.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",L=M.buildLogSuffix("encryptedChannelSupport");throw new he(`${w}. ${L}`)}else{if(E.indexOf("private-")===0)return zn.createPrivateChannel(E,b);if(E.indexOf("presence-")===0)return zn.createPresenceChannel(E,b);if(E.indexOf("#")===0)throw new z('Cannot create a channel with name "'+E+'".');return zn.createChannel(E,b)}}var kf={createChannels(){return new Lc},createConnectionManager(E,b){return new Rf(E,b)},createChannel(E,b){return new Gr(E,b)},createPrivateChannel(E,b){return new aa(E,b)},createPresenceChannel(E,b){return new Dc(E,b)},createEncryptedChannel(E,b,w){return new Ha(E,b,w)},createTimelineSender(E,b){return new Na(E,b)},createHandshake(E,b){return new zo(E,b)},createAssistantToTheTransportManager(E,b,w){return new Tf(E,b,w)}};const zn=kf;class _i{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return zn.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class vn{constructor(b,w){this.strategies=b,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return ln(this.strategies,ke.method("isSupported"))}connect(b,w){var L=this.strategies,I=0,re=this.timeout,me=null,Le=(We,dt)=>{dt?w(null,dt):(I=I+1,this.loop&&(I=I%L.length),I0&&(re=new ee(L.timeout,function(){me.abort(),I(!0)})),me=b.connect(w,function(Le,We){Le&&re&&re.isRunning()&&!L.failFast||(re&&re.ensureAborted(),I(Le,We))}),{abort:function(){re&&re.ensureAborted(),me.abort()},forceMinPriority:function(Le){me.forceMinPriority(Le)}}}}class kn{constructor(b){this.strategies=b}isSupported(){return ln(this.strategies,ke.method("isSupported"))}connect(b,w){return $c(this.strategies,b,function(L,I){return function(re,me){if(I[L].error=re,re){Df(I)&&w(!0);return}Oe(I,function(Le){Le.forceMinPriority(me.transport.priority)}),w(null,me)}})}}function $c(E,b,w){var L=nt(E,function(I,re,me,Le){return I.connect(b,w(re,Le))});return{abort:function(){Oe(L,Uo)},forceMinPriority:function(I){Oe(L,function(re){re.forceMinPriority(I)})}}}function Df(E){return Br(E,function(b){return!!b.error})}function Uo(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class Nc{constructor(b,w,L){this.strategy=b,this.transports=w,this.ttl=L.ttl||18e5,this.usingTLS=L.useTLS,this.timeline=L.timeline}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.usingTLS,I=Of(L),re=I&&I.cacheSkipCount?I.cacheSkipCount:0,me=[this.strategy];if(I&&I.timestamp+this.ttl>=ke.now()){var Le=this.transports[I.transport];Le&&(["ws","wss"].includes(I.transport)||re>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),me.push(new vn([Le],{timeout:I.latency*2+1e3,failFast:!0}))):re++)}var We=ke.now(),dt=me.pop().connect(b,function pt(Pt,Or){Pt?(vs(L),me.length>0?(We=ke.now(),dt=me.pop().connect(b,pt)):w(Pt)):(Un(L,Or.transport.name,ke.now()-We,re),w(null,Or))});return{abort:function(){dt.abort()},forceMinPriority:function(pt){b=pt,dt&&dt.forceMinPriority(pt)}}}}function ja(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Of(E){var b=ze.getLocalStorage();if(b)try{var w=b[ja(E)];if(w)return JSON.parse(w)}catch{vs(E)}return null}function Un(E,b,w,L){var I=ze.getLocalStorage();if(I)try{I[ja(E)]=yn({timestamp:ke.now(),transport:b,latency:w,cacheSkipCount:L})}catch{}}function vs(E){var b=ze.getLocalStorage();if(b)try{delete b[ja(E)]}catch{}}class Ai{constructor(b,{delay:w}){this.strategy=b,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.strategy,I,re=new ee(this.options.delay,function(){I=L.connect(b,w)});return{abort:function(){re.ensureAborted(),I&&I.abort()},forceMinPriority:function(me){b=me,I&&I.forceMinPriority(me)}}}}class ia{constructor(b,w,L){this.test=b,this.trueBranch=w,this.falseBranch=L}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,w){var L=this.test()?this.trueBranch:this.falseBranch;return L.connect(b,w)}}class za{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.strategy.connect(b,function(I,re){re&&L.abort(),w(I,re)});return L}}function Ua(E){return function(){return E.isSupported()}}var Ic=function(E,b,w){var L={};function I(el,Xc,Jc,Qf,Zf){var Qc=w(E,el,Xc,Jc,Qf,Zf);return L[el]=Qc,Qc}var re=Object.assign({},b,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),me=Object.assign({},re,{useTLS:!0}),Le=Object.assign({},b,{hostNonTLS:E.httpHost+":"+E.httpPort,hostTLS:E.httpHost+":"+E.httpsPort,httpPath:E.httpPath}),We={loop:!0,timeout:15e3,timeoutLimit:6e4},dt=new _i({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),pt=new _i({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),Pt=I("ws","ws",3,re,dt),Or=I("wss","ws",3,me,dt),Yf=I("sockjs","sockjs",1,Le),Wc=I("xhr_streaming","xhr_streaming",1,Le,pt),Xf=I("xdr_streaming","xdr_streaming",1,Le,pt),Jo=I("xhr_polling","xhr_polling",1,Le),Yc=I("xdr_polling","xdr_polling",1,Le),qa=new vn([Pt],We),Oi=new vn([Or],We),Jf=new vn([Yf],We),Li=new vn([new ia(Ua(Wc),Wc,Xf)],We),Qo=new vn([new ia(Ua(Jo),Jo,Yc)],We),Zo=new vn([new ia(Ua(Li),new kn([Li,new Ai(Qo,{delay:4e3})]),Qo)],We),Mi=new ia(Ua(Zo),Zo,Jf),$i;return b.useTLS?$i=new kn([qa,new Ai(Mi,{delay:2e3})]):$i=new kn([qa,new Ai(Oi,{delay:2e3}),new Ai(Mi,{delay:5e3})]),new Nc(new za(new ia(Ua(Pt),$i,Mi)),L,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})};const Pa=Ic;function Lf(){var E=this;E.timeline.info(E.buildTimelineMessage({transport:E.name+(E.options.useTLS?"s":"")})),E.hooks.isInitialized()?E.changeState("initialized"):E.hooks.file?(E.changeState("initializing"),A.load(E.hooks.file,{useTLS:E.options.useTLS},function(b,w){E.hooks.isInitialized()?(E.changeState("initialized"),w(!0)):(b&&E.onError(b),E.onClose(),w(!1))})):E.onClose()}var Hc={getRequest:function(E){var b=new window.XDomainRequest;return b.ontimeout=function(){E.emit("error",new P),E.close()},b.onerror=function(w){E.emit("error",w),E.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText),E.emit("finished",200),E.close()},b},abortRequest:function(E){E.ontimeout=E.onerror=E.onprogress=E.onload=null,E.abort()}};const jc=Hc,Po=256*1024;class Mf extends Ae{constructor(b,w,L){super(),this.hooks=b,this.method=w,this.url=L}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},ze.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(b)}close(){this.unloader&&(ze.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,w){for(;;){var L=this.advanceBuffer(w);if(L)this.emit("chunk",{status:b,data:L});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(b){var w=b.slice(this.position),L=w.indexOf(` -`);return L!==-1?(this.position+=L+1,w.slice(0,L)):null}isBufferTooLong(b){return this.position===b.length&&b.length>Po}}var Bo;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(Bo||(Bo={}));const or=Bo;var Rr=1;class qo{constructor(b,w){this.hooks=b,this.session=Ss(1e3)+"/"+Uc(8),this.location=Go(w),this.readyState=or.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,w){this.onClose(b,w,!0)}sendRaw(b){if(this.readyState===or.OPEN)try{return ze.createSocketRequest("POST",sa(Ba(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,w,L){this.closeStream(),this.readyState=or.CLOSED,this.onclose&&this.onclose({code:b,reason:w,wasClean:L})}onChunk(b){if(b.status===200){this.readyState===or.OPEN&&this.onActivity();var w,L=b.data.slice(0,1);switch(L){case"o":w=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(b.data.slice(1)||"[]");for(var I=0;I{this.onChunk(b)}),this.stream.bind("finished",b=>{this.hooks.onFinished(this,b)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(b){ke.defer(()=>{this.onError(b),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Go(E){var b=/([^\?]*)\/*(\??.*)/.exec(E);return{base:b[1],queryString:b[2]}}function Ba(E,b){return E.base+"/"+b+"/xhr_send"}function sa(E){var b=E.indexOf("?")===-1?"?":"&";return E+b+"t="+ +new Date+"&n="+Rr++}function zc(E,b){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+b+w[3]}function Ss(E){return ze.randomInt(E)}function Uc(E){for(var b=[],w=0;w0&&E.onChunk(w.status,w.responseText);break;case 4:w.responseText&&w.responseText.length>0&&E.onChunk(w.status,w.responseText),E.emit("finished",w.status),E.close();break}},w},abortRequest:function(E){E.onreadystatechange=null,E.abort()}};const ws=Fo;var Pc={createStreamingSocket(E){return this.createSocket(Vo,E)},createPollingSocket(E){return this.createSocket(Vr,E)},createSocket(E,b){return new xi(E,b)},createXHR(E,b){return this.createRequest(ws,E,b)},createRequest(E,b,w){return new Mf(E,b,w)}};const Ri=Pc;Ri.createXDR=function(E,b){return this.createRequest(jc,E,b)};var Bc={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Pa,Transports:Rn,transportConnectionInitializer:Lf,HTTPFactory:Ri,TimelineTransport:un,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(E){if(typeof window<"u"){window.Pusher=E;var b=()=>{this.onDocumentBody(E.ready)};window.JSON?b():A.load("json2",{},b)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Ge,jsonp:bn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,b){return new sr(E,b)},createScriptRequest(E){return new ra(E)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var E=this.getXHRAPI();return new E},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return jo},createWebSocket(E){var b=this.getWebSocketAPI();return new b(E)},createSocketRequest(E,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(E,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(E,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var E=this.getXHRAPI();return!!E&&new E().withCredentials!==void 0},isXDRSupported(E){var b=E?"https:":"http:",w=this.getProtocol();return!!window.XDomainRequest&&w===b},addUnloadListener(E){window.addEventListener!==void 0?window.addEventListener("pagehide",E,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",E)},removeUnloadListener(E){window.addEventListener!==void 0?window.removeEventListener("pagehide",E,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",E)},randomInt(E){const b=window.crypto||window.msCrypto,w=Math.floor(Math.pow(2,32)/E)*E;let L;do L=b.getRandomValues(new Uint32Array(1))[0];while(L>=w);return L%E}};const ze=Bc;var Dr;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Dr||(Dr={}));const oa=Dr;class ki{constructor(b,w,L){this.key=b,this.session=w,this.events=[],this.options=L||{},this.sent=0,this.uniqueID=0}log(b,w){b<=this.options.level&&(this.events.push(Ie({},w,{timestamp:ke.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(oa.ERROR,b)}info(b){this.log(oa.INFO,b)}debug(b){this.log(oa.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,w){var L=Ie({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],b(L,(I,re)=>{I||this.sent++,w&&w(I,re)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class $f{constructor(b,w,L,I){this.name=b,this.priority=w,this.transport=L,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,w){if(this.isSupported()){if(this.priority{L||(pt(),re?re.close():I.close())},forceMinPriority:Pt=>{L||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var L in b.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(b.params[L]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var L in I)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(I[L])}return w},If=E=>{if(typeof ze.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const L=Nf(b,E);ze.getAuthorizers()[E.transport](ze,L,E,T.UserAuthentication,w)}},Yo=(E,b)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var L in b.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(b.params[L]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var L in I)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(I[L])}return w},Hf=E=>{if(typeof ze.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const L=Yo(b,E);ze.getAuthorizers()[E.transport](ze,L,E,T.ChannelAuthorization,w)}},jf=(E,b,w)=>{const L={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(I,re)=>{const me=E.channel(I.channelName);w(me,L).authorize(I.socketId,re)}};function Gc(E,b){let w={activityTimeout:E.activityTimeout||S.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||S.httpPath,httpPort:E.httpPort||S.httpPort,httpsPort:E.httpsPort||S.httpsPort,pongTimeout:E.pongTimeout||S.pongTimeout,statsHost:E.statsHost||S.stats_host,unavailableTimeout:E.unavailableTimeout||S.unavailableTimeout,wsPath:E.wsPath||S.wsPath,wsPort:E.wsPort||S.wsPort,wssPort:E.wssPort||S.wssPort,enableStats:Bf(E),httpHost:zf(E),useTLS:Pf(E),wsHost:Vc(E),userAuthenticator:Xo(E),channelAuthorizer:Gf(E,b)};return"disabledTransports"in E&&(w.disabledTransports=E.disabledTransports),"enabledTransports"in E&&(w.enabledTransports=E.enabledTransports),"ignoreNullOrigin"in E&&(w.ignoreNullOrigin=E.ignoreNullOrigin),"timelineParams"in E&&(w.timelineParams=E.timelineParams),"nacl"in E&&(w.nacl=E.nacl),w}function zf(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:S.httpHost}function Vc(E){return E.wsHost?E.wsHost:Uf(E.cluster)}function Uf(E){return`ws-${E}.pusher.com`}function Pf(E){return ze.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Bf(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const Fc=E=>"customHandler"in E&&E.customHandler!=null;function Xo(E){const b=Object.assign(Object.assign({},S.userAuthentication),E.userAuthentication);return Fc(b)?b.customHandler:If(b)}function qf(E,b){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},S.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||S.authTransport,endpoint:E.authEndpoint||S.authEndpoint},"auth"in E&&("params"in E.auth&&(w.params=E.auth.params),"headers"in E.auth&&(w.headers=E.auth.headers)),"authorizer"in E&&(w.customHandler=jf(b,w,E.authorizer))),w}function Gf(E,b){const w=qf(E,b);return Fc(w)?w.customHandler:Hf(w)}class Vf extends Ae{constructor(b){super(function(w,L){rt.debug(`No callbacks on watchlist events for ${w}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(w=>{this.emit(w.name,w)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var w=b.event;w==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function Kc(){let E,b;return{promise:new Promise((L,I)=>{E=L,b=I}),resolve:E,reject:b}}const Ff=Kc;class Kf extends Ae{constructor(b){super(function(w,L){rt.debug("No callbacks on user for "+w)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(w,L)=>{if(w){rt.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Ue?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:L.auth,user_data:L.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:w,current:L})=>{w!=="connected"&&L==="connected"&&this._signin(),w==="connected"&&L!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Vf(b),this.pusher.connection.bind("message",w=>{var L=w.event;L==="pusher:signin_success"&&this._onSigninSuccess(w.data),this.serverToUserChannel&&this.serverToUserChannel.name===w.channel&&this.serverToUserChannel.handleEvent(w)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(b){try{this.user_data=JSON.parse(b.user_data)}catch{rt.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){rt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=w=>{w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.pusher.connection.state==="connected"&&w.subscribe()};this.serverToUserChannel=new Gr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,L)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,L)}),b(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:b,resolve:w}=Ff();b.done=!1;const L=()=>{b.done=!0};b.then(L).catch(L),this.signinDonePromise=b,this._signinDoneResolve=w}}class dn{static ready(){dn.isReady=!0;for(var b=0,w=dn.instances.length;bze.getDefaultStrategy(this.config,I,Di);this.connection=zn.createConnectionManager(this.key,{getStrategy:L,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",I=>{var re=I.event,me=re.indexOf("pusher_internal:")===0;if(I.channel){var Le=this.channel(I.channel);Le&&Le.handleEvent(I)}me||this.global_emitter.emit(I.event,I.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",I=>{rt.warn(I)}),dn.instances.push(this),this.timeline.info({instances:dn.instances.length}),this.user=new Kf(this),dn.isReady&&this.connect()}switchCluster(b){const{appKey:w,cluster:L}=b;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:L}),this.config=Gc(this.options,this),this.connection.switchCluster(this.key)}channel(b){return this.channels.find(b)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var b=this.connection.isUsingTLS(),w=this.timelineSender;this.timelineSenderTimer=new _e(6e4,function(){w.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,w,L){return this.global_emitter.bind(b,w,L),this}unbind(b,w,L){return this.global_emitter.unbind(b,w,L),this}bind_global(b){return this.global_emitter.bind_global(b),this}unbind_global(b){return this.global_emitter.unbind_global(b),this}unbind_all(b){return this.global_emitter.unbind_all(),this}subscribeAll(){var b;for(b in this.channels.channels)this.channels.channels.hasOwnProperty(b)&&this.subscribe(b)}subscribe(b){var w=this.channels.add(b,this);return w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.connection.state==="connected"&&w.subscribe(),w}unsubscribe(b){var w=this.channels.find(b);w&&w.subscriptionPending?w.cancelSubscription():(w=this.channels.remove(b),w&&w.subscribed&&w.unsubscribe())}send_event(b,w,L){return this.connection.send_event(b,w,L)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}dn.instances=[],dn.isReady=!1,dn.logToConsole=!1,dn.Runtime=ze,dn.ScriptReceivers=ze.ScriptReceivers,dn.DependenciesReceivers=ze.DependenciesReceivers,dn.auth_callbacks=ze.auth_callbacks;const _s=dn;function Wf(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}ze.setup(dn)}},a={};function i(c){var d=a[c];if(d!==void 0)return d.exports;var f=a[c]={exports:{}};return n[c].call(f.exports,f,f.exports,i),f.exports}i.d=(c,d)=>{for(var f in d)i.o(d,f)&&!i.o(c,f)&&Object.defineProperty(c,f,{enumerable:!0,get:d[f]})},i.o=(c,d)=>Object.prototype.hasOwnProperty.call(c,d);var l=i(721);return l})())})(Sf)),Sf.exports}var aA=rA();const vy=Jr(aA),qt=ht("WebSocketManager");class iA{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){qt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,qt.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){qt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:a=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(a)||80,d=i==="https";qt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=vy;const f=localStorage.getItem("auth_token"),g={wsHost:n,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};qt.log("[WebSocketManager] Pusher 옵션:",g);const m=new vy(e,g);m.connection.bind("connecting",()=>{qt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{qt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{qt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{qt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{qt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{qt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{qt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),qt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new nA({broadcaster:"reverb",client:m}),qt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,qt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,a,i={}){if(this.initialize(),!this.echo)return qt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return qt.log(`[WebSocketManager] 이미 구독 중: ${c}`),c;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,a),this.subscriptions.set(c,d),qt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){qt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),qt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(a=>this.subscriptions.delete(a)),qt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,qt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Cc=new iA,bt=ht("DataSourceManager"),Sy=new Dn;function Ec(o,e){const n=Aa(o);if(n!==null)try{return $n(n)?Sy.evaluatePipeExpression(n,e,{skipCache:!0}):Sy.evaluateExpression(n,e)}catch(a){return bt.error("Failed to evaluate param expression:",n,a),o}return rs(o,e,{skipCache:!0})}function wy(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}function sA(){try{return window.G7Core?.devTools}catch{return}}const Rc=class Rc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new Dn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const n=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(a,i):i!=null&&n.append(a,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Ec(c,n);d!=null&&d!==""&&(a[l]=String(d))});return a}filterByCondition(e,n={}){const a=new Set,i=[];for(const l of e){if(a.has(l.id))continue;if(!l.if&&!l.conditions){a.add(l.id),i.push(l);continue}ns({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(a.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:n};if(ns({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return bt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){bt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,n={},a=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,n,a,i,l);c[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(g,m);if(y!==null){const S={status:y,message:`Error condition matched for ${g.id}`,data:m},v=Sr(),_=v.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(_.handler)try{await v.execute(_.handler,S)}catch(A){bt.error(`Error executing errorCondition handler for ${g.id}:`,A)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const S={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,S)}catch(S){bt.error(`Error executing onSuccess handler for ${g.id}:`,S)}}catch(m){bt.error(`Failed to fetch data source: ${g.id}`,m);const y=m?.response?.status||m?.status||500,S=m?.response?.data,v=S?.message||m.message||"Unknown error",_={status:y,message:v,errors:S?.errors,data:S,statusText:m?.response?.statusText},A=Sr(),x=A.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(x.handler)try{await A.execute(x.handler,_)}catch(O){bt.error(`Error executing error handler for ${g.id}:`,O)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),c}async fetchDataSourcesWithResults(e,n={},a=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");bt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=c?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const y=await this.fetchDataSource(m,n,a,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const S=this.checkErrorCondition(m,y);if(S!==null){const v={status:S,message:`Error condition matched for ${m.id}`,data:y},_=Sr(),A=_.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let x=!1;if(A.handler)if(m.loading_strategy==="blocking")_.execute(A.handler,v).catch(O=>{bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}),x=!0;else try{await _.execute(A.handler,v),x=!0}catch(O){bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${S}`),errorCode:S,errorHandled:x}}if(m.onSuccess)try{const v={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,v)}catch(v){bt.error(`Error executing onSuccess handler for ${m.id}:`,v)}return{id:m.id,state:"success",data:y}}catch(y){bt.error(`Failed to fetch data source: ${m.id}`,y);const S=y?.response?.status||y?.status||500,v=y?.response?.data,_=v?.message||y.message||"Unknown error",A={status:S,message:_,errors:v?.errors,data:v,statusText:y?.response?.statusText},x=Sr(),O=x.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(O.handler)if(m.loading_strategy==="blocking")x.execute(O.handler,A).catch(T=>{bt.error(`Error executing error handler for ${m.id}:`,T)}),M=!0;else try{await x.execute(O.handler,A),M=!0}catch(T){bt.error(`Error executing error handler for ${m.id}:`,T)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(y,m),{id:m.id,state:"error",error:y,errorCode:S,errorHandled:M})}}))}fetchDataSourcesInBackground(e,n={},a=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,a).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const g={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Sr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,g)}catch(S){bt.error(`Error executing errorCondition handler for ${c.id}:`,S)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const g={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,g)}catch(g){bt.error(`Error executing onSuccess handler for ${c.id}:`,g)}i&&i(c.id,d)}).catch(async d=>{bt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",y={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},S=Sr(),v=S.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(v.handler)try{await S.execute(v.handler,y)}catch(_){bt.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${c.id}`),i&&i(c.id,c.fallback);return}this.options.onError&&this.options.onError(d,c)})})}async fetchDataSource(e,n,a,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,a,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return wy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,a,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const c={route:n,query:wy(a)};i&&(c._global=i),l&&(c._local=l);let d=rs(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?rs(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([_,A])=>{typeof A=="string"&&(y[_]=Ec(A,c))}),Object.keys(y).forEach(_=>{y[_]===""&&delete y[_]});const S=sA();let v=null;if(S?.isEnabled()){S.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let _=d;if(f==="GET"&&Object.keys(y).length>0){const A=new URLSearchParams;Object.entries(y).forEach(([O,M])=>{Array.isArray(M)?M.forEach(T=>A.append(O,String(T))):M!=null&&A.append(O,String(M))});const x=A.toString();_=x?`${d}?${x}`:d}v=S.trackRequest(_,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),S.trackDataSourceLoading(e.id)}try{let _;const A=e.auth_mode??(e.auth_required===!0?"required":"none"),x=br.getInstance().isAuthenticated();if(A==="required"&&!x){bt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),S?.isEnabled()&&(S.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),v&&S.failRequest(v,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const O=A==="required"||A==="optional"&&x;if(O){const M=Hr(),T=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&bt.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${T}`);const D=this.getMatchingGlobalHeaders(d,c),z={};e.headers&&Object.entries(e.headers).forEach(([he,Ee])=>{const be=Ec(Ee,c);be!=null&&be!==""&&(z[he]=String(be))});const P={...D,...z},q=Object.keys(P).length>0,W=m?this.toFormData(y):y;switch(f){case"GET":_=await M.get(T,{params:y,...q&&{headers:P}});break;case"POST":q?_=await M.post(T,W,{headers:P}):_=await M.post(T,W);break;case"PUT":q?_=await M.put(T,W,{headers:P}):_=await M.put(T,W);break;case"PATCH":q?_=await M.patch(T,W,{headers:P}):_=await M.patch(T,W);break;case"DELETE":_=await M.delete(T,{params:y,...q&&{headers:P}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const W=new URLSearchParams(y).toString();M=W?`${d}?${W}`:d}const T={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const W=localStorage.getItem("g7_locale");W&&(T["Accept-Language"]=W)}const D=this.getMatchingGlobalHeaders(d,c);Object.assign(T,D),e.headers&&Object.entries(e.headers).forEach(([W,he])=>{const Ee=Ec(he,c);Ee!=null&&Ee!==""&&(T[W]=String(Ee))});let z;f!=="GET"&&(m?(z=this.toFormData(y),delete T["Content-Type"]):z=JSON.stringify(y));const P=await fetch(M,{method:f,headers:T,body:z});let q;try{q=await P.json()}catch{q=null}if(v&&S?.isEnabled()&&(S.completeRequest(v,P.status,q),v=null),!P.ok){S?.isEnabled()&&S.trackDataSourceError(e.id,`HTTP ${P.status}: ${P.statusText}`);const W=new Error(`HTTP error! status: ${P.status}`);throw W.response={status:P.status,statusText:P.statusText,data:q},W.status=P.status,W}_=q,S?.isEnabled()&&S.trackDataSourceLoaded(e.id,_)}return O&&v&&S?.isEnabled()&&(S.completeRequest(v,200,_),S.trackDataSourceLoaded(e.id,_)),_}catch(_){if(v&&S?.isEnabled()){const A=_;A?.response?S.completeRequest(v,A.response.status,A.response.data):S.failRequest(v,_ instanceof Error?_.message:String(_)),S.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Rc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,a={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){bt.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=rs(c.channel,a,{skipCache:!0}),f=rs(c.event,a,{skipCache:!0})}catch(y){bt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const g=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(g(d)||g(f)){bt.warn(`WebSocket source ${c.id} has invalid channel/event after expression resolution, skipping. Original channel="${c.channel}", resolved="${d}". Original event="${c.event}", resolved="${f}". Available context keys: [${Object.keys(a).join(", ")}]`);return}const m=Cc.subscribe(d,f,y=>{const S=c.target_source||c.id;this.dataCache.set(S,{data:y,timestamp:Date.now()}),n(S,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Cc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const a=this.options.actionDispatcher??vm();if(!a){bt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await a.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw bt.error("Failed to execute onSuccess handler:",c),c}}};$(Rc,"DATA_CACHE_TTL",3e5);let _r=Rc;const oA=new _r,bi=ht("ModalDataSourceWrapper");function lA(o,e){if(!o||!e)return o;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of a){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const c=parseInt(l.slice(1,-1),10);i=i[c]}else i=i[l]}return i}const Cy=({isOpen:o,modalId:e,dataSources:n,dataContext:a,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,g]=H.useState(!1),[m,y]=H.useState(!1),S=H.useRef(!1),v=H.useRef(null);v.current||(v.current=new _r);const _=H.useCallback(async()=>{if(!(!n||n.length===0)&&v.current){g(!0);try{const A=a.route||{},x=new URLSearchParams(window.location.search),O=n.map(T=>{let D={...T};if(T.endpoint&&l){const z=l.resolveBindings(T.endpoint,a,{skipCache:!0});D.endpoint=z}if(T.params&&l){const z={};Object.entries(T.params).forEach(([P,q])=>{typeof q=="string"?z[P]=l.resolveBindings(q,a,{skipCache:!0}):z[P]=q}),D.params=z}return D});c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,O.map(T=>({id:T.id,endpoint:T.endpoint})));const M=await v.current.fetchDataSourcesWithResults(O,A,x);i&&M.forEach(T=>{if(T.state==="success"&&T.data!==void 0){const D=O.find(z=>z.id===T.id);if(D?.initGlobal){const z=T.data?.data??T.data,P=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const q of P)if(typeof q=="string")i({[q]:z}),c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${T.id}.data -> _global.${q}`);else if(typeof q=="object"&&q.key){const{key:W,path:he}=q,Ee=he?lA(z,he):z;i({[W]:Ee}),c&&bi.log(`Modal "${e}" initGlobal: ${T.id}.data${he?"."+he:""} -> _global.${W}`)}}}else T.state==="error"&&bi.error(`Modal "${e}" data source error:`,T.id,T.error)}),c&&bi.log(`Modal "${e}" data sources fetched successfully`)}catch(A){bi.error(`Modal "${e}" data source fetch error:`,A)}finally{g(!1),y(!0)}}},[n,a,i,l,e,c]);return H.useEffect(()=>{if(!n||n.length===0)return;const A=window.__templateApp;return A?.registerModalDataSources&&A.registerModalDataSources(e,n),()=>{A?.unregisterModalDataSources&&A.unregisterModalDataSources(e)}},[e,n]),H.useEffect(()=>{!o&&S.current&&(y(!1),c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!S.current&&n&&n.length>0&&!m&&_(),S.current=o},[o,n,m,_,e,c]),gt.jsx(gt.Fragment,{children:d})};class _c extends Error{constructor(n,a,i={}){super(a);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(n,a){if(!a||!n)return this.userMessageKey;try{return a.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class cA extends _c{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Ey(o){if(o instanceof _c)return o;if(o instanceof Error){const e=new _c("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new _c("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const uA=ht("ErrorDisplay");class wf{static render(e,n){const a=document.getElementById(e);if(!a){uA.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` + `,Kn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Kn.log("Layout data and cache cleared")}}const F_=ht("TranslationContext"),yf=H.createContext(null),vc=({children:o,translationEngine:e,translationContext:n})=>{const a=H.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=H.useMemo(()=>({translationEngine:e,translationContext:n,t:a}),[e,n,a]);return gt.jsx(yf.Provider,{value:i,children:o})},uy=()=>{const o=H.useContext(yf);return o||(F_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},La=ht("SlotContext"),K_={registerToSlot:()=>{La.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{La.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},W_=H.createContext(K_),bf=({children:o})=>{const e=H.useRef(new Map),n=H.useRef(new Map),a=H.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(S=>{try{S()}catch(v){La.error(`Slot subscriber error (slotId: ${m}):`,v)}})},[]),i=H.useCallback((m,y,S)=>{if(!m||!y){La.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const v=e.current.get(m),_=v.get(y);_&&_.registrationKey===S.registrationKey||(v.set(y,S),La.log(`Component registered to slot: ${y} -> ${m} (order: ${S.order})`),a(m))},[a]),l=H.useCallback((m,y)=>{const S=e.current.get(m);S&&S.has(y)&&(S.delete(y),La.log(`Component unregistered from slot: ${y} <- ${m}`),S.size===0&&e.current.delete(m),a(m))},[a]),c=H.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((S,v)=>S.order-v.order):[]},[]),d=H.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const S=n.current.get(m);return S.add(y),()=>{S.delete(y),S.size===0&&n.current.delete(m)}},[]),f=H.useCallback(()=>{e.current.forEach((m,y)=>{a(y)}),e.current.clear(),n.current.clear(),La.log("All slots cleared")},[a]),g=H.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return H.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,La.log("SlotContext exposed to window.__slotContextValue"))},[g]),gt.jsx(W_.Provider,{value:g,children:o})};class vf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}class dy{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function Y_(o){try{return Reflect.construct(String,[],o),!0}catch{return!1}}class Sf extends vf{constructor(e,n,a){super(),this.name=n,this.pusher=e,this.options=a,this.eventFormatter=new dy(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,a)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,a)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class fy extends Sf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class X_ extends Sf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class J_ extends fy{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(a=>n.members[a]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class hy extends vf{constructor(e,n,a){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=a,this.eventFormatter=new dy(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(a,i)=>{this.name===a&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(a=>a!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class gy extends hy{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class Q_ extends gy{here(e){return this.on("presence:subscribed",n=>{e(n.map(a=>a.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class Sc extends vf{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class py extends Sc{whisper(e,n){return this}}class Z_ extends Sc{whisper(e,n){return this}}class eA extends py{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Tc=class Tc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Tc._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){return typeof window<"u"&&window.Laravel?.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")??null:null}};Tc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let ko=Tc;class wc extends ko{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,n,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new Sf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new fy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new X_(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new J_(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},a=["state_change","connected","disconnected"];return a.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{a.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class tA extends ko{constructor(){super(...arguments),this.channels={}}connect(){const e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(n=>{n.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,n,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new hy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new gy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Q_(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},a=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return a.forEach(i=>{this.socket.on(i,n)}),()=>{a.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class my extends ko{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,a){return new Sc}channel(e){return new Sc}privateChannel(e){return new py}encryptedPrivateChannel(e){return new Z_}presenceChannel(e){return new eA}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class nA{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new wc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new wc(this.options);else if(this.options.broadcaster==="ably")this.connector=new wc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new tA(this.options);else if(this.options.broadcaster==="null")this.connector=new my(this.options);else if(typeof this.options.broadcaster=="function"&&Y_(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,n,a){return this.connector.listen(e,n,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof wc||e instanceof my}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&Vue?.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var wf={exports:{}};var yy;function rA(){return yy||(yy=1,(function(o,e){(function(a,i){o.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var M=function(T,D){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(z,P){z.__proto__=P}||function(z,P){for(var q in P)P.hasOwnProperty(q)&&(z[q]=P[q])},M(T,D)};return function(T,D){M(T,D);function z(){this.constructor=T}T.prototype=D===null?Object.create(D):(z.prototype=D.prototype,new z)}})();Object.defineProperty(d,"__esModule",{value:!0});var g=256,m=(function(){function M(T){T===void 0&&(T="="),this._paddingCharacter=T}return M.prototype.encodedLength=function(T){return this._paddingCharacter?(T+2)/3*4|0:(T*8+5)/6|0},M.prototype.encode=function(T){for(var D="",z=0;z>>18&63),D+=this._encodeByte(P>>>12&63),D+=this._encodeByte(P>>>6&63),D+=this._encodeByte(P>>>0&63)}var q=T.length-z;if(q>0){var P=T[z]<<16|(q===2?T[z+1]<<8:0);D+=this._encodeByte(P>>>18&63),D+=this._encodeByte(P>>>12&63),q===2?D+=this._encodeByte(P>>>6&63):D+=this._paddingCharacter||"",D+=this._paddingCharacter||""}return D},M.prototype.maxDecodedLength=function(T){return this._paddingCharacter?T/4*3|0:(T*6+7)/8|0},M.prototype.decodedLength=function(T){return this.maxDecodedLength(T.length-this._getPaddingLength(T))},M.prototype.decode=function(T){if(T.length===0)return new Uint8Array(0);for(var D=this._getPaddingLength(T),z=T.length-D,P=new Uint8Array(this.maxDecodedLength(z)),q=0,W=0,he=0,Ee=0,be=0,Ue=0,Fe=0;W>>4,P[q++]=be<<4|Ue>>>2,P[q++]=Ue<<6|Fe,he|=Ee&g,he|=be&g,he|=Ue&g,he|=Fe&g;if(W>>4,he|=Ee&g,he|=be&g),W>>2,he|=Ue&g),W>>8&6,D+=51-T>>>8&-75,D+=61-T>>>8&-15,D+=62-T>>>8&3,String.fromCharCode(D)},M.prototype._decodeChar=function(T){var D=g;return D+=(42-T&T-44)>>>8&-g+T-43+62,D+=(46-T&T-48)>>>8&-g+T-47+63,D+=(47-T&T-58)>>>8&-g+T-48+52,D+=(64-T&T-91)>>>8&-g+T-65+0,D+=(96-T&T-123)>>>8&-g+T-97+26,D},M.prototype._getPaddingLength=function(T){var D=0;if(this._paddingCharacter){for(var z=T.length-1;z>=0&&T[z]===this._paddingCharacter;z--)D++;if(T.length<4||D>2)throw new Error("Base64Coder: incorrect padding")}return D},M})();d.Coder=m;var y=new m;function S(M){return y.encode(M)}d.encode=S;function v(M){return y.decode(M)}d.decode=v;var _=(function(M){f(T,M);function T(){return M!==null&&M.apply(this,arguments)||this}return T.prototype._encodeByte=function(D){var z=D;return z+=65,z+=25-D>>>8&6,z+=51-D>>>8&-75,z+=61-D>>>8&-13,z+=62-D>>>8&49,String.fromCharCode(z)},T.prototype._decodeChar=function(D){var z=g;return z+=(44-D&D-46)>>>8&-g+D-45+62,z+=(94-D&D-96)>>>8&-g+D-95+63,z+=(47-D&D-58)>>>8&-g+D-48+52,z+=(64-D&D-91)>>>8&-g+D-65+0,z+=(96-D&D-123)>>>8&-g+D-97+26,z},T})(m);d.URLSafeCoder=_;var A=new _;function x(M){return A.encode(M)}d.encodeURLSafe=x;function O(M){return A.decode(M)}d.decodeURLSafe=O,d.encodedLength=function(M){return y.encodedLength(M)},d.maxDecodedLength=function(M){return y.maxDecodedLength(M)},d.decodedLength=function(M){return y.decodedLength(M)}},978(c,d){var f="utf8: invalid source encoding";function g(m){for(var y=[],S=0;S=m.length)throw new Error(f);var A=m[++S];if((A&192)!==128)throw new Error(f);v=(v&31)<<6|A&63,_=128}else if(v<240){if(S>=m.length-1)throw new Error(f);var A=m[++S],x=m[++S];if((A&192)!==128||(x&192)!==128)throw new Error(f);v=(v&15)<<12|(A&63)<<6|x&63,_=2048}else if(v<248){if(S>=m.length-2)throw new Error(f);var A=m[++S],x=m[++S],O=m[++S];if((A&192)!==128||(x&192)!==128||(O&192)!==128)throw new Error(f);v=(v&15)<<18|(A&63)<<12|(x&63)<<6|O&63,_=65536}else throw new Error(f);if(v<_||v>=55296&&v<=57343)throw new Error(f);if(v>=65536){if(v>1114111)throw new Error(f);v-=65536,y.push(String.fromCharCode(55296|v>>10)),v=56320|v&1023}}y.push(String.fromCharCode(v))}return y.join("")}d.D4=g},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>_s});class g{constructor(b,w){this.lastId=0,this.prefix=b,this.name=w}create(b){this.lastId++;var w=this.lastId,L=this.prefix+w,I=this.name+"["+w+"]",re=!1,me=function(){re||(b.apply(null,arguments),re=!0)};return this[w]=me,{number:w,id:L,name:I,callback:me}}remove(b){delete this[b.number]}}var m=new g("_pusher_script_","Pusher.ScriptReceivers"),y={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};const S=y;class v{constructor(b){this.options=b,this.receivers=b.receivers||m,this.loading={}}load(b,w,L){var I=this;if(I.loading[b]&&I.loading[b].length>0)I.loading[b].push(L);else{I.loading[b]=[L];var re=ze.createScriptRequest(I.getPath(b,w)),me=I.receivers.create(function(Le){if(I.receivers.remove(me),I.loading[b]){var We=I.loading[b];delete I.loading[b];for(var dt=function(Pt){Pt||re.cleanup()},pt=0;pt>>6)+J(128|b&63):J(224|b>>>12&15)+J(128|b>>>6&63)+J(128|b&63)},te=function(E){return E.replace(/[^\x00-\x7F]/g,Me)},pe=function(E){var b=[0,2,1][E.length%3],w=E.charCodeAt(0)<<16|(E.length>1?E.charCodeAt(1):0)<<8|(E.length>2?E.charCodeAt(2):0),L=[ue.charAt(w>>>18),ue.charAt(w>>>12&63),b>=2?"=":ue.charAt(w>>>6&63),b>=1?"=":ue.charAt(w&63)];return L.join("")},N=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,pe)};class R{constructor(b,w,L,I){this.clear=w,this.timer=b(()=>{this.timer&&(this.timer=I(this.timer))},L)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const de=R;function fe(E){window.clearTimeout(E)}function xe(E){window.clearInterval(E)}class ee extends de{constructor(b,w){super(setTimeout,fe,b,function(L){return w(),null})}}class _e extends de{constructor(b,w){super(setInterval,xe,b,function(L){return w(),L})}}var Be={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new ee(0,E)},method(E,...b){var w=Array.prototype.slice.call(arguments,1);return function(L){return L[E].apply(L,w.concat(arguments))}}};const ke=Be;function Ie(E,...b){for(var w=0;w{window.console&&window.console.log&&window.console.log(b)}}debug(...b){this.log(this.globalLog,b)}warn(...b){this.log(this.globalLogWarn,b)}error(...b){this.log(this.globalLogError,b)}globalLogWarn(b){window.console&&window.console.warn?window.console.warn(b):this.globalLog(b)}globalLogError(b){window.console&&window.console.error?window.console.error(b):this.globalLogWarn(b)}log(b,...w){var L=Ct.apply(this,arguments);_s.log?_s.log(L):_s.logToConsole&&b.bind(this)(L)}}const rt=new On;var Hn=function(E,b,w,L,I){(w.headers!==void 0||w.headersProvider!=null)&&rt.warn(`To send headers with the ${L.toString()} request, you must use AJAX, rather than JSONP.`);var re=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var me=E.getDocument(),Le=me.createElement("script");E.auth_callbacks[re]=function(pt){I(null,pt)};var We="Pusher.auth_callbacks['"+re+"']";Le.src=w.endpoint+"?callback="+encodeURIComponent(We)+"&"+b;var dt=me.getElementsByTagName("head")[0]||me.documentElement;dt.insertBefore(Le,dt.firstChild)};const bn=Hn;class ra{constructor(b){this.src=b}send(b){var w=this,L="Error loading "+w.src;w.script=document.createElement("script"),w.script.id=b.id,w.script.src=w.src,w.script.type="text/javascript",w.script.charset="UTF-8",w.script.addEventListener?(w.script.onerror=function(){b.callback(L)},w.script.onload=function(){b.callback(null)}):w.script.onreadystatechange=function(){(w.script.readyState==="loaded"||w.script.readyState==="complete")&&b.callback(null)},w.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(w.errorScript=document.createElement("script"),w.errorScript.id=b.id+"_error",w.errorScript.text=b.name+"('"+L+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(w.script,I.firstChild),w.errorScript&&I.insertBefore(w.errorScript,w.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class sr{constructor(b,w){this.url=b,this.data=w}send(b){if(!this.request){var w=Ci(this.data),L=this.url+"/"+b.number+"?"+w;this.request=ze.createScriptRequest(L),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var cn=function(E,b){return function(w,L){var I="http"+(b?"s":"")+"://",re=I+(E.host||E.options.host)+E.options.path,me=ze.createJSONPRequest(re,w),Le=ze.ScriptReceivers.create(function(We,dt){m.remove(Le),me.cleanup(),dt&&dt.host&&(E.host=dt.host),L&&L(We,dt)});me.send(Le)}},Tn={name:"jsonp",getAgent:cn};const un=Tn;function V(E,b,w){var L=E+(b.useTLS?"s":""),I=b.useTLS?b.hostTLS:b.hostNonTLS;return L+"://"+I+w}function se(E,b){var w="/app/"+E,L="?protocol="+S.PROTOCOL+"&client=js&version="+S.VERSION+(b?"&"+b:"");return w+L}var ce={getInitial:function(E,b){var w=(b.httpPath||"")+se(E,"flash=false");return V("ws",b,w)}},Z={getInitial:function(E,b){var w=(b.httpPath||"/pusher")+se(E);return V("http",b,w)}},ve={getInitial:function(E,b){return V("http",b,b.httpPath||"/pusher")},getPath:function(E,b){return se(E)}};class ge{constructor(){this._callbacks={}}get(b){return this._callbacks[we(b)]}add(b,w,L){var I=we(b);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:w,context:L})}remove(b,w,L){if(!b&&!w&&!L){this._callbacks={};return}var I=b?[we(b)]:vt(this._callbacks);w||L?this.removeCallback(I,w,L):this.removeAllCallbacks(I)}removeCallback(b,w,L){Oe(b,function(I){this._callbacks[I]=Mt(this._callbacks[I]||[],function(re){return w&&w!==re.fn||L&&L!==re.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(b){Oe(b,function(w){delete this._callbacks[w]},this)}}function we(E){return"_"+E}class Ae{constructor(b){this.callbacks=new ge,this.global_callbacks=[],this.failThrough=b}bind(b,w,L){return this.callbacks.add(b,w,L),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,w,L){return this.callbacks.remove(b,w,L),this}unbind_global(b){return b?(this.global_callbacks=Mt(this.global_callbacks||[],w=>w!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,w,L){for(var I=0;I0)for(var I=0;I{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),rt.debug("Connecting",{transport:this.name,url:b}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(b){return this.state==="open"?(ke.defer(()=>{this.socket&&this.socket.send(b)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(b){this.emit("error",{type:"WebSocketError",error:b}),this.timeline.error(this.buildTimelineMessage({error:b.toString()}))}onClose(b){b?this.changeState("closed",{code:b.code,reason:b.reason,wasClean:b.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(b){this.emit("message",b)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=b=>{this.onError(b)},this.socket.onclose=b=>{this.onClose(b)},this.socket.onmessage=b=>{this.onMessage(b)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(b,w){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:w})),this.emit(b,w)}buildTimelineMessage(b){return Ie({cid:this.id},b)}}class Te{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,w,L,I){return new Ke(this.hooks,b,w,L,I)}}var $e=new Te({urls:ce,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!ze.getWebSocketAPI()},isSupported:function(){return!!ze.getWebSocketAPI()},getSocket:function(E){return ze.createWebSocket(E)}}),Re={urls:Z,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},et=Ie({getSocket:function(E){return ze.HTTPFactory.createStreamingSocket(E)}},Re),je=Ie({getSocket:function(E){return ze.HTTPFactory.createPollingSocket(E)}},Re),Ve={isSupported:function(){return ze.isXHRSupported()}},Se=new Te(Ie({},et,Ve)),He=new Te(Ie({},je,Ve)),tt={ws:$e,xhr_streaming:Se,xhr_polling:He};const Tt=tt;var It=new Te({file:"sockjs",urls:ve,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(E,b){return new window.SockJS(E,null,{js_path:A.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(E,b){E.send(JSON.stringify({path:b}))}}),Ln={isSupported:function(E){var b=ze.isXDRSupported(E.useTLS);return b}},zt=new Te(Ie({},et,Ln)),Ut=new Te(Ie({},je,Ln));Tt.xdr_streaming=zt,Tt.xdr_polling=Ut,Tt.sockjs=It;const Rn=Tt;class $a extends Ae{constructor(){super();var b=this;typeof window<"u"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){b.emit("online")},!1),window.addEventListener("offline",function(){b.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var jo=new $a;class Rf{constructor(b,w,L){this.manager=b,this.transport=w,this.minPingDelay=L.minPingDelay,this.maxPingDelay=L.maxPingDelay,this.pingDelay=void 0}createConnection(b,w,L,I){I=Ie({},I,{activityTimeout:this.pingDelay});var re=this.transport.createConnection(b,w,L,I),me=null,Le=function(){re.unbind("open",Le),re.bind("closed",We),me=ke.now()},We=dt=>{if(re.unbind("closed",We),dt.code===1002||dt.code===1003)this.manager.reportDeath();else if(!dt.wasClean&&me){var pt=ke.now()-me;pt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(pt/2,this.minPingDelay))}};return re.bind("open",Le),re}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const kc={decodeMessage:function(E){try{var b=JSON.parse(E.data),w=b.data;if(typeof w=="string")try{w=JSON.parse(b.data)}catch{}var L={event:b.event,channel:b.channel,data:w};return b.user_id&&(L.user_id=b.user_id),L}catch(I){throw{type:"MessageParseError",error:I,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var b=kc.decodeMessage(E);if(b.event==="pusher:connection_established"){if(!b.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:b.data.socket_id,activityTimeout:b.data.activity_timeout*1e3}}else{if(b.event==="pusher:error")return{action:this.getCloseAction(b.data),error:this.getCloseError(b.data)};throw"Invalid handshake"}},getCloseAction:function(E){return E.code<4e3?E.code>=1002&&E.code<=1004?"backoff":null:E.code===4e3?"tls_only":E.code<4100?"refused":E.code<4200?"backoff":E.code<4300?"retry":"refused"},getCloseError:function(E){return E.code!==1e3&&E.code!==1001?{type:"PusherError",data:{code:E.code,message:E.reason||E.message}}:null}},qr=kc;class Ei extends Ae{constructor(b,w){super(),this.id=b,this.transport=w,this.activityTimeout=w.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,w,L){var I={event:b,data:w};return L&&(I.channel=L),rt.debug("Event sent",I),this.send(qr.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:L=>{var I;try{I=qr.decodeMessage(L)}catch(re){this.emit("error",{type:"MessageParseError",error:re,data:L.data})}if(I!==void 0){switch(rt.debug("Event recd",I),I.event){case"pusher:error":this.emit("error",{type:"PusherError",data:I.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",I)}},activity:()=>{this.emit("activity")},error:L=>{this.emit("error",L)},closed:L=>{w(),L&&L.code&&this.handleCloseEvent(L),this.transport=null,this.emit("closed")}},w=()=>{Ot(b,(L,I)=>{this.transport.unbind(I,L)})};Ot(b,(L,I)=>{this.transport.bind(I,L)})}handleCloseEvent(b){var w=qr.getCloseAction(b),L=qr.getCloseError(b);L&&this.emit("error",L),w&&this.emit(w,{action:w,error:L})}}class zo{constructor(b,w){this.transport=b,this.callback=w,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var w;try{w=qr.processHandshake(b)}catch(L){this.finish("error",{error:L}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new Ei(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var w=qr.getCloseAction(b)||"backoff",L=qr.getCloseError(b);this.finish(w,{error:L})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(b,w){this.callback(Ie({transport:this.transport,action:b},w))}}class Na{constructor(b,w){this.timeline=b,this.options=w||{}}send(b,w){this.timeline.isEmpty()||this.timeline.send(ze.TimelineTransport.getAgent(this,b),w)}}class Gr extends Ae{constructor(b,w){super(function(L,I){rt.debug("No callbacks on "+b+" for "+L)}),this.name=b,this.pusher=w,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,w){return w(null,{auth:""})}trigger(b,w){if(b.indexOf("client-")!==0)throw new D("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var L=M.buildLogSuffix("triggeringClientEvents");rt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${L}`)}return this.pusher.send_event(b,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var w=b.event,L=b.data;if(w==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(w==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(w.indexOf("pusher_internal:")!==0){var I={};this.emit(w,L,I)}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",b.data)}handleSubscriptionCountEvent(b){b.data.subscription_count&&(this.subscriptionCount=b.data.subscription_count),this.emit("pusher:subscription_count",b.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(b,w)=>{b?(this.subscriptionPending=!1,rt.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof Ue?{status:b.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:w.auth,channel_data:w.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class aa extends Gr{authorize(b,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},w)}}class Ia{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){Ot(this.members,(w,L)=>{b(this.get(L))})}setMyID(b){this.myID=b}onSubscription(b){this.members=b.presence.hash,this.count=b.presence.count,this.me=this.get(this.myID)}addMember(b){return this.get(b.user_id)===null&&this.count++,this.members[b.user_id]=b.user_info,this.get(b.user_id)}removeMember(b){var w=this.get(b.user_id);return w&&(delete this.members[b.user_id],this.count--),w}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Zt=function(E,b,w,L){function I(re){return re instanceof w?re:new w(function(me){me(re)})}return new(w||(w=Promise))(function(re,me){function Le(pt){try{dt(L.next(pt))}catch(Pt){me(Pt)}}function We(pt){try{dt(L.throw(pt))}catch(Pt){me(Pt)}}function dt(pt){pt.done?re(pt.value):I(pt.value).then(Le,We)}dt((L=L.apply(E,b||[])).next())})};class Dc extends aa{constructor(b,w){super(b,w),this.members=new Ia}authorize(b,w){super.authorize(b,(L,I)=>Zt(this,void 0,void 0,function*(){if(!L)if(I=I,I.channel_data!=null){var re=JSON.parse(I.channel_data);this.members.setMyID(re.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let me=M.buildLogSuffix("authorizationEndpoint");rt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${me}, or the user should be signed in.`),w("Invalid auth response");return}w(L,I)}))}handleEvent(b){var w=b.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var L=b.data,I={};b.user_id&&(I.user_id=b.user_id),this.emit(w,L,I)}}handleInternalEvent(b){var w=b.event,L=b.data;switch(w){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(b);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(b);break;case"pusher_internal:member_added":var I=this.members.addMember(L);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var re=this.members.removeMember(L);re&&this.emit("pusher:member_removed",re);break}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(b.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Oc=f(978),Tr=f(594);class Ha extends aa{constructor(b,w,L){super(b,w),this.key=null,this.nacl=L}authorize(b,w){super.authorize(b,(L,I)=>{if(L){w(L,I);return}let re=I.shared_secret;if(!re){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Tr.decode)(re),delete I.shared_secret,w(null,I)})}trigger(b,w){throw new he("Client events are not currently supported for encrypted channels")}handleEvent(b){var w=b.event,L=b.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(w,L)}handleEncryptedEvent(b,w){if(!this.key){rt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){rt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let L=(0,Tr.decode)(w.ciphertext);if(L.length{if(me){rt.error(`Failed to make a request to the authEndpoint: ${Le}. Unable to fetch new key, so dropping encrypted event`);return}if(re=this.nacl.secretbox.open(L,I,this.key),re===null){rt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(re))});return}this.emit(b,this.getDataToEmit(re))}getDataToEmit(b){let w=(0,Oc.D4)(b);try{return JSON.parse(w)}catch{return w}}}class kf extends Ae{constructor(b,w){super(),this.state="initialized",this.connection=null,this.key=b,this.options=w,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var L=ze.getNetwork();L.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),L.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(b){this.key=b,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(b){return this.connection?this.connection.send(b):!1}send_event(b,w,L){return this.connection?this.connection.send_event(b,w,L):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(w,L)=>{w?this.runner=this.strategy.connect(0,b):L.action==="error"?(this.emit("error",{type:"HandshakeError",error:L.error}),this.timeline.error({handshakeError:L.error})):(this.abortConnecting(),this.handshakeCallbacks[L.action](L))};this.runner=this.strategy.connect(0,b)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var b=this.abandonConnection();b.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(b){this.timeline.info({action:"retry",delay:b}),b>0&&this.emit("connecting_in",Math.round(b/1e3)),this.retryTimer=new ee(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new ee(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new ee(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new ee(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return Ie({},b,{message:w=>{this.resetActivityCheck(),this.emit("message",w)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:w=>{this.emit("error",w)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(b){return Ie({},b,{connected:w=>{this.activityTimeout=Math.min(this.options.activityTimeout,w.activityTimeout,w.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(w.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let b=w=>L=>{L.error&&this.emit("error",{type:"WebSocketError",error:L.error}),w(L)};return{tls_only:b(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:b(()=>{this.disconnect()}),backoff:b(()=>{this.retryIn(1e3)}),retry:b(()=>{this.retryIn(0)})}}setConnection(b){this.connection=b;for(var w in this.connectionCallbacks)this.connection.bind(w,this.connectionCallbacks[w]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var w=this.connection;return this.connection=null,w}}updateState(b,w){var L=this.state;if(this.state=b,L!==b){var I=b;I==="connected"&&(I+=" with new socket ID "+w.socket_id),rt.debug("State changed",L+" -> "+I),this.timeline.info({state:b,params:w}),this.emit("state_change",{previous:L,current:b}),this.emit(b,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Lc{constructor(){this.channels={}}add(b,w){return this.channels[b]||(this.channels[b]=Mc(b,w)),this.channels[b]}all(){return _t(this.channels)}find(b){return this.channels[b]}remove(b){var w=this.channels[b];return delete this.channels[b],w}disconnect(){Ot(this.channels,function(b){b.disconnect()})}}function Mc(E,b){if(E.indexOf("private-encrypted-")===0){if(b.config.nacl)return jn.createEncryptedChannel(E,b,b.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",L=M.buildLogSuffix("encryptedChannelSupport");throw new he(`${w}. ${L}`)}else{if(E.indexOf("private-")===0)return jn.createPrivateChannel(E,b);if(E.indexOf("presence-")===0)return jn.createPresenceChannel(E,b);if(E.indexOf("#")===0)throw new z('Cannot create a channel with name "'+E+'".');return jn.createChannel(E,b)}}var Df={createChannels(){return new Lc},createConnectionManager(E,b){return new kf(E,b)},createChannel(E,b){return new Gr(E,b)},createPrivateChannel(E,b){return new aa(E,b)},createPresenceChannel(E,b){return new Dc(E,b)},createEncryptedChannel(E,b,w){return new Ha(E,b,w)},createTimelineSender(E,b){return new Na(E,b)},createHandshake(E,b){return new zo(E,b)},createAssistantToTheTransportManager(E,b,w){return new Rf(E,b,w)}};const jn=Df;class _i{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return jn.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class vn{constructor(b,w){this.strategies=b,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return ln(this.strategies,ke.method("isSupported"))}connect(b,w){var L=this.strategies,I=0,re=this.timeout,me=null,Le=(We,dt)=>{dt?w(null,dt):(I=I+1,this.loop&&(I=I%L.length),I0&&(re=new ee(L.timeout,function(){me.abort(),I(!0)})),me=b.connect(w,function(Le,We){Le&&re&&re.isRunning()&&!L.failFast||(re&&re.ensureAborted(),I(Le,We))}),{abort:function(){re&&re.ensureAborted(),me.abort()},forceMinPriority:function(Le){me.forceMinPriority(Le)}}}}class kn{constructor(b){this.strategies=b}isSupported(){return ln(this.strategies,ke.method("isSupported"))}connect(b,w){return $c(this.strategies,b,function(L,I){return function(re,me){if(I[L].error=re,re){Of(I)&&w(!0);return}Oe(I,function(Le){Le.forceMinPriority(me.transport.priority)}),w(null,me)}})}}function $c(E,b,w){var L=nt(E,function(I,re,me,Le){return I.connect(b,w(re,Le))});return{abort:function(){Oe(L,Uo)},forceMinPriority:function(I){Oe(L,function(re){re.forceMinPriority(I)})}}}function Of(E){return Br(E,function(b){return!!b.error})}function Uo(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class Nc{constructor(b,w,L){this.strategy=b,this.transports=w,this.ttl=L.ttl||18e5,this.usingTLS=L.useTLS,this.timeline=L.timeline}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.usingTLS,I=Lf(L),re=I&&I.cacheSkipCount?I.cacheSkipCount:0,me=[this.strategy];if(I&&I.timestamp+this.ttl>=ke.now()){var Le=this.transports[I.transport];Le&&(["ws","wss"].includes(I.transport)||re>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),me.push(new vn([Le],{timeout:I.latency*2+1e3,failFast:!0}))):re++)}var We=ke.now(),dt=me.pop().connect(b,function pt(Pt,Or){Pt?(vs(L),me.length>0?(We=ke.now(),dt=me.pop().connect(b,pt)):w(Pt)):(zn(L,Or.transport.name,ke.now()-We,re),w(null,Or))});return{abort:function(){dt.abort()},forceMinPriority:function(pt){b=pt,dt&&dt.forceMinPriority(pt)}}}}function ja(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Lf(E){var b=ze.getLocalStorage();if(b)try{var w=b[ja(E)];if(w)return JSON.parse(w)}catch{vs(E)}return null}function zn(E,b,w,L){var I=ze.getLocalStorage();if(I)try{I[ja(E)]=yn({timestamp:ke.now(),transport:b,latency:w,cacheSkipCount:L})}catch{}}function vs(E){var b=ze.getLocalStorage();if(b)try{delete b[ja(E)]}catch{}}class Ai{constructor(b,{delay:w}){this.strategy=b,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.strategy,I,re=new ee(this.options.delay,function(){I=L.connect(b,w)});return{abort:function(){re.ensureAborted(),I&&I.abort()},forceMinPriority:function(me){b=me,I&&I.forceMinPriority(me)}}}}class ia{constructor(b,w,L){this.test=b,this.trueBranch=w,this.falseBranch=L}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,w){var L=this.test()?this.trueBranch:this.falseBranch;return L.connect(b,w)}}class za{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,w){var L=this.strategy.connect(b,function(I,re){re&&L.abort(),w(I,re)});return L}}function Ua(E){return function(){return E.isSupported()}}var Ic=function(E,b,w){var L={};function I(el,Xc,Jc,Zf,eh){var Qc=w(E,el,Xc,Jc,Zf,eh);return L[el]=Qc,Qc}var re=Object.assign({},b,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),me=Object.assign({},re,{useTLS:!0}),Le=Object.assign({},b,{hostNonTLS:E.httpHost+":"+E.httpPort,hostTLS:E.httpHost+":"+E.httpsPort,httpPath:E.httpPath}),We={loop:!0,timeout:15e3,timeoutLimit:6e4},dt=new _i({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),pt=new _i({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),Pt=I("ws","ws",3,re,dt),Or=I("wss","ws",3,me,dt),Xf=I("sockjs","sockjs",1,Le),Wc=I("xhr_streaming","xhr_streaming",1,Le,pt),Jf=I("xdr_streaming","xdr_streaming",1,Le,pt),Jo=I("xhr_polling","xhr_polling",1,Le),Yc=I("xdr_polling","xdr_polling",1,Le),qa=new vn([Pt],We),Oi=new vn([Or],We),Qf=new vn([Xf],We),Li=new vn([new ia(Ua(Wc),Wc,Jf)],We),Qo=new vn([new ia(Ua(Jo),Jo,Yc)],We),Zo=new vn([new ia(Ua(Li),new kn([Li,new Ai(Qo,{delay:4e3})]),Qo)],We),Mi=new ia(Ua(Zo),Zo,Qf),$i;return b.useTLS?$i=new kn([qa,new Ai(Mi,{delay:2e3})]):$i=new kn([qa,new Ai(Oi,{delay:2e3}),new Ai(Mi,{delay:5e3})]),new Nc(new za(new ia(Ua(Pt),$i,Mi)),L,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})};const Pa=Ic;function Mf(){var E=this;E.timeline.info(E.buildTimelineMessage({transport:E.name+(E.options.useTLS?"s":"")})),E.hooks.isInitialized()?E.changeState("initialized"):E.hooks.file?(E.changeState("initializing"),A.load(E.hooks.file,{useTLS:E.options.useTLS},function(b,w){E.hooks.isInitialized()?(E.changeState("initialized"),w(!0)):(b&&E.onError(b),E.onClose(),w(!1))})):E.onClose()}var Hc={getRequest:function(E){var b=new window.XDomainRequest;return b.ontimeout=function(){E.emit("error",new P),E.close()},b.onerror=function(w){E.emit("error",w),E.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText),E.emit("finished",200),E.close()},b},abortRequest:function(E){E.ontimeout=E.onerror=E.onprogress=E.onload=null,E.abort()}};const jc=Hc,Po=256*1024;class $f extends Ae{constructor(b,w,L){super(),this.hooks=b,this.method=w,this.url=L}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},ze.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(b)}close(){this.unloader&&(ze.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,w){for(;;){var L=this.advanceBuffer(w);if(L)this.emit("chunk",{status:b,data:L});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(b){var w=b.slice(this.position),L=w.indexOf(` +`);return L!==-1?(this.position+=L+1,w.slice(0,L)):null}isBufferTooLong(b){return this.position===b.length&&b.length>Po}}var Bo;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(Bo||(Bo={}));const or=Bo;var Rr=1;class qo{constructor(b,w){this.hooks=b,this.session=Ss(1e3)+"/"+Uc(8),this.location=Go(w),this.readyState=or.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,w){this.onClose(b,w,!0)}sendRaw(b){if(this.readyState===or.OPEN)try{return ze.createSocketRequest("POST",sa(Ba(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,w,L){this.closeStream(),this.readyState=or.CLOSED,this.onclose&&this.onclose({code:b,reason:w,wasClean:L})}onChunk(b){if(b.status===200){this.readyState===or.OPEN&&this.onActivity();var w,L=b.data.slice(0,1);switch(L){case"o":w=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(b.data.slice(1)||"[]");for(var I=0;I{this.onChunk(b)}),this.stream.bind("finished",b=>{this.hooks.onFinished(this,b)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(b){ke.defer(()=>{this.onError(b),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Go(E){var b=/([^\?]*)\/*(\??.*)/.exec(E);return{base:b[1],queryString:b[2]}}function Ba(E,b){return E.base+"/"+b+"/xhr_send"}function sa(E){var b=E.indexOf("?")===-1?"?":"&";return E+b+"t="+ +new Date+"&n="+Rr++}function zc(E,b){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+b+w[3]}function Ss(E){return ze.randomInt(E)}function Uc(E){for(var b=[],w=0;w0&&E.onChunk(w.status,w.responseText);break;case 4:w.responseText&&w.responseText.length>0&&E.onChunk(w.status,w.responseText),E.emit("finished",w.status),E.close();break}},w},abortRequest:function(E){E.onreadystatechange=null,E.abort()}};const ws=Fo;var Pc={createStreamingSocket(E){return this.createSocket(Vo,E)},createPollingSocket(E){return this.createSocket(Vr,E)},createSocket(E,b){return new xi(E,b)},createXHR(E,b){return this.createRequest(ws,E,b)},createRequest(E,b,w){return new $f(E,b,w)}};const Ri=Pc;Ri.createXDR=function(E,b){return this.createRequest(jc,E,b)};var Bc={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Pa,Transports:Rn,transportConnectionInitializer:Mf,HTTPFactory:Ri,TimelineTransport:un,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(E){if(typeof window<"u"){window.Pusher=E;var b=()=>{this.onDocumentBody(E.ready)};window.JSON?b():A.load("json2",{},b)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Ge,jsonp:bn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,b){return new sr(E,b)},createScriptRequest(E){return new ra(E)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var E=this.getXHRAPI();return new E},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return jo},createWebSocket(E){var b=this.getWebSocketAPI();return new b(E)},createSocketRequest(E,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(E,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(E,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var E=this.getXHRAPI();return!!E&&new E().withCredentials!==void 0},isXDRSupported(E){var b=E?"https:":"http:",w=this.getProtocol();return!!window.XDomainRequest&&w===b},addUnloadListener(E){window.addEventListener!==void 0?window.addEventListener("pagehide",E,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",E)},removeUnloadListener(E){window.addEventListener!==void 0?window.removeEventListener("pagehide",E,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",E)},randomInt(E){const b=window.crypto||window.msCrypto,w=Math.floor(Math.pow(2,32)/E)*E;let L;do L=b.getRandomValues(new Uint32Array(1))[0];while(L>=w);return L%E}};const ze=Bc;var Dr;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Dr||(Dr={}));const oa=Dr;class ki{constructor(b,w,L){this.key=b,this.session=w,this.events=[],this.options=L||{},this.sent=0,this.uniqueID=0}log(b,w){b<=this.options.level&&(this.events.push(Ie({},w,{timestamp:ke.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(oa.ERROR,b)}info(b){this.log(oa.INFO,b)}debug(b){this.log(oa.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,w){var L=Ie({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],b(L,(I,re)=>{I||this.sent++,w&&w(I,re)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Nf{constructor(b,w,L,I){this.name=b,this.priority=w,this.transport=L,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,w){if(this.isSupported()){if(this.priority{L||(pt(),re?re.close():I.close())},forceMinPriority:Pt=>{L||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var L in b.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(b.params[L]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var L in I)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(I[L])}return w},Hf=E=>{if(typeof ze.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const L=If(b,E);ze.getAuthorizers()[E.transport](ze,L,E,T.UserAuthentication,w)}},Yo=(E,b)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var L in b.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(b.params[L]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var L in I)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(I[L])}return w},jf=E=>{if(typeof ze.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const L=Yo(b,E);ze.getAuthorizers()[E.transport](ze,L,E,T.ChannelAuthorization,w)}},zf=(E,b,w)=>{const L={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(I,re)=>{const me=E.channel(I.channelName);w(me,L).authorize(I.socketId,re)}};function Gc(E,b){let w={activityTimeout:E.activityTimeout||S.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||S.httpPath,httpPort:E.httpPort||S.httpPort,httpsPort:E.httpsPort||S.httpsPort,pongTimeout:E.pongTimeout||S.pongTimeout,statsHost:E.statsHost||S.stats_host,unavailableTimeout:E.unavailableTimeout||S.unavailableTimeout,wsPath:E.wsPath||S.wsPath,wsPort:E.wsPort||S.wsPort,wssPort:E.wssPort||S.wssPort,enableStats:qf(E),httpHost:Uf(E),useTLS:Bf(E),wsHost:Vc(E),userAuthenticator:Xo(E),channelAuthorizer:Vf(E,b)};return"disabledTransports"in E&&(w.disabledTransports=E.disabledTransports),"enabledTransports"in E&&(w.enabledTransports=E.enabledTransports),"ignoreNullOrigin"in E&&(w.ignoreNullOrigin=E.ignoreNullOrigin),"timelineParams"in E&&(w.timelineParams=E.timelineParams),"nacl"in E&&(w.nacl=E.nacl),w}function Uf(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:S.httpHost}function Vc(E){return E.wsHost?E.wsHost:Pf(E.cluster)}function Pf(E){return`ws-${E}.pusher.com`}function Bf(E){return ze.getProtocol()==="https:"?!0:E.forceTLS!==!1}function qf(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const Fc=E=>"customHandler"in E&&E.customHandler!=null;function Xo(E){const b=Object.assign(Object.assign({},S.userAuthentication),E.userAuthentication);return Fc(b)?b.customHandler:Hf(b)}function Gf(E,b){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},S.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||S.authTransport,endpoint:E.authEndpoint||S.authEndpoint},"auth"in E&&("params"in E.auth&&(w.params=E.auth.params),"headers"in E.auth&&(w.headers=E.auth.headers)),"authorizer"in E&&(w.customHandler=zf(b,w,E.authorizer))),w}function Vf(E,b){const w=Gf(E,b);return Fc(w)?w.customHandler:jf(w)}class Ff extends Ae{constructor(b){super(function(w,L){rt.debug(`No callbacks on watchlist events for ${w}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(w=>{this.emit(w.name,w)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var w=b.event;w==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function Kc(){let E,b;return{promise:new Promise((L,I)=>{E=L,b=I}),resolve:E,reject:b}}const Kf=Kc;class Wf extends Ae{constructor(b){super(function(w,L){rt.debug("No callbacks on user for "+w)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(w,L)=>{if(w){rt.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Ue?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:L.auth,user_data:L.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:w,current:L})=>{w!=="connected"&&L==="connected"&&this._signin(),w==="connected"&&L!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Ff(b),this.pusher.connection.bind("message",w=>{var L=w.event;L==="pusher:signin_success"&&this._onSigninSuccess(w.data),this.serverToUserChannel&&this.serverToUserChannel.name===w.channel&&this.serverToUserChannel.handleEvent(w)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(b){try{this.user_data=JSON.parse(b.user_data)}catch{rt.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){rt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=w=>{w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.pusher.connection.state==="connected"&&w.subscribe()};this.serverToUserChannel=new Gr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,L)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,L)}),b(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:b,resolve:w}=Kf();b.done=!1;const L=()=>{b.done=!0};b.then(L).catch(L),this.signinDonePromise=b,this._signinDoneResolve=w}}class dn{static ready(){dn.isReady=!0;for(var b=0,w=dn.instances.length;bze.getDefaultStrategy(this.config,I,Di);this.connection=jn.createConnectionManager(this.key,{getStrategy:L,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",I=>{var re=I.event,me=re.indexOf("pusher_internal:")===0;if(I.channel){var Le=this.channel(I.channel);Le&&Le.handleEvent(I)}me||this.global_emitter.emit(I.event,I.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",I=>{rt.warn(I)}),dn.instances.push(this),this.timeline.info({instances:dn.instances.length}),this.user=new Wf(this),dn.isReady&&this.connect()}switchCluster(b){const{appKey:w,cluster:L}=b;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:L}),this.config=Gc(this.options,this),this.connection.switchCluster(this.key)}channel(b){return this.channels.find(b)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var b=this.connection.isUsingTLS(),w=this.timelineSender;this.timelineSenderTimer=new _e(6e4,function(){w.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,w,L){return this.global_emitter.bind(b,w,L),this}unbind(b,w,L){return this.global_emitter.unbind(b,w,L),this}bind_global(b){return this.global_emitter.bind_global(b),this}unbind_global(b){return this.global_emitter.unbind_global(b),this}unbind_all(b){return this.global_emitter.unbind_all(),this}subscribeAll(){var b;for(b in this.channels.channels)this.channels.channels.hasOwnProperty(b)&&this.subscribe(b)}subscribe(b){var w=this.channels.add(b,this);return w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.connection.state==="connected"&&w.subscribe(),w}unsubscribe(b){var w=this.channels.find(b);w&&w.subscriptionPending?w.cancelSubscription():(w=this.channels.remove(b),w&&w.subscribed&&w.unsubscribe())}send_event(b,w,L){return this.connection.send_event(b,w,L)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}dn.instances=[],dn.isReady=!1,dn.logToConsole=!1,dn.Runtime=ze,dn.ScriptReceivers=ze.ScriptReceivers,dn.DependenciesReceivers=ze.DependenciesReceivers,dn.auth_callbacks=ze.auth_callbacks;const _s=dn;function Yf(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}ze.setup(dn)}},a={};function i(c){var d=a[c];if(d!==void 0)return d.exports;var f=a[c]={exports:{}};return n[c].call(f.exports,f,f.exports,i),f.exports}i.d=(c,d)=>{for(var f in d)i.o(d,f)&&!i.o(c,f)&&Object.defineProperty(c,f,{enumerable:!0,get:d[f]})},i.o=(c,d)=>Object.prototype.hasOwnProperty.call(c,d);var l=i(721);return l})())})(wf)),wf.exports}var aA=rA();const by=Jr(aA),qt=ht("WebSocketManager");class iA{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){qt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,qt.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){qt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:a=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(a)||80,d=i==="https";qt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=by;const f=localStorage.getItem("auth_token"),g={wsHost:n,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};qt.log("[WebSocketManager] Pusher 옵션:",g);const m=new by(e,g);m.connection.bind("connecting",()=>{qt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{qt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{qt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{qt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{qt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{qt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{qt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),qt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new nA({broadcaster:"reverb",client:m}),qt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,qt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,a,i={}){if(this.initialize(),!this.echo)return qt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return qt.log(`[WebSocketManager] 이미 구독 중: ${c}`),c;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,a),this.subscriptions.set(c,d),qt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){qt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),qt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(a=>this.subscriptions.delete(a)),qt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,qt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Cc=new iA,bt=ht("DataSourceManager"),vy=new Dn;function Ec(o,e){const n=Aa(o);if(n!==null)try{return Vn(n)?vy.evaluatePipeExpression(n,e,{skipCache:!0}):vy.evaluateExpression(n,e)}catch(a){return bt.error("Failed to evaluate param expression:",n,a),o}return rs(o,e,{skipCache:!0})}function Sy(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}function sA(){try{return window.G7Core?.devTools}catch{return}}const Rc=class Rc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new Dn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const n=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(a,i):i!=null&&n.append(a,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Ec(c,n);d!=null&&d!==""&&(a[l]=String(d))});return a}filterByCondition(e,n={}){const a=new Set,i=[];for(const l of e){if(a.has(l.id))continue;if(!l.if&&!l.conditions){a.add(l.id),i.push(l);continue}ns({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(a.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:n};if(ns({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return bt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){bt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,n={},a=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,n,a,i,l);c[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(g,m);if(y!==null){const S={status:y,message:`Error condition matched for ${g.id}`,data:m},v=Sr(),_=v.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(_.handler)try{await v.execute(_.handler,S)}catch(A){bt.error(`Error executing errorCondition handler for ${g.id}:`,A)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const S={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,S)}catch(S){bt.error(`Error executing onSuccess handler for ${g.id}:`,S)}}catch(m){bt.error(`Failed to fetch data source: ${g.id}`,m);const y=m?.response?.status||m?.status||500,S=m?.response?.data,v=S?.message||m.message||"Unknown error",_={status:y,message:v,errors:S?.errors,data:S,statusText:m?.response?.statusText},A=Sr(),x=A.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(x.handler)try{await A.execute(x.handler,_)}catch(O){bt.error(`Error executing error handler for ${g.id}:`,O)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),c}async fetchDataSourcesWithResults(e,n={},a=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");bt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=c?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const y=await this.fetchDataSource(m,n,a,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const S=this.checkErrorCondition(m,y);if(S!==null){const v={status:S,message:`Error condition matched for ${m.id}`,data:y},_=Sr(),A=_.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let x=!1;if(A.handler)if(m.loading_strategy==="blocking")_.execute(A.handler,v).catch(O=>{bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}),x=!0;else try{await _.execute(A.handler,v),x=!0}catch(O){bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${S}`),errorCode:S,errorHandled:x}}if(m.onSuccess)try{const v={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,v)}catch(v){bt.error(`Error executing onSuccess handler for ${m.id}:`,v)}return{id:m.id,state:"success",data:y}}catch(y){bt.error(`Failed to fetch data source: ${m.id}`,y);const S=y?.response?.status||y?.status||500,v=y?.response?.data,_=v?.message||y.message||"Unknown error",A={status:S,message:_,errors:v?.errors,data:v,statusText:y?.response?.statusText},x=Sr(),O=x.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(O.handler)if(m.loading_strategy==="blocking")x.execute(O.handler,A).catch(T=>{bt.error(`Error executing error handler for ${m.id}:`,T)}),M=!0;else try{await x.execute(O.handler,A),M=!0}catch(T){bt.error(`Error executing error handler for ${m.id}:`,T)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(y,m),{id:m.id,state:"error",error:y,errorCode:S,errorHandled:M})}}))}fetchDataSourcesInBackground(e,n={},a=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,a).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const g={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Sr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,g)}catch(S){bt.error(`Error executing errorCondition handler for ${c.id}:`,S)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const g={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,g)}catch(g){bt.error(`Error executing onSuccess handler for ${c.id}:`,g)}i&&i(c.id,d)}).catch(async d=>{bt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",y={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},S=Sr(),v=S.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(v.handler)try{await S.execute(v.handler,y)}catch(_){bt.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${c.id}`),i&&i(c.id,c.fallback);return}this.options.onError&&this.options.onError(d,c)})})}async fetchDataSource(e,n,a,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,a,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Sy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,a,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const c={route:n,query:Sy(a)};i&&(c._global=i),l&&(c._local=l);let d=rs(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?rs(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([_,A])=>{typeof A=="string"&&(y[_]=Ec(A,c))}),Object.keys(y).forEach(_=>{y[_]===""&&delete y[_]});const S=sA();let v=null;if(S?.isEnabled()){S.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let _=d;if(f==="GET"&&Object.keys(y).length>0){const A=new URLSearchParams;Object.entries(y).forEach(([O,M])=>{Array.isArray(M)?M.forEach(T=>A.append(O,String(T))):M!=null&&A.append(O,String(M))});const x=A.toString();_=x?`${d}?${x}`:d}v=S.trackRequest(_,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),S.trackDataSourceLoading(e.id)}try{let _;const A=e.auth_mode??(e.auth_required===!0?"required":"none"),x=br.getInstance().isAuthenticated();if(A==="required"&&!x){bt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),S?.isEnabled()&&(S.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),v&&S.failRequest(v,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const O=A==="required"||A==="optional"&&x;if(O){const M=Hr(),T=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&bt.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${T}`);const D=this.getMatchingGlobalHeaders(d,c),z={};e.headers&&Object.entries(e.headers).forEach(([he,Ee])=>{const be=Ec(Ee,c);be!=null&&be!==""&&(z[he]=String(be))});const P={...D,...z},q=Object.keys(P).length>0,W=m?this.toFormData(y):y;switch(f){case"GET":_=await M.get(T,{params:y,...q&&{headers:P}});break;case"POST":q?_=await M.post(T,W,{headers:P}):_=await M.post(T,W);break;case"PUT":q?_=await M.put(T,W,{headers:P}):_=await M.put(T,W);break;case"PATCH":q?_=await M.patch(T,W,{headers:P}):_=await M.patch(T,W);break;case"DELETE":_=await M.delete(T,{params:y,...q&&{headers:P}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const W=new URLSearchParams(y).toString();M=W?`${d}?${W}`:d}const T={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const W=localStorage.getItem("g7_locale");W&&(T["Accept-Language"]=W)}const D=this.getMatchingGlobalHeaders(d,c);Object.assign(T,D),e.headers&&Object.entries(e.headers).forEach(([W,he])=>{const Ee=Ec(he,c);Ee!=null&&Ee!==""&&(T[W]=String(Ee))});let z;f!=="GET"&&(m?(z=this.toFormData(y),delete T["Content-Type"]):z=JSON.stringify(y));const P=await fetch(M,{method:f,headers:T,body:z});let q;try{q=await P.json()}catch{q=null}if(v&&S?.isEnabled()&&(S.completeRequest(v,P.status,q),v=null),!P.ok){S?.isEnabled()&&S.trackDataSourceError(e.id,`HTTP ${P.status}: ${P.statusText}`);const W=new Error(`HTTP error! status: ${P.status}`);throw W.response={status:P.status,statusText:P.statusText,data:q},W.status=P.status,W}_=q,S?.isEnabled()&&S.trackDataSourceLoaded(e.id,_)}return O&&v&&S?.isEnabled()&&(S.completeRequest(v,200,_),S.trackDataSourceLoaded(e.id,_)),_}catch(_){if(v&&S?.isEnabled()){const A=_;A?.response?S.completeRequest(v,A.response.status,A.response.data):S.failRequest(v,_ instanceof Error?_.message:String(_)),S.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Rc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,a={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){bt.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=rs(c.channel,a,{skipCache:!0}),f=rs(c.event,a,{skipCache:!0})}catch(y){bt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const g=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(g(d)||g(f)){bt.warn(`WebSocket source ${c.id} has invalid channel/event after expression resolution, skipping. Original channel="${c.channel}", resolved="${d}". Original event="${c.event}", resolved="${f}". Available context keys: [${Object.keys(a).join(", ")}]`);return}const m=Cc.subscribe(d,f,y=>{const S=c.target_source||c.id;this.dataCache.set(S,{data:y,timestamp:Date.now()}),n(S,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Cc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const a=this.options.actionDispatcher??bm();if(!a){bt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await a.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw bt.error("Failed to execute onSuccess handler:",c),c}}};$(Rc,"DATA_CACHE_TTL",3e5);let _r=Rc;const oA=new _r,bi=ht("ModalDataSourceWrapper");function lA(o,e){if(!o||!e)return o;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of a){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const c=parseInt(l.slice(1,-1),10);i=i[c]}else i=i[l]}return i}const wy=({isOpen:o,modalId:e,dataSources:n,dataContext:a,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,g]=H.useState(!1),[m,y]=H.useState(!1),S=H.useRef(!1),v=H.useRef(null);v.current||(v.current=new _r);const _=H.useCallback(async()=>{if(!(!n||n.length===0)&&v.current){g(!0);try{const A=a.route||{},x=new URLSearchParams(window.location.search),O=n.map(T=>{let D={...T};if(T.endpoint&&l){const z=l.resolveBindings(T.endpoint,a,{skipCache:!0});D.endpoint=z}if(T.params&&l){const z={};Object.entries(T.params).forEach(([P,q])=>{typeof q=="string"?z[P]=l.resolveBindings(q,a,{skipCache:!0}):z[P]=q}),D.params=z}return D});c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,O.map(T=>({id:T.id,endpoint:T.endpoint})));const M=await v.current.fetchDataSourcesWithResults(O,A,x);i&&M.forEach(T=>{if(T.state==="success"&&T.data!==void 0){const D=O.find(z=>z.id===T.id);if(D?.initGlobal){const z=T.data?.data??T.data,P=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const q of P)if(typeof q=="string")i({[q]:z}),c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${T.id}.data -> _global.${q}`);else if(typeof q=="object"&&q.key){const{key:W,path:he}=q,Ee=he?lA(z,he):z;i({[W]:Ee}),c&&bi.log(`Modal "${e}" initGlobal: ${T.id}.data${he?"."+he:""} -> _global.${W}`)}}}else T.state==="error"&&bi.error(`Modal "${e}" data source error:`,T.id,T.error)}),c&&bi.log(`Modal "${e}" data sources fetched successfully`)}catch(A){bi.error(`Modal "${e}" data source fetch error:`,A)}finally{g(!1),y(!0)}}},[n,a,i,l,e,c]);return H.useEffect(()=>{if(!n||n.length===0)return;const A=window.__templateApp;return A?.registerModalDataSources&&A.registerModalDataSources(e,n),()=>{A?.unregisterModalDataSources&&A.unregisterModalDataSources(e)}},[e,n]),H.useEffect(()=>{!o&&S.current&&(y(!1),c&&bi.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!S.current&&n&&n.length>0&&!m&&_(),S.current=o},[o,n,m,_,e,c]),gt.jsx(gt.Fragment,{children:d})};class _c extends Error{constructor(n,a,i={}){super(a);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(n,a){if(!a||!n)return this.userMessageKey;try{return a.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class cA extends _c{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Cy(o){if(o instanceof _c)return o;if(o instanceof Error){const e=new _c("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new _c("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const uA=ht("ErrorDisplay");class Cf{static render(e,n){const a=document.getElementById(e);if(!a){uA.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` display: flex; align-items: center; justify-content: center; @@ -224,7 +224,7 @@ Error generating stack: `+u.message+` `:""} - `}static renderFromError(e,n,a,i=!1,l,c,d){let f,g;if(n.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:a,message:f,detailMessage:g,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const ps=ht("Router");class dA{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,a=await fetch(Nr(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,ps.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw ps.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,ps.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const a of this.routes){const i=this.matchPattern(a.path,n);if(i!==null)return{route:a,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const a=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(a.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=n.match(l);if(!c)return null;const d={};return a.forEach((f,g)=>{d[f]=c[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,a=this.match(e);if(!a){ps.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){ps.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const c=this.getAuthType(a.route,e),d=br.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const g=d.getLoginRedirectUrl(c,e+n);ps.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(n),l={};for(const c of i.keys()){if(c in l)continue;const d=i.getAll(c);d.length>1?l[c]=d:d.length===1&&(c.endsWith("[]")?l[c]=d:l[c]=d[0])}await this.emit("routeChange",{path:e,layout:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:l,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const n=this.pendingNavigation;this.executeNavigation(n)}}}}const fA=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function _y(o){const e=fA.exec(o);return e?{templateIdentifier:e[1]}:null}const Gt=ht("ErrorPageHandler");class hA{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(Nr(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Gt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Gt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=n.data;return!a.error_config||!a.error_config.layouts?(this.debug&&Gt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&Gt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Gt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&Gt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&Gt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Gt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Gt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Gt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Gt.log("Fetching data sources:",d.map(v=>v.id));const m=d.filter(v=>v.loading_strategy==="blocking"),y=d.filter(v=>!v.loading_strategy||v.loading_strategy==="progressive"),S=[...m,...y];if(S.length>0)try{c=await this.dataSourceManager.fetchDataSources(S,{},new URLSearchParams),this.debug&&Gt.log("Data sources fetched:",Object.keys(c))}catch(v){Gt.error("Failed to fetch data sources:",v)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Gt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Gt.log(`Error page ${e} rendered successfully`),!0}catch(a){return Gt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,n,a){for(const i of e){const l=n[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")a[i.initLocal]=c,Gt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;a[d]=f?this.getValueByPath(c,f):c,Gt.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=c,Gt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(c,m):c,Gt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,n){return n.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Gt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Gt.log("Config cache cleared")}}const jt=ht("ModuleAssetLoader");class gA{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){jt.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);jt.log("Loading module assets:",n.map(d=>d.identifier));const a=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...a,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){jt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}jt.log("All module assets loaded successfully")}async loadBundle(e,n,a){const i=[];if(a&&i.push(this.loadBundleCss(e,a)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){jt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,n){const a=`ext-bundle-css-${e}`;if(document.getElementById(a)){jt.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=n,l.id=a,l.onload=()=>{jt.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{jt.warn(`Failed to load bundle CSS: ${e} (${n})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,n){const a=`ext-bundle-js-${e}`;if(document.getElementById(a)){jt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(a);if(i)return jt.log(`Bundle JS already loading: ${e}`),i;const l=lp(n,{id:a},{label:`bundle JS: ${e}`}).then(()=>{jt.log(`Bundle JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:c}),this.loadingPromises.delete(a)}).catch(c=>{throw jt.warn(`Failed to load bundle JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(a),c});return this.loadingPromises.set(a,l),l}async loadCSS(e,n){const a=`module-css-${e}`;if(document.getElementById(a)){jt.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const c=document.createElement("link");c.rel="stylesheet",c.href=n,c.id=a,c.onload=()=>{jt.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:c}),i()},c.onerror=()=>{jt.warn(`Failed to load CSS: ${e} (${n})`),i()},document.head.appendChild(c)})}async loadJS(e,n){const a=`module-js-${e}`;if(document.getElementById(a)){jt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return jt.log(`JS already loading: ${e}`),i;const l=lp(n,{id:a},{label:`JS: ${e}`}).then(()=>{jt.log(`JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw jt.warn(`Failed to load JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const a=this.loadedAssets.get(e)||[];a.push(n),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){jt.log(`No assets to unload for: ${e}`);return}n.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),jt.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),jt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),jt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let Cf=null;function Ef(){return Cf||(Cf=new gA),Cf}function pA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[n,a]of Object.entries(o.moduleAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}function mA(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?Ea(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ea(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ea(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ea(e.pluginCss):e.pluginCss}}function yA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[n,a]of Object.entries(o.pluginAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}const _f=ht("SystemBannerManager");class Ac{static show(e){this.banners.set(e.id,e),this.render(),_f.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),_f.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),_f.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),a=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,a),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}$(Ac,"banners",new Map),$(Ac,"containerId","g7-system-banners");const B=ht("TemplateApp");function Ay(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}const xr=class xr{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),a=n||e.locale||"ko";this.config={...e,locale:a},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,B.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,B.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,B.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,B.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new Dn,a={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=n.resolveBindings(l.path,a),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",c),l.path=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const c=l.redirect;l.redirect=n.resolveBindings(l.redirect,a),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",c),l.redirect=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const a=localStorage.getItem(n);a&&a!==localStorage.getItem(xr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(xr.LOCALE_STORAGE_KEY,a),B.log(`Migrated locale from '${n}' to '${xr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(a){B.warn(`Failed to migrate locale key '${n}':`,a)}}async init(){try{to.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),rw();const e=mr.getInstance(),n=br.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,l,c,d,f]=await Promise.all([No({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),Il(Nr(`/api/templates/${this.config.templateId}/routes`,"json",a>0?a:null),{label:"routes.json"}).then(A=>{if(!A.ok)throw new Error(`Failed to load routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to load routes from API");return A.data}).catch(A=>{throw B.error("Error loading routes:",A),A}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Nr(`/api/templates/${this.config.templateId}/config`,"json")).then(A=>A.ok?A.json():null).then(A=>!A?.success||!A?.data?null:A.data).catch(A=>(B.warn("Error loading template config:",A),null))]);if(B.log("Template Engine initialized"),B.log("ComponentRegistry loaded"),B.log("Routes data loaded"),B.log("User info preloaded"),B.log("Template config loaded:",f),f?.cache_version!==void 0){const A=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),B.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){B.log("Cache version changed, reloading routes...");const x=await Il(Nr(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(O=>{if(!O.ok)throw new Error(`Failed to reload routes: ${O.statusText}`);return O.json()}).then(O=>{if(!O.success)throw new Error("Failed to reload routes from API");return O.data});Array.isArray(x.routes)&&(x.routes=this.resolveRouteExpressions(x.routes),Object.assign(c,x),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>hp),M=O.getInstance();M.setCacheVersion(this.extensionCacheVersion);const T=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,T,"/api",!0),T!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(O){B.error("Failed to reload translations:",O)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,Sr().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{B.log("User logged out")}),n.on("authStateChange",A=>{B.log("Auth state changed:",A)}),B.log("AuthManager event handlers registered");const g=Hr(),m=this.config.templateType==="admin"?"admin":"user",y=n.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,x=n.getLoginRedirectUrl(m,A,"session_expired");window.location.href=x}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new pf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const S=new _r({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new hA({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:ms,dataSourceManager:S,globalState:this.globalState}),B.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){B.log("Server error handled, skipping normal initialization");return}if(this.router=new dA(this.config.templateId),Array.isArray(c.routes)){const A=this.resolveRouteExpressions(c.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");B.log("Router initialized:",this.router),B.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:v}=await Promise.resolve().then(()=>Pr),_=v();if(_&&(_.setDefaultContext({navigate:A=>this.router?.navigate(A)}),_.setGlobalStateUpdater((A,x)=>this.setGlobalState(A,x)),B.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",A=>this.handleRouteChange(A)),this.router.on("routeNotFound",A=>this.handleRouteNotFound(A)),typeof window<"u"&&_y(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await ms({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),B.log("Template App initialized successfully")}catch(e){B.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=Ef(),n=mA();if(!n){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=Ef(),n=pA();n.length>0&&(B.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const a=yA();a.length>0&&(B.log("Loading plugin assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a))}async handleRouteChange(e){const n=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(B.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,a);if(n!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",n);return}B.log("Layout loaded:",l);const c=Sr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[te,pe]of Object.entries(f))if(Array.isArray(pe))for(const N of pe)g.append(te,N);else g.set(te,pe);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:y,getActionDispatcher:S}=await Promise.resolve().then(()=>Pr),v=new y;if(i){const te=S();te&&te.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Ac.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),B.log("Preview mode activated")}else{const te=S();te?.isPreviewMode()&&(te.setPreviewMode(!1),Ac.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){v.setGlobalHeaders(this.currentGlobalHeaders);const te=S();te&&te.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(pe=>pe.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const te=S();te&&te.setNamedActions(l.named_actions)}const _=v.filterByCondition(d,m);d.length!==_.length&&B.log("Data sources filtered by condition:",{before:d.map(te=>te.id),after:_.map(te=>te.id)});const A=_.filter(te=>te.loading_strategy==="blocking"),x=_.filter(te=>(te.loading_strategy||"progressive")!=="blocking"&&te.type!=="websocket"),O=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=O.length>0&&_.some(te=>O.includes(te.id)&&te.type!=="websocket"&&(te.loading_strategy||"progressive")!=="background");if((A.length>0||M)&&l.transition_overlay){const te=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;te.enabled&&te.style==="skeleton"&&te.skeleton?.component&&te.target?this.renderSkeletonOverlay(te.target,te.skeleton,l,te.fallback_target):te.enabled&&te.style==="spinner"&&te.target&&this.renderSpinnerOverlay(te.target,te.spinner,te.fallback_target)}let T={},D={},z={},P={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),v.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${n} - queryObject:`,f),B.log(`handleRouteChange #${n} - queryParams:`,g.toString()),A.length>0&&(B.log("Fetching blocking data sources:",A.map(pe=>pe.id)),(await v.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(pe=>{if(pe.state==="success"&&pe.data!==void 0)T[pe.id]=pe.data;else if(pe.state==="error"&&pe.error){const N=pe.error,R=N.response?.data?.message;D[pe.id]={message:R||pe.error.message,status:N.response?.status||N.status}}}),this.processInitOptions(A,T,z,P),this.currentFetchedData={...T},B.log("Blocking data loaded:",Object.keys(T)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(z).length>0&&B.log("Local state init (blocking):",Object.keys(z)),Object.keys(P).length>0&&B.log("Isolated state init (blocking):",Object.keys(P)));const q=x.length>0;if(q&&(jr.setPending(!0),B.log("Transition started before rendering")),n!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:W}=await Promise.resolve().then(()=>Pr),he=W().currentDataContext||{},Ee=x.map(te=>te.id),be={};if(q){Ee.forEach(pe=>{he[pe]!==void 0?be[pe]=he[pe]:be[pe]=void 0});const te=Object.keys(be).filter(pe=>be[pe]!==void 0);te.length>0&&B.log("Preserving previous progressive data:",te),B.log("Progressive data sources initialized:",Ee)}const Ue=l.defines||{},Fe={...be,...e.params,...T,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:te=>this.setGlobalState(te),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys(z).length>0?z:void 0,_isolatedInit:Object.keys(P).length>0?P:void 0,_defines:Object.keys(Ue).length>0?Ue:void 0};if(l.computed&&Object.keys(l.computed).length>0){const te=this.calculateComputed(l.computed,Fe);Object.keys(te).length>0&&(Fe._computed=te,this.globalState._computed=te,B.log("Computed values calculated:",Object.keys(te))),Fe._computedDefinitions=l.computed}const Ge=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Ge&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Ge}),this.globalState._local={},TC()),this.currentLayoutName=Ge;const J=l.initLocal||l.state;if(J&&Object.keys(J).length>0){this.globalState._local||(this.globalState._local={});for(const[te,pe]of Object.entries(J))this.globalState._local[te]===void 0&&(this.globalState._local[te]=JSON.parse(JSON.stringify(pe)));Fe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(J))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[te,pe]of Object.entries(l.initGlobal))this.globalState[te]===void 0&&(this.globalState[te]=JSON.parse(JSON.stringify(pe)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[te,pe]of Object.entries(l.initIsolated))P[te]===void 0&&(P[te]=JSON.parse(JSON.stringify(pe)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}Fe._global={...this.globalState,layoutWarnings:l.warnings||[]};const ue=l.initActions||l.init_actions;if(ue&&ue.length>0){await this.executeInitActions(ue,Fe),B.log("initActions executed before render");const te=this.globalState;if(te._local){if(Object.keys(z).length>0){for(const[pe,N]of Object.entries(z))te._local[pe]!==void 0?te._local[pe]=this.deepMerge(te._local[pe],N):te._local[pe]=N;B.log("localInit merged into _local after initActions:",Object.keys(z))}Fe._local=te._local,B.log("_local merged into dataContext:",te._local)}if(Fe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const pe=this.calculateComputed(l.computed,Fe);Object.keys(pe).length>0&&(Fe._computed=pe,this.globalState._computed=pe,B.log("Computed values recalculated after init_actions:",Object.keys(pe)))}if(Object.keys(this.currentFetchedData).length>0){for(const[pe,N]of Object.entries(this.currentFetchedData))Fe[pe]=N;B.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await ms({containerId:"app",layoutJson:l,dataContext:Fe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),x.length>0){if(n!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",n),jr.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",x.map(N=>N.id));const{updateTemplateData:te,getState:pe}=await Promise.resolve().then(()=>Pr);try{const N=x.map(async R=>{try{const fe=(await v.fetchDataSourcesWithResults([R],e.params||{},g,this.globalState))[0];if(!fe){B.log(`Data source ${R.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){B.log(`Data source ${R.id} fetch cancelled (newer request exists)`);return}if(fe.state==="success"&&fe.data!==void 0){B.log(`Progressive data source loaded: ${R.id}`),this.currentFetchedData[R.id]=fe.data;const xe={};this.processInitOptions([R],{[R.id]:fe.data},xe);const ee=pe();if(ee.bindingEngine){const Be=[R.id];R.initGlobal&&Be.push("_global"),R.initLocal&&Be.push("_local"),ee.bindingEngine.invalidateCacheByKeys(Be)}const _e={[R.id]:fe.data};Object.keys(xe).length>0&&(_e._localInit=xe,Object.assign(z,xe)),R.initGlobal&&(_e._global={...this.globalState}),te(_e)}else if(fe.state==="error"&&fe.error){const xe=fe.error,ee=xe.response?.data?.message;D[R.id]={message:ee||fe.error.message,status:xe.response?.status||xe.status},B.log(`Progressive data source error: ${R.id}`,D[R.id]),te({[R.id]:null,_dataSourceErrors:{...D}})}}catch(de){B.error(`Failed to fetch data source: ${R.id}`,de)}});if(await Promise.all(N),n!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",n);return}B.log("All progressive data sources loaded")}finally{jr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Me=_.filter(te=>te.type==="websocket");if(Me.length>0){B.log("Subscribing WebSocket data sources:",Me.map(R=>R.id));const{updateTemplateData:te,getState:pe}=await Promise.resolve().then(()=>Pr),N={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(N)),this.currentWebSocketSubscriptions=v.subscribeWebSockets(_,(R,de)=>{B.log(`WebSocket data received for: ${R}`,de),this.currentFetchedData[R]=de;const fe=_.find(Be=>Be.id===R),xe=pe();if(xe.bindingEngine){const Be=[R];fe?.initGlobal&&Be.push("_global"),fe?.initLocal&&Be.push("_local"),xe.bindingEngine.invalidateCacheByKeys(Be)}te({[R]:de});const _e=_.find(Be=>Be.type==="websocket"&&(Be.target_source||Be.id)===R)?.onReceive;Array.isArray(_e)&&_e.length>0&&window.G7Core?.dispatch&&(async()=>{for(const ke of _e)try{const Ie=this.getActionDispatcher?.();Ie&&await Ie.dispatchAction(ke,{navigate:this.getRouter?.()?(Ct,ot)=>this.getRouter().navigate(Ct,ot):void 0,setState:Ct=>this.setGlobalState(Ct),state:this.globalState,data:{...this.globalState,$args:[de],$event:de},_isDispatchFallbackContext:!0})}catch(Ie){B.error(`WebSocket onReceive action failed for ${R}:`,Ie)}})()},N),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(a){B.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,n,a,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(a._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=n[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let g=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);g={...y,...f},B.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(a[c.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(a[c.initLocal]=g,B.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:g,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const v=this.evaluateDefaults(c.initLocalDefaults,n);y={...v,...y},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(v))}const S=this.globalState._local?.[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(a[g]=this.deepMerge(S,y),B.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${g}`)):(a[g]=y,B.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof c.initLocal=="object"){const g=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:S}of m){const v=this.extractValueByPathOrExpression(f,S,c.id);if(y.includes(".")){const _=y.split(".")[0];a[_]===void 0&&this.globalState._local?.[_]!==void 0&&(a[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(a,y,v,g),B.log(`initLocal map (${g}): ${c.id} ${S} -> _local.${y}`)}else{const _=this.globalState._local?.[y];g==="replace"?(a[y]=v,B.log(`initLocal map (replace): ${c.id} ${S} -> _local.${y}`)):g==="shallow"?_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[y]={..._,...v},B.log(`initLocal map (shallow): ${c.id} ${S} -> _local.${y}`)):(a[y]=v,B.log(`initLocal map: ${c.id} ${S} -> _local.${y}`)):_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[y]=this.deepMerge(_,v),B.log(`initLocal map (deep): ${c.id} ${S} -> _local.${y}`)):(a[y]=v,B.log(`initLocal map: ${c.id} ${S} -> _local.${y}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,y]of Object.entries(c.initGlobal)){if(typeof y!="string"){B.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const S=this.extractValueByPathOrExpression(f,y,c.id),v=this.globalState[m];v!==void 0&&typeof v=="object"&&typeof S=="object"?(this.globalState[m]=this.deepMerge(v,S),B.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=S,B.log(`initGlobal map: ${c.id} ${y} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const y of m)if(typeof y=="string"){const S=this.globalState[y];S!==void 0&&typeof S=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(S,f),B.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,B.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:S,path:v}=y,_=v?this.extractValueByPathOrExpression(f,v,c.id):f,A=this.globalState[S];A!==void 0&&typeof A=="object"&&typeof _=="object"?(this.globalState[S]=this.deepMerge(A,_),B.log(`initGlobal (merged): ${c.id}.data${v?"."+v:""} -> _global.${S}`)):(this.globalState[S]=_,B.log(`initGlobal: ${c.id}.data${v?"."+v:""} -> _global.${S}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const g=i[c.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,B.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:g,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,S=i[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(i[g]=this.deepMerge(S,y),B.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=y,B.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof c.initIsolated=="object")for(const[g,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),S=i[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(i[g]=this.deepMerge(S,y),B.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${g}`)):(i[g]=y,B.log(`initIsolated map: ${c.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,n){const a={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();a[i]=this.evaluateExpression(c,n)}else a[i]=l;return a}evaluateExpression(e,n){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(a){B.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,n){const a=n.replace(/\?\./g,".");let i=e;const l=a.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const y=g.match(/\[\d+\]/g);return y&&m.push(...y),m}return[c]}).filter(c=>c!=="");for(const c of l){if(i==null)return;if(c.startsWith("[")&&c.endsWith("]")){const d=parseInt(c.slice(1,-1),10);i=i[d]}else i=i[c]}return i}extractValueByPathOrExpression(e,n,a){const i=Aa(n);if(i!==null){const l=new Dn,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=$n(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return B.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){B.warn(`initLocal/initGlobal expression evaluation failed for ${a}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ns({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){B.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){B.log(`Script already loaded: ${i.id}`);continue}const c=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{B.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{B.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});a.push(c)}a.length>0&&(await Promise.all(a),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` + `}static renderFromError(e,n,a,i=!1,l,c,d){let f,g;if(n.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:a,message:f,detailMessage:g,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const ps=ht("Router");class dA{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,a=await fetch(Nr(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,ps.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw ps.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,ps.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const a of this.routes){const i=this.matchPattern(a.path,n);if(i!==null)return{route:a,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const a=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(a.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=n.match(l);if(!c)return null;const d={};return a.forEach((f,g)=>{d[f]=c[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,a=this.match(e);if(!a){ps.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){ps.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const c=this.getAuthType(a.route,e),d=br.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const g=d.getLoginRedirectUrl(c,e+n);ps.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(n),l={};for(const c of i.keys()){if(c in l)continue;const d=i.getAll(c);d.length>1?l[c]=d:d.length===1&&(c.endsWith("[]")?l[c]=d:l[c]=d[0])}await this.emit("routeChange",{path:e,layout:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:l,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const n=this.pendingNavigation;this.executeNavigation(n)}}}}const fA=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function Ey(o){const e=fA.exec(o);return e?{templateIdentifier:e[1]}:null}const Gt=ht("ErrorPageHandler");class hA{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(Nr(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Gt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Gt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=n.data;return!a.error_config||!a.error_config.layouts?(this.debug&&Gt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&Gt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Gt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&Gt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&Gt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Gt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Gt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Gt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Gt.log("Fetching data sources:",d.map(v=>v.id));const m=d.filter(v=>v.loading_strategy==="blocking"),y=d.filter(v=>!v.loading_strategy||v.loading_strategy==="progressive"),S=[...m,...y];if(S.length>0)try{c=await this.dataSourceManager.fetchDataSources(S,{},new URLSearchParams),this.debug&&Gt.log("Data sources fetched:",Object.keys(c))}catch(v){Gt.error("Failed to fetch data sources:",v)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Gt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Gt.log(`Error page ${e} rendered successfully`),!0}catch(a){return Gt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,n,a){for(const i of e){const l=n[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")a[i.initLocal]=c,Gt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;a[d]=f?this.getValueByPath(c,f):c,Gt.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=c,Gt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(c,m):c,Gt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,n){return n.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Gt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Gt.log("Config cache cleared")}}const jt=ht("ModuleAssetLoader");class gA{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){jt.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);jt.log("Loading module assets:",n.map(d=>d.identifier));const a=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...a,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){jt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}jt.log("All module assets loaded successfully")}async loadBundle(e,n,a){const i=[];if(a&&i.push(this.loadBundleCss(e,a)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){jt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,n){const a=`ext-bundle-css-${e}`;if(document.getElementById(a)){jt.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=n,l.id=a,l.onload=()=>{jt.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{jt.warn(`Failed to load bundle CSS: ${e} (${n})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,n){const a=`ext-bundle-js-${e}`;if(document.getElementById(a)){jt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(a);if(i)return jt.log(`Bundle JS already loading: ${e}`),i;const l=cp(n,{id:a},{label:`bundle JS: ${e}`}).then(()=>{jt.log(`Bundle JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:c}),this.loadingPromises.delete(a)}).catch(c=>{throw jt.warn(`Failed to load bundle JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(a),c});return this.loadingPromises.set(a,l),l}async loadCSS(e,n){const a=`module-css-${e}`;if(document.getElementById(a)){jt.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const c=document.createElement("link");c.rel="stylesheet",c.href=n,c.id=a,c.onload=()=>{jt.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:c}),i()},c.onerror=()=>{jt.warn(`Failed to load CSS: ${e} (${n})`),i()},document.head.appendChild(c)})}async loadJS(e,n){const a=`module-js-${e}`;if(document.getElementById(a)){jt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return jt.log(`JS already loading: ${e}`),i;const l=cp(n,{id:a},{label:`JS: ${e}`}).then(()=>{jt.log(`JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw jt.warn(`Failed to load JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const a=this.loadedAssets.get(e)||[];a.push(n),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){jt.log(`No assets to unload for: ${e}`);return}n.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),jt.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),jt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),jt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let Ef=null;function _f(){return Ef||(Ef=new gA),Ef}function pA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[n,a]of Object.entries(o.moduleAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}function mA(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?Ea(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ea(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ea(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ea(e.pluginCss):e.pluginCss}}function yA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[n,a]of Object.entries(o.pluginAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}const Af=ht("SystemBannerManager");class Ac{static show(e){this.banners.set(e.id,e),this.render(),Af.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),Af.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),Af.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),a=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,a),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}$(Ac,"banners",new Map),$(Ac,"containerId","g7-system-banners");const B=ht("TemplateApp");function _y(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}const xr=class xr{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),a=n||e.locale||"ko";this.config={...e,locale:a},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,B.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,B.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,B.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,B.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new Dn,a={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=n.resolveBindings(l.path,a),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",c),l.path=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const c=l.redirect;l.redirect=n.resolveBindings(l.redirect,a),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",c),l.redirect=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const a=localStorage.getItem(n);a&&a!==localStorage.getItem(xr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(xr.LOCALE_STORAGE_KEY,a),B.log(`Migrated locale from '${n}' to '${xr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(a){B.warn(`Failed to migrate locale key '${n}':`,a)}}async init(){try{to.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),nw();const e=mr.getInstance(),n=br.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,l,c,d,f]=await Promise.all([No({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),Il(Nr(`/api/templates/${this.config.templateId}/routes`,"json",a>0?a:null),{label:"routes.json"}).then(A=>{if(!A.ok)throw new Error(`Failed to load routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to load routes from API");return A.data}).catch(A=>{throw B.error("Error loading routes:",A),A}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Nr(`/api/templates/${this.config.templateId}/config`,"json")).then(A=>A.ok?A.json():null).then(A=>!A?.success||!A?.data?null:A.data).catch(A=>(B.warn("Error loading template config:",A),null))]);if(B.log("Template Engine initialized"),B.log("ComponentRegistry loaded"),B.log("Routes data loaded"),B.log("User info preloaded"),B.log("Template config loaded:",f),f?.cache_version!==void 0){const A=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),B.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){B.log("Cache version changed, reloading routes...");const x=await Il(Nr(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(O=>{if(!O.ok)throw new Error(`Failed to reload routes: ${O.statusText}`);return O.json()}).then(O=>{if(!O.success)throw new Error("Failed to reload routes from API");return O.data});Array.isArray(x.routes)&&(x.routes=this.resolveRouteExpressions(x.routes),Object.assign(c,x),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>gp),M=O.getInstance();M.setCacheVersion(this.extensionCacheVersion);const T=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,T,"/api",!0),T!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(O){B.error("Failed to reload translations:",O)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,Sr().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{B.log("User logged out")}),n.on("authStateChange",A=>{B.log("Auth state changed:",A)}),B.log("AuthManager event handlers registered");const g=Hr(),m=this.config.templateType==="admin"?"admin":"user",y=n.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,x=n.getLoginRedirectUrl(m,A,"session_expired");window.location.href=x}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new mf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const S=new _r({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new hA({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:ms,dataSourceManager:S,globalState:this.globalState}),B.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){B.log("Server error handled, skipping normal initialization");return}if(this.router=new dA(this.config.templateId),Array.isArray(c.routes)){const A=this.resolveRouteExpressions(c.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");B.log("Router initialized:",this.router),B.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:v}=await Promise.resolve().then(()=>Pr),_=v();if(_&&(_.setDefaultContext({navigate:A=>this.router?.navigate(A)}),_.setGlobalStateUpdater((A,x)=>this.setGlobalState(A,x)),B.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",A=>this.handleRouteChange(A)),this.router.on("routeNotFound",A=>this.handleRouteNotFound(A)),typeof window<"u"&&Ey(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await ms({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),B.log("Template App initialized successfully")}catch(e){B.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=_f(),n=mA();if(!n){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=_f(),n=pA();n.length>0&&(B.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const a=yA();a.length>0&&(B.log("Loading plugin assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a))}async handleRouteChange(e){const n=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(B.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,a);if(n!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",n);return}B.log("Layout loaded:",l);const c=Sr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[te,pe]of Object.entries(f))if(Array.isArray(pe))for(const N of pe)g.append(te,N);else g.set(te,pe);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:y,getActionDispatcher:S}=await Promise.resolve().then(()=>Pr),v=new y;if(i){const te=S();te&&te.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Ac.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),B.log("Preview mode activated")}else{const te=S();te?.isPreviewMode()&&(te.setPreviewMode(!1),Ac.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){v.setGlobalHeaders(this.currentGlobalHeaders);const te=S();te&&te.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(pe=>pe.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const te=S();te&&te.setNamedActions(l.named_actions)}const _=v.filterByCondition(d,m);d.length!==_.length&&B.log("Data sources filtered by condition:",{before:d.map(te=>te.id),after:_.map(te=>te.id)});const A=_.filter(te=>te.loading_strategy==="blocking"),x=_.filter(te=>(te.loading_strategy||"progressive")!=="blocking"&&te.type!=="websocket"),O=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=O.length>0&&_.some(te=>O.includes(te.id)&&te.type!=="websocket"&&(te.loading_strategy||"progressive")!=="background");if((A.length>0||M)&&l.transition_overlay){const te=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;te.enabled&&te.style==="skeleton"&&te.skeleton?.component&&te.target?this.renderSkeletonOverlay(te.target,te.skeleton,l,te.fallback_target):te.enabled&&te.style==="spinner"&&te.target&&this.renderSpinnerOverlay(te.target,te.spinner,te.fallback_target)}let T={},D={},z={},P={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),v.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${n} - queryObject:`,f),B.log(`handleRouteChange #${n} - queryParams:`,g.toString()),A.length>0&&(B.log("Fetching blocking data sources:",A.map(pe=>pe.id)),(await v.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(pe=>{if(pe.state==="success"&&pe.data!==void 0)T[pe.id]=pe.data;else if(pe.state==="error"&&pe.error){const N=pe.error,R=N.response?.data?.message;D[pe.id]={message:R||pe.error.message,status:N.response?.status||N.status}}}),this.processInitOptions(A,T,z,P),this.currentFetchedData={...T},B.log("Blocking data loaded:",Object.keys(T)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(z).length>0&&B.log("Local state init (blocking):",Object.keys(z)),Object.keys(P).length>0&&B.log("Isolated state init (blocking):",Object.keys(P)));const q=x.length>0;if(q&&(jr.setPending(!0),B.log("Transition started before rendering")),n!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:W}=await Promise.resolve().then(()=>Pr),he=W().currentDataContext||{},Ee=x.map(te=>te.id),be={};if(q){Ee.forEach(pe=>{he[pe]!==void 0?be[pe]=he[pe]:be[pe]=void 0});const te=Object.keys(be).filter(pe=>be[pe]!==void 0);te.length>0&&B.log("Preserving previous progressive data:",te),B.log("Progressive data sources initialized:",Ee)}const Ue=l.defines||{},Fe={...be,...e.params,...T,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:te=>this.setGlobalState(te),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys(z).length>0?z:void 0,_isolatedInit:Object.keys(P).length>0?P:void 0,_defines:Object.keys(Ue).length>0?Ue:void 0};if(l.computed&&Object.keys(l.computed).length>0){const te=this.calculateComputed(l.computed,Fe);Object.keys(te).length>0&&(Fe._computed=te,this.globalState._computed=te,B.log("Computed values calculated:",Object.keys(te))),Fe._computedDefinitions=l.computed}const Ge=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Ge&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Ge}),this.globalState._local={},TC()),this.currentLayoutName=Ge;const J=l.initLocal||l.state;if(J&&Object.keys(J).length>0){this.globalState._local||(this.globalState._local={});for(const[te,pe]of Object.entries(J))this.globalState._local[te]===void 0&&(this.globalState._local[te]=JSON.parse(JSON.stringify(pe)));Fe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(J))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[te,pe]of Object.entries(l.initGlobal))this.globalState[te]===void 0&&(this.globalState[te]=JSON.parse(JSON.stringify(pe)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[te,pe]of Object.entries(l.initIsolated))P[te]===void 0&&(P[te]=JSON.parse(JSON.stringify(pe)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}Fe._global={...this.globalState,layoutWarnings:l.warnings||[]};const ue=l.initActions||l.init_actions;if(ue&&ue.length>0){await this.executeInitActions(ue,Fe),B.log("initActions executed before render");const te=this.globalState;if(te._local){if(Object.keys(z).length>0){for(const[pe,N]of Object.entries(z))te._local[pe]!==void 0?te._local[pe]=this.deepMerge(te._local[pe],N):te._local[pe]=N;B.log("localInit merged into _local after initActions:",Object.keys(z))}Fe._local=te._local,B.log("_local merged into dataContext:",te._local)}if(Fe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const pe=this.calculateComputed(l.computed,Fe);Object.keys(pe).length>0&&(Fe._computed=pe,this.globalState._computed=pe,B.log("Computed values recalculated after init_actions:",Object.keys(pe)))}if(Object.keys(this.currentFetchedData).length>0){for(const[pe,N]of Object.entries(this.currentFetchedData))Fe[pe]=N;B.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await ms({containerId:"app",layoutJson:l,dataContext:Fe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),x.length>0){if(n!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",n),jr.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",x.map(N=>N.id));const{updateTemplateData:te,getState:pe}=await Promise.resolve().then(()=>Pr);try{const N=x.map(async R=>{try{const fe=(await v.fetchDataSourcesWithResults([R],e.params||{},g,this.globalState))[0];if(!fe){B.log(`Data source ${R.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){B.log(`Data source ${R.id} fetch cancelled (newer request exists)`);return}if(fe.state==="success"&&fe.data!==void 0){B.log(`Progressive data source loaded: ${R.id}`),this.currentFetchedData[R.id]=fe.data;const xe={};this.processInitOptions([R],{[R.id]:fe.data},xe);const ee=pe();if(ee.bindingEngine){const Be=[R.id];R.initGlobal&&Be.push("_global"),R.initLocal&&Be.push("_local"),ee.bindingEngine.invalidateCacheByKeys(Be)}const _e={[R.id]:fe.data};Object.keys(xe).length>0&&(_e._localInit=xe,Object.assign(z,xe)),R.initGlobal&&(_e._global={...this.globalState}),te(_e)}else if(fe.state==="error"&&fe.error){const xe=fe.error,ee=xe.response?.data?.message;D[R.id]={message:ee||fe.error.message,status:xe.response?.status||xe.status},B.log(`Progressive data source error: ${R.id}`,D[R.id]),te({[R.id]:null,_dataSourceErrors:{...D}})}}catch(de){B.error(`Failed to fetch data source: ${R.id}`,de)}});if(await Promise.all(N),n!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",n);return}B.log("All progressive data sources loaded")}finally{jr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Me=_.filter(te=>te.type==="websocket");if(Me.length>0){B.log("Subscribing WebSocket data sources:",Me.map(R=>R.id));const{updateTemplateData:te,getState:pe}=await Promise.resolve().then(()=>Pr),N={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(N)),this.currentWebSocketSubscriptions=v.subscribeWebSockets(_,(R,de)=>{B.log(`WebSocket data received for: ${R}`,de),this.currentFetchedData[R]=de;const fe=_.find(Be=>Be.id===R),xe=pe();if(xe.bindingEngine){const Be=[R];fe?.initGlobal&&Be.push("_global"),fe?.initLocal&&Be.push("_local"),xe.bindingEngine.invalidateCacheByKeys(Be)}te({[R]:de});const _e=_.find(Be=>Be.type==="websocket"&&(Be.target_source||Be.id)===R)?.onReceive;Array.isArray(_e)&&_e.length>0&&window.G7Core?.dispatch&&(async()=>{for(const ke of _e)try{const Ie=this.getActionDispatcher?.();Ie&&await Ie.dispatchAction(ke,{navigate:this.getRouter?.()?(Ct,ot)=>this.getRouter().navigate(Ct,ot):void 0,setState:Ct=>this.setGlobalState(Ct),state:this.globalState,data:{...this.globalState,$args:[de],$event:de},_isDispatchFallbackContext:!0})}catch(Ie){B.error(`WebSocket onReceive action failed for ${R}:`,Ie)}})()},N),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(a){B.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,n,a,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(a._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=n[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let g=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);g={...y,...f},B.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(a[c.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(a[c.initLocal]=g,B.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:g,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const v=this.evaluateDefaults(c.initLocalDefaults,n);y={...v,...y},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(v))}const S=this.globalState._local?.[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(a[g]=this.deepMerge(S,y),B.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${g}`)):(a[g]=y,B.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof c.initLocal=="object"){const g=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:S}of m){const v=this.extractValueByPathOrExpression(f,S,c.id);if(y.includes(".")){const _=y.split(".")[0];a[_]===void 0&&this.globalState._local?.[_]!==void 0&&(a[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(a,y,v,g),B.log(`initLocal map (${g}): ${c.id} ${S} -> _local.${y}`)}else{const _=this.globalState._local?.[y];g==="replace"?(a[y]=v,B.log(`initLocal map (replace): ${c.id} ${S} -> _local.${y}`)):g==="shallow"?_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[y]={..._,...v},B.log(`initLocal map (shallow): ${c.id} ${S} -> _local.${y}`)):(a[y]=v,B.log(`initLocal map: ${c.id} ${S} -> _local.${y}`)):_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[y]=this.deepMerge(_,v),B.log(`initLocal map (deep): ${c.id} ${S} -> _local.${y}`)):(a[y]=v,B.log(`initLocal map: ${c.id} ${S} -> _local.${y}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,y]of Object.entries(c.initGlobal)){if(typeof y!="string"){B.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const S=this.extractValueByPathOrExpression(f,y,c.id),v=this.globalState[m];v!==void 0&&typeof v=="object"&&typeof S=="object"?(this.globalState[m]=this.deepMerge(v,S),B.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=S,B.log(`initGlobal map: ${c.id} ${y} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const y of m)if(typeof y=="string"){const S=this.globalState[y];S!==void 0&&typeof S=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(S,f),B.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,B.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:S,path:v}=y,_=v?this.extractValueByPathOrExpression(f,v,c.id):f,A=this.globalState[S];A!==void 0&&typeof A=="object"&&typeof _=="object"?(this.globalState[S]=this.deepMerge(A,_),B.log(`initGlobal (merged): ${c.id}.data${v?"."+v:""} -> _global.${S}`)):(this.globalState[S]=_,B.log(`initGlobal: ${c.id}.data${v?"."+v:""} -> _global.${S}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const g=i[c.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,B.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:g,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,S=i[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(i[g]=this.deepMerge(S,y),B.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=y,B.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof c.initIsolated=="object")for(const[g,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),S=i[g];S!==void 0&&typeof S=="object"&&typeof y=="object"?(i[g]=this.deepMerge(S,y),B.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${g}`)):(i[g]=y,B.log(`initIsolated map: ${c.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,n){const a={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();a[i]=this.evaluateExpression(c,n)}else a[i]=l;return a}evaluateExpression(e,n){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(a){B.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,n){const a=n.replace(/\?\./g,".");let i=e;const l=a.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const y=g.match(/\[\d+\]/g);return y&&m.push(...y),m}return[c]}).filter(c=>c!=="");for(const c of l){if(i==null)return;if(c.startsWith("[")&&c.endsWith("]")){const d=parseInt(c.slice(1,-1),10);i=i[d]}else i=i[c]}return i}extractValueByPathOrExpression(e,n,a){const i=Aa(n);if(i!==null){const l=new Dn,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Vn(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return B.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){B.warn(`initLocal/initGlobal expression evaluation failed for ${a}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ns({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){B.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){B.log(`Script already loaded: ${i.id}`);continue}const c=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{B.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{B.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});a.push(c)}a.length>0&&(await Promise.all(a),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` with(ctx) { try { return Boolean(${a}); @@ -232,7 +232,7 @@ Error generating stack: `+u.message+` return false; } } - `)(n)}return!!e}catch(a){return B.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){if(fd()){B.warn("Init failed while document is unloading — skipping error screen",e);return}const n=Ey(e);wf.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&n){this.renderSkeletonOverlay(a.target,a.skeleton,n,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(a.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",c="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(a.target){const d=`#${CSS.escape(a.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${c}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of c.split(";")){const g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,a,i){const c=mr.getInstance().getComponent(n.component);if(!c){B.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){B.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=f==="fullpage"?"app":f==="fallback"?i:e,S=`#${CSS.escape(y)}`,v=document.createElement("style");v.id="g7-skeleton-overlay-style",v.textContent=`${S}{position:relative;z-index:0;}${S}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(v),this.transitionOverlayEl=v;const _=document.createElement("div");if(_.id="g7-skeleton-overlay",_.setAttribute("role","status"),_.setAttribute("aria-busy","true"),_.setAttribute("aria-label","Loading..."),f==="fullpage")_.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const T=d.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,z=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${T.top+z}px`,`left:${T.left+D}px`,`width:${T.width}px`,`height:${T.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const A=a.components||[];let x;if(f==="fullpage")x=A;else{const T=f==="fallback"?i:e;x=this.findComponentChildrenById(A,T)}const O=od.createRoot(_);this.skeletonOverlayRoot=O,ka.flushSync(()=>{O.render(Xe.createElement(c,{components:x,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;B.log(`Skeleton overlay rendered [${M}] with "${n.component}" (${x.length} components)`)}findComponentChildrenById(e,n){const a=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=a(l.children);if(c!==null)return c}}return null};return a(e)||e}renderSpinnerOverlay(e,n,a){let i=document.getElementById(e),l="target";if(!i&&a&&(i=document.getElementById(a),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){B.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?a:e,d=`#${CSS.escape(c)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const g=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:n,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${a})`:`target (#${e})`,y=n?.component||"default spinner";B.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,n?.component){const c=mr.getInstance().getComponent(n.component);if(c){const d=od.createRoot(i);this.skeletonOverlayRoot=d,ka.flushSync(()=>{d.render(Xe.createElement(c,{options:{text:a}}))});return}B.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let a=document.getElementById(e);!a&&n&&(a=document.getElementById(n)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),B.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){if(e instanceof Er&&e.details?.status===401){const a=this.config.templateId||"",i=window.location.pathname,l=a.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!Hr().getToken()||e.details?.hadToken===!0,f=br.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=Ey(e);wf.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;B.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(B.log(`${e.code} error page rendered successfully`),!0):(B.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return B.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){B.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){B.log("404 error page rendered successfully");return}B.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){B.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){B.log("reloadExtensionState: start");let e;try{const n=await fetch(Nr(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const a=await n.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.data.cache_version)}}catch(n){B.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(B.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),B.log("reloadExtensionState: routes reloaded"))}catch(n){B.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),B.log("reloadExtensionState: layout cache cleared"))}catch(n){B.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>hp),a=n.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await a.loadTranslations(this.config.templateId,l,"/api",!0),B.log("reloadExtensionState: translations reloaded")}catch(n){B.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),B.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){B.warn("reloadExtensionState: supportedLocales refresh failed",n)}B.log("reloadExtensionState: done")}getActionDispatcher(){return ea().actionDispatcher}async changeLocale(e){try{if(B.log("Changing locale to:",e),this.config.locale===e){B.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),B.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),B.log("ErrorPageHandler locale updated")),xc(),await No({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),B.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Pr),a=n();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),B.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),B.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),B.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),B.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),B.log("Locale changed successfully to",e)}catch(n){throw B.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(xr.LOCALE_STORAGE_KEY)}catch(e){return B.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(xr.LOCALE_STORAGE_KEY,e)}catch(n){B.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){B.log("No auth token, skipping DB locale save");return}let a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";a=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});c.ok?B.log("Locale saved to DB:",e):B.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){B.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(xr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return B.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(xr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){B.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(a=>{if(a.startsWith(e)&&typeof n[a]?.initModule=="function")try{n[a].initModule(),B.log(`Module handler re-initialized: ${a}`)}catch(i){B.warn(`Failed to re-initialize module handlers for ${a}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){B.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){B.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([a,i])=>{n.registerHandler(a,i)}),B.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(a=>{if(a.startsWith(e)&&typeof n[a]?.initPlugin=="function")try{n[a].initPlugin(),B.log(`Plugin handler re-initialized: ${a}`)}catch(i){B.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const a={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},B.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:a,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Pr).then(({updateTemplateData:l,getState:c})=>{const d=c();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){a=l;break}}if(!a){B.warn(`Data source not found: ${e}`);return}B.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),jr.setPending(!0);try{const i=new _r;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ea(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},g=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const S={};this.processInitOptions([a],{[e]:y.data},S);const v=ea();if(v.bindingEngine){const A=[e];a.initGlobal&&A.push("_global"),a.initLocal&&A.push("_local"),v.bindingEngine.invalidateCacheByKeys(A)}const _={[e]:y.data};return Object.keys(S).length>0&&(_._localInit=S),a.initGlobal&&(_._global={...this.globalState}),ys(_,n?.sync?{sync:!0}:void 0),B.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){B.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){B.error(`Error refetching data source: ${e}`,i);return}finally{jr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),B.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),B.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,a){if(!e){B.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Pr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),B.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,a,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return B.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=g;for(const _ of m)if(y=y?.[_],y===void 0)return B.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return B.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const S=y.findIndex(_=>String(_[c])===String(a));if(S===-1)return B.warn(`updateDataSourceItem: Item with ${c}='${a}' not found`),!1;d?y[S]=this.deepMerge(y[S],i):y[S]={...y[S],...i};const v=window.G7Core?.devTools;return v?.isEnabled?.()&&v.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:a,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Pr).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),B.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${a}]`),!0}parseItemPath(e){const n=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const a={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?a[i]=this.deepMerge(a[i]||{},n[i]):a[i]=n[i];return a}setValueAtPath(e,n,a,i="deep"){const l=n.split(".");let c=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(A=>A.auto_fetch!==!1&&A.type!=="websocket");if(g.length===0){B.log("No auto_fetch data sources to refetch");return}B.log(`Refetching ${g.length} auto_fetch data sources`),jr.setPending(!0);const m=ea().currentLayoutJson,y=m?.transition_overlay,S=Array.isArray(y?.wait_for)?y.wait_for:[],v=g.some(A=>(A.loading_strategy||"progressive")==="blocking"),_=S.length>0&&g.some(A=>S.includes(A.id)&&A.type!=="websocket"&&(A.loading_strategy||"progressive")!=="background");if((v||_)&&y&&typeof y=="object"){const A=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&A?this.renderSkeletonOverlay(A,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&A&&this.renderSpinnerOverlay(A,y.spinner,y.fallback_target)}try{const A=new _r;this.currentGlobalHeaders.length>0&&A.setGlobalHeaders(this.currentGlobalHeaders);const x=ea(),O=x.currentDataContext?._global||{},M=await A.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,O,void 0,{ignoreAutoFetch:!1}),T={},D={},z=new Map(g.map(P=>[P.id,P]));for(const P of M){const q=z.get(P.id);if(!q){B.warn(`Refetch result id not found in autoFetchDataSources: ${P.id}`);continue}const W=P.id;P.state==="success"&&P.data!==void 0?(this.currentFetchedData[W]=P.data,T[W]=P.data,this.processInitOptions([q],{[W]:P.data},D),B.log(`Data source refetched: ${W}`)):P.state==="error"&&B.error(`Failed to refetch data source: ${W}`,P.error)}if(x.bindingEngine){const P=Object.keys(T);P.push("query"),x.bindingEngine.invalidateCacheByKeys(P)}if(Object.keys(D).length>0&&(T._localInit=D),Object.keys(T).length>0){if(T.query=Ay(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const P={...x.currentDataContext,...T,query:T.query},q=this.calculateComputed(x.currentLayoutJson.computed,P);Object.keys(q).length>0&&(T._computed=q,this.globalState._computed=q,B.log("Computed values recalculated in updateQueryParams:",Object.keys(q)))}ys(T,{sync:!0}),B.log("Template data updated with new query params")}}catch(A){B.error("Error in updateQueryParams:",A)}finally{jr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const a={},i=new Dn;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,n,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=c;a[l]=d,B.log(`Computed ${l}:`,d)}catch(d){B.warn(`Failed to calculate computed value: ${l}`,d),a[l]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return new Function("ctx",` + `)(n)}return!!e}catch(a){return B.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){if(fd()){B.warn("Init failed while document is unloading — skipping error screen",e);return}const n=Cy(e);Cf.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&n){this.renderSkeletonOverlay(a.target,a.skeleton,n,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(a.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",c="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(a.target){const d=`#${CSS.escape(a.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${c}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of c.split(";")){const g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,a,i){const c=mr.getInstance().getComponent(n.component);if(!c){B.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){B.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=f==="fullpage"?"app":f==="fallback"?i:e,S=`#${CSS.escape(y)}`,v=document.createElement("style");v.id="g7-skeleton-overlay-style",v.textContent=`${S}{position:relative;z-index:0;}${S}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(v),this.transitionOverlayEl=v;const _=document.createElement("div");if(_.id="g7-skeleton-overlay",_.setAttribute("role","status"),_.setAttribute("aria-busy","true"),_.setAttribute("aria-label","Loading..."),f==="fullpage")_.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const T=d.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,z=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${T.top+z}px`,`left:${T.left+D}px`,`width:${T.width}px`,`height:${T.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const A=a.components||[];let x;if(f==="fullpage")x=A;else{const T=f==="fallback"?i:e;x=this.findComponentChildrenById(A,T)}const O=od.createRoot(_);this.skeletonOverlayRoot=O,ka.flushSync(()=>{O.render(Xe.createElement(c,{components:x,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;B.log(`Skeleton overlay rendered [${M}] with "${n.component}" (${x.length} components)`)}findComponentChildrenById(e,n){const a=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=a(l.children);if(c!==null)return c}}return null};return a(e)||e}renderSpinnerOverlay(e,n,a){let i=document.getElementById(e),l="target";if(!i&&a&&(i=document.getElementById(a),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){B.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?a:e,d=`#${CSS.escape(c)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const g=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:n,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${a})`:`target (#${e})`,y=n?.component||"default spinner";B.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,n?.component){const c=mr.getInstance().getComponent(n.component);if(c){const d=od.createRoot(i);this.skeletonOverlayRoot=d,ka.flushSync(()=>{d.render(Xe.createElement(c,{options:{text:a}}))});return}B.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let a=document.getElementById(e);!a&&n&&(a=document.getElementById(n)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),B.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){if(e instanceof Er&&e.details?.status===401){const a=this.config.templateId||"",i=window.location.pathname,l=a.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!Hr().getToken()||e.details?.hadToken===!0,f=br.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=Cy(e);Cf.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;B.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(B.log(`${e.code} error page rendered successfully`),!0):(B.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return B.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){B.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){B.log("404 error page rendered successfully");return}B.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){B.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){B.log("reloadExtensionState: start");let e;try{const n=await fetch(Nr(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const a=await n.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.data.cache_version)}}catch(n){B.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(B.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),B.log("reloadExtensionState: routes reloaded"))}catch(n){B.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),B.log("reloadExtensionState: layout cache cleared"))}catch(n){B.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>gp),a=n.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await a.loadTranslations(this.config.templateId,l,"/api",!0),B.log("reloadExtensionState: translations reloaded")}catch(n){B.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),B.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){B.warn("reloadExtensionState: supportedLocales refresh failed",n)}B.log("reloadExtensionState: done")}getActionDispatcher(){return ea().actionDispatcher}async changeLocale(e){try{if(B.log("Changing locale to:",e),this.config.locale===e){B.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),B.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),B.log("ErrorPageHandler locale updated")),xc(),await No({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),B.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Pr),a=n();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),B.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),B.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),B.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),B.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),B.log("Locale changed successfully to",e)}catch(n){throw B.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(xr.LOCALE_STORAGE_KEY)}catch(e){return B.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(xr.LOCALE_STORAGE_KEY,e)}catch(n){B.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){B.log("No auth token, skipping DB locale save");return}let a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";a=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});c.ok?B.log("Locale saved to DB:",e):B.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){B.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(xr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return B.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(xr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){B.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(a=>{if(a.startsWith(e)&&typeof n[a]?.initModule=="function")try{n[a].initModule(),B.log(`Module handler re-initialized: ${a}`)}catch(i){B.warn(`Failed to re-initialize module handlers for ${a}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){B.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){B.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([a,i])=>{n.registerHandler(a,i)}),B.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(a=>{if(a.startsWith(e)&&typeof n[a]?.initPlugin=="function")try{n[a].initPlugin(),B.log(`Plugin handler re-initialized: ${a}`)}catch(i){B.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const a={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},B.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:a,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Pr).then(({updateTemplateData:l,getState:c})=>{const d=c();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){a=l;break}}if(!a){B.warn(`Data source not found: ${e}`);return}B.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),jr.setPending(!0);try{const i=new _r;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ea(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},g=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const S={};this.processInitOptions([a],{[e]:y.data},S);const v=ea();if(v.bindingEngine){const A=[e];a.initGlobal&&A.push("_global"),a.initLocal&&A.push("_local"),v.bindingEngine.invalidateCacheByKeys(A)}const _={[e]:y.data};return Object.keys(S).length>0&&(_._localInit=S),a.initGlobal&&(_._global={...this.globalState}),ys(_,n?.sync?{sync:!0}:void 0),B.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){B.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){B.error(`Error refetching data source: ${e}`,i);return}finally{jr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),B.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),B.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,a){if(!e){B.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Pr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),B.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,a,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return B.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=g;for(const _ of m)if(y=y?.[_],y===void 0)return B.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return B.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const S=y.findIndex(_=>String(_[c])===String(a));if(S===-1)return B.warn(`updateDataSourceItem: Item with ${c}='${a}' not found`),!1;d?y[S]=this.deepMerge(y[S],i):y[S]={...y[S],...i};const v=window.G7Core?.devTools;return v?.isEnabled?.()&&v.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:a,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Pr).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),B.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${a}]`),!0}parseItemPath(e){const n=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const a={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?a[i]=this.deepMerge(a[i]||{},n[i]):a[i]=n[i];return a}setValueAtPath(e,n,a,i="deep"){const l=n.split(".");let c=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(A=>A.auto_fetch!==!1&&A.type!=="websocket");if(g.length===0){B.log("No auto_fetch data sources to refetch");return}B.log(`Refetching ${g.length} auto_fetch data sources`),jr.setPending(!0);const m=ea().currentLayoutJson,y=m?.transition_overlay,S=Array.isArray(y?.wait_for)?y.wait_for:[],v=g.some(A=>(A.loading_strategy||"progressive")==="blocking"),_=S.length>0&&g.some(A=>S.includes(A.id)&&A.type!=="websocket"&&(A.loading_strategy||"progressive")!=="background");if((v||_)&&y&&typeof y=="object"){const A=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&A?this.renderSkeletonOverlay(A,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&A&&this.renderSpinnerOverlay(A,y.spinner,y.fallback_target)}try{const A=new _r;this.currentGlobalHeaders.length>0&&A.setGlobalHeaders(this.currentGlobalHeaders);const x=ea(),O=x.currentDataContext?._global||{},M=await A.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,O,void 0,{ignoreAutoFetch:!1}),T={},D={},z=new Map(g.map(P=>[P.id,P]));for(const P of M){const q=z.get(P.id);if(!q){B.warn(`Refetch result id not found in autoFetchDataSources: ${P.id}`);continue}const W=P.id;P.state==="success"&&P.data!==void 0?(this.currentFetchedData[W]=P.data,T[W]=P.data,this.processInitOptions([q],{[W]:P.data},D),B.log(`Data source refetched: ${W}`)):P.state==="error"&&B.error(`Failed to refetch data source: ${W}`,P.error)}if(x.bindingEngine){const P=Object.keys(T);P.push("query"),x.bindingEngine.invalidateCacheByKeys(P)}if(Object.keys(D).length>0&&(T._localInit=D),Object.keys(T).length>0){if(T.query=_y(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const P={...x.currentDataContext,...T,query:T.query},q=this.calculateComputed(x.currentLayoutJson.computed,P);Object.keys(q).length>0&&(T._computed=q,this.globalState._computed=q,B.log("Computed values recalculated in updateQueryParams:",Object.keys(q)))}ys(T,{sync:!0}),B.log("Template data updated with new query params")}}catch(A){B.error("Error in updateQueryParams:",A)}finally{jr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const a={},i=new Dn;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,n,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=c;a[l]=d,B.log(`Computed ${l}:`,d)}catch(d){B.warn(`Failed to calculate computed value: ${l}`,d),a[l]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return new Function("ctx",` with(ctx) { try { return ${e}; @@ -240,5 +240,5 @@ Error generating stack: `+u.message+` return undefined; } } - `)(n)}catch(a){B.warn(`Expression evaluation failed: ${e}`,a);return}}async executeInitActions(e,n={}){const{getActionDispatcher:a}=await Promise.resolve().then(()=>Pr),i=a();if(!i){B.warn("ActionDispatcher not available for init_actions");return}B.log("Executing init_actions:",e.map(d=>d.handler)),B.log("Init actions dataContext:",n),B.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},g=i.createHandler(f,c),m=new Event("init");await g(m),B.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},B.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){B.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,a=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){B.log("All module handlers already registered");return}const d=Ef().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),g=n.filter(y=>!e.customHandlers?.has(y)),m=g.length>0&&g.every(y=>d.some(S=>y.startsWith(`${S}.`)));if(f||m){B.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return B.log("Waiting for module handlers:",n),new Promise(f=>{const g=()=>{if(c()){B.log("All module handlers now registered"),f();return}if(Date.now()-i>=a){const m=n.filter(y=>!e.customHandlers?.has(y));B.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(xr,"LOCALE_STORAGE_KEY","g7_locale"),$(xr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Do=xr;function Af(o){const e=new Do(o);return o.websocket&&(Cc.configure(o.websocket),B.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=Af,window.G7Core.dataSource={refetch:async(o,e)=>{const n=window.__templateApp;if(!n){B.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){B.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function bA(o={}){const{checked:e,value:n,name:a,type:i="checkbox"}=o,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:a??"",type:i};return{target:d,currentTarget:d,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function vA(o={}){const{button:e=0,clientX:n=0,clientY:a=0}=o;return{button:e,clientX:n,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function SA(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function wA(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const CA={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function xy(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,a]of Object.entries(CA))if(a.test(e))return n;return null}function Ty(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function EA(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const n=o.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of a){const d=xy(c);if(d){const f=Ty(c),g=`${d}:${f}`;i.set(g,c)}}return[...n.filter(c=>{const d=xy(c);if(!d)return!0;const f=Ty(c),g=`${d}:${f}`;return!i.has(g)}),...a].join(" ")}function _A(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function AA(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const ye=ht("G7CoreGlobals");function xA(){window.React=Xe,window.ReactDOM={...ld,createPortal:ka.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=wC,ye.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function TA(o){const e=new Map,n=Oa.getInstance();o.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),n.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),n.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const l=e.get(a),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(a,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw ye.error(`componentEvent: Error in listener for "${a}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(n.trackEventEmit(a,i,c,f,d),d)throw d;return f},off:a=>{e.delete(a),n.trackEventOff(a)},clear:()=>{e.clear(),n.trackEventClear()}},ye.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function RA(o){o.__runtime||(o.__runtime={DynamicRenderer:Ur,ComponentRegistry:mr,TranslationEngine:_a,DataSourceManager:_r,dataSourceManager:oA,DataBindingEngine:Dn,dataBindingEngine:vd,ActionDispatcher:bo,TranslationReactContext:mf,TranslationProvider:vc,useTranslation:dy,ResponsiveContext:Fd,ResponsiveProvider:ic,useResponsive:Kd,responsiveManager:hi,BREAKPOINT_PRESETS:Ul,AuthManager:br,createLogger:ht,G7DevToolsCore:Oa},ye.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function kA(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],n=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(a,i)=>e.push(["widget",a,i]),registerNodeEditor:(a,i)=>e.push(["nodeEditor",a,i]),registerCanvasOverlay:(a,i)=>e.push(["canvasOverlay",a,i]),onReady:a=>{typeof a=="function"&&n.push(a)}},ye.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function DA(o,e){o.useTranslation=dy,o.t=(n,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(a){const l="|"+Object.entries(a).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},ye.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function OA(o,e){o.createChangeEvent=bA,o.createClickEvent=vA,o.createSubmitEvent=SA,o.createKeyboardEvent=wA,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)}),o.createLogger=ht,ye.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(n,a,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},y=new Set,S=(_,A)=>{const x=m._global?._remountKeys;return _&&x?.[_]&&!y.has(_)?(y.add(_),`${_}-remount-${x[_]}`):_||A},v={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:S,...c};return lo(n,m,i,l,v)},o.evaluateCondition=(n,a)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...a||{}},f=i.bindingEngine??vd;return vp(n,d,f)},o.getComponentMap=()=>mr.getInstance().getComponentMap(),o.renderComponentLayout=(n,a,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=mr.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...a},m=new Set,y=(S,v)=>{const _=g._global?._remountKeys;return S&&_?.[S]&&!m.has(S)?(m.add(S),`${S}-remount-${_[S]}`):S||v};return lo(n,g,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},o.renderExpandContent=n=>{const{children:a,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!a||!Array.isArray(a)||a.length===0)return null;const f=n.componentMap||mr.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},S={...m._local||{},...y},v=c?.computedRef?.current??m._computed??{},_=g.bindingEngine??o.getDataBindingEngine?.(),A={...m,_local:S,_computed:v,row:i,item:i,$item:i};let x={};if(l&&typeof l=="object"&&_)try{for(const[D,z]of Object.entries(l))if(typeof z=="string"){const P=Aa(z);if(P!==null)try{x[D]=$n(P)?_.evaluatePipeExpression(P,A,{skipCache:!0}):_.evaluateExpression(P,A,{skipCache:!0})}catch{x[D]=void 0}else x[D]=_.resolveBindings(z,A,{skipCache:!0})}else x[D]=z}catch(D){ye.warn("renderExpandContent: expandContext 평가 오류:",D)}const O={row:i,item:i,$item:i,_local:S,_global:m._global||{},_computed:m._computed||{},...x},M=new Set,T=(D,z)=>{const P=O._global?._remountKeys;return D&&P?.[D]&&!M.has(D)?(M.add(D),`${D}-remount-${P[D]}`):D||z};return lo(a,O,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:c,getRemountKey:T})},o.$get=function(a,i,l=void 0){if(a==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return a;let d=a;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},ye.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),ye.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),ye.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),ye.log("전역 객체 window.G7Core.$get에 노출됨")}function LA(o){o.dispatch=async(e,n)=>{const a=window.__templateApp;if(!a)return ye.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return ye.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=a.getRouter?.(),c=a.getGlobalState?.(),d=a.setGlobalState?.bind(a),g=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=g?.state??c;m&&g&&(y=m,ye.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let S=g?.data??c;m&&g?.data?._local&&(S={...g.data,_local:m},ye.log("[dispatch] Updated context.data._local with pendingLocalState"));const v={navigate:l?(_,A)=>l.navigate(_,A):void 0,setState:g?.setState??d,state:y,data:S,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,A=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,A,()=>{const{debounce:x,debounceKey:O,...M}=e;i.dispatchAction(M,v)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,v)}catch(_){return ye.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},ye.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Oo(o){const e={};for(const[n,a]of Object.entries(o))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function ky(o,e){const n={...o};for(const a of Object.keys(e))a in n?n[a]!==null&&typeof n[a]=="object"&&!Array.isArray(n[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(n[a]=ky(n[a],e[a])):n[a]=e[a];return n}function ir(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&MA(e)){const a=Object.keys(e).map(l=>parseInt(l,10));if(!((a.length>0?Math.max(...a):0)>=o.length+a.length+10)){const l=[...o];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...o};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[a]!==null&&typeof n[a]=="object"?n[a]=ir(n[a],i):n[a]={...i}:n[a]=i;return n}function $A(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=n?.merge||"deep",l=Oo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...a.getGlobalState(),...l};else{const d=a.getGlobalState();c=ir(d,l)}a.setGlobalState(c,{render:n?.render})}else ye.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const a=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const x=window.__g7AutoBindingPaths;x&&x.size>0&&Ry(Oo(e)).some(M=>x.has(M))&&(ye.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const x=a?.getActionDispatcher?.();if(x){const O=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:T,...D}=n;x.debouncedCall(O,n.debounce,()=>{o.state.setLocal(e,D)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Oo(e);if(i==="parent"||i==="root"){const x=window.__g7LayoutContextStack||[];if(x.length>0){const O=i==="parent"?x[x.length-1]:x[0];if(O?.setState){O.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:ir(M||{},d)),ye.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}ye.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=a?.getGlobalState?.()?._local||{},S=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,v=S?ky(g,S):g,_=f||v;let A;if(l==="replace"?A=d:l==="shallow"?A={..._,...d}:A=ir(_,d),a?.setGlobalState&&(a.setGlobalState({_local:A},{render:n?.render}),ye.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=A,ye.log("[setLocal] __g7PendingLocalState updated:",A),window.__g7SequenceLocalSync=A,window.__g7LastSetLocalSnapshot=A,l==="replace")window.__g7ForcedLocalFields=d;else{const x=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(x,d)}if(ye.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const x=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ir(x,d)}ye.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(x=>l==="replace"?d:l==="shallow"?{...x||{},...d}:ir(x||{},d)),a?.setGlobalState||ye.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ir(a,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==a?ir(a,l):a},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const a=n.getGlobalState(),i=e(a);n.setGlobalState(i)}else ye.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(ye.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,n,a)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=a):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:a);const d=c?.merge||"deep",f=Oo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):ye.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.isolatedContext.mergeState(f,d):ye.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return ye.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const a=n.dataContext||{};return{_local:n.state||a._local||{},_global:a._global||o.state.get()||{},setState:n.setState}},setParentLocal:(e,n,a)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){ye.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){ye.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=a):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:a);const f=d?.merge||"deep",g=Oo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let S;f==="replace"?S=g:f==="shallow"?S={...y,...g}:S=ir(y,g),window.__g7PendingLocalState=S;const v=window.__templateApp;if(v?.setGlobalState&&v.setGlobalState({_local:S}),l.setState(S),m?l.state._local=S:l.state=S,l.dataContext&&(l.dataContext._local=S),f==="replace")window.__g7ForcedLocalFields=g;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(_,g)}qd()},setParentGlobal:(e,n)=>{let a;typeof e=="string"?a={[e]:n}:a=e,o.state.set(a),ye.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,ye.log("전역 객체 window.G7Core.state에 노출됨")}function NA(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,a):ye.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,n);ye.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,a,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,a,i,l):(ye.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,a,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return ye.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return ye.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,g=null;if(n){const y=n.split(".");g=y.pop();for(const S of y)if(f&&typeof f=="object"&&S in f)f=f[S];else return ye.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=c;if(!Array.isArray(d))return ye.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return ye.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...a,...d]:[...d,...a];return n&&g?(f[g]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),ye.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},ye.log("전역 객체 window.G7Core.dataSource에 노출됨")}function IA(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const a=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(a)&&a.length>0?a:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(n):ye.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},ye.log("전역 객체 window.G7Core.locale에 노출됨")}function HA(o){o.toast={show:(e,n)=>{o.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{o.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{o.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{o.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{o.toast.show(e,{type:"info",duration:n})}},ye.log("전역 객체 window.G7Core.toast에 노출됨")}function jA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=o.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},ye.log("전역 객체 window.G7Core.modal에 노출됨")}function zA(o){o.style={mergeClasses:EA,conditionalClass:_A,joinClasses:AA},ye.log("전역 객체 window.G7Core.style에 노출됨")}function UA(o,e){const{webSocketManager:n}=e;o.websocket={manager:n,subscribe:(a,i,l,c)=>n.subscribe(a,i,l,c),unsubscribe:a=>n.unsubscribe(a),leaveChannel:a=>n.leaveChannel(a),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},ye.log("전역 객체 window.G7Core.websocket에 노출됨")}function PA(o,e){const{transitionManager:n}=e;o.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:a=>{if(!n)return a(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(a(),l())});return l}},ye.log("전역 객체 window.G7Core.navigation에 노출됨")}function BA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,a)=>window.G7Config?.plugins?.[e]?.[n]??a,getAll:()=>window.G7Config?.plugins??{}},ye.log("전역 객체 window.G7Core.plugin에 노출됨")}function qA(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,a)=>window.G7Config?.modules?.[e]?.[n]??a,getAll:()=>window.G7Config?.modules??{}},ye.log("전역 객체 window.G7Core.module에 노출됨")}function GA(o,e){const{transitionManager:n,responsiveManager:a}=e;o.AuthManager=br,o.api=Hr(),o.TransitionManager=n,o.useTransitionState=Cm,o.ResponsiveManager=a,o.useResponsive=Kd,o.useControllableState=$C,o.shallowArrayEqual=NC,o.shallowObjectEqual=_m,o.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);ye.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},ye.log("전역 객체 window.G7Core.AuthManager에 노출됨"),ye.log("전역 객체 window.G7Core.api에 노출됨"),ye.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),ye.log("전역 객체 window.G7Core.useResponsive에 노출됨"),ye.log("전역 객체 window.G7Core.useControllableState에 노출됨"),ye.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function VA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??mr.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,ye.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function FA(o){o.identity={setLauncher:Et.setLauncher.bind(Et),handle:Et.handle.bind(Et),isIdentityRequired:Et.isIdentityRequired.bind(Et),hasLauncher:Et.hasLauncher.bind(Et),markDomainNoticeShown:Et.markDomainNoticeShown.bind(Et),redirectExternally:Et.redirectExternally.bind(Et),createDeferred:Et.createDeferred.bind(Et),resolveDeferred:Et.resolveDeferred.bind(Et),reset:Et.reset.bind(Et),redirectStashKey:Hd},ye.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function KA(o){if(typeof window>"u")return;xA(),window.G7Core||(window.G7Core={});const e=window.G7Core;RA(e),TA(e),kA(e),GA(e,o),DA(e,o),OA(e,o),LA(e),$A(e),NA(e),IA(e,o),HA(e),jA(e),zA(e),UA(e,o),PA(e,o),BA(e),qA(e),VA(e,o),FA(e),ye.log("G7Core 전역 객체 초기화 완료")}function WA(){const o=window.G7Core;if(!o){ye.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Oa.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(a,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,l)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,l,c)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,l)=>{try{e().isEnabled()&&e().completeRequest(a,i,l)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,l)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,l)=>{try{e().isEnabled()&&e().trackForm(a,i,l)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(a,i,l,c):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,l,c,d,f)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,l,c)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,l,c,d,f)}catch{}},trackComponentStyle:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,l,c)}catch{}},trackAuthEvent:(a,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,l,c)}catch{}},trackAuthHeader:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,l,c,d)}catch{}},trackLog:(a,i,l)=>{try{e().isEnabled()&&e().trackLog(a,i,l)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,l,c,d)}catch{}},captureSequenceActionAfter:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,l,c,d,f)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,l)}catch{}},detectStaleClosure:(a,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,l,c,d,f,g)}catch{}},trackComputedRecalc:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,l,c,d,f,g)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};o.devTools=n,ye.log("G7Core.devTools 인터페이스 초기화 완료")}let Lo=null;function YA(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):Lo||(Lo=new Promise((e,n)=>{const a=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const c=document.getElementById(i);if(c){c.addEventListener("load",l,{once:!0}),c.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Lo=null,n(new Error(`DevTools 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Lo)}function XA(){const o=window.G7Core;if(!o){ye.warn("G7Core가 초기화되지 않았습니다.");return}const e=Oa.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{ye.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},ud(),ye.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}JA(o,e)}async function JA(o,e){let n;try{n=await YA()}catch(g){ye.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},ud();return}const{DiagnosticEngine:a,getServerConnector:i,getStyleTracker:l}=n;WA(),ud();try{l().enable(),ye.log("StyleTracker 활성화됨")}catch(g){ye.warn("StyleTracker 활성화 실패:",g)}const c=new a,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){ye.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),ye.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>c.analyze(g),suggestFix:g=>c.suggestFix(g),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:g=>c.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=f,o.devtools=f,ye.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),QA(n.DevToolsPanel)}function QA(o){if(document.getElementById("g7-devtools-root")){ye.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{ld.createRoot(e).render(Xe.createElement(o)),ye.log("DevToolsPanel UI 렌더링 완료")}catch(n){ye.error("DevToolsPanel UI 렌더링 실패:",n)}}const Ze=ht("TemplateEngine"),ie={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Mo=!1;const $o=[];async function ZA(o){try{Ze.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(a=>a.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Ze.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Ze.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Ze.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function Dy(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=ie.templateMetadata?.locales;return{$locale:ie.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:ie.templateId}}async function No(o){try{if(Ze.log("템플릿 엔진 초기화 시작",o),ie.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new cA;Mo=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Mo),XA(),ie.templateId=o.templateId,ie.locale=o.locale||"ko",Ze.log("엔진 인스턴스 생성 중..."),ie.registry=mr.getInstance(),ie.bindingEngine=new Dn,ie.translationEngine=_a.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&ie.translationEngine.setCacheVersion(o.cacheVersion),ie.translationContext={templateId:o.templateId,locale:ie.locale},ie.actionDispatcher=new bo({},ie.translationEngine,ie.translationContext),AC(ie.actionDispatcher),Ze.log("다국어 파일 로드 중...",o.templateId,ie.locale);const e="en",n=[ie.translationEngine.loadTranslations(o.templateId,ie.locale).then(()=>{Ze.log(`다국어 파일 로드 완료: ${ie.locale}`)}).catch(a=>{Ze.warn(`다국어 파일 로드 실패 (${ie.locale}):`,a instanceof Error?a.message:a)})];ie.locale!==e&&n.push(ie.translationEngine.loadTranslations(o.templateId,e).then(()=>{Ze.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{Ze.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(n),Ze.log("템플릿 메타데이터 로드 중...",o.templateId),ie.templateMetadata=await ZA(o.templateId),ie.isInitialized=!0,Ze.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Ze.error("템플릿 엔진 초기화 실패",e),ie.isInitialized=!1,ie.registry=null,ie.bindingEngine=null,ie.translationEngine=null,ie.actionDispatcher=null,e}}let Io=null;function xf(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):Io||(Io=new Promise((e,n)=>{const a=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),c=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):n(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=c,l){l.addEventListener("load",c,{once:!0}),l.addEventListener("error",()=>n(new Error(`편집기 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",c,{once:!0}),d.addEventListener("error",()=>{Io=null,n(new Error(`편집기 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Io)}async function ms(o){try{if(Ze.log("템플릿 렌더링 시작",o),!ie.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const n=Dy();if(ie.containerId=o.containerId,ie.currentLayoutJson=o.layoutJson,ie.currentDataContext={...n,...o.dataContext||{}},ie.translationContext=o.translationContext||{templateId:ie.templateId||"",locale:ie.locale},ie.reactRoot||(Ze.log("React Root 생성"),ie.reactRoot=ld.createRoot(e)),typeof window<"u"){const l=_y(window.location.pathname);if(l){Ze.log("레이아웃 편집기 모드 진입",l);let c;try{c=await xf()}catch(f){Ze.error("레이아웃 편집기 번들 로드 실패",f),wf.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Mo});return}const d=Xe.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ie.locale});ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext,children:Xe.createElement(Gd,{children:Xe.createElement(ic,{children:Xe.createElement(yf,{children:d})})})}));return}}const a=o.layoutJson.components||[];if(a.length===0){Ze.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(Ze.log("modals 배열:",i),Ze.log("modals 개수:",i.length),Ze.log("DynamicRenderer로 렌더링 시작"),ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext},Xe.createElement(Gd,null,Xe.createElement(ic,null,Xe.createElement(yf,null,[...a.map((l,c)=>{const d=ie.currentLayoutJson?.layout_name||"";return Xe.createElement(Ur,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),Xe.createElement(ym,{key:"__modal_parent_context_provider"},i.map(l=>{const c=ie.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||ie.currentDataContext._global?.activeModal===l.id,g=c.indexOf(l.id),m=g>=0?50+g:50,y=window.__g7LayoutContextStack||[],v=y[y.length-1]?.dataContext,_=Xe.createElement(Ur,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:ie.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ie.currentDataContext)}},dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,parentDataContext:v});return l.data_sources&&l.data_sources.length>0?Xe.createElement(Cy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ie.currentDataContext,globalStateUpdater:ie.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ie.bindingEngine,debug:Mo,children:_}):_}))]))))),Ze.log("템플릿 렌더링 완료"),$o.length>0){Ze.log(`대기 중인 데이터 업데이트 ${$o.length}건 적용`);const l=[...$o];$o.length=0;for(const{data:c,options:d}of l)ys(c,d)}}catch(e){throw Ze.error("템플릿 렌더링 실패",e),e}}function ys(o,e){try{if(Ze.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!ie.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ie.reactRoot||!ie.currentLayoutJson){Ze.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),$o.push({data:o,options:e});return}const n=Dy(),a={...ie.currentDataContext._global||{},...o._global||{}},i=LC(ie.currentDataContext._localInit,o._localInit);ie.currentDataContext={...n,...ie.currentDataContext,...o,_global:a,_localInit:i},a._local!==void 0&&(ie.currentDataContext._local=a._local),a._computed!==void 0&&(ie.currentDataContext._computed=a._computed);const l=ie.currentLayoutJson.components||[],c=ie.currentLayoutJson.modals||[];Ze.log("updateTemplateData - modals 배열:",c),Ze.log("updateTemplateData - modals 개수:",c.length),Ze.log("updateTemplateData - activeModal:",ie.currentDataContext._global?.activeModal);const d=()=>{ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext},Xe.createElement(Gd,null,Xe.createElement(ic,null,Xe.createElement(yf,null,[...l.map((f,g)=>{const m=ie.currentLayoutJson?.layout_name||"";return Xe.createElement(Ur,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,isRootRenderer:g===0,layoutKey:m})}),Xe.createElement(ym,{key:"__modal_parent_context_provider_update"},c.map(f=>{const g=ie.currentDataContext._global?.modalStack||[],y=g.includes(f.id)||ie.currentDataContext._global?.activeModal===f.id,S=g.indexOf(f.id),v=S>=0?50+S:50,_=window.__g7LayoutContextStack||[],x=_[_.length-1]?.dataContext,O=Xe.createElement(Ur,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:v},onClose:ie.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ie.currentDataContext)}},dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,parentDataContext:x});return f.data_sources&&f.data_sources.length>0?Xe.createElement(Cy,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:ie.currentDataContext,globalStateUpdater:ie.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ie.bindingEngine,debug:Mo,children:O}):O}))])))))};e?.sync?(Ze.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Ze.log("재렌더링 시작 (with startTransition)"),H.startTransition(()=>{d()})),Ze.log("템플릿 데이터 업데이트 완료")}catch(n){throw Ze.error("템플릿 데이터 업데이트 실패",n),n}}function xc(){try{Ze.log("템플릿 정리 시작"),ie.reactRoot&&(Ze.log("React Root 언마운트"),ie.reactRoot.unmount(),ie.reactRoot=null),ie.templateId=null,ie.locale="ko",ie.isInitialized=!1,ie.containerId=null,ie.currentLayoutJson=null,ie.currentDataContext={},ie.translationContext={templateId:"",locale:"ko"},ie.registry=null,ie.bindingEngine=null,ie.translationEngine=null,ie.actionDispatcher=null,ie.templateMetadata=null,Ze.log("템플릿 정리 완료")}catch(o){throw Ze.error("템플릿 정리 실패",o),o}}function ea(){return Object.freeze({...ie})}function Oy(){return ie.actionDispatcher}const Ho={initTemplateEngine:No,renderTemplate:ms,updateTemplateData:ys,destroyTemplate:xc,getState:ea};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Ho,KA({getState:()=>({translationEngine:ie.translationEngine,translationContext:ie.translationContext,bindingEngine:ie.bindingEngine,actionDispatcher:ie.actionDispatcher,templateMetadata:ie.templateMetadata}),transitionManager:jr,responsiveManager:hi,webSocketManager:Cc}),Ze.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Pr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:_r,LayoutLoader:pf,TemplateApp:Do,TemplateEngine:Ho,default:Ho,destroyTemplate:xc,getActionDispatcher:Oy,getState:ea,initTemplateApp:Af,initTemplateEngine:No,loadLayoutEditorBundle:xf,renderTemplate:ms,updateTemplateData:ys},Symbol.toStringTag,{value:"Module"}));Qt.DataSourceManager=_r,Qt.LayoutLoader=pf,Qt.TemplateApp=Do,Qt.TemplateEngine=Ho,Qt.default=Ho,Qt.destroyTemplate=xc,Qt.getActionDispatcher=Oy,Qt.getState=ea,Qt.initTemplateApp=Af,Qt.initTemplateEngine=No,Qt.loadLayoutEditorBundle=xf,Qt.renderTemplate=ms,Qt.updateTemplateData=ys,Object.defineProperties(Qt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); + `)(n)}catch(a){B.warn(`Expression evaluation failed: ${e}`,a);return}}async executeInitActions(e,n={}){const{getActionDispatcher:a}=await Promise.resolve().then(()=>Pr),i=a();if(!i){B.warn("ActionDispatcher not available for init_actions");return}B.log("Executing init_actions:",e.map(d=>d.handler)),B.log("Init actions dataContext:",n),B.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},g=i.createHandler(f,c),m=new Event("init");await g(m),B.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},B.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){B.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,a=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){B.log("All module handlers already registered");return}const d=_f().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),g=n.filter(y=>!e.customHandlers?.has(y)),m=g.length>0&&g.every(y=>d.some(S=>y.startsWith(`${S}.`)));if(f||m){B.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return B.log("Waiting for module handlers:",n),new Promise(f=>{const g=()=>{if(c()){B.log("All module handlers now registered"),f();return}if(Date.now()-i>=a){const m=n.filter(y=>!e.customHandlers?.has(y));B.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(xr,"LOCALE_STORAGE_KEY","g7_locale"),$(xr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Do=xr;function xf(o){const e=new Do(o);return o.websocket&&(Cc.configure(o.websocket),B.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=xf,window.G7Core.dataSource={refetch:async(o,e)=>{const n=window.__templateApp;if(!n){B.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){B.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function bA(o={}){const{checked:e,value:n,name:a,type:i="checkbox"}=o,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:a??"",type:i};return{target:d,currentTarget:d,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function vA(o={}){const{button:e=0,clientX:n=0,clientY:a=0}=o;return{button:e,clientX:n,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function SA(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function wA(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const CA={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function Ay(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,a]of Object.entries(CA))if(a.test(e))return n;return null}function xy(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function EA(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const n=o.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of a){const d=Ay(c);if(d){const f=xy(c),g=`${d}:${f}`;i.set(g,c)}}return[...n.filter(c=>{const d=Ay(c);if(!d)return!0;const f=xy(c),g=`${d}:${f}`;return!i.has(g)}),...a].join(" ")}function _A(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function AA(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const ye=ht("G7CoreGlobals");function xA(){window.React=Xe,window.ReactDOM={...ld,createPortal:ka.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=wC,ye.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function TA(o){const e=new Map,n=Oa.getInstance();o.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),n.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),n.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const l=e.get(a),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(a,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw ye.error(`componentEvent: Error in listener for "${a}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(n.trackEventEmit(a,i,c,f,d),d)throw d;return f},off:a=>{e.delete(a),n.trackEventOff(a)},clear:()=>{e.clear(),n.trackEventClear()}},ye.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function RA(o){o.__runtime||(o.__runtime={DynamicRenderer:Ur,ComponentRegistry:mr,TranslationEngine:_a,DataSourceManager:_r,dataSourceManager:oA,DataBindingEngine:Dn,dataBindingEngine:Sd,ActionDispatcher:bo,TranslationReactContext:yf,TranslationProvider:vc,useTranslation:uy,ResponsiveContext:Kd,ResponsiveProvider:ic,useResponsive:Wd,responsiveManager:hi,BREAKPOINT_PRESETS:Ul,AuthManager:br,createLogger:ht,G7DevToolsCore:Oa},ye.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function kA(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],n=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(a,i)=>e.push(["widget",a,i]),registerNodeEditor:(a,i)=>e.push(["nodeEditor",a,i]),registerCanvasOverlay:(a,i)=>e.push(["canvasOverlay",a,i]),onReady:a=>{typeof a=="function"&&n.push(a)}},ye.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function DA(o,e){o.useTranslation=uy,o.t=(n,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(a){const l="|"+Object.entries(a).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},ye.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function OA(o,e){o.createChangeEvent=bA,o.createClickEvent=vA,o.createSubmitEvent=SA,o.createKeyboardEvent=wA,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)}),o.createLogger=ht,ye.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(n,a,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},y=new Set,S=(_,A)=>{const x=m._global?._remountKeys;return _&&x?.[_]&&!y.has(_)?(y.add(_),`${_}-remount-${x[_]}`):_||A},v={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:S,...c};return lo(n,m,i,l,v)},o.evaluateCondition=(n,a)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...a||{}},f=i.bindingEngine??Sd;return vp(n,d,f)},o.getComponentMap=()=>mr.getInstance().getComponentMap(),o.renderComponentLayout=(n,a,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=mr.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...a},m=new Set,y=(S,v)=>{const _=g._global?._remountKeys;return S&&_?.[S]&&!m.has(S)?(m.add(S),`${S}-remount-${_[S]}`):S||v};return lo(n,g,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},o.renderExpandContent=n=>{const{children:a,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!a||!Array.isArray(a)||a.length===0)return null;const f=n.componentMap||mr.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},S={...m._local||{},...y},v=c?.computedRef?.current??m._computed??{},_=g.bindingEngine??o.getDataBindingEngine?.(),A={...m,_local:S,_computed:v,row:i,item:i,$item:i};let x={};if(l&&typeof l=="object"&&_)try{for(const[D,z]of Object.entries(l))if(typeof z=="string"){const P=Aa(z);if(P!==null)try{x[D]=Vn(P)?_.evaluatePipeExpression(P,A,{skipCache:!0}):_.evaluateExpression(P,A,{skipCache:!0})}catch{x[D]=void 0}else x[D]=_.resolveBindings(z,A,{skipCache:!0})}else x[D]=z}catch(D){ye.warn("renderExpandContent: expandContext 평가 오류:",D)}const O={row:i,item:i,$item:i,_local:S,_global:m._global||{},_computed:m._computed||{},...x},M=new Set,T=(D,z)=>{const P=O._global?._remountKeys;return D&&P?.[D]&&!M.has(D)?(M.add(D),`${D}-remount-${P[D]}`):D||z};return lo(a,O,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:c,getRemountKey:T})},o.$get=function(a,i,l=void 0){if(a==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return a;let d=a;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},ye.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),ye.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),ye.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),ye.log("전역 객체 window.G7Core.$get에 노출됨")}function LA(o){o.dispatch=async(e,n)=>{const a=window.__templateApp;if(!a)return ye.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return ye.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=a.getRouter?.(),c=a.getGlobalState?.(),d=a.setGlobalState?.bind(a),g=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=g?.state??c;m&&g&&(y=m,ye.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let S=g?.data??c;m&&g?.data?._local&&(S={...g.data,_local:m},ye.log("[dispatch] Updated context.data._local with pendingLocalState"));const v={navigate:l?(_,A)=>l.navigate(_,A):void 0,setState:g?.setState??d,state:y,data:S,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,A=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,A,()=>{const{debounce:x,debounceKey:O,...M}=e;i.dispatchAction(M,v)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,v)}catch(_){return ye.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},ye.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Oo(o){const e={};for(const[n,a]of Object.entries(o))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Ry(o,e){const n={...o};for(const a of Object.keys(e))a in n?n[a]!==null&&typeof n[a]=="object"&&!Array.isArray(n[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(n[a]=Ry(n[a],e[a])):n[a]=e[a];return n}function ir(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&MA(e)){const a=Object.keys(e).map(l=>parseInt(l,10));if(!((a.length>0?Math.max(...a):0)>=o.length+a.length+10)){const l=[...o];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...o};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[a]!==null&&typeof n[a]=="object"?n[a]=ir(n[a],i):n[a]={...i}:n[a]=i;return n}function $A(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=n?.merge||"deep",l=Oo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...a.getGlobalState(),...l};else{const d=a.getGlobalState();c=ir(d,l)}a.setGlobalState(c,{render:n?.render})}else ye.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const a=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const x=window.__g7AutoBindingPaths;x&&x.size>0&&Ty(Oo(e)).some(M=>x.has(M))&&(ye.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const x=a?.getActionDispatcher?.();if(x){const O=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:T,...D}=n;x.debouncedCall(O,n.debounce,()=>{o.state.setLocal(e,D)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Oo(e);if(i==="parent"||i==="root"){const x=window.__g7LayoutContextStack||[];if(x.length>0){const O=i==="parent"?x[x.length-1]:x[0];if(O?.setState){O.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:ir(M||{},d)),ye.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}ye.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=a?.getGlobalState?.()?._local||{},S=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,v=S?Ry(g,S):g,_=f||v;let A;if(l==="replace"?A=d:l==="shallow"?A={..._,...d}:A=ir(_,d),a?.setGlobalState&&(a.setGlobalState({_local:A},{render:n?.render}),ye.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=A,ye.log("[setLocal] __g7PendingLocalState updated:",A),window.__g7SequenceLocalSync=A,window.__g7LastSetLocalSnapshot=A,l==="replace")window.__g7ForcedLocalFields=d;else{const x=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(x,d)}if(ye.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const x=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ir(x,d)}ye.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(x=>l==="replace"?d:l==="shallow"?{...x||{},...d}:ir(x||{},d)),a?.setGlobalState||ye.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ir(a,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==a?ir(a,l):a},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const a=n.getGlobalState(),i=e(a);n.setGlobalState(i)}else ye.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(ye.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,n,a)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=a):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:a);const d=c?.merge||"deep",f=Oo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):ye.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.isolatedContext.mergeState(f,d):ye.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return ye.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const a=n.dataContext||{};return{_local:n.state||a._local||{},_global:a._global||o.state.get()||{},setState:n.setState}},setParentLocal:(e,n,a)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){ye.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){ye.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=a):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:a);const f=d?.merge||"deep",g=Oo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let S;f==="replace"?S=g:f==="shallow"?S={...y,...g}:S=ir(y,g),window.__g7PendingLocalState=S;const v=window.__templateApp;if(v?.setGlobalState&&v.setGlobalState({_local:S}),l.setState(S),m?l.state._local=S:l.state=S,l.dataContext&&(l.dataContext._local=S),f==="replace")window.__g7ForcedLocalFields=g;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(_,g)}Gd()},setParentGlobal:(e,n)=>{let a;typeof e=="string"?a={[e]:n}:a=e,o.state.set(a),ye.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,ye.log("전역 객체 window.G7Core.state에 노출됨")}function NA(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,a):ye.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,n);ye.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,a,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,a,i,l):(ye.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,a,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return ye.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return ye.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,g=null;if(n){const y=n.split(".");g=y.pop();for(const S of y)if(f&&typeof f=="object"&&S in f)f=f[S];else return ye.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=c;if(!Array.isArray(d))return ye.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return ye.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...a,...d]:[...d,...a];return n&&g?(f[g]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),ye.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},ye.log("전역 객체 window.G7Core.dataSource에 노출됨")}function IA(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const a=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(a)&&a.length>0?a:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(n):ye.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},ye.log("전역 객체 window.G7Core.locale에 노출됨")}function HA(o){o.toast={show:(e,n)=>{o.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{o.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{o.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{o.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{o.toast.show(e,{type:"info",duration:n})}},ye.log("전역 객체 window.G7Core.toast에 노출됨")}function jA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=o.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},ye.log("전역 객체 window.G7Core.modal에 노출됨")}function zA(o){o.style={mergeClasses:EA,conditionalClass:_A,joinClasses:AA},ye.log("전역 객체 window.G7Core.style에 노출됨")}function UA(o,e){const{webSocketManager:n}=e;o.websocket={manager:n,subscribe:(a,i,l,c)=>n.subscribe(a,i,l,c),unsubscribe:a=>n.unsubscribe(a),leaveChannel:a=>n.leaveChannel(a),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},ye.log("전역 객체 window.G7Core.websocket에 노출됨")}function PA(o,e){const{transitionManager:n}=e;o.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:a=>{if(!n)return a(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(a(),l())});return l}},ye.log("전역 객체 window.G7Core.navigation에 노출됨")}function BA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,a)=>window.G7Config?.plugins?.[e]?.[n]??a,getAll:()=>window.G7Config?.plugins??{}},ye.log("전역 객체 window.G7Core.plugin에 노출됨")}function qA(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,a)=>window.G7Config?.modules?.[e]?.[n]??a,getAll:()=>window.G7Config?.modules??{}},ye.log("전역 객체 window.G7Core.module에 노출됨")}function GA(o,e){const{transitionManager:n,responsiveManager:a}=e;o.AuthManager=br,o.api=Hr(),o.TransitionManager=n,o.useTransitionState=wm,o.ResponsiveManager=a,o.useResponsive=Wd,o.useControllableState=$C,o.shallowArrayEqual=NC,o.shallowObjectEqual=Em,o.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);ye.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},ye.log("전역 객체 window.G7Core.AuthManager에 노출됨"),ye.log("전역 객체 window.G7Core.api에 노출됨"),ye.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),ye.log("전역 객체 window.G7Core.useResponsive에 노출됨"),ye.log("전역 객체 window.G7Core.useControllableState에 노출됨"),ye.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function VA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??mr.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,ye.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function FA(o){o.identity={setLauncher:Et.setLauncher.bind(Et),handle:Et.handle.bind(Et),isIdentityRequired:Et.isIdentityRequired.bind(Et),hasLauncher:Et.hasLauncher.bind(Et),markDomainNoticeShown:Et.markDomainNoticeShown.bind(Et),redirectExternally:Et.redirectExternally.bind(Et),createDeferred:Et.createDeferred.bind(Et),resolveDeferred:Et.resolveDeferred.bind(Et),reset:Et.reset.bind(Et),redirectStashKey:jd},ye.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function KA(o){if(typeof window>"u")return;xA(),window.G7Core||(window.G7Core={});const e=window.G7Core;RA(e),TA(e),kA(e),GA(e,o),DA(e,o),OA(e,o),LA(e),$A(e),NA(e),IA(e,o),HA(e),jA(e),zA(e),UA(e,o),PA(e,o),BA(e),qA(e),VA(e,o),FA(e),ye.log("G7Core 전역 객체 초기화 완료")}function WA(){const o=window.G7Core;if(!o){ye.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Oa.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(a,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,l)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,l,c)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,l)=>{try{e().isEnabled()&&e().completeRequest(a,i,l)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,l)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,l)=>{try{e().isEnabled()&&e().trackForm(a,i,l)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(a,i,l,c):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,l,c,d,f)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,l,c)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,l,c,d,f)}catch{}},trackComponentStyle:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,l,c)}catch{}},trackAuthEvent:(a,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,l,c)}catch{}},trackAuthHeader:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,l,c,d)}catch{}},trackLog:(a,i,l)=>{try{e().isEnabled()&&e().trackLog(a,i,l)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,l,c,d)}catch{}},captureSequenceActionAfter:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,l,c,d,f)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,l)}catch{}},detectStaleClosure:(a,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,l,c,d,f,g)}catch{}},trackComputedRecalc:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,l,c,d,f,g)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};o.devTools=n,ye.log("G7Core.devTools 인터페이스 초기화 완료")}let Lo=null;function YA(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):Lo||(Lo=new Promise((e,n)=>{const a=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const c=document.getElementById(i);if(c){c.addEventListener("load",l,{once:!0}),c.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Lo=null,n(new Error(`DevTools 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Lo)}function XA(){const o=window.G7Core;if(!o){ye.warn("G7Core가 초기화되지 않았습니다.");return}const e=Oa.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{ye.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},ud(),ye.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}JA(o,e)}async function JA(o,e){let n;try{n=await YA()}catch(g){ye.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},ud();return}const{DiagnosticEngine:a,getServerConnector:i,getStyleTracker:l}=n;WA(),ud();try{l().enable(),ye.log("StyleTracker 활성화됨")}catch(g){ye.warn("StyleTracker 활성화 실패:",g)}const c=new a,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){ye.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),ye.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>c.analyze(g),suggestFix:g=>c.suggestFix(g),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:g=>c.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=f,o.devtools=f,ye.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),QA(n.DevToolsPanel)}function QA(o){if(document.getElementById("g7-devtools-root")){ye.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{ld.createRoot(e).render(Xe.createElement(o)),ye.log("DevToolsPanel UI 렌더링 완료")}catch(n){ye.error("DevToolsPanel UI 렌더링 실패:",n)}}const Ze=ht("TemplateEngine"),ie={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Mo=!1;const $o=[];async function ZA(o){try{Ze.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(a=>a.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Ze.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Ze.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Ze.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function ky(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=ie.templateMetadata?.locales;return{$locale:ie.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:ie.templateId}}async function No(o){try{if(Ze.log("템플릿 엔진 초기화 시작",o),ie.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new cA;Mo=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Mo),XA(),ie.templateId=o.templateId,ie.locale=o.locale||"ko",Ze.log("엔진 인스턴스 생성 중..."),ie.registry=mr.getInstance(),ie.bindingEngine=new Dn,ie.translationEngine=_a.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&ie.translationEngine.setCacheVersion(o.cacheVersion),ie.translationContext={templateId:o.templateId,locale:ie.locale},ie.actionDispatcher=new bo({},ie.translationEngine,ie.translationContext),AC(ie.actionDispatcher),Ze.log("다국어 파일 로드 중...",o.templateId,ie.locale);const e="en",n=[ie.translationEngine.loadTranslations(o.templateId,ie.locale).then(()=>{Ze.log(`다국어 파일 로드 완료: ${ie.locale}`)}).catch(a=>{Ze.warn(`다국어 파일 로드 실패 (${ie.locale}):`,a instanceof Error?a.message:a)})];ie.locale!==e&&n.push(ie.translationEngine.loadTranslations(o.templateId,e).then(()=>{Ze.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{Ze.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(n),Ze.log("템플릿 메타데이터 로드 중...",o.templateId),ie.templateMetadata=await ZA(o.templateId),ie.isInitialized=!0,Ze.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Ze.error("템플릿 엔진 초기화 실패",e),ie.isInitialized=!1,ie.registry=null,ie.bindingEngine=null,ie.translationEngine=null,ie.actionDispatcher=null,e}}let Io=null;function Tf(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):Io||(Io=new Promise((e,n)=>{const a=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),c=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):n(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=c,l){l.addEventListener("load",c,{once:!0}),l.addEventListener("error",()=>n(new Error(`편집기 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",c,{once:!0}),d.addEventListener("error",()=>{Io=null,n(new Error(`편집기 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Io)}async function ms(o){try{if(Ze.log("템플릿 렌더링 시작",o),!ie.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const n=ky();if(ie.containerId=o.containerId,ie.currentLayoutJson=o.layoutJson,ie.currentDataContext={...n,...o.dataContext||{}},ie.translationContext=o.translationContext||{templateId:ie.templateId||"",locale:ie.locale},ie.reactRoot||(Ze.log("React Root 생성"),ie.reactRoot=ld.createRoot(e)),typeof window<"u"){const l=Ey(window.location.pathname);if(l){Ze.log("레이아웃 편집기 모드 진입",l);let c;try{c=await Tf()}catch(f){Ze.error("레이아웃 편집기 번들 로드 실패",f),Cf.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Mo});return}const d=Xe.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ie.locale});ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext,children:Xe.createElement(Vd,{children:Xe.createElement(ic,{children:Xe.createElement(bf,{children:d})})})}));return}}const a=o.layoutJson.components||[];if(a.length===0){Ze.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(Ze.log("modals 배열:",i),Ze.log("modals 개수:",i.length),Ze.log("DynamicRenderer로 렌더링 시작"),ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext},Xe.createElement(Vd,null,Xe.createElement(ic,null,Xe.createElement(bf,null,[...a.map((l,c)=>{const d=ie.currentLayoutJson?.layout_name||"";return Xe.createElement(Ur,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),Xe.createElement(mm,{key:"__modal_parent_context_provider"},i.map(l=>{const c=ie.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||ie.currentDataContext._global?.activeModal===l.id,g=c.indexOf(l.id),m=g>=0?50+g:50,y=window.__g7LayoutContextStack||[],v=y[y.length-1]?.dataContext,_=Xe.createElement(Ur,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:ie.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ie.currentDataContext)}},dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,parentDataContext:v});return l.data_sources&&l.data_sources.length>0?Xe.createElement(wy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ie.currentDataContext,globalStateUpdater:ie.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ie.bindingEngine,debug:Mo,children:_}):_}))]))))),Ze.log("템플릿 렌더링 완료"),$o.length>0){Ze.log(`대기 중인 데이터 업데이트 ${$o.length}건 적용`);const l=[...$o];$o.length=0;for(const{data:c,options:d}of l)ys(c,d)}}catch(e){throw Ze.error("템플릿 렌더링 실패",e),e}}function ys(o,e){try{if(Ze.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!ie.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ie.reactRoot||!ie.currentLayoutJson){Ze.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),$o.push({data:o,options:e});return}const n=ky(),a={...ie.currentDataContext._global||{},...o._global||{}},i=LC(ie.currentDataContext._localInit,o._localInit);ie.currentDataContext={...n,...ie.currentDataContext,...o,_global:a,_localInit:i},a._local!==void 0&&(ie.currentDataContext._local=a._local),a._computed!==void 0&&(ie.currentDataContext._computed=a._computed);const l=ie.currentLayoutJson.components||[],c=ie.currentLayoutJson.modals||[];Ze.log("updateTemplateData - modals 배열:",c),Ze.log("updateTemplateData - modals 개수:",c.length),Ze.log("updateTemplateData - activeModal:",ie.currentDataContext._global?.activeModal);const d=()=>{ie.reactRoot.render(Xe.createElement(vc,{translationEngine:ie.translationEngine,translationContext:ie.translationContext},Xe.createElement(Vd,null,Xe.createElement(ic,null,Xe.createElement(bf,null,[...l.map((f,g)=>{const m=ie.currentLayoutJson?.layout_name||"";return Xe.createElement(Ur,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,isRootRenderer:g===0,layoutKey:m})}),Xe.createElement(mm,{key:"__modal_parent_context_provider_update"},c.map(f=>{const g=ie.currentDataContext._global?.modalStack||[],y=g.includes(f.id)||ie.currentDataContext._global?.activeModal===f.id,S=g.indexOf(f.id),v=S>=0?50+S:50,_=window.__g7LayoutContextStack||[],x=_[_.length-1]?.dataContext,O=Xe.createElement(Ur,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:v},onClose:ie.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ie.currentDataContext)}},dataContext:ie.currentDataContext,translationContext:ie.translationContext,registry:ie.registry,bindingEngine:ie.bindingEngine,translationEngine:ie.translationEngine,actionDispatcher:ie.actionDispatcher,parentDataContext:x});return f.data_sources&&f.data_sources.length>0?Xe.createElement(wy,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:ie.currentDataContext,globalStateUpdater:ie.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ie.bindingEngine,debug:Mo,children:O}):O}))])))))};e?.sync?(Ze.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Ze.log("재렌더링 시작 (with startTransition)"),H.startTransition(()=>{d()})),Ze.log("템플릿 데이터 업데이트 완료")}catch(n){throw Ze.error("템플릿 데이터 업데이트 실패",n),n}}function xc(){try{Ze.log("템플릿 정리 시작"),ie.reactRoot&&(Ze.log("React Root 언마운트"),ie.reactRoot.unmount(),ie.reactRoot=null),ie.templateId=null,ie.locale="ko",ie.isInitialized=!1,ie.containerId=null,ie.currentLayoutJson=null,ie.currentDataContext={},ie.translationContext={templateId:"",locale:"ko"},ie.registry=null,ie.bindingEngine=null,ie.translationEngine=null,ie.actionDispatcher=null,ie.templateMetadata=null,Ze.log("템플릿 정리 완료")}catch(o){throw Ze.error("템플릿 정리 실패",o),o}}function ea(){return Object.freeze({...ie})}function Dy(){return ie.actionDispatcher}const Ho={initTemplateEngine:No,renderTemplate:ms,updateTemplateData:ys,destroyTemplate:xc,getState:ea};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Ho,KA({getState:()=>({translationEngine:ie.translationEngine,translationContext:ie.translationContext,bindingEngine:ie.bindingEngine,actionDispatcher:ie.actionDispatcher,templateMetadata:ie.templateMetadata}),transitionManager:jr,responsiveManager:hi,webSocketManager:Cc}),Ze.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Pr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:_r,LayoutLoader:mf,TemplateApp:Do,TemplateEngine:Ho,default:Ho,destroyTemplate:xc,getActionDispatcher:Dy,getState:ea,initTemplateApp:xf,initTemplateEngine:No,loadLayoutEditorBundle:Tf,renderTemplate:ms,updateTemplateData:ys},Symbol.toStringTag,{value:"Module"}));Qt.DataSourceManager=_r,Qt.LayoutLoader=mf,Qt.TemplateApp=Do,Qt.TemplateEngine=Ho,Qt.default=Ho,Qt.destroyTemplate=xc,Qt.getActionDispatcher=Dy,Qt.getState=ea,Qt.initTemplateApp=xf,Qt.initTemplateEngine=No,Qt.loadLayoutEditorBundle=Tf,Qt.renderTemplate=ms,Qt.updateTemplateData=ys,Object.defineProperties(Qt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); //# sourceMappingURL=template-engine.min.js.map diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 3a66c60b..a9100017 100644 --- a/resources/js/core/template-engine/CHANGELOG.md +++ b/resources/js/core/template-engine/CHANGELOG.md @@ -5,6 +5,13 @@ > > 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) +## [engine-v1.56.4] - 2026-08-04 + +### Fixed + +- 반복 렌더 경로(`renderItemChildren`)가 리터럴 단일 바인딩(`{{true}}` / `{{false}}` / `{{null}}` / `{{undefined}}`)을 경로로 탐색해 값이 `undefined` 가 됐다. 판정 통일(engine-v1.55.0)에서 리터럴을 `BindingShape` 한 곳으로 모았지만 이 경로만 `hasPipes → isComplexExpression → 경로 탐색` 3분기를 직접 갈라 리터럴을 몰랐고, 그 결과 같은 `{{true}}` 가 조건 자리에서는 `true`, 목록 셀·카드 등 반복 렌더 prop 자리에서는 `undefined` 로 갈렸다 — 통일이 없애려던 비대칭이 이 지점에만 남아 있었다. 형태 판정을 `resolveSingleBindingValue` 에 위임해 다른 경로와 같은 규칙을 쓴다. +- 저장소 레이아웃의 리터럴 단일 바인딩 60건은 전부 `if`/`condition` 자리라 화면 표시에는 변화가 없다. 브라우저 실측으로 발견했고(배포 번들의 `G7Core.renderItemChildren` 직접 호출), 같은 지점이 빈 바인딩(`{{}}`)도 몰라 경로 탐색으로 보내던 것을 함께 봉인했다. + ## [engine-v1.56.3] - 2026-08-02 ### Fixed diff --git a/resources/js/core/template-engine/helpers/RenderHelpers.ts b/resources/js/core/template-engine/helpers/RenderHelpers.ts index 57a1277c..66770fe1 100644 --- a/resources/js/core/template-engine/helpers/RenderHelpers.ts +++ b/resources/js/core/template-engine/helpers/RenderHelpers.ts @@ -1,3 +1,7 @@ +// audit:allow seo-renderer-parity-sync 이번 변경은 노드 키·컨텍스트 처리 추가가 아니라 +// 리터럴 판정을 BindingShape 로 위임한 것이다. 봇(SEO) 측 ExpressionEvaluator 는 +// 이미 'true'/'false'/'null' 을 리터럴로 해석하고 있었으므로(app/Seo/ExpressionEvaluator.php), +// 이 수정은 React 경로를 봇 경로에 맞춘 것이며 패리티를 좁힌다. 봇 측 대응 변경 없음. /** * 렌더링 관련 헬퍼 함수 모듈 * @@ -762,34 +766,34 @@ export function renderItemChildren( effectivePath = singleBindingPath.slice(RAW_PREFIX.length); } - let result; - if (hasPipes(effectivePath)) { - // 파이프 표현식은 evaluatePipeExpression 으로 평가한다. - // isComplexExpression 은 `|` 를 연산자로 보아 evaluateExpression 으로 보내는데, - // 그 경로에서는 `value | pipe` 가 JS 비트 OR 로 평가되어 - // 인자 있는 파이프는 예외(값 소실), 인자 없는 파이프는 조용한 오답이 된다. - // DynamicRenderer 의 text 처리와 동일한 분기 순서를 유지한다. - // raw: 접두사는 아래 공통 분기(wrapRawDeep)가 담당하므로 여기서는 제거된 - // effectivePath 만 넘긴다 — 원본 value 를 넘기면 raw 마커가 이중으로 감싸진다. - // @since engine-v1.54.3 - // 반복 렌더의 props 값도 원본 타입이 필요하다 (문자열 서식 미적용). - // @since engine-v1.54.9 - try { - result = bindingEngine.evaluatePipeExpression(effectivePath, context, { skipCache: true }); - } catch (error) { - logger.warn('renderItemChildren: 파이프 표현식 평가 실패:', error); - return undefined; - } - } else if (isComplexExpression(effectivePath)) { - try { - result = bindingEngine.evaluateExpression(effectivePath, context); - } catch (error) { + // 형태 판정은 `BindingShape` 단일 출처에 맡긴다. 종전에는 이 지점만 + // `hasPipes → isComplexExpression → 경로 탐색` 3분기를 직접 갈라, 판정 통일 + // (engine-v1.55.0)이 모아 둔 **리터럴**(`true`/`false`/`null`/`undefined`)을 + // 이 경로만 몰랐다. 그래서 `{{true}}` 가 조건 자리에서는 `true`, 반복 렌더 prop + // 자리에서는 경로 탐색으로 새어 `undefined` 가 됐다 — 통일이 없애려던 바로 그 + // 비대칭이 여기에만 남아 있었다. + // + // 실행 정책은 종전과 같다: 파이프는 원본 타입 보존(engine-v1.54.9), 평가 실패는 + // 경고 후 `undefined`(값 소실이 화면 전체를 깨뜨리지 않도록). + // raw: 접두사는 아래 공통 분기(wrapRawDeep)가 담당하므로 제거된 effectivePath 만 + // 넘긴다 — 원본 value 를 넘기면 raw 마커가 이중으로 감싸진다. @since engine-v1.54.3 + // @since engine-v1.56.4 + let evaluationFailed = false; + let result = resolveSingleBindingValue(effectivePath, context, bindingEngine, { + skipCache: true, + onError: (error) => { logger.warn('renderItemChildren: 표현식 평가 실패:', error); + evaluationFailed = true; + return undefined; - } - } else { - // skipCache: true - 반복 렌더링에서 같은 경로가 다른 값을 가져야 함 - result = bindingEngine.resolve(effectivePath, context, { skipCache: true }); + }, + onEmpty: () => { + logger.warn('renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.'); + }, + }); + + if (evaluationFailed) { + return undefined; } // 표현식 평가 결과가 $t: 접두사 문자열이면 번역 처리 diff --git a/resources/js/core/template-engine/helpers/__tests__/RenderHelpers.repeatParity.test.tsx b/resources/js/core/template-engine/helpers/__tests__/RenderHelpers.repeatParity.test.tsx index 0932e081..ebc116c9 100644 --- a/resources/js/core/template-engine/helpers/__tests__/RenderHelpers.repeatParity.test.tsx +++ b/resources/js/core/template-engine/helpers/__tests__/RenderHelpers.repeatParity.test.tsx @@ -307,4 +307,38 @@ describe('renderItemChildren — 반복 렌더 경로 기능 격차', () => { expect(JSON.parse(screen.getByTestId('probe').getAttribute('data-json')!)).toBe(42); view.unmount(); }); + + /** + * 리터럴 단일 바인딩 (engine-v1.56.4) + * + * 판정 통일(engine-v1.55.0)에서 리터럴을 `BindingShape` 한 곳으로 모았지만, 이 경로만 + * `hasPipes → isComplexExpression → 경로 탐색` 3분기를 직접 갈라 리터럴을 몰랐다. + * 그래서 `{{true}}` 가 조건 자리에서는 `true`, 반복 렌더 prop 자리에서는 `undefined` 로 + * 갈렸다 — 통일이 없애려던 바로 그 비대칭이 이 경로에만 남아 있었다. + */ + it.each([ + ['{{true}}', true], + ['{{false}}', false], + ['{{null}}', null], + ])('리터럴 %s 이 prop 자리에서 경로 탐색으로 새지 않는다', (expr, expected) => { + const view = renderItems( + [{ id: 'p', type: 'basic', name: 'Probe', props: { value: expr } }], + { row: { id: 1 } }, + ); + + expect(JSON.parse(screen.getByTestId('probe').getAttribute('data-json')!)).toBe(expected); + view.unmount(); + }); + + it('리터럴과 같은 이름의 컨텍스트 경로보다 리터럴이 우선한다', () => { + // `true` 라는 이름의 컨텍스트 키가 있어도 `{{true}}` 는 리터럴이다 — + // 조건 평가 경로와 같은 규칙. + const view = renderItems( + [{ id: 'p', type: 'basic', name: 'Probe', props: { value: '{{true}}' } }], + { true: '경로값', row: { id: 1 } }, + ); + + expect(JSON.parse(screen.getByTestId('probe').getAttribute('data-json')!)).toBe(true); + view.unmount(); + }); }); diff --git a/tests/Playwright/specs/binding-render-path-symmetry.spec.ts b/tests/Playwright/specs/binding-render-path-symmetry.spec.ts index 8e978f3d..9a831d85 100644 --- a/tests/Playwright/specs/binding-render-path-symmetry.spec.ts +++ b/tests/Playwright/specs/binding-render-path-symmetry.spec.ts @@ -110,6 +110,39 @@ test.describe('렌더 경로 간 바인딩 해석 대칭', () => { expect(String(value)).not.toContain('{{'); }); + // @scenario binding_literal_symmetry + // @effects same_expression_same_value_across_paths + test('리터럴이 반복 렌더와 조건 판정에서 같은 값을 본다', async ({ page }) => { + const result = await page.evaluate(() => { + const g7 = (window as any).G7Core; + const Span = function Span() { return null; }; + const context = { row: { id: 1 } }; + const viaRepeat = (expr: string) => + (g7.renderItemChildren( + [{ type: 'basic', name: 'Span', props: { title: expr } }], + context, + { Span }, + 'e2e-literal', + ) as any[])[0]?.props?.title; + + return { + repeatTrue: viaRepeat('{{true}}'), + repeatFalse: viaRepeat('{{false}}'), + repeatNull: viaRepeat('{{null}}'), + condTrue: g7.evaluateCondition('{{true}}', context), + condFalse: g7.evaluateCondition('{{false}}', context), + }; + }); + + // 수정 전: 반복 렌더 경로만 리터럴을 몰라 경로 탐색으로 새어 전부 undefined 였다. + // 조건 경로는 리터럴을 알았으므로 같은 작성이 자리에 따라 갈렸다. + expect(result.repeatTrue).toBe(true); + expect(result.repeatFalse).toBe(false); + expect(result.repeatNull).toBeNull(); + expect(result.repeatTrue).toBe(result.condTrue); + expect(result.repeatFalse).toBe(result.condFalse); + }); + // @scenario binding_empty_expression // @effects same_expression_same_value_across_paths test('빈 바인딩이 컨텍스트 객체 전체를 노출하지 않는다', async ({ page }) => {