From 9bcd97098be64c47b93e690abadf8d1db791fb12 Mon Sep 17 00:00:00 2001 From: HeuJung Date: Thu, 23 Jul 2026 21:34:44 +0900 Subject: [PATCH] =?UTF-8?q?fix(core):=20=EB=81=9D=20=EC=8A=AC=EB=9E=98?= =?UTF-8?q?=EC=8B=9C=EA=B0=80=20=EB=B6=99=EC=9D=80=20=EA=B2=BD=EB=A1=9C(/a?= =?UTF-8?q?dmin/)=EA=B0=80=20=EB=9D=BC=EC=9A=B0=ED=8A=B8=EC=97=90=20?= =?UTF-8?q?=EB=A7=A4=EC=B9=AD=EB=90=98=EC=A7=80=20=EC=95=8A=EB=8D=98=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 라우트 패턴은 끝 슬래시 없는 형태(*/admin 등)로만 정의되는데(routes.json 규약), Router.match 가 들어온 경로의 끝 슬래시를 정규화하지 않아 /admin/ (끝 슬래시)이 어떤 라우트에도 매칭되지 않고 404 로 떨어졌다. 특히 미인증 상태로 /admin/ 진입 시 대시보드 → 로그인 리다이렉트 흐름 대신 404 가 노출됐다. match 진입에 normalizePathname 을 두어 루트(/)를 제외한 경로의 끝 슬래시(연속 포함)를 제거한 뒤 대조한다. match 는 라우팅 단일 진입점이라 모든 호출부가 함께 정상화되고, 다운스트림(auth back-URL, getAuthType)은 원본 pathname 을 그대로 써 의미 변화가 없다. 기존 릴리스부터 있던 라우터 견고성 결함이며 자산 URL 이중 모드 변경과는 무관하다(matchPattern 은 미변경, routes.json 은 81건 정상 로드 확인). --- CHANGELOG.md | 1 + public/build/core/template-engine.min.js | 2 +- resources/js/core/routing/Router.ts | 25 ++++++++++- .../js/core/routing/__tests__/Router.test.ts | 44 +++++++++++++++++++ .../js/core/template-engine/CHANGELOG.md | 8 ++++ .../admin/admin-trailing-slash-route.spec.ts | 44 +++++++++++++++++++ 6 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 tests/Playwright/specs/admin/admin-trailing-slash-route.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 51cf53fe..cb5ba2b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ - 일부 안내가 실제 문장 대신 내부 식별자(`messages.auth.unauthenticated` 같은 문자열)로 표시되던 문제를 수정했습니다. 로그인하지 않았거나 역할 권한이 없어 요청이 거절될 때, 메뉴에 역할을 지정할 때, 확장 식별자를 잘못 입력했을 때, 활동 로그를 기간·유형으로 검색할 때가 해당됩니다. - 플러그인을 GitHub 주소나 ZIP 파일로 설치할 때의 입력 안내가 내부 식별자로 표시되던 문제를 수정했습니다. 주소 형식이 잘못됐거나, ZIP이 아닌 파일을 올렸거나, 파일 용량을 초과했을 때 정상 문장으로 안내합니다. - 레이아웃 편집기 화면이 정상 동작하는데도 서버가 "페이지 없음"(404)으로 응답하던 문제를 수정했습니다. 화면은 그대로 보였지만 브라우저 캐싱과 서버 접속 기록에서 없는 페이지로 취급되던 상태입니다. +- 주소 끝에 슬래시가 붙은 형태(예: `/admin/`)로 접속하면 화면이 "페이지 없음"(404)으로 뜨던 문제를 수정했습니다. 특히 로그인이 풀린 상태에서 이렇게 접속하면 로그인 화면으로 넘어가지 않고 404가 나타났습니다. 이제 끝 슬래시가 있어도 정상적으로 같은 페이지로 연결됩니다. ## [7.0.5] - 2026-07-16 diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index 08642004..d708b2d0 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -224,7 +224,7 @@ Error generating stack: `+c.message+` `:""} - `}static renderFromError(e,a,r,i=!1,l,u,d){let f,g;if(a.userMessageKey.startsWith("$t:"))if(u&&l)try{f=u.translate(a.userMessageKey,l)}catch{f=a.userMessageKey.replace("$t:","")}else f=a.userMessageKey.replace("$t:","");else f=a.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:r,message:f,detailMessage:g,icon:a.icon,showStack:a.showStack,stackTrace:a.stack,showReloadButton:a.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const a=document.createElement("div");return a.textContent=e,a.innerHTML}}const ss=ct("Router");class U_{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,a){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(a)}async emit(e,...a){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...a)))}async loadRoutes(e){try{const a=e!==void 0&&e>0?e:null,r=await fetch(La(`/api/templates/${this.templateIdentifier}/routes`,"json",a));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.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,ss.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(a){throw ss.error("Error loading routes:",a),a}}setRoutes(e){this.routes=e,ss.log(`Set ${this.routes.length} routes`)}match(e){for(const a of this.routes){const r=this.matchPattern(a.path,e);if(r!==null)return{route:a,params:r}}return null}matchPattern(e,a){const r=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(r.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),u=a.match(l);if(!u)return null;const d={};return r.forEach((f,g)=>{d[f]=u[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,a){return e.auth_type?e.auth_type:a.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,a=window.location.search,r=this.match(e);if(!r){ss.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){ss.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const u=this.getAuthType(r.route,e),d=ha.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===u;if(f||(f=await d.checkAuth(u)),!f){const g=d.getLoginRedirectUrl(u,e+a);ss.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(a),l={};for(const u of i.keys()){if(u in l)continue;const d=i.getAll(u);d.length>1?l[u]=d:d.length===1&&(u.endsWith("[]")?l[u]=d:l[u]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.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 a=this.pendingNavigation;this.executeNavigation(a)}}}}const B_=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function iy(o){const e=B_.exec(o);return e?{templateIdentifier:e[1]}:null}const zt=ct("ErrorPageHandler");class P_{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(La(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&zt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const a=await e.json();if(!a.success||!a.data)return this.debug&&zt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=a.data;return!r.error_config||!r.error_config.layouts?(this.debug&&zt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&zt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return zt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,a="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&zt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&zt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&zt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&zt.error(`Failed to load error layout: ${i}`),!1;this.debug&&zt.log("Error layout loaded:",l);let u={};const d=l.data_sources||[];if(d.length>0){this.debug&&zt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),b=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...b];if(v.length>0)try{u=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&zt.log("Data sources fetched:",Object.keys(u))}catch(S){zt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,u,f),this.debug&&zt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...u,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:a,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&zt.log(`Error page ${e} rendered successfully`),!0}catch(r){return zt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,a,r){for(const i of e){const l=a[i.id];if(!l)continue;const u=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=u,zt.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;r[d]=f?this.getValueByPath(u,f):u,zt.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]=u,zt.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(u,m):u,zt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,a){return a.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&zt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const a=await this.loadConfig();return a?!!(a.layouts[e]||a.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&zt.log("Config cache cleared")}}const $t=ct("ModuleAssetLoader");class q_{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){$t.log("No module assets to load");return}const a=[...e].sort((d,f)=>d.priority-f.priority);$t.log("Loading module assets:",a.map(d=>d.identifier));const r=a.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=a.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),u=l.filter(d=>d.status==="rejected");if(u.length>0){$t.warn(`Some module assets failed to load (${u.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}$t.log("All module assets loaded successfully")}async loadBundle(e,a,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),a&&i.push(this.loadBundleJs(e,a)),i.length===0){$t.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,a){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){$t.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=a,l.id=r,l.onload=()=>{$t.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{$t.warn(`Failed to load bundle CSS: ${e} (${a})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,a){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){$t.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return $t.log(`Bundle JS already loading: ${e}`),i;const l=Yg(a,{id:r},{label:`bundle JS: ${e}`}).then(()=>{$t.log(`Bundle JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:u}),this.loadingPromises.delete(r)}).catch(u=>{throw $t.warn(`Failed to load bundle JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(r),u});return this.loadingPromises.set(r,l),l}async loadCSS(e,a){const r=`module-css-${e}`;if(document.getElementById(r)){$t.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const u=document.createElement("link");u.rel="stylesheet",u.href=a,u.id=r,u.onload=()=>{$t.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:u}),i()},u.onerror=()=>{$t.warn(`Failed to load CSS: ${e} (${a})`),i()},document.head.appendChild(u)})}async loadJS(e,a){const r=`module-js-${e}`;if(document.getElementById(r)){$t.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return $t.log(`JS already loading: ${e}`),i;const l=Yg(a,{id:r},{label:`JS: ${e}`}).then(()=>{$t.log(`JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(e,{type:"js",element:u}),this.loadingPromises.delete(e)}).catch(u=>{throw $t.warn(`Failed to load JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(e),u});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,a){const r=this.loadedAssets.get(e)||[];r.push(a),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const a=this.loadedAssets.get(e);if(!a||a.length===0){$t.log(`No assets to unload for: ${e}`);return}a.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),$t.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),$t.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(a=>{this.unloadExtensionAsset(a)}),$t.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let cf=null;function uf(){return cf||(cf=new q_),cf}function G_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[a,r]of Object.entries(o.moduleAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}function V_(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?wr(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?wr(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?wr(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?wr(e.pluginCss):e.pluginCss}}function F_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[a,r]of Object.entries(o.pluginAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}const df=ct("SystemBannerManager");class pc{static show(e){this.banners.set(e.id,e),this.render(),df.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),df.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),df.log("All banners hidden")}static detectLocale(){try{const a=window.G7Core;if(a?.locale?.current)return a.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,a){return typeof e=="string"?e:e[a]||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 a=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=a.map(i=>{const l=this.resolveMessage(i.message,r),u=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const a=document.getElementById("app");a&&(a.style.paddingTop=e>0?`${e}px`:"")}}$(pc,"banners",new Map),$(pc,"containerId","g7-system-banners");const B=ct("TemplateApp");function sy(o){const e={};for(const a of o.keys()){if(a in e)continue;const r=o.getAll(a);r.length>1?e[a]=r:r.length===1&&(a.endsWith("[]")?e[a]=r:e[a]=r[0])}return e}const Ca=class Ca{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 a=this.loadLocaleFromStorage(),r=a||e.locale||"ko";this.config={...e,locale:r},!a&&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 a=new wn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const u=l.path;l.path=a.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",u),l.path=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const u=l.redirect;l.redirect=a.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",u),l.redirect=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const a of e)try{const r=localStorage.getItem(a);r&&r!==localStorage.getItem(Ca.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Ca.LOCALE_STORAGE_KEY,r),B.log(`Migrated locale from '${a}' to '${Ca.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(a)}catch(r){B.warn(`Failed to migrate locale key '${a}':`,r)}}async init(){try{Fs.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),US();const e=da.getInstance(),a=ha.getInstance(),r=this.loadCacheVersionFromStorage()||0,[i,l,u,d,f]=await Promise.all([_o({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:r}),e.loadComponents(this.config.templateId,this.config.templateType),Al(La(`/api/templates/${this.config.templateId}/routes`,"json",r>0?r: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}),a.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(La(`/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 T=await Al(La(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(L=>{if(!L.ok)throw new Error(`Failed to reload routes: ${L.statusText}`);return L.json()}).then(L=>{if(!L.success)throw new Error("Failed to reload routes from API");return L.data});Array.isArray(T.routes)&&(T.routes=this.resolveRouteExpressions(T.routes),Object.assign(u,T),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>ep),M=L.getInstance();M.setCacheVersion(this.extensionCacheVersion);const R=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,R,"/api",!0),R!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(L){B.error("Failed to reload translations:",L)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,pa().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),a.on("logout",()=>{B.log("User logged out")}),a.on("authStateChange",A=>{B.log("Auth state changed:",A)}),B.log("AuthManager event handlers registered");const g=$a(),m=this.config.templateType==="admin"?"admin":"user",b=a.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,T=a.getLoginRedirectUrl(m,A,"session_expired");window.location.href=T}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ef(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const v=new va({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new P_({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:os,dataSourceManager:v,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 U_(this.config.templateId),Array.isArray(u.routes)){const A=this.resolveRouteExpressions(u.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:S}=await Promise.resolve().then(()=>za),E=S();if(E&&(E.setDefaultContext({navigate:A=>this.router?.navigate(A)}),E.setGlobalStateUpdater((A,T)=>this.setGlobalState(A,T)),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"&&iy(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await os({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=uf(),a=V_();if(!a){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",a.moduleJs,a.moduleCss),await e.loadBundle("plugin",a.pluginJs,a.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=uf(),a=G_();a.length>0&&(B.log("Loading module assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a));const r=F_();r.length>0&&(B.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const a=++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:",a),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(a!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",a);return}B.log("Layout loaded:",l);const u=pa();l.errorHandling?(u.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):u.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[te,he]of Object.entries(f))if(Array.isArray(he))for(const x of he)g.append(te,x);else g.set(te,he);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:b,getActionDispatcher:v}=await Promise.resolve().then(()=>za),S=new b;if(i){const te=v();te&&te.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),pc.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=v();te?.isPreviewMode()&&(te.setPreviewMode(!1),pc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const te=v();te&&te.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(he=>he.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const te=v();te&&te.setNamedActions(l.named_actions)}const E=S.filterByCondition(d,m);d.length!==E.length&&B.log("Data sources filtered by condition:",{before:d.map(te=>te.id),after:E.map(te=>te.id)});const A=E.filter(te=>te.loading_strategy==="blocking"),T=E.filter(te=>(te.loading_strategy||"progressive")!=="blocking"&&te.type!=="websocket"),L=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=L.length>0&&E.some(te=>L.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 R={},D={},U={},j={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=E,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${a} - queryObject:`,f),B.log(`handleRouteChange #${a} - queryParams:`,g.toString()),A.length>0&&(B.log("Fetching blocking data sources:",A.map(he=>he.id)),(await S.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(he=>{if(he.state==="success"&&he.data!==void 0)R[he.id]=he.data;else if(he.state==="error"&&he.error){const x=he.error,K=x.response?.data?.message;D[he.id]={message:K||he.error.message,status:x.response?.status||x.status}}}),this.processInitOptions(A,R,U,j),this.currentFetchedData={...R},B.log("Blocking data loaded:",Object.keys(R)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(U).length>0&&B.log("Local state init (blocking):",Object.keys(U)),Object.keys(j).length>0&&B.log("Isolated state init (blocking):",Object.keys(j)));const P=T.length>0;if(P&&(Na.setPending(!0),B.log("Transition started before rendering")),a!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",a);return}const{getState:X}=await Promise.resolve().then(()=>za),ge=X().currentDataContext||{},Ee=T.map(te=>te.id),Ce={};if(P){Ee.forEach(he=>{ge[he]!==void 0?Ce[he]=ge[he]:Ce[he]=void 0});const te=Object.keys(Ce).filter(he=>Ce[he]!==void 0);te.length>0&&B.log("Preserving previous progressive data:",te),B.log("Progressive data sources initialized:",Ee)}const $e=l.defines||{},Pe={...Ce,...e.params,...R,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(U).length>0?U:void 0,_isolatedInit:Object.keys(j).length>0?j:void 0,_defines:Object.keys($e).length>0?$e:void 0};if(l.computed&&Object.keys(l.computed).length>0){const te=this.calculateComputed(l.computed,Pe);Object.keys(te).length>0&&(Pe._computed=te,this.globalState._computed=te,B.log("Computed values calculated:",Object.keys(te))),Pe._computedDefinitions=l.computed}const Xe=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Xe&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Xe}),this.globalState._local={},nC()),this.currentLayoutName=Xe;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[te,he]of Object.entries(Q))this.globalState._local[te]===void 0&&(this.globalState._local[te]=JSON.parse(JSON.stringify(he)));Pe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[te,he]of Object.entries(l.initGlobal))this.globalState[te]===void 0&&(this.globalState[te]=JSON.parse(JSON.stringify(he)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[te,he]of Object.entries(l.initIsolated))j[te]===void 0&&(j[te]=JSON.parse(JSON.stringify(he)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}Pe._global={...this.globalState,layoutWarnings:l.warnings||[]};const fe=l.initActions||l.init_actions;if(fe&&fe.length>0){await this.executeInitActions(fe,Pe),B.log("initActions executed before render");const te=this.globalState;if(te._local){if(Object.keys(U).length>0){for(const[he,x]of Object.entries(U))te._local[he]!==void 0?te._local[he]=this.deepMerge(te._local[he],x):te._local[he]=x;B.log("localInit merged into _local after initActions:",Object.keys(U))}Pe._local=te._local,B.log("_local merged into dataContext:",te._local)}if(Pe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const he=this.calculateComputed(l.computed,Pe);Object.keys(he).length>0&&(Pe._computed=he,this.globalState._computed=he,B.log("Computed values recalculated after init_actions:",Object.keys(he)))}if(Object.keys(this.currentFetchedData).length>0){for(const[he,x]of Object.entries(this.currentFetchedData))Pe[he]=x;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 os({containerId:"app",layoutJson:l,dataContext:Pe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),T.length>0){if(a!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",a),Na.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",T.map(x=>x.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za);try{const x=T.map(async K=>{try{const de=(await S.fetchDataSourcesWithResults([K],e.params||{},g,this.globalState))[0];if(!de){B.log(`Data source ${K.id} skipped (no fetch result)`);return}if(a!==this.currentRouteChangeId){B.log(`Data source ${K.id} fetch cancelled (newer request exists)`);return}if(de.state==="success"&&de.data!==void 0){B.log(`Progressive data source loaded: ${K.id}`),this.currentFetchedData[K.id]=de.data;const se={};this.processInitOptions([K],{[K.id]:de.data},se);const me=he();if(me.bindingEngine){const ve=[K.id];K.initGlobal&&ve.push("_global"),K.initLocal&&ve.push("_local"),me.bindingEngine.invalidateCacheByKeys(ve)}const Ne={[K.id]:de.data};Object.keys(se).length>0&&(Ne._localInit=se,Object.assign(U,se)),K.initGlobal&&(Ne._global={...this.globalState}),te(Ne)}else if(de.state==="error"&&de.error){const se=de.error,me=se.response?.data?.message;D[K.id]={message:me||de.error.message,status:se.response?.status||se.status},B.log(`Progressive data source error: ${K.id}`,D[K.id]),te({[K.id]:null,_dataSourceErrors:{...D}})}}catch(re){B.error(`Failed to fetch data source: ${K.id}`,re)}});if(await Promise.all(x),a!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",a);return}B.log("All progressive data sources loaded")}finally{Na.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ye=E.filter(te=>te.type==="websocket");if(ye.length>0){B.log("Subscribing WebSocket data sources:",ye.map(K=>K.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za),x={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(x)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(E,(K,re)=>{B.log(`WebSocket data received for: ${K}`,re),this.currentFetchedData[K]=re;const de=E.find(ve=>ve.id===K),se=he();if(se.bindingEngine){const ve=[K];de?.initGlobal&&ve.push("_global"),de?.initLocal&&ve.push("_local"),se.bindingEngine.invalidateCacheByKeys(ve)}te({[K]:re});const Ne=E.find(ve=>ve.type==="websocket"&&(ve.target_source||ve.id)===K)?.onReceive;Array.isArray(Ne)&&Ne.length>0&&window.G7Core?.dispatch&&(async()=>{for(const He of Ne)try{const Ae=this.getActionDispatcher?.();Ae&&await Ae.dispatchAction(He,{navigate:this.getRouter?.()?(Et,Rt)=>this.getRouter().navigate(Et,Rt):void 0,setState:Et=>this.setGlobalState(Et),state:this.globalState,data:{...this.globalState,$args:[re],$event:re},_isDispatchFallbackContext:!0})}catch(Ae){B.error(`WebSocket onReceive action failed for ${K}:`,Ae)}})()},x),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(r){B.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,a,r,i){e.some(u=>u.refetchOnMount===!0&&u.initLocal)&&(r._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(u=>{const d=a[u.id];if(!d)return;const f=d.data??d;if(u.initLocal){if(typeof u.initLocal=="string"){let g=f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const b=this.evaluateDefaults(u.initLocalDefaults,a);g={...b,...f},B.log(`initLocalDefaults applied for ${u.initLocal}:`,Object.keys(b))}const m=this.globalState._local?.[u.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(r[u.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${u.id}.data -> _local.${u.initLocal}`)):(r[u.initLocal]=g,B.log(`initLocal: ${u.id}.data -> _local.${u.initLocal}`))}else if(typeof u.initLocal=="object"&&u.initLocal.key){const{key:g,path:m}=u.initLocal;let b=m?this.extractValueByPathOrExpression(f,m,u.id):f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const S=this.evaluateDefaults(u.initLocalDefaults,a);b={...S,...b},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(S))}const v=this.globalState._local?.[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(r[g]=this.deepMerge(v,b),B.log(`initLocal (merged): ${u.id}.data${m?"."+m:""} -> _local.${g}`)):(r[g]=b,B.log(`initLocal: ${u.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof u.initLocal=="object"){const g=u.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(u.initLocal);for(const{targetPath:b,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,u.id);if(b.includes(".")){const E=b.split(".")[0];r[E]===void 0&&this.globalState._local?.[E]!==void 0&&(r[E]=JSON.parse(JSON.stringify(this.globalState._local[E]))),this.setValueAtPath(r,b,S,g),B.log(`initLocal map (${g}): ${u.id} ${v} -> _local.${b}`)}else{const E=this.globalState._local?.[b];g==="replace"?(r[b]=S,B.log(`initLocal map (replace): ${u.id} ${v} -> _local.${b}`)):g==="shallow"?E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]={...E,...S},B.log(`initLocal map (shallow): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`)):E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]=this.deepMerge(E,S),B.log(`initLocal map (deep): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`))}}}}if(u.initGlobal)if(typeof u.initGlobal=="object"&&!Array.isArray(u.initGlobal)&&!("key"in u.initGlobal))for(const[m,b]of Object.entries(u.initGlobal)){if(typeof b!="string"){B.warn(`initGlobal map value must be string, got ${typeof b} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,b,u.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),B.log(`initGlobal map (merged): ${u.id} ${b} -> _global.${m}`)):(this.globalState[m]=v,B.log(`initGlobal map: ${u.id} ${b} -> _global.${m}`))}else{const m=Array.isArray(u.initGlobal)?u.initGlobal:[u.initGlobal];for(const b of m)if(typeof b=="string"){const v=this.globalState[b];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[b]=this.deepMerge(v,f),B.log(`initGlobal (merged): ${u.id}.data -> _global.${b}`)):(this.globalState[b]=f,B.log(`initGlobal: ${u.id}.data -> _global.${b}`))}else if(typeof b=="object"&&b.key){const{key:v,path:S}=b,E=S?this.extractValueByPathOrExpression(f,S,u.id):f,A=this.globalState[v];A!==void 0&&typeof A=="object"&&typeof E=="object"?(this.globalState[v]=this.deepMerge(A,E),B.log(`initGlobal (merged): ${u.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=E,B.log(`initGlobal: ${u.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&u.initIsolated){if(typeof u.initIsolated=="string"){const g=i[u.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[u.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${u.id}.data -> _isolated.${u.initIsolated}`)):(i[u.initIsolated]=f,B.log(`initIsolated: ${u.id}.data -> _isolated.${u.initIsolated}`))}else if(typeof u.initIsolated=="object"&&u.initIsolated.key){const{key:g,path:m}=u.initIsolated,b=m?this.extractValueByPathOrExpression(f,m,u.id):f,v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated (merged): ${u.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated: ${u.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof u.initIsolated=="object")for(const[g,m]of Object.entries(u.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const b=this.extractValueByPathOrExpression(f,m,u.id),v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated map (merged): ${u.id} ${m} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated map: ${u.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,a){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const u=l.slice(2,-2).trim();r[i]=this.evaluateExpression(u,a)}else r[i]=l;return r}evaluateExpression(e,a){try{const r=e.split("??").map(i=>i.trim());for(const i of r){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(a,i);if(l!=null)return l}return}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,a){const r=a.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(u=>{const d=u.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const b=g.match(/\[\d+\]/g);return b&&m.push(...b),m}return[u]}).filter(u=>u!=="");for(const u of l){if(i==null)return;if(u.startsWith("[")&&u.endsWith("]")){const d=parseInt(u.slice(1,-1),10);i=i[d]}else i=i[u]}return i}extractValueByPathOrExpression(e,a,r){const i=a.match(/^\{\{(.+)\}\}$/);if(i){const l=i[1].trim(),u=new wn,d={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const f=u.evaluateExpression(l,d);return B.log(`initLocal/initGlobal expression evaluated: ${a} -> `,f),f}catch(f){B.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,a,f);return}}return this.getNestedValue(e,a)}async loadLayoutScripts(e,a){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!Yi({if:i.if,conditions:i.conditions},a,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 u=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)});r.push(u)}r.length>0&&(await Promise.all(r),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,a){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return new Function("ctx",` + `}static renderFromError(e,a,r,i=!1,l,u,d){let f,g;if(a.userMessageKey.startsWith("$t:"))if(u&&l)try{f=u.translate(a.userMessageKey,l)}catch{f=a.userMessageKey.replace("$t:","")}else f=a.userMessageKey.replace("$t:","");else f=a.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:r,message:f,detailMessage:g,icon:a.icon,showStack:a.showStack,stackTrace:a.stack,showReloadButton:a.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const a=document.createElement("div");return a.textContent=e,a.innerHTML}}const ss=ct("Router");class U_{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,a){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(a)}async emit(e,...a){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...a)))}async loadRoutes(e){try{const a=e!==void 0&&e>0?e:null,r=await fetch(La(`/api/templates/${this.templateIdentifier}/routes`,"json",a));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.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,ss.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(a){throw ss.error("Error loading routes:",a),a}}setRoutes(e){this.routes=e,ss.log(`Set ${this.routes.length} routes`)}match(e){const a=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,a);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,a){const r=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(r.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),u=a.match(l);if(!u)return null;const d={};return r.forEach((f,g)=>{d[f]=u[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,a){return e.auth_type?e.auth_type:a.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,a=window.location.search,r=this.match(e);if(!r){ss.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){ss.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const u=this.getAuthType(r.route,e),d=ha.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===u;if(f||(f=await d.checkAuth(u)),!f){const g=d.getLoginRedirectUrl(u,e+a);ss.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(a),l={};for(const u of i.keys()){if(u in l)continue;const d=i.getAll(u);d.length>1?l[u]=d:d.length===1&&(u.endsWith("[]")?l[u]=d:l[u]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.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 a=this.pendingNavigation;this.executeNavigation(a)}}}}const B_=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function iy(o){const e=B_.exec(o);return e?{templateIdentifier:e[1]}:null}const zt=ct("ErrorPageHandler");class P_{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(La(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&zt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const a=await e.json();if(!a.success||!a.data)return this.debug&&zt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=a.data;return!r.error_config||!r.error_config.layouts?(this.debug&&zt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&zt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return zt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,a="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&zt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&zt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&zt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&zt.error(`Failed to load error layout: ${i}`),!1;this.debug&&zt.log("Error layout loaded:",l);let u={};const d=l.data_sources||[];if(d.length>0){this.debug&&zt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),b=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...b];if(v.length>0)try{u=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&zt.log("Data sources fetched:",Object.keys(u))}catch(S){zt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,u,f),this.debug&&zt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...u,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:a,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&zt.log(`Error page ${e} rendered successfully`),!0}catch(r){return zt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,a,r){for(const i of e){const l=a[i.id];if(!l)continue;const u=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=u,zt.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;r[d]=f?this.getValueByPath(u,f):u,zt.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]=u,zt.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(u,m):u,zt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,a){return a.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&zt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const a=await this.loadConfig();return a?!!(a.layouts[e]||a.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&zt.log("Config cache cleared")}}const $t=ct("ModuleAssetLoader");class q_{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){$t.log("No module assets to load");return}const a=[...e].sort((d,f)=>d.priority-f.priority);$t.log("Loading module assets:",a.map(d=>d.identifier));const r=a.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=a.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),u=l.filter(d=>d.status==="rejected");if(u.length>0){$t.warn(`Some module assets failed to load (${u.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}$t.log("All module assets loaded successfully")}async loadBundle(e,a,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),a&&i.push(this.loadBundleJs(e,a)),i.length===0){$t.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,a){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){$t.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=a,l.id=r,l.onload=()=>{$t.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{$t.warn(`Failed to load bundle CSS: ${e} (${a})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,a){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){$t.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return $t.log(`Bundle JS already loading: ${e}`),i;const l=Yg(a,{id:r},{label:`bundle JS: ${e}`}).then(()=>{$t.log(`Bundle JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:u}),this.loadingPromises.delete(r)}).catch(u=>{throw $t.warn(`Failed to load bundle JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(r),u});return this.loadingPromises.set(r,l),l}async loadCSS(e,a){const r=`module-css-${e}`;if(document.getElementById(r)){$t.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const u=document.createElement("link");u.rel="stylesheet",u.href=a,u.id=r,u.onload=()=>{$t.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:u}),i()},u.onerror=()=>{$t.warn(`Failed to load CSS: ${e} (${a})`),i()},document.head.appendChild(u)})}async loadJS(e,a){const r=`module-js-${e}`;if(document.getElementById(r)){$t.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return $t.log(`JS already loading: ${e}`),i;const l=Yg(a,{id:r},{label:`JS: ${e}`}).then(()=>{$t.log(`JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(e,{type:"js",element:u}),this.loadingPromises.delete(e)}).catch(u=>{throw $t.warn(`Failed to load JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(e),u});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,a){const r=this.loadedAssets.get(e)||[];r.push(a),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const a=this.loadedAssets.get(e);if(!a||a.length===0){$t.log(`No assets to unload for: ${e}`);return}a.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),$t.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),$t.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(a=>{this.unloadExtensionAsset(a)}),$t.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let cf=null;function uf(){return cf||(cf=new q_),cf}function G_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[a,r]of Object.entries(o.moduleAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}function V_(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?wr(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?wr(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?wr(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?wr(e.pluginCss):e.pluginCss}}function F_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[a,r]of Object.entries(o.pluginAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}const df=ct("SystemBannerManager");class pc{static show(e){this.banners.set(e.id,e),this.render(),df.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),df.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),df.log("All banners hidden")}static detectLocale(){try{const a=window.G7Core;if(a?.locale?.current)return a.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,a){return typeof e=="string"?e:e[a]||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 a=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=a.map(i=>{const l=this.resolveMessage(i.message,r),u=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const a=document.getElementById("app");a&&(a.style.paddingTop=e>0?`${e}px`:"")}}$(pc,"banners",new Map),$(pc,"containerId","g7-system-banners");const B=ct("TemplateApp");function sy(o){const e={};for(const a of o.keys()){if(a in e)continue;const r=o.getAll(a);r.length>1?e[a]=r:r.length===1&&(a.endsWith("[]")?e[a]=r:e[a]=r[0])}return e}const Ca=class Ca{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 a=this.loadLocaleFromStorage(),r=a||e.locale||"ko";this.config={...e,locale:r},!a&&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 a=new wn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const u=l.path;l.path=a.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",u),l.path=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const u=l.redirect;l.redirect=a.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",u),l.redirect=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const a of e)try{const r=localStorage.getItem(a);r&&r!==localStorage.getItem(Ca.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Ca.LOCALE_STORAGE_KEY,r),B.log(`Migrated locale from '${a}' to '${Ca.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(a)}catch(r){B.warn(`Failed to migrate locale key '${a}':`,r)}}async init(){try{Fs.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),US();const e=da.getInstance(),a=ha.getInstance(),r=this.loadCacheVersionFromStorage()||0,[i,l,u,d,f]=await Promise.all([_o({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:r}),e.loadComponents(this.config.templateId,this.config.templateType),Al(La(`/api/templates/${this.config.templateId}/routes`,"json",r>0?r: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}),a.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(La(`/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 T=await Al(La(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(L=>{if(!L.ok)throw new Error(`Failed to reload routes: ${L.statusText}`);return L.json()}).then(L=>{if(!L.success)throw new Error("Failed to reload routes from API");return L.data});Array.isArray(T.routes)&&(T.routes=this.resolveRouteExpressions(T.routes),Object.assign(u,T),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>ep),M=L.getInstance();M.setCacheVersion(this.extensionCacheVersion);const R=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,R,"/api",!0),R!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(L){B.error("Failed to reload translations:",L)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,pa().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),a.on("logout",()=>{B.log("User logged out")}),a.on("authStateChange",A=>{B.log("Auth state changed:",A)}),B.log("AuthManager event handlers registered");const g=$a(),m=this.config.templateType==="admin"?"admin":"user",b=a.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,T=a.getLoginRedirectUrl(m,A,"session_expired");window.location.href=T}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ef(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const v=new va({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new P_({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:os,dataSourceManager:v,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 U_(this.config.templateId),Array.isArray(u.routes)){const A=this.resolveRouteExpressions(u.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:S}=await Promise.resolve().then(()=>za),E=S();if(E&&(E.setDefaultContext({navigate:A=>this.router?.navigate(A)}),E.setGlobalStateUpdater((A,T)=>this.setGlobalState(A,T)),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"&&iy(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await os({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=uf(),a=V_();if(!a){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",a.moduleJs,a.moduleCss),await e.loadBundle("plugin",a.pluginJs,a.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=uf(),a=G_();a.length>0&&(B.log("Loading module assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a));const r=F_();r.length>0&&(B.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const a=++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:",a),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(a!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",a);return}B.log("Layout loaded:",l);const u=pa();l.errorHandling?(u.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):u.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[te,he]of Object.entries(f))if(Array.isArray(he))for(const x of he)g.append(te,x);else g.set(te,he);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:b,getActionDispatcher:v}=await Promise.resolve().then(()=>za),S=new b;if(i){const te=v();te&&te.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),pc.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=v();te?.isPreviewMode()&&(te.setPreviewMode(!1),pc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const te=v();te&&te.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(he=>he.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const te=v();te&&te.setNamedActions(l.named_actions)}const E=S.filterByCondition(d,m);d.length!==E.length&&B.log("Data sources filtered by condition:",{before:d.map(te=>te.id),after:E.map(te=>te.id)});const A=E.filter(te=>te.loading_strategy==="blocking"),T=E.filter(te=>(te.loading_strategy||"progressive")!=="blocking"&&te.type!=="websocket"),L=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=L.length>0&&E.some(te=>L.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 R={},D={},U={},j={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=E,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${a} - queryObject:`,f),B.log(`handleRouteChange #${a} - queryParams:`,g.toString()),A.length>0&&(B.log("Fetching blocking data sources:",A.map(he=>he.id)),(await S.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(he=>{if(he.state==="success"&&he.data!==void 0)R[he.id]=he.data;else if(he.state==="error"&&he.error){const x=he.error,K=x.response?.data?.message;D[he.id]={message:K||he.error.message,status:x.response?.status||x.status}}}),this.processInitOptions(A,R,U,j),this.currentFetchedData={...R},B.log("Blocking data loaded:",Object.keys(R)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(U).length>0&&B.log("Local state init (blocking):",Object.keys(U)),Object.keys(j).length>0&&B.log("Isolated state init (blocking):",Object.keys(j)));const P=T.length>0;if(P&&(Na.setPending(!0),B.log("Transition started before rendering")),a!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",a);return}const{getState:X}=await Promise.resolve().then(()=>za),ge=X().currentDataContext||{},Ee=T.map(te=>te.id),Ce={};if(P){Ee.forEach(he=>{ge[he]!==void 0?Ce[he]=ge[he]:Ce[he]=void 0});const te=Object.keys(Ce).filter(he=>Ce[he]!==void 0);te.length>0&&B.log("Preserving previous progressive data:",te),B.log("Progressive data sources initialized:",Ee)}const $e=l.defines||{},Pe={...Ce,...e.params,...R,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(U).length>0?U:void 0,_isolatedInit:Object.keys(j).length>0?j:void 0,_defines:Object.keys($e).length>0?$e:void 0};if(l.computed&&Object.keys(l.computed).length>0){const te=this.calculateComputed(l.computed,Pe);Object.keys(te).length>0&&(Pe._computed=te,this.globalState._computed=te,B.log("Computed values calculated:",Object.keys(te))),Pe._computedDefinitions=l.computed}const Xe=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Xe&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Xe}),this.globalState._local={},nC()),this.currentLayoutName=Xe;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[te,he]of Object.entries(Q))this.globalState._local[te]===void 0&&(this.globalState._local[te]=JSON.parse(JSON.stringify(he)));Pe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[te,he]of Object.entries(l.initGlobal))this.globalState[te]===void 0&&(this.globalState[te]=JSON.parse(JSON.stringify(he)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[te,he]of Object.entries(l.initIsolated))j[te]===void 0&&(j[te]=JSON.parse(JSON.stringify(he)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}Pe._global={...this.globalState,layoutWarnings:l.warnings||[]};const fe=l.initActions||l.init_actions;if(fe&&fe.length>0){await this.executeInitActions(fe,Pe),B.log("initActions executed before render");const te=this.globalState;if(te._local){if(Object.keys(U).length>0){for(const[he,x]of Object.entries(U))te._local[he]!==void 0?te._local[he]=this.deepMerge(te._local[he],x):te._local[he]=x;B.log("localInit merged into _local after initActions:",Object.keys(U))}Pe._local=te._local,B.log("_local merged into dataContext:",te._local)}if(Pe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const he=this.calculateComputed(l.computed,Pe);Object.keys(he).length>0&&(Pe._computed=he,this.globalState._computed=he,B.log("Computed values recalculated after init_actions:",Object.keys(he)))}if(Object.keys(this.currentFetchedData).length>0){for(const[he,x]of Object.entries(this.currentFetchedData))Pe[he]=x;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 os({containerId:"app",layoutJson:l,dataContext:Pe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),T.length>0){if(a!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",a),Na.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",T.map(x=>x.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za);try{const x=T.map(async K=>{try{const de=(await S.fetchDataSourcesWithResults([K],e.params||{},g,this.globalState))[0];if(!de){B.log(`Data source ${K.id} skipped (no fetch result)`);return}if(a!==this.currentRouteChangeId){B.log(`Data source ${K.id} fetch cancelled (newer request exists)`);return}if(de.state==="success"&&de.data!==void 0){B.log(`Progressive data source loaded: ${K.id}`),this.currentFetchedData[K.id]=de.data;const se={};this.processInitOptions([K],{[K.id]:de.data},se);const me=he();if(me.bindingEngine){const ve=[K.id];K.initGlobal&&ve.push("_global"),K.initLocal&&ve.push("_local"),me.bindingEngine.invalidateCacheByKeys(ve)}const Ne={[K.id]:de.data};Object.keys(se).length>0&&(Ne._localInit=se,Object.assign(U,se)),K.initGlobal&&(Ne._global={...this.globalState}),te(Ne)}else if(de.state==="error"&&de.error){const se=de.error,me=se.response?.data?.message;D[K.id]={message:me||de.error.message,status:se.response?.status||se.status},B.log(`Progressive data source error: ${K.id}`,D[K.id]),te({[K.id]:null,_dataSourceErrors:{...D}})}}catch(re){B.error(`Failed to fetch data source: ${K.id}`,re)}});if(await Promise.all(x),a!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",a);return}B.log("All progressive data sources loaded")}finally{Na.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ye=E.filter(te=>te.type==="websocket");if(ye.length>0){B.log("Subscribing WebSocket data sources:",ye.map(K=>K.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za),x={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(x)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(E,(K,re)=>{B.log(`WebSocket data received for: ${K}`,re),this.currentFetchedData[K]=re;const de=E.find(ve=>ve.id===K),se=he();if(se.bindingEngine){const ve=[K];de?.initGlobal&&ve.push("_global"),de?.initLocal&&ve.push("_local"),se.bindingEngine.invalidateCacheByKeys(ve)}te({[K]:re});const Ne=E.find(ve=>ve.type==="websocket"&&(ve.target_source||ve.id)===K)?.onReceive;Array.isArray(Ne)&&Ne.length>0&&window.G7Core?.dispatch&&(async()=>{for(const He of Ne)try{const Ae=this.getActionDispatcher?.();Ae&&await Ae.dispatchAction(He,{navigate:this.getRouter?.()?(Et,Rt)=>this.getRouter().navigate(Et,Rt):void 0,setState:Et=>this.setGlobalState(Et),state:this.globalState,data:{...this.globalState,$args:[re],$event:re},_isDispatchFallbackContext:!0})}catch(Ae){B.error(`WebSocket onReceive action failed for ${K}:`,Ae)}})()},x),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(r){B.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,a,r,i){e.some(u=>u.refetchOnMount===!0&&u.initLocal)&&(r._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(u=>{const d=a[u.id];if(!d)return;const f=d.data??d;if(u.initLocal){if(typeof u.initLocal=="string"){let g=f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const b=this.evaluateDefaults(u.initLocalDefaults,a);g={...b,...f},B.log(`initLocalDefaults applied for ${u.initLocal}:`,Object.keys(b))}const m=this.globalState._local?.[u.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(r[u.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${u.id}.data -> _local.${u.initLocal}`)):(r[u.initLocal]=g,B.log(`initLocal: ${u.id}.data -> _local.${u.initLocal}`))}else if(typeof u.initLocal=="object"&&u.initLocal.key){const{key:g,path:m}=u.initLocal;let b=m?this.extractValueByPathOrExpression(f,m,u.id):f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const S=this.evaluateDefaults(u.initLocalDefaults,a);b={...S,...b},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(S))}const v=this.globalState._local?.[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(r[g]=this.deepMerge(v,b),B.log(`initLocal (merged): ${u.id}.data${m?"."+m:""} -> _local.${g}`)):(r[g]=b,B.log(`initLocal: ${u.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof u.initLocal=="object"){const g=u.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(u.initLocal);for(const{targetPath:b,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,u.id);if(b.includes(".")){const E=b.split(".")[0];r[E]===void 0&&this.globalState._local?.[E]!==void 0&&(r[E]=JSON.parse(JSON.stringify(this.globalState._local[E]))),this.setValueAtPath(r,b,S,g),B.log(`initLocal map (${g}): ${u.id} ${v} -> _local.${b}`)}else{const E=this.globalState._local?.[b];g==="replace"?(r[b]=S,B.log(`initLocal map (replace): ${u.id} ${v} -> _local.${b}`)):g==="shallow"?E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]={...E,...S},B.log(`initLocal map (shallow): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`)):E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]=this.deepMerge(E,S),B.log(`initLocal map (deep): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`))}}}}if(u.initGlobal)if(typeof u.initGlobal=="object"&&!Array.isArray(u.initGlobal)&&!("key"in u.initGlobal))for(const[m,b]of Object.entries(u.initGlobal)){if(typeof b!="string"){B.warn(`initGlobal map value must be string, got ${typeof b} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,b,u.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),B.log(`initGlobal map (merged): ${u.id} ${b} -> _global.${m}`)):(this.globalState[m]=v,B.log(`initGlobal map: ${u.id} ${b} -> _global.${m}`))}else{const m=Array.isArray(u.initGlobal)?u.initGlobal:[u.initGlobal];for(const b of m)if(typeof b=="string"){const v=this.globalState[b];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[b]=this.deepMerge(v,f),B.log(`initGlobal (merged): ${u.id}.data -> _global.${b}`)):(this.globalState[b]=f,B.log(`initGlobal: ${u.id}.data -> _global.${b}`))}else if(typeof b=="object"&&b.key){const{key:v,path:S}=b,E=S?this.extractValueByPathOrExpression(f,S,u.id):f,A=this.globalState[v];A!==void 0&&typeof A=="object"&&typeof E=="object"?(this.globalState[v]=this.deepMerge(A,E),B.log(`initGlobal (merged): ${u.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=E,B.log(`initGlobal: ${u.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&u.initIsolated){if(typeof u.initIsolated=="string"){const g=i[u.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[u.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${u.id}.data -> _isolated.${u.initIsolated}`)):(i[u.initIsolated]=f,B.log(`initIsolated: ${u.id}.data -> _isolated.${u.initIsolated}`))}else if(typeof u.initIsolated=="object"&&u.initIsolated.key){const{key:g,path:m}=u.initIsolated,b=m?this.extractValueByPathOrExpression(f,m,u.id):f,v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated (merged): ${u.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated: ${u.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof u.initIsolated=="object")for(const[g,m]of Object.entries(u.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const b=this.extractValueByPathOrExpression(f,m,u.id),v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated map (merged): ${u.id} ${m} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated map: ${u.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,a){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const u=l.slice(2,-2).trim();r[i]=this.evaluateExpression(u,a)}else r[i]=l;return r}evaluateExpression(e,a){try{const r=e.split("??").map(i=>i.trim());for(const i of r){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(a,i);if(l!=null)return l}return}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,a){const r=a.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(u=>{const d=u.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const b=g.match(/\[\d+\]/g);return b&&m.push(...b),m}return[u]}).filter(u=>u!=="");for(const u of l){if(i==null)return;if(u.startsWith("[")&&u.endsWith("]")){const d=parseInt(u.slice(1,-1),10);i=i[d]}else i=i[u]}return i}extractValueByPathOrExpression(e,a,r){const i=a.match(/^\{\{(.+)\}\}$/);if(i){const l=i[1].trim(),u=new wn,d={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const f=u.evaluateExpression(l,d);return B.log(`initLocal/initGlobal expression evaluated: ${a} -> `,f),f}catch(f){B.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,a,f);return}}return this.getNestedValue(e,a)}async loadLayoutScripts(e,a){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!Yi({if:i.if,conditions:i.conditions},a,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 u=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)});r.push(u)}r.length>0&&(await Promise.all(r),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,a){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return new Function("ctx",` with(ctx) { try { return Boolean(${r}); diff --git a/resources/js/core/routing/Router.ts b/resources/js/core/routing/Router.ts index ef2dd2f1..68e80c52 100644 --- a/resources/js/core/routing/Router.ts +++ b/resources/js/core/routing/Router.ts @@ -153,8 +153,10 @@ export class Router { * @returns 매칭된 라우트와 파라미터, 없으면 null */ match(pathname: string): RouteMatch | null { + const normalizedPath = this.normalizePathname(pathname); + for (const route of this.routes) { - const params = this.matchPattern(route.path, pathname); + const params = this.matchPattern(route.path, normalizedPath); if (params !== null) { return { @@ -167,6 +169,27 @@ export class Router { return null; } + /** + * URL 경로의 끝 슬래시를 정규화합니다. + * + * 브라우저가 `/admin/` 처럼 끝 슬래시가 붙은 경로로 진입해도 끝 슬래시 없는 + * 라우트 패턴(언어 prefix 형태 포함)에 매칭되도록, 루트(`/`)를 제외한 나머지 + * 경로의 끝 슬래시를 제거한다. 라우트 패턴은 끝 슬래시 없는 형태로만 정의되므로 + * (routes.json 규약), 미정규화 시 `/admin/` 이 어떤 라우트에도 매칭되지 않아 + * 404 로 떨어지고 — 미인증 진입 시 로그인 리다이렉트 대신 404 가 노출된다. + * + * @param pathname 원본 URL 경로 + * @returns 끝 슬래시가 정규화된 경로 (루트는 `/` 유지) + * @since engine-v1.54.1 + */ + private normalizePathname(pathname: string): string { + if (pathname.length > 1 && pathname.endsWith('/')) { + return pathname.replace(/\/+$/, '') || '/'; + } + + return pathname; + } + /** * 패턴과 경로를 매칭하고 파라미터를 추출합니다. * diff --git a/resources/js/core/routing/__tests__/Router.test.ts b/resources/js/core/routing/__tests__/Router.test.ts index 5e359df5..105f6367 100644 --- a/resources/js/core/routing/__tests__/Router.test.ts +++ b/resources/js/core/routing/__tests__/Router.test.ts @@ -192,6 +192,50 @@ describe('Router', () => { expect(result?.route.layout).toBe('user-list'); expect(result?.params).toEqual({}); }); + + // 브라우저가 끝 슬래시가 붙은 경로(`/admin/`)로 진입해도, 끝 슬래시 없는 + // 라우트 패턴(`/admin`)에 매칭되어야 한다. 미정규화 시 어떤 라우트에도 + // 매칭되지 않아 404 로 떨어지고, 미인증 진입 시 로그인 리다이렉트 대신 + // 404 가 노출되는 회귀가 발생한다. + it('끝 슬래시가 붙은 경로도 끝 슬래시 없는 라우트에 매칭해야 합니다', () => { + const result = router.match('/admin/'); + + expect(result).not.toBeNull(); + expect(result?.route.layout).toBe('dashboard'); + expect(result?.params).toEqual({}); + }); + + it('끝 슬래시가 붙은 하위 경로도 매칭해야 합니다', () => { + const result = router.match('/admin/users/'); + + expect(result).not.toBeNull(); + expect(result?.route.layout).toBe('user-list'); + expect(result?.params).toEqual({}); + }); + + it('끝 슬래시가 붙은 동적 파라미터 경로도 매칭하고 파라미터를 추출해야 합니다', () => { + const result = router.match('/admin/users/123/'); + + expect(result).not.toBeNull(); + expect(result?.route.layout).toBe('user-detail'); + expect(result?.params).toEqual({ id: '123' }); + }); + + it('연속된 끝 슬래시도 정규화해야 합니다', () => { + const result = router.match('/admin//'); + + expect(result).not.toBeNull(); + expect(result?.route.layout).toBe('dashboard'); + }); + + it('루트 경로(/)는 끝 슬래시를 제거하지 않아야 합니다', () => { + // 루트만 있는 라우트를 임시로 주입해 루트 정규화 안전성을 검증한다. + router.setRoutes([{ path: '/', layout: 'home' }]); + const result = router.match('/'); + + expect(result).not.toBeNull(); + expect(result?.route.layout).toBe('home'); + }); }); describe('matchPattern (간접 테스트)', () => { diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 23e8fdd5..c305034a 100644 --- a/resources/js/core/template-engine/CHANGELOG.md +++ b/resources/js/core/template-engine/CHANGELOG.md @@ -5,6 +5,14 @@ > > 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) +## [engine-v1.54.1] - 2026-07-23 + +### Fixed + +#### 끝 슬래시가 붙은 경로(`/admin/`)가 라우트에 매칭되지 않던 문제 + +- `routing/Router.ts` — `match()` 진입 시 경로의 끝 슬래시를 정규화(`normalizePathname`)한 뒤 패턴과 대조한다. 라우트 패턴은 끝 슬래시 없는 형태(`*/admin` 등)로만 정의되므로(routes.json 규약), 종전에는 브라우저가 `/admin/` 처럼 끝 슬래시가 붙은 경로로 진입하면 `matchPattern` 이 만드는 앵커 정규식(`^…/admin$`)에 걸리지 않아 어떤 라우트에도 매칭되지 않고 404 로 떨어졌다. 특히 미인증 상태로 `/admin/` 에 진입하면 대시보드 리다이렉트 → 로그인 화면 흐름 대신 404 가 노출됐다. 이제 루트(`/`)를 제외한 경로의 끝 슬래시(연속 슬래시 포함)를 제거해 정상 매칭한다. + ## [engine-v1.54.0] - 2026-07-20 ### Added diff --git a/tests/Playwright/specs/admin/admin-trailing-slash-route.spec.ts b/tests/Playwright/specs/admin/admin-trailing-slash-route.spec.ts new file mode 100644 index 00000000..c15b77a5 --- /dev/null +++ b/tests/Playwright/specs/admin/admin-trailing-slash-route.spec.ts @@ -0,0 +1,44 @@ +/** + * E2E: 끝 슬래시가 붙은 관리자 경로(`/admin/`) 라우팅 + * + * 회귀: 클라이언트 라우터가 라우트 패턴을 끝 슬래시 없는 형태(언어 prefix 형태 + * 포함)로만 정의하는데, `match()` 가 들어온 경로의 끝 슬래시를 정규화하지 않아 `/admin/` + * (끝 슬래시)가 어떤 라우트에도 매칭되지 않고 404 로 떨어졌다. 특히 로그인이 + * 풀린 상태로 `/admin/` 에 접근하면 대시보드 → 로그인 리다이렉트 흐름 대신 404 가 + * 노출됐다. 수정: `Router.match()` 진입 시 끝 슬래시를 정규화한다. + * + * 단위 테스트(Router.test.ts)가 매칭 로직을 잠그지만, PO 가 실제로 브라우저에서 + * 재현한 증상이므로(단위 green + 브라우저 깨짐 방지) 브라우저 레벨로도 잠근다. + * + * @scenario admin_trailing_slash_unauthenticated + admin_no_trailing_slash_unauthenticated + * @effects redirect_to_login_not_404 + */ +import { test, expect } from '../../fixtures/auth'; + +/** 404 에러 페이지 특유의 안내 문구 — 이 문구가 보이면 라우팅 실패다. */ +const NOT_FOUND_TEXT = '페이지를 찾을 수 없습니다'; + +test.describe('관리자 경로 끝 슬래시 정규화', () => { + // @scenario admin_trailing_slash_unauthenticated + // @effects redirect_to_login_not_404 + test('미인증 상태로 /admin/ (끝 슬래시) 접근 시 404 가 아니라 로그인으로 이동한다', async ({ page }) => { + // authenticatePage 미호출 — 로그인 풀린 상태 모사(localStorage 에 auth_token 없음). + await page.goto('/admin/'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + // 미인증 대시보드 진입 → 로그인 화면으로 리다이렉트. 끝 슬래시 미정규화 시 + // 여기서 404 페이지가 떴다. + await expect(page).toHaveURL(/\/admin\/login/, { timeout: 20_000 }); + await expect(page.getByText(NOT_FOUND_TEXT)).toHaveCount(0); + }); + + // @scenario admin_no_trailing_slash_unauthenticated + // @effects redirect_to_login_not_404 + test('미인증 상태로 /admin (끝 슬래시 없음) 접근도 동일하게 로그인으로 이동한다', async ({ page }) => { + await page.goto('/admin'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + await expect(page).toHaveURL(/\/admin\/login/, { timeout: 20_000 }); + await expect(page.getByText(NOT_FOUND_TEXT)).toHaveCount(0); + }); +});