diff --git a/CHANGELOG.md b/CHANGELOG.md index 07839494..a54c3b13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,7 +69,7 @@ - 초기 화면 파일을 새로 만드는 도중 짧은 시간 동안 기존 파일을 찾지 못할 수 있던 문제를 수정했습니다. 새 파일이 완성된 뒤에야 이전 파일을 정리합니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) - 캐시를 비운 뒤 정리 작업이 먼저 실행되면 아직 사용 중인 직전 초기 화면 파일이 삭제될 수 있던 문제를 수정했습니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) - 확장 프로그램의 스크립트·스타일 묶음을 저장하지 못하는 환경에서 해당 요청이 서버 오류(500)가 되던 문제를 수정했습니다. 저장에 실패해도 화면에는 정상적으로 전달됩니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) -- 배포 도중 확장 파일이 잠시 비면 내용이 빠진 빈 묶음이 정상 응답으로 전달되어, 한참 뒤 기능이 동작하지 않는 형태로만 드러나던 문제를 수정했습니다. 이제 그 상태를 오류로 알립니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) +- 배포 도중 확장 파일이 잠시 비면 내용이 빠진 빈 묶음이 정상 응답으로 전달되어, 한참 뒤 기능이 동작하지 않는 형태로만 드러나던 문제를 수정했습니다. 이제 그 상태를 오류로 알립니다. 스타일이 비어 있는 확장만 설치된 사이트처럼 내용이 원래 없는 경우는 오류로 보지 않습니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) - 일부 확장자(`.mjs`, `.webp`, `.otf`) 의 없는 파일을 요청하면 파일 대신 페이지 내용이 전달되어 화면이 깨지던 문제를 수정했습니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) - 초기 화면 파일을 새로 만들 때 파일 시스템이 일시적으로 이동을 거부하면 그 한 번으로 생성이 실패하던 문제를 수정했습니다. 이제 잠시 후 다시 시도하며, 사이트 동작에는 영향이 없지만 불필요한 실패 알림이 뜨던 상황이 사라집니다. (#122 @glitter-gim 님께서 건의해주셨습니다.) - 설치 마법사 2단계(설치 환경 확인)가 Windows 사용자 계정 이름에 한글이 포함되어 있으면 빈 응답을 받아 `Unexpected end of JSON input` 오류로 더 진행되지 않던 문제를 수정했습니다. 계정 이름을 영문으로 바꾸지 않아도 설치할 수 있습니다. (sir.kr 커뮤니티의 FreeMax 님께서 제보해주셨습니다.) diff --git a/app/Extension/AbstractModule.php b/app/Extension/AbstractModule.php index cf4f9033..acba99ab 100644 --- a/app/Extension/AbstractModule.php +++ b/app/Extension/AbstractModule.php @@ -1304,6 +1304,29 @@ abstract class AbstractModule implements CacheableExtensionInterface, ModuleInte return $result; } + /** + * 매니페스트가 **선언한** 프론트엔드 자산의 절대 경로를 반환합니다 (파일 존재 여부 무관). + * + * `getBuiltAssetAbsolutePaths()` 는 `file_exists()` 게이트라 소실된 산출물이 목록에서 + * 사라진다. 배포 중 `dist` 가 잠깐 비는 상태를 "선언은 있는데 파일이 없다" 로 세려면 + * 선언 축을 그대로 돌려주는 통로가 필요하다 — 이 메서드가 그 축이다. + * + * @return array kind('js'|'css') => 절대 경로 (선언된 kind 만) + */ + public function getDeclaredAssetAbsolutePaths(): array + { + $assets = $this->getAssets(); + $result = []; + + foreach (['js', 'css'] as $kind) { + if (! empty($assets[$kind]['output'])) { + $result[$kind] = $this->getModulePath().'/'.$assets[$kind]['output']; + } + } + + return $result; + } + /** * 모듈 스토리지 드라이버 인스턴스 반환 * diff --git a/app/Extension/AbstractPlugin.php b/app/Extension/AbstractPlugin.php index c6fc3b00..236cc313 100644 --- a/app/Extension/AbstractPlugin.php +++ b/app/Extension/AbstractPlugin.php @@ -1126,6 +1126,29 @@ abstract class AbstractPlugin implements CacheableExtensionInterface, PluginInte return $result; } + /** + * 매니페스트가 **선언한** 프론트엔드 자산의 절대 경로를 반환합니다 (파일 존재 여부 무관). + * + * `getBuiltAssetAbsolutePaths()` 는 `file_exists()` 게이트라 소실된 산출물이 목록에서 + * 사라진다. 배포 중 `dist` 가 잠깐 비는 상태를 "선언은 있는데 파일이 없다" 로 세려면 + * 선언 축을 그대로 돌려주는 통로가 필요하다 — 이 메서드가 그 축이다. + * + * @return array kind('js'|'css') => 절대 경로 (선언된 kind 만) + */ + public function getDeclaredAssetAbsolutePaths(): array + { + $assets = $this->getAssets(); + $result = []; + + foreach (['js', 'css'] as $kind) { + if (! empty($assets[$kind]['output'])) { + $result[$kind] = $this->getPluginPath().'/'.$assets[$kind]['output']; + } + } + + return $result; + } + /** * 플러그인이 설정 페이지를 가지고 있는지 확인합니다. * diff --git a/app/Http/Controllers/Api/Public/PublicModuleController.php b/app/Http/Controllers/Api/Public/PublicModuleController.php index 35680cfb..041fa85c 100644 --- a/app/Http/Controllers/Api/Public/PublicModuleController.php +++ b/app/Http/Controllers/Api/Public/PublicModuleController.php @@ -34,7 +34,7 @@ class PublicModuleController extends PublicBaseController * * 병합 파일을 fileResponse 로 서빙한다(ETag/304/환경별 Cache-Control 재사용). * 디스크 캐시가 실패하면 메모리 병합 결과로 200 을 낸다(캐시는 최적화일 뿐이다). - * 에셋을 선언한 활성 확장이 0개면 빈 200, 선언은 있는데 결과가 비면 503 — + * 선언한 산출물이 소실·판독 불가면 503, 존재하되 비었으면(또는 선언 0) 빈 200 — * 판정은 ServesExtensionBundles::bundleResponse() 단일 지점. * * @return BinaryFileResponse|Response 병합 JS 파일 응답 또는 빈 응답 diff --git a/app/Http/Controllers/Api/Public/PublicPluginController.php b/app/Http/Controllers/Api/Public/PublicPluginController.php index f171003f..d11c05a9 100644 --- a/app/Http/Controllers/Api/Public/PublicPluginController.php +++ b/app/Http/Controllers/Api/Public/PublicPluginController.php @@ -34,7 +34,7 @@ class PublicPluginController extends PublicBaseController * * 병합 파일을 fileResponse 로 서빙한다(ETag/304/환경별 Cache-Control 재사용). * 디스크 캐시가 실패하면 메모리 병합 결과로 200 을 낸다(캐시는 최적화일 뿐이다). - * 에셋을 선언한 활성 확장이 0개면 빈 200, 선언은 있는데 결과가 비면 503 — + * 선언한 산출물이 소실·판독 불가면 503, 존재하되 비었으면(또는 선언 0) 빈 200 — * 판정은 ServesExtensionBundles::bundleResponse() 단일 지점. * * @return BinaryFileResponse|Response 병합 JS 파일 응답 또는 빈 응답 diff --git a/app/Http/Controllers/Concerns/ServesExtensionBundles.php b/app/Http/Controllers/Concerns/ServesExtensionBundles.php index 3ea0bcfa..d7cf5f55 100644 --- a/app/Http/Controllers/Concerns/ServesExtensionBundles.php +++ b/app/Http/Controllers/Concerns/ServesExtensionBundles.php @@ -20,10 +20,13 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse; * 2. 병합 결과는 있는데 디스크 캐시가 실패 → **메모리 결과를 그대로 200** 으로 서빙. * 디스크 캐시는 최적화이므로 쓰기 실패가 공개 엔드포인트의 500 이 되면 안 된다. * 3. 병합 결과가 비었음 → - * - 에셋을 선언한 활성 확장이 **0개**면 정상 → 빈 200 - * - 선언은 있는데 결과가 0 이면 장애(배포 중 `dist` 가 잠깐 빔, 경로 어긋남) → - * **503**. 빈 200 으로 내보내면 프론트는 404 도 오류도 받지 못한 채 한참 뒤 - * "Unknown action handler" 로 죽어, 원인이 번들이라는 사실이 드러나지 않는다. + * - 선언한 산출물이 **소실·판독 불가**면 장애(배포 중 `dist` 가 잠깐 빔, 경로 + * 어긋남) → **503**. 빈 200 으로 내보내면 프론트는 404 도 오류도 받지 못한 채 + * 한참 뒤 "Unknown action handler" 로 죽어, 원인이 번들이라는 사실이 드러나지 않는다. + * - 산출물이 **존재하되 비어 있으면** 정상 → 빈 200. 스타일 소스가 자리표시 주석뿐이라 + * 0바이트 CSS 를 내보내는 확장은 정당한 상태다. 선언 축만으로 판정하면 그런 확장만 + * 설치된 기본 구성이 통째로 503 이 되어 사용자 화면마다 실패 안내가 뜬다. + * - 선언이 **0개**여도 정상 → 빈 200 */ trait ServesExtensionBundles { @@ -61,15 +64,17 @@ trait ServesExtensionBundles ->header('Cache-Control', 'no-cache, private'); } - $declared = $bundleService->countAssetDeclaringExtensions($type, $kind); + $missing = $bundleService->findMissingDeclaredAssets($type, $kind); - if ($declared > 0) { - // (3) 장애 — 선언은 있는데 결과가 0 - Log::error('확장 번들 병합 결과가 비었습니다 — 에셋을 선언한 활성 확장이 있습니다', [ + if ($missing !== []) { + // (3) 장애 — 선언한 산출물이 소실·판독 불가 (배포 중 dist 가 잠깐 빔, 경로 어긋남). + // 어느 파일이 없는지를 함께 남긴다 — 선언 수만으로는 운영자가 조치 대상을 짚을 수 없다. + Log::error('확장 번들 병합 결과가 비었습니다 — 선언된 산출물이 없거나 읽을 수 없습니다', [ 'type' => $type, 'kind' => $kind, 'version' => $version, - 'declared_extensions' => $declared, + 'declared_extensions' => $bundleService->countAssetDeclaringExtensions($type, $kind), + 'missing' => $missing, ]); return response('', 503) @@ -77,7 +82,8 @@ trait ServesExtensionBundles ->header('Cache-Control', 'no-cache, private'); } - // (3) 정상 — 선언이 0개면 빈 번들이 맞다 + // (3) 정상 — 선언이 0 이거나, 선언된 산출물이 전부 존재하되 비어 있다 + // (스타일이 비어 있는 확장). 빈 번들이 맞다. return response('', 200)->header('Content-Type', $mimeType); } } diff --git a/app/Seo/SeoRenderer.php b/app/Seo/SeoRenderer.php index 53929e9f..acb8089a 100644 --- a/app/Seo/SeoRenderer.php +++ b/app/Seo/SeoRenderer.php @@ -739,18 +739,36 @@ class SeoRenderer implements SeoRendererInterface return $resolved; } + /** + * 템플릿 디렉토리의 절대 경로를 반환합니다. + * + * 테스트가 임시 디렉토리를 템플릿 루트로 쓸 수 있도록 분리한 seam 이다. + * + * @param string $identifier 템플릿 식별자 + * @return string 템플릿 루트 절대 경로 + */ + protected function templateRootPath(string $identifier): string + { + return base_path("templates/{$identifier}"); + } + /** * 템플릿의 CSS 에셋 URL 목록을 반환합니다. * * template.json의 assets.css 경로를 서빙 URL로 변환합니다. * 예: "dist/css/components.css" → "/api/templates/assets/{id}/css/components.css" * + * `assets.css` 는 **선언**일 뿐이라 산출물이 없을 수 있다. 없는 경로를 그대로 링크하면 + * 봇 화면에서만 404 가 나고 일반 화면에는 흔적이 없다 — 서버 로그에도 남지 않아 + * 운영자가 알 방법이 없다. 그래서 파일이 실재하는 경로만 싣는다(0바이트는 정상). + * * @param string $templateIdentifier 템플릿 식별자 * @return array CSS URL 배열 */ private function getTemplateCssUrls(string $templateIdentifier): array { - $templateJsonPath = base_path("templates/{$templateIdentifier}/template.json"); + $templateRoot = $this->templateRootPath($templateIdentifier); + $templateJsonPath = $templateRoot.'/template.json'; if (! file_exists($templateJsonPath)) { return []; } @@ -767,6 +785,12 @@ class SeoRenderer implements SeoRendererInterface $urls = []; foreach ($cssPaths as $cssPath) { + // 선언한 파일이 실재할 때만 링크한다 — 없는 경로의 는 봇 화면에서만 + // 404 가 되고 어디에도 흔적을 남기지 않는다 + if (! is_file($templateRoot.'/'.$cssPath)) { + continue; + } + // dist/ 접두사 제거 (서빙 경로에서는 dist가 자동 추가됨) $servePath = preg_replace('#^dist/#', '', $cssPath); diff --git a/app/Services/ExtensionBundleService.php b/app/Services/ExtensionBundleService.php index 6077c2aa..ec7b51ce 100644 --- a/app/Services/ExtensionBundleService.php +++ b/app/Services/ExtensionBundleService.php @@ -26,6 +26,8 @@ use Illuminate\Support\Facades\Log; * 경로는 절대경로 게터(`getBuiltAssetAbsolutePaths()`)를 재사용한다 — * `ModuleService::getAssetFilePath()` 의 `base_path("modules/{id}/...")` * 하드코딩을 복제하지 않아야 `_bundled` 확장에서도 정확히 읽는다(제약 4). + * 소실 판정만 선언 축 게터(`getDeclaredAssetAbsolutePaths()`)를 쓴다 — 그 게터는 + * `file_exists()` 게이트를 타지 않아 "선언은 있는데 파일이 없다" 를 셀 수 있다. * * @see TemplateComposer */ @@ -315,10 +317,13 @@ class ExtensionBundleService /** * 해당 타입에서 프론트엔드 에셋을 **선언한** 활성 확장 수를 반환합니다. * - * "선언이 0 이라 빈 번들" (정상)과 "선언은 있는데 병합 결과가 0" (장애 — 배포 중 - * `dist` 가 잠깐 비었거나 경로가 어긋났다)을 구분하는 유일한 근거다. 구분하지 않으면 - * 후자가 빈 200 으로 나가고, 프론트는 404 도 오류도 받지 못한 채 한참 뒤 - * "Unknown action handler" 로 죽는다. + * 이 값은 **선언 축**이다 — 503 의 판정은 소실 축(`findMissingDeclaredAssets()`)이 + * 한다. 선언 축만으로 "선언 > 0 && 병합 결과 0 = 장애" 로 등치하면, 산출물이 존재하되 + * 비어 있는 정당한 상태(스타일이 비어 있는 확장)까지 배포 장애로 잡혀 그 확장만 + * 설치된 기본 구성이 통째로 503 이 된다. + * + * 선언 축은 로그 컨텍스트(운영자가 보는 "선언한 확장이 몇 개인가")와 화면 진단이 + * 근거로 삼는다. * * 판정은 **kind 별**이다 — js 만 선언한 확장이 있는 상태에서 css 번들이 비는 것은 * 정상이므로, 그 경우까지 장애로 보면 정상 구성이 503 이 된다. @@ -365,6 +370,57 @@ class ExtensionBundleService } } + /** + * 선언된 산출물 중 **소실·판독 불가**한 것의 절대 경로 목록을 반환합니다. + * + * 503 의 근거는 선언이 아니라 이 소실 축이다. 선언만으로 판정하면 "선언됨 + 산출물이 존재하지만 + * 0바이트"(스타일이 비어 있는 확장의 정당한 상태) 와 "선언됨 + 산출물 소실"(배포 중 dist 가 잠깐 빔) + * 이 구분되지 않아 정상 구성이 503 이 된다 — 번들 확장만 설치한 기본 구성 전부가 그랬다. + * + * 모집단은 countAssetDeclaringExtensions() 와 같다. 경로는 확장의 선언 축 게터로만 얻는다 — + * getBuiltAssetAbsolutePaths() 는 file_exists() 게이트라 부재를 셀 수 없고, base_path("modules"…) + * 직접 조립은 _bundled 확장에서 어긋난다. + * + * @param string $type 'module' | 'plugin' + * @param string $kind 'js' | 'css' + * @return list 소실·판독 불가 산출물의 절대 경로 (없으면 빈 배열) + */ + public function findMissingDeclaredAssets(string $type, string $kind): array + { + try { + $extensions = $type === 'plugin' + ? $this->pluginManager->getActivePlugins() + : $this->moduleManager->getActiveModules(); + + $missing = []; + + foreach ($extensions as $extension) { + // global 전략만 번들 대상 — 병합 대상 모집단과 동일한 필터를 쓴다 + if (($extension->getAssetLoadingConfig()['strategy'] ?? 'global') !== 'global') { + continue; + } + + $path = $extension->getDeclaredAssetAbsolutePaths()[$kind] ?? null; + + if ($path !== null && (! is_file($path) || ! is_readable($path))) { + $missing[] = $path; + } + } + + return $missing; + } catch (\Throwable $e) { + // 판정 자체가 실패하면 장애로 단정하지 않는다(선언 축 카운트와 같은 fail-open). 흔적은 error 로 — + // 출하 기본 로그 수준이 error 라 warning 은 기록되지 않는다. + Log::error('확장 에셋 소실 판정 실패', [ + 'type' => $type, + 'kind' => $kind, + 'error' => $e->getMessage(), + ]); + + return []; + } + } + /** * 현재 version 외의 오래된 번들 파일을 삭제하고 삭제 건수를 반환합니다. * diff --git a/docs/backend/api/modules.md b/docs/backend/api/modules.md index 3f6261dc..b332cbb7 100644 --- a/docs/backend/api/modules.md +++ b/docs/backend/api/modules.md @@ -2098,11 +2098,11 @@ Cache-Control: public, max-age=31536000 **에러 응답** -_에러 응답 없음 — 공개 엔드포인트이며, 병합 대상이 없어도 빈 본문의 200(text/css)을 반환합니다._ +_선언한 산출물이 소실·판독 불가일 때 **503**(빈 본문, `Cache-Control: no-cache, private`) — 배포 중 `dist` 가 잠깐 비었거나 경로가 어긋난 상태입니다. 에셋을 선언한 활성 확장이 없거나, 선언한 산출물이 전부 존재하되 비어 있으면(스타일 규칙이 아직 없는 확장) 정상 빈 200 입니다._ -**설명** 활성 모듈들의 프론트엔드 CSS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 활성 global 모듈 에셋이 없으면 빈 200(text/css) 응답을 반환하고, 있으면 병합 파일을 ETag·환경별 Cache-Control 과 함께 서빙합니다. 페이지가 모듈 스타일을 요청 1건으로 로드하도록 합니다. +**설명** 활성 모듈들의 프론트엔드 CSS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 병합 결과가 있으면 ETag·환경별 Cache-Control 과 함께 서빙하고, 비어 있으면 그 이유에 따라 갈립니다 — 선언이 0 이거나 선언한 산출물이 전부 존재하되 비어 있으면 빈 200(text/css), 선언한 산출물이 소실·판독 불가면 503 입니다. 0바이트 CSS 는 스타일 규칙이 아직 없는 확장의 정당한 상태이므로 장애로 보지 않습니다. 페이지가 모듈 스타일을 요청 1건으로 로드하도록 합니다. ### GET /api/modules/bundle.js @@ -2140,11 +2140,11 @@ Cache-Control: public, max-age=31536000 **에러 응답** -_에러 응답 없음 — 공개 엔드포인트이며, 병합 대상이 없어도 빈 본문의 200(text/javascript)을 반환합니다._ +_선언한 산출물이 소실·판독 불가일 때 **503**(빈 본문, `Cache-Control: no-cache, private`) — 배포 중 `dist` 가 잠깐 비었거나 경로가 어긋난 상태입니다. 에셋을 선언한 활성 확장이 없거나, 선언한 산출물이 전부 존재하되 비어 있으면(스타일 규칙이 아직 없는 확장) 정상 빈 200 입니다._ -**설명** 활성 모듈들의 프론트엔드 IIFE JS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 활성 global 모듈 에셋이 없으면 빈 200(text/javascript) 응답을 반환하고(프론트는 빈 스크립트 로드로 무해), 있으면 병합 파일을 ETag·환경별 Cache-Control 과 함께 서빙합니다. 프론트는 `G7Config.bundleUrls` 를 읽어 이 번들을 로드합니다. +**설명** 활성 모듈들의 프론트엔드 IIFE JS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 병합 결과가 있으면 ETag·환경별 Cache-Control 과 함께 서빙하고, 비어 있으면 그 이유에 따라 갈립니다 — 선언이 0 이거나 선언한 산출물이 전부 존재하되 비어 있으면 빈 200(text/javascript, 프론트는 빈 스크립트 로드로 무해), 선언한 산출물이 소실·판독 불가면 503 입니다. 프론트는 `G7Config.bundleUrls` 를 읽어 이 번들을 로드합니다. ### GET /api/modules/bundle/css diff --git a/docs/backend/api/plugins.md b/docs/backend/api/plugins.md index 3b410d8b..19b07bfe 100644 --- a/docs/backend/api/plugins.md +++ b/docs/backend/api/plugins.md @@ -2382,11 +2382,11 @@ Cache-Control: public, max-age=31536000 **에러 응답** -_에러 응답 없음 — 공개 조회이며 요청 파라미터가 없고, 활성 에셋이 하나도 없는 경우에도 빈 200 을 반환합니다._ +_선언한 산출물이 소실·판독 불가일 때 **503**(빈 본문, `Cache-Control: no-cache, private`) — 배포 중 `dist` 가 잠깐 비었거나 경로가 어긋난 상태입니다. 에셋을 선언한 활성 확장이 없거나, 선언한 산출물이 전부 존재하되 비어 있으면(스타일 규칙이 아직 없는 확장) 정상 빈 200 입니다._ -**설명** 활성 플러그인들의 프론트엔드 CSS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 활성 global 플러그인 에셋이 없으면 빈 200(text/css) 응답을 반환하고, 있으면 병합 파일을 ETag·환경별 Cache-Control 과 함께 서빙합니다. 페이지가 플러그인 스타일을 요청 1건으로 로드하도록 합니다. +**설명** 활성 플러그인들의 프론트엔드 CSS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 판정은 모듈 번들과 같은 단일 지점을 공유합니다 — 선언이 0 이거나 선언한 산출물이 전부 존재하되 비어 있으면 빈 200(text/css), 선언한 산출물이 소실·판독 불가면 503, 병합 결과가 있으면 ETag·환경별 Cache-Control 과 함께 서빙합니다. 페이지가 플러그인 스타일을 요청 1건으로 로드하도록 합니다. ### GET /api/plugins/bundle.js @@ -2433,11 +2433,11 @@ Cache-Control: public, max-age=31536000 **에러 응답** -_에러 응답 없음 — 공개 조회이며 요청 파라미터가 없고, 활성 에셋이 하나도 없는 경우에도 빈 200 을 반환합니다._ +_선언한 산출물이 소실·판독 불가일 때 **503**(빈 본문, `Cache-Control: no-cache, private`) — 배포 중 `dist` 가 잠깐 비었거나 경로가 어긋난 상태입니다. 에셋을 선언한 활성 확장이 없거나, 선언한 산출물이 전부 존재하되 비어 있으면(스타일 규칙이 아직 없는 확장) 정상 빈 200 입니다._ -**설명** 활성 플러그인들의 프론트엔드 IIFE JS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 활성 global 플러그인 에셋이 없으면 빈 200(text/javascript) 응답을 반환하고, 있으면 병합 파일을 ETag·환경별 Cache-Control 과 함께 서빙합니다. 프론트는 `G7Config.bundleUrls` 를 읽어 이 번들을 로드합니다. +**설명** 활성 플러그인들의 프론트엔드 IIFE JS 를 서버에서 하나로 병합한 번들을 서빙하는 공개 엔드포인트입니다. 인증이 필요하지 않습니다. 판정은 모듈 번들과 같은 단일 지점을 공유합니다 — 선언이 0 이거나 선언한 산출물이 전부 존재하되 비어 있으면 빈 200(text/javascript), 선언한 산출물이 소실·판독 불가면 503, 병합 결과가 있으면 ETag·환경별 Cache-Control 과 함께 서빙합니다. 프론트는 `G7Config.bundleUrls` 를 읽어 이 번들을 로드합니다. ### GET /api/plugins/bundle/css diff --git a/docs/backend/seo-system.md b/docs/backend/seo-system.md index bfde63c5..7011dd3a 100644 --- a/docs/backend/seo-system.md +++ b/docs/backend/seo-system.md @@ -823,7 +823,7 @@ SEO 엔진은 컴포넌트 지식을 갖지 않습니다. 모든 컴포넌트→ | `text_props` | string[] | 텍스트 추출 우선순위 (예: `["text", "label", "value", "title"]`) | | `attr_map` | object | props→HTML 속성 매핑 (예: `{"className": "class", "htmlFor": "for"}`) | | `allowed_attrs` | string[] | 허용 HTML 속성 목록 (목록에 없는 속성은 출력 안됨) | -| `stylesheets` | string[] | 외부 CSS URL (예: Font Awesome CDN) | +| `stylesheets` | string[] | 추가 CSS URL | | `self_closing` | string[] | 셀프 클로징 태그 목록 (예: `["img", "input", "hr", "br"]`) | | `component_map` | object | 컴포넌트명 → HTML 태그 매핑 | | `render_modes` | object | 렌더 모드 정의 | @@ -1490,6 +1490,11 @@ SeoRenderer.render() └─ View::make('seo', [..., 'stylesheets' => config.stylesheets]) ``` +봇 화면의 `` 에는 활성 사용자 템플릿의 `template.json` `assets.css` 도 실린다. 그 선언은 +**파일이 실재할 때만** 링크한다 — 선언은 있는데 산출물이 없는 경로를 그대로 실으면 봇 화면에서만 +404 가 나고 일반 화면에는 흔적이 없다. 서버 로그에도 남지 않으므로 운영자가 알 방법이 없다. +내용이 비어 있는 파일(0바이트)은 실재하므로 링크한다. + ### navigate 핸들러 링크 자동 생성 SEO 렌더링 시 `navigate`/`openWindow` 핸들러가 정의된 컴포넌트에 `` 하이퍼링크를 자동 생성합니다. 검색 엔진 봇이 내부 페이지를 발견할 수 있도록 링크 구조를 자동 형성합니다. diff --git a/docs/extension/module-assets.md b/docs/extension/module-assets.md index e551a5d7..865d5b74 100644 --- a/docs/extension/module-assets.md +++ b/docs/extension/module-assets.md @@ -185,6 +185,13 @@ manifest 는 배포물), 코어가 활성 확장 전체의 선언을 모아 allo | `loading.strategy` | 로딩 전략 (global, layout, lazy) | | `loading.priority` | 로드 우선순위 (낮을수록 먼저) | +`assets.js` · `assets.css` 는 **객체**이며 `output` 을 가져야 합니다. 목록형(`"js": ["dist/js/module.iife.js"]`)은 +어느 소비자도 읽지 않아 **그 자산이 영영 로드되지 않는데, 오류도 경고도 남지 않습니다.** + +선언한 `output` 이 가리키는 파일은 디스크에 실재해야 합니다. 내용이 비어 있는 것(0바이트)은 +정상입니다 — 스타일 규칙이 아직 없는 확장이 CSS 를 선언하는 것은 어긋남이 아닙니다. 정적 검사가 +번들 확장 전수를 대상으로 두 조건(객체 형식 · 산출물 실재)을 확인합니다. + --- ## 모듈 프론트엔드 구조 @@ -508,11 +515,11 @@ GET /api/plugins/bundle.css?v={version} | `\n;\n` 구분자 | IIFE 사이는 `\n;\n`(JS)/`\n`(CSS). 미사용 시 ASI 붕괴 → 전체 파싱 에러 | `extension-bundle-concat-separator` | | 소스맵 | prod strip, dev 는 개별 에셋 서빙 절대 URL 로 rewrite | - | | same-origin | 번들 URL 은 `/api/...` 만 (CDN 금지 — gdpr preblocker 자기차단 방지) | `extension-bundle-url-same-origin` | -| 절대경로 게터 | `getBuiltAssetAbsolutePaths()` 사용. `base_path("modules"\|"plugins")` 직접 조립 금지 | `extension-bundle-asset-path-getter` | +| 절대경로 게터 | `getBuiltAssetAbsolutePaths()` 사용. `base_path("modules"\|"plugins")` 직접 조립 금지. 소실 판정만 선언 축 게터 `getDeclaredAssetAbsolutePaths()` | `extension-bundle-asset-path-getter` | | 확장별 try/catch | 파일 읽기 실패 시 해당 확장만 skip, 나머지 병합 지속 | (메모리+회귀테스트) | | CSS url() | 상대 `url()`·`@import` 참조는 그 확장의 절대 자산 URL 로 **치환**해 병합. 병합본의 주소는 어느 확장의 dist 디렉토리도 아니라 상대 해석이 반드시 어긋난다 | (계약 테스트) | | 디스크 캐시 fail-soft | 캐시 쓰기 실패는 **500 이 아니다** — 메모리 병합 결과를 그대로 200 으로 서빙 | (계약 테스트) | -| 빈 번들 판정 | 선언 0개면 빈 200, 선언은 있는데 결과가 0이면 **503** | (계약 테스트) | +| 빈 번들 판정 | 선언한 산출물이 소실·판독 불가면 **503**, 존재하되 비었으면 빈 200 (선언 0 도 빈 200) | (계약 테스트) | ### 병합 CSS 의 상대 참조 @@ -531,11 +538,19 @@ GET /api/plugins/bundle.css?v={version} | 상태 | 판정 | 응답 | |---|---|---| | 에셋을 선언한 활성 확장이 0개 | 정상 | 빈 200 | -| 선언은 있는데 병합 결과가 0 | 장애 (배포 중 `dist` 가 잠깐 빔, 경로 어긋남) | **503** + `Log::error` | +| 선언은 있고 그 산출물이 **전부 존재**하되 비어 있음 | 정상 (스타일이 비어 있는 확장) | 빈 200 | +| 선언한 산출물이 **소실·판독 불가** | 장애 (배포 중 `dist` 가 잠깐 빔, 경로 어긋남) | **503** + `Log::error`(소실 경로 목록) | -구분하지 않으면 후자가 빈 200 으로 나가고, 프론트는 404 도 오류도 받지 못한 채 한참 뒤 "Unknown action handler" 로 죽는다 — 그 시점에는 원인이 번들이라는 사실이 화면에도 로그에도 남아 있지 않다. 판정은 **kind 별**이다(js 만 선언한 확장이 있는 상태에서 css 번들이 비는 것은 정상). +장애를 정상으로 흘리면 프론트는 404 도 오류도 받지 못한 채 한참 뒤 "Unknown action handler" 로 죽는다 — 그 시점에는 원인이 번들이라는 사실이 화면에도 로그에도 남아 있지 않다. 반대로 정상을 장애로 잡으면 스타일 소스가 자리표시 주석뿐인 확장만 설치된 기본 구성이 통째로 503 이 되어 **사용자 화면마다 실패 안내가 뜬다.** 판정은 **kind 별**이다(js 만 선언한 확장이 있는 상태에서 css 번들이 비는 것은 정상). -"선언" 의 근거는 manifest 의 `assets.{kind}.output` 이며 **산출물 파일의 존재를 보지 않는다.** 병합 경로가 쓰는 게터들(`getOrderedGlobalAssetPaths()` · `hasAssets()` · `getBuiltAssetPaths()`)은 모두 `file_exists()` 로 거르므로, 그 경로로 선언 수를 세면 "`dist` 가 잠깐 빔" 이 곧 "선언 0" 이 되어 **막으려던 상태가 정상(빈 200)으로 판정된다.** 선언과 산출은 다른 축이고, 이 판정이 재는 것은 선언 축이다. +두 축이 다르다는 점이 핵심이다. + +- **선언 축**의 근거는 manifest 의 `assets.{kind}.output` 이며 **산출물 파일의 존재를 보지 않는다.** 병합 경로가 쓰는 게터들(`getOrderedGlobalAssetPaths()` · `hasAssets()` · `getBuiltAssetPaths()`)은 모두 `file_exists()` 로 거르므로, 그 경로로 선언 수를 세면 "`dist` 가 잠깐 빔" 이 곧 "선언 0" 이 된다. 이 축은 로그 컨텍스트와 진단이 근거로 삼는다. +- **소실 축**은 선언된 산출물 중 실제로 없거나 읽을 수 없는 것을 센다. 경로는 `getDeclaredAssetAbsolutePaths()` 로 얻는다 — 존재 게이트가 없어야 부재를 셀 수 있다. **503 의 판정은 이 축이 한다.** + +0바이트 산출물은 정당한 상태다. 스타일 규칙이 아직 없는 확장이 CSS 를 선언하는 것은 어긋남이 아니며, 그 상태를 배포 장애로 등치하면 정상 사이트가 서비스 불능으로 보고된다. + +빈 번들은 정적 게시 대상이 아니다(게시할 사본이 없다). 그 결과 `AssetUrl::extensionBundle()` 이 정적 URL 대신 API URL 을 방출하므로 브라우저에는 정적 404 폴백이 생기지 않고, 그 API 가 위 표대로 빈 200 을 낸다. 두 판정은 모듈·플러그인 컨트롤러가 **공유하는 단일 지점**(`ServesExtensionBundles::bundleResponse()`)에 둔다. 각자 구현하면 한쪽만 고쳐진 채 다른 쪽이 옛 동작으로 남는다. diff --git a/docs/frontend/g7core-api.md b/docs/frontend/g7core-api.md index 788ba459..7baf5712 100644 --- a/docs/frontend/g7core-api.md +++ b/docs/frontend/g7core-api.md @@ -885,7 +885,7 @@ loader.config({ | 필드 | 타입 | 설명 | |------|------|------| | `id` | `string` | 중복 누적을 막는 식별자 (필수) | -| `label` | `string` | 짧은 항목명 — 여러 건 합산 표시에 쓰인다 | +| `label` | `string` | 짧은 항목명 — 여러 건 합산 표시에 쓰인다. **사용자 어휘**여야 한다: 내부 구분 키·식별자를 그대로 넘기면 배너에 「module을(를) 불러오지 못했습니다」처럼 해석 불가한 문구가 노출된다 | | `message` | `string?` | 사용자에게 보일 안내 문장. 생략하면 `label` 기반 기본 문구 | | `retry` | `() => Promise \| void` | 생략하면 [다시 시도] 버튼을 렌더하지 않는다 | diff --git a/lang-packs/_bundled/g7-core-ja/CHANGELOG.md b/lang-packs/_bundled/g7-core-ja/CHANGELOG.md index 19948b10..da8eae4e 100644 --- a/lang-packs/_bundled/g7-core-ja/CHANGELOG.md +++ b/lang-packs/_bundled/g7-core-ja/CHANGELOG.md @@ -16,6 +16,7 @@ - 초기 화면 파일 생성이 거듭 실패할 때 관리자 대시보드에 표시되는 안내의 일본어 번역을 추가했습니다 — 폴더 권한·디스크 공간·캐시 저장소 중 어느 쪽이 원인인지에 따라 다른 안내가 일본어 로케일에서 표시됩니다. - 리버스 프록시 뒤에서 신뢰 프록시가 지정되지 않았을 때 관리자 대시보드에 표시되는 안내의 일본어 번역을 추가했습니다. - 사이트 설정 문제로 화면 구성 파일이 차단됐을 때 표시되는 안내 문구의 일본어 번역을 추가했습니다 — 방문자 쪽 문제가 아니라는 안내가 일본어 로케일에서 표시됩니다. +- 확장 프로그램의 스타일 묶음을 끝내 불러오지 못했을 때 안내에 표시되는 항목명의 일본어 번역을 추가했습니다 — 종전에는 그 자리에 내부 구분 이름이 그대로 보였고, 이제 「모듈 스타일」·「플러그인 스타일」에 해당하는 일본어가 표시됩니다. ## [1.0.8] - 2026-08-24 diff --git a/lang-packs/_bundled/g7-core-ja/frontend/partial/assets.json b/lang-packs/_bundled/g7-core-ja/frontend/partial/assets.json index 830d03b2..97f2fb05 100644 --- a/lang-packs/_bundled/g7-core-ja/frontend/partial/assets.json +++ b/lang-packs/_bundled/g7-core-ja/frontend/partial/assets.json @@ -4,5 +4,7 @@ "retry": "再試行", "retrying": "再試行中...", "close": "閉じる", - "retry_failed": "再試行しましたが失敗しました。しばらく後に再度お試しください。" + "retry_failed": "再試行しましたが失敗しました。しばらく後に再度お試しください。", + "module_styles": "モジュールスタイル", + "plugin_styles": "プラグインスタイル" } diff --git a/lang/partial/en/assets.json b/lang/partial/en/assets.json index 03bbae21..1ba9e90b 100644 --- a/lang/partial/en/assets.json +++ b/lang/partial/en/assets.json @@ -1,6 +1,8 @@ { "load_failed": "Could not load {label}.", "load_failed_multiple": "Could not load {count} items.", + "module_styles": "module styles", + "plugin_styles": "plugin styles", "retry": "Retry", "retrying": "Retrying...", "close": "Close", diff --git a/lang/partial/ko/assets.json b/lang/partial/ko/assets.json index a4edbfb6..fe0d1a1a 100644 --- a/lang/partial/ko/assets.json +++ b/lang/partial/ko/assets.json @@ -1,6 +1,8 @@ { "load_failed": "{label}을(를) 불러오지 못했습니다.", "load_failed_multiple": "{count}개 항목을 불러오지 못했습니다.", + "module_styles": "모듈 스타일", + "plugin_styles": "플러그인 스타일", "retry": "다시 시도", "retrying": "다시 시도 중...", "close": "닫기", diff --git a/modules/_bundled/gnuboard7-hello_module/CHANGELOG.md b/modules/_bundled/gnuboard7-hello_module/CHANGELOG.md index 0d6205cc..d54c5570 100644 --- a/modules/_bundled/gnuboard7-hello_module/CHANGELOG.md +++ b/modules/_bundled/gnuboard7-hello_module/CHANGELOG.md @@ -12,6 +12,10 @@ - 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다. - 문서의 제품 표기를 「그누보드7」로 통일했습니다. +### Fixed + +- 설정 파일의 프론트엔드 자산 항목이 문서화된 형식과 다른 목록형으로 적혀 있어 예제로 삼으면 스크립트가 로드되지 않는 형태였습니다. 선언할 자산이 없어 항목을 제거했습니다. + ## [0.1.1] - 2026-08-10 ### Fixed diff --git a/modules/_bundled/gnuboard7-hello_module/docs/frontend.md b/modules/_bundled/gnuboard7-hello_module/docs/frontend.md index d7584e57..2f636015 100644 --- a/modules/_bundled/gnuboard7-hello_module/docs/frontend.md +++ b/modules/_bundled/gnuboard7-hello_module/docs/frontend.md @@ -79,7 +79,10 @@ _프론트 에셋이 없습니다._ 그래서 반영이 `php artisan module:update gnuboard7-hello_module --force` 하나로 끝납니다. JS 를 더하면 그때 빌드(`module:build --production`)·`dist/` 커밋·전역 진입점 셋이 함께 -필요해집니다. +필요해집니다. 그때 `module.json` 에는 `assets.js.output` **객체 형식**으로 선언합니다 +(`"assets": { "js": { "entry": "resources/js/index.ts", "output": "dist/js/....iife.js" } }`). +목록형(`"js": ["..."]`)은 어느 소비자도 읽지 않아 그 스크립트가 영영 로드되지 않는데, +오류도 경고도 남지 않습니다. 구동에 필요한 제3자 자산은 외부 CDN 에서 받지 않고 확장이 동봉합니다 — CDN 도달 실패는 예외도 서버 로그도 남기지 않고 화면 기능만 조용히 사라지기 때문입니다. diff --git a/modules/_bundled/gnuboard7-hello_module/module.json b/modules/_bundled/gnuboard7-hello_module/module.json index 4f0ee319..7c27ce6e 100644 --- a/modules/_bundled/gnuboard7-hello_module/module.json +++ b/modules/_bundled/gnuboard7-hello_module/module.json @@ -16,9 +16,5 @@ "dependencies": { "modules": {}, "plugins": {} - }, - "assets": { - "js": [], - "css": [] } } diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index c453565c..a386983b 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,23 +1,23 @@ -var SR=Object.defineProperty;var wR=(tn,na,ra)=>na in tn?SR(tn,na,{enumerable:!0,configurable:!0,writable:!0,value:ra}):tn[na]=ra;var M=(tn,na,ra)=>wR(tn,typeof na!="symbol"?na+"":na,ra);(function(tn){"use strict";function na(s,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}function ra(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ad={exports:{}},Ye={};var Mg;function r0(){if(Mg)return Ye;Mg=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=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"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),v=Symbol.iterator;function S(H){return H===null||typeof H!="object"?null:(H=v&&H[v]||H["@@iterator"],typeof H=="function"?H:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,A={};function D(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}D.prototype.isReactComponent={},D.prototype.setState=function(H,T){if(typeof H!="object"&&typeof H!="function"&&H!=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,H,T,"setState")},D.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function O(){}O.prototype=D.prototype;function k(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}var L=k.prototype=new O;L.constructor=k,x(L,D.prototype),L.isPureReactComponent=!0;var B=Array.isArray;function q(){}var z={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function de(H,T,fe){var he=fe.ref;return{$$typeof:s,type:H,key:T,ref:he!==void 0?he:null,props:fe}}function _e(H,T){return de(H.type,T,H.props)}function Se(H){return typeof H=="object"&&H!==null&&H.$$typeof===s}function Ie(H){var T={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(fe){return T[fe]})}var Fe=/\/+/g;function ze(H,T){return typeof H=="object"&&H!==null&&H.key!=null?Ie(""+H.key):T.toString(36)}function Et(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(q,q):(H.status="pending",H.then(function(T){H.status==="pending"&&(H.status="fulfilled",H.value=T)},function(T){H.status==="pending"&&(H.status="rejected",H.reason=T)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function Q(H,T,fe,he,Ae){var se=typeof H;(se==="undefined"||se==="boolean")&&(H=null);var ge=!1;if(H===null)ge=!0;else switch(se){case"bigint":case"string":case"number":ge=!0;break;case"object":switch(H.$$typeof){case s:case e:ge=!0;break;case m:return ge=H._init,Q(ge(H._payload),T,fe,he,Ae)}}if(ge)return Ae=Ae(H),ge=he===""?"."+ze(H,0):he,B(Ae)?(fe="",ge!=null&&(fe=ge.replace(Fe,"$&/")+"/"),Q(Ae,T,fe,"",function(je){return je})):Ae!=null&&(Se(Ae)&&(Ae=_e(Ae,fe+(Ae.key==null||H&&H.key===Ae.key?"":(""+Ae.key).replace(Fe,"$&/")+"/")+ge)),T.push(Ae)),1;ge=0;var $e=he===""?".":he+":";if(B(H))for(var Te=0;Te>>1,me=Q[ee];if(0>>1;eei(fe,De))hei(Ae,fe)?(Q[ee]=Ae,Q[he]=De,ee=he):(Q[ee]=fe,Q[T]=De,ee=T);else if(hei(Ae,De))Q[ee]=Ae,Q[he]=De,ee=he;else break e}}return ue}function i(Q,ue){var De=Q.sortIndex-ue.sortIndex;return De!==0?De:Q.id-ue.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;s.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();s.unstable_now=function(){return c.now()-d}}var f=[],h=[],m=1,y=null,v=3,S=!1,_=!1,x=!1,A=!1,D=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function L(Q){for(var ue=n(h);ue!==null;){if(ue.callback===null)r(h);else if(ue.startTime<=Q)r(h),ue.sortIndex=ue.expirationTime,e(f,ue);else break;ue=n(h)}}function B(Q){if(x=!1,L(Q),!_)if(n(f)!==null)_=!0,q||(q=!0,Ie());else{var ue=n(h);ue!==null&&Et(B,ue.startTime-Q)}}var q=!1,z=-1,W=5,de=-1;function _e(){return A?!0:!(s.unstable_now()-deQ&&_e());){var ee=y.callback;if(typeof ee=="function"){y.callback=null,v=y.priorityLevel;var me=ee(y.expirationTime<=Q);if(Q=s.unstable_now(),typeof me=="function"){y.callback=me,L(Q),ue=!0;break t}y===n(f)&&r(f),L(Q)}else r(f);y=n(f)}if(y!==null)ue=!0;else{var H=n(h);H!==null&&Et(B,H.startTime-Q),ue=!1}}break e}finally{y=null,v=De,S=!1}ue=void 0}}finally{ue?Ie():q=!1}}}var Ie;if(typeof k=="function")Ie=function(){k(Se)};else if(typeof MessageChannel<"u"){var Fe=new MessageChannel,ze=Fe.port2;Fe.port1.onmessage=Se,Ie=function(){ze.postMessage(null)}}else Ie=function(){D(Se,0)};function Et(Q,ue){z=D(function(){Q(s.unstable_now())},ue)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(Q){Q.callback=null},s.unstable_forceFrameRate=function(Q){0>Q||125ee?(Q.sortIndex=De,e(h,Q),n(f)===null&&Q===n(h)&&(x?(O(z),z=-1):x=!0,Et(B,De-ee))):(Q.sortIndex=me,e(f,Q),_||S||(_=!0,q||(q=!0,Ie()))),Q},s.unstable_shouldYield=_e,s.unstable_wrapCallback=function(Q){var ue=v;return function(){var De=v;v=ue;try{return Q.apply(this,arguments)}finally{v=De}}}})(Rd)),Rd}var jg;function i0(){return jg||(jg=1,kd.exports=a0()),kd.exports}var Dd={exports:{}},An={};var Hg;function s0(){if(Hg)return An;Hg=1;var s=xd();function e(f){var h="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Dd.exports=s0(),Dd.exports}var Ug;function o0(){if(Ug)return fo;Ug=1;var s=i0(),e=xd(),n=Pg();function r(t){var a="https://react.dev/errors/"+t;if(1me||(t.current=ee[me],ee[me]=null,me--)}function fe(t,a){me++,ee[me]=t.current,t.current=a}var he=H(null),Ae=H(null),se=H(null),ge=H(null);function $e(t,a){switch(fe(se,a),fe(Ae,t),fe(he,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?_w(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=_w(a),t=Aw(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(he),fe(he,t)}function Te(){T(he),T(Ae),T(se)}function je(t){t.memoizedState!==null&&fe(ge,t);var a=he.current,o=Aw(a,t.type);a!==o&&(fe(Ae,t),fe(he,o))}function xt(t){Ae.current===t&&(T(he),T(Ae)),ge.current===t&&(T(ge),Xl._currentValue=De)}var rt,gt;function at(t){if(rt===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);rt=a&&a[1]||"",gt=-1na in tn?CR(tn,na,{enumerable:!0,configurable:!0,writable:!0,value:ra}):tn[na]=ra;var M=(tn,na,ra)=>ER(tn,typeof na!="symbol"?na+"":na,ra);(function(tn){"use strict";function na(s,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}function ra(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ad={exports:{}},Ye={};var Mg;function a0(){if(Mg)return Ye;Mg=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=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"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),v=Symbol.iterator;function S(H){return H===null||typeof H!="object"?null:(H=v&&H[v]||H["@@iterator"],typeof H=="function"?H:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,A={};function D(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}D.prototype.isReactComponent={},D.prototype.setState=function(H,T){if(typeof H!="object"&&typeof H!="function"&&H!=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,H,T,"setState")},D.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function O(){}O.prototype=D.prototype;function k(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}var L=k.prototype=new O;L.constructor=k,x(L,D.prototype),L.isPureReactComponent=!0;var B=Array.isArray;function q(){}var z={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function de(H,T,fe){var he=fe.ref;return{$$typeof:s,type:H,key:T,ref:he!==void 0?he:null,props:fe}}function _e(H,T){return de(H.type,T,H.props)}function Se(H){return typeof H=="object"&&H!==null&&H.$$typeof===s}function Ie(H){var T={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(fe){return T[fe]})}var Fe=/\/+/g;function ze(H,T){return typeof H=="object"&&H!==null&&H.key!=null?Ie(""+H.key):T.toString(36)}function Et(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(q,q):(H.status="pending",H.then(function(T){H.status==="pending"&&(H.status="fulfilled",H.value=T)},function(T){H.status==="pending"&&(H.status="rejected",H.reason=T)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function Q(H,T,fe,he,Ae){var se=typeof H;(se==="undefined"||se==="boolean")&&(H=null);var ge=!1;if(H===null)ge=!0;else switch(se){case"bigint":case"string":case"number":ge=!0;break;case"object":switch(H.$$typeof){case s:case e:ge=!0;break;case m:return ge=H._init,Q(ge(H._payload),T,fe,he,Ae)}}if(ge)return Ae=Ae(H),ge=he===""?"."+ze(H,0):he,B(Ae)?(fe="",ge!=null&&(fe=ge.replace(Fe,"$&/")+"/"),Q(Ae,T,fe,"",function(je){return je})):Ae!=null&&(Se(Ae)&&(Ae=_e(Ae,fe+(Ae.key==null||H&&H.key===Ae.key?"":(""+Ae.key).replace(Fe,"$&/")+"/")+ge)),T.push(Ae)),1;ge=0;var $e=he===""?".":he+":";if(B(H))for(var Te=0;Te>>1,me=Q[ee];if(0>>1;eei(fe,De))hei(Ae,fe)?(Q[ee]=Ae,Q[he]=De,ee=he):(Q[ee]=fe,Q[T]=De,ee=T);else if(hei(Ae,De))Q[ee]=Ae,Q[he]=De,ee=he;else break e}}return ue}function i(Q,ue){var De=Q.sortIndex-ue.sortIndex;return De!==0?De:Q.id-ue.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;s.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();s.unstable_now=function(){return c.now()-d}}var f=[],h=[],m=1,y=null,v=3,S=!1,_=!1,x=!1,A=!1,D=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function L(Q){for(var ue=n(h);ue!==null;){if(ue.callback===null)r(h);else if(ue.startTime<=Q)r(h),ue.sortIndex=ue.expirationTime,e(f,ue);else break;ue=n(h)}}function B(Q){if(x=!1,L(Q),!_)if(n(f)!==null)_=!0,q||(q=!0,Ie());else{var ue=n(h);ue!==null&&Et(B,ue.startTime-Q)}}var q=!1,z=-1,W=5,de=-1;function _e(){return A?!0:!(s.unstable_now()-deQ&&_e());){var ee=y.callback;if(typeof ee=="function"){y.callback=null,v=y.priorityLevel;var me=ee(y.expirationTime<=Q);if(Q=s.unstable_now(),typeof me=="function"){y.callback=me,L(Q),ue=!0;break t}y===n(f)&&r(f),L(Q)}else r(f);y=n(f)}if(y!==null)ue=!0;else{var H=n(h);H!==null&&Et(B,H.startTime-Q),ue=!1}}break e}finally{y=null,v=De,S=!1}ue=void 0}}finally{ue?Ie():q=!1}}}var Ie;if(typeof k=="function")Ie=function(){k(Se)};else if(typeof MessageChannel<"u"){var Fe=new MessageChannel,ze=Fe.port2;Fe.port1.onmessage=Se,Ie=function(){ze.postMessage(null)}}else Ie=function(){D(Se,0)};function Et(Q,ue){z=D(function(){Q(s.unstable_now())},ue)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(Q){Q.callback=null},s.unstable_forceFrameRate=function(Q){0>Q||125ee?(Q.sortIndex=De,e(h,Q),n(f)===null&&Q===n(h)&&(x?(O(z),z=-1):x=!0,Et(B,De-ee))):(Q.sortIndex=me,e(f,Q),_||S||(_=!0,q||(q=!0,Ie()))),Q},s.unstable_shouldYield=_e,s.unstable_wrapCallback=function(Q){var ue=v;return function(){var De=v;v=ue;try{return Q.apply(this,arguments)}finally{v=De}}}})(Rd)),Rd}var jg;function s0(){return jg||(jg=1,kd.exports=i0()),kd.exports}var Dd={exports:{}},An={};var Hg;function o0(){if(Hg)return An;Hg=1;var s=xd();function e(f){var h="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Dd.exports=o0(),Dd.exports}var Ug;function l0(){if(Ug)return fo;Ug=1;var s=s0(),e=xd(),n=Pg();function r(t){var a="https://react.dev/errors/"+t;if(1me||(t.current=ee[me],ee[me]=null,me--)}function fe(t,a){me++,ee[me]=t.current,t.current=a}var he=H(null),Ae=H(null),se=H(null),ge=H(null);function $e(t,a){switch(fe(se,a),fe(Ae,t),fe(he,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?Aw(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=Aw(a),t=xw(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(he),fe(he,t)}function Te(){T(he),T(Ae),T(se)}function je(t){t.memoizedState!==null&&fe(ge,t);var a=he.current,o=xw(a,t.type);a!==o&&(fe(Ae,t),fe(he,o))}function xt(t){Ae.current===t&&(T(he),T(Ae)),ge.current===t&&(T(ge),Xl._currentValue=De)}var rt,gt;function at(t){if(rt===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);rt=a&&a[1]||"",gt=-1)":-1p||P[u]!==X[p]){var re=` `+P[u].replace(" at new "," at ");return t.displayName&&re.includes("")&&(re=re.replace("",t.displayName)),re}while(1<=u&&0<=p);break}}}finally{Yt=!1,Error.prepareStackTrace=o}return(o=t?t.displayName||t.name:"")?at(o):""}function bt(t,a){switch(t.tag){case 26:case 27:case 5:return at(t.type);case 16:return at("Lazy");case 13:return t.child!==a&&a!==null?at("Suspense Fallback"):at("Suspense");case 19:return at("SuspenseList");case 0:case 15:return Ht(t.type,!1);case 11:return Ht(t.type.render,!1);case 1:return Ht(t.type,!0);case 31:return at("Activity");default:return""}}function qe(t){try{var a="",o=null;do a+=bt(t,o),o=t,t=t.return;while(t);return a}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var mt=Object.prototype.hasOwnProperty,Dt=s.unstable_scheduleCallback,zt=s.unstable_cancelCallback,kn=s.unstable_shouldYield,dr=s.unstable_requestPaint,Ot=s.unstable_now,Li=s.unstable_getCurrentPriorityLevel,ua=s.unstable_ImmediatePriority,bn=s.unstable_UserBlockingPriority,Mn=s.unstable_NormalPriority,it=s.unstable_LowPriority,Pn=s.unstable_IdlePriority,vn=s.log,da=s.unstable_setDisableYieldValue,fr=null,un=null;function Rn(t){if(typeof vn=="function"&&da(t),un&&typeof un.setStrictMode=="function")try{un.setStrictMode(fr,t)}catch{}}var dn=Math.clz32?Math.clz32:ce,V=Math.log,ie=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(V(t)/ie|0)|0}var Z=256,ve=262144,pe=4194304;function Ee(t){var a=t&42;if(a!==0)return a;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 xe(t,a,o){var u=t.pendingLanes;if(u===0)return 0;var p=0,g=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var R=u&134217727;return R!==0?(u=R&~g,u!==0?p=Ee(u):(C&=R,C!==0?p=Ee(C):o||(o=R&~t,o!==0&&(p=Ee(o))))):(R=u&~g,R!==0?p=Ee(R):C!==0?p=Ee(C):o||(o=u&~t,o!==0&&(p=Ee(o)))),p===0?0:a!==0&&a!==p&&(a&g)===0&&(g=p&-p,o=a&-a,g>=o||g===32&&(o&4194048)!==0)?a:p}function Ke(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function ke(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+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 a+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 Me(){var t=pe;return pe<<=1,(pe&62914560)===0&&(pe=4194304),t}function Re(t){for(var a=[],o=0;31>o;o++)a.push(t);return a}function tt(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Pe(t,a,o,u,p,g){var C=t.pendingLanes;t.pendingLanes=o,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=o,t.entangledLanes&=o,t.errorRecoveryDisabledLanes&=o,t.shellSuspendCounter=0;var R=t.entanglements,P=t.expirationTimes,X=t.hiddenUpdates;for(o=C&~o;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Sh=/[\n"\\]/g;function Bn(t){return t.replace(Sh,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Os(t,a,o,u,p,g,C,R){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),a!=null?C==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+On(a)):t.value!==""+On(a)&&(t.value=""+On(a)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),a!=null?ha(t,C,On(a)):o!=null?ha(t,C,On(o)):u!=null&&t.removeAttribute("value"),p==null&&g!=null&&(t.defaultChecked=!!g),p!=null&&(t.checked=p&&typeof p!="function"&&typeof p!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?t.name=""+On(R):t.removeAttribute("name")}function Ni(t,a,o,u,p,g,C,R){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(t.type=g),a!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||a!=null)){il(t);return}o=o!=null?""+On(o):"",a=a!=null?""+On(a):o,R||a===t.value||(t.value=a),t.defaultValue=a}u=u??p,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=R?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),il(t)}function ha(t,a,o){a==="number"&&Va(t.ownerDocument)===t||t.defaultValue===""+o||(t.defaultValue=""+o)}function Ka(t,a,o,u){if(t=t.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ul=!1;if(Nr)try{var ji={};Object.defineProperty(ji,"passive",{get:function(){ul=!0}}),window.addEventListener("test",ji,ji),window.removeEventListener("test",ji,ji)}catch{ul=!1}var Jr=null,dl=null,$s=null;function du(){if($s)return $s;var t,a=dl,o=a.length,u,p="value"in Jr?Jr.value:Jr.textContent,g=p.length;for(t=0;t=ne),We=" ",ft=!1;function vt(t,a){switch(t){case"keyup":return $.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var jr=!1;function Hh(t,a){switch(t){case"compositionend":return Vt(a);case"keypress":return a.which!==32?null:(ft=!0,We);case"textInput":return t=a.data,t===We&&ft?null:t;default:return null}}function bu(t,a){if(jr)return t==="compositionend"||!N&&vt(t,a)?(t=du(),$s=dl=Jr=null,jr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-t};t=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Bb(o)}}function Gb(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?Gb(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Fb(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=Va(t.document);a instanceof t.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)t=a.contentWindow;else break;a=Va(t.document)}return a}function qh(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var ZT=Nr&&"documentMode"in document&&11>=document.documentMode,js=null,Gh=null,wl=null,Fh=!1;function Vb(t,a,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Fh||js==null||js!==Va(u)||(u=js,"selectionStart"in u&&qh(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}),wl&&Sl(wl,u)||(wl=u,u=ud(Gh,"onSelect"),0>=C,p-=C,Qr=1<<32-dn(a)+p|o<Ze?(ut=Ne,Ne=null):ut=Ne.sibling;var wt=J(K,Ne,Y[Ze],oe);if(wt===null){Ne===null&&(Ne=ut);break}t&&Ne&&wt.alternate===null&&a(K,Ne),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt,Ne=ut}if(Ze===Y.length)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;ZeZe?(ut=Ne,Ne=null):ut=Ne.sibling;var vi=J(K,Ne,wt.value,oe);if(vi===null){Ne===null&&(Ne=ut);break}t&&Ne&&vi.alternate===null&&a(K,Ne),F=g(vi,F,Ze),St===null?Be=vi:St.sibling=vi,St=vi,Ne=ut}if(wt.done)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;!wt.done;Ze++,wt=Y.next())wt=le(K,wt.value,oe),wt!==null&&(F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return ht&&ya(K,Ze),Be}for(Ne=u(Ne);!wt.done;Ze++,wt=Y.next())wt=te(Ne,K,Ze,wt.value,oe),wt!==null&&(t&&wt.alternate!==null&&Ne.delete(wt.key===null?Ze:wt.key),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return t&&Ne.forEach(function(vR){return a(K,vR)}),ht&&ya(K,Ze),Be}function Nt(K,F,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===x&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case S:e:{for(var Be=Y.key;F!==null;){if(F.key===Be){if(Be=Y.type,Be===x){if(F.tag===7){o(K,F.sibling),oe=p(F,Y.props.children),oe.return=K,K=oe;break e}}else if(F.elementType===Be||typeof Be=="object"&&Be!==null&&Be.$$typeof===W&&Zi(Be)===F.type){o(K,F.sibling),oe=p(F,Y.props),Tl(oe,Y),oe.return=K,K=oe;break e}o(K,F);break}else a(K,F);F=F.sibling}Y.type===x?(oe=Wi(Y.props.children,K.mode,oe,Y.key),oe.return=K,K=oe):(oe=Tu(Y.type,Y.key,Y.props,null,K.mode,oe),Tl(oe,Y),oe.return=K,K=oe)}return C(K);case _:e:{for(Be=Y.key;F!==null;){if(F.key===Be)if(F.tag===4&&F.stateNode.containerInfo===Y.containerInfo&&F.stateNode.implementation===Y.implementation){o(K,F.sibling),oe=p(F,Y.children||[]),oe.return=K,K=oe;break e}else{o(K,F);break}else a(K,F);F=F.sibling}oe=Qh(Y,K.mode,oe),oe.return=K,K=oe}return C(K);case W:return Y=Zi(Y),Nt(K,F,Y,oe)}if(Et(Y))return Oe(K,F,Y,oe);if(Ie(Y)){if(Be=Ie(Y),typeof Be!="function")throw Error(r(150));return Y=Be.call(Y),Ge(K,F,Y,oe)}if(typeof Y.then=="function")return Nt(K,F,Mu(Y),oe);if(Y.$$typeof===k)return Nt(K,F,Du(K,Y),oe);Nu(K,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,F!==null&&F.tag===6?(o(K,F.sibling),oe=p(F,Y),oe.return=K,K=oe):(o(K,F),oe=Jh(Y,K.mode,oe),oe.return=K,K=oe),C(K)):o(K,F)}return function(K,F,Y,oe){try{xl=0;var Be=Nt(K,F,Y,oe);return Ws=null,Be}catch(Ne){if(Ne===Ks||Ne===Lu)throw Ne;var St=er(29,Ne,null,K.mode);return St.lanes=oe,St.return=K,St}}}var ts=gv(!0),mv=gv(!1),ni=!1;function up(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function dp(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ri(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ai(t,a,o){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(_t&2)!==0){var p=u.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),u.pending=a,a=xu(t),Zb(t,null,o),a}return Au(t,u,a,o),xu(t)}function kl(t,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}function fp(t,a){var o=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var p=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var C={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?p=g=C:g=g.next=C,o=o.next}while(o!==null);g===null?p=g=a:g=g.next=a}else p=g=a;o={baseState:u.baseState,firstBaseUpdate:p,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},t.updateQueue=o;return}t=o.lastBaseUpdate,t===null?o.firstBaseUpdate=a:t.next=a,o.lastBaseUpdate=a}var hp=!1;function Rl(){if(hp){var t=Vs;if(t!==null)throw t}}function Dl(t,a,o,u){hp=!1;var p=t.updateQueue;ni=!1;var g=p.firstBaseUpdate,C=p.lastBaseUpdate,R=p.shared.pending;if(R!==null){p.shared.pending=null;var P=R,X=P.next;P.next=null,C===null?g=X:C.next=X,C=P;var re=t.alternate;re!==null&&(re=re.updateQueue,R=re.lastBaseUpdate,R!==C&&(R===null?re.firstBaseUpdate=X:R.next=X,re.lastBaseUpdate=P))}if(g!==null){var le=p.baseState;C=0,re=X=P=null,R=g;do{var J=R.lane&-536870913,te=J!==R.lane;if(te?(ct&J)===J:(u&J)===J){J!==0&&J===Fs&&(hp=!0),re!==null&&(re=re.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Oe=t,Ge=R;J=a;var Nt=o;switch(Ge.tag){case 1:if(Oe=Ge.payload,typeof Oe=="function"){le=Oe.call(Nt,le,J);break e}le=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ge.payload,J=typeof Oe=="function"?Oe.call(Nt,le,J):Oe,J==null)break e;le=y({},le,J);break e;case 2:ni=!0}}J=R.callback,J!==null&&(t.flags|=64,te&&(t.flags|=8192),te=p.callbacks,te===null?p.callbacks=[J]:te.push(J))}else te={lane:J,tag:R.tag,payload:R.payload,callback:R.callback,next:null},re===null?(X=re=te,P=le):re=re.next=te,C|=J;if(R=R.next,R===null){if(R=p.shared.pending,R===null)break;te=R,R=te.next,te.next=null,p.lastBaseUpdate=te,p.shared.pending=null}}while(!0);re===null&&(P=le),p.baseState=P,p.firstBaseUpdate=X,p.lastBaseUpdate=re,g===null&&(p.shared.lanes=0),ci|=C,t.lanes=C,t.memoizedState=le}}function yv(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function bv(t,a){var o=t.callbacks;if(o!==null)for(t.callbacks=null,t=0;tg?g:8;var C=Q.T,R={};Q.T=R,Lp(t,!1,a,o);try{var P=p(),X=Q.S;if(X!==null&&X(R,P),P!==null&&typeof P=="object"&&typeof P.then=="function"){var re=lk(P,u);$l(t,a,re,ir(t))}else $l(t,a,u,ir(t))}catch(le){$l(t,a,{then:function(){},status:"rejected",reason:le},ir())}finally{ue.p=g,C!==null&&R.types!==null&&(C.types=R.types),Q.T=C}}function pk(){}function Dp(t,a,o,u){if(t.tag!==5)throw Error(r(476));var p=Xv(t).queue;Yv(t,p,a,De,o===null?pk:function(){return Jv(t),o(u)})}function Xv(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:De,baseState:De,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:De},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:o},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function Jv(t){var a=Xv(t);a.next===null&&(a=t.alternate.memoizedState),$l(t,a.next.queue,{},ir())}function Op(){return Cn(Xl)}function Qv(){return en().memoizedState}function Zv(){return en().memoizedState}function gk(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var o=ir();t=ri(o);var u=ai(a,t,o);u!==null&&(Kn(u,a,o),kl(u,a,o)),a={cache:sp()},t.payload=a;return}a=a.return}}function mk(t,a,o){var u=ir();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Fu(t)?tS(a,o):(o=Yh(t,a,o,u),o!==null&&(Kn(o,t,u),nS(o,a,u)))}function eS(t,a,o){var u=ir();$l(t,a,o,u)}function $l(t,a,o,u){var p={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Fu(t))tS(a,p);else{var g=t.alternate;if(t.lanes===0&&(g===null||g.lanes===0)&&(g=a.lastRenderedReducer,g!==null))try{var C=a.lastRenderedState,R=g(C,o);if(p.hasEagerState=!0,p.eagerState=R,Zn(R,C))return Au(t,a,p,0),It===null&&_u(),!1}catch{}if(o=Yh(t,a,p,u),o!==null)return Kn(o,t,u),nS(o,a,u),!0}return!1}function Lp(t,a,o,u){if(u={lane:2,revertLane:ug(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Fu(t)){if(a)throw Error(r(479))}else a=Yh(t,o,u,2),a!==null&&Kn(a,t,2)}function Fu(t){var a=t.alternate;return t===Je||a!==null&&a===Je}function tS(t,a){Xs=Hu=!0;var o=t.pending;o===null?a.next=a:(a.next=o.next,o.next=a),t.pending=a}function nS(t,a,o){if((o&4194048)!==0){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}var Ml={readContext:Cn,use:Uu,useCallback:Xt,useContext:Xt,useEffect:Xt,useImperativeHandle:Xt,useLayoutEffect:Xt,useInsertionEffect:Xt,useMemo:Xt,useReducer:Xt,useRef:Xt,useState:Xt,useDebugValue:Xt,useDeferredValue:Xt,useTransition:Xt,useSyncExternalStore:Xt,useId:Xt,useHostTransitionStatus:Xt,useFormState:Xt,useActionState:Xt,useOptimistic:Xt,useMemoCache:Xt,useCacheRefresh:Xt};Ml.useEffectEvent=Xt;var rS={readContext:Cn,use:Uu,useCallback:function(t,a){return In().memoizedState=[t,a===void 0?null:a],t},useContext:Cn,useEffect:Pv,useImperativeHandle:function(t,a,o){o=o!=null?o.concat([t]):null,qu(4194308,4,Gv.bind(null,a,t),o)},useLayoutEffect:function(t,a){return qu(4194308,4,t,a)},useInsertionEffect:function(t,a){qu(4,2,t,a)},useMemo:function(t,a){var o=In();a=a===void 0?null:a;var u=t();if(ns){Rn(!0);try{t()}finally{Rn(!1)}}return o.memoizedState=[u,a],u},useReducer:function(t,a,o){var u=In();if(o!==void 0){var p=o(a);if(ns){Rn(!0);try{o(a)}finally{Rn(!1)}}}else p=a;return u.memoizedState=u.baseState=p,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:p},u.queue=t,t=t.dispatch=mk.bind(null,Je,t),[u.memoizedState,t]},useRef:function(t){var a=In();return t={current:t},a.memoizedState=t},useState:function(t){t=Ap(t);var a=t.queue,o=eS.bind(null,Je,a);return a.dispatch=o,[t.memoizedState,o]},useDebugValue:kp,useDeferredValue:function(t,a){var o=In();return Rp(o,t,a)},useTransition:function(){var t=Ap(!1);return t=Yv.bind(null,Je,t.queue,!0,!1),In().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,o){var u=Je,p=In();if(ht){if(o===void 0)throw Error(r(407));o=o()}else{if(o=a(),It===null)throw Error(r(349));(ct&127)!==0||_v(u,a,o)}p.memoizedState=o;var g={value:o,getSnapshot:a};return p.queue=g,Pv(xv.bind(null,u,g,t),[t]),u.flags|=2048,Qs(9,{destroy:void 0},Av.bind(null,u,g,o,a),null),o},useId:function(){var t=In(),a=It.identifierPrefix;if(ht){var o=Zr,u=Qr;o=(u&~(1<<32-dn(u)-1)).toString(32)+o,a="_"+a+"R_"+o,o=zu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?C.createElement(p,{is:u.is}):C.createElement(p)}}g[Ft]=a,g[Dn]=u;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)g.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=g;e:switch(_n(g,p,u),p){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ea(a)}}return Ut(a),Vp(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,o),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==u&&Ea(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(t=se.current,qs(a)){if(t=a.stateNode,o=a.memoizedProps,u=null,p=wn,p!==null)switch(p.tag){case 27:case 5:u=p.memoizedProps}t[Ft]=a,t=!!(t.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||Cw(t.nodeValue,o)),t||ei(a,!0)}else t=dd(t).createTextNode(u),t[Ft]=a,a.stateNode=t}return Ut(a),null;case 31:if(o=a.memoizedState,t===null||t.memoizedState!==null){if(u=qs(a),o!==null){if(t===null){if(!u)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[Ft]=a}else Yi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),t=!1}else o=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),t=!0;if(!t)return a.flags&256?(nr(a),a):(nr(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Ut(a),null;case 13:if(u=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(p=qs(a),u!==null&&u.dehydrated!==null){if(t===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else Yi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),p=!1}else p=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(nr(a),a):(nr(a),null)}return nr(a),(a.flags&128)!==0?(a.lanes=o,a):(o=u!==null,t=t!==null&&t.memoizedState!==null,o&&(u=a.child,p=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(p=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==p&&(u.flags|=2048)),o!==t&&o&&(a.child.flags|=8192),Xu(a,a.updateQueue),Ut(a),null);case 4:return Te(),t===null&&pg(a.stateNode.containerInfo),Ut(a),null;case 10:return va(a.type),Ut(a),null;case 19:if(T(Zt),u=a.memoizedState,u===null)return Ut(a),null;if(p=(a.flags&128)!==0,g=u.rendering,g===null)if(p)Il(u,!1);else{if(Jt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(g=ju(t),g!==null){for(a.flags|=128,Il(u,!1),t=g.updateQueue,a.updateQueue=t,Xu(a,t),a.subtreeFlags=0,t=o,o=a.child;o!==null;)ev(o,t),o=o.sibling;return fe(Zt,Zt.current&1|2),ht&&ya(a,u.treeForkCount),a.child}t=t.sibling}u.tail!==null&&Ot()>td&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304)}else{if(!p)if(t=ju(g),t!==null){if(a.flags|=128,p=!0,t=t.updateQueue,a.updateQueue=t,Xu(a,t),Il(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!ht)return Ut(a),null}else 2*Ot()-u.renderingStartTime>td&&o!==536870912&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304);u.isBackwards?(g.sibling=a.child,a.child=g):(t=u.last,t!==null?t.sibling=g:a.child=g,u.last=g)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ot(),t.sibling=null,o=Zt.current,fe(Zt,p?o&1|2:o&1),ht&&ya(a,u.treeForkCount),t):(Ut(a),null);case 22:case 23:return nr(a),gp(),u=a.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(o&536870912)!==0&&(a.flags&128)===0&&(Ut(a),a.subtreeFlags&6&&(a.flags|=8192)):Ut(a),o=a.updateQueue,o!==null&&Xu(a,o.retryQueue),o=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==o&&(a.flags|=2048),t!==null&&T(Qi),null;case 24:return o=null,t!==null&&(o=t.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),va(rn),Ut(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function wk(t,a){switch(ep(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return va(rn),Te(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return xt(a),null;case 31:if(a.memoizedState!==null){if(nr(a),a.alternate===null)throw Error(r(340));Yi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(nr(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Yi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return T(Zt),null;case 4:return Te(),null;case 10:return va(a.type),null;case 22:case 23:return nr(a),gp(),t!==null&&T(Qi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return va(rn),null;case 25:return null;default:return null}}function TS(t,a){switch(ep(a),a.tag){case 3:va(rn),Te();break;case 26:case 27:case 5:xt(a);break;case 4:Te();break;case 31:a.memoizedState!==null&&nr(a);break;case 13:nr(a);break;case 19:T(Zt);break;case 10:va(a.type);break;case 22:case 23:nr(a),gp(),t!==null&&T(Qi);break;case 24:va(rn)}}function jl(t,a){try{var o=a.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var p=u.next;o=p;do{if((o.tag&t)===t){u=void 0;var g=o.create,C=o.inst;u=g(),C.destroy=u}o=o.next}while(o!==p)}}catch(R){kt(a,a.return,R)}}function oi(t,a,o){try{var u=a.updateQueue,p=u!==null?u.lastEffect:null;if(p!==null){var g=p.next;u=g;do{if((u.tag&t)===t){var C=u.inst,R=C.destroy;if(R!==void 0){C.destroy=void 0,p=a;var P=o,X=R;try{X()}catch(re){kt(p,P,re)}}}u=u.next}while(u!==g)}}catch(re){kt(a,a.return,re)}}function kS(t){var a=t.updateQueue;if(a!==null){var o=t.stateNode;try{bv(a,o)}catch(u){kt(t,t.return,u)}}}function RS(t,a,o){o.props=rs(t.type,t.memoizedProps),o.state=t.memoizedState;try{o.componentWillUnmount()}catch(u){kt(t,a,u)}}function Hl(t,a){try{var o=t.ref;if(o!==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 o=="function"?t.refCleanup=o(u):o.current=u}}catch(p){kt(t,a,p)}}function ea(t,a){var o=t.ref,u=t.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(p){kt(t,a,p)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(p){kt(t,a,p)}else o.current=null}function DS(t){var a=t.type,o=t.memoizedProps,u=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(p){kt(t,t.return,p)}}function Kp(t,a,o){try{var u=t.stateNode;qk(u,t.type,o,a),u[Dn]=a}catch(p){kt(t,t.return,p)}}function OS(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&pi(t.type)||t.tag===4}function Wp(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||OS(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&&pi(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 Yp(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(t,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(t),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=Mr));else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode,a=null),t=t.child,t!==null))for(Yp(t,a,o),t=t.sibling;t!==null;)Yp(t,a,o),t=t.sibling}function Ju(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?o.insertBefore(t,a):o.appendChild(t);else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode),t=t.child,t!==null))for(Ju(t,a,o),t=t.sibling;t!==null;)Ju(t,a,o),t=t.sibling}function LS(t){var a=t.stateNode,o=t.memoizedProps;try{for(var u=t.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);_n(a,u,o),a[Ft]=t,a[Dn]=o}catch(g){kt(t,t.return,g)}}var _a=!1,on=!1,Xp=!1,$S=typeof WeakSet=="function"?WeakSet:Set,yn=null;function Ck(t,a){if(t=t.containerInfo,yg=bd,t=Fb(t),qh(t)){if("selectionStart"in t)var o={start:t.selectionStart,end:t.selectionEnd};else e:{o=(o=t.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var p=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var C=0,R=-1,P=-1,X=0,re=0,le=t,J=null;t:for(;;){for(var te;le!==o||p!==0&&le.nodeType!==3||(R=C+p),le!==g||u!==0&&le.nodeType!==3||(P=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(te=le.firstChild)!==null;)J=le,le=te;for(;;){if(le===t)break t;if(J===o&&++X===p&&(R=C),J===g&&++re===u&&(P=C),(te=le.nextSibling)!==null)break;le=J,J=le.parentNode}le=te}o=R===-1||P===-1?null:{start:R,end:P}}else o=null}o=o||{start:0,end:0}}else o=null;for(bg={focusedElem:t,selectionRange:o},bd=!1,yn=a;yn!==null;)if(a=yn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,yn=t;else for(;yn!==null;){switch(a=yn,g=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(o=0;o title"))),_n(g,u,o),g[Ft]=t,nn(g),u=g;break e;case"link":var C=zw("link","href",p).get(u+(o.href||""));if(C){for(var R=0;RNt&&(C=Nt,Nt=Ge,Ge=C);var K=qb(R,Ge),F=qb(R,Nt);if(K&&F&&(te.rangeCount!==1||te.anchorNode!==K.node||te.anchorOffset!==K.offset||te.focusNode!==F.node||te.focusOffset!==F.offset)){var Y=le.createRange();Y.setStart(K.node,K.offset),te.removeAllRanges(),Ge>Nt?(te.addRange(Y),te.extend(F.node,F.offset)):(Y.setEnd(F.node,F.offset),te.addRange(Y))}}}}for(le=[],te=R;te=te.parentNode;)te.nodeType===1&&le.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;Ro?32:o,Q.T=null,o=rg,rg=null;var g=di,C=Ra;if(hn=0,ro=di=null,Ra=0,(_t&6)!==0)throw Error(r(331));var R=_t;if(_t|=4,GS(g.current),US(g,g.current,C,o),_t=R,Gl(0,!1),un&&typeof un.onPostCommitFiberRoot=="function")try{un.onPostCommitFiberRoot(fr,g)}catch{}return!0}finally{ue.p=p,Q.T=u,lw(t,a)}}function uw(t,a,o){a=gr(o,a),a=Ip(t.stateNode,a,2),t=ai(t,a,2),t!==null&&(tt(t,2),ta(t))}function kt(t,a,o){if(t.tag===3)uw(t,t,o);else for(;a!==null;){if(a.tag===3){uw(a,t,o);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ui===null||!ui.has(u))){t=gr(o,t),o=dS(2),u=ai(a,o,2),u!==null&&(fS(o,u,a,t),tt(u,2),ta(u));break}}a=a.return}}function og(t,a,o){var u=t.pingCache;if(u===null){u=t.pingCache=new Ak;var p=new Set;u.set(a,p)}else p=u.get(a),p===void 0&&(p=new Set,u.set(a,p));p.has(o)||(Zp=!0,p.add(o),t=Dk.bind(null,t,a,o),a.then(t,t))}function Dk(t,a,o){var u=t.pingCache;u!==null&&u.delete(a),t.pingedLanes|=t.suspendedLanes&o,t.warmLanes&=~o,It===t&&(ct&o)===o&&(Jt===4||Jt===3&&(ct&62914560)===ct&&300>Ot()-ed?(_t&2)===0&&ao(t,0):eg|=o,no===ct&&(no=0)),ta(t)}function dw(t,a){a===0&&(a=Me()),t=Ki(t,a),t!==null&&(tt(t,a),ta(t))}function Ok(t){var a=t.memoizedState,o=0;a!==null&&(o=a.retryLane),dw(t,o)}function Lk(t,a){var o=0;switch(t.tag){case 31:case 13:var u=t.stateNode,p=t.memoizedState;p!==null&&(o=p.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),dw(t,o)}function $k(t,a){return Dt(t,a)}var od=null,so=null,lg=!1,ld=!1,cg=!1,hi=0;function ta(t){t!==so&&t.next===null&&(so===null?od=so=t:so=so.next=t),ld=!0,lg||(lg=!0,Nk())}function Gl(t,a){if(!cg&&ld){cg=!0;do for(var o=!1,u=od;u!==null;){if(t!==0){var p=u.pendingLanes;if(p===0)var g=0;else{var C=u.suspendedLanes,R=u.pingedLanes;g=(1<<31-dn(42|t)+1)-1,g&=p&~(C&~R),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,gw(u,g))}else g=ct,g=xe(u,u===It?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Ke(u,g)||(o=!0,gw(u,g));u=u.next}while(o);cg=!1}}function Mk(){fw()}function fw(){ld=lg=!1;var t=0;hi!==0&&Fk()&&(t=hi);for(var a=Ot(),o=null,u=od;u!==null;){var p=u.next,g=hw(u,a);g===0?(u.next=null,o===null?od=p:o.next=p,p===null&&(so=o)):(o=u,(t!==0||(g&3)!==0)&&(ld=!0)),u=p}hn!==0&&hn!==5||Gl(t),hi!==0&&(hi=0)}function hw(t,a){for(var o=t.suspendedLanes,u=t.pingedLanes,p=t.expirationTimes,g=t.pendingLanes&-62914561;0R)break;var re=P.transferSize,le=P.initiatorType;re&&Ew(le)&&(P=P.responseEnd,C+=re*(P"u"?null:document;function Nw(t,a,o){var u=oo;if(u&&typeof a=="string"&&a){var p=Bn(a);p='link[rel="'+t+'"][href="'+p+'"]',typeof o=="string"&&(p+='[crossorigin="'+o+'"]'),Mw.has(p)||(Mw.add(p),t={rel:t,crossOrigin:o,href:a},u.querySelector(p)===null&&(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function eR(t){Da.D(t),Nw("dns-prefetch",t,null)}function tR(t,a){Da.C(t,a),Nw("preconnect",t,a)}function nR(t,a,o){Da.L(t,a,o);var u=oo;if(u&&t&&a){var p='link[rel="preload"][as="'+Bn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(p+='[imagesrcset="'+Bn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(p+='[imagesizes="'+Bn(o.imageSizes)+'"]')):p+='[href="'+Bn(t)+'"]';var g=p;switch(a){case"style":g=lo(t);break;case"script":g=co(t)}wr.has(g)||(t=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:t,as:a},o),wr.set(g,t),u.querySelector(p)!==null||a==="style"&&u.querySelector(Wl(g))||a==="script"&&u.querySelector(Yl(g))||(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function rR(t,a){Da.m(t,a);var o=oo;if(o&&t){var u=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+Bn(u)+'"][href="'+Bn(t)+'"]',g=p;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=co(t)}if(!wr.has(g)&&(t=y({rel:"modulepreload",href:t},a),wr.set(g,t),o.querySelector(p)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Yl(g)))return}u=o.createElement("link"),_n(u,"link",t),nn(u),o.head.appendChild(u)}}}function aR(t,a,o){Da.S(t,a,o);var u=oo;if(u&&t){var p=Ga(u).hoistableStyles,g=lo(t);a=a||"default";var C=p.get(g);if(!C){var R={loading:0,preload:null};if(C=u.querySelector(Wl(g)))R.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},o),(o=wr.get(g))&&Ag(t,o);var P=C=u.createElement("link");nn(P),_n(P,"link",t),P._p=new Promise(function(X,re){P.onload=X,P.onerror=re}),P.addEventListener("load",function(){R.loading|=1}),P.addEventListener("error",function(){R.loading|=2}),R.loading|=4,hd(C,a,u)}C={type:"stylesheet",instance:C,count:1,state:R},p.set(g,C)}}}function iR(t,a){Da.X(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function sR(t,a){Da.M(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0,type:"module"},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function Iw(t,a,o,u){var p=(p=se.current)?fd(p):null;if(!p)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=lo(o.href),o=Ga(p).hoistableStyles,u=o.get(a),u||(u={type:"style",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){t=lo(o.href);var g=Ga(p).hoistableStyles,C=g.get(t);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(t,C),(g=p.querySelector(Wl(t)))&&!g._p&&(C.instance=g,C.state.loading=5),wr.has(t)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},wr.set(t,o),g||oR(p,t,o,C.state))),a&&u===null)throw Error(r(528,""));return C}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=co(o),o=Ga(p).hoistableScripts,u=o.get(a),u||(u={type:"script",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function lo(t){return'href="'+Bn(t)+'"'}function Wl(t){return'link[rel="stylesheet"]['+t+"]"}function jw(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function oR(t,a,o,u){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=t.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),_n(a,"link",o),nn(a),t.head.appendChild(a))}function co(t){return'[src="'+Bn(t)+'"]'}function Yl(t){return"script[async]"+t}function Hw(t,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var u=t.querySelector('style[data-href~="'+Bn(o.href)+'"]');if(u)return a.instance=u,nn(u),u;var p=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),nn(u),_n(u,"style",p),hd(u,o.precedence,t),a.instance=u;case"stylesheet":p=lo(o.href);var g=t.querySelector(Wl(p));if(g)return a.state.loading|=4,a.instance=g,nn(g),g;u=jw(o),(p=wr.get(p))&&Ag(u,p),g=(t.ownerDocument||t).createElement("link"),nn(g);var C=g;return C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),a.state.loading|=4,hd(g,o.precedence,t),a.instance=g;case"script":return g=co(o.src),(p=t.querySelector(Yl(g)))?(a.instance=p,nn(p),p):(u=o,(p=wr.get(g))&&(u=y({},o),xg(u,p)),t=t.ownerDocument||t,p=t.createElement("script"),nn(p),_n(p,"link",u),t.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,hd(u,o.precedence,t));return a.instance}function hd(t,a,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=u.length?u[u.length-1]:null,g=p,C=0;C title"):null)}function lR(t,a,o){if(o===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(t=a.disabled,typeof a.precedence=="string"&&t==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Uw(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function cR(t,a,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var p=lo(u.href),g=a.querySelector(Wl(p));if(g){a=g._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=gd.bind(t),a.then(t,t)),o.state.loading|=4,o.instance=g,nn(g);return}g=a.ownerDocument||a,u=jw(u),(p=wr.get(p))&&Ag(u,p),g=g.createElement("link"),nn(g);var C=g;C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),o.instance=g}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(t.count++,o=gd.bind(t),a.addEventListener("load",o),a.addEventListener("error",o))}}var Tg=0;function uR(t,a){return t.stylesheets&&t.count===0&&yd(t,t.stylesheets),0Tg?50:800)+a);return t.unsuspend=o,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(p)}}:null}function gd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)yd(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var md=null;function yd(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,md=new Map,a.forEach(dR,t),md=null,gd.call(t))}function dR(t,a){if(!(a.state.loading&4)){var o=md.get(t);if(o)var u=o.get(null);else{o=new Map,md.set(t,o);for(var p=t.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Td.exports=o0(),Td.exports}var Od=l0();const Ld=ra(Od),ho=[],c0=50;let $d=!1;function qg(){try{return window.G7Core?.devTools}catch{return}}function ss(s,e,n){const r=qg();if($d&&r?.isEnabled?.()){r.trackLog?.(s,e,n);return}$d||(s==="error"||s==="warn")&&ho.length{n.isDebugEnabled()&&console.log(e,...r),ss("log",s,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),ss("warn",s,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),ss("error",s,r)}}}po.getInstance();const Gg="extension",os="extensionless",Fg="file";function u0(){const s=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===os)return os;const n=s?.assetUrlMode;return n===os||n===Gg?n:s?.settings?.general?.asset_url_mode===os?os:Gg}function Nd(){return u0()===os}function d0(s,e,n){return Id("templates",s,e,n)}function f0(s,e){const n=e.replace(/^\/+/,"").replace(/\/+$/,""),r=encodeURIComponent(s),i=go(`templates/${s}/assets/${n}`);return i!==null?i:`/api/templates/assets/${r}/${n}`}function h0(s,e,n){return Id("modules",s,e,n)}function p0(s,e,n){return Id("plugins",s,e,n)}function Id(s,e,n,r){const i=n.replace(/^\/+/,""),l=encodeURIComponent(e);if(!Nd())return`/api/${s}/assets/${l}/${i}${y0(r)}`;let c=`${Fg}=${encodeURIComponent(i)}`;return r!=null&&r!==""&&(c+=`&v=${r}`),`/api/${s}/assets/${l}?${c}`}function Ur(s,e,n,r){const i=s.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=Nd()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Vg(){const s=globalThis?.G7Config?.staticBase;return typeof s=="string"&&s!==""?s.replace(/\/+$/,""):null}function g0(){const s=Vg();if(!s)return null;const e=s.match(/\/(\d+)$/);return e?Number(e[1]):null}function go(s,e){const n=Vg();if(!n)return null;const r=s.replace(/^\/+/,"");return e!==void 0&&e>0&&e!==g0()?`${n.replace(/\/\d+$/,"")}/${e}/${r}`:`${n}/${r}`}function jd(s){if(!s)return null;const e=globalThis?.location?.origin,r=(e&&s.startsWith(e)?s.slice(e.length):s).match(/^\/build\/ext\/(\d+)\/(.+)$/);if(!r)return null;const i=r[1],l=r[2].split("?")[0],c=l.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);if(c){const[,h,m,y]=c;return`/api/${h}/assets/${m}/${y}?v=${i}`}const d=l.match(/^bundles\/(modules|plugins)\.(js|css)$/);if(d)return`/api/${d[1]}/bundle.${d[2]}?v=${i}`;const f=l.match(/^templates\/([^/]+)\/(routes\.json|components\.json|lang\/([a-zA-Z-]+)\.json)$/);if(f){const[,h,m]=f,y=m.replace(/\.json$/,"");return`/api/templates/${h}/${y}.json?v=${i}`}return null}function Ln(s){if(!s||!Nd())return s;const e=globalThis?.location?.origin,n=e&&s.startsWith(e)?s.slice(e.length):s;if(!n.startsWith("/api/"))return s;const[r,i]=m0(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return Kg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,h,m]=c,y=`${Fg}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${h}?${y}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?Kg(d[1],i):s}function m0(s){const e=s.indexOf("?");return e===-1?[s,""]:[s.slice(0,e),s.slice(e+1)]}function Kg(s,e){return e?`${s}?${e}`:s}function y0(s){return s==null||s===""?"":`?v=${s}`}const aa=pt("networkResilience"),Hd=2,zd=300,Pd=2e3,b0=15e3;function Ud(s){return s?.name==="AbortError"}function Wg(s){return Ud(s)?!1:s instanceof TypeError}let ec=!1,Yg=!1;function tc(){return ec}function v0(){typeof window>"u"||Yg||(Yg=!0,window.addEventListener("pagehide",()=>{ec=!0}),window.addEventListener("pageshow",s=>{s.persisted&&(ec=!1)}),window.addEventListener("beforeunload",()=>{ec=!0}))}function Bd(s,e,n){const r=Math.min(e*Math.pow(2,s),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function qd(s){return new Promise(e=>setTimeout(e,s))}async function nc(s,e={}){const{retries:n=Hd,baseDelayMs:r=zd,maxDelayMs:i=Pd,timeoutMs:l=b0,label:c=s,init:d}=e,f=n+1;let h;for(let m=0;m0?new AbortController:null;try{const _={...d};if(S){const A=d?.signal;A&&(A.aborted?S.abort():A.addEventListener("abort",()=>S.abort(),{once:!0})),_.signal=S.signal,v=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(s,_)}catch(_){if(h=_,Ud(_)&&!y||!(y||Wg(_)))throw _;if(tc())throw aa.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw aa.warn(`All ${f} attempts failed: ${c}`,_),_;const D=Bd(m,r,i);aa.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${D}ms: ${c}`),await qd(D)}finally{v!==void 0&&clearTimeout(v)}}throw h}async function Cr(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=s,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=()=>r(new Error(`Failed to load script: ${s}`)),document.head.appendChild(i)})}async function ia(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{s.onload=()=>e(),s.onerror=()=>n(new Error(`Failed to load stylesheet: ${s.href}`))})}async function rc(s,e,n={}){if(!s)return nc(e,n);try{const r=await fetch(s,n.init);if(r.ok){const i=await r.text();try{return JSON.parse(i),new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return console.warn(`[fetchStaticFirst] Static fast path returned malformed JSON — falling back to API: ${s}`),nc(e,n)}}console.warn(`[fetchStaticFirst] Static fast path miss (${r.status}) — falling back to API: ${s}`)}catch(r){console.warn(`[fetchStaticFirst] Static fast path fetch failed — falling back to API: ${s}`,r)}return nc(e,n)}const Br=pt("ComponentRegistry");class pn extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="ComponentRegistryError"}}const Qn=class Qn{constructor(){M(this,"registry",{});M(this,"manifest",null);M(this,"cacheVersion",0);M(this,"loadingState","idle");M(this,"error",null);M(this,"templateId",null);M(this,"templateType",null)}static getInstance(){return Qn.instance||(Qn.instance=new Qn),Qn.instance}static createIsolatedInstance(){return new Qn}static resetInstance(){Qn.instance=null}async loadComponents(e,n,r=0){if(this.loadingState==="loading")throw new pn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Br.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.cacheVersion=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Br.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(i){throw this.loadingState="error",this.error=i instanceof Error?i:new Error(String(i)),new pn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}:v${this.cacheVersion||0}`;if(Qn.manifestCache.has(e)){this.manifest=Qn.manifestCache.get(e),Br.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Ur(`/api/templates/${this.templateId}/components`,"json",this.cacheVersion>0?this.cacheVersion:null),r=await rc(this.cacheVersion>0?go(`templates/${this.templateId}/components.json`,this.cacheVersion):null,n,{label:"components.json"});if(!r.ok)throw new pn(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Qn.manifestCache.set(e,i),Br.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof pn?e:new pn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new pn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new pn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new pn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new pn(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Br.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new pn(`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),Br.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof pn?e:new pn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new pn("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 pn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Br.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,r){this.registry[e]&&Br.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:r},Br.log(`[ComponentRegistry] Registered component: ${e} (${r.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,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.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,Br.log("Registry cleared")}};M(Qn,"instance",null),M(Qn,"manifestCache",new Map);let Er=Qn;const Xg=pt("TranslationEngine");class Gd extends Error{constructor(n,r,i){super(n);M(this,"key");M(this,"locale");this.key=r,this.locale=i,this.name="TranslationError"}}const zn=class zn{constructor(e={}){M(this,"cache",new Map);M(this,"translations",new Map);M(this,"options");M(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return zn.instance||(zn.instance=new zn(e)),zn.instance}static resetInstance(){zn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Xg.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/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=Ur(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=!i&&this.cacheVersion>0?go(`templates/${e}/lang/${n}.json`,this.cacheVersion):null,h=f!==null?await rc(f,d,{label:`lang/${n}.json`}):await fetch(d);if(!h.ok)throw new Gd(`Failed to load translations: ${h.statusText}`,void 0,n);const y=await h.json();return this.saveToCache(l,y),this.translations.set(l,y),y}catch(c){throw new Gd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,r)),i===d)break;c++}return i.replace(zn.TRANSLATION_PATTERN,(d,f,h)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(h);return this.translate(f,n,m,r)+y})}translate(e,n,r,i){const l=this.getTranslation(e,n),c=r&&this.cleanParamsStr(r);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${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=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const h=this.getNestedValue(f,e);if(h!==null)return h}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=r.split(".");let f=c;for(let h=0;h(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(zn.PARAM_PATTERN);for(const f of d){const[,h,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(v,S)=>l[parseInt(S,10)]);r[h.trim()]=this.resolveParamValue(y.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const l=of.evaluateExpression(r,n);return String(l??"")}catch(l){return Xg.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);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 r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}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[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};M(zn,"instance",null),M(zn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),M(zn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),M(zn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let Oa=zn,Fd=null;function E0(s){return Fd||(Fd=new Oa(s)),Fd}const Jg=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:Oa,TranslationError:Gd,getTranslationEngine:E0},Symbol.toStringTag,{value:"Module"})),ls=pt("PipeRegistry");function Qg(s,e){const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0"),d=String(s.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(s.getMonth()+1)).replace("DD",i).replace("D",String(s.getDate())).replace("HH",l).replace("H",String(s.getHours())).replace("mm",c).replace("m",String(s.getMinutes())).replace("ss",d).replace("s",String(s.getSeconds()))}function _0(s,e="ko"){const r=new Date().getTime()-s.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),h=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}주 전`:h<12?`${h}개월 전`:`${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`:h<12?`${h} month${h===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function Vd(s){if(s==null)return null;if(s instanceof Date)return s;if(typeof s=="number")return new Date(s);if(typeof s=="string"){const e=new Date(s);return isNaN(e.getTime())?null:e}return null}const mo={date:{fn:(s,e="YYYY-MM-DD")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(s,e="YYYY-MM-DD HH:mm")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(s,e="ko")=>{const n=Vd(s);return n?_0(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(s,e)=>{const n=Number(s);if(isNaN(n))return String(s??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(s,e=100,n="...")=>typeof s!="string"?String(s??""):s.length<=e?s:s.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:s=>typeof s!="string"?String(s??""):s.toUpperCase(),description:"대문자 변환"},lowercase:{fn:s=>typeof s!="string"?String(s??""):s.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:s=>typeof s!="string"?String(s??""):s.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(s,e="")=>s==null||s===""?e:s,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(s,e)=>s??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:s=>{if(Array.isArray(s))return s[0]},description:"배열의 첫 번째 요소"},last:{fn:s=>{if(Array.isArray(s))return s[s.length-1]},description:"배열의 마지막 요소"},join:{fn:(s,e=", ")=>Array.isArray(s)?s.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:s=>Array.isArray(s)||typeof s=="string"?s.length:0,description:"배열/문자열 길이"},filterBy:{fn:(s,e,n)=>Array.isArray(s)?Array.isArray(e)?s.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):s:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:s=>s==null||typeof s!="object"?[]:Object.keys(s),description:"객체의 키 배열"},values:{fn:s=>s==null||typeof s!="object"?[]:Object.values(s),description:"객체의 값 배열"},json:{fn:(s,e)=>{try{return JSON.stringify(s,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(s,e)=>s==null?"":typeof s=="string"?s:typeof s!="object"?String(s):s[e||"ko"]||s.ko||s.en||Object.values(s)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},cs=new Map,Di=class Di{static getInstance(){return Di.instance||(Di.instance=new Di),Di.instance}register(e,n,r){if(mo[e]){ls.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}cs.set(e,{fn:n,description:r}),ls.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(mo[e])return ls.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=cs.delete(e);return n&&ls.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=mo[e];return n?n.fn:cs.get(e)?.fn}has(e){return!!mo[e]||cs.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return ls.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return ls.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(mo))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of cs.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){cs.clear()}};M(Di,"instance",null);let ac=Di;ac.getInstance();function A0(s){const e=s.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let c="",d=null,f=0;for(let h=0;h0?i[h-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(Zg(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(Zg(c.trim())),{name:r,args:l}}function Zg(s){if(s==="null")return null;if(s==="undefined")return;if(s==="true")return!0;if(s==="false")return!1;const e=Number(s);return!isNaN(e)&&s!==""?e:s}function x0(s){const e=[];let n="",r=null,i=0;for(let l=0;l0?s[l-1]:"",f=l0?s[r-1]:"",c=r0){r--;continue}return null}}return r===0?e.trim():null}function k0(s){const e=[];if(typeof s!="string")return e;for(let n=0;n0){i--;continue}if(s[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:s.slice(n+2,l)}),n=l+1)}return e}function yo(s){return/[?:|&!+\-*/<>=()[\]{}]/.test(s)}function em(s){const e=typeof s=="string"?s.trim():"";return e===""?"empty":Kd.has(e)?"literal":Wn(e)?"pipe":yo(e)?"expression":"path"}function Wd(s,e,n,r){const i=typeof s=="string"?s.trim():"",l=em(i),c=r?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){r?.onEmpty?.(s);return}if(l==="literal")return Kd.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,r?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,r?.trackingInfo):n.resolve(i,e,c,r?.trackingInfo)}catch(d){if(r?.onError)return r.onError(d,i);throw d}}const sr="raw:";function tm(s){return s.startsWith(sr)?s.slice(sr.length):s}const bo="﷐",Si="﷑",$a="﷒";function vo(s){return bo+s+Si}function ic(s){return s.length>=2&&s.charCodeAt(0)===64976&&s.charCodeAt(s.length-1)===64977}function sc(s){return s.includes(bo)}function Yd(s){return s.slice(1,-1)}function us(s){if(typeof s=="string")return vo(s);if(Array.isArray(s))return s.map(us);if(s&&typeof s=="object"){const e={};for(const[n,r]of Object.entries(s))e[n]=us(r);return e}return s}function Ma(s){if(typeof s=="string")return ic(s)?Yd(s):sc(s)||s.includes(Si)?s.split(bo).join("").split(Si).join(""):s;if(Array.isArray(s)){let e=!1;const n=s.map(r=>{const i=Ma(r);return i!==r&&(e=!0),i});return e?n:s}if(s&&typeof s=="object"){if(s.$$typeof!==void 0)return s;let e=!1;const n={};for(const[r,i]of Object.entries(s)){const l=Ma(i);l!==i&&(e=!0),n[r]=l}return e?n:s}return s}const So=new Set(["constructor","__proto__","prototype","__lookupGetter__","__lookupSetter__","__defineGetter__","__defineSetter__"]),R0=new Set(["Function","eval","globalThis","window","self","document","require","module","process","Reflect","Proxy","WebAssembly","import","constructor"]);function nm(s,e){if(s!==null&&(typeof s=="object"||typeof s=="function")&&rm.has(s))throw new Error(`Object.${e} on a built-in global object is not allowed`);return s}const D0=Object.freeze({keys:Object.keys,values:Object.values,entries:Object.entries,assign:(s,...e)=>{const n=nm(s,"assign");for(const r of e)if(r!=null)for(const i of Object.keys(r)){if(So.has(i))throw new Error(`Access to "${i}" is forbidden`);rf(n,i,r[i])}return n},freeze:s=>Object.freeze(nm(s,"freeze")),fromEntries:Object.fromEntries,create:Object.create,isFrozen:Object.isFrozen}),Xd={Math,JSON,Date,Array,Object:D0,Number,String,Boolean,Set,Map,WeakSet,WeakMap,parseInt,parseFloat,isNaN,isFinite},Jd={Date,Set,Map,WeakSet,WeakMap,Array,Number,String,Boolean,Object},rm=new Set([...Object.values(Xd),...Object.values(Jd)].filter(s=>s!==null&&(typeof s=="object"||typeof s=="function"))),oc=new Set(["function"]),_r=Symbol("short-circuit");class Qd{constructor(e){M(this,"value");this.value=e}}class Zd{}class ef{}function O0(s){return/[A-Za-z_$]/.test(s)}function L0(s){return/[A-Za-z0-9_$]/.test(s)}function wi(s){return s>="0"&&s<="9"}function $0(s,e,n){let r=e+1;for(;r0;){const h=s[n];if(h==="{")f++,n++;else if(h==="}"){if(f--,f===0)break;n++}else h==='"'||h==="'"?n=$0(s,n,h):h==="`"?n=am(s,n).end:n++}if(f!==0)throw new Error("Unterminated ${...} in template literal");i.push(s.slice(d,n)),n++;continue}l+=c,n++}throw new Error(`Unterminated template literal at position ${e}`)}function M0(s){const e=[];let n=0;const r=s.length,i=l=>n+l>>=0,t===0?32:31-(V(t)/ie|0)|0}var Z=256,ve=262144,pe=4194304;function Ee(t){var a=t&42;if(a!==0)return a;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 xe(t,a,o){var u=t.pendingLanes;if(u===0)return 0;var p=0,g=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var R=u&134217727;return R!==0?(u=R&~g,u!==0?p=Ee(u):(C&=R,C!==0?p=Ee(C):o||(o=R&~t,o!==0&&(p=Ee(o))))):(R=u&~g,R!==0?p=Ee(R):C!==0?p=Ee(C):o||(o=u&~t,o!==0&&(p=Ee(o)))),p===0?0:a!==0&&a!==p&&(a&g)===0&&(g=p&-p,o=a&-a,g>=o||g===32&&(o&4194048)!==0)?a:p}function Ke(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function ke(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+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 a+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 Me(){var t=pe;return pe<<=1,(pe&62914560)===0&&(pe=4194304),t}function Re(t){for(var a=[],o=0;31>o;o++)a.push(t);return a}function tt(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Pe(t,a,o,u,p,g){var C=t.pendingLanes;t.pendingLanes=o,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=o,t.entangledLanes&=o,t.errorRecoveryDisabledLanes&=o,t.shellSuspendCounter=0;var R=t.entanglements,P=t.expirationTimes,X=t.hiddenUpdates;for(o=C&~o;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Sh=/[\n"\\]/g;function Bn(t){return t.replace(Sh,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Os(t,a,o,u,p,g,C,R){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),a!=null?C==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+On(a)):t.value!==""+On(a)&&(t.value=""+On(a)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),a!=null?ha(t,C,On(a)):o!=null?ha(t,C,On(o)):u!=null&&t.removeAttribute("value"),p==null&&g!=null&&(t.defaultChecked=!!g),p!=null&&(t.checked=p&&typeof p!="function"&&typeof p!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?t.name=""+On(R):t.removeAttribute("name")}function Ii(t,a,o,u,p,g,C,R){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(t.type=g),a!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||a!=null)){il(t);return}o=o!=null?""+On(o):"",a=a!=null?""+On(a):o,R||a===t.value||(t.value=a),t.defaultValue=a}u=u??p,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=R?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),il(t)}function ha(t,a,o){a==="number"&&Va(t.ownerDocument)===t||t.defaultValue===""+o||(t.defaultValue=""+o)}function Ka(t,a,o,u){if(t=t.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ul=!1;if(Nr)try{var Hi={};Object.defineProperty(Hi,"passive",{get:function(){ul=!0}}),window.addEventListener("test",Hi,Hi),window.removeEventListener("test",Hi,Hi)}catch{ul=!1}var Jr=null,dl=null,$s=null;function du(){if($s)return $s;var t,a=dl,o=a.length,u,p="value"in Jr?Jr.value:Jr.textContent,g=p.length;for(t=0;t=ne),We=" ",ft=!1;function vt(t,a){switch(t){case"keyup":return $.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var jr=!1;function Hh(t,a){switch(t){case"compositionend":return Vt(a);case"keypress":return a.which!==32?null:(ft=!0,We);case"textInput":return t=a.data,t===We&&ft?null:t;default:return null}}function bu(t,a){if(jr)return t==="compositionend"||!N&&vt(t,a)?(t=du(),$s=dl=Jr=null,jr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-t};t=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=qb(o)}}function Fb(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?Fb(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Vb(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=Va(t.document);a instanceof t.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)t=a.contentWindow;else break;a=Va(t.document)}return a}function qh(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var tk=Nr&&"documentMode"in document&&11>=document.documentMode,js=null,Gh=null,wl=null,Fh=!1;function Kb(t,a,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Fh||js==null||js!==Va(u)||(u=js,"selectionStart"in u&&qh(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}),wl&&Sl(wl,u)||(wl=u,u=ud(Gh,"onSelect"),0>=C,p-=C,Qr=1<<32-dn(a)+p|o<Ze?(ut=Ne,Ne=null):ut=Ne.sibling;var wt=J(K,Ne,Y[Ze],oe);if(wt===null){Ne===null&&(Ne=ut);break}t&&Ne&&wt.alternate===null&&a(K,Ne),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt,Ne=ut}if(Ze===Y.length)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;ZeZe?(ut=Ne,Ne=null):ut=Ne.sibling;var vi=J(K,Ne,wt.value,oe);if(vi===null){Ne===null&&(Ne=ut);break}t&&Ne&&vi.alternate===null&&a(K,Ne),F=g(vi,F,Ze),St===null?Be=vi:St.sibling=vi,St=vi,Ne=ut}if(wt.done)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;!wt.done;Ze++,wt=Y.next())wt=le(K,wt.value,oe),wt!==null&&(F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return ht&&ya(K,Ze),Be}for(Ne=u(Ne);!wt.done;Ze++,wt=Y.next())wt=te(Ne,K,Ze,wt.value,oe),wt!==null&&(t&&wt.alternate!==null&&Ne.delete(wt.key===null?Ze:wt.key),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return t&&Ne.forEach(function(wR){return a(K,wR)}),ht&&ya(K,Ze),Be}function Nt(K,F,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===x&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case S:e:{for(var Be=Y.key;F!==null;){if(F.key===Be){if(Be=Y.type,Be===x){if(F.tag===7){o(K,F.sibling),oe=p(F,Y.props.children),oe.return=K,K=oe;break e}}else if(F.elementType===Be||typeof Be=="object"&&Be!==null&&Be.$$typeof===W&&es(Be)===F.type){o(K,F.sibling),oe=p(F,Y.props),Tl(oe,Y),oe.return=K,K=oe;break e}o(K,F);break}else a(K,F);F=F.sibling}Y.type===x?(oe=Yi(Y.props.children,K.mode,oe,Y.key),oe.return=K,K=oe):(oe=Tu(Y.type,Y.key,Y.props,null,K.mode,oe),Tl(oe,Y),oe.return=K,K=oe)}return C(K);case _:e:{for(Be=Y.key;F!==null;){if(F.key===Be)if(F.tag===4&&F.stateNode.containerInfo===Y.containerInfo&&F.stateNode.implementation===Y.implementation){o(K,F.sibling),oe=p(F,Y.children||[]),oe.return=K,K=oe;break e}else{o(K,F);break}else a(K,F);F=F.sibling}oe=Qh(Y,K.mode,oe),oe.return=K,K=oe}return C(K);case W:return Y=es(Y),Nt(K,F,Y,oe)}if(Et(Y))return Oe(K,F,Y,oe);if(Ie(Y)){if(Be=Ie(Y),typeof Be!="function")throw Error(r(150));return Y=Be.call(Y),Ge(K,F,Y,oe)}if(typeof Y.then=="function")return Nt(K,F,Mu(Y),oe);if(Y.$$typeof===k)return Nt(K,F,Du(K,Y),oe);Nu(K,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,F!==null&&F.tag===6?(o(K,F.sibling),oe=p(F,Y),oe.return=K,K=oe):(o(K,F),oe=Jh(Y,K.mode,oe),oe.return=K,K=oe),C(K)):o(K,F)}return function(K,F,Y,oe){try{xl=0;var Be=Nt(K,F,Y,oe);return Ws=null,Be}catch(Ne){if(Ne===Ks||Ne===Lu)throw Ne;var St=er(29,Ne,null,K.mode);return St.lanes=oe,St.return=K,St}}}var ns=mv(!0),yv=mv(!1),ni=!1;function up(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function dp(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ri(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ai(t,a,o){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(_t&2)!==0){var p=u.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),u.pending=a,a=xu(t),ev(t,null,o),a}return Au(t,u,a,o),xu(t)}function kl(t,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}function fp(t,a){var o=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var p=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var C={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?p=g=C:g=g.next=C,o=o.next}while(o!==null);g===null?p=g=a:g=g.next=a}else p=g=a;o={baseState:u.baseState,firstBaseUpdate:p,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},t.updateQueue=o;return}t=o.lastBaseUpdate,t===null?o.firstBaseUpdate=a:t.next=a,o.lastBaseUpdate=a}var hp=!1;function Rl(){if(hp){var t=Vs;if(t!==null)throw t}}function Dl(t,a,o,u){hp=!1;var p=t.updateQueue;ni=!1;var g=p.firstBaseUpdate,C=p.lastBaseUpdate,R=p.shared.pending;if(R!==null){p.shared.pending=null;var P=R,X=P.next;P.next=null,C===null?g=X:C.next=X,C=P;var re=t.alternate;re!==null&&(re=re.updateQueue,R=re.lastBaseUpdate,R!==C&&(R===null?re.firstBaseUpdate=X:R.next=X,re.lastBaseUpdate=P))}if(g!==null){var le=p.baseState;C=0,re=X=P=null,R=g;do{var J=R.lane&-536870913,te=J!==R.lane;if(te?(ct&J)===J:(u&J)===J){J!==0&&J===Fs&&(hp=!0),re!==null&&(re=re.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Oe=t,Ge=R;J=a;var Nt=o;switch(Ge.tag){case 1:if(Oe=Ge.payload,typeof Oe=="function"){le=Oe.call(Nt,le,J);break e}le=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ge.payload,J=typeof Oe=="function"?Oe.call(Nt,le,J):Oe,J==null)break e;le=y({},le,J);break e;case 2:ni=!0}}J=R.callback,J!==null&&(t.flags|=64,te&&(t.flags|=8192),te=p.callbacks,te===null?p.callbacks=[J]:te.push(J))}else te={lane:J,tag:R.tag,payload:R.payload,callback:R.callback,next:null},re===null?(X=re=te,P=le):re=re.next=te,C|=J;if(R=R.next,R===null){if(R=p.shared.pending,R===null)break;te=R,R=te.next,te.next=null,p.lastBaseUpdate=te,p.shared.pending=null}}while(!0);re===null&&(P=le),p.baseState=P,p.firstBaseUpdate=X,p.lastBaseUpdate=re,g===null&&(p.shared.lanes=0),ci|=C,t.lanes=C,t.memoizedState=le}}function bv(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function vv(t,a){var o=t.callbacks;if(o!==null)for(t.callbacks=null,t=0;tg?g:8;var C=Q.T,R={};Q.T=R,Lp(t,!1,a,o);try{var P=p(),X=Q.S;if(X!==null&&X(R,P),P!==null&&typeof P=="object"&&typeof P.then=="function"){var re=uk(P,u);$l(t,a,re,ir(t))}else $l(t,a,u,ir(t))}catch(le){$l(t,a,{then:function(){},status:"rejected",reason:le},ir())}finally{ue.p=g,C!==null&&R.types!==null&&(C.types=R.types),Q.T=C}}function mk(){}function Dp(t,a,o,u){if(t.tag!==5)throw Error(r(476));var p=Jv(t).queue;Xv(t,p,a,De,o===null?mk:function(){return Qv(t),o(u)})}function Jv(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:De,baseState:De,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:De},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:o},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function Qv(t){var a=Jv(t);a.next===null&&(a=t.alternate.memoizedState),$l(t,a.next.queue,{},ir())}function Op(){return Cn(Xl)}function Zv(){return en().memoizedState}function eS(){return en().memoizedState}function yk(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var o=ir();t=ri(o);var u=ai(a,t,o);u!==null&&(Kn(u,a,o),kl(u,a,o)),a={cache:sp()},t.payload=a;return}a=a.return}}function bk(t,a,o){var u=ir();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Fu(t)?nS(a,o):(o=Yh(t,a,o,u),o!==null&&(Kn(o,t,u),rS(o,a,u)))}function tS(t,a,o){var u=ir();$l(t,a,o,u)}function $l(t,a,o,u){var p={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Fu(t))nS(a,p);else{var g=t.alternate;if(t.lanes===0&&(g===null||g.lanes===0)&&(g=a.lastRenderedReducer,g!==null))try{var C=a.lastRenderedState,R=g(C,o);if(p.hasEagerState=!0,p.eagerState=R,Zn(R,C))return Au(t,a,p,0),It===null&&_u(),!1}catch{}if(o=Yh(t,a,p,u),o!==null)return Kn(o,t,u),rS(o,a,u),!0}return!1}function Lp(t,a,o,u){if(u={lane:2,revertLane:ug(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Fu(t)){if(a)throw Error(r(479))}else a=Yh(t,o,u,2),a!==null&&Kn(a,t,2)}function Fu(t){var a=t.alternate;return t===Je||a!==null&&a===Je}function nS(t,a){Xs=Hu=!0;var o=t.pending;o===null?a.next=a:(a.next=o.next,o.next=a),t.pending=a}function rS(t,a,o){if((o&4194048)!==0){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}var Ml={readContext:Cn,use:Uu,useCallback:Xt,useContext:Xt,useEffect:Xt,useImperativeHandle:Xt,useLayoutEffect:Xt,useInsertionEffect:Xt,useMemo:Xt,useReducer:Xt,useRef:Xt,useState:Xt,useDebugValue:Xt,useDeferredValue:Xt,useTransition:Xt,useSyncExternalStore:Xt,useId:Xt,useHostTransitionStatus:Xt,useFormState:Xt,useActionState:Xt,useOptimistic:Xt,useMemoCache:Xt,useCacheRefresh:Xt};Ml.useEffectEvent=Xt;var aS={readContext:Cn,use:Uu,useCallback:function(t,a){return In().memoizedState=[t,a===void 0?null:a],t},useContext:Cn,useEffect:Uv,useImperativeHandle:function(t,a,o){o=o!=null?o.concat([t]):null,qu(4194308,4,Fv.bind(null,a,t),o)},useLayoutEffect:function(t,a){return qu(4194308,4,t,a)},useInsertionEffect:function(t,a){qu(4,2,t,a)},useMemo:function(t,a){var o=In();a=a===void 0?null:a;var u=t();if(rs){Rn(!0);try{t()}finally{Rn(!1)}}return o.memoizedState=[u,a],u},useReducer:function(t,a,o){var u=In();if(o!==void 0){var p=o(a);if(rs){Rn(!0);try{o(a)}finally{Rn(!1)}}}else p=a;return u.memoizedState=u.baseState=p,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:p},u.queue=t,t=t.dispatch=bk.bind(null,Je,t),[u.memoizedState,t]},useRef:function(t){var a=In();return t={current:t},a.memoizedState=t},useState:function(t){t=Ap(t);var a=t.queue,o=tS.bind(null,Je,a);return a.dispatch=o,[t.memoizedState,o]},useDebugValue:kp,useDeferredValue:function(t,a){var o=In();return Rp(o,t,a)},useTransition:function(){var t=Ap(!1);return t=Xv.bind(null,Je,t.queue,!0,!1),In().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,o){var u=Je,p=In();if(ht){if(o===void 0)throw Error(r(407));o=o()}else{if(o=a(),It===null)throw Error(r(349));(ct&127)!==0||Av(u,a,o)}p.memoizedState=o;var g={value:o,getSnapshot:a};return p.queue=g,Uv(Tv.bind(null,u,g,t),[t]),u.flags|=2048,Qs(9,{destroy:void 0},xv.bind(null,u,g,o,a),null),o},useId:function(){var t=In(),a=It.identifierPrefix;if(ht){var o=Zr,u=Qr;o=(u&~(1<<32-dn(u)-1)).toString(32)+o,a="_"+a+"R_"+o,o=zu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?C.createElement(p,{is:u.is}):C.createElement(p)}}g[Ft]=a,g[Dn]=u;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)g.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=g;e:switch(_n(g,p,u),p){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ea(a)}}return Ut(a),Vp(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,o),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==u&&Ea(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(t=se.current,qs(a)){if(t=a.stateNode,o=a.memoizedProps,u=null,p=wn,p!==null)switch(p.tag){case 27:case 5:u=p.memoizedProps}t[Ft]=a,t=!!(t.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||Ew(t.nodeValue,o)),t||ei(a,!0)}else t=dd(t).createTextNode(u),t[Ft]=a,a.stateNode=t}return Ut(a),null;case 31:if(o=a.memoizedState,t===null||t.memoizedState!==null){if(u=qs(a),o!==null){if(t===null){if(!u)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[Ft]=a}else Xi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),t=!1}else o=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),t=!0;if(!t)return a.flags&256?(nr(a),a):(nr(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Ut(a),null;case 13:if(u=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(p=qs(a),u!==null&&u.dehydrated!==null){if(t===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else Xi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),p=!1}else p=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(nr(a),a):(nr(a),null)}return nr(a),(a.flags&128)!==0?(a.lanes=o,a):(o=u!==null,t=t!==null&&t.memoizedState!==null,o&&(u=a.child,p=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(p=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==p&&(u.flags|=2048)),o!==t&&o&&(a.child.flags|=8192),Xu(a,a.updateQueue),Ut(a),null);case 4:return Te(),t===null&&pg(a.stateNode.containerInfo),Ut(a),null;case 10:return va(a.type),Ut(a),null;case 19:if(T(Zt),u=a.memoizedState,u===null)return Ut(a),null;if(p=(a.flags&128)!==0,g=u.rendering,g===null)if(p)Il(u,!1);else{if(Jt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(g=ju(t),g!==null){for(a.flags|=128,Il(u,!1),t=g.updateQueue,a.updateQueue=t,Xu(a,t),a.subtreeFlags=0,t=o,o=a.child;o!==null;)tv(o,t),o=o.sibling;return fe(Zt,Zt.current&1|2),ht&&ya(a,u.treeForkCount),a.child}t=t.sibling}u.tail!==null&&Ot()>td&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304)}else{if(!p)if(t=ju(g),t!==null){if(a.flags|=128,p=!0,t=t.updateQueue,a.updateQueue=t,Xu(a,t),Il(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!ht)return Ut(a),null}else 2*Ot()-u.renderingStartTime>td&&o!==536870912&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304);u.isBackwards?(g.sibling=a.child,a.child=g):(t=u.last,t!==null?t.sibling=g:a.child=g,u.last=g)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ot(),t.sibling=null,o=Zt.current,fe(Zt,p?o&1|2:o&1),ht&&ya(a,u.treeForkCount),t):(Ut(a),null);case 22:case 23:return nr(a),gp(),u=a.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(o&536870912)!==0&&(a.flags&128)===0&&(Ut(a),a.subtreeFlags&6&&(a.flags|=8192)):Ut(a),o=a.updateQueue,o!==null&&Xu(a,o.retryQueue),o=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==o&&(a.flags|=2048),t!==null&&T(Zi),null;case 24:return o=null,t!==null&&(o=t.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),va(rn),Ut(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Ek(t,a){switch(ep(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return va(rn),Te(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return xt(a),null;case 31:if(a.memoizedState!==null){if(nr(a),a.alternate===null)throw Error(r(340));Xi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(nr(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Xi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return T(Zt),null;case 4:return Te(),null;case 10:return va(a.type),null;case 22:case 23:return nr(a),gp(),t!==null&&T(Zi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return va(rn),null;case 25:return null;default:return null}}function kS(t,a){switch(ep(a),a.tag){case 3:va(rn),Te();break;case 26:case 27:case 5:xt(a);break;case 4:Te();break;case 31:a.memoizedState!==null&&nr(a);break;case 13:nr(a);break;case 19:T(Zt);break;case 10:va(a.type);break;case 22:case 23:nr(a),gp(),t!==null&&T(Zi);break;case 24:va(rn)}}function jl(t,a){try{var o=a.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var p=u.next;o=p;do{if((o.tag&t)===t){u=void 0;var g=o.create,C=o.inst;u=g(),C.destroy=u}o=o.next}while(o!==p)}}catch(R){kt(a,a.return,R)}}function oi(t,a,o){try{var u=a.updateQueue,p=u!==null?u.lastEffect:null;if(p!==null){var g=p.next;u=g;do{if((u.tag&t)===t){var C=u.inst,R=C.destroy;if(R!==void 0){C.destroy=void 0,p=a;var P=o,X=R;try{X()}catch(re){kt(p,P,re)}}}u=u.next}while(u!==g)}}catch(re){kt(a,a.return,re)}}function RS(t){var a=t.updateQueue;if(a!==null){var o=t.stateNode;try{vv(a,o)}catch(u){kt(t,t.return,u)}}}function DS(t,a,o){o.props=as(t.type,t.memoizedProps),o.state=t.memoizedState;try{o.componentWillUnmount()}catch(u){kt(t,a,u)}}function Hl(t,a){try{var o=t.ref;if(o!==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 o=="function"?t.refCleanup=o(u):o.current=u}}catch(p){kt(t,a,p)}}function ea(t,a){var o=t.ref,u=t.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(p){kt(t,a,p)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(p){kt(t,a,p)}else o.current=null}function OS(t){var a=t.type,o=t.memoizedProps,u=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(p){kt(t,t.return,p)}}function Kp(t,a,o){try{var u=t.stateNode;Fk(u,t.type,o,a),u[Dn]=a}catch(p){kt(t,t.return,p)}}function LS(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&pi(t.type)||t.tag===4}function Wp(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||LS(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&&pi(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 Yp(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(t,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(t),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=Mr));else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode,a=null),t=t.child,t!==null))for(Yp(t,a,o),t=t.sibling;t!==null;)Yp(t,a,o),t=t.sibling}function Ju(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?o.insertBefore(t,a):o.appendChild(t);else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode),t=t.child,t!==null))for(Ju(t,a,o),t=t.sibling;t!==null;)Ju(t,a,o),t=t.sibling}function $S(t){var a=t.stateNode,o=t.memoizedProps;try{for(var u=t.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);_n(a,u,o),a[Ft]=t,a[Dn]=o}catch(g){kt(t,t.return,g)}}var _a=!1,on=!1,Xp=!1,MS=typeof WeakSet=="function"?WeakSet:Set,yn=null;function _k(t,a){if(t=t.containerInfo,yg=bd,t=Vb(t),qh(t)){if("selectionStart"in t)var o={start:t.selectionStart,end:t.selectionEnd};else e:{o=(o=t.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var p=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var C=0,R=-1,P=-1,X=0,re=0,le=t,J=null;t:for(;;){for(var te;le!==o||p!==0&&le.nodeType!==3||(R=C+p),le!==g||u!==0&&le.nodeType!==3||(P=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(te=le.firstChild)!==null;)J=le,le=te;for(;;){if(le===t)break t;if(J===o&&++X===p&&(R=C),J===g&&++re===u&&(P=C),(te=le.nextSibling)!==null)break;le=J,J=le.parentNode}le=te}o=R===-1||P===-1?null:{start:R,end:P}}else o=null}o=o||{start:0,end:0}}else o=null;for(bg={focusedElem:t,selectionRange:o},bd=!1,yn=a;yn!==null;)if(a=yn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,yn=t;else for(;yn!==null;){switch(a=yn,g=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(o=0;o title"))),_n(g,u,o),g[Ft]=t,nn(g),u=g;break e;case"link":var C=Pw("link","href",p).get(u+(o.href||""));if(C){for(var R=0;RNt&&(C=Nt,Nt=Ge,Ge=C);var K=Gb(R,Ge),F=Gb(R,Nt);if(K&&F&&(te.rangeCount!==1||te.anchorNode!==K.node||te.anchorOffset!==K.offset||te.focusNode!==F.node||te.focusOffset!==F.offset)){var Y=le.createRange();Y.setStart(K.node,K.offset),te.removeAllRanges(),Ge>Nt?(te.addRange(Y),te.extend(F.node,F.offset)):(Y.setEnd(F.node,F.offset),te.addRange(Y))}}}}for(le=[],te=R;te=te.parentNode;)te.nodeType===1&&le.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;Ro?32:o,Q.T=null,o=rg,rg=null;var g=di,C=Ra;if(hn=0,ro=di=null,Ra=0,(_t&6)!==0)throw Error(r(331));var R=_t;if(_t|=4,FS(g.current),BS(g,g.current,C,o),_t=R,Gl(0,!1),un&&typeof un.onPostCommitFiberRoot=="function")try{un.onPostCommitFiberRoot(fr,g)}catch{}return!0}finally{ue.p=p,Q.T=u,cw(t,a)}}function dw(t,a,o){a=gr(o,a),a=Ip(t.stateNode,a,2),t=ai(t,a,2),t!==null&&(tt(t,2),ta(t))}function kt(t,a,o){if(t.tag===3)dw(t,t,o);else for(;a!==null;){if(a.tag===3){dw(a,t,o);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ui===null||!ui.has(u))){t=gr(o,t),o=fS(2),u=ai(a,o,2),u!==null&&(hS(o,u,a,t),tt(u,2),ta(u));break}}a=a.return}}function og(t,a,o){var u=t.pingCache;if(u===null){u=t.pingCache=new Tk;var p=new Set;u.set(a,p)}else p=u.get(a),p===void 0&&(p=new Set,u.set(a,p));p.has(o)||(Zp=!0,p.add(o),t=Lk.bind(null,t,a,o),a.then(t,t))}function Lk(t,a,o){var u=t.pingCache;u!==null&&u.delete(a),t.pingedLanes|=t.suspendedLanes&o,t.warmLanes&=~o,It===t&&(ct&o)===o&&(Jt===4||Jt===3&&(ct&62914560)===ct&&300>Ot()-ed?(_t&2)===0&&ao(t,0):eg|=o,no===ct&&(no=0)),ta(t)}function fw(t,a){a===0&&(a=Me()),t=Wi(t,a),t!==null&&(tt(t,a),ta(t))}function $k(t){var a=t.memoizedState,o=0;a!==null&&(o=a.retryLane),fw(t,o)}function Mk(t,a){var o=0;switch(t.tag){case 31:case 13:var u=t.stateNode,p=t.memoizedState;p!==null&&(o=p.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),fw(t,o)}function Nk(t,a){return Dt(t,a)}var od=null,so=null,lg=!1,ld=!1,cg=!1,hi=0;function ta(t){t!==so&&t.next===null&&(so===null?od=so=t:so=so.next=t),ld=!0,lg||(lg=!0,jk())}function Gl(t,a){if(!cg&&ld){cg=!0;do for(var o=!1,u=od;u!==null;){if(t!==0){var p=u.pendingLanes;if(p===0)var g=0;else{var C=u.suspendedLanes,R=u.pingedLanes;g=(1<<31-dn(42|t)+1)-1,g&=p&~(C&~R),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,mw(u,g))}else g=ct,g=xe(u,u===It?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Ke(u,g)||(o=!0,mw(u,g));u=u.next}while(o);cg=!1}}function Ik(){hw()}function hw(){ld=lg=!1;var t=0;hi!==0&&Kk()&&(t=hi);for(var a=Ot(),o=null,u=od;u!==null;){var p=u.next,g=pw(u,a);g===0?(u.next=null,o===null?od=p:o.next=p,p===null&&(so=o)):(o=u,(t!==0||(g&3)!==0)&&(ld=!0)),u=p}hn!==0&&hn!==5||Gl(t),hi!==0&&(hi=0)}function pw(t,a){for(var o=t.suspendedLanes,u=t.pingedLanes,p=t.expirationTimes,g=t.pendingLanes&-62914561;0R)break;var re=P.transferSize,le=P.initiatorType;re&&_w(le)&&(P=P.responseEnd,C+=re*(P"u"?null:document;function Iw(t,a,o){var u=oo;if(u&&typeof a=="string"&&a){var p=Bn(a);p='link[rel="'+t+'"][href="'+p+'"]',typeof o=="string"&&(p+='[crossorigin="'+o+'"]'),Nw.has(p)||(Nw.add(p),t={rel:t,crossOrigin:o,href:a},u.querySelector(p)===null&&(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function nR(t){Da.D(t),Iw("dns-prefetch",t,null)}function rR(t,a){Da.C(t,a),Iw("preconnect",t,a)}function aR(t,a,o){Da.L(t,a,o);var u=oo;if(u&&t&&a){var p='link[rel="preload"][as="'+Bn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(p+='[imagesrcset="'+Bn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(p+='[imagesizes="'+Bn(o.imageSizes)+'"]')):p+='[href="'+Bn(t)+'"]';var g=p;switch(a){case"style":g=lo(t);break;case"script":g=co(t)}wr.has(g)||(t=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:t,as:a},o),wr.set(g,t),u.querySelector(p)!==null||a==="style"&&u.querySelector(Wl(g))||a==="script"&&u.querySelector(Yl(g))||(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function iR(t,a){Da.m(t,a);var o=oo;if(o&&t){var u=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+Bn(u)+'"][href="'+Bn(t)+'"]',g=p;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=co(t)}if(!wr.has(g)&&(t=y({rel:"modulepreload",href:t},a),wr.set(g,t),o.querySelector(p)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Yl(g)))return}u=o.createElement("link"),_n(u,"link",t),nn(u),o.head.appendChild(u)}}}function sR(t,a,o){Da.S(t,a,o);var u=oo;if(u&&t){var p=Ga(u).hoistableStyles,g=lo(t);a=a||"default";var C=p.get(g);if(!C){var R={loading:0,preload:null};if(C=u.querySelector(Wl(g)))R.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},o),(o=wr.get(g))&&Ag(t,o);var P=C=u.createElement("link");nn(P),_n(P,"link",t),P._p=new Promise(function(X,re){P.onload=X,P.onerror=re}),P.addEventListener("load",function(){R.loading|=1}),P.addEventListener("error",function(){R.loading|=2}),R.loading|=4,hd(C,a,u)}C={type:"stylesheet",instance:C,count:1,state:R},p.set(g,C)}}}function oR(t,a){Da.X(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function lR(t,a){Da.M(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0,type:"module"},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function jw(t,a,o,u){var p=(p=se.current)?fd(p):null;if(!p)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=lo(o.href),o=Ga(p).hoistableStyles,u=o.get(a),u||(u={type:"style",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){t=lo(o.href);var g=Ga(p).hoistableStyles,C=g.get(t);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(t,C),(g=p.querySelector(Wl(t)))&&!g._p&&(C.instance=g,C.state.loading=5),wr.has(t)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},wr.set(t,o),g||cR(p,t,o,C.state))),a&&u===null)throw Error(r(528,""));return C}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=co(o),o=Ga(p).hoistableScripts,u=o.get(a),u||(u={type:"script",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function lo(t){return'href="'+Bn(t)+'"'}function Wl(t){return'link[rel="stylesheet"]['+t+"]"}function Hw(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function cR(t,a,o,u){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=t.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),_n(a,"link",o),nn(a),t.head.appendChild(a))}function co(t){return'[src="'+Bn(t)+'"]'}function Yl(t){return"script[async]"+t}function zw(t,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var u=t.querySelector('style[data-href~="'+Bn(o.href)+'"]');if(u)return a.instance=u,nn(u),u;var p=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),nn(u),_n(u,"style",p),hd(u,o.precedence,t),a.instance=u;case"stylesheet":p=lo(o.href);var g=t.querySelector(Wl(p));if(g)return a.state.loading|=4,a.instance=g,nn(g),g;u=Hw(o),(p=wr.get(p))&&Ag(u,p),g=(t.ownerDocument||t).createElement("link"),nn(g);var C=g;return C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),a.state.loading|=4,hd(g,o.precedence,t),a.instance=g;case"script":return g=co(o.src),(p=t.querySelector(Yl(g)))?(a.instance=p,nn(p),p):(u=o,(p=wr.get(g))&&(u=y({},o),xg(u,p)),t=t.ownerDocument||t,p=t.createElement("script"),nn(p),_n(p,"link",u),t.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,hd(u,o.precedence,t));return a.instance}function hd(t,a,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=u.length?u[u.length-1]:null,g=p,C=0;C title"):null)}function uR(t,a,o){if(o===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(t=a.disabled,typeof a.precedence=="string"&&t==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Bw(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function dR(t,a,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var p=lo(u.href),g=a.querySelector(Wl(p));if(g){a=g._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=gd.bind(t),a.then(t,t)),o.state.loading|=4,o.instance=g,nn(g);return}g=a.ownerDocument||a,u=Hw(u),(p=wr.get(p))&&Ag(u,p),g=g.createElement("link"),nn(g);var C=g;C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),o.instance=g}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(t.count++,o=gd.bind(t),a.addEventListener("load",o),a.addEventListener("error",o))}}var Tg=0;function fR(t,a){return t.stylesheets&&t.count===0&&yd(t,t.stylesheets),0Tg?50:800)+a);return t.unsuspend=o,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(p)}}:null}function gd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)yd(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var md=null;function yd(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,md=new Map,a.forEach(hR,t),md=null,gd.call(t))}function hR(t,a){if(!(a.state.loading&4)){var o=md.get(t);if(o)var u=o.get(null);else{o=new Map,md.set(t,o);for(var p=t.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Td.exports=l0(),Td.exports}var Od=c0();const Ld=ra(Od),ho=[],u0=50;let $d=!1;function qg(){try{return window.G7Core?.devTools}catch{return}}function os(s,e,n){const r=qg();if($d&&r?.isEnabled?.()){r.trackLog?.(s,e,n);return}$d||(s==="error"||s==="warn")&&ho.length{n.isDebugEnabled()&&console.log(e,...r),os("log",s,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),os("warn",s,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),os("error",s,r)}}}po.getInstance();const Gg="extension",ls="extensionless",Fg="file";function d0(){const s=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===ls)return ls;const n=s?.assetUrlMode;return n===ls||n===Gg?n:s?.settings?.general?.asset_url_mode===ls?ls:Gg}function Nd(){return d0()===ls}function f0(s,e,n){return Id("templates",s,e,n)}function h0(s,e){const n=e.replace(/^\/+/,"").replace(/\/+$/,""),r=encodeURIComponent(s),i=go(`templates/${s}/assets/${n}`);return i!==null?i:`/api/templates/assets/${r}/${n}`}function p0(s,e,n){return Id("modules",s,e,n)}function g0(s,e,n){return Id("plugins",s,e,n)}function Id(s,e,n,r){const i=n.replace(/^\/+/,""),l=encodeURIComponent(e);if(!Nd())return`/api/${s}/assets/${l}/${i}${b0(r)}`;let c=`${Fg}=${encodeURIComponent(i)}`;return r!=null&&r!==""&&(c+=`&v=${r}`),`/api/${s}/assets/${l}?${c}`}function Ur(s,e,n,r){const i=s.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=Nd()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Vg(){const s=globalThis?.G7Config?.staticBase;return typeof s=="string"&&s!==""?s.replace(/\/+$/,""):null}function m0(){const s=Vg();if(!s)return null;const e=s.match(/\/(\d+)$/);return e?Number(e[1]):null}function go(s,e){const n=Vg();if(!n)return null;const r=s.replace(/^\/+/,"");return e!==void 0&&e>0&&e!==m0()?`${n.replace(/\/\d+$/,"")}/${e}/${r}`:`${n}/${r}`}function jd(s){if(!s)return null;const e=globalThis?.location?.origin,r=(e&&s.startsWith(e)?s.slice(e.length):s).match(/^\/build\/ext\/(\d+)\/(.+)$/);if(!r)return null;const i=r[1],l=r[2].split("?")[0],c=l.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);if(c){const[,h,m,y]=c;return`/api/${h}/assets/${m}/${y}?v=${i}`}const d=l.match(/^bundles\/(modules|plugins)\.(js|css)$/);if(d)return`/api/${d[1]}/bundle.${d[2]}?v=${i}`;const f=l.match(/^templates\/([^/]+)\/(routes\.json|components\.json|lang\/([a-zA-Z-]+)\.json)$/);if(f){const[,h,m]=f,y=m.replace(/\.json$/,"");return`/api/templates/${h}/${y}.json?v=${i}`}return null}function Ln(s){if(!s||!Nd())return s;const e=globalThis?.location?.origin,n=e&&s.startsWith(e)?s.slice(e.length):s;if(!n.startsWith("/api/"))return s;const[r,i]=y0(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return Kg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,h,m]=c,y=`${Fg}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${h}?${y}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?Kg(d[1],i):s}function y0(s){const e=s.indexOf("?");return e===-1?[s,""]:[s.slice(0,e),s.slice(e+1)]}function Kg(s,e){return e?`${s}?${e}`:s}function b0(s){return s==null||s===""?"":`?v=${s}`}const aa=pt("networkResilience"),Hd=2,zd=300,Pd=2e3,v0=15e3;function Ud(s){return s?.name==="AbortError"}function Wg(s){return Ud(s)?!1:s instanceof TypeError}let ec=!1,Yg=!1;function tc(){return ec}function S0(){typeof window>"u"||Yg||(Yg=!0,window.addEventListener("pagehide",()=>{ec=!0}),window.addEventListener("pageshow",s=>{s.persisted&&(ec=!1)}),window.addEventListener("beforeunload",()=>{ec=!0}))}function Bd(s,e,n){const r=Math.min(e*Math.pow(2,s),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function qd(s){return new Promise(e=>setTimeout(e,s))}async function nc(s,e={}){const{retries:n=Hd,baseDelayMs:r=zd,maxDelayMs:i=Pd,timeoutMs:l=v0,label:c=s,init:d}=e,f=n+1;let h;for(let m=0;m0?new AbortController:null;try{const _={...d};if(S){const A=d?.signal;A&&(A.aborted?S.abort():A.addEventListener("abort",()=>S.abort(),{once:!0})),_.signal=S.signal,v=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(s,_)}catch(_){if(h=_,Ud(_)&&!y||!(y||Wg(_)))throw _;if(tc())throw aa.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw aa.warn(`All ${f} attempts failed: ${c}`,_),_;const D=Bd(m,r,i);aa.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${D}ms: ${c}`),await qd(D)}finally{v!==void 0&&clearTimeout(v)}}throw h}async function Cr(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=s,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=()=>r(new Error(`Failed to load script: ${s}`)),document.head.appendChild(i)})}async function ia(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{s.onload=()=>e(),s.onerror=()=>n(new Error(`Failed to load stylesheet: ${s.href}`))})}async function rc(s,e,n={}){if(!s)return nc(e,n);try{const r=await fetch(s,n.init);if(r.ok){const i=await r.text();try{return JSON.parse(i),new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return console.warn(`[fetchStaticFirst] Static fast path returned malformed JSON — falling back to API: ${s}`),nc(e,n)}}console.warn(`[fetchStaticFirst] Static fast path miss (${r.status}) — falling back to API: ${s}`)}catch(r){console.warn(`[fetchStaticFirst] Static fast path fetch failed — falling back to API: ${s}`,r)}return nc(e,n)}const Br=pt("ComponentRegistry");class pn extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="ComponentRegistryError"}}const Qn=class Qn{constructor(){M(this,"registry",{});M(this,"manifest",null);M(this,"cacheVersion",0);M(this,"loadingState","idle");M(this,"error",null);M(this,"templateId",null);M(this,"templateType",null)}static getInstance(){return Qn.instance||(Qn.instance=new Qn),Qn.instance}static createIsolatedInstance(){return new Qn}static resetInstance(){Qn.instance=null}async loadComponents(e,n,r=0){if(this.loadingState==="loading")throw new pn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Br.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.cacheVersion=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Br.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(i){throw this.loadingState="error",this.error=i instanceof Error?i:new Error(String(i)),new pn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}:v${this.cacheVersion||0}`;if(Qn.manifestCache.has(e)){this.manifest=Qn.manifestCache.get(e),Br.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Ur(`/api/templates/${this.templateId}/components`,"json",this.cacheVersion>0?this.cacheVersion:null),r=await rc(this.cacheVersion>0?go(`templates/${this.templateId}/components.json`,this.cacheVersion):null,n,{label:"components.json"});if(!r.ok)throw new pn(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Qn.manifestCache.set(e,i),Br.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof pn?e:new pn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new pn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new pn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new pn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new pn(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Br.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new pn(`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),Br.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof pn?e:new pn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new pn("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 pn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Br.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,r){this.registry[e]&&Br.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:r},Br.log(`[ComponentRegistry] Registered component: ${e} (${r.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,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.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,Br.log("Registry cleared")}};M(Qn,"instance",null),M(Qn,"manifestCache",new Map);let Er=Qn;const Xg=pt("TranslationEngine");class Gd extends Error{constructor(n,r,i){super(n);M(this,"key");M(this,"locale");this.key=r,this.locale=i,this.name="TranslationError"}}const zn=class zn{constructor(e={}){M(this,"cache",new Map);M(this,"translations",new Map);M(this,"options");M(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return zn.instance||(zn.instance=new zn(e)),zn.instance}static resetInstance(){zn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Xg.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/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=Ur(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=!i&&this.cacheVersion>0?go(`templates/${e}/lang/${n}.json`,this.cacheVersion):null,h=f!==null?await rc(f,d,{label:`lang/${n}.json`}):await fetch(d);if(!h.ok)throw new Gd(`Failed to load translations: ${h.statusText}`,void 0,n);const y=await h.json();return this.saveToCache(l,y),this.translations.set(l,y),y}catch(c){throw new Gd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,r)),i===d)break;c++}return i.replace(zn.TRANSLATION_PATTERN,(d,f,h)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(h);return this.translate(f,n,m,r)+y})}translate(e,n,r,i){const l=this.getTranslation(e,n),c=r&&this.cleanParamsStr(r);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${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=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const h=this.getNestedValue(f,e);if(h!==null)return h}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=r.split(".");let f=c;for(let h=0;h(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(zn.PARAM_PATTERN);for(const f of d){const[,h,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(v,S)=>l[parseInt(S,10)]);r[h.trim()]=this.resolveParamValue(y.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const l=of.evaluateExpression(r,n);return String(l??"")}catch(l){return Xg.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);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 r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}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[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};M(zn,"instance",null),M(zn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),M(zn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),M(zn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let Oa=zn,Fd=null;function _0(s){return Fd||(Fd=new Oa(s)),Fd}const Jg=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:Oa,TranslationError:Gd,getTranslationEngine:_0},Symbol.toStringTag,{value:"Module"})),cs=pt("PipeRegistry");function Qg(s,e){const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0"),d=String(s.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(s.getMonth()+1)).replace("DD",i).replace("D",String(s.getDate())).replace("HH",l).replace("H",String(s.getHours())).replace("mm",c).replace("m",String(s.getMinutes())).replace("ss",d).replace("s",String(s.getSeconds()))}function A0(s,e="ko"){const r=new Date().getTime()-s.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),h=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}주 전`:h<12?`${h}개월 전`:`${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`:h<12?`${h} month${h===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function Vd(s){if(s==null)return null;if(s instanceof Date)return s;if(typeof s=="number")return new Date(s);if(typeof s=="string"){const e=new Date(s);return isNaN(e.getTime())?null:e}return null}const mo={date:{fn:(s,e="YYYY-MM-DD")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(s,e="YYYY-MM-DD HH:mm")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(s,e="ko")=>{const n=Vd(s);return n?A0(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(s,e)=>{const n=Number(s);if(isNaN(n))return String(s??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(s,e=100,n="...")=>typeof s!="string"?String(s??""):s.length<=e?s:s.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:s=>typeof s!="string"?String(s??""):s.toUpperCase(),description:"대문자 변환"},lowercase:{fn:s=>typeof s!="string"?String(s??""):s.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:s=>typeof s!="string"?String(s??""):s.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(s,e="")=>s==null||s===""?e:s,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(s,e)=>s??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:s=>{if(Array.isArray(s))return s[0]},description:"배열의 첫 번째 요소"},last:{fn:s=>{if(Array.isArray(s))return s[s.length-1]},description:"배열의 마지막 요소"},join:{fn:(s,e=", ")=>Array.isArray(s)?s.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:s=>Array.isArray(s)||typeof s=="string"?s.length:0,description:"배열/문자열 길이"},filterBy:{fn:(s,e,n)=>Array.isArray(s)?Array.isArray(e)?s.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):s:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:s=>s==null||typeof s!="object"?[]:Object.keys(s),description:"객체의 키 배열"},values:{fn:s=>s==null||typeof s!="object"?[]:Object.values(s),description:"객체의 값 배열"},json:{fn:(s,e)=>{try{return JSON.stringify(s,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(s,e)=>s==null?"":typeof s=="string"?s:typeof s!="object"?String(s):s[e||"ko"]||s.ko||s.en||Object.values(s)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},us=new Map,Oi=class Oi{static getInstance(){return Oi.instance||(Oi.instance=new Oi),Oi.instance}register(e,n,r){if(mo[e]){cs.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}us.set(e,{fn:n,description:r}),cs.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(mo[e])return cs.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=us.delete(e);return n&&cs.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=mo[e];return n?n.fn:us.get(e)?.fn}has(e){return!!mo[e]||us.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return cs.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return cs.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(mo))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of us.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){us.clear()}};M(Oi,"instance",null);let ac=Oi;ac.getInstance();function x0(s){const e=s.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let c="",d=null,f=0;for(let h=0;h0?i[h-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(Zg(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(Zg(c.trim())),{name:r,args:l}}function Zg(s){if(s==="null")return null;if(s==="undefined")return;if(s==="true")return!0;if(s==="false")return!1;const e=Number(s);return!isNaN(e)&&s!==""?e:s}function T0(s){const e=[];let n="",r=null,i=0;for(let l=0;l0?s[l-1]:"",f=l0?s[r-1]:"",c=r0){r--;continue}return null}}return r===0?e.trim():null}function R0(s){const e=[];if(typeof s!="string")return e;for(let n=0;n0){i--;continue}if(s[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:s.slice(n+2,l)}),n=l+1)}return e}function yo(s){return/[?:|&!+\-*/<>=()[\]{}]/.test(s)}function em(s){const e=typeof s=="string"?s.trim():"";return e===""?"empty":Kd.has(e)?"literal":Wn(e)?"pipe":yo(e)?"expression":"path"}function Wd(s,e,n,r){const i=typeof s=="string"?s.trim():"",l=em(i),c=r?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){r?.onEmpty?.(s);return}if(l==="literal")return Kd.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,r?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,r?.trackingInfo):n.resolve(i,e,c,r?.trackingInfo)}catch(d){if(r?.onError)return r.onError(d,i);throw d}}const sr="raw:";function tm(s){return s.startsWith(sr)?s.slice(sr.length):s}const bo="﷐",Si="﷑",$a="﷒";function vo(s){return bo+s+Si}function ic(s){return s.length>=2&&s.charCodeAt(0)===64976&&s.charCodeAt(s.length-1)===64977}function sc(s){return s.includes(bo)}function Yd(s){return s.slice(1,-1)}function ds(s){if(typeof s=="string")return vo(s);if(Array.isArray(s))return s.map(ds);if(s&&typeof s=="object"){const e={};for(const[n,r]of Object.entries(s))e[n]=ds(r);return e}return s}function Ma(s){if(typeof s=="string")return ic(s)?Yd(s):sc(s)||s.includes(Si)?s.split(bo).join("").split(Si).join(""):s;if(Array.isArray(s)){let e=!1;const n=s.map(r=>{const i=Ma(r);return i!==r&&(e=!0),i});return e?n:s}if(s&&typeof s=="object"){if(s.$$typeof!==void 0)return s;let e=!1;const n={};for(const[r,i]of Object.entries(s)){const l=Ma(i);l!==i&&(e=!0),n[r]=l}return e?n:s}return s}const So=new Set(["constructor","__proto__","prototype","__lookupGetter__","__lookupSetter__","__defineGetter__","__defineSetter__"]),D0=new Set(["Function","eval","globalThis","window","self","document","require","module","process","Reflect","Proxy","WebAssembly","import","constructor"]);function nm(s,e){if(s!==null&&(typeof s=="object"||typeof s=="function")&&rm.has(s))throw new Error(`Object.${e} on a built-in global object is not allowed`);return s}const O0=Object.freeze({keys:Object.keys,values:Object.values,entries:Object.entries,assign:(s,...e)=>{const n=nm(s,"assign");for(const r of e)if(r!=null)for(const i of Object.keys(r)){if(So.has(i))throw new Error(`Access to "${i}" is forbidden`);rf(n,i,r[i])}return n},freeze:s=>Object.freeze(nm(s,"freeze")),fromEntries:Object.fromEntries,create:Object.create,isFrozen:Object.isFrozen}),Xd={Math,JSON,Date,Array,Object:O0,Number,String,Boolean,Set,Map,WeakSet,WeakMap,parseInt,parseFloat,isNaN,isFinite},Jd={Date,Set,Map,WeakSet,WeakMap,Array,Number,String,Boolean,Object},rm=new Set([...Object.values(Xd),...Object.values(Jd)].filter(s=>s!==null&&(typeof s=="object"||typeof s=="function"))),oc=new Set(["function"]),_r=Symbol("short-circuit");class Qd{constructor(e){M(this,"value");this.value=e}}class Zd{}class ef{}function L0(s){return/[A-Za-z_$]/.test(s)}function $0(s){return/[A-Za-z0-9_$]/.test(s)}function wi(s){return s>="0"&&s<="9"}function M0(s,e,n){let r=e+1;for(;r0;){const h=s[n];if(h==="{")f++,n++;else if(h==="}"){if(f--,f===0)break;n++}else h==='"'||h==="'"?n=M0(s,n,h):h==="`"?n=am(s,n).end:n++}if(f!==0)throw new Error("Unterminated ${...} in template literal");i.push(s.slice(d,n)),n++;continue}l+=c,n++}throw new Error(`Unterminated template literal at position ${e}`)}function N0(s){const e=[];let n=0;const r=s.length,i=l=>n+l=r)throw new Error(`Unterminated string literal at position ${h}`);n++,e.push({type:"str",value:y,pos:h});continue}if(O0(l)){const h=n;for(n++;n"?(e.push({type:"punct",value:"=>",pos:c}),n+=2):i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"===",pos:c}),n+=3):(e.push({type:"punct",value:"==",pos:c}),n+=2):(e.push({type:"punct",value:"=",pos:c}),n+=1);continue}case"!":{i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"!==",pos:c}),n+=3):(e.push({type:"punct",value:"!=",pos:c}),n+=2):(e.push({type:"punct",value:"!",pos:c}),n+=1);continue}case"<":{if(i(1)==="=")e.push({type:"punct",value:"<=",pos:c}),n+=2;else{if(i(1)==="<")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:"<",pos:c}),n+=1}continue}case">":{if(i(1)==="=")e.push({type:"punct",value:">=",pos:c}),n+=2;else{if(i(1)===">")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:">",pos:c}),n+=1}continue}case"&":{if(i(1)==="&")e.push({type:"punct",value:"&&",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"|":{if(i(1)==="|")e.push({type:"punct",value:"||",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"?":{i(1)==="."&&!wi(i(2))?(e.push({type:"punct",value:"?.",pos:c}),n+=2):i(1)==="?"?(e.push({type:"punct",value:"??",pos:c}),n+=2):(e.push({type:"punct",value:"?",pos:c}),n+=1);continue}case"+":{if(i(1)==="+")throw new Error("Increment operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"+",pos:c}),n+=1;continue}case"-":{if(i(1)==="-")throw new Error("Decrement operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"-",pos:c}),n+=1;continue}case"*":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");if(i(1)==="*")throw new Error("Exponentiation operator is not supported");e.push({type:"punct",value:"*",pos:c}),n+=1;continue}case"/":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"/",pos:c}),n+=1;continue}case"%":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"%",pos:c}),n+=1;continue}case"~":case"^":throw new Error("Bitwise operators are not allowed");case".":case":":case"(":case")":case"[":case"]":case"{":case"}":case",":e.push({type:"punct",value:l,pos:c}),n+=1;continue;case";":e.push({type:"punct",value:";",pos:c}),n+=1;continue;default:throw new Error(`Unexpected character "${l}" at position ${c}`)}}return e}const N0={"??":1,"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},I0=new Set(["??","||","&&"]);class j0{constructor(e){M(this,"tokens");M(this,"pos",0);this.tokens=e}atEnd(){return this.pos>=this.tokens.length}peek(e=0){const n=this.pos+e;return n"}"`);this.pos++}parseExpression(){const e=this.tryParseArrow();return e||this.parseTernary()}tryParseArrow(){const e=this.pos,n=this.peek();if(!n)return null;if(n.type==="ident"&&this.isPunct("=>",1)&&!oc.has(String(n.value))){this.pos+=1,this.pos+=1;const{body:r,isBlock:i}=this.parseArrowBody();return{type:"Arrow",params:[{name:String(n.value),default:null}],body:r,isBlock:i}}if(n.type==="punct"&&n.value==="("){this.pos+=1;const r=this.tryParseParamList();if(r&&this.isPunct(")")&&(this.pos+=1,this.isPunct("=>"))){this.pos+=1;const{body:i,isBlock:l}=this.parseArrowBody();return{type:"Arrow",params:r,body:i,isBlock:l}}return this.pos=e,null}return this.pos=e,null}tryParseParamList(){const e=[];if(this.isPunct(")"))return e;for(;;){const n=this.peek();let r=null,i;if(n&&n.type==="punct"&&n.value==="["){const c=this.tryParseArrayPattern();if(!c)return null;i=c}else if(n&&n.type==="ident"&&!oc.has(String(n.value)))r=String(n.value),this.pos+=1;else return null;let l=null;if(this.isPunct("=")&&(this.pos+=1,l=this.parseExpression()),e.push(i?{name:r,elements:i,default:l}:{name:r,default:l}),this.isPunct(",")){this.pos+=1;continue}break}return e}tryParseArrayPattern(){const e=this.pos;this.pos+=1;const n=[];for(;;){if(this.isPunct("]"))return this.pos+=1,n;if(this.isPunct(",")){n.push(null),this.pos+=1;continue}const r=this.peek();if(!r||r.type!=="ident"||oc.has(String(r.value)))return this.pos=e,null;if(n.push(String(r.value)),this.pos+=1,this.isPunct(",")){this.pos+=1;continue}return this.isPunct("]")?(this.pos+=1,n):(this.pos=e,null)}}parseArrowBody(){return this.isPunct("{")?{body:this.parseBlock(),isBlock:!0}:{body:this.parseExpression(),isBlock:!1}}parseBlock(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.atEnd())throw new Error("Unterminated block");e.push(this.parseStatement())}return this.expectPunct("}"),{type:"Block",body:e}}parseStatement(){const e=this.peek();if(!e)throw new Error("Unexpected end of statement");if(e.type==="punct"&&e.value==="{")return this.parseBlock();if(e.type==="punct"&&e.value===";")return this.pos+=1,{type:"Empty"};if(e.type==="ident")switch(String(e.value)){case"const":case"let":return this.parseVarDecl();case"if":return this.parseIf();case"for":return this.parseForOf();case"return":return this.parseReturn();case"try":return this.parseTry();case"break":return this.pos+=1,this.consumeSemicolon(),{type:"Break"};case"continue":return this.pos+=1,this.consumeSemicolon(),{type:"Continue"}}const n=this.parseExpression();return this.consumeSemicolon(),{type:"ExprStmt",expression:n}}consumeSemicolon(){this.isPunct(";")&&(this.pos+=1)}parseVarDecl(){this.pos+=1;const e=[];for(;;){const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected variable name in declaration");const r=String(n.value);this.pos+=1,this.expectPunct("=");const i=this.parseExpression();if(e.push({name:r,init:i}),this.isPunct(",")){this.pos+=1;continue}break}return this.consumeSemicolon(),{type:"VarDecl",declarations:e}}parseIf(){this.pos+=1,this.expectPunct("(");const e=this.parseExpression();this.expectPunct(")");const n=this.parseStatement();let r=null;const i=this.peek();return i&&i.type==="ident"&&i.value==="else"&&(this.pos+=1,r=this.parseStatement()),{type:"If",test:e,consequent:n,alternate:r}}parseForOf(){this.pos+=1,this.expectPunct("(");const e=this.peek();if(!e||e.type!=="ident"||e.value!=="const"&&e.value!=="let")throw new Error('Only "for (const x of …)" / "for (let x of …)" loops are supported');this.pos+=1;const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected loop variable name");const r=String(n.value);this.pos+=1;const i=this.peek();if(!i||i.type!=="ident"||i.value!=="of")throw new Error("Only for-of loops are supported (for-in / C-style for are not allowed)");this.pos+=1;const l=this.parseExpression();this.expectPunct(")");const c=this.parseStatement();return{type:"ForOf",name:r,iterable:l,body:c}}parseReturn(){if(this.pos+=1,this.isPunct(";")||this.isPunct("}")||this.atEnd())return this.consumeSemicolon(),{type:"Return",argument:null};const e=this.parseExpression();return this.consumeSemicolon(),{type:"Return",argument:e}}parseTry(){this.pos+=1;const e=this.parseBlock();let n=null,r=null,i=null;const l=this.peek();if(l&&l.type==="ident"&&l.value==="catch"){if(this.pos+=1,this.isPunct("(")){this.pos+=1;const d=this.peek();d&&d.type==="ident"&&(n=String(d.value),this.pos+=1),this.expectPunct(")")}r=this.parseBlock()}const c=this.peek();if(c&&c.type==="ident"&&c.value==="finally"&&(this.pos+=1,i=this.parseBlock()),!r&&!i)throw new Error("Missing catch or finally after try");return{type:"Try",block:e,handlerParam:n,handler:r,finalizer:i}}parseFunctionExpression(){this.pos+=1;let e=null;const n=this.peek();n&&n.type==="ident"&&n.value!==void 0&&!this.isPunct("(")&&(e=String(n.value),this.pos+=1),this.expectPunct("(");const r=this.tryParseParamList();if(!r)throw new Error("Invalid function parameter list");this.expectPunct(")");const i=this.parseBlock();return{type:"Function",name:e,params:r,body:i}}parseTernary(){const e=this.parseBinary(0);if(this.isPunct("?")){this.pos+=1;const n=this.parseExpression();this.expectPunct(":");const r=this.parseExpression();return{type:"Conditional",test:e,consequent:n,alternate:r}}return e}parseBinary(e){let n=this.parseUnary();for(;;){const r=this.peek();if(!r||r.type!=="punct")break;const i=String(r.value),l=N0[i];if(l===void 0||lim(l));return{type:"Template",quasis:n,expressions:i}}if(e.type==="ident"&&e.value==="new")return this.parseNew();if(e.type==="ident"&&e.value==="function")return this.parseFunctionExpression();if(e.type==="ident"){const n=String(e.value);if(oc.has(n))throw new Error(`Keyword "${n}" is not allowed`);switch(this.pos+=1,n){case"true":return{type:"Literal",value:!0};case"false":return{type:"Literal",value:!1};case"null":return{type:"Literal",value:null};case"undefined":return{type:"Literal",value:void 0};default:return{type:"Identifier",name:n}}}if(e.type==="punct"){if(e.value==="("){this.pos+=1;const n=this.parseExpression();return this.expectPunct(")"),n}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral()}throw new Error(`Unexpected token "${e.value}"`)}parseArrayLiteral(){this.expectPunct("[");const e=[];for(;!this.isPunct("]");){if(this.isPunct(",")){this.pos+=1,e.push({type:"Literal",value:void 0});continue}if(this.isPunct("...")?(this.pos+=1,e.push({type:"Spread",argument:this.parseExpression()})):e.push(this.parseExpression()),this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("]"),{type:"Array",elements:e}}parseObjectLiteral(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.isPunct("..."))this.pos+=1,e.push({kind:"spread",value:this.parseExpression()});else{let n,r=!1;const i=this.peek();if(!i)throw new Error("Unexpected end of expression in object literal");if(i.type==="punct"&&i.value==="[")this.pos+=1,n=this.parseExpression(),this.expectPunct("]"),r=!0;else if(i.type==="str")this.pos+=1,n={type:"Literal",value:i.value};else if(i.type==="num")this.pos+=1,n={type:"Literal",value:String(i.value)};else if(i.type==="ident")this.pos+=1,n={type:"Literal",value:String(i.value)};else throw new Error(`Unexpected token "${i.value}" in object literal`);if(this.isPunct(":")){this.pos+=1;const l=this.parseExpression();e.push({kind:"init",key:n,computed:r,value:l})}else{if(r||n.type!=="Literal"||typeof n.value!="string")throw new Error("Invalid shorthand property in object literal");if(i.type!=="ident")throw new Error("Invalid shorthand property in object literal");e.push({kind:"init",key:n,computed:!1,value:{type:"Identifier",name:n.value}})}}if(this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("}"),{type:"Object",properties:e}}}function im(s){const e=M0(s),n=new j0(e),r=n.parseExpression();if(!n.atEnd()){const i=n.peek();throw i&&i.type==="punct"&&i.value===","?new Error("The comma/sequence operator is not allowed"):new Error(`Unexpected token "${i?i.value:""}" after expression`)}return r}function H0(s,e){let n=e;for(;n;){if(Object.prototype.hasOwnProperty.call(n.vars,s))return n.vars[s];n=n.parent}if(Object.prototype.hasOwnProperty.call(Xd,s))return Xd[s];if(R0.has(s))throw new Error(`Reference to forbidden global "${s}" is not allowed`)}function tf(s){const e=typeof s=="symbol"?s:String(s);if(typeof e=="string"&&So.has(e))throw new Error(`Access to "${e}" is forbidden`);return e}function nf(s,e){return s.type==="Member"?sm(s,e):s.type==="Call"?om(s,e):et(s,e)}function sm(s,e){const n=nf(s.object,e);if(n===_r||s.optional&&n==null)return _r;let r;s.computed?r=et(s.property,e):r=s.property.value;const i=tf(r);if(n!=null)return n[i]}function om(s,e){let n,r;if(s.callee.type==="Member"){const l=s.callee,c=nf(l.object,e);if(c===_r||l.optional&&c==null)return _r;let d;l.computed?d=et(l.property,e):d=l.property.value;const f=tf(d);c==null?n=void 0:(n=c[f],r=c)}else if(n=nf(s.callee,e),n===_r)return _r;if(s.optional&&n==null)return _r;if(typeof n!="function")throw new Error("Attempted to call a non-function value");const i=lm(s.args,e);return n.apply(r,i)}function lm(s,e){const n=[];for(const r of s)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}function cm(s,e,n){for(let r=0;r":return n>r;case"<=":return n<=r;case">=":return n>=r;default:throw new Error(`Unknown binary operator "${s.operator}"`)}}case"Logical":{const n=et(s.left,e);switch(s.operator){case"&&":return n&&et(s.right,e);case"||":return n||et(s.right,e);case"??":return n??et(s.right,e);default:throw new Error(`Unknown logical operator "${s.operator}"`)}}case"Conditional":return et(s.test,e)?et(s.consequent,e):et(s.alternate,e);case"Array":{const n=[];for(const r of s.elements)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}case"Object":{const n={};for(const r of s.properties)if(r.kind==="spread"){const i=et(r.value,e);if(i!=null&&typeof i=="object")for(const l of Object.keys(i))rf(n,l,i[l])}else{let i;r.computed?i=et(r.key,e):i=r.key.value;const l=et(r.value,e);rf(n,String(i),l)}return n}case"Arrow":{const n=e,r=s.params,i=s.body,l=s.isBlock;return function(...d){const f={vars:{},parent:n};return cm(r,d,f),l?um(i,f):et(i,f)}}case"Function":{const n=e,r=s.params,i=s.body,l=s.name,c=function(...f){const h={vars:{},parent:n};return l&&(h.vars[l]=c),cm(r,f,h),um(i,h)};return c}case"Delete":{const n=s.argument,r=et(n.object,e);let i;n.computed?i=et(n.property,e):i=n.property.value;const l=tf(i);if(r==null||typeof r!="object"&&typeof r!="function")return!0;if(rm.has(r))throw new Error("delete on a built-in global object is not allowed");return delete r[l]}case"Block":{const n={vars:{},parent:e};for(const r of s.body)et(r,n);return}case"VarDecl":{for(const n of s.declarations)e.vars[n.name]=et(n.init,e);return}case"If":{et(s.test,e)?et(s.consequent,e):s.alternate&&et(s.alternate,e);return}case"ForOf":{const n=et(s.iterable,e);if(n!=null)for(const r of n){const i={vars:{},parent:e};i.vars[s.name]=r;try{et(s.body,i)}catch(l){if(l instanceof ef)continue;if(l instanceof Zd)break;throw l}}return}case"Return":throw new Qd(s.argument?et(s.argument,e):void 0);case"ExprStmt":et(s.expression,e);return;case"Break":throw new Zd;case"Continue":throw new ef;case"Empty":return;case"Try":{try{try{et(s.block,e)}catch(n){if(n instanceof Qd||n instanceof Zd||n instanceof ef)throw n;if(s.handler){const r={vars:{},parent:e};s.handlerParam&&(r.vars[s.handlerParam]=n),et(s.handler,r)}else throw n}}finally{s.finalizer&&et(s.finalizer,e)}return}case"New":{const n=Jd[s.ctor];if(typeof n!="function")throw new Error("new on non-whitelisted constructor");const r=lm(s.args,e);return new n(...r)}case"Template":{let n=s.quasis[0]??"";for(let r=0;r0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(v,S)=>{const _=S.trim();let x=!1,A=_;if(_.startsWith(sr)&&(x=!0,A=_.slice(sr.length)),Wn(A))try{const z=this.evaluatePipeExpression(A,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),W=this.formatValue(z);return x?vo(W):W}catch(z){return Na.error("Pipe expression evaluation failed:",A,z),v}if(yo(A)){const z=c?.isEnabled()?performance.now():0;try{let W,de=!1;if(l.skipCache)W=this.evaluateExpression(A,d);else{const Se=`expr:${A}`,Ie=this.getFromRenderCycleCache(Se);Ie!==void 0?(W=Ie,de=!0):(W=this.evaluateExpression(A,d),this.saveToRenderCycleCache(Se,W))}if(c?.isEnabled()){const Se=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:de,duration:Se,method:"resolveBindings",skipCache:l.skipCache})}const _e=this.formatValue(W);return x?vo(_e):_e}catch(W){return Na.error("Expression evaluation failed:",A,W),v}}if(l.skipCache){const z=c?.isEnabled()?performance.now():0,W=this.resolvePath(A,d,l);if(c?.isEnabled()){const _e=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:_e,method:"resolveBindings",skipCache:!0})}const de=this.formatValue(W);return x?vo(de):de}const O=A.startsWith("_global")||A.startsWith("_local")||A.startsWith("_isolated")||A.startsWith("$parent"),k=c?.isEnabled()?performance.now():0;let L,B=!1;if(O){const z=this.getFromRenderCycleCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToRenderCycleCache(A,L))}else{const z=this.getFromCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToCache(A,L))}if(c?.isEnabled()){const z=performance.now()-k;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(L),resultType:this.getResultType(L),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:B,duration:z,method:"resolveBindings",skipCache:l.skipCache})}const q=this.formatValue(L);return x?vo(q):q},h=k0(e);if(h.length===0)return e;let m="",y=0;for(const v of h)m+=e.slice(y,v.start),m+=f(e.slice(v.start,v.end),v.expr),y=v.end;return m+e.slice(y)}evaluatePipeExpression(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[h,m]=x0(e);let y,v=!1;const S=yo(h),_=h.startsWith("_global")||h.startsWith("_local")||h.startsWith("_isolated")||h.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(h,f):y=this.resolvePath(h,f,l);else if(S){const A=this.getFromRenderCycleCache(`expr:${h}`);A!==void 0?(y=A,v=!0):(y=this.evaluateExpression(h,f),this.saveToRenderCycleCache(`expr:${h}`,y))}else if(_){const A=this.getFromRenderCycleCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToRenderCycleCache(h,y))}else{const A=this.getFromCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToCache(h,y))}const x=T0(y,m);if(c?.isEnabled()){const A=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:v,duration:A,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return x}resolve(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),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 h=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return h=!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 h=!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:h,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Na.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new sf(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fca.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.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,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,r)}catch(h){Na.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,h),i[d]=void 0}}return i}resolveObjectEntry(e,n,r,i,l){if(typeof r=="string"){const c=La(r);if(c!==null){const d=c.trim();let f=!1,h=d;d.startsWith(sr)&&(f=!0,h=d.slice(sr.length));let m;switch(em(h)){case"empty":Na.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=Kd.get(h);break;case"pipe":m=this.evaluatePipeExpression(h,i,l);break;case"expression":m=this.evaluateExpression(h,i,l);break;default:m=this.resolve(h,i,l)}e[n]=f&&m!=null?us(m):m}else e[n]=this.resolveBindings(r,i,l)}else Array.isArray(r)?e[n]=r.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):r&&typeof r=="object"?e[n]=this.resolveObject(r,i,l):e[n]=r}clearCache(){this.cache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>ca.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>ca.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=wo(),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 A of d)A in f||(f[A]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let h=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!h||!m)){const A=window.__templateApp?.getConfig?.();h??(h=A?.templateId),m??(m=A?.locale)}const y=m||"ko";f.$localized=(A,D)=>{if(A==null&&!D)return"";if(typeof A=="string")return A;if(A&&typeof A=="object"&&A[y])return A[y];if(D&&typeof D=="string"){const O=f.$t?f.$t(D):D;if(O&&O!==D)return O}return A&&typeof A=="object"?A.ko||A.en||Object.values(A)[0]||"":A==null?"":String(A)};const v=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>v?.uuid?v.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,A=>{const D=Math.random()*16|0;return(A==="x"?D:D&3|8).toString(16)});const S={templateId:h||"",locale:y};f.$t=A=>{if(!A||typeof A!="string")return"";try{return Oa.getInstance().translate(A,S)}catch(D){return Na.warn("$t() translation failed for key:",A,D),A}},f.$get=(A,D,O=void 0)=>{if(A==null)return O;const k=Array.isArray(D)?D:[D];if(k.length===0)return A;let L=A;for(const B of k){if(L==null||B==null)return O;L=L[B]}return L??O};const _=!1,x=af(c,f);if(i?.isEnabled()){const A=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:_,duration:A,method:"evaluateExpression",skipCache:r?.skipCache})}return x}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,r,i,l)=>`$t('${l}')`),e.replace(/(['"]\s*)?(\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*)(?!\s*['"])/g,(n,r,i)=>r?n:`"${i}"`)}preprocessOptionalChaining(e){const n=[];let r=e.replace(/(['"])(?:(?!\1|\\).|\\.)*\1/g,l=>(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),r}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"]),r=/(^|[^.\w$])([a-zA-Z_$][a-zA-Z0-9_$]*)/g,i=new Set;let l;for(;(l=r.exec(e))!==null;){const c=l[2];n.has(c)||i.add(c)}return Array.from(i)}isSwitchExpression(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}resolveSwitch(e,n,r){const i={...r,skipCache:!0};let l;try{l=this.resolveBindings(e.$switch,n,i)?.toString()?.trim()??""}catch(d){Na.warn("resolveSwitch: $switch 키 평가 실패:",e.$switch,d),l=""}let c;if(l&&e.$cases&&l in e.$cases)c=e.$cases[l];else if("$default"in e)c=e.$default;else return;return typeof c=="string"?c.includes("{{")?this.resolveBindings(c,n,i):c:c!==null&&typeof c=="object"?this.resolveObject(c,n,i):c}};M(ca,"PATH_SEGMENT_PATTERN",/([^.[\]]+)|\[(\d+)\]/g),M(ca,"CACHE_EXPIRY",3e4);let $n=ca;const of=new $n,lc={mobile:{min:0,max:767},tablet:{min:768,max:1023},desktop:{min:1024,max:1/0},portable:{min:0,max:1023}},cc=new Map;function z0(s,e){let n=null;return((...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{s(...r)},e)})}class P0{constructor(){M(this,"subscribers",new Set);M(this,"currentWidth",1024);M(this,"debouncedHandler",null);M(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=z0(()=>{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(cc.has(e))return cc.get(e)??null;let n=null;if(lc[e])n={...lc[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,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 cc.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!lc[i]})}return r.length===0?null:(r.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}),r[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(),cc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const Ci=new P0,Co=pt("ConditionEvaluator");function U0(s,e,n,r){return Wd(tm(s),e,n,{skipCache:!0,onEmpty:()=>{Co.warn(`${r}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function dm(s,e,n){if(!s)return!0;try{const r=La(s);let i;if(r!==null?i=U0(r,e,n,"evaluateStringCondition"):i=n.resolveBindings(s,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(r){return Co.warn(`evaluateStringCondition: 조건 평가 실패: ${s}`,r),!1}}function uc(s,e,n){if(typeof s=="string")return dm(s,e,n);if("and"in s){if(!Array.isArray(s.and)||s.and.length===0)return Co.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of s.and)if(!uc(r,e,n))return!1;return!0}if("or"in s){if(!Array.isArray(s.or)||s.or.length===0)return Co.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of s.or)if(uc(r,e,n))return!0;return!1}return Co.warn("evaluateConditionExpression: 알 수 없는 조건 형식",s),!1}function fm(s,e,n){if(!Array.isArray(s)||s.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r{or.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${r||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(s,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 or.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function ds(s,e,n,r){if(s.if!==void 0)return mm(s.if,e,n,r);if(s.condition!==void 0)return mm(s.condition,e,n,r);if(s.conditions===void 0)return!0;const i=s.conditions;try{return B0(i)?uc(i,e,n):q0(i)?fm(i,e,n).matched:(or.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return or.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function ym(s){if(!s.responsive)return s;const e=Ci.getWidth(),n=Ci.getMatchingKey(s.responsive,e);if(!n)return s;const r=s.responsive[n];return{...s,props:{...s.props,...r.props},children:r.children??s.children,text:r.text??s.text,if:r.if??s.if,iteration:r.iteration??s.iteration}}function Eo(s,e,n,r,i){if(!s||s.length===0)return[];const l=i?.bindingEngine??new $n,c=i?.translationEngine??Oa.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=F0(e,i?.componentContext),h=(S,_)=>{if(typeof S=="string")return ic(S)||sc(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,_);if(Array.isArray(S))return S.map(x=>h(x,_));if(S&&typeof S=="object"){const x={};for(const[A,D]of Object.entries(S))x[A]=h(D,_);return x}return S},m=(S,_)=>{if(typeof S=="string"){if(ic(S))return Yd(S);if(sc(S)){const A=[],D=S.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(k,L)=>(A.push(L),`${$a}${A.length-1}${$a}`));let O=D;return/\$t:[a-zA-Z0-9._-]+/.test(D)&&(O=c.resolveTranslations(D,d,_)),O.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(k,L)=>A[parseInt(L)])}if(S.startsWith("$t:defer:")){const A="$t:"+S.slice(9);return c.resolveTranslations(A,d,_)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const A=S.trim();if(!(A.startsWith("{")&&A.endsWith("}")||A.startsWith("[")&&A.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,_)}const x=gm(S);if(x!==null){let A=!1,D=x;x.startsWith(sr)&&(A=!0,D=x.slice(sr.length));let O=!1,k=Wd(D,_,l,{skipCache:!0,onError:L=>{or.warn("renderItemChildren: 표현식 평가 실패:",L),O=!0},onEmpty:()=>{or.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return O?void 0:(A||(k=h(k,_)),A&&k!=null?us(k):k)}if(S.includes("{{")){const A=l.resolveBindings(S,_,{skipCache:!0});return typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)?c.resolveTranslations(A,d,_):A}return S}if(Array.isArray(S))return S.map(x=>m(x,_));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,_,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x}return S},y=(S,_)=>{if(!S)return{};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x},v=(S,_,x)=>{const A=ym(S),D=A.iteration;if(!D)return[];const O=lf(D.source,x,l);if(!Array.isArray(O))return or.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${D.source}`),[];const k=hm();if(k?.isEnabled()){const B=`${_}-iteration`;k.trackIteration(B,D.source,D.item_var,D.index_var,O.length)}const L=n[A.name];return L?O.flatMap((B,q)=>{const z={...x,[D.item_var]:B,[`${D.item_var}_index`]:q,...D.index_var?{[D.index_var]:q}:{}},W=ds({if:A.if,condition:A.condition,conditions:A.conditions},z,l,A.id);if(A.if&&k?.isEnabled()){const Et=`${_}-iter-${q}-if`;k.trackIfCondition(Et,A.if,W,A.name)}if(!W)return[];const de=A.id?String(Ma(m(A.id,z))):void 0,_e=`${_}-iter-${q}`,Se=i?.getRemountKey?i.getRemountKey(de,_e):_e,Ie=y(A.props,z),Fe=cf(Ie,A.actions,z,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let ze=null;return A.text!==void 0?ze=m(A.text,z):A.children&&A.children.length>0&&(ze=Eo(A.children,z,n,Se,i)),k?.isEnabled()&&k.trackRender(A.name),[Xe.createElement(L,{key:Se,...Ma(Fe)},Ma(ze))]}):(or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[])};return s.flatMap((S,_)=>{const x=ym(S),A=x.id?String(Ma(m(x.id,f))):void 0,D=r?`${r}-${A||_}`:A||`child-${_}`,O=i?.getRemountKey?i.getRemountKey(A,D):D;if(x.iteration)return v(x,O,f);const k=ds({if:x.if,condition:x.condition,conditions:x.conditions},f,l,x.id),L=hm();if(x.if&&L?.isEnabled()){const de=`${O}-if`;L.trackIfCondition(de,x.if,k,x.name)}if(!k)return[];const B=n[x.name];if(!B)return or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[];const q=y(x.props,f),z=cf(q,x.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let W=null;return x.text!==void 0?W=m(x.text,f):x.children&&x.children.length>0&&(W=Eo(x.children,f,n,O,i)),L?.isEnabled()&&L.trackRender(x.name),[Xe.createElement(B,{key:O,...Ma(z)},Ma(W))]})}function fs(s,e,n,r){let i,l;return n instanceof $n?(i=n,l=r):(i=pm,l=n),i.resolveBindings(s,e,l)}function V0(s,e,n,r){const i=n??pm,l={skipCache:!0,...r};let c;try{c=i.resolveBindings(s.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(h){or.warn("resolveClassMap: key 평가 실패:",s.key,h),c=""}let d="";c&&s.variants&&c in s.variants?d=s.variants[c]:s.default&&(d=s.default);const f=[];return s.base?.trim()&&f.push(s.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function bm(s,e){return function(){return s.apply(e,arguments)}}const{toString:K0}=Object.prototype,{getPrototypeOf:Ia}=Object,{iterator:_o,toStringTag:vm}=Symbol,Ao=(({hasOwnProperty:s})=>(e,n)=>s.call(e,n))(Object.prototype),Sm=s=>typeof s=="string"&&(s==="__proto__"||s==="constructor"||s==="prototype"),wm=(s,e,n)=>s===Object.prototype||!n&&e===null,W0=s=>{if(!Object.isExtensible(s))return!1;const e=Object.getOwnPropertyNames(s);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(s)),e.every(n=>{if(Sm(n))return!1;const r=Object.getOwnPropertyDescriptor(s,n);return!!r&&r.configurable&&r.writable===!0})},xo=(s,e)=>{let n=s;const r=[];for(;n!=null;){if(r.indexOf(n)!==-1)return!1;r.push(n);const i=Ia(n);if(wm(n,i,n===s))return!1;if(Ao(n,e))return!0;n=i}return!1},Y0=(s,e)=>s!=null&&xo(s,e)?s[e]:void 0,X0=s=>{if(s==null||typeof s!="object"&&typeof s!="function")return s;const e=Ia(s);if(e===null&&W0(s))return s;const n=Object.create(null),r=Object.create(null),i=[];let l=s;for(;l!=null&&i.indexOf(l)===-1;){i.push(l);const c=l===s?e:Ia(l);if(wm(l,c,l===s))break;const d=Object.getOwnPropertyNames(l);Object.getOwnPropertySymbols&&d.push(...Object.getOwnPropertySymbols(l));for(const f of d)Sm(f)||Ao(r,f)||(n[f]=s[f],r[f]=!0);l=c}return n},uf=(s=>e=>{const n=K0.call(e);return s[n]||(s[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),lr=s=>(s=s.toLowerCase(),e=>uf(e)===s),dc=s=>e=>typeof e===s,{isArray:Ei}=Array,_i=dc("undefined");function hs(s){return s!==null&&!_i(s)&&s.constructor!==null&&!_i(s.constructor)&&jn(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const Cm=lr("ArrayBuffer");function J0(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&Cm(s.buffer),e}const Q0=dc("string"),jn=dc("function"),Em=dc("number"),ps=s=>s!==null&&typeof s=="object",Z0=s=>s===!0||s===!1,fc=s=>{if(!ps(s))return!1;const e=Ia(s);return(e===null||e===Object.prototype||Ia(e)===null)&&!xo(s,vm)&&!xo(s,_o)},eC=s=>{if(!ps(s)||hs(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},tC=lr("Date"),nC=lr("File"),rC=s=>!!(s&&typeof s.uri<"u"),aC=s=>s&&typeof s.getParts<"u",iC=lr("Blob"),sC=lr("FileList"),oC=lr("Set"),lC=s=>ps(s)&&jn(s.pipe);function cC(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const _m=cC(),Am=typeof _m.FormData<"u"?_m.FormData:void 0,uC=s=>{if(!s)return!1;if(Am&&s instanceof Am)return!0;const e=Ia(s);if(!e||e===Object.prototype||!jn(s.append))return!1;const n=uf(s);return n==="formdata"||n==="object"&&jn(s.toString)&&s.toString()==="[object FormData]"},dC=lr("URLSearchParams"),[fC,hC,pC,gC]=["ReadableStream","Request","Response","Headers"].map(lr),mC=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function To(s,e,{allOwnKeys:n=!1}={}){if(s===null||typeof s>"u")return;let r,i;if(typeof s!="object"&&(s=[s]),Ei(s))for(r=0,i=s.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const Ai=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tm=s=>!_i(s)&&s!==Ai;function df(...s){const{caseless:e,skipUndefined:n}=Tm(this)&&this||{},r={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&typeof c=="string"&&xm(r,c)||c,f=Ao(r,d)?r[d]:void 0;fc(f)&&fc(l)?r[d]=df(f,l):fc(l)?r[d]=df({},l):Ei(l)?r[d]=l.slice():(!n||!_i(l))&&(r[d]=l)};for(let l=0,c=s.length;l(To(e,(i,l)=>{n&&jn(i)?Object.defineProperty(s,l,{__proto__:null,value:bm(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(s,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),s),bC=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),vC=(s,e,n,r)=>{s.prototype=Object.create(e.prototype,r),Object.defineProperty(s.prototype,"constructor",{__proto__:null,value:s,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(s,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(s.prototype,n)},SC=(s,e,n,r)=>{let i,l,c;const d={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),l=i.length;l-- >0;)c=i[l],(!r||r(c,s,e))&&!d[c]&&(e[c]=s[c],d[c]=!0);s=n!==!1&&Ia(s)}while(s&&(!n||n(s,e))&&s!==Object.prototype);return e},wC=(s,e,n)=>{s=String(s),(n===void 0||n>s.length)&&(n=s.length),n-=e.length;const r=s.indexOf(e,n);return r!==-1&&r===n},CC=s=>{if(!s)return null;if(Ei(s))return s;let e=s.length;if(!Em(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=s[e];return n},EC=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Ia(Uint8Array)),_C=(s,e)=>{const r=(s&&s[_o]).call(s);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(s,l[0],l[1])}},AC=(s,e)=>{let n;const r=[];for(;(n=s.exec(e))!==null;)r.push(n);return r},xC=lr("HTMLFormElement"),TC=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),{propertyIsEnumerable:kC}=Object.prototype,RC=lr("RegExp"),km=(s,e)=>{const n=Object.getOwnPropertyDescriptors(s),r={};To(n,(i,l)=>{let c;(c=e(i,l,s))!==!1&&(r[l]=c||i)}),Object.defineProperties(s,r)},DC=s=>{km(s,(e,n)=>{if(jn(s)&&["arguments","caller","callee"].includes(n))return!1;const r=s[n];if(jn(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},OC=(s,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return Ei(s)?r(s):r(String(s).split(e)),n},LC=()=>{},$C=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function MC(s){return!!(s&&jn(s.append)&&s[vm]==="FormData"&&s[_o])}const NC=s=>{const e=new WeakSet,n=r=>{if(ps(r)){if(e.has(r))return;if(hs(r))return r;if(!("toJSON"in r)){e.add(r);let i;if(oC(r)){i=[];for(const l of r){const c=n(l);!_i(c)&&i.push(c)}}else i=Ei(r)?[]:{},To(r,(l,c)=>{const d=n(l);!_i(d)&&(i[c]=d)});return e.delete(r),i}}return r};return n(s)},IC=lr("AsyncFunction"),jC=s=>s&&(ps(s)||jn(s))&&jn(s.then)&&jn(s.catch),Rm=((s,e)=>s?setImmediate:e?((n,r)=>(Ai.addEventListener("message",({source:i,data:l})=>{i===Ai&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Ai.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",jn(Ai.postMessage)),HC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ai):typeof process<"u"&&process.nextTick||Rm,Dm=s=>s!=null&&jn(s[_o]),G={isArray:Ei,isArrayBuffer:Cm,isBuffer:hs,isFormData:uC,isArrayBufferView:J0,isString:Q0,isNumber:Em,isBoolean:Z0,isObject:ps,isPlainObject:fc,isEmptyObject:eC,isReadableStream:fC,isRequest:hC,isResponse:pC,isHeaders:gC,isUndefined:_i,isDate:tC,isFile:nC,isReactNativeBlob:rC,isReactNative:aC,isBlob:iC,isRegExp:RC,isFunction:jn,isStream:lC,isURLSearchParams:dC,isTypedArray:EC,isFileList:sC,forEach:To,merge:df,extend:yC,trim:mC,stripBOM:bC,inherits:vC,toFlatObject:SC,kindOf:uf,kindOfTest:lr,endsWith:wC,toArray:CC,forEachEntry:_C,matchAll:AC,isHTMLForm:xC,hasOwnProperty:Ao,hasOwnProp:Ao,hasOwnInPrototypeChain:xo,getSafeProp:Y0,toSafeFlatObject:X0,reduceDescriptors:km,freezeMethods:DC,toObjectSet:OC,toCamelCase:TC,noop:LC,toFiniteNumber:$C,findKey:xm,global:Ai,isContextDefined:Tm,isSpecCompliantForm:MC,toJSONObject:NC,isAsyncFn:IC,isThenable:jC,setImmediate:Rm,asap:HC,isIterable:Dm,isSafeIterable:s=>s!=null&&xo(s,_o)&&Dm(s)},zC=G.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"]),PC=s=>{const e={};let n,r,i;return s&&s.split(` -`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),r=c.substring(i+1).trim();const d=G.hasOwnProp(e,n);!n||d&&G.hasOwnProp(zC,n)||(n==="set-cookie"?d?e[n].push(r):e[n]=[r]:e[n]=d?e[n]+", "+r:r)}),e};function UC(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}const BC=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),qC=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function ff(s,e){return G.isArray(s)?s.map(n=>ff(n,e)):UC(String(s).replace(e,""))}const GC=s=>ff(s,BC),FC=s=>ff(s,qC);function Om(s){const e=Object.create(null);return G.forEach(s.toJSON(),(n,r)=>{e[r]=FC(n)}),e}const Lm=Symbol("internals");function ko(s){return s&&String(s).trim().toLowerCase()}function hc(s){return s===!1||s==null?s:G.isArray(s)?s.map(hc):GC(String(s))}function VC(s){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(s);)e[r[1]]=r[2];return e}const KC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function hf(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}function WC(s){const e=s.length-1;if(e<1||s.charCodeAt(0)!==34||s.charCodeAt(e)!==34)return s;let n="";for(let r=1;r=e))return s;n+=s[r]}return n}function YC(s){const e=Object.create(null),n=String(s);let r=0,i=!1,l=!1;function c(d){const f=hf(n.slice(r,d)),h=f.indexOf("=");if(h<1)return;const m=hf(f.slice(0,h));if(!KC.test(m))return;const y=m.toLowerCase();if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=hf(f.slice(h+1));e[y]=WC(v)}for(let d=0;d/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function pf(s,e,n,r,i){if(G.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!G.isString(e)){if(G.isString(r))return e.indexOf(r)!==-1;if(G.isRegExp(r))return r.test(e)}}function JC(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function QC(s,e){const n=G.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(s,r+n,{__proto__:null,value:function(i,l,c){return this[r].call(this,e,i,l,c)},configurable:!0})})}let xn=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,h){const m=ko(f);if(!m)return;const y=G.findKey(i,m);(!y||i[y]===void 0||h===!0||h===void 0&&i[y]!==!1)&&(i[y||f]=hc(d))}const c=(d,f)=>G.forEach(d,(h,m)=>l(h,m,f));if(G.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(G.isString(e)&&(e=e.trim())&&!XC(e))c(PC(e),n);else if(G.isObject(e)&&G.isSafeIterable(e)){let d=Object.create(null),f,h;for(const m of e){if(!G.isArray(m))throw new TypeError("Object iterator must return a key-value pair");h=m[0],G.hasOwnProp(d,h)?(f=d[h],d[h]=G.isArray(f)?[...f,m[1]]:[f,m[1]]):d[h]=m[1]}c(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=ko(e),e){const r=G.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return VC(i);if(G.isFunction(n))return n.call(this,i,r);if(G.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ko(e),e){const r=G.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||pf(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(c){if(c=ko(c),c){const d=G.findKey(r,c);d&&(!n||pf(r,r[d],d,n))&&(delete r[d],i=!0)}}return G.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||pf(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return G.forEach(this,(i,l)=>{const c=G.findKey(r,l);if(c){n[c]=hc(i),delete n[l];return}const d=e?JC(l):String(l).trim();d!==l&&delete n[l],n[d]=hc(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return G.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&G.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` -`)}getSetCookie(){const e=this.get("set-cookie");return G.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return YC(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[Lm]=this[Lm]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ko(c);r[d]||(QC(i,c),r[d]=!0)}return G.isArray(e)?e.forEach(l):l(e),this}};xn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),G.reduceDescriptors(xn.prototype,({value:s},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(r){this[n]=r}}}),G.freezeMethods(xn);const pc="[REDACTED ****]";function ZC(s){if(G.hasOwnProp(s,"toJSON"))return!0;let e=Object.getPrototypeOf(s);for(;e&&e!==Object.prototype;){if(G.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function eE(s,e){const n=new Set(e.map(l=>String(l).toLowerCase())),r=[],i=l=>{if(l===null||typeof l!="object"||G.isBuffer(l))return l;if(r.indexOf(l)!==-1)return;l instanceof xn&&(l=l.toJSON()),r.push(l);let c;if(G.isArray(l))c=[],l.forEach((d,f)=>{const h=i(d);G.isUndefined(h)||(c[f]=h)});else{if(!G.isPlainObject(l)&&ZC(l))return r.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const h=n.has(d.toLowerCase())?pc:i(f);G.isUndefined(h)||(c[d]=h)}}return r.pop(),c};return i(s)}function $m(s){try{return String(s)}catch{return""}}function tE(s){return s.errors.map(n=>{try{return n&&n.message?$m(n.message):$m(n)}catch{return""}}).filter(Boolean).join("; ")||s.name||"AggregateError"}let we=class t0 extends Error{static from(e,n,r,i,l,c){let d=e.message;!d&&G.isArray(e.errors)&&e.errors.length&&(d=tE(e));const f=new t0(d,n||e.code,r,i,l);return Object.defineProperty(f,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),f.name=e.name,e.status!=null&&f.status==null&&(f.status=e.status),c&&Object.assign(f,c),f}constructor(e,n,r,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),r&&(this.config=r),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&G.hasOwnProp(e,"redact")?e.redact:void 0,r=G.isArray(n)&&n.length>0?eE(e,n):G.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:r,code:this.code,status:this.status}}};we.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",we.ERR_BAD_OPTION="ERR_BAD_OPTION",we.ECONNABORTED="ECONNABORTED",we.ETIMEDOUT="ETIMEDOUT",we.ECONNREFUSED="ECONNREFUSED",we.ERR_NETWORK="ERR_NETWORK",we.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",we.ERR_DEPRECATED="ERR_DEPRECATED",we.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",we.ERR_BAD_REQUEST="ERR_BAD_REQUEST",we.ERR_CANCELED="ERR_CANCELED",we.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",we.ERR_INVALID_URL="ERR_INVALID_URL",we.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const nE=null,Mm=100;function gf(s){return G.isPlainObject(s)||G.isArray(s)}function Nm(s){return G.endsWith(s,"[]")?s.slice(0,-2):s}function mf(s,e,n){return s?s.concat(e).map(function(i,l){return i=Nm(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function rE(s){return G.isArray(s)&&!s.some(gf)}const aE=G.toFlatObject(G,{},null,function(e){return/^is[A-Z]/.test(e)});function gc(s,e,n){if(!G.isObject(s))throw new TypeError("target must be an object");e=e||new FormData;const r=(O,k)=>{const L=G.getSafeProp(n,O);return G.isUndefined(L)?k:L},i=r("metaTokens",!0),l=r("visitor")||x,c=r("dots",!1),d=r("indexes",!1),f=r("Blob")||typeof Blob<"u"&&Blob,h=r("maxDepth",Mm),m=f&&G.isSpecCompliantForm(e),y=[];if(!G.isFunction(l))throw new TypeError("visitor must be a function");function v(O){if(O===null)return"";if(G.isDate(O))return O.toISOString();if(G.isBoolean(O))return O.toString();if(!m&&G.isBlob(O))throw new we("Blob is not supported. Use a Buffer instead.");if(G.isArrayBuffer(O)||G.isTypedArray(O)){if(m&&typeof f=="function")return new f([O]);throw new we("Blob is not supported. Use a Buffer instead.",we.ERR_NOT_SUPPORT)}return O}function S(O){if(O>h)throw new we("Object is too deeply nested ("+O+" levels). Max depth: "+h,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _(O,k){if(h===1/0)return JSON.stringify(O);const L=[];return JSON.stringify(O,function(q,z){if(!G.isObject(z))return z;for(;L.length&&L[L.length-1]!==this;)L.pop();return L.push(z),S(k+L.length-1),z})}function x(O,k,L){let B=O;if(G.isReactNative(e)&&G.isReactNativeBlob(O))return e.append(mf(L,k,c),v(O)),!1;if(O&&!L&&typeof O=="object"){if(G.endsWith(k,"{}"))k=i?k:k.slice(0,-2),O=_(O,1);else if(G.isArray(O)&&rE(O)||(G.isFileList(O)||G.endsWith(k,"[]"))&&(B=G.toArray(O)))return k=Nm(k),B.forEach(function(z,W){!(G.isUndefined(z)||z===null)&&e.append(d===!0?mf([k],W,c):d===null?k:k+"[]",v(z))}),!1}return gf(O)?!0:(e.append(mf(L,k,c),v(O)),!1)}const A=Object.assign(aE,{defaultVisitor:x,convertValue:v,isVisitable:gf});function D(O,k,L=0){if(!G.isUndefined(O)){if(S(L),y.indexOf(O)!==-1)throw new Error("Circular reference detected in "+k.join("."));y.push(O),G.forEach(O,function(q,z){(!(G.isUndefined(q)||q===null)&&l.call(e,q,G.isString(z)?z.trim():z,k,A))===!0&&D(q,k?k.concat(z):[z],L+1)}),y.pop()}}if(!G.isObject(s))throw new TypeError("data must be an object");return D(s),e}function Im(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(s).replace(/[!'()~]|%20/g,function(r){return e[r]})}function yf(s,e){this._pairs=[],s&&gc(s,this,e)}const jm=yf.prototype;jm.append=function(e,n){this._pairs.push([e,n])},jm.toString=function(e){const n=e?r=>e.call(this,r,Im):Im;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function iE(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Hm(s,e,n){if(!e)return s;s=s||"";const r=G.isFunction(n)?{serialize:n}:n,i=G.getSafeProp(r,"encode")||iE,l=G.getSafeProp(r,"serialize");let c;if(l?c=l(e,r):c=G.isURLSearchParams(e)?e.toString():new yf(e,r).toString(i),c){const d=s.indexOf("#");d!==-1&&(s=s.slice(0,d)),s+=(s.indexOf("?")===-1?"?":"&")+c}return s}const Ro=Symbol("internals");function zm(s){return s?s.length:0}function Pm(s){if(s)for(;s.length&&s[s.length-1]===null;)s.pop()}function Do(s,e){const n=s.handlers,r=zm(n);n!==e.handlersRef?(e.handlersRef=n,e.handlerEntries.clear()):r!==e.handlersLength&&(r?e.handlerEntries.forEach(function(l,c){n[l.index]!==l.handler&&e.handlerEntries.delete(c)}):e.handlerEntries.clear()),e.handlersLength=r}class Um{constructor(){this.handlers=[],this[Ro]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,n,r){const i={fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null},l=this[Ro];this.handlers==null&&(this.handlers=[]),Do(this,l);const c=l.nextId++;return this.handlers.push(i),l.handlerEntries.set(c,{handler:i,index:this.handlers.length-1}),l.handlersLength=this.handlers.length,c}eject(e){const n=this[Ro];Do(this,n);const r=n.handlerEntries.get(e);if(r){if(n.handlerEntries.delete(e),this.handlers[r.index]!==r.handler)return;this.handlers[r.index]=null,n.iterationDepth||(Pm(this.handlers),n.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Do(this,this[Ro]))}forEach(e){const n=this[Ro];Do(this,n),n.iterationDepth++;try{G.forEach(this.handlers,function(i){i!==null&&e(i)})}finally{--n.iterationDepth||(Do(this,n),Pm(this.handlers),n.handlersLength=zm(this.handlers))}}}const bf={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},sE={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:yf,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},vf=typeof window<"u"&&typeof document<"u",Sf=typeof navigator=="object"&&navigator||void 0,oE=vf&&(!Sf||["ReactNative","NativeScript","NS"].indexOf(Sf.product)<0),lE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cE=vf&&window.location.href||"http://localhost",gn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:vf,hasStandardBrowserEnv:oE,hasStandardBrowserWebWorkerEnv:lE,navigator:Sf,origin:cE},Symbol.toStringTag,{value:"Module"})),...sE};function uE(s,e){return gc(s,new gn.classes.URLSearchParams,{visitor:function(n,r,i,l){return gn.isNode&&G.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Bm=Mm;function qm(s){if(s>Bm)throw new we("FormData field is too deeply nested ("+s+" levels). Max depth: "+Bm,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function dE(s){const e=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;let r;for(;(r=n.exec(s))!==null;)qm(e.length),e.push(r[0]==="[]"?"":r[1]||r[0]);return e}function fE(s){const e={},n=Object.keys(s);let r;const i=n.length;let l;for(r=0;r=n.length;return c=!c&&G.isArray(i)?i.length:c,f?(G.hasOwnProp(i,c)?i[c]=G.isArray(i[c])?i[c].concat(r):[i[c],r]:i[c]=r,!d):((!G.hasOwnProp(i,c)||!G.isObject(i[c]))&&(i[c]=[]),e(n,r,i[c],l)&&G.isArray(i[c])&&(i[c]=fE(i[c])),!d)}if(G.isFormData(s)&&G.isFunction(s.entries)){const n={};return G.forEachEntry(s,(r,i)=>{e(dE(r),i,n,0)}),n}return null}const Fm=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),gs=(s,e)=>s!=null&&G.hasOwnProp(s,e)?s[e]:void 0;function hE(s,e,n){if(G.isString(s))try{return(e||JSON.parse)(s),G.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(s)}const Oo={transitional:bf,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=G.isObject(e);if(l&&G.isHTMLForm(e)&&(e=new FormData(e)),G.isFormData(e))return i?JSON.stringify(Gm(e)):e;if(G.isArrayBuffer(e)||G.isBuffer(e)||G.isStream(e)||G.isFile(e)||G.isBlob(e)||G.isReadableStream(e))return e;if(G.isArrayBufferView(e))return e.buffer;if(G.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=gs(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return uE(e,f).toString();if((d=G.isFileList(e))||r.indexOf("multipart/form-data")>-1){const h=gs(this,"env"),m=h&&h.FormData;return gc(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),hE(e)):e}],transformResponse:[function(e){const n=gs(this,"transitional")||Oo.transitional,r=n&&n.forcedJSONParsing,i=gs(this,"responseType"),l=i==="json";if(G.isResponse(e)||G.isReadableStream(e))return e;if(e&&G.isString(e)&&(r&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,gs(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?we.from(f,we.ERR_BAD_RESPONSE,this,null,gs(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:gn.classes.FormData,Blob:gn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};G.forEach(Fm,s=>{Oo.headers[s]={}});function wf(s,e){const n=this||Oo,r=e||n,i=xn.from(r.headers);let l=r.data;return G.forEach(s,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Vm(s){return!!(s&&s.__CANCEL__)}let Lo=class extends we{constructor(e,n,r){super(e??"canceled",we.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function Km(s,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?s(n):e(new we("Request failed with status code "+n.status,n.status>=400&&n.status<500?we.ERR_BAD_REQUEST:we.ERR_BAD_RESPONSE,n.config,n.request,n))}const pE=/[\t\n\r]/g;function Wm(s){if(typeof s!="string")return s;let e=0;for(;e{n=y,i=null,l&&(clearTimeout(l),l=null),s(...m)};return[(...m)=>{const y=Date.now(),v=y-n;v>=r?c(m,y):(i=m,l||(l=setTimeout(()=>{l=null,c(i)},r-v)))},()=>i&&c(i),(...m)=>c(m)]}const mc=(s,e,n=3)=>{let r=0;const i=gE(50,250);return mE(l=>{if(!l||!G.isNumber(l.loaded))return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=Math.max(0,d!=null?Math.min(c,d):c),h=Math.max(0,f-r),m=i(h);r=Math.max(r,f);const y={loaded:f,total:d,progress:d?f/d:void 0,bytes:h,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};s(y)},n)},Ym=(s,e)=>{const n=s!=null;return[r=>e[0]({lengthComputable:n,total:s,loaded:r}),e[1]]},Xm=(s,e=G.asap)=>(...n)=>e(()=>s(...n)),yE=gn.hasStandardBrowserEnv?((s,e)=>n=>(n=new URL(n,gn.origin),s.protocol===n.protocol&&s.host===n.host&&(e||s.port===n.port)))(new URL(gn.origin),gn.navigator&&/(msie|trident)/i.test(gn.navigator.userAgent)):()=>!0,bE=gn.hasStandardBrowserEnv?{write(s,e,n,r,i,l,c){if(typeof document>"u")return;const d=[`${s}=${encodeURIComponent(e)}`];G.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),G.isString(r)&&d.push(`path=${r}`),G.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),G.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;n0&&s.charCodeAt(n-1)===47;)n--;return s.slice(0,n)+"/"+e.replace(/^\/+/,"")}const wE=/^https?:(?!\/\/)/i;function CE(s){return s&&s.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,n,r="")=>`${n}${r}${pc}`)}function EE(s){const e=s.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${pc}@`),n=e.indexOf("#"),i=(n===-1?e:e.slice(0,n)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${pc}`);return n===-1?i:`${i}#${CE(e.slice(n+1))}`}function Jm(s,e){if(typeof s=="string"){const n=Wm(s);if(wE.test(n))throw new we(`Invalid URL ${JSON.stringify(EE(n))}: missing "//" after protocol`,we.ERR_INVALID_URL,e)}}function Qm(s,e,n,r){Jm(e,r);let i=!vE(e);return s&&(i||n===!1)?(Jm(s,r),SE(s,e)):e}const Zm=s=>s instanceof xn?{...s}:s,_E=s=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(s).concat(Object.getOwnPropertySymbols(s).filter(e=>Object.getOwnPropertyDescriptor(s,e).enumerable)):Object.keys(s);function xi(s,e){s=s||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(m,y,v,S){return G.isPlainObject(m)&&G.isPlainObject(y)?G.merge.call({caseless:S},m,y):G.isPlainObject(y)?G.merge({},y):G.isArray(y)?y.slice():y}function i(m,y,v,S){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m,v,S)}else return r(m,y,v,S)}function l(m,y){if(!G.isUndefined(y))return r(void 0,y)}function c(m,y){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m)}else return r(void 0,y)}function d(m){const y=G.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!G.isUndefined(y))if(G.isPlainObject(y)){if(G.hasOwnProp(y,m))return y[m]}else return;const v=G.hasOwnProp(s,"transitional")?s.transitional:void 0;if(G.isPlainObject(v)&&G.hasOwnProp(v,m))return v[m]}function f(m,y,v){if(G.hasOwnProp(e,v))return r(m,y);if(G.hasOwnProp(s,v))return r(void 0,m)}const h={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutErrorMessage: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,v)=>i(Zm(m),Zm(y),v,!0)};return G.forEach(_E({...s,...e}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=G.hasOwnProp(h,y)?h[y]:i,S=G.hasOwnProp(s,y)?s[y]:void 0,_=G.hasOwnProp(e,y)?e[y]:void 0,x=v(S,_,y);G.isUndefined(x)&&v!==f||(n[y]=x)}),G.hasOwnProp(e,"validateStatus")&&G.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(G.hasOwnProp(s,"validateStatus")?n.validateStatus=r(void 0,s.validateStatus):delete n.validateStatus),n}const AE=["content-type","content-length"];function xE(s,e,n){if(n!=="content-only"){s.set(e);return}Object.entries(e||{}).forEach(([r,i])=>{AE.includes(r.toLowerCase())&&s.set(r,i)})}const TE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function ey(s){const e=xi({},s),n=v=>G.hasOwnProp(e,v)?e[v]:void 0,r=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),h=n("baseURL"),m=n("allowAbsoluteUrls"),y=n("url");if(e.headers=d=xn.from(d),e.url=Hm(Qm(h,y,m,e),n("params"),n("paramsSerializer")),f){const v=G.getSafeProp(f,"username")||"",S=G.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(v+":"+(S?TE(S):"")))}catch(_){throw we.from(_,we.ERR_BAD_OPTION_VALUE,s)}}if(G.isFormData(r)){const v=G.getSafeProp(r,"getHeaders");gn.hasStandardBrowserEnv||gn.hasStandardBrowserWebWorkerEnv||G.isReactNative(r)?d.setContentType(void 0):G.isFunction(v)&&xE(d,v.call(r),n("formDataHeaderPolicy"))}if(gn.hasStandardBrowserEnv&&(G.isFunction(i)&&(i=i(e)),i===!0||i==null&&yE(e.url))){const S=l&&c&&bE.read(c);S&&d.set(l,S)}return e}const kE=typeof XMLHttpRequest<"u"&&function(s){return new Promise(function(n,r){const i=ey(s);let l=i.data;const c=xn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:h}=i,m,y,v,S,_,x;function A(){S&&S(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let D=new XMLHttpRequest;D.open(i.method.toUpperCase(),i.url,!0),D.timeout=i.timeout;function O(L){if(!D)return;if(D.status===0&&(Cf(Wm(i.url))||Cf(gn.origin))!=="file"&&!(D.responseURL&&D.responseURL.startsWith("file:"))){r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null;return}try{L?x&&x(L):_&&_()}catch(W){setTimeout(()=>{throw W})}if(!D)return;const B=xn.from("getAllResponseHeaders"in D&&D.getAllResponseHeaders()),z={data:!d||d==="text"||d==="json"?D.responseText:D.response,status:D.status,statusText:D.statusText,headers:B,config:s,request:D};Km(function(de){n(de),A()},function(de){r(de),A()},z),D=null}"onloadend"in D?D.onloadend=O:D.onreadystatechange=function(){!D||D.readyState!==4||D.status===0&&!(D.responseURL&&D.responseURL.startsWith("file:"))||setTimeout(O)},D.onabort=function(){D&&(r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null)},D.onerror=function(B){const q=B&&B.message?B.message:"Network Error",z=new we(q,we.ERR_NETWORK,s,D);z.event=B||null,r(z),A(),D=null},D.ontimeout=function(){let B=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const q=i.transitional||bf;i.timeoutErrorMessage&&(B=i.timeoutErrorMessage),r(new we(B,q.clarifyTimeoutError?we.ETIMEDOUT:we.ECONNABORTED,s,D)),A(),D=null},l===void 0&&c.setContentType(null),"setRequestHeader"in D&&G.forEach(Om(c),function(B,q){D.setRequestHeader(q,B)}),G.isUndefined(i.withCredentials)||(D.withCredentials=!!i.withCredentials),d&&d!=="json"&&(D.responseType=i.responseType),h&&([v,_,x]=mc(h,!0),D.addEventListener("progress",v)),f&&D.upload&&([y,S]=mc(f),D.upload.addEventListener("progress",y),D.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=L=>{D&&(r(!L||L.type?new Lo(null,s,D):L),D.abort(),A(),D=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const k=Cf(i.url);if(k&&!gn.protocols.includes(k)){r(new we("Unsupported protocol "+k+":",we.ERR_BAD_REQUEST,s)),A();return}D.send(l||null)})},RE=(s,e)=>{if(s=s?s.filter(Boolean):[],!e&&!s.length)return;const n=new AbortController;let r=!1;const i=function(f){if(!r){r=!0,c();const h=f instanceof Error?f:this.reason;n.abort(h instanceof we?h:new Lo(h instanceof Error?h.message:h))}};let l=e&&setTimeout(()=>{l=null,i(new we(`timeout of ${e}ms exceeded`,we.ETIMEDOUT))},e);const c=()=>{s&&(l&&clearTimeout(l),l=null,s.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),s=null)};s.forEach(f=>{if(!r){if(f.aborted){i.call(f);return}f.addEventListener("abort",i,{once:!0})}});const{signal:d}=n;return d.unsubscribe=()=>G.asap(c),d},DE=function*(s,e){let n=s.byteLength;if(n{const i=OE(s,e);let l=0,c,d=f=>{c||(c=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:h,value:m}=await i.next();if(h){d(),f.close();return}let y=m.byteLength;if(n){let v=l+=y;n(v)}f.enqueue(new Uint8Array(m))}catch(h){throw d(h),h}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},ny=s=>s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102,ry=(s,e,n)=>e+2s<=57?s-48:(s&223)-55,$E=s=>s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47||s===45||s===95,ME=s=>s===9||s===10||s===12||s===13||s===32,NE=s=>{const e=Math.floor(s/4),n=s%4;return e*3+(n===2?1:n===3?2:0)},IE=s=>{const e=s.length;let n=0;return e>0&&s.charCodeAt(e-1)===61&&(n++,e>1&&s.charCodeAt(e-2)===61&&n++),Math.floor((e-n)*3/4)},jE=s=>{const e=s.length;let n=0,r=0,i=!1;for(let l=0;l0){i=!0;continue}n++}}return i||r>2||r>0&&(n+r)%4!==0||n%4===1?IE(s):NE(n)},HE=(s,e)=>{if(!s||typeof s!="string"||!s.startsWith("data:"))return 0;const n=s.indexOf(",");if(n<0)return 0;const r=s.slice(5,n),i=s.slice(n+1);if(/;base64/i.test(r))return e(i);let c=0;for(let d=0,f=i.length;d=55296&&h<=56319&&d+1=56320&&m<=57343?(c+=4,d++):c+=3}else c+=3}return c};function zE(s){const e=typeof s=="string"?s.indexOf("#"):-1;return HE(e===-1?s:s.slice(0,e),jE)}const Ef="1.20.0",iy=64*1024,PE={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:yc}=G,UE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),sy=s=>{if(!G.isString(s))return s;try{return decodeURIComponent(s)}catch{return s}},oy=(s,...e)=>{try{return!!s(...e)}catch{return!1}},BE=s=>{const e=s.indexOf("://");let n=s;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},qE=s=>{const e=G.global!==void 0&&G.global!==null?G.global:globalThis,{ReadableStream:n,TextEncoder:r}=e;s=G.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},s);const{fetch:i,Request:l,Response:c}=s,d=i?yc(i):typeof fetch=="function",f=yc(l),h=yc(c);if(!d)return!1;const m=d&&yc(n),y=d&&(typeof r=="function"?(D=>O=>D.encode(O))(new r):async D=>new Uint8Array(await new l(D).arrayBuffer())),v=f&&m&&oy(()=>{let D=!1;const O=new l(gn.origin,{body:new n,method:"POST",get duplex(){return D=!0,"half"}}),k=O.headers.has("Content-Type");return O.body!=null&&O.body.cancel(),D&&!k}),S=h&&m&&oy(()=>G.isReadableStream(new c("").body)),_={stream:S&&(D=>D.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(D=>{!_[D]&&(_[D]=(O,k)=>{let L=O&&O[D];if(L)return L.call(O);throw new we(`Response type '${D}' is not supported`,we.ERR_NOT_SUPPORT,k)})});const x=async D=>{if(D==null)return 0;if(G.isBlob(D))return D.size;if(G.isSpecCompliantForm(D))return(await new l(gn.origin,{method:"POST",body:D}).arrayBuffer()).byteLength;if(G.isArrayBufferView(D)||G.isArrayBuffer(D))return D.byteLength;if(G.isURLSearchParams(D)&&(D=D+""),G.isString(D))return(await y(D)).byteLength},A=async(D,O)=>{const k=G.toFiniteNumber(D.getContentLength());return k??x(O)};return async D=>{let{url:O,method:k,data:L,signal:B,cancelToken:q,timeout:z,onDownloadProgress:W,onUploadProgress:de,responseType:_e,headers:Se,withCredentials:Ie="same-origin",fetchOptions:Fe,maxContentLength:ze,maxBodyLength:Et,maxRedirects:Q}=ey(D);const ue=G.isNumber(ze)&&ze>-1,De=G.isNumber(Et)&&Et>-1,ee=ge=>G.hasOwnProp(D,ge)?D[ge]:void 0;let me=i||fetch;_e=_e?(_e+"").toLowerCase():"text";let H=RE([B,q&&q.toAbortSignal()],z),T=null;const fe=H&&H.unsubscribe&&(()=>{H.unsubscribe()});let he,Ae=null;const se=()=>new we("Request body larger than maxBodyLength limit",we.ERR_BAD_REQUEST,D,T);try{let ge;const $e=ee("auth");if($e){const qe=G.getSafeProp($e,"username")||"",mt=G.getSafeProp($e,"password")||"";ge={username:qe,password:mt}}if(BE(O)){const qe=new URL(O,gn.origin);if(!ge&&(qe.username||qe.password)){const mt=sy(qe.username),Dt=sy(qe.password);ge={username:mt,password:Dt}}(qe.username||qe.password)&&(qe.username="",qe.password="",O=qe.href)}if(ge&&(Se.delete("authorization"),Se.set("Authorization","Basic "+btoa(UE((ge.username||"")+":"+(ge.password||""))))),ue&&typeof O=="string"&&O.startsWith("data:")&&zE(O)>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);if(De&&k!=="get"&&k!=="head"){const qe=await x(L);if(typeof qe=="number"&&isFinite(qe)&&(he=qe,qe>Et))throw se()}const Te=De&&(G.isReadableStream(L)||G.isStream(L)),je=(qe,mt,Dt)=>ty(qe,iy,zt=>{if(De&&zt>Et)throw Ae=se();mt&&mt(zt)},Dt);if(v&&k!=="get"&&k!=="head"&&(de||Te)){if(he=he??await A(Se,L),he!==0||Te){let qe=new l(O,{method:"POST",body:L,duplex:"half"}),mt;if(G.isFormData(L)&&(mt=qe.headers.get("content-type"))&&Se.setContentType(mt),qe.body){const[Dt,zt]=de&&Ym(he,mc(Xm(de)))||[];L=je(qe.body,Dt,zt)}}}else if(Te&&!f&&m&&k!=="get"&&k!=="head")L=je(L);else if(Te&&f&&!v&&k!=="get"&&k!=="head")throw new we("Stream request bodies are not supported by the current fetch implementation",we.ERR_NOT_SUPPORT,D,T);G.isString(Ie)||(Ie=Ie?"include":"omit");const xt=f&&"credentials"in l.prototype;if(G.isFormData(L)){const qe=Se.getContentType();qe&&/^multipart\/form-data/i.test(qe)&&!/boundary=/i.test(qe)&&Se.delete("content-type")}Se.set("User-Agent","axios/"+Ef,!1);const rt=Fe==null?Fe:Object.assign(Object.create(null),Fe);rt&&(delete rt.body,delete rt.headers,delete rt.method,delete rt.signal,delete rt.duplex,delete rt.credentials);const gt=Object.assign(Object.create(null),rt,{signal:H,method:k.toUpperCase(),headers:Om(Se.normalize()),body:L,duplex:"half",credentials:xt?Ie:void 0});f&&(G.forEach(PE,(qe,mt)=>{gt[mt]===void 0&&(gt[mt]=qe)}),gt.signal===void 0&&(gt.signal=null),gt.body===void 0&&(gt.body=null)),Q===0&&(gt.redirect="manual",rt&&(rt.redirect="manual")),T=f&&new l(O,gt);let at=await(f?me(T,rt):me(O,gt));const Yt=xn.from(at.headers);if(ue){const qe=G.toFiniteNumber(Yt.getContentLength());if(qe!=null&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}const Ht=S&&(_e==="stream"||_e==="response");if(S&&at.body&&(W||ue||Ht&&fe)){const qe={};["status","statusText","headers"].forEach(Ot=>{qe[Ot]=at[Ot]});const mt=G.toFiniteNumber(Yt.getContentLength()),[Dt,zt]=W&&Ym(mt,mc(Xm(W),!0))||[];let kn=0;const dr=Ot=>{if(ue&&(kn=Ot,kn>ze))throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);Dt&&Dt(Ot)};at=new c(ty(at.body,iy,dr,()=>{zt&&zt(),fe&&fe()}),qe)}_e=_e||"text";let bt=await _[G.findKey(_,_e)||"text"](at,D);if(ue&&!S&&!Ht){let qe;if(bt!=null&&(typeof bt.byteLength=="number"?qe=bt.byteLength:typeof bt.size=="number"?qe=bt.size:typeof bt=="string"&&(qe=typeof r=="function"?new r().encode(bt).byteLength:bt.length)),typeof qe=="number"&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}return!Ht&&fe&&fe(),await new Promise((qe,mt)=>{Km(qe,mt,{data:bt,headers:xn.from(at.headers),status:at.status,statusText:at.statusText,config:D,request:T})})}catch(ge){if(fe&&fe(),H&&H.aborted&&H.reason instanceof we){const $e=H.reason;throw $e.config=D,T&&($e.request=T),ge!==$e&&Object.defineProperty($e,"cause",{__proto__:null,value:ge,writable:!0,enumerable:!1,configurable:!0}),$e}if(Ae)throw T&&!Ae.request&&(Ae.request=T),Ae;if(ge instanceof we)throw T&&!ge.request&&(ge.request=T),ge;if(ge&&ge.name==="TypeError"&&/Load failed|fetch/i.test(ge.message)){const $e=new we("Network Error",we.ERR_NETWORK,D,T,ge&&ge.response);throw Object.defineProperty($e,"cause",{__proto__:null,value:ge.cause||ge,writable:!0,enumerable:!1,configurable:!0}),$e}throw we.from(ge,ge&&ge.code,D,T,ge&&ge.response)}}},GE=new Map,ly=s=>{let e=s&&s.env||{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let c=l.length,d=c,f,h,m=GE;for(;d--;)f=l[d],h=m.get(f),h===void 0&&m.set(f,h=d?new Map:qE(e)),m=h;return h};ly();const _f={http:nE,xhr:kE,fetch:{get:ly}};G.forEach(_f,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(s,"adapterName",{__proto__:null,value:e})}});const cy=s=>`- ${s}`,FE=s=>G.isFunction(s)||s===null||s===!1;function VE(s,e){s=G.isArray(s)?s:[s];const{length:n}=s;let r,i;const l={};for(let c=0;c`adapter ${f} `+(h===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : +`;break;case"t":y+=" ";break;case"r":y+="\r";break;case"b":y+="\b";break;case"f":y+="\f";break;case"v":y+="\v";break;case"0":y+="\0";break;case"\\":y+="\\";break;case"'":y+="'";break;case'"':y+='"';break;case"`":y+="`";break;default:y+=v;break}n++}else y+=s[n],n++;if(n>=r)throw new Error(`Unterminated string literal at position ${h}`);n++,e.push({type:"str",value:y,pos:h});continue}if(L0(l)){const h=n;for(n++;n"?(e.push({type:"punct",value:"=>",pos:c}),n+=2):i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"===",pos:c}),n+=3):(e.push({type:"punct",value:"==",pos:c}),n+=2):(e.push({type:"punct",value:"=",pos:c}),n+=1);continue}case"!":{i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"!==",pos:c}),n+=3):(e.push({type:"punct",value:"!=",pos:c}),n+=2):(e.push({type:"punct",value:"!",pos:c}),n+=1);continue}case"<":{if(i(1)==="=")e.push({type:"punct",value:"<=",pos:c}),n+=2;else{if(i(1)==="<")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:"<",pos:c}),n+=1}continue}case">":{if(i(1)==="=")e.push({type:"punct",value:">=",pos:c}),n+=2;else{if(i(1)===">")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:">",pos:c}),n+=1}continue}case"&":{if(i(1)==="&")e.push({type:"punct",value:"&&",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"|":{if(i(1)==="|")e.push({type:"punct",value:"||",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"?":{i(1)==="."&&!wi(i(2))?(e.push({type:"punct",value:"?.",pos:c}),n+=2):i(1)==="?"?(e.push({type:"punct",value:"??",pos:c}),n+=2):(e.push({type:"punct",value:"?",pos:c}),n+=1);continue}case"+":{if(i(1)==="+")throw new Error("Increment operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"+",pos:c}),n+=1;continue}case"-":{if(i(1)==="-")throw new Error("Decrement operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"-",pos:c}),n+=1;continue}case"*":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");if(i(1)==="*")throw new Error("Exponentiation operator is not supported");e.push({type:"punct",value:"*",pos:c}),n+=1;continue}case"/":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"/",pos:c}),n+=1;continue}case"%":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"%",pos:c}),n+=1;continue}case"~":case"^":throw new Error("Bitwise operators are not allowed");case".":case":":case"(":case")":case"[":case"]":case"{":case"}":case",":e.push({type:"punct",value:l,pos:c}),n+=1;continue;case";":e.push({type:"punct",value:";",pos:c}),n+=1;continue;default:throw new Error(`Unexpected character "${l}" at position ${c}`)}}return e}const I0={"??":1,"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},j0=new Set(["??","||","&&"]);class H0{constructor(e){M(this,"tokens");M(this,"pos",0);this.tokens=e}atEnd(){return this.pos>=this.tokens.length}peek(e=0){const n=this.pos+e;return n"}"`);this.pos++}parseExpression(){const e=this.tryParseArrow();return e||this.parseTernary()}tryParseArrow(){const e=this.pos,n=this.peek();if(!n)return null;if(n.type==="ident"&&this.isPunct("=>",1)&&!oc.has(String(n.value))){this.pos+=1,this.pos+=1;const{body:r,isBlock:i}=this.parseArrowBody();return{type:"Arrow",params:[{name:String(n.value),default:null}],body:r,isBlock:i}}if(n.type==="punct"&&n.value==="("){this.pos+=1;const r=this.tryParseParamList();if(r&&this.isPunct(")")&&(this.pos+=1,this.isPunct("=>"))){this.pos+=1;const{body:i,isBlock:l}=this.parseArrowBody();return{type:"Arrow",params:r,body:i,isBlock:l}}return this.pos=e,null}return this.pos=e,null}tryParseParamList(){const e=[];if(this.isPunct(")"))return e;for(;;){const n=this.peek();let r=null,i;if(n&&n.type==="punct"&&n.value==="["){const c=this.tryParseArrayPattern();if(!c)return null;i=c}else if(n&&n.type==="ident"&&!oc.has(String(n.value)))r=String(n.value),this.pos+=1;else return null;let l=null;if(this.isPunct("=")&&(this.pos+=1,l=this.parseExpression()),e.push(i?{name:r,elements:i,default:l}:{name:r,default:l}),this.isPunct(",")){this.pos+=1;continue}break}return e}tryParseArrayPattern(){const e=this.pos;this.pos+=1;const n=[];for(;;){if(this.isPunct("]"))return this.pos+=1,n;if(this.isPunct(",")){n.push(null),this.pos+=1;continue}const r=this.peek();if(!r||r.type!=="ident"||oc.has(String(r.value)))return this.pos=e,null;if(n.push(String(r.value)),this.pos+=1,this.isPunct(",")){this.pos+=1;continue}return this.isPunct("]")?(this.pos+=1,n):(this.pos=e,null)}}parseArrowBody(){return this.isPunct("{")?{body:this.parseBlock(),isBlock:!0}:{body:this.parseExpression(),isBlock:!1}}parseBlock(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.atEnd())throw new Error("Unterminated block");e.push(this.parseStatement())}return this.expectPunct("}"),{type:"Block",body:e}}parseStatement(){const e=this.peek();if(!e)throw new Error("Unexpected end of statement");if(e.type==="punct"&&e.value==="{")return this.parseBlock();if(e.type==="punct"&&e.value===";")return this.pos+=1,{type:"Empty"};if(e.type==="ident")switch(String(e.value)){case"const":case"let":return this.parseVarDecl();case"if":return this.parseIf();case"for":return this.parseForOf();case"return":return this.parseReturn();case"try":return this.parseTry();case"break":return this.pos+=1,this.consumeSemicolon(),{type:"Break"};case"continue":return this.pos+=1,this.consumeSemicolon(),{type:"Continue"}}const n=this.parseExpression();return this.consumeSemicolon(),{type:"ExprStmt",expression:n}}consumeSemicolon(){this.isPunct(";")&&(this.pos+=1)}parseVarDecl(){this.pos+=1;const e=[];for(;;){const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected variable name in declaration");const r=String(n.value);this.pos+=1,this.expectPunct("=");const i=this.parseExpression();if(e.push({name:r,init:i}),this.isPunct(",")){this.pos+=1;continue}break}return this.consumeSemicolon(),{type:"VarDecl",declarations:e}}parseIf(){this.pos+=1,this.expectPunct("(");const e=this.parseExpression();this.expectPunct(")");const n=this.parseStatement();let r=null;const i=this.peek();return i&&i.type==="ident"&&i.value==="else"&&(this.pos+=1,r=this.parseStatement()),{type:"If",test:e,consequent:n,alternate:r}}parseForOf(){this.pos+=1,this.expectPunct("(");const e=this.peek();if(!e||e.type!=="ident"||e.value!=="const"&&e.value!=="let")throw new Error('Only "for (const x of …)" / "for (let x of …)" loops are supported');this.pos+=1;const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected loop variable name");const r=String(n.value);this.pos+=1;const i=this.peek();if(!i||i.type!=="ident"||i.value!=="of")throw new Error("Only for-of loops are supported (for-in / C-style for are not allowed)");this.pos+=1;const l=this.parseExpression();this.expectPunct(")");const c=this.parseStatement();return{type:"ForOf",name:r,iterable:l,body:c}}parseReturn(){if(this.pos+=1,this.isPunct(";")||this.isPunct("}")||this.atEnd())return this.consumeSemicolon(),{type:"Return",argument:null};const e=this.parseExpression();return this.consumeSemicolon(),{type:"Return",argument:e}}parseTry(){this.pos+=1;const e=this.parseBlock();let n=null,r=null,i=null;const l=this.peek();if(l&&l.type==="ident"&&l.value==="catch"){if(this.pos+=1,this.isPunct("(")){this.pos+=1;const d=this.peek();d&&d.type==="ident"&&(n=String(d.value),this.pos+=1),this.expectPunct(")")}r=this.parseBlock()}const c=this.peek();if(c&&c.type==="ident"&&c.value==="finally"&&(this.pos+=1,i=this.parseBlock()),!r&&!i)throw new Error("Missing catch or finally after try");return{type:"Try",block:e,handlerParam:n,handler:r,finalizer:i}}parseFunctionExpression(){this.pos+=1;let e=null;const n=this.peek();n&&n.type==="ident"&&n.value!==void 0&&!this.isPunct("(")&&(e=String(n.value),this.pos+=1),this.expectPunct("(");const r=this.tryParseParamList();if(!r)throw new Error("Invalid function parameter list");this.expectPunct(")");const i=this.parseBlock();return{type:"Function",name:e,params:r,body:i}}parseTernary(){const e=this.parseBinary(0);if(this.isPunct("?")){this.pos+=1;const n=this.parseExpression();this.expectPunct(":");const r=this.parseExpression();return{type:"Conditional",test:e,consequent:n,alternate:r}}return e}parseBinary(e){let n=this.parseUnary();for(;;){const r=this.peek();if(!r||r.type!=="punct")break;const i=String(r.value),l=I0[i];if(l===void 0||lim(l));return{type:"Template",quasis:n,expressions:i}}if(e.type==="ident"&&e.value==="new")return this.parseNew();if(e.type==="ident"&&e.value==="function")return this.parseFunctionExpression();if(e.type==="ident"){const n=String(e.value);if(oc.has(n))throw new Error(`Keyword "${n}" is not allowed`);switch(this.pos+=1,n){case"true":return{type:"Literal",value:!0};case"false":return{type:"Literal",value:!1};case"null":return{type:"Literal",value:null};case"undefined":return{type:"Literal",value:void 0};default:return{type:"Identifier",name:n}}}if(e.type==="punct"){if(e.value==="("){this.pos+=1;const n=this.parseExpression();return this.expectPunct(")"),n}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral()}throw new Error(`Unexpected token "${e.value}"`)}parseArrayLiteral(){this.expectPunct("[");const e=[];for(;!this.isPunct("]");){if(this.isPunct(",")){this.pos+=1,e.push({type:"Literal",value:void 0});continue}if(this.isPunct("...")?(this.pos+=1,e.push({type:"Spread",argument:this.parseExpression()})):e.push(this.parseExpression()),this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("]"),{type:"Array",elements:e}}parseObjectLiteral(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.isPunct("..."))this.pos+=1,e.push({kind:"spread",value:this.parseExpression()});else{let n,r=!1;const i=this.peek();if(!i)throw new Error("Unexpected end of expression in object literal");if(i.type==="punct"&&i.value==="[")this.pos+=1,n=this.parseExpression(),this.expectPunct("]"),r=!0;else if(i.type==="str")this.pos+=1,n={type:"Literal",value:i.value};else if(i.type==="num")this.pos+=1,n={type:"Literal",value:String(i.value)};else if(i.type==="ident")this.pos+=1,n={type:"Literal",value:String(i.value)};else throw new Error(`Unexpected token "${i.value}" in object literal`);if(this.isPunct(":")){this.pos+=1;const l=this.parseExpression();e.push({kind:"init",key:n,computed:r,value:l})}else{if(r||n.type!=="Literal"||typeof n.value!="string")throw new Error("Invalid shorthand property in object literal");if(i.type!=="ident")throw new Error("Invalid shorthand property in object literal");e.push({kind:"init",key:n,computed:!1,value:{type:"Identifier",name:n.value}})}}if(this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("}"),{type:"Object",properties:e}}}function im(s){const e=N0(s),n=new H0(e),r=n.parseExpression();if(!n.atEnd()){const i=n.peek();throw i&&i.type==="punct"&&i.value===","?new Error("The comma/sequence operator is not allowed"):new Error(`Unexpected token "${i?i.value:""}" after expression`)}return r}function z0(s,e){let n=e;for(;n;){if(Object.prototype.hasOwnProperty.call(n.vars,s))return n.vars[s];n=n.parent}if(Object.prototype.hasOwnProperty.call(Xd,s))return Xd[s];if(D0.has(s))throw new Error(`Reference to forbidden global "${s}" is not allowed`)}function tf(s){const e=typeof s=="symbol"?s:String(s);if(typeof e=="string"&&So.has(e))throw new Error(`Access to "${e}" is forbidden`);return e}function nf(s,e){return s.type==="Member"?sm(s,e):s.type==="Call"?om(s,e):et(s,e)}function sm(s,e){const n=nf(s.object,e);if(n===_r||s.optional&&n==null)return _r;let r;s.computed?r=et(s.property,e):r=s.property.value;const i=tf(r);if(n!=null)return n[i]}function om(s,e){let n,r;if(s.callee.type==="Member"){const l=s.callee,c=nf(l.object,e);if(c===_r||l.optional&&c==null)return _r;let d;l.computed?d=et(l.property,e):d=l.property.value;const f=tf(d);c==null?n=void 0:(n=c[f],r=c)}else if(n=nf(s.callee,e),n===_r)return _r;if(s.optional&&n==null)return _r;if(typeof n!="function")throw new Error("Attempted to call a non-function value");const i=lm(s.args,e);return n.apply(r,i)}function lm(s,e){const n=[];for(const r of s)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}function cm(s,e,n){for(let r=0;r":return n>r;case"<=":return n<=r;case">=":return n>=r;default:throw new Error(`Unknown binary operator "${s.operator}"`)}}case"Logical":{const n=et(s.left,e);switch(s.operator){case"&&":return n&&et(s.right,e);case"||":return n||et(s.right,e);case"??":return n??et(s.right,e);default:throw new Error(`Unknown logical operator "${s.operator}"`)}}case"Conditional":return et(s.test,e)?et(s.consequent,e):et(s.alternate,e);case"Array":{const n=[];for(const r of s.elements)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}case"Object":{const n={};for(const r of s.properties)if(r.kind==="spread"){const i=et(r.value,e);if(i!=null&&typeof i=="object")for(const l of Object.keys(i))rf(n,l,i[l])}else{let i;r.computed?i=et(r.key,e):i=r.key.value;const l=et(r.value,e);rf(n,String(i),l)}return n}case"Arrow":{const n=e,r=s.params,i=s.body,l=s.isBlock;return function(...d){const f={vars:{},parent:n};return cm(r,d,f),l?um(i,f):et(i,f)}}case"Function":{const n=e,r=s.params,i=s.body,l=s.name,c=function(...f){const h={vars:{},parent:n};return l&&(h.vars[l]=c),cm(r,f,h),um(i,h)};return c}case"Delete":{const n=s.argument,r=et(n.object,e);let i;n.computed?i=et(n.property,e):i=n.property.value;const l=tf(i);if(r==null||typeof r!="object"&&typeof r!="function")return!0;if(rm.has(r))throw new Error("delete on a built-in global object is not allowed");return delete r[l]}case"Block":{const n={vars:{},parent:e};for(const r of s.body)et(r,n);return}case"VarDecl":{for(const n of s.declarations)e.vars[n.name]=et(n.init,e);return}case"If":{et(s.test,e)?et(s.consequent,e):s.alternate&&et(s.alternate,e);return}case"ForOf":{const n=et(s.iterable,e);if(n!=null)for(const r of n){const i={vars:{},parent:e};i.vars[s.name]=r;try{et(s.body,i)}catch(l){if(l instanceof ef)continue;if(l instanceof Zd)break;throw l}}return}case"Return":throw new Qd(s.argument?et(s.argument,e):void 0);case"ExprStmt":et(s.expression,e);return;case"Break":throw new Zd;case"Continue":throw new ef;case"Empty":return;case"Try":{try{try{et(s.block,e)}catch(n){if(n instanceof Qd||n instanceof Zd||n instanceof ef)throw n;if(s.handler){const r={vars:{},parent:e};s.handlerParam&&(r.vars[s.handlerParam]=n),et(s.handler,r)}else throw n}}finally{s.finalizer&&et(s.finalizer,e)}return}case"New":{const n=Jd[s.ctor];if(typeof n!="function")throw new Error("new on non-whitelisted constructor");const r=lm(s.args,e);return new n(...r)}case"Template":{let n=s.quasis[0]??"";for(let r=0;r0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(v,S)=>{const _=S.trim();let x=!1,A=_;if(_.startsWith(sr)&&(x=!0,A=_.slice(sr.length)),Wn(A))try{const z=this.evaluatePipeExpression(A,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),W=this.formatValue(z);return x?vo(W):W}catch(z){return Na.error("Pipe expression evaluation failed:",A,z),v}if(yo(A)){const z=c?.isEnabled()?performance.now():0;try{let W,de=!1;if(l.skipCache)W=this.evaluateExpression(A,d);else{const Se=`expr:${A}`,Ie=this.getFromRenderCycleCache(Se);Ie!==void 0?(W=Ie,de=!0):(W=this.evaluateExpression(A,d),this.saveToRenderCycleCache(Se,W))}if(c?.isEnabled()){const Se=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:de,duration:Se,method:"resolveBindings",skipCache:l.skipCache})}const _e=this.formatValue(W);return x?vo(_e):_e}catch(W){return Na.error("Expression evaluation failed:",A,W),v}}if(l.skipCache){const z=c?.isEnabled()?performance.now():0,W=this.resolvePath(A,d,l);if(c?.isEnabled()){const _e=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:_e,method:"resolveBindings",skipCache:!0})}const de=this.formatValue(W);return x?vo(de):de}const O=A.startsWith("_global")||A.startsWith("_local")||A.startsWith("_isolated")||A.startsWith("$parent"),k=c?.isEnabled()?performance.now():0;let L,B=!1;if(O){const z=this.getFromRenderCycleCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToRenderCycleCache(A,L))}else{const z=this.getFromCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToCache(A,L))}if(c?.isEnabled()){const z=performance.now()-k;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(L),resultType:this.getResultType(L),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:B,duration:z,method:"resolveBindings",skipCache:l.skipCache})}const q=this.formatValue(L);return x?vo(q):q},h=R0(e);if(h.length===0)return e;let m="",y=0;for(const v of h)m+=e.slice(y,v.start),m+=f(e.slice(v.start,v.end),v.expr),y=v.end;return m+e.slice(y)}evaluatePipeExpression(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[h,m]=T0(e);let y,v=!1;const S=yo(h),_=h.startsWith("_global")||h.startsWith("_local")||h.startsWith("_isolated")||h.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(h,f):y=this.resolvePath(h,f,l);else if(S){const A=this.getFromRenderCycleCache(`expr:${h}`);A!==void 0?(y=A,v=!0):(y=this.evaluateExpression(h,f),this.saveToRenderCycleCache(`expr:${h}`,y))}else if(_){const A=this.getFromRenderCycleCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToRenderCycleCache(h,y))}else{const A=this.getFromCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToCache(h,y))}const x=k0(y,m);if(c?.isEnabled()){const A=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:v,duration:A,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return x}resolve(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),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 h=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return h=!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 h=!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:h,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Na.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new sf(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fca.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.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,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,r)}catch(h){Na.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,h),i[d]=void 0}}return i}resolveObjectEntry(e,n,r,i,l){if(typeof r=="string"){const c=La(r);if(c!==null){const d=c.trim();let f=!1,h=d;d.startsWith(sr)&&(f=!0,h=d.slice(sr.length));let m;switch(em(h)){case"empty":Na.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=Kd.get(h);break;case"pipe":m=this.evaluatePipeExpression(h,i,l);break;case"expression":m=this.evaluateExpression(h,i,l);break;default:m=this.resolve(h,i,l)}e[n]=f&&m!=null?ds(m):m}else e[n]=this.resolveBindings(r,i,l)}else Array.isArray(r)?e[n]=r.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):r&&typeof r=="object"?e[n]=this.resolveObject(r,i,l):e[n]=r}clearCache(){this.cache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>ca.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>ca.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=wo(),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 A of d)A in f||(f[A]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let h=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!h||!m)){const A=window.__templateApp?.getConfig?.();h??(h=A?.templateId),m??(m=A?.locale)}const y=m||"ko";f.$localized=(A,D)=>{if(A==null&&!D)return"";if(typeof A=="string")return A;if(A&&typeof A=="object"&&A[y])return A[y];if(D&&typeof D=="string"){const O=f.$t?f.$t(D):D;if(O&&O!==D)return O}return A&&typeof A=="object"?A.ko||A.en||Object.values(A)[0]||"":A==null?"":String(A)};const v=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>v?.uuid?v.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,A=>{const D=Math.random()*16|0;return(A==="x"?D:D&3|8).toString(16)});const S={templateId:h||"",locale:y};f.$t=A=>{if(!A||typeof A!="string")return"";try{return Oa.getInstance().translate(A,S)}catch(D){return Na.warn("$t() translation failed for key:",A,D),A}},f.$get=(A,D,O=void 0)=>{if(A==null)return O;const k=Array.isArray(D)?D:[D];if(k.length===0)return A;let L=A;for(const B of k){if(L==null||B==null)return O;L=L[B]}return L??O};const _=!1,x=af(c,f);if(i?.isEnabled()){const A=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:_,duration:A,method:"evaluateExpression",skipCache:r?.skipCache})}return x}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,r,i,l)=>`$t('${l}')`),e.replace(/(['"]\s*)?(\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*)(?!\s*['"])/g,(n,r,i)=>r?n:`"${i}"`)}preprocessOptionalChaining(e){const n=[];let r=e.replace(/(['"])(?:(?!\1|\\).|\\.)*\1/g,l=>(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),r}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"]),r=/(^|[^.\w$])([a-zA-Z_$][a-zA-Z0-9_$]*)/g,i=new Set;let l;for(;(l=r.exec(e))!==null;){const c=l[2];n.has(c)||i.add(c)}return Array.from(i)}isSwitchExpression(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}resolveSwitch(e,n,r){const i={...r,skipCache:!0};let l;try{l=this.resolveBindings(e.$switch,n,i)?.toString()?.trim()??""}catch(d){Na.warn("resolveSwitch: $switch 키 평가 실패:",e.$switch,d),l=""}let c;if(l&&e.$cases&&l in e.$cases)c=e.$cases[l];else if("$default"in e)c=e.$default;else return;return typeof c=="string"?c.includes("{{")?this.resolveBindings(c,n,i):c:c!==null&&typeof c=="object"?this.resolveObject(c,n,i):c}};M(ca,"PATH_SEGMENT_PATTERN",/([^.[\]]+)|\[(\d+)\]/g),M(ca,"CACHE_EXPIRY",3e4);let $n=ca;const of=new $n,lc={mobile:{min:0,max:767},tablet:{min:768,max:1023},desktop:{min:1024,max:1/0},portable:{min:0,max:1023}},cc=new Map;function P0(s,e){let n=null;return((...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{s(...r)},e)})}class U0{constructor(){M(this,"subscribers",new Set);M(this,"currentWidth",1024);M(this,"debouncedHandler",null);M(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=P0(()=>{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(cc.has(e))return cc.get(e)??null;let n=null;if(lc[e])n={...lc[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,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 cc.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!lc[i]})}return r.length===0?null:(r.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}),r[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(),cc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const Ci=new U0,Co=pt("ConditionEvaluator");function B0(s,e,n,r){return Wd(tm(s),e,n,{skipCache:!0,onEmpty:()=>{Co.warn(`${r}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function dm(s,e,n){if(!s)return!0;try{const r=La(s);let i;if(r!==null?i=B0(r,e,n,"evaluateStringCondition"):i=n.resolveBindings(s,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(r){return Co.warn(`evaluateStringCondition: 조건 평가 실패: ${s}`,r),!1}}function uc(s,e,n){if(typeof s=="string")return dm(s,e,n);if("and"in s){if(!Array.isArray(s.and)||s.and.length===0)return Co.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of s.and)if(!uc(r,e,n))return!1;return!0}if("or"in s){if(!Array.isArray(s.or)||s.or.length===0)return Co.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of s.or)if(uc(r,e,n))return!0;return!1}return Co.warn("evaluateConditionExpression: 알 수 없는 조건 형식",s),!1}function fm(s,e,n){if(!Array.isArray(s)||s.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r{or.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${r||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(s,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 or.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function fs(s,e,n,r){if(s.if!==void 0)return mm(s.if,e,n,r);if(s.condition!==void 0)return mm(s.condition,e,n,r);if(s.conditions===void 0)return!0;const i=s.conditions;try{return q0(i)?uc(i,e,n):G0(i)?fm(i,e,n).matched:(or.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return or.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function ym(s){if(!s.responsive)return s;const e=Ci.getWidth(),n=Ci.getMatchingKey(s.responsive,e);if(!n)return s;const r=s.responsive[n];return{...s,props:{...s.props,...r.props},children:r.children??s.children,text:r.text??s.text,if:r.if??s.if,iteration:r.iteration??s.iteration}}function Eo(s,e,n,r,i){if(!s||s.length===0)return[];const l=i?.bindingEngine??new $n,c=i?.translationEngine??Oa.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=V0(e,i?.componentContext),h=(S,_)=>{if(typeof S=="string")return ic(S)||sc(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,_);if(Array.isArray(S))return S.map(x=>h(x,_));if(S&&typeof S=="object"){const x={};for(const[A,D]of Object.entries(S))x[A]=h(D,_);return x}return S},m=(S,_)=>{if(typeof S=="string"){if(ic(S))return Yd(S);if(sc(S)){const A=[],D=S.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(k,L)=>(A.push(L),`${$a}${A.length-1}${$a}`));let O=D;return/\$t:[a-zA-Z0-9._-]+/.test(D)&&(O=c.resolveTranslations(D,d,_)),O.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(k,L)=>A[parseInt(L)])}if(S.startsWith("$t:defer:")){const A="$t:"+S.slice(9);return c.resolveTranslations(A,d,_)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const A=S.trim();if(!(A.startsWith("{")&&A.endsWith("}")||A.startsWith("[")&&A.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,_)}const x=gm(S);if(x!==null){let A=!1,D=x;x.startsWith(sr)&&(A=!0,D=x.slice(sr.length));let O=!1,k=Wd(D,_,l,{skipCache:!0,onError:L=>{or.warn("renderItemChildren: 표현식 평가 실패:",L),O=!0},onEmpty:()=>{or.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return O?void 0:(A||(k=h(k,_)),A&&k!=null?ds(k):k)}if(S.includes("{{")){const A=l.resolveBindings(S,_,{skipCache:!0});return typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)?c.resolveTranslations(A,d,_):A}return S}if(Array.isArray(S))return S.map(x=>m(x,_));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,_,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x}return S},y=(S,_)=>{if(!S)return{};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x},v=(S,_,x)=>{const A=ym(S),D=A.iteration;if(!D)return[];const O=lf(D.source,x,l);if(!Array.isArray(O))return or.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${D.source}`),[];const k=hm();if(k?.isEnabled()){const B=`${_}-iteration`;k.trackIteration(B,D.source,D.item_var,D.index_var,O.length)}const L=n[A.name];return L?O.flatMap((B,q)=>{const z={...x,[D.item_var]:B,[`${D.item_var}_index`]:q,...D.index_var?{[D.index_var]:q}:{}},W=fs({if:A.if,condition:A.condition,conditions:A.conditions},z,l,A.id);if(A.if&&k?.isEnabled()){const Et=`${_}-iter-${q}-if`;k.trackIfCondition(Et,A.if,W,A.name)}if(!W)return[];const de=A.id?String(Ma(m(A.id,z))):void 0,_e=`${_}-iter-${q}`,Se=i?.getRemountKey?i.getRemountKey(de,_e):_e,Ie=y(A.props,z),Fe=cf(Ie,A.actions,z,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let ze=null;return A.text!==void 0?ze=m(A.text,z):A.children&&A.children.length>0&&(ze=Eo(A.children,z,n,Se,i)),k?.isEnabled()&&k.trackRender(A.name),[Xe.createElement(L,{key:Se,...Ma(Fe)},Ma(ze))]}):(or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[])};return s.flatMap((S,_)=>{const x=ym(S),A=x.id?String(Ma(m(x.id,f))):void 0,D=r?`${r}-${A||_}`:A||`child-${_}`,O=i?.getRemountKey?i.getRemountKey(A,D):D;if(x.iteration)return v(x,O,f);const k=fs({if:x.if,condition:x.condition,conditions:x.conditions},f,l,x.id),L=hm();if(x.if&&L?.isEnabled()){const de=`${O}-if`;L.trackIfCondition(de,x.if,k,x.name)}if(!k)return[];const B=n[x.name];if(!B)return or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[];const q=y(x.props,f),z=cf(q,x.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let W=null;return x.text!==void 0?W=m(x.text,f):x.children&&x.children.length>0&&(W=Eo(x.children,f,n,O,i)),L?.isEnabled()&&L.trackRender(x.name),[Xe.createElement(B,{key:O,...Ma(z)},Ma(W))]})}function hs(s,e,n,r){let i,l;return n instanceof $n?(i=n,l=r):(i=pm,l=n),i.resolveBindings(s,e,l)}function K0(s,e,n,r){const i=n??pm,l={skipCache:!0,...r};let c;try{c=i.resolveBindings(s.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(h){or.warn("resolveClassMap: key 평가 실패:",s.key,h),c=""}let d="";c&&s.variants&&c in s.variants?d=s.variants[c]:s.default&&(d=s.default);const f=[];return s.base?.trim()&&f.push(s.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function bm(s,e){return function(){return s.apply(e,arguments)}}const{toString:W0}=Object.prototype,{getPrototypeOf:Ia}=Object,{iterator:_o,toStringTag:vm}=Symbol,Ao=(({hasOwnProperty:s})=>(e,n)=>s.call(e,n))(Object.prototype),Sm=s=>typeof s=="string"&&(s==="__proto__"||s==="constructor"||s==="prototype"),wm=(s,e,n)=>s===Object.prototype||!n&&e===null,Y0=s=>{if(!Object.isExtensible(s))return!1;const e=Object.getOwnPropertyNames(s);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(s)),e.every(n=>{if(Sm(n))return!1;const r=Object.getOwnPropertyDescriptor(s,n);return!!r&&r.configurable&&r.writable===!0})},xo=(s,e)=>{let n=s;const r=[];for(;n!=null;){if(r.indexOf(n)!==-1)return!1;r.push(n);const i=Ia(n);if(wm(n,i,n===s))return!1;if(Ao(n,e))return!0;n=i}return!1},X0=(s,e)=>s!=null&&xo(s,e)?s[e]:void 0,J0=s=>{if(s==null||typeof s!="object"&&typeof s!="function")return s;const e=Ia(s);if(e===null&&Y0(s))return s;const n=Object.create(null),r=Object.create(null),i=[];let l=s;for(;l!=null&&i.indexOf(l)===-1;){i.push(l);const c=l===s?e:Ia(l);if(wm(l,c,l===s))break;const d=Object.getOwnPropertyNames(l);Object.getOwnPropertySymbols&&d.push(...Object.getOwnPropertySymbols(l));for(const f of d)Sm(f)||Ao(r,f)||(n[f]=s[f],r[f]=!0);l=c}return n},uf=(s=>e=>{const n=W0.call(e);return s[n]||(s[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),lr=s=>(s=s.toLowerCase(),e=>uf(e)===s),dc=s=>e=>typeof e===s,{isArray:Ei}=Array,_i=dc("undefined");function ps(s){return s!==null&&!_i(s)&&s.constructor!==null&&!_i(s.constructor)&&jn(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const Cm=lr("ArrayBuffer");function Q0(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&Cm(s.buffer),e}const Z0=dc("string"),jn=dc("function"),Em=dc("number"),gs=s=>s!==null&&typeof s=="object",eC=s=>s===!0||s===!1,fc=s=>{if(!gs(s))return!1;const e=Ia(s);return(e===null||e===Object.prototype||Ia(e)===null)&&!xo(s,vm)&&!xo(s,_o)},tC=s=>{if(!gs(s)||ps(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},nC=lr("Date"),rC=lr("File"),aC=s=>!!(s&&typeof s.uri<"u"),iC=s=>s&&typeof s.getParts<"u",sC=lr("Blob"),oC=lr("FileList"),lC=lr("Set"),cC=s=>gs(s)&&jn(s.pipe);function uC(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const _m=uC(),Am=typeof _m.FormData<"u"?_m.FormData:void 0,dC=s=>{if(!s)return!1;if(Am&&s instanceof Am)return!0;const e=Ia(s);if(!e||e===Object.prototype||!jn(s.append))return!1;const n=uf(s);return n==="formdata"||n==="object"&&jn(s.toString)&&s.toString()==="[object FormData]"},fC=lr("URLSearchParams"),[hC,pC,gC,mC]=["ReadableStream","Request","Response","Headers"].map(lr),yC=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function To(s,e,{allOwnKeys:n=!1}={}){if(s===null||typeof s>"u")return;let r,i;if(typeof s!="object"&&(s=[s]),Ei(s))for(r=0,i=s.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const Ai=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tm=s=>!_i(s)&&s!==Ai;function df(...s){const{caseless:e,skipUndefined:n}=Tm(this)&&this||{},r={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&typeof c=="string"&&xm(r,c)||c,f=Ao(r,d)?r[d]:void 0;fc(f)&&fc(l)?r[d]=df(f,l):fc(l)?r[d]=df({},l):Ei(l)?r[d]=l.slice():(!n||!_i(l))&&(r[d]=l)};for(let l=0,c=s.length;l(To(e,(i,l)=>{n&&jn(i)?Object.defineProperty(s,l,{__proto__:null,value:bm(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(s,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),s),vC=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),SC=(s,e,n,r)=>{s.prototype=Object.create(e.prototype,r),Object.defineProperty(s.prototype,"constructor",{__proto__:null,value:s,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(s,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(s.prototype,n)},wC=(s,e,n,r)=>{let i,l,c;const d={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),l=i.length;l-- >0;)c=i[l],(!r||r(c,s,e))&&!d[c]&&(e[c]=s[c],d[c]=!0);s=n!==!1&&Ia(s)}while(s&&(!n||n(s,e))&&s!==Object.prototype);return e},CC=(s,e,n)=>{s=String(s),(n===void 0||n>s.length)&&(n=s.length),n-=e.length;const r=s.indexOf(e,n);return r!==-1&&r===n},EC=s=>{if(!s)return null;if(Ei(s))return s;let e=s.length;if(!Em(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=s[e];return n},_C=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Ia(Uint8Array)),AC=(s,e)=>{const r=(s&&s[_o]).call(s);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(s,l[0],l[1])}},xC=(s,e)=>{let n;const r=[];for(;(n=s.exec(e))!==null;)r.push(n);return r},TC=lr("HTMLFormElement"),kC=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),{propertyIsEnumerable:RC}=Object.prototype,DC=lr("RegExp"),km=(s,e)=>{const n=Object.getOwnPropertyDescriptors(s),r={};To(n,(i,l)=>{let c;(c=e(i,l,s))!==!1&&(r[l]=c||i)}),Object.defineProperties(s,r)},OC=s=>{km(s,(e,n)=>{if(jn(s)&&["arguments","caller","callee"].includes(n))return!1;const r=s[n];if(jn(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},LC=(s,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return Ei(s)?r(s):r(String(s).split(e)),n},$C=()=>{},MC=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function NC(s){return!!(s&&jn(s.append)&&s[vm]==="FormData"&&s[_o])}const IC=s=>{const e=new WeakSet,n=r=>{if(gs(r)){if(e.has(r))return;if(ps(r))return r;if(!("toJSON"in r)){e.add(r);let i;if(lC(r)){i=[];for(const l of r){const c=n(l);!_i(c)&&i.push(c)}}else i=Ei(r)?[]:{},To(r,(l,c)=>{const d=n(l);!_i(d)&&(i[c]=d)});return e.delete(r),i}}return r};return n(s)},jC=lr("AsyncFunction"),HC=s=>s&&(gs(s)||jn(s))&&jn(s.then)&&jn(s.catch),Rm=((s,e)=>s?setImmediate:e?((n,r)=>(Ai.addEventListener("message",({source:i,data:l})=>{i===Ai&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Ai.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",jn(Ai.postMessage)),zC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ai):typeof process<"u"&&process.nextTick||Rm,Dm=s=>s!=null&&jn(s[_o]),G={isArray:Ei,isArrayBuffer:Cm,isBuffer:ps,isFormData:dC,isArrayBufferView:Q0,isString:Z0,isNumber:Em,isBoolean:eC,isObject:gs,isPlainObject:fc,isEmptyObject:tC,isReadableStream:hC,isRequest:pC,isResponse:gC,isHeaders:mC,isUndefined:_i,isDate:nC,isFile:rC,isReactNativeBlob:aC,isReactNative:iC,isBlob:sC,isRegExp:DC,isFunction:jn,isStream:cC,isURLSearchParams:fC,isTypedArray:_C,isFileList:oC,forEach:To,merge:df,extend:bC,trim:yC,stripBOM:vC,inherits:SC,toFlatObject:wC,kindOf:uf,kindOfTest:lr,endsWith:CC,toArray:EC,forEachEntry:AC,matchAll:xC,isHTMLForm:TC,hasOwnProperty:Ao,hasOwnProp:Ao,hasOwnInPrototypeChain:xo,getSafeProp:X0,toSafeFlatObject:J0,reduceDescriptors:km,freezeMethods:OC,toObjectSet:LC,toCamelCase:kC,noop:$C,toFiniteNumber:MC,findKey:xm,global:Ai,isContextDefined:Tm,isSpecCompliantForm:NC,toJSONObject:IC,isAsyncFn:jC,isThenable:HC,setImmediate:Rm,asap:zC,isIterable:Dm,isSafeIterable:s=>s!=null&&xo(s,_o)&&Dm(s)},PC=G.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"]),UC=s=>{const e={};let n,r,i;return s&&s.split(` +`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),r=c.substring(i+1).trim();const d=G.hasOwnProp(e,n);!n||d&&G.hasOwnProp(PC,n)||(n==="set-cookie"?d?e[n].push(r):e[n]=[r]:e[n]=d?e[n]+", "+r:r)}),e};function BC(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}const qC=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),GC=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function ff(s,e){return G.isArray(s)?s.map(n=>ff(n,e)):BC(String(s).replace(e,""))}const FC=s=>ff(s,qC),VC=s=>ff(s,GC);function Om(s){const e=Object.create(null);return G.forEach(s.toJSON(),(n,r)=>{e[r]=VC(n)}),e}const Lm=Symbol("internals");function ko(s){return s&&String(s).trim().toLowerCase()}function hc(s){return s===!1||s==null?s:G.isArray(s)?s.map(hc):FC(String(s))}function KC(s){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(s);)e[r[1]]=r[2];return e}const WC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function hf(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}function YC(s){const e=s.length-1;if(e<1||s.charCodeAt(0)!==34||s.charCodeAt(e)!==34)return s;let n="";for(let r=1;r=e))return s;n+=s[r]}return n}function XC(s){const e=Object.create(null),n=String(s);let r=0,i=!1,l=!1;function c(d){const f=hf(n.slice(r,d)),h=f.indexOf("=");if(h<1)return;const m=hf(f.slice(0,h));if(!WC.test(m))return;const y=m.toLowerCase();if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=hf(f.slice(h+1));e[y]=YC(v)}for(let d=0;d/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function pf(s,e,n,r,i){if(G.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!G.isString(e)){if(G.isString(r))return e.indexOf(r)!==-1;if(G.isRegExp(r))return r.test(e)}}function QC(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function ZC(s,e){const n=G.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(s,r+n,{__proto__:null,value:function(i,l,c){return this[r].call(this,e,i,l,c)},configurable:!0})})}let xn=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,h){const m=ko(f);if(!m)return;const y=G.findKey(i,m);(!y||i[y]===void 0||h===!0||h===void 0&&i[y]!==!1)&&(i[y||f]=hc(d))}const c=(d,f)=>G.forEach(d,(h,m)=>l(h,m,f));if(G.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(G.isString(e)&&(e=e.trim())&&!JC(e))c(UC(e),n);else if(G.isObject(e)&&G.isSafeIterable(e)){let d=Object.create(null),f,h;for(const m of e){if(!G.isArray(m))throw new TypeError("Object iterator must return a key-value pair");h=m[0],G.hasOwnProp(d,h)?(f=d[h],d[h]=G.isArray(f)?[...f,m[1]]:[f,m[1]]):d[h]=m[1]}c(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=ko(e),e){const r=G.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return KC(i);if(G.isFunction(n))return n.call(this,i,r);if(G.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ko(e),e){const r=G.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||pf(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(c){if(c=ko(c),c){const d=G.findKey(r,c);d&&(!n||pf(r,r[d],d,n))&&(delete r[d],i=!0)}}return G.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||pf(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return G.forEach(this,(i,l)=>{const c=G.findKey(r,l);if(c){n[c]=hc(i),delete n[l];return}const d=e?QC(l):String(l).trim();d!==l&&delete n[l],n[d]=hc(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return G.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&G.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){const e=this.get("set-cookie");return G.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return XC(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[Lm]=this[Lm]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ko(c);r[d]||(ZC(i,c),r[d]=!0)}return G.isArray(e)?e.forEach(l):l(e),this}};xn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),G.reduceDescriptors(xn.prototype,({value:s},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(r){this[n]=r}}}),G.freezeMethods(xn);const pc="[REDACTED ****]";function eE(s){if(G.hasOwnProp(s,"toJSON"))return!0;let e=Object.getPrototypeOf(s);for(;e&&e!==Object.prototype;){if(G.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function tE(s,e){const n=new Set(e.map(l=>String(l).toLowerCase())),r=[],i=l=>{if(l===null||typeof l!="object"||G.isBuffer(l))return l;if(r.indexOf(l)!==-1)return;l instanceof xn&&(l=l.toJSON()),r.push(l);let c;if(G.isArray(l))c=[],l.forEach((d,f)=>{const h=i(d);G.isUndefined(h)||(c[f]=h)});else{if(!G.isPlainObject(l)&&eE(l))return r.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const h=n.has(d.toLowerCase())?pc:i(f);G.isUndefined(h)||(c[d]=h)}}return r.pop(),c};return i(s)}function $m(s){try{return String(s)}catch{return""}}function nE(s){return s.errors.map(n=>{try{return n&&n.message?$m(n.message):$m(n)}catch{return""}}).filter(Boolean).join("; ")||s.name||"AggregateError"}let we=class n0 extends Error{static from(e,n,r,i,l,c){let d=e.message;!d&&G.isArray(e.errors)&&e.errors.length&&(d=nE(e));const f=new n0(d,n||e.code,r,i,l);return Object.defineProperty(f,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),f.name=e.name,e.status!=null&&f.status==null&&(f.status=e.status),c&&Object.assign(f,c),f}constructor(e,n,r,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),r&&(this.config=r),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&G.hasOwnProp(e,"redact")?e.redact:void 0,r=G.isArray(n)&&n.length>0?tE(e,n):G.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:r,code:this.code,status:this.status}}};we.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",we.ERR_BAD_OPTION="ERR_BAD_OPTION",we.ECONNABORTED="ECONNABORTED",we.ETIMEDOUT="ETIMEDOUT",we.ECONNREFUSED="ECONNREFUSED",we.ERR_NETWORK="ERR_NETWORK",we.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",we.ERR_DEPRECATED="ERR_DEPRECATED",we.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",we.ERR_BAD_REQUEST="ERR_BAD_REQUEST",we.ERR_CANCELED="ERR_CANCELED",we.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",we.ERR_INVALID_URL="ERR_INVALID_URL",we.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const rE=null,Mm=100;function gf(s){return G.isPlainObject(s)||G.isArray(s)}function Nm(s){return G.endsWith(s,"[]")?s.slice(0,-2):s}function mf(s,e,n){return s?s.concat(e).map(function(i,l){return i=Nm(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function aE(s){return G.isArray(s)&&!s.some(gf)}const iE=G.toFlatObject(G,{},null,function(e){return/^is[A-Z]/.test(e)});function gc(s,e,n){if(!G.isObject(s))throw new TypeError("target must be an object");e=e||new FormData;const r=(O,k)=>{const L=G.getSafeProp(n,O);return G.isUndefined(L)?k:L},i=r("metaTokens",!0),l=r("visitor")||x,c=r("dots",!1),d=r("indexes",!1),f=r("Blob")||typeof Blob<"u"&&Blob,h=r("maxDepth",Mm),m=f&&G.isSpecCompliantForm(e),y=[];if(!G.isFunction(l))throw new TypeError("visitor must be a function");function v(O){if(O===null)return"";if(G.isDate(O))return O.toISOString();if(G.isBoolean(O))return O.toString();if(!m&&G.isBlob(O))throw new we("Blob is not supported. Use a Buffer instead.");if(G.isArrayBuffer(O)||G.isTypedArray(O)){if(m&&typeof f=="function")return new f([O]);throw new we("Blob is not supported. Use a Buffer instead.",we.ERR_NOT_SUPPORT)}return O}function S(O){if(O>h)throw new we("Object is too deeply nested ("+O+" levels). Max depth: "+h,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _(O,k){if(h===1/0)return JSON.stringify(O);const L=[];return JSON.stringify(O,function(q,z){if(!G.isObject(z))return z;for(;L.length&&L[L.length-1]!==this;)L.pop();return L.push(z),S(k+L.length-1),z})}function x(O,k,L){let B=O;if(G.isReactNative(e)&&G.isReactNativeBlob(O))return e.append(mf(L,k,c),v(O)),!1;if(O&&!L&&typeof O=="object"){if(G.endsWith(k,"{}"))k=i?k:k.slice(0,-2),O=_(O,1);else if(G.isArray(O)&&aE(O)||(G.isFileList(O)||G.endsWith(k,"[]"))&&(B=G.toArray(O)))return k=Nm(k),B.forEach(function(z,W){!(G.isUndefined(z)||z===null)&&e.append(d===!0?mf([k],W,c):d===null?k:k+"[]",v(z))}),!1}return gf(O)?!0:(e.append(mf(L,k,c),v(O)),!1)}const A=Object.assign(iE,{defaultVisitor:x,convertValue:v,isVisitable:gf});function D(O,k,L=0){if(!G.isUndefined(O)){if(S(L),y.indexOf(O)!==-1)throw new Error("Circular reference detected in "+k.join("."));y.push(O),G.forEach(O,function(q,z){(!(G.isUndefined(q)||q===null)&&l.call(e,q,G.isString(z)?z.trim():z,k,A))===!0&&D(q,k?k.concat(z):[z],L+1)}),y.pop()}}if(!G.isObject(s))throw new TypeError("data must be an object");return D(s),e}function Im(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(s).replace(/[!'()~]|%20/g,function(r){return e[r]})}function yf(s,e){this._pairs=[],s&&gc(s,this,e)}const jm=yf.prototype;jm.append=function(e,n){this._pairs.push([e,n])},jm.toString=function(e){const n=e?r=>e.call(this,r,Im):Im;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function sE(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Hm(s,e,n){if(!e)return s;s=s||"";const r=G.isFunction(n)?{serialize:n}:n,i=G.getSafeProp(r,"encode")||sE,l=G.getSafeProp(r,"serialize");let c;if(l?c=l(e,r):c=G.isURLSearchParams(e)?e.toString():new yf(e,r).toString(i),c){const d=s.indexOf("#");d!==-1&&(s=s.slice(0,d)),s+=(s.indexOf("?")===-1?"?":"&")+c}return s}const Ro=Symbol("internals");function zm(s){return s?s.length:0}function Pm(s){if(s)for(;s.length&&s[s.length-1]===null;)s.pop()}function Do(s,e){const n=s.handlers,r=zm(n);n!==e.handlersRef?(e.handlersRef=n,e.handlerEntries.clear()):r!==e.handlersLength&&(r?e.handlerEntries.forEach(function(l,c){n[l.index]!==l.handler&&e.handlerEntries.delete(c)}):e.handlerEntries.clear()),e.handlersLength=r}class Um{constructor(){this.handlers=[],this[Ro]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,n,r){const i={fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null},l=this[Ro];this.handlers==null&&(this.handlers=[]),Do(this,l);const c=l.nextId++;return this.handlers.push(i),l.handlerEntries.set(c,{handler:i,index:this.handlers.length-1}),l.handlersLength=this.handlers.length,c}eject(e){const n=this[Ro];Do(this,n);const r=n.handlerEntries.get(e);if(r){if(n.handlerEntries.delete(e),this.handlers[r.index]!==r.handler)return;this.handlers[r.index]=null,n.iterationDepth||(Pm(this.handlers),n.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Do(this,this[Ro]))}forEach(e){const n=this[Ro];Do(this,n),n.iterationDepth++;try{G.forEach(this.handlers,function(i){i!==null&&e(i)})}finally{--n.iterationDepth||(Do(this,n),Pm(this.handlers),n.handlersLength=zm(this.handlers))}}}const bf={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},oE={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:yf,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},vf=typeof window<"u"&&typeof document<"u",Sf=typeof navigator=="object"&&navigator||void 0,lE=vf&&(!Sf||["ReactNative","NativeScript","NS"].indexOf(Sf.product)<0),cE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uE=vf&&window.location.href||"http://localhost",gn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:vf,hasStandardBrowserEnv:lE,hasStandardBrowserWebWorkerEnv:cE,navigator:Sf,origin:uE},Symbol.toStringTag,{value:"Module"})),...oE};function dE(s,e){return gc(s,new gn.classes.URLSearchParams,{visitor:function(n,r,i,l){return gn.isNode&&G.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Bm=Mm;function qm(s){if(s>Bm)throw new we("FormData field is too deeply nested ("+s+" levels). Max depth: "+Bm,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function fE(s){const e=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;let r;for(;(r=n.exec(s))!==null;)qm(e.length),e.push(r[0]==="[]"?"":r[1]||r[0]);return e}function hE(s){const e={},n=Object.keys(s);let r;const i=n.length;let l;for(r=0;r=n.length;return c=!c&&G.isArray(i)?i.length:c,f?(G.hasOwnProp(i,c)?i[c]=G.isArray(i[c])?i[c].concat(r):[i[c],r]:i[c]=r,!d):((!G.hasOwnProp(i,c)||!G.isObject(i[c]))&&(i[c]=[]),e(n,r,i[c],l)&&G.isArray(i[c])&&(i[c]=hE(i[c])),!d)}if(G.isFormData(s)&&G.isFunction(s.entries)){const n={};return G.forEachEntry(s,(r,i)=>{e(fE(r),i,n,0)}),n}return null}const Fm=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),ms=(s,e)=>s!=null&&G.hasOwnProp(s,e)?s[e]:void 0;function pE(s,e,n){if(G.isString(s))try{return(e||JSON.parse)(s),G.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(s)}const Oo={transitional:bf,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=G.isObject(e);if(l&&G.isHTMLForm(e)&&(e=new FormData(e)),G.isFormData(e))return i?JSON.stringify(Gm(e)):e;if(G.isArrayBuffer(e)||G.isBuffer(e)||G.isStream(e)||G.isFile(e)||G.isBlob(e)||G.isReadableStream(e))return e;if(G.isArrayBufferView(e))return e.buffer;if(G.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=ms(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return dE(e,f).toString();if((d=G.isFileList(e))||r.indexOf("multipart/form-data")>-1){const h=ms(this,"env"),m=h&&h.FormData;return gc(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),pE(e)):e}],transformResponse:[function(e){const n=ms(this,"transitional")||Oo.transitional,r=n&&n.forcedJSONParsing,i=ms(this,"responseType"),l=i==="json";if(G.isResponse(e)||G.isReadableStream(e))return e;if(e&&G.isString(e)&&(r&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,ms(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?we.from(f,we.ERR_BAD_RESPONSE,this,null,ms(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:gn.classes.FormData,Blob:gn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};G.forEach(Fm,s=>{Oo.headers[s]={}});function wf(s,e){const n=this||Oo,r=e||n,i=xn.from(r.headers);let l=r.data;return G.forEach(s,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Vm(s){return!!(s&&s.__CANCEL__)}let Lo=class extends we{constructor(e,n,r){super(e??"canceled",we.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function Km(s,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?s(n):e(new we("Request failed with status code "+n.status,n.status>=400&&n.status<500?we.ERR_BAD_REQUEST:we.ERR_BAD_RESPONSE,n.config,n.request,n))}const gE=/[\t\n\r]/g;function Wm(s){if(typeof s!="string")return s;let e=0;for(;e{n=y,i=null,l&&(clearTimeout(l),l=null),s(...m)};return[(...m)=>{const y=Date.now(),v=y-n;v>=r?c(m,y):(i=m,l||(l=setTimeout(()=>{l=null,c(i)},r-v)))},()=>i&&c(i),(...m)=>c(m)]}const mc=(s,e,n=3)=>{let r=0;const i=mE(50,250);return yE(l=>{if(!l||!G.isNumber(l.loaded))return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=Math.max(0,d!=null?Math.min(c,d):c),h=Math.max(0,f-r),m=i(h);r=Math.max(r,f);const y={loaded:f,total:d,progress:d?f/d:void 0,bytes:h,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};s(y)},n)},Ym=(s,e)=>{const n=s!=null;return[r=>e[0]({lengthComputable:n,total:s,loaded:r}),e[1]]},Xm=(s,e=G.asap)=>(...n)=>e(()=>s(...n)),bE=gn.hasStandardBrowserEnv?((s,e)=>n=>(n=new URL(n,gn.origin),s.protocol===n.protocol&&s.host===n.host&&(e||s.port===n.port)))(new URL(gn.origin),gn.navigator&&/(msie|trident)/i.test(gn.navigator.userAgent)):()=>!0,vE=gn.hasStandardBrowserEnv?{write(s,e,n,r,i,l,c){if(typeof document>"u")return;const d=[`${s}=${encodeURIComponent(e)}`];G.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),G.isString(r)&&d.push(`path=${r}`),G.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),G.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;n0&&s.charCodeAt(n-1)===47;)n--;return s.slice(0,n)+"/"+e.replace(/^\/+/,"")}const CE=/^https?:(?!\/\/)/i;function EE(s){return s&&s.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,n,r="")=>`${n}${r}${pc}`)}function _E(s){const e=s.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${pc}@`),n=e.indexOf("#"),i=(n===-1?e:e.slice(0,n)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${pc}`);return n===-1?i:`${i}#${EE(e.slice(n+1))}`}function Jm(s,e){if(typeof s=="string"){const n=Wm(s);if(CE.test(n))throw new we(`Invalid URL ${JSON.stringify(_E(n))}: missing "//" after protocol`,we.ERR_INVALID_URL,e)}}function Qm(s,e,n,r){Jm(e,r);let i=!SE(e);return s&&(i||n===!1)?(Jm(s,r),wE(s,e)):e}const Zm=s=>s instanceof xn?{...s}:s,AE=s=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(s).concat(Object.getOwnPropertySymbols(s).filter(e=>Object.getOwnPropertyDescriptor(s,e).enumerable)):Object.keys(s);function xi(s,e){s=s||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(m,y,v,S){return G.isPlainObject(m)&&G.isPlainObject(y)?G.merge.call({caseless:S},m,y):G.isPlainObject(y)?G.merge({},y):G.isArray(y)?y.slice():y}function i(m,y,v,S){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m,v,S)}else return r(m,y,v,S)}function l(m,y){if(!G.isUndefined(y))return r(void 0,y)}function c(m,y){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m)}else return r(void 0,y)}function d(m){const y=G.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!G.isUndefined(y))if(G.isPlainObject(y)){if(G.hasOwnProp(y,m))return y[m]}else return;const v=G.hasOwnProp(s,"transitional")?s.transitional:void 0;if(G.isPlainObject(v)&&G.hasOwnProp(v,m))return v[m]}function f(m,y,v){if(G.hasOwnProp(e,v))return r(m,y);if(G.hasOwnProp(s,v))return r(void 0,m)}const h={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutErrorMessage: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,v)=>i(Zm(m),Zm(y),v,!0)};return G.forEach(AE({...s,...e}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=G.hasOwnProp(h,y)?h[y]:i,S=G.hasOwnProp(s,y)?s[y]:void 0,_=G.hasOwnProp(e,y)?e[y]:void 0,x=v(S,_,y);G.isUndefined(x)&&v!==f||(n[y]=x)}),G.hasOwnProp(e,"validateStatus")&&G.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(G.hasOwnProp(s,"validateStatus")?n.validateStatus=r(void 0,s.validateStatus):delete n.validateStatus),n}const xE=["content-type","content-length"];function TE(s,e,n){if(n!=="content-only"){s.set(e);return}Object.entries(e||{}).forEach(([r,i])=>{xE.includes(r.toLowerCase())&&s.set(r,i)})}const kE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function ey(s){const e=xi({},s),n=v=>G.hasOwnProp(e,v)?e[v]:void 0,r=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),h=n("baseURL"),m=n("allowAbsoluteUrls"),y=n("url");if(e.headers=d=xn.from(d),e.url=Hm(Qm(h,y,m,e),n("params"),n("paramsSerializer")),f){const v=G.getSafeProp(f,"username")||"",S=G.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(v+":"+(S?kE(S):"")))}catch(_){throw we.from(_,we.ERR_BAD_OPTION_VALUE,s)}}if(G.isFormData(r)){const v=G.getSafeProp(r,"getHeaders");gn.hasStandardBrowserEnv||gn.hasStandardBrowserWebWorkerEnv||G.isReactNative(r)?d.setContentType(void 0):G.isFunction(v)&&TE(d,v.call(r),n("formDataHeaderPolicy"))}if(gn.hasStandardBrowserEnv&&(G.isFunction(i)&&(i=i(e)),i===!0||i==null&&bE(e.url))){const S=l&&c&&vE.read(c);S&&d.set(l,S)}return e}const RE=typeof XMLHttpRequest<"u"&&function(s){return new Promise(function(n,r){const i=ey(s);let l=i.data;const c=xn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:h}=i,m,y,v,S,_,x;function A(){S&&S(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let D=new XMLHttpRequest;D.open(i.method.toUpperCase(),i.url,!0),D.timeout=i.timeout;function O(L){if(!D)return;if(D.status===0&&(Cf(Wm(i.url))||Cf(gn.origin))!=="file"&&!(D.responseURL&&D.responseURL.startsWith("file:"))){r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null;return}try{L?x&&x(L):_&&_()}catch(W){setTimeout(()=>{throw W})}if(!D)return;const B=xn.from("getAllResponseHeaders"in D&&D.getAllResponseHeaders()),z={data:!d||d==="text"||d==="json"?D.responseText:D.response,status:D.status,statusText:D.statusText,headers:B,config:s,request:D};Km(function(de){n(de),A()},function(de){r(de),A()},z),D=null}"onloadend"in D?D.onloadend=O:D.onreadystatechange=function(){!D||D.readyState!==4||D.status===0&&!(D.responseURL&&D.responseURL.startsWith("file:"))||setTimeout(O)},D.onabort=function(){D&&(r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null)},D.onerror=function(B){const q=B&&B.message?B.message:"Network Error",z=new we(q,we.ERR_NETWORK,s,D);z.event=B||null,r(z),A(),D=null},D.ontimeout=function(){let B=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const q=i.transitional||bf;i.timeoutErrorMessage&&(B=i.timeoutErrorMessage),r(new we(B,q.clarifyTimeoutError?we.ETIMEDOUT:we.ECONNABORTED,s,D)),A(),D=null},l===void 0&&c.setContentType(null),"setRequestHeader"in D&&G.forEach(Om(c),function(B,q){D.setRequestHeader(q,B)}),G.isUndefined(i.withCredentials)||(D.withCredentials=!!i.withCredentials),d&&d!=="json"&&(D.responseType=i.responseType),h&&([v,_,x]=mc(h,!0),D.addEventListener("progress",v)),f&&D.upload&&([y,S]=mc(f),D.upload.addEventListener("progress",y),D.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=L=>{D&&(r(!L||L.type?new Lo(null,s,D):L),D.abort(),A(),D=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const k=Cf(i.url);if(k&&!gn.protocols.includes(k)){r(new we("Unsupported protocol "+k+":",we.ERR_BAD_REQUEST,s)),A();return}D.send(l||null)})},DE=(s,e)=>{if(s=s?s.filter(Boolean):[],!e&&!s.length)return;const n=new AbortController;let r=!1;const i=function(f){if(!r){r=!0,c();const h=f instanceof Error?f:this.reason;n.abort(h instanceof we?h:new Lo(h instanceof Error?h.message:h))}};let l=e&&setTimeout(()=>{l=null,i(new we(`timeout of ${e}ms exceeded`,we.ETIMEDOUT))},e);const c=()=>{s&&(l&&clearTimeout(l),l=null,s.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),s=null)};s.forEach(f=>{if(!r){if(f.aborted){i.call(f);return}f.addEventListener("abort",i,{once:!0})}});const{signal:d}=n;return d.unsubscribe=()=>G.asap(c),d},OE=function*(s,e){let n=s.byteLength;if(n{const i=LE(s,e);let l=0,c,d=f=>{c||(c=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:h,value:m}=await i.next();if(h){d(),f.close();return}let y=m.byteLength;if(n){let v=l+=y;n(v)}f.enqueue(new Uint8Array(m))}catch(h){throw d(h),h}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},ny=s=>s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102,ry=(s,e,n)=>e+2s<=57?s-48:(s&223)-55,ME=s=>s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47||s===45||s===95,NE=s=>s===9||s===10||s===12||s===13||s===32,IE=s=>{const e=Math.floor(s/4),n=s%4;return e*3+(n===2?1:n===3?2:0)},jE=s=>{const e=s.length;let n=0;return e>0&&s.charCodeAt(e-1)===61&&(n++,e>1&&s.charCodeAt(e-2)===61&&n++),Math.floor((e-n)*3/4)},HE=s=>{const e=s.length;let n=0,r=0,i=!1;for(let l=0;l0){i=!0;continue}n++}}return i||r>2||r>0&&(n+r)%4!==0||n%4===1?jE(s):IE(n)},zE=(s,e)=>{if(!s||typeof s!="string"||!s.startsWith("data:"))return 0;const n=s.indexOf(",");if(n<0)return 0;const r=s.slice(5,n),i=s.slice(n+1);if(/;base64/i.test(r))return e(i);let c=0;for(let d=0,f=i.length;d=55296&&h<=56319&&d+1=56320&&m<=57343?(c+=4,d++):c+=3}else c+=3}return c};function PE(s){const e=typeof s=="string"?s.indexOf("#"):-1;return zE(e===-1?s:s.slice(0,e),HE)}const Ef="1.20.0",iy=64*1024,UE={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:yc}=G,BE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),sy=s=>{if(!G.isString(s))return s;try{return decodeURIComponent(s)}catch{return s}},oy=(s,...e)=>{try{return!!s(...e)}catch{return!1}},qE=s=>{const e=s.indexOf("://");let n=s;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},GE=s=>{const e=G.global!==void 0&&G.global!==null?G.global:globalThis,{ReadableStream:n,TextEncoder:r}=e;s=G.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},s);const{fetch:i,Request:l,Response:c}=s,d=i?yc(i):typeof fetch=="function",f=yc(l),h=yc(c);if(!d)return!1;const m=d&&yc(n),y=d&&(typeof r=="function"?(D=>O=>D.encode(O))(new r):async D=>new Uint8Array(await new l(D).arrayBuffer())),v=f&&m&&oy(()=>{let D=!1;const O=new l(gn.origin,{body:new n,method:"POST",get duplex(){return D=!0,"half"}}),k=O.headers.has("Content-Type");return O.body!=null&&O.body.cancel(),D&&!k}),S=h&&m&&oy(()=>G.isReadableStream(new c("").body)),_={stream:S&&(D=>D.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(D=>{!_[D]&&(_[D]=(O,k)=>{let L=O&&O[D];if(L)return L.call(O);throw new we(`Response type '${D}' is not supported`,we.ERR_NOT_SUPPORT,k)})});const x=async D=>{if(D==null)return 0;if(G.isBlob(D))return D.size;if(G.isSpecCompliantForm(D))return(await new l(gn.origin,{method:"POST",body:D}).arrayBuffer()).byteLength;if(G.isArrayBufferView(D)||G.isArrayBuffer(D))return D.byteLength;if(G.isURLSearchParams(D)&&(D=D+""),G.isString(D))return(await y(D)).byteLength},A=async(D,O)=>{const k=G.toFiniteNumber(D.getContentLength());return k??x(O)};return async D=>{let{url:O,method:k,data:L,signal:B,cancelToken:q,timeout:z,onDownloadProgress:W,onUploadProgress:de,responseType:_e,headers:Se,withCredentials:Ie="same-origin",fetchOptions:Fe,maxContentLength:ze,maxBodyLength:Et,maxRedirects:Q}=ey(D);const ue=G.isNumber(ze)&&ze>-1,De=G.isNumber(Et)&&Et>-1,ee=ge=>G.hasOwnProp(D,ge)?D[ge]:void 0;let me=i||fetch;_e=_e?(_e+"").toLowerCase():"text";let H=DE([B,q&&q.toAbortSignal()],z),T=null;const fe=H&&H.unsubscribe&&(()=>{H.unsubscribe()});let he,Ae=null;const se=()=>new we("Request body larger than maxBodyLength limit",we.ERR_BAD_REQUEST,D,T);try{let ge;const $e=ee("auth");if($e){const qe=G.getSafeProp($e,"username")||"",mt=G.getSafeProp($e,"password")||"";ge={username:qe,password:mt}}if(qE(O)){const qe=new URL(O,gn.origin);if(!ge&&(qe.username||qe.password)){const mt=sy(qe.username),Dt=sy(qe.password);ge={username:mt,password:Dt}}(qe.username||qe.password)&&(qe.username="",qe.password="",O=qe.href)}if(ge&&(Se.delete("authorization"),Se.set("Authorization","Basic "+btoa(BE((ge.username||"")+":"+(ge.password||""))))),ue&&typeof O=="string"&&O.startsWith("data:")&&PE(O)>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);if(De&&k!=="get"&&k!=="head"){const qe=await x(L);if(typeof qe=="number"&&isFinite(qe)&&(he=qe,qe>Et))throw se()}const Te=De&&(G.isReadableStream(L)||G.isStream(L)),je=(qe,mt,Dt)=>ty(qe,iy,zt=>{if(De&&zt>Et)throw Ae=se();mt&&mt(zt)},Dt);if(v&&k!=="get"&&k!=="head"&&(de||Te)){if(he=he??await A(Se,L),he!==0||Te){let qe=new l(O,{method:"POST",body:L,duplex:"half"}),mt;if(G.isFormData(L)&&(mt=qe.headers.get("content-type"))&&Se.setContentType(mt),qe.body){const[Dt,zt]=de&&Ym(he,mc(Xm(de)))||[];L=je(qe.body,Dt,zt)}}}else if(Te&&!f&&m&&k!=="get"&&k!=="head")L=je(L);else if(Te&&f&&!v&&k!=="get"&&k!=="head")throw new we("Stream request bodies are not supported by the current fetch implementation",we.ERR_NOT_SUPPORT,D,T);G.isString(Ie)||(Ie=Ie?"include":"omit");const xt=f&&"credentials"in l.prototype;if(G.isFormData(L)){const qe=Se.getContentType();qe&&/^multipart\/form-data/i.test(qe)&&!/boundary=/i.test(qe)&&Se.delete("content-type")}Se.set("User-Agent","axios/"+Ef,!1);const rt=Fe==null?Fe:Object.assign(Object.create(null),Fe);rt&&(delete rt.body,delete rt.headers,delete rt.method,delete rt.signal,delete rt.duplex,delete rt.credentials);const gt=Object.assign(Object.create(null),rt,{signal:H,method:k.toUpperCase(),headers:Om(Se.normalize()),body:L,duplex:"half",credentials:xt?Ie:void 0});f&&(G.forEach(UE,(qe,mt)=>{gt[mt]===void 0&&(gt[mt]=qe)}),gt.signal===void 0&&(gt.signal=null),gt.body===void 0&&(gt.body=null)),Q===0&&(gt.redirect="manual",rt&&(rt.redirect="manual")),T=f&&new l(O,gt);let at=await(f?me(T,rt):me(O,gt));const Yt=xn.from(at.headers);if(ue){const qe=G.toFiniteNumber(Yt.getContentLength());if(qe!=null&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}const Ht=S&&(_e==="stream"||_e==="response");if(S&&at.body&&(W||ue||Ht&&fe)){const qe={};["status","statusText","headers"].forEach(Ot=>{qe[Ot]=at[Ot]});const mt=G.toFiniteNumber(Yt.getContentLength()),[Dt,zt]=W&&Ym(mt,mc(Xm(W),!0))||[];let kn=0;const dr=Ot=>{if(ue&&(kn=Ot,kn>ze))throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);Dt&&Dt(Ot)};at=new c(ty(at.body,iy,dr,()=>{zt&&zt(),fe&&fe()}),qe)}_e=_e||"text";let bt=await _[G.findKey(_,_e)||"text"](at,D);if(ue&&!S&&!Ht){let qe;if(bt!=null&&(typeof bt.byteLength=="number"?qe=bt.byteLength:typeof bt.size=="number"?qe=bt.size:typeof bt=="string"&&(qe=typeof r=="function"?new r().encode(bt).byteLength:bt.length)),typeof qe=="number"&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}return!Ht&&fe&&fe(),await new Promise((qe,mt)=>{Km(qe,mt,{data:bt,headers:xn.from(at.headers),status:at.status,statusText:at.statusText,config:D,request:T})})}catch(ge){if(fe&&fe(),H&&H.aborted&&H.reason instanceof we){const $e=H.reason;throw $e.config=D,T&&($e.request=T),ge!==$e&&Object.defineProperty($e,"cause",{__proto__:null,value:ge,writable:!0,enumerable:!1,configurable:!0}),$e}if(Ae)throw T&&!Ae.request&&(Ae.request=T),Ae;if(ge instanceof we)throw T&&!ge.request&&(ge.request=T),ge;if(ge&&ge.name==="TypeError"&&/Load failed|fetch/i.test(ge.message)){const $e=new we("Network Error",we.ERR_NETWORK,D,T,ge&&ge.response);throw Object.defineProperty($e,"cause",{__proto__:null,value:ge.cause||ge,writable:!0,enumerable:!1,configurable:!0}),$e}throw we.from(ge,ge&&ge.code,D,T,ge&&ge.response)}}},FE=new Map,ly=s=>{let e=s&&s.env||{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let c=l.length,d=c,f,h,m=FE;for(;d--;)f=l[d],h=m.get(f),h===void 0&&m.set(f,h=d?new Map:GE(e)),m=h;return h};ly();const _f={http:rE,xhr:RE,fetch:{get:ly}};G.forEach(_f,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(s,"adapterName",{__proto__:null,value:e})}});const cy=s=>`- ${s}`,VE=s=>G.isFunction(s)||s===null||s===!1;function KE(s,e){s=G.isArray(s)?s:[s];const{length:n}=s;let r,i;const l={};for(let c=0;c`adapter ${f} `+(h===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : `+c.map(cy).join(` -`):" "+cy(c[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+d,we.ERR_NOT_SUPPORT)}return i}const uy={getAdapter:VE,adapters:_f};function Af(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Lo(null,s)}function xf(s){const e=G.toSafeFlatObject(s);return Af(e),e.headers=xn.from(G.getSafeProp(e,"headers")),e.data=wf.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),uy.getAdapter(e.adapter||Oo.adapter,e)(e).then(function(i){Af(e),e.response=i;try{i.data=wf.call(e,e.transformResponse,i)}finally{delete e.response}return i.headers=xn.from(i.headers),i},function(i){if(!Vm(i)&&(Af(e),i&&i.response)){e.response=i.response;try{i.response.data=wf.call(e,e.transformResponse,i.response)}finally{delete e.response}i.response.headers=xn.from(i.response.headers)}return Promise.reject(i)})}const bc={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{bc[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});const dy={};bc.transitional=function(e,n,r){function i(l,c){return"[Axios v"+Ef+"] Transitional option '"+l+"'"+c+(r?". "+r:"")}return(l,c,d)=>{if(e===!1)throw new we(i(c," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!dy[c]&&(dy[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}},bc.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function KE(s,e,n){if(typeof s!="object"||s===null)throw new we("options must be an object",we.ERR_BAD_OPTION_VALUE);const r=Object.keys(s);let i=r.length;for(;i-- >0;){const l=r[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=s[l],f=d===void 0||c(d,l,s);if(f!==!0)throw new we("option "+l+" must be "+f,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+l,we.ERR_BAD_OPTION)}}const vc={assertOptions:KE,validators:bc},Tn=vc.validators;let Ti=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Um,response:new Um}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error)try{let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack;let c="";if(typeof l=="string"){const d=l.indexOf(` +`):" "+cy(c[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+d,we.ERR_NOT_SUPPORT)}return i}const uy={getAdapter:KE,adapters:_f};function Af(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Lo(null,s)}function xf(s){const e=G.toSafeFlatObject(s);return Af(e),e.headers=xn.from(G.getSafeProp(e,"headers")),e.data=wf.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),uy.getAdapter(e.adapter||Oo.adapter,e)(e).then(function(i){Af(e),e.response=i;try{i.data=wf.call(e,e.transformResponse,i)}finally{delete e.response}return i.headers=xn.from(i.headers),i},function(i){if(!Vm(i)&&(Af(e),i&&i.response)){e.response=i.response;try{i.response.data=wf.call(e,e.transformResponse,i.response)}finally{delete e.response}i.response.headers=xn.from(i.response.headers)}return Promise.reject(i)})}const bc={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{bc[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});const dy={};bc.transitional=function(e,n,r){function i(l,c){return"[Axios v"+Ef+"] Transitional option '"+l+"'"+c+(r?". "+r:"")}return(l,c,d)=>{if(e===!1)throw new we(i(c," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!dy[c]&&(dy[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}},bc.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function WE(s,e,n){if(typeof s!="object"||s===null)throw new we("options must be an object",we.ERR_BAD_OPTION_VALUE);const r=Object.keys(s);let i=r.length;for(;i-- >0;){const l=r[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=s[l],f=d===void 0||c(d,l,s);if(f!==!0)throw new we("option "+l+" must be "+f,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+l,we.ERR_BAD_OPTION)}}const vc={assertOptions:WE,validators:bc},Tn=vc.validators;let Ti=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Um,response:new Um}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error)try{let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack;let c="";if(typeof l=="string"){const d=l.indexOf(` `);c=d===-1?"":l.slice(d+1)}if(!r.stack)r.stack=c;else if(c){const d=c.indexOf(` `),f=d===-1?-1:c.indexOf(` `,d+1),h=f===-1?"":c.slice(f+1);String(r.stack).endsWith(h)||(r.stack+=` -`+c)}}catch{}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=xi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&vc.assertOptions(r,{silentJSONParsing:Tn.transitional(Tn.boolean),forcedJSONParsing:Tn.transitional(Tn.boolean),clarifyTimeoutError:Tn.transitional(Tn.boolean),legacyInterceptorReqResOrdering:Tn.transitional(Tn.boolean),advertiseZstdAcceptEncoding:Tn.transitional(Tn.boolean),validateStatusUndefinedResolves:Tn.transitional(Tn.boolean)},!1),i!=null&&(G.isFunction(i)?n.paramsSerializer={serialize:i}:vc.assertOptions(i,{encode:Tn.function,serialize:Tn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),vc.assertOptions(n,{baseUrl:Tn.spelling("baseURL"),withXsrfToken:Tn.spelling("withXSRFToken")},!0),n.method=(G.getSafeProp(n,"method")||G.getSafeProp(this.defaults,"method")||"get").toLowerCase();let c=l&&G.merge(l.common,l[n.method]);l&&G.forEach(Fm.concat("common"),_=>{delete l[_]}),n.headers=xn.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){if(typeof x.runWhen=="function"&&x.runWhen(n)===!1)return;f=f&&x.synchronous;const A=n.transitional||bf;A&&A.legacyInterceptorReqResOrdering?d.unshift(x.fulfilled,x.rejected):d.push(x.fulfilled,x.rejected)});const h=[];this.interceptors.response.forEach(function(x){h.push(x.fulfilled,x.rejected)});let m,y=0,v;if(!f){const _=[xf.bind(this),void 0];for(_.unshift(...d),_.push(...h),v=_.length,m=Promise.resolve(n);yxf.call(this,S)))}catch(D){m=Promise.reject(D)}break}}if(!m)try{m=xf.call(this,S)}catch(_){m=Promise.reject(_)}for(y=0,v=h.length;y{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{r.subscribe(d),l=d}).then(i);return c.cancel=function(){r.unsubscribe(l)},c},e(function(l,c,d){r.reason||(r.reason=new Lo(l,c,d),n(r.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=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new n0(function(i){e=i}),cancel:e}}};function YE(s){return function(n){return s.apply(null,n)}}function XE(s){return G.isObject(s)&&s.isAxiosError===!0}const Sc={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Sc).forEach(([s,e])=>{Sc[e]===void 0&&(Sc[e]=s)});function fy(s){const e=new Ti(s),n=bm(Ti.prototype.request,e);return G.extend(n,Ti.prototype,e,{allOwnKeys:!0}),G.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return fy(xi(s,i))},n}const Qt=fy(Oo);Qt.Axios=Ti,Qt.CanceledError=Lo,Qt.CancelToken=WE,Qt.isCancel=Vm,Qt.VERSION=Ef,Qt.toFormData=gc,Qt.AxiosError=we,Qt.Cancel=Qt.CanceledError,Qt.all=function(e){return Promise.all(e)},Qt.spread=YE,Qt.isAxiosError=XE,Qt.mergeConfig=xi,Qt.AxiosHeaders=xn,Qt.formToJSON=s=>Gm(G.isHTMLForm(s)?new FormData(s):s),Qt.getAdapter=uy.getAdapter,Qt.HttpStatusCode=Sc,Qt.default=Qt;const{Axios:kR,AxiosError:RR,CanceledError:DR,isCancel:OR,CancelToken:LR,VERSION:$R,all:MR,Cancel:NR,isAxiosError:IR,spread:jR,toFormData:HR,AxiosHeaders:zR,HttpStatusCode:PR,formToJSON:UR,getAdapter:BR,mergeConfig:qR,create:GR}=Qt,Tf="g7.identity.redirectStash",wc=pt("IdentityGuardInterceptor");class At{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){wc.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,r){this.domainNoticeShown=!1;const i=this.launcher??QE,c=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const h=JE(f.url,d.token);return fetch(h,{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 wc.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 r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch(i){wc.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}}M(At,"launcher",null),M(At,"deferredResolver",null),M(At,"domainNoticeShown",!1);function JE(s,e){if(!e)return s;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(s,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(s)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=s.includes("?")?"&":"?";return`${s}${n}verification_token=${encodeURIComponent(e)}`}}const QE=async s=>{if(typeof window>"u")return{status:"cancelled"};if(s.render_hint==="external_redirect"||s.redirect_url)return At.redirectExternally(s);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,r={return_url:n,payload:s,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){wc.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},ZE=pt("ApiClient");function kf(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class e_{constructor(e={}){M(this,"client");M(this,"config");M(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=Qt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];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)r.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.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&&!this.isCrossOriginRequest(e.url)&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=kf();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=r.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,r=n._devToolsRequestId;if(r){const i=kf();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(c=>r.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await Ar.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(At.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[v,S]of Object.entries(d))typeof S=="string"&&(c[v]=S);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 h=n?.identity_target,m=await At.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},h);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,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).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 r=kf();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}isCrossOriginRequest(e){if(!e||typeof window>"u"||!window.location||!/^(https?:)?\/\//i.test(e))return!1;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}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 r=e.params,i=[];for(const[l,c]of Object.entries(r))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(r){ZE.error("Error in onError handler:",r)}}}let Rf=null;function qr(){return Rf||(Rf=new e_),Rf}const $o=pt("AuthManager");function ms(s,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(s,e,n,r)}catch{}}const Cc={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"}},Or=class Or{constructor(){M(this,"state");M(this,"config");M(this,"isRefreshing",!1);M(this,"refreshPromise",null);M(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",Cc.admin),this.config.set("user",Cc.user)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=qr();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return $o.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 $o.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=qr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?Cc.admin.loginEndpoint:Cc.user.loginEndpoint;try{const d=r?.headers?{headers:r.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const h=f.data.user.language,m=localStorage.getItem(Or.LOCALE_STORAGE_KEY),y=h&&h!==m;if(h)try{localStorage.setItem(Or.LOCALE_STORAGE_KEY,h)}catch(v){$o.warn("Failed to save user language to localStorage:",v)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ms("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(h),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,h=new Error(f||d.message||"Login failed");throw h.response=d.response,h.status=d.response?.status,ms("login",!1,h.message,{type:e,status:d.response?.status}),h}}async logout(){const e=qr(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){$o.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ms("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.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 r=qr();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ms("token-refresh",!0,void 0,{type:e}),!0):(ms("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return $o.error("Token refresh failed:",i),ms("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return r&&(c+=`&reason=${encodeURIComponent(r)}`),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 r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=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 r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Or.instance=null}};M(Or,"instance"),M(Or,"LOCALE_STORAGE_KEY","g7_locale");let Ar=Or;const hy={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}}"}}},sa={findHandler(s,e){if(s){if(s[e])return s[e];if(s[String(e)])return s[String(e)];if(s.default)return s.default}},normalizeOnError(s){return s?Array.isArray(s)?s:[s]:[]},injectErrorCode(s,e,n){if(s.handler!=="showErrorPage"||s.params?.errorCode!==void 0)return s;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?s:{...s,params:{...s.params,errorCode:i}}}},xr=pt("ErrorHandlingResolver"),Ua=class Ua{constructor(){M(this,"templateErrorHandling",null);M(this,"layoutErrorHandling",null);M(this,"executeAction",null)}static getInstance(){return Ua.instance||(Ua.instance=new Ua),Ua.instance}static resetInstance(){Ua.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,xr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,xr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;xr.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=sa.findHandler(r,e);if(l){const c=this.getMatchedKey(r,e);return{handler:sa.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=sa.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=sa.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=sa.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=sa.findHandler(hy,e),l){const c=this.getMatchedKey(hy,e);return{handler:sa.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){xr.error("Action executor is not set");return}xr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw xr.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(xr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return xr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return xr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,xr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,xr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};M(Ua,"instance",null);let Df=Ua;function Tr(){return Df.getInstance()}function Mo(s,e){const n={...s};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=Mo(n[r],e[r])):n[r]=e[r];return n}var Of={exports:{}},No={};var py;function t_(){if(py)return No;py=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,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:s,type:r,key:c,ref:i!==void 0?i:null,props:l}}return No.Fragment=e,No.jsx=n,No.jsxs=n,No}var gy;function n_(){return gy||(gy=1,Of.exports=t_()),Of.exports}var yt=n_();const r_=na({__proto__:null,default:ra(yt)},[yt]),Lf=pt("ParentContextProvider"),my=I.createContext(null);let Ec=null;function $f(){Ec?(Lf.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ec()):Lf.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const yy=({children:s})=>{const[e,n]=I.useState(0),r=I.useRef(!0),i=I.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);I.useEffect(()=>(r.current=!0,Ec=()=>{r.current&&(n(c=>c+1),Lf.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Ec=null}),[]);const l={version:e,getParentDataContext:i};return yt.jsx(my.Provider,{value:l,children:s})};function a_(){return I.useContext(my)}function by(s){return s.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function vy(s,e){try{const n=typeof window<"u"&&window.location?.protocol||"https:",r=e||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",i=s.startsWith("//")?`${n}${s}`:s,l=new URL(i,r);return l.protocol!=="http:"&&l.protocol!=="https:"?null:l.hostname.toLowerCase()}catch{return null}}function ys(){const s=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(s)?s.map(e=>String(e).toLowerCase()):[]}function Io(s,e){if(typeof s!="string")return!1;const n=s.trim();if(n==="")return!1;const r=by(n),i=r.startsWith("//"),l=/^[a-z][a-z0-9+.-]*:/i.test(r);if(!i&&!l&&r.startsWith("/"))return!0;const c=vy(r),d=e??ys();return c!==null&&d.map(f=>String(f).toLowerCase()).includes(c)}const j=pt("ActionDispatcher");function i_(s,e,n,r){return n||(Wg(s)||Ud(s)?"$t:core.errors.network_request_failed":r||`Failed to execute action: ${e}`)}const Sy=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),s_=new Set(["redirect"]);function Yn(){try{return window.G7Core?.devTools}catch{return}}class jt extends Error{constructor(n,r,i){super(n);M(this,"action");M(this,"originalError");M(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const wy={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"},cn=class cn{constructor(e={},n,r){M(this,"bindingEngine");M(this,"translationEngine");M(this,"translationContext");M(this,"customHandlers",new Map);M(this,"defaultContext");M(this,"globalStateUpdater");M(this,"errorHandlingSetup",!1);M(this,"debounceTimers",new Map);M(this,"pendingDebounceFlushers",new Map);M(this,"debounceAccumulatedValues",new Map);M(this,"globalHeaders",[]);M(this,"namedActions",{});M(this,"previewMode",!1);M(this,"localMirrorDepth",0);M(this,"intervals",new Map);this.bindingEngine=new $n,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Yn();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 Sy}static getPreviewSuppressedLayoutFeatures(){return s_}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 r=Yn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,h={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(h.key=c),d!==void 0&&(h.event=d),h}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=fs(c,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;Tr().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{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={...r.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},h=r.data?._local||r.state||{},m={...f,...h},y=r.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,r)=>{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,r)=>{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,r)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:h=2e3,delay:m=0,retryCount:y=0,retryInterval:v=50,scrollContainer:S}=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(x=>{const A=document.querySelector(i);if(A){x(A);return}const D=setTimeout(()=>{O.disconnect(),x(null)},h),O=new MutationObserver(()=>{const k=document.querySelector(i);k&&(clearTimeout(D),O.disconnect(),x(k))});O.observe(document.body,{childList:!0,subtree:!0})}),!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${h}ms timeout`);return}}else{m>0&&await new Promise(A=>setTimeout(A,m)),_=document.querySelector(i);let x=0;for(;!_&&xsetTimeout(A,v)),_=document.querySelector(i),x++;if(!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){j.warn(`scrollIntoView: container not found for selector "${S}"`);return}const A=_.getBoundingClientRect(),D=x.getBoundingClientRect(),O=A.top-D.top+x.scrollTop,k=O+A.height;let L;switch(c){case"start":L=O;break;case"center":L=O-x.clientHeight/2+A.height/2;break;case"end":L=k-x.clientHeight;break;default:const B=A.topD.bottom;if(B)L=O;else if(q)L=k-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,L),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{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},r)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{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,r)=>{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,r)=>{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,r)=>{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,r)=>{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){if(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`module-${f}`;this.assertAllowedExtensionAssetUrl(h,`module script (${f})`,n),document.getElementById(m)?j.warn(`reloadModuleHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`module-script:${f}`}),j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`module-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`module stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`module-css:${f}`}),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 h=`module-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,h),h}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{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){if(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`plugin-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin script (${f})`,n),document.getElementById(m)?j.warn(`reloadPluginHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`plugin-script:${f}`}),j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`plugin-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`plugin-css:${f}`}),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 h=`plugin-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,h),h}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{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 h=(m,y=6e4)=>new Promise((v,S)=>{const _=document.getElementById(m);if(_){v(_);return}j.log(`showErrorPage: Waiting for container #${m}...`);let x;const A=new MutationObserver((D,O)=>{const k=document.getElementById(m);k&&(j.log(`showErrorPage: Container #${m} found`),O.disconnect(),clearTimeout(x),v(k))});A.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{A.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await h(f);const m=Tr(),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,r)=>{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:r.data,state:r.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 h=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...h,_eventResult:m}});const y=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:h;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,r)=>{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(v=>v.id===i?{...v,[l]:c,_modified:!0}:v),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,r)=>{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 h=f.state.get()||{},y=(h.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const _=S.options.map(x=>x.id===l?{...x,[c]:d,_modified:!0}:x);return{...S,options:_,_modified:!0}}return S}),v=new Set(h._local?.modifiedProductIds||[]);v.add(i),this.globalStateUpdater({products:{...h.products,data:{...h.products?.data,data:y}},_local:{...h._local,modifiedProductIds:Array.from(v)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(h){throw j.error("updateOptionField: Error updating option field",h),h}}),this.registerHandler("setLocale",async(n,r)=>{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=Yn();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 r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=r?.state?{...r.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?.()??r?.state??{},y=Date.now()-l;for(const v of Object.keys(c)){const S=c[v],_=m[v];S!==_&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${v}`,capturedValue:S,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${v} changed after handler creation:`,`captured="${S}" → current="${_}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let h={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const v=f.target;new FormData(v).forEach((_,x)=>{h[x]=_})}const m={...this.defaultContext,data:{...n,form:h,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let v=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext,m.data)),!confirm(v))return}const y=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(h){if(j.error("Action execution failed:",h),e.onError){const m=h instanceof jt&&h.originalError?h.originalError:h,y={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},v=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of v)await this.executeAction(S,y)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${r}_${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 r=Yn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&r&&r.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),h=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,h),!h)return i&&r&&r.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&&r&&r.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 h=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,h);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&Sy.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,h||f),i&&r&&r.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||h;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||h;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||h||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const _=window.G7Core,x={};if(_?.state?.get){const A=_.state.get();x._global=A}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const v=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(h,f,n,v,S);break;case"login":m=await this.handleLogin(h,f,n);break;case"logout":m=await this.handleLogout(h,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(h,f,n);break;case"openModal":m=await this.handleOpenModal(h,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(h,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:h,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:v,merge:S}=e.resultTo,_=this.resolveValue(v,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const A=this.buildNestedUpdate(_,m),D=x!=="deep"?{...A,__mergeMode:x}:A;this.writeLocalState(n,D),j.log(`[resultTo] Saved to _local.${_} (merge=${x}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const O=(window.G7Core?.state?.get()||{})._local||{},k=this.buildNestedUpdate(_,m);let L;x==="replace"?L=k:x==="shallow"?L={...O,...k}:L=this.deepMergeWithState(k,O),this.globalStateUpdater({_local:L}),j.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${x}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const A=this.buildNestedUpdate(_,m);this.globalStateUpdater(A),j.log(`[resultTo] Saved to _global.${_}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const A=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(A,x),j.log(`[resultTo] Saved to _isolated.${_} (merge=${x}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,_={};S?.state?.get&&(_._global=S.state.get()),n.state&&(_._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},v=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];v.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:v},y):v.length===1&&await this.executeAction(v[0],y)}return i&&r&&r.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 h=f instanceof jt?f:new jt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=h.originalError?.response||{},y=m.data||{},v=h.originalError?.status||m.status||500;let S=i_(h.originalError??f,e.handler,y.message,h.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const _={status:v,message:S,errors:y.errors||m.errors,data:y,statusText:h.originalError?.statusText,error_code:y.error_code??m.error_code};if(h.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),h;const A=Tr().resolve(v,{errorHandling:e.errorHandling,onError:e.onError});if(A.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const O=window.G7Core,k={};O?.state?.get&&(k._global=O.state.get()),n.state&&(k._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,k,"callback-state-capture",i)}const D={...n,data:{...n.data,error:_}};try{const O={type:"click",handler:A.handler.handler,target:A.handler.target,params:A.handler.params,actions:A.handler.actions};return await this.executeAction(O,D),{success:!1,error:h}}catch(O){return j.error("Error executing error handler:",O),{success:!1,error:h}}}throw i&&r&&r.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:h.name,message:h.message,stack:h.stack}}),h}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:h,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){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,h]of Object.entries(n.query))if(h!=null&&h!=="")if(Array.isArray(h)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of h)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(h));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},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new jt("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!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(r,e,n)}resolveNavigateFallback(e,n,r){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,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const v=y;return"container"in v||"to"in v||"block"in v||"offset"in v},d=(y,v,S=0)=>{y===window?window.scrollTo({top:v,left:S,behavior:l}):y.scrollTo({top:v,left:S,behavior:l})},f=(y,v,S,_)=>{if(v===window){y.scrollIntoView({behavior:l,block:S}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const x=v,A=y.getBoundingClientRect(),D=x.getBoundingClientRect(),O=x.scrollTop+(A.top-D.top);let k;S==="center"?k=O-(x.clientHeight-y.clientHeight)/2:S==="end"?k=O-(x.clientHeight-y.clientHeight):k=O,k-=_,x.scrollTo({top:Math.max(0,k),left:0,behavior:l})},h=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const _=window.getComputedStyle(S),x=_.overflowY,A=_.overflowX;(x==="auto"||x==="scroll"||A==="auto"||A==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,v=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let _=window;if(typeof y.container=="string"&&y.container.length>0){const A=document.querySelector(y.container);if(!A){j.warn(`applyScrollOption: container not found: ${y.container}`);return}_=A}const x=y.to??"top";if(x==="top"){_===window?h():d(_,0);return}if(typeof x=="number"){d(_,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:A=0,y:D=0}=x;d(_,D-S,A);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const A=document.querySelector(x);A?f(A,_,v,S):j.warn(`applyScrollOption: target element not found: ${x}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){h();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:v=0}=i;window.scrollTo({top:v,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 r=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&&(r=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=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 h of d)h!=null&&h!==""&&i.append(f,String(h))}else i.set(c,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")r.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;r.delete(c),r.delete(f);for(const h of d)h!=null&&h!==""&&r.append(f,String(h))}else r.set(c,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new jt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await At.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,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={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 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:r={status:"cancelled"};break}return At.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:c="GET",body:d,headers:f,contentType:h}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const W=qr().getToken();W&&(y={Authorization:`Bearer ${W}`})}let v=e;const S=n.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const z=this.buildQueryString(S);if(z){const W=e.includes("?")?"&":"?";v=`${e}${W}${z}`}}const _=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},A={_global:_,_local:x},D=this.getMatchingGlobalHeaders(e,A),O={};if(typeof window<"u"){const z=localStorage.getItem("g7_locale");z&&(O["Accept-Language"]=z)}const k=h==="multipart/form-data",L={method:c,headers:{...k?{}:{"Content-Type":"application/json"},Accept:"application/json",...O,...m&&{"X-XSRF-TOKEN":m},...y,...D,...f},credentials:"include"};if(d&&c!=="GET")if(k){const z=new FormData;for(const[W,de]of Object.entries(d))de instanceof File||de instanceof Blob?z.append(W,de):de!=null&&z.append(W,typeof de=="object"?JSON.stringify(de):String(de));L.body=z}else L.body=JSON.stringify(d);const B=Yn();let q=null;B?.isEnabled()&&(q=B.trackRequest(v,c));try{let z=await fetch(v,L),W;try{W=await z.json()}catch{W=null}if(At.isIdentityRequired(z.status,W)){const de=await At.handle(W,{body:L.body,headers:L.headers,credentials:L.credentials},l);if(de){z=de;try{W=await z.json()}catch{W=null}}}if(q&&B?.isEnabled()&&(B.completeRequest(q,z.status,W),q=null),!z.ok){const de=W||{},_e=new Error(de.message||`API call failed: ${z.statusText}`);throw _e.response=de,_e.status=z.status,_e.statusText=z.statusText,new jt(de.message||`API call failed: ${z.statusText}`,void 0,_e)}return W}catch(z){throw q&&B?.isEnabled()&&B.failRequest(q,z instanceof Error?z.message:String(z)),z}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new jt("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?.()||r.state?._global||{},f=window.G7Core?.state?.getLocal?.()||r.state?._local||{},h={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,h),y=Ar.getInstance();try{const v=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},v)}}catch(v){const S=v.message||"Login failed",_=new Error(S);throw _.response=v.response?.data||{},_.status=v.status||v.response?.status||500,new jt(S,void 0,_)}}async handleLogout(e,n){await Ar.getInstance().logout()}async handleSetState(e,n){j.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:c,...d}=e,f=Yn(),h=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:h?.state?.get()||{},y=r==="global"?"_global":r.startsWith("_local.")?r:"_local",v=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,v,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=_!=="deep"?{...d,__mergeMode:_,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const A=h?.state?.get()||{},{__setStateId:D,__mergeMode:O,...k}=x,L=_==="deep"?this.deepMergeWithState(k,A):k,B={...L,...S?{__setStateId:S}:{},..._!=="deep"?{__mergeMode:_}:{}};return j.log("setState global:",B),this.globalStateUpdater(B,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...L}}else if(r==="isolated"){const A=n.isolatedContext;if(A){const{__mergeMode:D,__setStateId:O,...k}=x;return A.mergeState(k,_),j.log("[handleSetState] isolated state updated:",k,"mergeMode:",_),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...k}}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 O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,O):x;return this.writeLocalState(n,k),S&&f&&setTimeout(()=>f.completeStateChange(S),0),k}else throw S&&f&&f.completeStateChange(S),new jt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const D=window.__g7LayoutContextStack||[];if(D.length>0){const O=i==="parent"?D[D.length-1]:D[0];if(O?.setState){const{__mergeMode:k,__setStateId:L,...B}=x,q=_==="deep"?this.deepMergeWithState(B,O.state||{}):B;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,q),O.setState(q),S&&f&&setTimeout(()=>f.completeStateChange(S),0),q}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const A=n.setState&&!n._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",A,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),A){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",x),j.log("[handleSetState] context.state:",n.state),j.log("[handleSetState] mergeMode:",_);const O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,{}):x;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",k),n.setState(k);const L=_==="deep"?this.deepMergeWithState(x,O):_==="shallow"?{...n.state||{},...x}:x,{__mergeMode:B,__setStateId:q,...z}=L;window.__g7PendingLocalState=z,j.log("[handleSetState] __g7PendingLocalState updated:",z);const W=(window.__g7LayoutContextStack||[]).length;let de;if(this.globalStateUpdater){const ze=W===0?window.__templateApp?.getGlobalState?.()?._local:void 0;if(_!=="replace"&&!!ze&&typeof ze=="object"&&!Array.isArray(ze)){const ue=_==="deep"?this.deepMergeWithState(x,ze):{...ze,...x},{__mergeMode:De,__setStateId:ee,...me}=ue;de=me}else _!=="replace"&&j.log("[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백",{modalDepth:W,hasTemplateApp:!!window.__templateApp});const Q=de?Mo(de,z):z;this.globalStateUpdater({_local:Q},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",Q)}const{__mergeMode:_e,__setStateId:Se,...Ie}=x;if(_==="replace")window.__g7ForcedLocalFields=Ie;else{const ze=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ie,ze)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ie),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...de?Mo(de,z):L,..._!=="deep"?{__mergeMode:_}:{}}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const O=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",O);const k=_==="deep"?this.deepMergeWithState(x,O):x;return j.log("[handleSetState] finalLocal (merged):",k),this.globalStateUpdater({_local:k},{render:c}),window.__g7PendingLocalState=k,j.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...k}}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const A=r.slice(7),{__mergeMode:D,__setStateId:O,...k}=x,L=k.value!==void 0?k.value:Object.values(k)[0];if(n.setState){const q=window.__g7PendingLocalState||n.state||{},z=this.createNestedUpdate(A,L,q),W={...q,...z};if(n.setState(z),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const de=window.__templateApp?.getGlobalState?.()?._local,_e=de&&typeof de=="object"?{...de,...z}:W;this.globalStateUpdater({_local:_e},{render:!1}),j.log("[handleSetState] _global._local synced for dot notation (render:false):",_e)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),W}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context");const D=window.__g7PendingLocalState||n.state||{},O=_==="deep"?this.deepMergeWithState(x,D):x;return this.writeLocalState(n,O,void 0,{scope:i}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}}async handleParentScopeSetState(e,n,r,i){const l=Yn(),c=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),h=f?"$parent.":"$root.",m=e.slice(h.length);let y,v;if(m==="_local"||m==="_global")y=m,v=void 0;else if(m.startsWith("_local."))y="_local",v=m.slice(7);else if(m.startsWith("_global."))y="_global",v=m.slice(8);else{j.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){j.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?S[S.length-1]:S[0];if(!_){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=y==="_global"?_.state?._global:_.state?._local,A=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:D,__setStateId:O,...k}=n;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),A&&l&&l.completeStateChange(A);return}const L=c?.state?.get()||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,z),this.globalStateUpdater(z)}else{const B=d==="deep"?this.deepMergeWithState(k,L):k;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,B),this.globalStateUpdater(d!=="deep"?{...B,__mergeMode:d}:B)}return A&&l&&setTimeout(()=>l.completeStateChange(A),0),{__target:e,...k}}else{if(!_.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),A&&l&&l.completeStateChange(A);return}const L=_.state||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,q),_.setState(q),_.state=z,_.dataContext&&(_.dataContext._local=z),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),z}else{const B=d!=="deep"?{...k,__mergeMode:d}:k,q=d==="replace"?k:d==="shallow"?{...L,...k}:this.deepMergeWithState(k,L);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,q),_.setState(B),_.state=q,_.dataContext&&(_.dataContext._local=q),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),q}}}deepMergeWithState(e,n){const r=["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(r.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,r){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]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:v,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=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const h=Yn();if(h?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;h.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||[],r=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(r){const d=Yn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:c}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&At.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 h={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],h];this.globalStateUpdater({toasts:S})}else j.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){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(r.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=r[c];if(!d&&r.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=r.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:r}=e;if(!r||!Array.isArray(r)){j.warn("conditions handler requires conditions array");return}const i=n.data||{},l=fm(r,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=r[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 r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(r);c&&(clearInterval(c),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(h=>{j.error(`[startInterval:${r}] tick action failed`,h)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return j.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),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 r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Yn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},h=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,v=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(h).length>0?{...h}:void 0});for(let S=0;S0){const k={},L={...n.data,_local:f,_computed:k,$computed:k,_isolated:h};for(const[B,q]of Object.entries(O))if(typeof q=="string"){const z=q.trim();if(z.startsWith("{{")&&z.endsWith("}}"))try{const W=z.slice(2,-2).trim();k[B]=Wn(W)?this.bindingEngine.evaluatePipeExpression(W,L,{skipCache:!0}):this.bindingEngine.evaluateExpression(W,L,{skipCache:!0})}catch{k[B]=m[B]}}m=k,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const O=window.__g7SequenceLocalSync;if(O&&O!==f){f=O,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const k=n.data?._computedDefinitions;if(k&&Object.keys(k).length>0){const L={},B={...n.data,_local:f,_computed:L,$computed:L,_isolated:h};for(const[q,z]of Object.entries(k))if(typeof z=="string"){const W=z.trim();if(W.startsWith("{{")&&W.endsWith("}}"))try{const de=W.slice(2,-2).trim();L[q]=Wn(de)?this.bindingEngine.evaluatePipeExpression(de,B,{skipCache:!0}):this.bindingEngine.evaluateExpression(de,B,{skipCache:!0})}catch{L[q]=m[q]}}m=L,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,D.data)}catch(D){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,void 0,D),i.endSequenceExecution?.(l,D)),j.error(`sequence handler: action[${S}] failed:`,D),D}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,h)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${h}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${r.length} actions failed`),c}assertAllowedExtensionAssetUrl(e,n,r){if(!Io(e,ys()))throw j.error(`Blocked untrusted ${n} asset url: ${e}`),new jt(`Blocked untrusted ${n} url (same-origin path or declared trusted host required): ${e}`,r)}async handleLoadScript(e,n,r){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new jt('loadScript handler requires "src" parameter',n);if(!Io(i,ys()))throw j.warn(`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${i}`),new jt(`Blocked untrusted script src (same-origin path or declared trusted host required): ${i}`,n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;if(cn.loadedScripts.has(f))return j.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0;const h=cn.loadingScripts.get(f);if(h)return j.log(`loadScript: joining in-flight load: ${f}`),await h,n.onLoad&&await this.executeAction(n.onLoad,r),!0;if(document.getElementById(f))return j.log(`loadScript: script element already exists: ${f}`),cn.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0;j.log(`loadScript: loading script: ${i}`);const y=document.createElement("script");if(y.id=f,y.src=i,y.async=c,y.defer=d,y.hasAttribute("data-gdpr-blocked-src"))return j.warn(`loadScript: script blocked by consent manager (not loaded): ${i}`),!1;const v=new Promise((S,_)=>{y.onload=()=>{j.log(`loadScript: script loaded successfully: ${f}`),cn.loadedScripts.add(f),cn.loadingScripts.delete(f),S()},y.onerror=x=>{j.error(`loadScript: failed to load script: ${i}`,x),cn.loadingScripts.delete(f),_(new jt(`Failed to load script: ${i}`,n))},document.head.appendChild(y)});if(v.catch(()=>{}),cn.loadingScripts.set(f,v),await v,n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){j.error("loadScript: onLoad action failed:",S)}return!0}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,h=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new jt('callExternal handler requires "constructor" parameter',n);const v=this.getNestedProperty(window,i);if(!v||typeof v!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);this.assertCallableExternalConstructor(v,i,n),j.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternal: callback triggered for ${x}`,D),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,D),m&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(m);j.log("callExternal: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternal: merged with existing state",L),this.writeLocalState(r,L)}else f&&r.setState&&this.writeLocalState(r,{[`${f.replace(/:/g,"_")}_result`]:D});if(y){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(y)?y:[y];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternal: callbackAction failed:",B)}}});const _=new v(S);if(c&&typeof _[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&h){const x=document.querySelector(h);if(x)return _[c](x,...d);throw new jt(`Embed target element not found: ${h}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,h=e.callbackAction;if(!i)throw new jt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);this.assertCallableExternalConstructor(m,i,n),j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:v}=this.createEmbedLayer(f),S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternalEmbed: callback triggered for ${x}`,D),v(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,D),c&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(c);j.log("callExternalEmbed: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternalEmbed: merged with existing state",L),this.writeLocalState(r,L)}if(h){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(h)?h:[h];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternalEmbed: callbackAction failed:",B)}}});const _=new m(S);if(typeof _.embed=="function")_.embed(y),j.log("callExternalEmbed: embedded in layer");else throw v(),new jt(`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=` +`+c)}}catch{}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=xi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&vc.assertOptions(r,{silentJSONParsing:Tn.transitional(Tn.boolean),forcedJSONParsing:Tn.transitional(Tn.boolean),clarifyTimeoutError:Tn.transitional(Tn.boolean),legacyInterceptorReqResOrdering:Tn.transitional(Tn.boolean),advertiseZstdAcceptEncoding:Tn.transitional(Tn.boolean),validateStatusUndefinedResolves:Tn.transitional(Tn.boolean)},!1),i!=null&&(G.isFunction(i)?n.paramsSerializer={serialize:i}:vc.assertOptions(i,{encode:Tn.function,serialize:Tn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),vc.assertOptions(n,{baseUrl:Tn.spelling("baseURL"),withXsrfToken:Tn.spelling("withXSRFToken")},!0),n.method=(G.getSafeProp(n,"method")||G.getSafeProp(this.defaults,"method")||"get").toLowerCase();let c=l&&G.merge(l.common,l[n.method]);l&&G.forEach(Fm.concat("common"),_=>{delete l[_]}),n.headers=xn.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){if(typeof x.runWhen=="function"&&x.runWhen(n)===!1)return;f=f&&x.synchronous;const A=n.transitional||bf;A&&A.legacyInterceptorReqResOrdering?d.unshift(x.fulfilled,x.rejected):d.push(x.fulfilled,x.rejected)});const h=[];this.interceptors.response.forEach(function(x){h.push(x.fulfilled,x.rejected)});let m,y=0,v;if(!f){const _=[xf.bind(this),void 0];for(_.unshift(...d),_.push(...h),v=_.length,m=Promise.resolve(n);yxf.call(this,S)))}catch(D){m=Promise.reject(D)}break}}if(!m)try{m=xf.call(this,S)}catch(_){m=Promise.reject(_)}for(y=0,v=h.length;y{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{r.subscribe(d),l=d}).then(i);return c.cancel=function(){r.unsubscribe(l)},c},e(function(l,c,d){r.reason||(r.reason=new Lo(l,c,d),n(r.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=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new r0(function(i){e=i}),cancel:e}}};function XE(s){return function(n){return s.apply(null,n)}}function JE(s){return G.isObject(s)&&s.isAxiosError===!0}const Sc={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Sc).forEach(([s,e])=>{Sc[e]===void 0&&(Sc[e]=s)});function fy(s){const e=new Ti(s),n=bm(Ti.prototype.request,e);return G.extend(n,Ti.prototype,e,{allOwnKeys:!0}),G.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return fy(xi(s,i))},n}const Qt=fy(Oo);Qt.Axios=Ti,Qt.CanceledError=Lo,Qt.CancelToken=YE,Qt.isCancel=Vm,Qt.VERSION=Ef,Qt.toFormData=gc,Qt.AxiosError=we,Qt.Cancel=Qt.CanceledError,Qt.all=function(e){return Promise.all(e)},Qt.spread=XE,Qt.isAxiosError=JE,Qt.mergeConfig=xi,Qt.AxiosHeaders=xn,Qt.formToJSON=s=>Gm(G.isHTMLForm(s)?new FormData(s):s),Qt.getAdapter=uy.getAdapter,Qt.HttpStatusCode=Sc,Qt.default=Qt;const{Axios:DR,AxiosError:OR,CanceledError:LR,isCancel:$R,CancelToken:MR,VERSION:NR,all:IR,Cancel:jR,isAxiosError:HR,spread:zR,toFormData:PR,AxiosHeaders:UR,HttpStatusCode:BR,formToJSON:qR,getAdapter:GR,mergeConfig:FR,create:VR}=Qt,Tf="g7.identity.redirectStash",wc=pt("IdentityGuardInterceptor");class At{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){wc.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,r){this.domainNoticeShown=!1;const i=this.launcher??ZE,c=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const h=QE(f.url,d.token);return fetch(h,{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 wc.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 r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch(i){wc.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}}M(At,"launcher",null),M(At,"deferredResolver",null),M(At,"domainNoticeShown",!1);function QE(s,e){if(!e)return s;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(s,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(s)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=s.includes("?")?"&":"?";return`${s}${n}verification_token=${encodeURIComponent(e)}`}}const ZE=async s=>{if(typeof window>"u")return{status:"cancelled"};if(s.render_hint==="external_redirect"||s.redirect_url)return At.redirectExternally(s);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,r={return_url:n,payload:s,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){wc.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},e_=pt("ApiClient");function kf(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class t_{constructor(e={}){M(this,"client");M(this,"config");M(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=Qt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];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)r.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.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&&!this.isCrossOriginRequest(e.url)&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=kf();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=r.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,r=n._devToolsRequestId;if(r){const i=kf();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(c=>r.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await Ar.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(At.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[v,S]of Object.entries(d))typeof S=="string"&&(c[v]=S);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 h=n?.identity_target,m=await At.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},h);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,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).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 r=kf();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}isCrossOriginRequest(e){if(!e||typeof window>"u"||!window.location||!/^(https?:)?\/\//i.test(e))return!1;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}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 r=e.params,i=[];for(const[l,c]of Object.entries(r))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(r){e_.error("Error in onError handler:",r)}}}let Rf=null;function qr(){return Rf||(Rf=new t_),Rf}const $o=pt("AuthManager");function ys(s,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(s,e,n,r)}catch{}}const Cc={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"}},Or=class Or{constructor(){M(this,"state");M(this,"config");M(this,"isRefreshing",!1);M(this,"refreshPromise",null);M(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",Cc.admin),this.config.set("user",Cc.user)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=qr();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return $o.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 $o.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=qr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?Cc.admin.loginEndpoint:Cc.user.loginEndpoint;try{const d=r?.headers?{headers:r.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const h=f.data.user.language,m=localStorage.getItem(Or.LOCALE_STORAGE_KEY),y=h&&h!==m;if(h)try{localStorage.setItem(Or.LOCALE_STORAGE_KEY,h)}catch(v){$o.warn("Failed to save user language to localStorage:",v)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ys("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(h),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,h=new Error(f||d.message||"Login failed");throw h.response=d.response,h.status=d.response?.status,ys("login",!1,h.message,{type:e,status:d.response?.status}),h}}async logout(){const e=qr(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){$o.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ys("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.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 r=qr();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ys("token-refresh",!0,void 0,{type:e}),!0):(ys("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return $o.error("Token refresh failed:",i),ys("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return r&&(c+=`&reason=${encodeURIComponent(r)}`),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 r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=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 r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Or.instance=null}};M(Or,"instance"),M(Or,"LOCALE_STORAGE_KEY","g7_locale");let Ar=Or;const hy={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}}"}}},sa={findHandler(s,e){if(s){if(s[e])return s[e];if(s[String(e)])return s[String(e)];if(s.default)return s.default}},normalizeOnError(s){return s?Array.isArray(s)?s:[s]:[]},injectErrorCode(s,e,n){if(s.handler!=="showErrorPage"||s.params?.errorCode!==void 0)return s;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?s:{...s,params:{...s.params,errorCode:i}}}},xr=pt("ErrorHandlingResolver"),Ua=class Ua{constructor(){M(this,"templateErrorHandling",null);M(this,"layoutErrorHandling",null);M(this,"executeAction",null)}static getInstance(){return Ua.instance||(Ua.instance=new Ua),Ua.instance}static resetInstance(){Ua.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,xr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,xr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;xr.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=sa.findHandler(r,e);if(l){const c=this.getMatchedKey(r,e);return{handler:sa.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=sa.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=sa.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=sa.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=sa.findHandler(hy,e),l){const c=this.getMatchedKey(hy,e);return{handler:sa.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){xr.error("Action executor is not set");return}xr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw xr.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(xr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return xr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return xr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,xr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,xr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};M(Ua,"instance",null);let Df=Ua;function Tr(){return Df.getInstance()}function Mo(s,e){const n={...s};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=Mo(n[r],e[r])):n[r]=e[r];return n}var Of={exports:{}},No={};var py;function n_(){if(py)return No;py=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,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:s,type:r,key:c,ref:i!==void 0?i:null,props:l}}return No.Fragment=e,No.jsx=n,No.jsxs=n,No}var gy;function r_(){return gy||(gy=1,Of.exports=n_()),Of.exports}var yt=r_();const a_=na({__proto__:null,default:ra(yt)},[yt]),Lf=pt("ParentContextProvider"),my=I.createContext(null);let Ec=null;function $f(){Ec?(Lf.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ec()):Lf.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const yy=({children:s})=>{const[e,n]=I.useState(0),r=I.useRef(!0),i=I.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);I.useEffect(()=>(r.current=!0,Ec=()=>{r.current&&(n(c=>c+1),Lf.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Ec=null}),[]);const l={version:e,getParentDataContext:i};return yt.jsx(my.Provider,{value:l,children:s})};function i_(){return I.useContext(my)}function by(s){return s.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function vy(s,e){try{const n=typeof window<"u"&&window.location?.protocol||"https:",r=e||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",i=s.startsWith("//")?`${n}${s}`:s,l=new URL(i,r);return l.protocol!=="http:"&&l.protocol!=="https:"?null:l.hostname.toLowerCase()}catch{return null}}function bs(){const s=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(s)?s.map(e=>String(e).toLowerCase()):[]}function Io(s,e){if(typeof s!="string")return!1;const n=s.trim();if(n==="")return!1;const r=by(n),i=r.startsWith("//"),l=/^[a-z][a-z0-9+.-]*:/i.test(r);if(!i&&!l&&r.startsWith("/"))return!0;const c=vy(r),d=e??bs();return c!==null&&d.map(f=>String(f).toLowerCase()).includes(c)}const j=pt("ActionDispatcher");function s_(s,e,n,r){return n||(Wg(s)||Ud(s)?"$t:core.errors.network_request_failed":r||`Failed to execute action: ${e}`)}const Sy=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),o_=new Set(["redirect"]);function Yn(){try{return window.G7Core?.devTools}catch{return}}class jt extends Error{constructor(n,r,i){super(n);M(this,"action");M(this,"originalError");M(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const wy={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"},cn=class cn{constructor(e={},n,r){M(this,"bindingEngine");M(this,"translationEngine");M(this,"translationContext");M(this,"customHandlers",new Map);M(this,"defaultContext");M(this,"globalStateUpdater");M(this,"errorHandlingSetup",!1);M(this,"debounceTimers",new Map);M(this,"pendingDebounceFlushers",new Map);M(this,"debounceAccumulatedValues",new Map);M(this,"globalHeaders",[]);M(this,"namedActions",{});M(this,"previewMode",!1);M(this,"localMirrorDepth",0);M(this,"intervals",new Map);this.bindingEngine=new $n,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Yn();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 Sy}static getPreviewSuppressedLayoutFeatures(){return o_}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 r=Yn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,h={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(h.key=c),d!==void 0&&(h.event=d),h}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=hs(c,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;Tr().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{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={...r.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},h=r.data?._local||r.state||{},m={...f,...h},y=r.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,r)=>{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,r)=>{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,r)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:h=2e3,delay:m=0,retryCount:y=0,retryInterval:v=50,scrollContainer:S}=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(x=>{const A=document.querySelector(i);if(A){x(A);return}const D=setTimeout(()=>{O.disconnect(),x(null)},h),O=new MutationObserver(()=>{const k=document.querySelector(i);k&&(clearTimeout(D),O.disconnect(),x(k))});O.observe(document.body,{childList:!0,subtree:!0})}),!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${h}ms timeout`);return}}else{m>0&&await new Promise(A=>setTimeout(A,m)),_=document.querySelector(i);let x=0;for(;!_&&xsetTimeout(A,v)),_=document.querySelector(i),x++;if(!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){j.warn(`scrollIntoView: container not found for selector "${S}"`);return}const A=_.getBoundingClientRect(),D=x.getBoundingClientRect(),O=A.top-D.top+x.scrollTop,k=O+A.height;let L;switch(c){case"start":L=O;break;case"center":L=O-x.clientHeight/2+A.height/2;break;case"end":L=k-x.clientHeight;break;default:const B=A.topD.bottom;if(B)L=O;else if(q)L=k-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,L),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{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},r)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{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,r)=>{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,r)=>{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,r)=>{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,r)=>{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){if(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`module-${f}`;this.assertAllowedExtensionAssetUrl(h,`module script (${f})`,n),document.getElementById(m)?j.warn(`reloadModuleHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`module-script:${f}`}),j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`module-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`module stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`module-css:${f}`}),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 h=`module-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,h),h}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{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){if(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`plugin-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin script (${f})`,n),document.getElementById(m)?j.warn(`reloadPluginHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`plugin-script:${f}`}),j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`plugin-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`plugin-css:${f}`}),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 h=`plugin-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,h),h}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{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 h=(m,y=6e4)=>new Promise((v,S)=>{const _=document.getElementById(m);if(_){v(_);return}j.log(`showErrorPage: Waiting for container #${m}...`);let x;const A=new MutationObserver((D,O)=>{const k=document.getElementById(m);k&&(j.log(`showErrorPage: Container #${m} found`),O.disconnect(),clearTimeout(x),v(k))});A.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{A.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await h(f);const m=Tr(),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,r)=>{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:r.data,state:r.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 h=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...h,_eventResult:m}});const y=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:h;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,r)=>{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(v=>v.id===i?{...v,[l]:c,_modified:!0}:v),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,r)=>{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 h=f.state.get()||{},y=(h.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const _=S.options.map(x=>x.id===l?{...x,[c]:d,_modified:!0}:x);return{...S,options:_,_modified:!0}}return S}),v=new Set(h._local?.modifiedProductIds||[]);v.add(i),this.globalStateUpdater({products:{...h.products,data:{...h.products?.data,data:y}},_local:{...h._local,modifiedProductIds:Array.from(v)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(h){throw j.error("updateOptionField: Error updating option field",h),h}}),this.registerHandler("setLocale",async(n,r)=>{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=Yn();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 r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=r?.state?{...r.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?.()??r?.state??{},y=Date.now()-l;for(const v of Object.keys(c)){const S=c[v],_=m[v];S!==_&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${v}`,capturedValue:S,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${v} changed after handler creation:`,`captured="${S}" → current="${_}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let h={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const v=f.target;new FormData(v).forEach((_,x)=>{h[x]=_})}const m={...this.defaultContext,data:{...n,form:h,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let v=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext,m.data)),!confirm(v))return}const y=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(h){if(j.error("Action execution failed:",h),e.onError){const m=h instanceof jt&&h.originalError?h.originalError:h,y={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},v=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of v)await this.executeAction(S,y)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${r}_${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 r=Yn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&r&&r.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),h=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,h),!h)return i&&r&&r.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&&r&&r.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 h=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,h);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&Sy.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,h||f),i&&r&&r.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||h;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||h;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||h||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const _=window.G7Core,x={};if(_?.state?.get){const A=_.state.get();x._global=A}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const v=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(h,f,n,v,S);break;case"login":m=await this.handleLogin(h,f,n);break;case"logout":m=await this.handleLogout(h,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(h,f,n);break;case"openModal":m=await this.handleOpenModal(h,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(h,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:h,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:v,merge:S}=e.resultTo,_=this.resolveValue(v,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const A=this.buildNestedUpdate(_,m),D=x!=="deep"?{...A,__mergeMode:x}:A;this.writeLocalState(n,D),j.log(`[resultTo] Saved to _local.${_} (merge=${x}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const O=(window.G7Core?.state?.get()||{})._local||{},k=this.buildNestedUpdate(_,m);let L;x==="replace"?L=k:x==="shallow"?L={...O,...k}:L=this.deepMergeWithState(k,O),this.globalStateUpdater({_local:L}),j.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${x}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const A=this.buildNestedUpdate(_,m);this.globalStateUpdater(A),j.log(`[resultTo] Saved to _global.${_}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const A=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(A,x),j.log(`[resultTo] Saved to _isolated.${_} (merge=${x}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,_={};S?.state?.get&&(_._global=S.state.get()),n.state&&(_._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},v=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];v.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:v},y):v.length===1&&await this.executeAction(v[0],y)}return i&&r&&r.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 h=f instanceof jt?f:new jt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=h.originalError?.response||{},y=m.data||{},v=h.originalError?.status||m.status||500;let S=s_(h.originalError??f,e.handler,y.message,h.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const _={status:v,message:S,errors:y.errors||m.errors,data:y,statusText:h.originalError?.statusText,error_code:y.error_code??m.error_code};if(h.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),h;const A=Tr().resolve(v,{errorHandling:e.errorHandling,onError:e.onError});if(A.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const O=window.G7Core,k={};O?.state?.get&&(k._global=O.state.get()),n.state&&(k._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,k,"callback-state-capture",i)}const D={...n,data:{...n.data,error:_}};try{const O={type:"click",handler:A.handler.handler,target:A.handler.target,params:A.handler.params,actions:A.handler.actions};return await this.executeAction(O,D),{success:!1,error:h}}catch(O){return j.error("Error executing error handler:",O),{success:!1,error:h}}}throw i&&r&&r.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:h.name,message:h.message,stack:h.stack}}),h}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:h,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){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,h]of Object.entries(n.query))if(h!=null&&h!=="")if(Array.isArray(h)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of h)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(h));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},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new jt("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!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(r,e,n)}resolveNavigateFallback(e,n,r){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,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const v=y;return"container"in v||"to"in v||"block"in v||"offset"in v},d=(y,v,S=0)=>{y===window?window.scrollTo({top:v,left:S,behavior:l}):y.scrollTo({top:v,left:S,behavior:l})},f=(y,v,S,_)=>{if(v===window){y.scrollIntoView({behavior:l,block:S}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const x=v,A=y.getBoundingClientRect(),D=x.getBoundingClientRect(),O=x.scrollTop+(A.top-D.top);let k;S==="center"?k=O-(x.clientHeight-y.clientHeight)/2:S==="end"?k=O-(x.clientHeight-y.clientHeight):k=O,k-=_,x.scrollTo({top:Math.max(0,k),left:0,behavior:l})},h=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const _=window.getComputedStyle(S),x=_.overflowY,A=_.overflowX;(x==="auto"||x==="scroll"||A==="auto"||A==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,v=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let _=window;if(typeof y.container=="string"&&y.container.length>0){const A=document.querySelector(y.container);if(!A){j.warn(`applyScrollOption: container not found: ${y.container}`);return}_=A}const x=y.to??"top";if(x==="top"){_===window?h():d(_,0);return}if(typeof x=="number"){d(_,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:A=0,y:D=0}=x;d(_,D-S,A);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const A=document.querySelector(x);A?f(A,_,v,S):j.warn(`applyScrollOption: target element not found: ${x}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){h();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:v=0}=i;window.scrollTo({top:v,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 r=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&&(r=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=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 h of d)h!=null&&h!==""&&i.append(f,String(h))}else i.set(c,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")r.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;r.delete(c),r.delete(f);for(const h of d)h!=null&&h!==""&&r.append(f,String(h))}else r.set(c,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new jt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await At.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,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={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 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:r={status:"cancelled"};break}return At.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:c="GET",body:d,headers:f,contentType:h}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const W=qr().getToken();W&&(y={Authorization:`Bearer ${W}`})}let v=e;const S=n.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const z=this.buildQueryString(S);if(z){const W=e.includes("?")?"&":"?";v=`${e}${W}${z}`}}const _=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},A={_global:_,_local:x},D=this.getMatchingGlobalHeaders(e,A),O={};if(typeof window<"u"){const z=localStorage.getItem("g7_locale");z&&(O["Accept-Language"]=z)}const k=h==="multipart/form-data",L={method:c,headers:{...k?{}:{"Content-Type":"application/json"},Accept:"application/json",...O,...m&&{"X-XSRF-TOKEN":m},...y,...D,...f},credentials:"include"};if(d&&c!=="GET")if(k){const z=new FormData;for(const[W,de]of Object.entries(d))de instanceof File||de instanceof Blob?z.append(W,de):de!=null&&z.append(W,typeof de=="object"?JSON.stringify(de):String(de));L.body=z}else L.body=JSON.stringify(d);const B=Yn();let q=null;B?.isEnabled()&&(q=B.trackRequest(v,c));try{let z=await fetch(v,L),W;try{W=await z.json()}catch{W=null}if(At.isIdentityRequired(z.status,W)){const de=await At.handle(W,{body:L.body,headers:L.headers,credentials:L.credentials},l);if(de){z=de;try{W=await z.json()}catch{W=null}}}if(q&&B?.isEnabled()&&(B.completeRequest(q,z.status,W),q=null),!z.ok){const de=W||{},_e=new Error(de.message||`API call failed: ${z.statusText}`);throw _e.response=de,_e.status=z.status,_e.statusText=z.statusText,new jt(de.message||`API call failed: ${z.statusText}`,void 0,_e)}return W}catch(z){throw q&&B?.isEnabled()&&B.failRequest(q,z instanceof Error?z.message:String(z)),z}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new jt("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?.()||r.state?._global||{},f=window.G7Core?.state?.getLocal?.()||r.state?._local||{},h={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,h),y=Ar.getInstance();try{const v=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},v)}}catch(v){const S=v.message||"Login failed",_=new Error(S);throw _.response=v.response?.data||{},_.status=v.status||v.response?.status||500,new jt(S,void 0,_)}}async handleLogout(e,n){await Ar.getInstance().logout()}async handleSetState(e,n){j.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:c,...d}=e,f=Yn(),h=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:h?.state?.get()||{},y=r==="global"?"_global":r.startsWith("_local.")?r:"_local",v=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,v,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=_!=="deep"?{...d,__mergeMode:_,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const A=h?.state?.get()||{},{__setStateId:D,__mergeMode:O,...k}=x,L=_==="deep"?this.deepMergeWithState(k,A):k,B={...L,...S?{__setStateId:S}:{},..._!=="deep"?{__mergeMode:_}:{}};return j.log("setState global:",B),this.globalStateUpdater(B,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...L}}else if(r==="isolated"){const A=n.isolatedContext;if(A){const{__mergeMode:D,__setStateId:O,...k}=x;return A.mergeState(k,_),j.log("[handleSetState] isolated state updated:",k,"mergeMode:",_),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...k}}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 O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,O):x;return this.writeLocalState(n,k),S&&f&&setTimeout(()=>f.completeStateChange(S),0),k}else throw S&&f&&f.completeStateChange(S),new jt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const D=window.__g7LayoutContextStack||[];if(D.length>0){const O=i==="parent"?D[D.length-1]:D[0];if(O?.setState){const{__mergeMode:k,__setStateId:L,...B}=x,q=_==="deep"?this.deepMergeWithState(B,O.state||{}):B;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,q),O.setState(q),S&&f&&setTimeout(()=>f.completeStateChange(S),0),q}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const A=n.setState&&!n._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",A,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),A){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",x),j.log("[handleSetState] context.state:",n.state),j.log("[handleSetState] mergeMode:",_);const O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,{}):x;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",k),n.setState(k);const L=_==="deep"?this.deepMergeWithState(x,O):_==="shallow"?{...n.state||{},...x}:x,{__mergeMode:B,__setStateId:q,...z}=L;window.__g7PendingLocalState=z,j.log("[handleSetState] __g7PendingLocalState updated:",z);const W=(window.__g7LayoutContextStack||[]).length;let de;if(this.globalStateUpdater){const ze=W===0?window.__templateApp?.getGlobalState?.()?._local:void 0;if(_!=="replace"&&!!ze&&typeof ze=="object"&&!Array.isArray(ze)){const ue=_==="deep"?this.deepMergeWithState(x,ze):{...ze,...x},{__mergeMode:De,__setStateId:ee,...me}=ue;de=me}else _!=="replace"&&j.log("[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백",{modalDepth:W,hasTemplateApp:!!window.__templateApp});const Q=de?Mo(de,z):z;this.globalStateUpdater({_local:Q},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",Q)}const{__mergeMode:_e,__setStateId:Se,...Ie}=x;if(_==="replace")window.__g7ForcedLocalFields=Ie;else{const ze=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ie,ze)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ie),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...de?Mo(de,z):L,..._!=="deep"?{__mergeMode:_}:{}}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const O=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",O);const k=_==="deep"?this.deepMergeWithState(x,O):x;return j.log("[handleSetState] finalLocal (merged):",k),this.globalStateUpdater({_local:k},{render:c}),window.__g7PendingLocalState=k,j.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...k}}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const A=r.slice(7),{__mergeMode:D,__setStateId:O,...k}=x,L=k.value!==void 0?k.value:Object.values(k)[0];if(n.setState){const q=window.__g7PendingLocalState||n.state||{},z=this.createNestedUpdate(A,L,q),W={...q,...z};if(n.setState(z),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const de=window.__templateApp?.getGlobalState?.()?._local,_e=de&&typeof de=="object"?{...de,...z}:W;this.globalStateUpdater({_local:_e},{render:!1}),j.log("[handleSetState] _global._local synced for dot notation (render:false):",_e)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),W}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context");const D=window.__g7PendingLocalState||n.state||{},O=_==="deep"?this.deepMergeWithState(x,D):x;return this.writeLocalState(n,O,void 0,{scope:i}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}}async handleParentScopeSetState(e,n,r,i){const l=Yn(),c=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),h=f?"$parent.":"$root.",m=e.slice(h.length);let y,v;if(m==="_local"||m==="_global")y=m,v=void 0;else if(m.startsWith("_local."))y="_local",v=m.slice(7);else if(m.startsWith("_global."))y="_global",v=m.slice(8);else{j.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){j.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?S[S.length-1]:S[0];if(!_){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=y==="_global"?_.state?._global:_.state?._local,A=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:D,__setStateId:O,...k}=n;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),A&&l&&l.completeStateChange(A);return}const L=c?.state?.get()||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,z),this.globalStateUpdater(z)}else{const B=d==="deep"?this.deepMergeWithState(k,L):k;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,B),this.globalStateUpdater(d!=="deep"?{...B,__mergeMode:d}:B)}return A&&l&&setTimeout(()=>l.completeStateChange(A),0),{__target:e,...k}}else{if(!_.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),A&&l&&l.completeStateChange(A);return}const L=_.state||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,q),_.setState(q),_.state=z,_.dataContext&&(_.dataContext._local=z),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),z}else{const B=d!=="deep"?{...k,__mergeMode:d}:k,q=d==="replace"?k:d==="shallow"?{...L,...k}:this.deepMergeWithState(k,L);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,q),_.setState(B),_.state=q,_.dataContext&&(_.dataContext._local=q),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),q}}}deepMergeWithState(e,n){const r=["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(r.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,r){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]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:v,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=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const h=Yn();if(h?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;h.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||[],r=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(r){const d=Yn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:c}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&At.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 h={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],h];this.globalStateUpdater({toasts:S})}else j.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){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(r.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=r[c];if(!d&&r.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=r.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:r}=e;if(!r||!Array.isArray(r)){j.warn("conditions handler requires conditions array");return}const i=n.data||{},l=fm(r,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=r[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 r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(r);c&&(clearInterval(c),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(h=>{j.error(`[startInterval:${r}] tick action failed`,h)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return j.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),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 r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Yn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},h=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,v=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(h).length>0?{...h}:void 0});for(let S=0;S0){const k={},L={...n.data,_local:f,_computed:k,$computed:k,_isolated:h};for(const[B,q]of Object.entries(O))if(typeof q=="string"){const z=q.trim();if(z.startsWith("{{")&&z.endsWith("}}"))try{const W=z.slice(2,-2).trim();k[B]=Wn(W)?this.bindingEngine.evaluatePipeExpression(W,L,{skipCache:!0}):this.bindingEngine.evaluateExpression(W,L,{skipCache:!0})}catch{k[B]=m[B]}}m=k,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const O=window.__g7SequenceLocalSync;if(O&&O!==f){f=O,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const k=n.data?._computedDefinitions;if(k&&Object.keys(k).length>0){const L={},B={...n.data,_local:f,_computed:L,$computed:L,_isolated:h};for(const[q,z]of Object.entries(k))if(typeof z=="string"){const W=z.trim();if(W.startsWith("{{")&&W.endsWith("}}"))try{const de=W.slice(2,-2).trim();L[q]=Wn(de)?this.bindingEngine.evaluatePipeExpression(de,B,{skipCache:!0}):this.bindingEngine.evaluateExpression(de,B,{skipCache:!0})}catch{L[q]=m[q]}}m=L,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,D.data)}catch(D){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,void 0,D),i.endSequenceExecution?.(l,D)),j.error(`sequence handler: action[${S}] failed:`,D),D}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,h)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${h}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${r.length} actions failed`),c}assertAllowedExtensionAssetUrl(e,n,r){if(!Io(e,bs()))throw j.error(`Blocked untrusted ${n} asset url: ${e}`),new jt(`Blocked untrusted ${n} url (same-origin path or declared trusted host required): ${e}`,r)}async handleLoadScript(e,n,r){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new jt('loadScript handler requires "src" parameter',n);if(!Io(i,bs()))throw j.warn(`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${i}`),new jt(`Blocked untrusted script src (same-origin path or declared trusted host required): ${i}`,n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;if(cn.loadedScripts.has(f))return j.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0;const h=cn.loadingScripts.get(f);if(h)return j.log(`loadScript: joining in-flight load: ${f}`),await h,n.onLoad&&await this.executeAction(n.onLoad,r),!0;if(document.getElementById(f))return j.log(`loadScript: script element already exists: ${f}`),cn.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0;j.log(`loadScript: loading script: ${i}`);const y=document.createElement("script");if(y.id=f,y.src=i,y.async=c,y.defer=d,y.hasAttribute("data-gdpr-blocked-src"))return j.warn(`loadScript: script blocked by consent manager (not loaded): ${i}`),!1;const v=new Promise((S,_)=>{y.onload=()=>{j.log(`loadScript: script loaded successfully: ${f}`),cn.loadedScripts.add(f),cn.loadingScripts.delete(f),S()},y.onerror=x=>{j.error(`loadScript: failed to load script: ${i}`,x),cn.loadingScripts.delete(f),_(new jt(`Failed to load script: ${i}`,n))},document.head.appendChild(y)});if(v.catch(()=>{}),cn.loadingScripts.set(f,v),await v,n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){j.error("loadScript: onLoad action failed:",S)}return!0}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,h=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new jt('callExternal handler requires "constructor" parameter',n);const v=this.getNestedProperty(window,i);if(!v||typeof v!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);this.assertCallableExternalConstructor(v,i,n),j.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternal: callback triggered for ${x}`,D),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,D),m&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(m);j.log("callExternal: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternal: merged with existing state",L),this.writeLocalState(r,L)}else f&&r.setState&&this.writeLocalState(r,{[`${f.replace(/:/g,"_")}_result`]:D});if(y){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(y)?y:[y];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternal: callbackAction failed:",B)}}});const _=new v(S);if(c&&typeof _[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&h){const x=document.querySelector(h);if(x)return _[c](x,...d);throw new jt(`Embed target element not found: ${h}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,h=e.callbackAction;if(!i)throw new jt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);this.assertCallableExternalConstructor(m,i,n),j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:v}=this.createEmbedLayer(f),S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternalEmbed: callback triggered for ${x}`,D),v(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,D),c&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(c);j.log("callExternalEmbed: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternalEmbed: merged with existing state",L),this.writeLocalState(r,L)}if(h){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(h)?h:[h];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternalEmbed: callbackAction failed:",B)}}});const _=new m(S);if(typeof _.embed=="function")_.embed(y),j.log("callExternalEmbed: embedded in layer");else throw v(),new jt(`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); @@ -50,11 +50,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()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}static isPrototypePathSegment(e){return cn.PROTOTYPE_PATH_SEGMENTS.includes(e)}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>{if(!cn.isPrototypePathSegment(i))return r&&r[i]!==void 0?r[i]:void 0},e)}assertCallableExternalConstructor(e,n,r){if(typeof window>"u")return;if([window.Function,window.eval,window.setTimeout,window.setInterval].some(l=>l!==void 0&&l===e))throw j.error(`callExternal: blocked arbitrary code execution seam: ${n}`),new jt(`Blocked constructor (arbitrary code execution): ${n}`,r)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),j.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:c}=e;if(!r)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(r);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&this.writeLocalState(n,{[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&this.writeLocalState(n,{[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:r,error:d}),c}}writeLocalState(e,n,r,i){const l=r||e.setState;if(!l)return;if(typeof n=="function"){j.warn("[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다."),l(n);return}if(i?.scope==="parent"||i?.scope==="root"){l(n);return}if(this.localMirrorDepth>0||l?.__g7CanonicalWriter){l(n);return}const c=n&&typeof n=="object"?n:{},d=c.__mergeMode;if(d==="replace"){l(n);return}const{__mergeMode:f,__setStateId:h,...m}=c;if("errors"in m||!cn.isMirrorSafePayload(m)){l(n);return}const y=window;if((y.__g7LayoutContextStack||[]).length>0){l(n);return}const v=y.G7Core?.state?.setLocal;if(!y.__templateApp||typeof v!="function"){l(n);return}const S=this.deepMergeWithState(m,{});this.localMirrorDepth++;try{v(S,{render:!1,merge:d??"deep"}),y.__g7ActionContext?.setState!==l&&l(n),d&&(y.__g7ForcedLocalFields={...y.__g7ForcedLocalFields||{},...S})}finally{this.localMirrorDepth--}}static isMirrorSafePayload(e,n=0){if(e===null||typeof e!="object"||n>=8)return!0;if(Array.isArray(e))return e.every(i=>cn.isMirrorSafePayload(i,n+1));const r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null?!1:Object.values(e).every(i=>cn.isMirrorSafePayload(i,n+1))}makeLocalSetStateProxy(e){const n=e.setState;if(!n)return;if(n.__g7CanonicalWriter)return n;const r=i=>{this.writeLocalState(e,i,n)};return r.__g7CanonicalWriter=!0,r}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const c=new jt(`Unknown action handler: ${e.handler}`,e);throw c.unknownHandler=!0,c}const i=this.makeLocalSetStateProxy(n),l=i&&i!==n.setState?{...n,setState:i}:n;return await r(e,l)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[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?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};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)&&(r={...r,...c})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=La(e);if(r===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=r;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=Wn(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 r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof jt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...r,data:{...r.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,r){this.customHandlers.set(e,n);const i=Yn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Yn();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,r,i,l){const c={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,r,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,h=this.extractEventData(n),m=h._changedKeys;if(m&&Array.isArray(m)&&h?.target?.value&&typeof h.target.value=="object"&&!Array.isArray(h.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const x={..._};for(const A of m)x[A]=h.target.value[A];h.target.value=x}this.debounceAccumulatedValues.set(f,h.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const v=Yn();v?.isEnabled()&&v.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 S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,h,r,i,c),v?.isEnabled()&&v.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,h,r,i,c),v?.isEnabled()&&v.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"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),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,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){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),v=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(v)||l.set(v,[]),l.get(v).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),h=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!h&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...v)=>{for(const S of y){const _=v[0],x=_&&typeof _=="object"&&"preventDefault"in _;if(x&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),x&&S.key&&"key"in _){if(this.isImeComposing(_)){j.log("Key filter skipped (IME composing):",S.key);continue}if(_.key!==S.key){j.log("Key filter not matched:",S.key,"actual:",_.key);continue}j.log("Key filter matched:",S.key)}if(S.debounce){const A=`${c}-${S.handler}-${m}`,D=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let O;if(x)O=_;else if(D){const L={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(L._changedKeys=_._changedKeys),O=L}else O=new Event("custom");const k=S.event?{...n,$args:v}:n;this.handleDebouncedAction(S,O,k,r,A,v)}else if(this.flushPendingDebounceTimers(),S.event){const A={...n,$args:v},D=this.resolveEventForHandler(_,x);this.createHandler(S,A,r)(D)}else if(x)this.createHandler(S,n,r)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(D)}}}}return i}getEventHandlerName(e){return wy[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return wy[e]??e}resolveEventForHandler(e,n){if(n)return e;if(!(e&&typeof e=="object"&&!("preventDefault"in e)&&"target"in e&&e.target!==null))return new Event("custom");const i={type:"custom",target:e.target,preventDefault:()=>{},stopPropagation:()=>{}};return e._changedKeys&&(i._changedKeys=e._changedKeys),i}sanitizeForDevTools(e,n=5){const r=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(r.has(l))return"[Circular Array]";r.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(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),h=f.slice(0,20);for(const m of h)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)}};M(cn,"loadedScripts",new Set),M(cn,"loadingScripts",new Map),M(cn,"PROTOTYPE_PATH_SEGMENTS",["__proto__","prototype","constructor"]);let jo=cn,_c=null;function Cy(s){return _c||(_c=new jo(s)),_c}function o_(s){_c=s}const Ey=pt("TransitionManager");class l_{constructor(){M(this,"isPending",!1);M(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Ey.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(){Ey.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Gr=new l_,Ac=pt("TransitionContext"),_y=I.createContext({isTransitioning:!1}),Mf=({children:s})=>{const[e,n]=I.useState(()=>{const i=Gr.getIsPending();return Ac.log("Initial state:",i),i});I.useEffect(()=>{Ac.log("Subscribing to TransitionManager");const i=Gr.subscribe(l=>{Ac.log("Received isPending update:",l),n(l)});return()=>{Ac.log("Unsubscribing from TransitionManager"),i()}},[]);const r=I.useMemo(()=>({isTransitioning:e}),[e]);return yt.jsx(_y.Provider,{value:r,children:s})},Ay=()=>I.useContext(_y),xc="__g7LocalInitTracking";function Nf(){const s=globalThis;return s[xc]||(s[xc]={hash:"",timestamp:void 0,consumed:void 0}),s[xc]}function c_(){const s=globalThis;s[xc]={hash:"",timestamp:void 0,consumed:void 0}}function u_(s){Nf().consumed=s}function d_(s){return Nf().consumed===s}function f_(s){return s.globalTrackedKey!==s.trackingKey?"apply":s.instanceHandledKey===s.trackingKey?"skip":"prune"}function h_(s,e){return typeof s=="number"&&typeof e=="number"?Math.max(s,e):e??s}function p_(s,e){if(e===void 0)return s;if(!(s!==null&&typeof s=="object"&&e!==null&&typeof e=="object"&&!d_(s)))return e;const{_forceLocalInit:r,...i}=s,{_forceLocalInit:l,...c}=e,d={...i,...c},f=h_(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function g_(s){return s<768?"mobile":s<1024?"tablet":"desktop"}function xy(s){const e=g_(s);return{width:s,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const If=I.createContext(xy(1024)),Tc=({children:s,overrideWidth:e})=>{const[n,r]=I.useState(()=>Ci.getWidth());I.useEffect(()=>{const c=Ci.subscribe(d=>{r(d)});return()=>{c()}},[]);const i=e??n,l=I.useMemo(()=>xy(i),[i]);return yt.jsx(If.Provider,{value:l,children:s})},jf=()=>I.useContext(If);window.G7Core?.createLogger?.("Core:State");function m_(s,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},c=s!==void 0;I.useRef(c);const[d,f]=I.useState(s!==void 0?s:e),h=d,m=I.useRef(s),y=I.useRef(!1);I.useEffect(()=>{if(y.current){m.current=s;return}i&&c&&s!==m.current&&(l?!l(d,s):d!==s)&&f(s),m.current=s},[s,c,i,l,d]);const v=I.useCallback(S=>{const _=typeof S=="function"?S(h):S;(l?l(h,_):h===_)||(y.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{y.current=!1}))},[h,c,n,l]);return[h,v]}function y_(s,e){return s===e?!0:s.length!==e.length?!1:s.every((n,r)=>n===e[r])}function Ty(s,e){if(s===e)return!0;const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>s[i]===e[i])}const ky=I.createContext({}),b_=({children:s,value:e})=>yt.jsx(ky.Provider,{value:e,children:s}),v_=()=>I.useContext(ky),S_=(s,e)=>{if(!s)return;const n=e.split(".");let r=s;for(const i of n){if(r==null)return;r=r[i]}return r},Ry=(s,e,n)=>{const r=e.split(".");if(r.length===1)return{...s,[r[0]]:n};const i={...s};let l=i;for(let c=0;c{bs.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{bs.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},Dy=I.createContext(w_);let C_=0;function E_(){return`isolated-${++C_}-${Date.now().toString(36)}`}function Oy(s,e){if(e==null)return s;if(typeof e!="object"||Array.isArray(e))return e;const n={...s};for(const r of Object.keys(e)){const i=e[r],l=s?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=Oy(l,i):n[r]=i}return n}function __(s,e){return e?e.split(".").reduce((n,r)=>n?.[r],s):s}function A_(s,e,n){const r=e.split("."),i={...s};let l=i;for(let c=0;c{const i=I.useRef(e||E_()).current,[l,c]=I.useState(s),d=I.useRef(l);d.current=l;const f=I.useCallback(S=>__(d.current,S),[]),h=I.useCallback((S,_)=>{c(x=>{const A=A_(x,S,_);return bs.log(`[${i}] setState: ${S} =`,_),A})},[i]),m=I.useCallback((S,_="deep")=>{c(x=>{let A;return _==="replace"?A=S:_==="shallow"?A={...x,...S}:A=Oy(x,S),bs.log(`[${i}] mergeState (${_}):`,S),A})},[i]),y=I.useMemo(()=>({state:l,setState:h,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,h,f,m,i]),v=I.useMemo(()=>({state:d.current,setState:h,getState:f,mergeState:m}),[h,f,m]);return I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=v,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),bs.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),bs.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,v]),I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),yt.jsx(Dy.Provider,{value:y,children:n})},T_=()=>{const s=I.useContext(Dy);return s.scopeId?s:null};var ja=Pg();function k_(){for(var s=arguments.length,e=new Array(s),n=0;nr=>{e.forEach(i=>i(r))},e)}const kc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function vs(s){const e=Object.prototype.toString.call(s);return e==="[object Window]"||e==="[object global]"}function Hf(s){return"nodeType"in s}function Hn(s){var e,n;return s?vs(s)?s:Hf(s)&&(e=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function zf(s){const{Document:e}=Hn(s);return s instanceof e}function Ho(s){return vs(s)?!1:s instanceof Hn(s).HTMLElement}function Ly(s){return s instanceof Hn(s).SVGElement}function Ss(s){return s?vs(s)?s.document:Hf(s)?zf(s)?s:Ho(s)||Ly(s)?s.ownerDocument:document:document:document}const Fr=kc?I.useLayoutEffect:I.useEffect;function Pf(s){const e=I.useRef(s);return Fr(()=>{e.current=s}),I.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{s.current=setInterval(r,i)},[]),n=I.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[e,n]}function zo(s,e){e===void 0&&(e=[s]);const n=I.useRef(s);return Fr(()=>{n.current!==s&&(n.current=s)},e),n}function Po(s,e){const n=I.useRef();return I.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...e])}function Rc(s){const e=Pf(s),n=I.useRef(null),r=I.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Uf(s){const e=I.useRef();return I.useEffect(()=>{e.current=s},[s]),e.current}let Bf={};function Uo(s,e){return I.useMemo(()=>{if(e)return e;const n=Bf[s]==null?0:Bf[s]+1;return Bf[s]=n,s+"-"+n},[s,e])}function $y(s){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,h]of d){const m=l[f];m!=null&&(l[f]=m+s*h)}return l},{...e})}}const ws=$y(1),Bo=$y(-1);function D_(s){return"clientX"in s&&"clientY"in s}function qf(s){if(!s)return!1;const{KeyboardEvent:e}=Hn(s.target);return e&&s instanceof e}function O_(s){if(!s)return!1;const{TouchEvent:e}=Hn(s.target);return e&&s instanceof e}function Gf(s){if(O_(s)){if(s.touches&&s.touches.length){const{clientX:e,clientY:n}=s.touches[0];return{x:e,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:e,clientY:n}=s.changedTouches[0];return{x:e,y:n}}}return D_(s)?{x:s.clientX,y:s.clientY}:null}const qo=Object.freeze({Translate:{toString(s){if(!s)return;const{x:e,y:n}=s;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:e,scaleY:n}=s;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[qo.Translate.toString(s),qo.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:e,duration:n,easing:r}=s;return e+" "+n+"ms "+r}}}),My="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function L_(s){return s.matches(My)?s:s.querySelector(My)}const $_={display:"none"};function M_(s){let{id:e,value:n}=s;return Xe.createElement("div",{id:e,style:$_},n)}function N_(s){let{id:e,announcement:n,ariaLiveType:r="assertive"}=s;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":r,"aria-atomic":!0},n)}function I_(){const[s,e]=I.useState("");return{announce:I.useCallback(r=>{r!=null&&e(r)},[]),announcement:s}}const Ny=I.createContext(null);function j_(s){const e=I.useContext(Ny);I.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(s)},[s,e])}function H_(){const[s]=I.useState(()=>new Set),e=I.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[I.useCallback(r=>{let{type:i,event:l}=r;s.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[s]),e]}const z_={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()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}static isPrototypePathSegment(e){return cn.PROTOTYPE_PATH_SEGMENTS.includes(e)}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>{if(!cn.isPrototypePathSegment(i))return r&&r[i]!==void 0?r[i]:void 0},e)}assertCallableExternalConstructor(e,n,r){if(typeof window>"u")return;if([window.Function,window.eval,window.setTimeout,window.setInterval].some(l=>l!==void 0&&l===e))throw j.error(`callExternal: blocked arbitrary code execution seam: ${n}`),new jt(`Blocked constructor (arbitrary code execution): ${n}`,r)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),j.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:c}=e;if(!r)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(r);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&this.writeLocalState(n,{[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&this.writeLocalState(n,{[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:r,error:d}),c}}writeLocalState(e,n,r,i){const l=r||e.setState;if(!l)return;if(typeof n=="function"){j.warn("[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다."),l(n);return}if(i?.scope==="parent"||i?.scope==="root"){l(n);return}if(this.localMirrorDepth>0||l?.__g7CanonicalWriter){l(n);return}const c=n&&typeof n=="object"?n:{},d=c.__mergeMode;if(d==="replace"){l(n);return}const{__mergeMode:f,__setStateId:h,...m}=c;if("errors"in m||!cn.isMirrorSafePayload(m)){l(n);return}const y=window;if((y.__g7LayoutContextStack||[]).length>0){l(n);return}const v=y.G7Core?.state?.setLocal;if(!y.__templateApp||typeof v!="function"){l(n);return}const S=this.deepMergeWithState(m,{});this.localMirrorDepth++;try{v(S,{render:!1,merge:d??"deep"}),y.__g7ActionContext?.setState!==l&&l(n),d&&(y.__g7ForcedLocalFields={...y.__g7ForcedLocalFields||{},...S})}finally{this.localMirrorDepth--}}static isMirrorSafePayload(e,n=0){if(e===null||typeof e!="object"||n>=8)return!0;if(Array.isArray(e))return e.every(i=>cn.isMirrorSafePayload(i,n+1));const r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null?!1:Object.values(e).every(i=>cn.isMirrorSafePayload(i,n+1))}makeLocalSetStateProxy(e){const n=e.setState;if(!n)return;if(n.__g7CanonicalWriter)return n;const r=i=>{this.writeLocalState(e,i,n)};return r.__g7CanonicalWriter=!0,r}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const c=new jt(`Unknown action handler: ${e.handler}`,e);throw c.unknownHandler=!0,c}const i=this.makeLocalSetStateProxy(n),l=i&&i!==n.setState?{...n,setState:i}:n;return await r(e,l)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[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?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};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)&&(r={...r,...c})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=La(e);if(r===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=r;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=Wn(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 r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof jt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...r,data:{...r.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,r){this.customHandlers.set(e,n);const i=Yn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Yn();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,r,i,l){const c={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,r,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,h=this.extractEventData(n),m=h._changedKeys;if(m&&Array.isArray(m)&&h?.target?.value&&typeof h.target.value=="object"&&!Array.isArray(h.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const x={..._};for(const A of m)x[A]=h.target.value[A];h.target.value=x}this.debounceAccumulatedValues.set(f,h.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const v=Yn();v?.isEnabled()&&v.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 S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,h,r,i,c),v?.isEnabled()&&v.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,h,r,i,c),v?.isEnabled()&&v.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"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),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,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){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),v=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(v)||l.set(v,[]),l.get(v).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),h=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!h&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...v)=>{for(const S of y){const _=v[0],x=_&&typeof _=="object"&&"preventDefault"in _;if(x&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),x&&S.key&&"key"in _){if(this.isImeComposing(_)){j.log("Key filter skipped (IME composing):",S.key);continue}if(_.key!==S.key){j.log("Key filter not matched:",S.key,"actual:",_.key);continue}j.log("Key filter matched:",S.key)}if(S.debounce){const A=`${c}-${S.handler}-${m}`,D=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let O;if(x)O=_;else if(D){const L={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(L._changedKeys=_._changedKeys),O=L}else O=new Event("custom");const k=S.event?{...n,$args:v}:n;this.handleDebouncedAction(S,O,k,r,A,v)}else if(this.flushPendingDebounceTimers(),S.event){const A={...n,$args:v},D=this.resolveEventForHandler(_,x);this.createHandler(S,A,r)(D)}else if(x)this.createHandler(S,n,r)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(D)}}}}return i}getEventHandlerName(e){return wy[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return wy[e]??e}resolveEventForHandler(e,n){if(n)return e;if(!(e&&typeof e=="object"&&!("preventDefault"in e)&&"target"in e&&e.target!==null))return new Event("custom");const i={type:"custom",target:e.target,preventDefault:()=>{},stopPropagation:()=>{}};return e._changedKeys&&(i._changedKeys=e._changedKeys),i}sanitizeForDevTools(e,n=5){const r=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(r.has(l))return"[Circular Array]";r.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(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),h=f.slice(0,20);for(const m of h)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)}};M(cn,"loadedScripts",new Set),M(cn,"loadingScripts",new Map),M(cn,"PROTOTYPE_PATH_SEGMENTS",["__proto__","prototype","constructor"]);let jo=cn,_c=null;function Cy(s){return _c||(_c=new jo(s)),_c}function l_(s){_c=s}const Ey=pt("TransitionManager");class c_{constructor(){M(this,"isPending",!1);M(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Ey.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(){Ey.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Gr=new c_,Ac=pt("TransitionContext"),_y=I.createContext({isTransitioning:!1}),Mf=({children:s})=>{const[e,n]=I.useState(()=>{const i=Gr.getIsPending();return Ac.log("Initial state:",i),i});I.useEffect(()=>{Ac.log("Subscribing to TransitionManager");const i=Gr.subscribe(l=>{Ac.log("Received isPending update:",l),n(l)});return()=>{Ac.log("Unsubscribing from TransitionManager"),i()}},[]);const r=I.useMemo(()=>({isTransitioning:e}),[e]);return yt.jsx(_y.Provider,{value:r,children:s})},Ay=()=>I.useContext(_y),xc="__g7LocalInitTracking";function Nf(){const s=globalThis;return s[xc]||(s[xc]={hash:"",timestamp:void 0,consumed:void 0}),s[xc]}function u_(){const s=globalThis;s[xc]={hash:"",timestamp:void 0,consumed:void 0}}function d_(s){Nf().consumed=s}function f_(s){return Nf().consumed===s}function h_(s){return s.globalTrackedKey!==s.trackingKey?"apply":s.instanceHandledKey===s.trackingKey?"skip":"prune"}function p_(s,e){return typeof s=="number"&&typeof e=="number"?Math.max(s,e):e??s}function g_(s,e){if(e===void 0)return s;if(!(s!==null&&typeof s=="object"&&e!==null&&typeof e=="object"&&!f_(s)))return e;const{_forceLocalInit:r,...i}=s,{_forceLocalInit:l,...c}=e,d={...i,...c},f=p_(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function m_(s){return s<768?"mobile":s<1024?"tablet":"desktop"}function xy(s){const e=m_(s);return{width:s,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const If=I.createContext(xy(1024)),Tc=({children:s,overrideWidth:e})=>{const[n,r]=I.useState(()=>Ci.getWidth());I.useEffect(()=>{const c=Ci.subscribe(d=>{r(d)});return()=>{c()}},[]);const i=e??n,l=I.useMemo(()=>xy(i),[i]);return yt.jsx(If.Provider,{value:l,children:s})},jf=()=>I.useContext(If);window.G7Core?.createLogger?.("Core:State");function y_(s,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},c=s!==void 0;I.useRef(c);const[d,f]=I.useState(s!==void 0?s:e),h=d,m=I.useRef(s),y=I.useRef(!1);I.useEffect(()=>{if(y.current){m.current=s;return}i&&c&&s!==m.current&&(l?!l(d,s):d!==s)&&f(s),m.current=s},[s,c,i,l,d]);const v=I.useCallback(S=>{const _=typeof S=="function"?S(h):S;(l?l(h,_):h===_)||(y.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{y.current=!1}))},[h,c,n,l]);return[h,v]}function b_(s,e){return s===e?!0:s.length!==e.length?!1:s.every((n,r)=>n===e[r])}function Ty(s,e){if(s===e)return!0;const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>s[i]===e[i])}const ky=I.createContext({}),v_=({children:s,value:e})=>yt.jsx(ky.Provider,{value:e,children:s}),S_=()=>I.useContext(ky),w_=(s,e)=>{if(!s)return;const n=e.split(".");let r=s;for(const i of n){if(r==null)return;r=r[i]}return r},Ry=(s,e,n)=>{const r=e.split(".");if(r.length===1)return{...s,[r[0]]:n};const i={...s};let l=i;for(let c=0;c{vs.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{vs.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},Dy=I.createContext(C_);let E_=0;function __(){return`isolated-${++E_}-${Date.now().toString(36)}`}function Oy(s,e){if(e==null)return s;if(typeof e!="object"||Array.isArray(e))return e;const n={...s};for(const r of Object.keys(e)){const i=e[r],l=s?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=Oy(l,i):n[r]=i}return n}function A_(s,e){return e?e.split(".").reduce((n,r)=>n?.[r],s):s}function x_(s,e,n){const r=e.split("."),i={...s};let l=i;for(let c=0;c{const i=I.useRef(e||__()).current,[l,c]=I.useState(s),d=I.useRef(l);d.current=l;const f=I.useCallback(S=>A_(d.current,S),[]),h=I.useCallback((S,_)=>{c(x=>{const A=x_(x,S,_);return vs.log(`[${i}] setState: ${S} =`,_),A})},[i]),m=I.useCallback((S,_="deep")=>{c(x=>{let A;return _==="replace"?A=S:_==="shallow"?A={...x,...S}:A=Oy(x,S),vs.log(`[${i}] mergeState (${_}):`,S),A})},[i]),y=I.useMemo(()=>({state:l,setState:h,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,h,f,m,i]),v=I.useMemo(()=>({state:d.current,setState:h,getState:f,mergeState:m}),[h,f,m]);return I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=v,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),vs.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),vs.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,v]),I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),yt.jsx(Dy.Provider,{value:y,children:n})},k_=()=>{const s=I.useContext(Dy);return s.scopeId?s:null};var ja=Pg();function R_(){for(var s=arguments.length,e=new Array(s),n=0;nr=>{e.forEach(i=>i(r))},e)}const kc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ss(s){const e=Object.prototype.toString.call(s);return e==="[object Window]"||e==="[object global]"}function Hf(s){return"nodeType"in s}function Hn(s){var e,n;return s?Ss(s)?s:Hf(s)&&(e=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function zf(s){const{Document:e}=Hn(s);return s instanceof e}function Ho(s){return Ss(s)?!1:s instanceof Hn(s).HTMLElement}function Ly(s){return s instanceof Hn(s).SVGElement}function ws(s){return s?Ss(s)?s.document:Hf(s)?zf(s)?s:Ho(s)||Ly(s)?s.ownerDocument:document:document:document}const Fr=kc?I.useLayoutEffect:I.useEffect;function Pf(s){const e=I.useRef(s);return Fr(()=>{e.current=s}),I.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{s.current=setInterval(r,i)},[]),n=I.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[e,n]}function zo(s,e){e===void 0&&(e=[s]);const n=I.useRef(s);return Fr(()=>{n.current!==s&&(n.current=s)},e),n}function Po(s,e){const n=I.useRef();return I.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...e])}function Rc(s){const e=Pf(s),n=I.useRef(null),r=I.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Uf(s){const e=I.useRef();return I.useEffect(()=>{e.current=s},[s]),e.current}let Bf={};function Uo(s,e){return I.useMemo(()=>{if(e)return e;const n=Bf[s]==null?0:Bf[s]+1;return Bf[s]=n,s+"-"+n},[s,e])}function $y(s){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,h]of d){const m=l[f];m!=null&&(l[f]=m+s*h)}return l},{...e})}}const Cs=$y(1),Bo=$y(-1);function O_(s){return"clientX"in s&&"clientY"in s}function qf(s){if(!s)return!1;const{KeyboardEvent:e}=Hn(s.target);return e&&s instanceof e}function L_(s){if(!s)return!1;const{TouchEvent:e}=Hn(s.target);return e&&s instanceof e}function Gf(s){if(L_(s)){if(s.touches&&s.touches.length){const{clientX:e,clientY:n}=s.touches[0];return{x:e,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:e,clientY:n}=s.changedTouches[0];return{x:e,y:n}}}return O_(s)?{x:s.clientX,y:s.clientY}:null}const qo=Object.freeze({Translate:{toString(s){if(!s)return;const{x:e,y:n}=s;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:e,scaleY:n}=s;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[qo.Translate.toString(s),qo.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:e,duration:n,easing:r}=s;return e+" "+n+"ms "+r}}}),My="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function $_(s){return s.matches(My)?s:s.querySelector(My)}const M_={display:"none"};function N_(s){let{id:e,value:n}=s;return Xe.createElement("div",{id:e,style:M_},n)}function I_(s){let{id:e,announcement:n,ariaLiveType:r="assertive"}=s;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":r,"aria-atomic":!0},n)}function j_(){const[s,e]=I.useState("");return{announce:I.useCallback(r=>{r!=null&&e(r)},[]),announcement:s}}const Ny=I.createContext(null);function H_(s){const e=I.useContext(Ny);I.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(s)},[s,e])}function z_(){const[s]=I.useState(()=>new Set),e=I.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[I.useCallback(r=>{let{type:i,event:l}=r;s.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[s]),e]}const P_={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. - `},P_={onDragStart(s){let{active:e}=s;return"Picked up draggable item "+e.id+"."},onDragOver(s){let{active:e,over:n}=s;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(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(s){let{active:e}=s;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function U_(s){let{announcements:e=P_,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=z_}=s;const{announce:l,announcement:c}=I_(),d=Uo("DndLiveRegion"),[f,h]=I.useState(!1);if(I.useEffect(()=>{h(!0)},[]),j_(I.useMemo(()=>({onDragStart(y){let{active:v}=y;l(e.onDragStart({active:v}))},onDragMove(y){let{active:v,over:S}=y;e.onDragMove&&l(e.onDragMove({active:v,over:S}))},onDragOver(y){let{active:v,over:S}=y;l(e.onDragOver({active:v,over:S}))},onDragEnd(y){let{active:v,over:S}=y;l(e.onDragEnd({active:v,over:S}))},onDragCancel(y){let{active:v,over:S}=y;l(e.onDragCancel({active:v,over:S}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(M_,{id:r,value:i.draggable}),Xe.createElement(N_,{id:d,announcement:c}));return n?ja.createPortal(m,n):m}var ln;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(ln||(ln={}));function Dc(){}function Iy(s,e){return I.useMemo(()=>({sensor:s,options:e??{}}),[s,e])}function B_(){for(var s=arguments.length,e=new Array(s),n=0;n[...e].filter(r=>r!=null),[...e])}const kr=Object.freeze({x:0,y:0});function jy(s,e){return Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2))}function Hy(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return n-r}function q_(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return r-n}function zy(s){let{left:e,top:n,height:r,width:i}=s;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Py(s,e){if(!s||s.length===0)return null;const[n]=s;return n[e]}function Uy(s,e,n){return e===void 0&&(e=s.left),n===void 0&&(n=s.top),{x:e+s.width*.5,y:n+s.height*.5}}const G_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=Uy(e,e.left,e.top),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=jy(Uy(f),i);l.push({id:d,data:{droppableContainer:c,value:h}})}}return l.sort(Hy)},F_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=zy(e),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=zy(f),m=i.reduce((v,S,_)=>v+jy(h[_],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(Hy)};function V_(s,e){const n=Math.max(e.top,s.top),r=Math.max(e.left,s.left),i=Math.min(e.left+e.width,s.left+s.width),l=Math.min(e.top+e.height,s.top+s.height),c=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=[];for(const l of r){const{id:c}=l,d=n.get(c);if(d){const f=V_(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(q_)};function W_(s,e,n){return{...s,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function By(s,e){return s&&e?{x:s.left-e.left,y:s.top-e.top}:kr}function Y_(s){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...c,top:c.top+s*d.y,bottom:c.bottom+s*d.y,left:c.left+s*d.x,right:c.right+s*d.x}),{...n})}}const X_=Y_(1);function J_(s){if(s.startsWith("matrix3d(")){const e=s.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(s.startsWith("matrix(")){const e=s.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Q_(s,e,n){const r=J_(e);if(!r)return s;const{scaleX:i,scaleY:l,x:c,y:d}=r,f=s.left-c-(1-i)*parseFloat(n),h=s.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?s.width/i:s.width,y=l?s.height/l:s.height;return{width:m,height:y,top:h,right:f+m,bottom:h+y,left:f}}const Z_={ignoreTransform:!1};function Cs(s,e){e===void 0&&(e=Z_);let n=s.getBoundingClientRect();if(e.ignoreTransform){const{transform:h,transformOrigin:m}=Hn(s).getComputedStyle(s);h&&(n=Q_(n,h,m))}const{top:r,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:c,bottom:d,right:f}}function qy(s){return Cs(s,{ignoreTransform:!0})}function eA(s){const e=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function tA(s,e){return e===void 0&&(e=Hn(s).getComputedStyle(s)),e.position==="fixed"}function nA(s,e){e===void 0&&(e=Hn(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function Oc(s,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(zf(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Ho(i)||Ly(i)||n.includes(i))return n;const l=Hn(s).getComputedStyle(i);return i!==s&&nA(i,l)&&n.push(i),tA(i,l)?n:r(i.parentNode)}return s?r(s):n}function Gy(s){const[e]=Oc(s,1);return e??null}function Ff(s){return!kc||!s?null:vs(s)?s:Hf(s)?zf(s)||s===Ss(s).scrollingElement?window:Ho(s)?s:null:null}function Fy(s){return vs(s)?s.scrollX:s.scrollLeft}function Vy(s){return vs(s)?s.scrollY:s.scrollTop}function Vf(s){return{x:Fy(s),y:Vy(s)}}var mn;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(mn||(mn={}));function Ky(s){return!kc||!s?!1:s===document.scrollingElement}function Wy(s){const e={x:0,y:0},n=Ky(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},i=s.scrollTop<=e.y,l=s.scrollLeft<=e.x,c=s.scrollTop>=r.y,d=s.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:r,minScroll:e}}const rA={x:.2,y:.2};function aA(s,e,n,r,i){let{top:l,left:c,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=rA);const{isTop:h,isBottom:m,isLeft:y,isRight:v}=Wy(s),S={x:0,y:0},_={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!h&&l<=e.top+x.height?(S.y=mn.Backward,_.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=mn.Forward,_.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!v&&d>=e.right-x.width?(S.x=mn.Forward,_.x=r*Math.abs((e.right-x.width-d)/x.width)):!y&&c<=e.left+x.width&&(S.x=mn.Backward,_.x=r*Math.abs((e.left+x.width-c)/x.width)),{direction:S,speed:_}}function iA(s){if(s===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:r,bottom:i}=s.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:s.clientWidth,height:s.clientHeight}}function Yy(s){return s.reduce((e,n)=>ws(e,Vf(n)),kr)}function sA(s){return s.reduce((e,n)=>e+Fy(n),0)}function oA(s){return s.reduce((e,n)=>e+Vy(n),0)}function lA(s,e){if(e===void 0&&(e=Cs),!s)return;const{top:n,left:r,bottom:i,right:l}=e(s);Gy(s)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const cA=[["x",["left","right"],sA],["y",["top","bottom"],oA]];class Kf{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 r=Oc(n),i=Yy(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of cA)for(const f of c)Object.defineProperty(this,f,{get:()=>{const h=d(r),m=i[l]-h;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Go{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function uA(s){const{EventTarget:e}=Hn(s);return s instanceof e?s:Ss(s)}function Wf(s,e){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var cr;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(cr||(cr={}));function Xy(s){s.preventDefault()}function dA(s){s.stopPropagation()}var dt;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(dt||(dt={}));const Jy={start:[dt.Space,dt.Enter],cancel:[dt.Esc],end:[dt.Space,dt.Enter,dt.Tab]},fA=(s,e)=>{let{currentCoordinates:n}=e;switch(s.code){case dt.Right:return{...n,x:n.x+25};case dt.Left:return{...n,x:n.x-25};case dt.Down:return{...n,y:n.y+25};case dt.Up:return{...n,y:n.y-25}}};class Yf{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 Go(Ss(n)),this.windowListeners=new Go(Hn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(cr.Resize,this.handleCancel),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(cr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&lA(r),n(kr)}handleKeyDown(e){if(qf(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Jy,coordinateGetter:c=fA,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:h}=r.current,m=h?{x:h.left,y:h.top}:kr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:r.current,currentCoordinates:m});if(y){const v=Bo(y,m),S={x:0,y:0},{scrollableAncestors:_}=r.current;for(const x of _){const A=e.code,{isTop:D,isRight:O,isLeft:k,isBottom:L,maxScroll:B,minScroll:q}=Wy(x),z=iA(x),W={x:Math.min(A===dt.Right?z.right-z.width/2:z.right,Math.max(A===dt.Right?z.left:z.left+z.width/2,y.x)),y:Math.min(A===dt.Down?z.bottom-z.height/2:z.bottom,Math.max(A===dt.Down?z.top:z.top+z.height/2,y.y))},de=A===dt.Right&&!O||A===dt.Left&&!k,_e=A===dt.Down&&!L||A===dt.Up&&!D;if(de&&W.x!==y.x){const Se=x.scrollLeft+v.x,Ie=A===dt.Right&&Se<=B.x||A===dt.Left&&Se>=q.x;if(Ie&&!v.y){x.scrollTo({left:Se,behavior:d});return}Ie?S.x=x.scrollLeft-Se:S.x=A===dt.Right?x.scrollLeft-B.x:x.scrollLeft-q.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(_e&&W.y!==y.y){const Se=x.scrollTop+v.y,Ie=A===dt.Down&&Se<=B.y||A===dt.Up&&Se>=q.y;if(Ie&&!v.x){x.scrollTo({top:Se,behavior:d});return}Ie?S.y=x.scrollTop-Se:S.y=A===dt.Down?x.scrollTop-B.y:x.scrollTop-q.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,ws(Bo(y,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(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()}}Yf.activators=[{eventName:"onKeyDown",handler:(s,e,n)=>{let{keyboardCodes:r=Jy,onActivation:i}=e,{active:l}=n;const{code:c}=s.nativeEvent;if(r.start.includes(c)){const d=l.activatorNode.current;return d&&s.target!==d?!1:(s.preventDefault(),i?.({event:s.nativeEvent}),!0)}return!1}}];function Qy(s){return!!(s&&"distance"in s)}function Zy(s){return!!(s&&"delay"in s)}class Xf{constructor(e,n,r){var i;r===void 0&&(r=uA(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=Ss(c),this.documentListeners=new Go(this.document),this.listeners=new Go(r),this.windowListeners=new Go(Hn(c)),this.initialCoordinates=(i=Gf(l))!=null?i:kr,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:r}}}=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(cr.Resize,this.handleCancel),this.windowListeners.add(cr.DragStart,Xy),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),this.windowListeners.add(cr.ContextMenu,Xy),this.documentListeners.add(cr.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Zy(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Qy(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:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(cr.Click,dA,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(cr.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Gf(e))!=null?n:kr,h=Bo(i,f);if(!r&&d){if(Qy(d)){if(d.tolerance!=null&&Wf(h,d.tolerance))return this.handleCancel();if(Wf(h,d.distance))return this.handleStart()}if(Zy(d)&&Wf(h,d.tolerance))return this.handleCancel();this.handlePending(d,h);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===dt.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const hA={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Jf extends Xf{constructor(e){const{event:n}=e,r=Ss(n.target);super(e,hA,r)}}Jf.activators=[{eventName:"onPointerDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const pA={move:{name:"mousemove"},end:{name:"mouseup"}};var Qf;(function(s){s[s.RightClick=2]="RightClick"})(Qf||(Qf={}));class gA extends Xf{constructor(e){super(e,pA,Ss(e.event.target))}}gA.activators=[{eventName:"onMouseDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return n.button===Qf.RightClick?!1:(r?.({event:n}),!0)}}];const Zf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class mA extends Xf{constructor(e){super(e,Zf)}static setup(){return window.addEventListener(Zf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Zf.move.name,e)};function e(){}}}mA.activators=[{eventName:"onTouchStart",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var Fo;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var Lc;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Lc||(Lc={}));function yA(s){let{acceleration:e,activator:n=Fo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:c=5,order:d=Lc.TreeOrder,pointerCoordinates:f,scrollableAncestors:h,scrollableAncestorRects:m,delta:y,threshold:v}=s;const S=vA({delta:y,disabled:!l}),[_,x]=R_(),A=I.useRef({x:0,y:0}),D=I.useRef({x:0,y:0}),O=I.useMemo(()=>{switch(n){case Fo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Fo.DraggableRect:return i}},[n,i,f]),k=I.useRef(null),L=I.useCallback(()=>{const q=k.current;if(!q)return;const z=A.current.x*D.current.x,W=A.current.y*D.current.y;q.scrollBy(z,W)},[]),B=I.useMemo(()=>d===Lc.TreeOrder?[...h].reverse():h,[d,h]);I.useEffect(()=>{if(!l||!h.length||!O){x();return}for(const q of B){if(r?.(q)===!1)continue;const z=h.indexOf(q),W=m[z];if(!W)continue;const{direction:de,speed:_e}=aA(q,W,O,e,v);for(const Se of["x","y"])S[Se][de[Se]]||(_e[Se]=0,de[Se]=0);if(_e.x>0||_e.y>0){x(),k.current=q,_(L,c),A.current=_e,D.current=de;return}}A.current={x:0,y:0},D.current={x:0,y:0},x()},[e,L,r,x,l,c,JSON.stringify(O),JSON.stringify(S),_,h,B,m,JSON.stringify(v)])}const bA={x:{[mn.Backward]:!1,[mn.Forward]:!1},y:{[mn.Backward]:!1,[mn.Forward]:!1}};function vA(s){let{delta:e,disabled:n}=s;const r=Uf(e);return Po(i=>{if(n||!r||!i)return bA;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[mn.Backward]:i.x[mn.Backward]||l.x===-1,[mn.Forward]:i.x[mn.Forward]||l.x===1},y:{[mn.Backward]:i.y[mn.Backward]||l.y===-1,[mn.Forward]:i.y[mn.Forward]||l.y===1}}},[n,e,r])}function SA(s,e){const n=e!=null?s.get(e):void 0,r=n?n.node.current:null;return Po(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function wA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,r)}));return[...n,...l]},[]),[s,e])}var Vo;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Vo||(Vo={}));var eh;(function(s){s.Optimized="optimized"})(eh||(eh={}));const eb=new Map;function CA(s,e){let{dragging:n,dependencies:r,config:i}=e;const[l,c]=I.useState(null),{frequency:d,measure:f,strategy:h}=i,m=I.useRef(s),y=A(),v=zo(y),S=I.useCallback(function(D){D===void 0&&(D=[]),!v.current&&c(O=>O===null?D:O.concat(D.filter(k=>!O.includes(k))))},[v]),_=I.useRef(null),x=Po(D=>{if(y&&!n)return eb;if(!D||D===eb||m.current!==s||l!=null){const O=new Map;for(let k of s){if(!k)continue;if(l&&l.length>0&&!l.includes(k.id)&&k.rect.current){O.set(k.id,k.rect.current);continue}const L=k.node.current,B=L?new Kf(f(L),L):null;k.rect.current=B,B&&O.set(k.id,B)}return O}return D},[s,l,n,y,f]);return I.useEffect(()=>{m.current=s},[s]),I.useEffect(()=>{y||S()},[n,y]),I.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),I.useEffect(()=>{y||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{S(),_.current=null},d))},[d,y,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function A(){switch(h){case Vo.Always:return!1;case Vo.BeforeDragging:return n;default:return!n}}}function tb(s,e){return Po(n=>s?n||(typeof e=="function"?e(s):s):null,[e,s])}function EA(s,e){return tb(s,e)}function _A(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function $c(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function AA(s){return new Kf(Cs(s),s)}function nb(s,e,n){e===void 0&&(e=AA);const[r,i]=I.useState(null);function l(){i(f=>{if(!s)return null;if(s.isConnected===!1){var h;return(h=f??n)!=null?h:null}const m=e(s);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=_A({callback(f){if(s)for(const h of f){const{type:m,target:y}=h;if(m==="childList"&&y instanceof HTMLElement&&y.contains(s)){l();break}}}}),d=$c({callback:l});return Fr(()=>{l(),s?(d?.observe(s),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[s]),r}function xA(s){const e=tb(s);return By(s,e)}const rb=[];function TA(s){const e=I.useRef(s),n=Po(r=>s?r&&r!==rb&&s&&e.current&&s.parentNode===e.current.parentNode?r:Oc(s):rb,[s]);return I.useEffect(()=>{e.current=s},[s]),n}function kA(s){const[e,n]=I.useState(null),r=I.useRef(s),i=I.useCallback(l=>{const c=Ff(l.target);c&&n(d=>d?(d.set(c,Vf(c)),new Map(d)):null)},[]);return I.useEffect(()=>{const l=r.current;if(s!==l){c(l);const d=s.map(f=>{const h=Ff(f);return h?(h.addEventListener("scroll",i,{passive:!0}),[h,Vf(h)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=s}return()=>{c(s),c(l)};function c(d){d.forEach(f=>{const h=Ff(f);h?.removeEventListener("scroll",i)})}},[i,s]),I.useMemo(()=>s.length?e?Array.from(e.values()).reduce((l,c)=>ws(l,c),kr):Yy(s):kr,[s,e])}function ab(s,e){e===void 0&&(e=[]);const n=I.useRef(null);return I.useEffect(()=>{n.current=null},e),I.useEffect(()=>{const r=s!==kr;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?Bo(s,n.current):kr}function RA(s){I.useEffect(()=>{if(!kc)return;const e=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},s.map(e=>{let{sensor:n}=e;return n}))}function DA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=c=>{l(c,e)},n},{}),[s,e])}function ib(s){return I.useMemo(()=>s?eA(s):null,[s])}const sb=[];function OA(s,e){e===void 0&&(e=Cs);const[n]=s,r=ib(n?Hn(n):null),[i,l]=I.useState(sb);function c(){l(()=>s.length?s.map(f=>Ky(f)?r:new Kf(e(f),f)):sb)}const d=$c({callback:c});return Fr(()=>{d?.disconnect(),c(),s.forEach(f=>d?.observe(f))},[s]),i}function LA(s){if(!s)return null;if(s.children.length>1)return s;const e=s.children[0];return Ho(e)?e:s}function $A(s){let{measure:e}=s;const[n,r]=I.useState(null),i=I.useCallback(h=>{for(const{target:m}of h)if(Ho(m)){r(y=>{const v=e(m);return y?{...y,width:v.width,height:v.height}:v});break}},[e]),l=$c({callback:i}),c=I.useCallback(h=>{const m=LA(h);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Rc(c);return I.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const MA=[{sensor:Jf,options:{}},{sensor:Yf,options:{}}],NA={current:{}},Mc={draggable:{measure:qy},droppable:{measure:qy,strategy:Vo.WhileDragging,frequency:eh.Optimized},dragOverlay:{measure:Cs}};class Ko 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,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const IA={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ko,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Dc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Mc,measureDroppableContainers:Dc,windowRect:null,measuringScheduled:!1},jA={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Dc,draggableNodes:new Map,over:null,measureDroppableContainers:Dc},Nc=I.createContext(jA),ob=I.createContext(IA);function HA(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ko}}}function zA(s,e){switch(e.type){case ln.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case ln.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:e.coordinates.x-s.draggable.initialCoordinates.x,y:e.coordinates.y-s.draggable.initialCoordinates.y}}};case ln.DragEnd:case ln.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ln.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Ko(s.droppable.containers);return i.set(r,n),{...s,droppable:{...s.droppable,containers:i}}}case ln.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=s.droppable.containers.get(n);if(!l||r!==l.key)return s;const c=new Ko(s.droppable.containers);return c.set(n,{...l,disabled:i}),{...s,droppable:{...s.droppable,containers:c}}}case ln.UnregisterDroppable:{const{id:n,key:r}=e,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Ko(s.droppable.containers);return l.delete(n),{...s,droppable:{...s.droppable,containers:l}}}default:return s}}function PA(s){let{disabled:e}=s;const{active:n,activatorEvent:r,draggableNodes:i}=I.useContext(Nc),l=Uf(r),c=Uf(n?.id);return I.useEffect(()=>{if(!e&&!r&&l&&c!=null){if(!qf(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:h}=d;if(!f.current&&!h.current)return;requestAnimationFrame(()=>{for(const m of[f.current,h.current]){if(!m)continue;const y=L_(m);if(y){y.focus();break}}})}},[r,e,i,c,l]),null}function UA(s,e){let{transform:n,...r}=e;return s!=null&&s.length?s.reduce((i,l)=>l({transform:i,...r}),n):n}function BA(s){return I.useMemo(()=>({draggable:{...Mc.draggable,...s?.draggable},droppable:{...Mc.droppable,...s?.droppable},dragOverlay:{...Mc.dragOverlay,...s?.dragOverlay}}),[s?.draggable,s?.droppable,s?.dragOverlay])}function qA(s){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=s;const l=I.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Fr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!r)return;const h=e?.node.current;if(!h||h.isConnected===!1)return;const m=n(h),y=By(m,r);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const v=Gy(h);v&&v.scrollBy({top:y.y,left:y.x})}},[e,c,d,r,n])}const lb=I.createContext({...kr,scaleX:1,scaleY:1});var Ha;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Ha||(Ha={}));const GA=I.memo(function(e){var n,r,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:h,sensors:m=MA,collisionDetection:y=K_,measuring:v,modifiers:S,..._}=e;const x=I.useReducer(zA,void 0,HA),[A,D]=x,[O,k]=H_(),[L,B]=I.useState(Ha.Uninitialized),q=L===Ha.Initialized,{draggable:{active:z,nodes:W,translate:de},droppable:{containers:_e}}=A,Se=z!=null?W.get(z):null,Ie=I.useRef({initial:null,translated:null}),Fe=I.useMemo(()=>{var pe;return z!=null?{id:z,data:(pe=Se?.data)!=null?pe:NA,rect:Ie}:null},[z,Se]),ze=I.useRef(null),[Et,Q]=I.useState(null),[ue,De]=I.useState(null),ee=zo(_,Object.values(_)),me=Uo("DndDescribedBy",c),H=I.useMemo(()=>_e.getEnabled(),[_e]),T=BA(v),{droppableRects:fe,measureDroppableContainers:he,measuringScheduled:Ae}=CA(H,{dragging:q,dependencies:[de.x,de.y],config:T.droppable}),se=SA(W,z),ge=I.useMemo(()=>ue?Gf(ue):null,[ue]),$e=ve(),Te=EA(se,T.draggable.measure);qA({activeNode:z!=null?W.get(z):null,config:$e.layoutShiftCompensation,initialRect:Te,measure:T.draggable.measure});const je=nb(se,T.draggable.measure,Te),xt=nb(se?se.parentElement:null),rt=I.useRef({activatorEvent:null,active:null,activeNode:se,collisionRect:null,collisions:null,droppableRects:fe,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:_e,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),gt=_e.getNodeFor((n=rt.current.over)==null?void 0:n.id),at=$A({measure:T.dragOverlay.measure}),Yt=(r=at.nodeRef.current)!=null?r:se,Ht=q?(i=at.rect)!=null?i:je:null,bt=!!(at.nodeRef.current&&at.rect),qe=xA(bt?null:je),mt=ib(Yt?Hn(Yt):null),Dt=TA(q?gt??se:null),zt=OA(Dt),kn=UA(S,{transform:{x:de.x-qe.x,y:de.y-qe.y,scaleX:1,scaleY:1},activatorEvent:ue,active:Fe,activeNodeRect:je,containerNodeRect:xt,draggingNodeRect:Ht,over:rt.current.over,overlayNodeRect:at.rect,scrollableAncestors:Dt,scrollableAncestorRects:zt,windowRect:mt}),dr=ge?ws(ge,de):null,Ot=kA(Dt),Li=ab(Ot),ua=ab(Ot,[je]),bn=ws(kn,Li),Mn=Ht?X_(Ht,kn):null,it=Fe&&Mn?y({active:Fe,collisionRect:Mn,droppableRects:fe,droppableContainers:H,pointerCoordinates:dr}):null,Pn=Py(it,"id"),[vn,da]=I.useState(null),fr=bt?kn:ws(kn,ua),un=W_(fr,(l=vn?.rect)!=null?l:null,je),Rn=I.useRef(null),dn=I.useCallback((pe,Ee)=>{let{sensor:xe,options:Ke}=Ee;if(ze.current==null)return;const ke=W.get(ze.current);if(!ke)return;const Me=pe.nativeEvent,Re=new xe({active:ze.current,activeNode:ke,event:Me,options:Ke,context:rt,onAbort(Pe){if(!W.get(Pe))return;const{onDragAbort:Ce}=ee.current,He={id:Pe};Ce?.(He),O({type:"onDragAbort",event:He})},onPending(Pe,Ve,Ce,He){if(!W.get(Pe))return;const{onDragPending:Lt}=ee.current,Bt={id:Pe,constraint:Ve,initialCoordinates:Ce,offset:He};Lt?.(Bt),O({type:"onDragPending",event:Bt})},onStart(Pe){const Ve=ze.current;if(Ve==null)return;const Ce=W.get(Ve);if(!Ce)return;const{onDragStart:He}=ee.current,nt={activatorEvent:Me,active:{id:Ve,data:Ce.data,rect:Ie}};ja.unstable_batchedUpdates(()=>{He?.(nt),B(Ha.Initializing),D({type:ln.DragStart,initialCoordinates:Pe,active:Ve}),O({type:"onDragStart",event:nt}),Q(Rn.current),De(Me)})},onMove(Pe){D({type:ln.DragMove,coordinates:Pe})},onEnd:tt(ln.DragEnd),onCancel:tt(ln.DragCancel)});Rn.current=Re;function tt(Pe){return async function(){const{active:Ce,collisions:He,over:nt,scrollAdjustedTranslate:Lt}=rt.current;let Bt=null;if(Ce&&Lt){const{cancelDrop:Nn}=ee.current;Bt={activatorEvent:Me,active:Ce,collisions:He,delta:Lt,over:nt},Pe===ln.DragEnd&&typeof Nn=="function"&&await Promise.resolve(Nn(Bt))&&(Pe=ln.DragCancel)}ze.current=null,ja.unstable_batchedUpdates(()=>{D({type:Pe}),B(Ha.Uninitialized),da(null),Q(null),De(null),Rn.current=null;const Nn=Pe===ln.DragEnd?"onDragEnd":"onDragCancel";if(Bt){const Gt=ee.current[Nn];Gt?.(Bt),O({type:Nn,event:Bt})}})}}},[W]),V=I.useCallback((pe,Ee)=>(xe,Ke)=>{const ke=xe.nativeEvent,Me=W.get(Ke);if(ze.current!==null||!Me||ke.dndKit||ke.defaultPrevented)return;const Re={active:Me};pe(xe,Ee.options,Re)===!0&&(ke.dndKit={capturedBy:Ee.sensor},ze.current=Ke,dn(xe,Ee))},[W,dn]),ie=wA(m,V);RA(m),Fr(()=>{je&&L===Ha.Initializing&&B(Ha.Initialized)},[je,L]),I.useEffect(()=>{const{onDragMove:pe}=ee.current,{active:Ee,activatorEvent:xe,collisions:Ke,over:ke}=rt.current;if(!Ee||!xe)return;const Me={active:Ee,activatorEvent:xe,collisions:Ke,delta:{x:bn.x,y:bn.y},over:ke};ja.unstable_batchedUpdates(()=>{pe?.(Me),O({type:"onDragMove",event:Me})})},[bn.x,bn.y]),I.useEffect(()=>{const{active:pe,activatorEvent:Ee,collisions:xe,droppableContainers:Ke,scrollAdjustedTranslate:ke}=rt.current;if(!pe||ze.current==null||!Ee||!ke)return;const{onDragOver:Me}=ee.current,Re=Ke.get(Pn),tt=Re&&Re.rect.current?{id:Re.id,rect:Re.rect.current,data:Re.data,disabled:Re.disabled}:null,Pe={active:pe,activatorEvent:Ee,collisions:xe,delta:{x:ke.x,y:ke.y},over:tt};ja.unstable_batchedUpdates(()=>{da(tt),Me?.(Pe),O({type:"onDragOver",event:Pe})})},[Pn]),Fr(()=>{rt.current={activatorEvent:ue,active:Fe,activeNode:se,collisionRect:Mn,collisions:it,droppableRects:fe,draggableNodes:W,draggingNode:Yt,draggingNodeRect:Ht,droppableContainers:_e,over:vn,scrollableAncestors:Dt,scrollAdjustedTranslate:bn},Ie.current={initial:Ht,translated:Mn}},[Fe,se,it,Mn,W,Yt,Ht,fe,_e,vn,Dt,bn]),yA({...$e,delta:de,draggingRect:Mn,pointerCoordinates:dr,scrollableAncestors:Dt,scrollableAncestorRects:zt});const ce=I.useMemo(()=>({active:Fe,activeNode:se,activeNodeRect:je,activatorEvent:ue,collisions:it,containerNodeRect:xt,dragOverlay:at,draggableNodes:W,droppableContainers:_e,droppableRects:fe,over:vn,measureDroppableContainers:he,scrollableAncestors:Dt,scrollableAncestorRects:zt,measuringConfiguration:T,measuringScheduled:Ae,windowRect:mt}),[Fe,se,je,ue,it,xt,at,W,_e,fe,vn,he,Dt,zt,T,Ae,mt]),Z=I.useMemo(()=>({activatorEvent:ue,activators:ie,active:Fe,activeNodeRect:je,ariaDescribedById:{draggable:me},dispatch:D,draggableNodes:W,over:vn,measureDroppableContainers:he}),[ue,ie,Fe,je,D,me,W,vn,he]);return Xe.createElement(Ny.Provider,{value:k},Xe.createElement(Nc.Provider,{value:Z},Xe.createElement(ob.Provider,{value:ce},Xe.createElement(lb.Provider,{value:un},h)),Xe.createElement(PA,{disabled:d?.restoreFocus===!1})),Xe.createElement(U_,{...d,hiddenTextDescribedById:me}));function ve(){const pe=Et?.autoScrollEnabled===!1,Ee=typeof f=="object"?f.enabled===!1:f===!1,xe=q&&!pe&&!Ee;return typeof f=="object"?{...f,enabled:xe}:{enabled:xe}}}),FA=I.createContext(null),cb="button",VA="Draggable";function KA(s){let{id:e,data:n,disabled:r=!1,attributes:i}=s;const l=Uo(VA),{activators:c,activatorEvent:d,active:f,activeNodeRect:h,ariaDescribedById:m,draggableNodes:y,over:v}=I.useContext(Nc),{role:S=cb,roleDescription:_="draggable",tabIndex:x=0}=i??{},A=f?.id===e,D=I.useContext(A?lb:FA),[O,k]=Rc(),[L,B]=Rc(),q=DA(c,e),z=zo(n);Fr(()=>(y.set(e,{id:e,key:l,node:O,activatorNode:L,data:z}),()=>{const de=y.get(e);de&&de.key===l&&y.delete(e)}),[y,e]);const W=I.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":A&&S===cb?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[r,S,x,A,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:h,attributes:W,isDragging:A,listeners:r?void 0:q,node:O,over:v,setNodeRef:k,setActivatorNodeRef:B,transform:D}}function WA(){return I.useContext(ob)}const YA="Droppable",XA={timeout:25};function JA(s){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=s;const l=Uo(YA),{active:c,dispatch:d,over:f,measureDroppableContainers:h}=I.useContext(Nc),m=I.useRef({disabled:n}),y=I.useRef(!1),v=I.useRef(null),S=I.useRef(null),{disabled:_,updateMeasurementsFor:x,timeout:A}={...XA,...i},D=zo(x??r),O=I.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{h(Array.isArray(D.current)?D.current:[D.current]),S.current=null},A)},[A]),k=$c({callback:O,disabled:_||!c}),L=I.useCallback((W,de)=>{k&&(de&&(k.unobserve(de),y.current=!1),W&&k.observe(W))},[k]),[B,q]=Rc(L),z=zo(e);return I.useEffect(()=>{!k||!B.current||(k.disconnect(),y.current=!1,k.observe(B.current))},[B,k]),I.useEffect(()=>(d({type:ln.RegisterDroppable,element:{id:r,key:l,disabled:n,node:B,rect:v,data:z}}),()=>d({type:ln.UnregisterDroppable,key:l,id:r})),[r]),I.useEffect(()=>{n!==m.current.disabled&&(d({type:ln.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:c,rect:v,isOver:f?.id===r,node:B,over:f,setNodeRef:q}}function th(s,e,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function QA(s,e){return s.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(s.length))}function Ic(s){return s!==null&&s>=0}function ZA(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:c}=s;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=nx(n,c,i);if(c===i){const h=n[l];return h?{x:ii&&c<=l?{x:-d.width-f,y:0,...jc}:c=l?{x:d.width+f,y:0,...jc}:{x:0,y:0,...jc}};function nx(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=s;const l=th(e,r,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}},Hc={scaleX:1,scaleY:1},rx=s=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:c}=s;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const h=l[c];return h?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...Hc}:i=c?{x:0,y:d.height+f,...Hc}:{x:0,y:0,...Hc}};function ax(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return r?nr.map(q=>typeof q=="object"&&"id"in q?q.id:q),[r]),_=c!=null,x=c?S.indexOf(c.id):-1,A=h?S.indexOf(h.id):-1,D=I.useRef(S),O=!ZA(S,D.current),k=A!==-1&&x===-1||O,L=ex(l);Fr(()=>{O&&_&&m(S)},[O,S,_,m]),I.useEffect(()=>{D.current=S},[S]);const B=I.useMemo(()=>({activeIndex:x,containerId:y,disabled:L,disableTransforms:k,items:S,overIndex:A,useDragOverlay:v,sortedRects:QA(S,f),strategy:i}),[x,y,L.draggable,L.droppable,k,S,A,f,v,i]);return Xe.createElement(db.Provider,{value:B},e)}const sx=s=>{let{id:e,items:n,activeIndex:r,overIndex:i}=s;return th(n,r,i).indexOf(e)},ox=s=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:h}=s;return!h||!r||d!==l&&i===c?!1:n?!0:c!==i&&e===f},lx={duration:200,easing:"ease"},fb="transform",cx=qo.Transition.toString({property:fb,duration:0,easing:"linear"}),ux={roleDescription:"sortable"};function dx(s){let{disabled:e,index:n,node:r,rect:i}=s;const[l,c]=I.useState(null),d=I.useRef(n);return Fr(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const h=Cs(r.current,{ignoreTransform:!0}),m={x:f.left-h.left,y:f.top-h.top,scaleX:f.width/h.width,scaleY:f.height/h.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),I.useEffect(()=>{l&&c(null)},[l]),l}function fx(s){let{animateLayoutChanges:e=ox,attributes:n,disabled:r,data:i,getNewIndex:l=sx,id:c,strategy:d,resizeObserverConfig:f,transition:h=lx}=s;const{items:m,containerId:y,activeIndex:v,disabled:S,disableTransforms:_,sortedRects:x,overIndex:A,useDragOverlay:D,strategy:O}=I.useContext(db),k=hx(r,S),L=m.indexOf(c),B=I.useMemo(()=>({sortable:{containerId:y,index:L,items:m},...i}),[y,i,L,m]),q=I.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:z,node:W,isOver:de,setNodeRef:_e}=JA({id:c,data:B,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:q,...f}}),{active:Se,activatorEvent:Ie,activeNodeRect:Fe,attributes:ze,setNodeRef:Et,listeners:Q,isDragging:ue,over:De,setActivatorNodeRef:ee,transform:me}=KA({id:c,data:B,attributes:{...ux,...n},disabled:k.draggable}),H=k_(_e,Et),T=!!Se,fe=T&&!_&&Ic(v)&&Ic(A),he=!D&&ue,Ae=he&&fe?me:null,ge=fe?Ae??(d??O)({rects:x,activeNodeRect:Fe,activeIndex:v,overIndex:A,index:L}):null,$e=Ic(v)&&Ic(A)?l({id:c,items:m,activeIndex:v,overIndex:A}):L,Te=Se?.id,je=I.useRef({activeId:Te,items:m,newIndex:$e,containerId:y}),xt=m!==je.current.items,rt=e({active:Se,containerId:y,isDragging:ue,isSorting:T,id:c,index:L,items:m,newIndex:je.current.newIndex,previousItems:je.current.items,previousContainerId:je.current.containerId,transition:h,wasDragging:je.current.activeId!=null}),gt=dx({disabled:!rt,index:L,node:W,rect:z});return I.useEffect(()=>{T&&je.current.newIndex!==$e&&(je.current.newIndex=$e),y!==je.current.containerId&&(je.current.containerId=y),m!==je.current.items&&(je.current.items=m)},[T,$e,y,m]),I.useEffect(()=>{if(Te===je.current.activeId)return;if(Te!=null&&je.current.activeId==null){je.current.activeId=Te;return}const Yt=setTimeout(()=>{je.current.activeId=Te},50);return()=>clearTimeout(Yt)},[Te]),{active:Se,activeIndex:v,attributes:ze,data:B,rect:z,index:L,newIndex:$e,items:m,isOver:de,isSorting:T,isDragging:ue,listeners:Q,node:W,overIndex:A,over:De,setNodeRef:H,setActivatorNodeRef:ee,setDroppableNodeRef:_e,setDraggableNodeRef:Et,transform:gt??ge,transition:at()};function at(){if(gt||xt&&je.current.newIndex===L)return cx;if(!(he&&!qf(Ie)||!h)&&(T||rt))return qo.Transition.toString({...h,property:fb})}}function hx(s,e){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s?.draggable)!=null?n:e.draggable,droppable:(r=s?.droppable)!=null?r:e.droppable}}function zc(s){if(!s)return!1;const e=s.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const px=[dt.Down,dt.Right,dt.Up,dt.Left],gx=(s,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(px.includes(s.code)){if(s.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const v=i.get(y.id);if(v)switch(s.code){case dt.Down:r.topv.top&&f.push(y);break;case dt.Left:r.left>v.left&&f.push(y);break;case dt.Right:r.left1&&(m=h[1].id),m!=null){const y=l.get(n.id),v=l.get(m),S=v?i.get(v.id):null,_=v?.node.current;if(_&&S&&y&&v){const A=Oc(_).some((q,z)=>d[z]!==q),D=hb(y,v),O=mx(y,v),k=A||!D?{x:0,y:0}:{x:O?r.width-S.width:0,y:O?r.height-S.height:0},L={x:S.left,y:S.top};return k.x&&k.y?L:Bo(L,k)}}}};function hb(s,e){return!zc(s)||!zc(e)?!1:s.data.current.sortable.containerId===e.data.current.sortable.containerId}function mx(s,e){return!zc(s)||!zc(e)||!hb(s,e)?!1:s.data.current.sortable.index{const d=I.useId(),f=I.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),h=B_(Iy(Jf,{activationConstraint:{distance:5}}),Iy(Yf,{coordinateGetter:gx})),m=I.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=I.useCallback(S=>{const{active:_,over:x}=S,A=Date.now();if(!x||_.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:D,lastActiveId:O,inProgress:k}=f.current;if(O===_.id&&A-D<500&&!k)return;f.current={inProgress:!1,lastSortTime:A,lastActiveId:_.id};const L=s.findIndex(q=>String(q[e])===String(_.id)),B=s.findIndex(q=>String(q[e])===String(x.id));if(L!==-1&&B!==-1&&L!==B){const q=th(s,L,B);i?.(q,{oldIndex:L,newIndex:B})}},[s,e,i]),v=s.map(S=>String(S[e]));return yt.jsx(GA,{id:d,sensors:h,collisionDetection:G_,onDragStart:m,onDragEnd:y,children:yt.jsx(ix,{items:v,strategy:yx[n],children:r})},c!==void 0?`${d}-v${c}`:d)},pb=I.createContext(null),vx=({value:s,children:e})=>yt.jsx(pb.Provider,{value:s,children:e}),Sx=()=>I.useContext(pb),wx=({id:s,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:h}=fx({id:s}),m={transform:qo.Transform.toString(d),transition:f,opacity:h?.5:1,position:"relative"};return yt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(s),"data-dragging":h,children:yt.jsx(vx,{value:{listeners:l,handle:e,isDragging:h},children:r})})},lt=pt("DynamicRenderer");function oa(){try{return window.G7Core?.devTools}catch{return}}function rh(s,e,n,r){if(typeof s=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(s))try{return e.resolveTranslations(s,n,r)}catch{return s}return s}if(Array.isArray(s))return s.map(i=>rh(i,e,n,r));if(s&&typeof s=="object"){const i={};for(const[l,c]of Object.entries(s))i[l]=rh(c,e,n,r);return i}return s}function Cx(s){const e=Object.keys(s);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const ur=(s,e)=>{const n=["errors"],r={...s};for(const i of Object.keys(e)){const l=e[i],c=s[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&Cx(l)){const d=Object.keys(l).map(h=>parseInt(h,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)r[i]={...l};else{const h=[...c];for(const[m,y]of Object.entries(l)){const v=parseInt(m,10);v>=0&&v=h.length&&(h[v]=y)}r[i]=h}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?r[i]=ur(c,l):r[i]=l}return r},Ex=(s,e,n,r)=>{if(!e||typeof e!="object"||Array.isArray(e))return s;const i=ur(s,e);return Ry(i,n,r)},Pc=(s,e)=>{let n=null;const r=()=>(n===null&&(n={...s}),n);for(const i of Object.keys(e)){if(!(i in s))continue;const l=e[i],c=s[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Pc(c,l);if(d===c)continue;Object.keys(d).length===0?delete r()[i]:r()[i]=d}else delete r()[i]}return n??s},_x=s=>{const e={},n=s.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),c=r.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,h)=>h.toUpperCase());e[d]=c}}return e};class Ax extends I.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){lt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:yt.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:[yt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),yt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&yt.jsxs("details",{className:"mt-2",children:[yt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),yt.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 Vr=I.memo(({componentDef:s,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:h,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:v=!1,onComponentSelect:S,onComponentHover:_,onDragStart:x,onDragEnd:A,componentPath:D,layoutKey:O})=>{const[k,L]=I.useState({loadingActions:{}});I.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const B=I.useRef(null);I.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:ie,...ce}=e._localInit,Z=`${JSON.stringify(ce)}:${V||"no-force"}`;if(B.current!==Z){B.current=Z;const ve=ie||"shallow",Ee=window.G7Core?.state?.get?.()?._local||{},xe=window.__g7PendingLocalState||{},Ke={...Ee,...xe};ve==="replace"?window.__g7PendingLocalState={loadingActions:Ke.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=ur(Ke,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Ke,...ce,hasChanges:!1};const ke=window.__g7SetLocalOverrideKeys;ke&&typeof ke=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ur(ke,{...ce,hasChanges:!1}))}}}),I.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){L(ve=>Pc(ve,V));const ie=V,ce=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ie&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const q=I.useRef(O);I.useEffect(()=>{s._fromBase&&O&&q.current!==O&&(q.current=O,L({loadingActions:{}}))},[O,s._fromBase]);const z=I.useRef(""),W=I.useRef(!1),de=I.useRef(null),_e=I.useRef(null),Se=I.useRef({}),Ie=I.useRef({}),Fe=I.useRef(h),ze=T_(),Et=a_(),Q=Et?.getParentDataContext()??h;I.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...ie}=e._localInit,ce=JSON.stringify(ie),Z=V!==void 0,ve=Nf(),pe=`${ce}:${V||"no-force"}`,Ee=f_({globalTrackedKey:ve.hash,instanceHandledKey:_e.current,trackingKey:pe});if(Ee==="apply"){_e.current=pe,ve.hash=pe,ve.timestamp=V,z.current=ce,Z&&(W.current=!0);const{_merge:Ke,...ke}=ie,Me=Ke||"shallow";L(Re=>Me==="replace"?{loadingActions:Re.loadingActions||{},...ke,hasChanges:!1}:Me==="deep"?ur(Re,{...ke,hasChanges:!1}):{...Re,...ke,hasChanges:!1}),e._globalSetState&&e._globalSetState(Re=>{const tt=Re?._local||{};let Pe;return Me==="replace"?Pe={...ke,hasChanges:!1}:Me==="deep"?Pe=ur(tt,{...ke,hasChanges:!1}):Pe={...tt,...ke,hasChanges:!1},{...Re,_local:Pe}}),i.invalidateCacheByKeys(["_local"]),lt.log("_localInit applied (data changed):",Object.keys(ie))}else if(Ee==="prune"){_e.current=pe;const{_merge:Ke,...ke}=ie;L(Re=>Pc(Re,ke)),Pc(k,ke)!==k&&(i.invalidateCacheByKeys(["_local"]),lt.log("_localInit pruned (applied by another renderer):",Object.keys(ke)))}de.current=e._localInit,u_(e._localInit)}},[e._localInit,h,i]);const{isTransitioning:ue}=Ay(),De=v_(),ee=f??De,{width:me}=jf(),H=Sx(),T=I.useMemo(()=>{let V=s;if(s.type==="iterator"&&s.data){const{data:Z,itemName:ve,indexName:pe,...Ee}=s;V={...Ee,iteration:{source:Z,item_var:ve||"item",index_var:pe}}}if(!V.responsive)return V;const ie=Ci.getMatchingKey(V.responsive,me);if(!ie)return V;const ce=V.responsive[ie];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?ie:void 0}},[s,me]),fe=I.useCallback(V=>{const ie=V?.__setStateId;if(L(ce=>{const Z=window.__g7PendingLocalState,pe=window.__g7SetLocalOverrideKeys||Z,Ee=pe?ur(ce,pe):ce;if(typeof V=="function"){const Re=V(Ee);return ur(Ee,Re)}const{__mergeMode:xe,__setStateId:Ke,...ke}=V;let Me;if(xe==="replace"?Me=ke:xe==="shallow"?Me={...Ee,...ke}:Me=ur(Ee,ke),xe!==void 0){const Re=window.__g7ForcedLocalFields;Re&&(window.__g7ForcedLocalFields={...Re,...ke})}return Me}),ie){const ce=oa();if(ce?.isEnabled()){const Z=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(Z,ve,0,["_local"],[]),ce.completeStateChange?.(ie)},0)}}},[T.id,T.name]),he=d?.state??k,Ae=d?.setState??fe,se=I.useMemo(()=>{const V=e._localInit&&e._localInit!==de.current;let ie;V&&e._local?ie=e._local:ie=e._local?ur(e._local,he):he;const ce=window.__g7ForcedLocalFields;ce&&(ie=ur(ie,ce));const Z={...e,_local:ie},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const pe=new $n,Ee={...Z,...ze?{_isolated:ze.state}:{}},xe={},Ke=oa(),ke=Ke?.isEnabled()??!1;for(const[Me,Re]of Object.entries(ve)){const tt=ke?Date.now():0,Pe=ke?e._computed?.[Me]:void 0;let Ve;try{if(typeof Re=="string")if(Re.startsWith("{{")&&Re.endsWith("}}")){const Ce=Re.slice(2,-2).trim(),He=Wn(Ce)?pe.evaluatePipeExpression(Ce,Ee,{skipCache:!0}):pe.evaluateExpression(Ce,Ee,{skipCache:!0});xe[Me]=He}else xe[Me]=Re;else if(Re&&typeof Re=="object"&&"$switch"in Re){const Ce=pe.resolveSwitch(Re,Ee,{skipCache:!0});xe[Me]=Ce}}catch(Ce){lt.warn(`Failed to recalculate computed value: ${Me}`,Ce),xe[Me]=e._computed?.[Me],Ve=Ce instanceof Error?Ce.message:String(Ce)}if(ke&&(Ve||Pe!==xe[Me])){const He=Date.now()-tt;Ke.trackComputedProperty?.(Me,typeof Re=="string"?Re:JSON.stringify(Re),[{type:"_local",path:"_local",value:Z._local}],xe[Me],He,T.id,Ve),Pe!==xe[Me]&&Ke.trackComputedRecalc?.(Me,"dependency-change",Pe,xe[Me],He,{type:"_local",path:"_local"},T.id)}}Z._computed=xe}if(ze&&(Z._isolated=ze.state),Q&&(Z.$parent=Q),s.extensionPointProps){const pe=i.resolveObject(s.extensionPointProps,Z,y?{skipCache:!0}:void 0);Z.extensionPointProps=v&&l?rh(pe,l,n,Z):pe}return s.extensionPointCallbacks&&(Z.extensionPointCallbacks=s.extensionPointCallbacks),v&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,he,ze?.state,Q,Et?.version,s.extensionPointProps,s.extensionPointCallbacks]);Se.current=se._local,Ie.current=se._computed||{},Fe.current=Q,I.useEffect(()=>{const V=oa();if(!V?.isEnabled())return;const ie=se._local;ie&&V.updateLocalState(ie);const ce=se._computed;ce&&V.updateComputedState(ce),Q&&V.updateParentContext?.(Q);const Z=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",pe={global:Object.keys(e._global||{}),local:Object.keys(ie||{}),context:d?Object.keys(d.state||{}):[]},Ee={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(Z,ve,pe,Ee),he&&Object.keys(he).length>0&&V.trackDynamicState?.(Z,he);const xe=!!(T.expandChildren||T.props?.expandChildren);V.trackContextFlow?.(Z,ve,!!d,xe,!0)},[se._local,e,T.id,T.name,d,he,T.expandChildren,T.props?.expandChildren,Q]);const ge=I.useMemo(()=>({state:{...se._local},setState:Ae,stateRef:Se,computedRef:Ie,isolatedContext:ze,parentDataContext:se}),[se._local,Ae,k,ze,se]),$e=I.useMemo(()=>{const V=ds({if:T.if,condition:T.condition,conditions:T.conditions},se,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=oa();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,V)}return V},[T.if,T.conditions,se,i,T.id]),Te=I.useMemo(()=>{if(!T.slot)return null;const V=T.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const ie=V.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},Z=Wn(ie)?i.evaluatePipeExpression(ie,se,void 0,ce):i.evaluateExpression(ie,se,ce);return lt.log(`[Slot] 표현식 평가: "${ie}" => "${Z}" (컴포넌트: ${T.id})`),typeof Z=="string"?Z:null}catch(ce){return lt.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return lt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${T.id})`),V},[T.slot,T.id,se,i]),je=I.useMemo(()=>!Te||!T.id?"":`${T.id}-${Te}-${JSON.stringify(T.slotOrder??0)}`,[Te,T.id,T.slotOrder]),xt=I.useRef(null);I.useEffect(()=>{const V=window.__slotContextValue,ie=V?.isEnabled??!1;if(T.slot&<.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${ie}, shouldRender: ${$e}, resolvedSlotId: ${Te}`),!ie||!$e){T.slot&<.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ie}, shouldRender: ${$e}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}if(!Te||!T.id){T.slot&<.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${T.id}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}xt.current&&xt.current!==Te&&V.unregisterFromSlot(xt.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>ge,translationContext:n,registrationKey:je}),xt.current=Te,()=>{const Z=window.__slotContextValue;Te&&T.id&&Z&&Z.unregisterFromSlot(Te,T.id)}},[$e,Te,T,e,f,ge,n,je]);const rt=I.useCallback(V=>{if(typeof V=="string"){if(ic(V))return Yd(V);if(sc(V)){const ie=[],ce=V.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(ve,pe)=>(ie.push(pe),`${$a}${ie.length-1}${$a}`));let Z=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(Z=l.resolveTranslations(ce,n,se)),Z.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(ve,pe)=>ie[parseInt(pe)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const ie=V.trim();return ie.startsWith("{")&&ie.endsWith("}")||ie.startsWith("[")&&ie.endsWith("]")?V:l.resolveTranslations(V,n,se)}return V}if(Array.isArray(V))return V.map(ie=>rt(ie));if(V&&typeof V=="object"){const ie={};for(const[ce,Z]of Object.entries(V))ie[ce]=rt(Z);return ie}return V},[l,n,se]),gt=I.useCallback(V=>yo(V),[]),at=I.useCallback(V=>La(V),[]),Yt=I.useMemo(()=>{let V={...T.props||{}};const ie=["cellChildren","expandChildren","expandContext","render"],Z=r.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...ie,...Z])],pe=y?{skipCache:!0}:void 0,Ee={...pe??{},skipBindingKeys:ve},xe=Ce=>{if(pe)return pe;if(Ce.startsWith("_computed")||Ce.startsWith("$computed"))return{skipCache:!0}};for(const[Ce,He]of Object.entries(V))if(!ve.includes(Ce))if(typeof He=="string"){const nt=at(He);if(nt!==null){let Lt=!1,Bt=nt;nt.startsWith(sr)&&(Lt=!0,Bt=nt.slice(sr.length));const Nn={componentId:T.id,componentName:T.name,propName:Ce};let Gt;if(Wn(Bt))try{Gt=i.evaluatePipeExpression(Bt,se,xe(Bt),Nn)}catch(Ft){lt.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else if(gt(Bt))try{Gt=i.evaluateExpression(Bt,se,Nn)}catch(Ft){lt.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else Gt=i.resolve(Bt,se,xe(Bt),Nn);V[Ce]=Lt&&Gt!=null?us(Gt):Gt}else{const Lt={componentId:T.id,componentName:T.name,propName:Ce};V[Ce]=i.resolveBindings(He,se,pe,Lt)}}else Array.isArray(He)?V[Ce]=He.map(nt=>typeof nt=="string"?i.resolveBindings(nt,se,pe):typeof nt=="object"&&nt!==null?i.resolveObject(nt,se,Ee):nt):He&&typeof He=="object"&&(V[Ce]=i.resolveObject(He,se,Ee));for(const[Ce,He]of Object.entries(V))V[Ce]=rt(He);if(typeof V.style=="string"&&(V.style=_x(V.style)),V=cf(V,v?void 0:T.actions,se,{componentContext:ge,actionDispatcher:c}),T.classMap){const Ce=V0(T.classMap,se,i,{skipCache:!0});if(Ce){const He=V.className||"";V.className=He?`${He} ${Ce}`:Ce}}T.style&&(V.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(V,he),T.component_layout&&(V.__componentLayoutDefs=T.component_layout);const Ke=T.expandChildren||T.props?.expandChildren,ke=T.props?.cellChildren,Me=T.children&&T.children.length>0,Re=T.component_layout,tt=T.slot,Pe=T.props?.modalId,Ve=T.type==="composite";return(Ke||ke||Me||Re||tt||Pe||Ve)&&(V.__componentContext=ge),V},[T.props,T.actions,T.style,T.classMap,T.id,se,n,i,l,ge,he,rt,gt,at,y]),Ht=I.useRef(null),bt=I.useMemo(()=>Ht.current&&Ty(Ht.current,Yt)?Ht.current:(Ht.current=Yt,Yt),[Yt]),qe=I.useMemo(()=>{const V=T.id;if(typeof V!="string"||!V.includes("{{"))return V;const ie=i.resolveBindings(V,se,{skipCache:!0});return typeof ie=="string"?ie:V},[T.id,se,i]),mt=I.useMemo(()=>{const V=T.dataKey,ie=T.trackChanges,ce=T.debounce;if(V){const Z=V.startsWith("_global."),ve=Z?V.slice(8):V,pe=Z?e._global:se._local;return{dataKey:ve,trackChanges:ie??!1,debounce:ce,setState:Z?xe=>{e._globalSetState?e._globalSetState(xe):lt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:Ae,state:pe??{},_isGlobal:Z}}if(ee.dataKey)return ee},[T.dataKey,T.trackChanges,T.debounce,T.id,Ae,se._local,e._global,e._globalSetState,ee]),Dt=I.useRef(new Set);I.useEffect(()=>{Dt.current.clear()},[e._global?._remountKeys]);const zt=I.useCallback((V,ie)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!Dt.current.has(V)?(Dt.current.add(V),`${V}-remount-${ce[V]}`):V||ie},[e._global?._remountKeys]),kn=I.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const V=T.text;let ie=V;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},Z=at(V);if(Z!==null){let ve=!1,pe=Z;if(Z.startsWith(sr)&&(ve=!0,pe=Z.slice(sr.length)),Wn(pe))try{ie=i.evaluatePipeExpression(pe,se,{skipCache:!0},ce)}catch(Ee){lt.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else if(gt(pe))try{ie=i.evaluateExpression(pe,se,ce)}catch(Ee){lt.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else ie=i.resolve(pe,se,{skipCache:!0},ce);ve&&ie!=null&&(ie=us(ie))}else V.includes("{{")&&(ie=i.resolveBindings(V,se,{skipCache:!0},ce));return ie=rt(ie),ie??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((V,ie)=>{if(typeof V=="string")return V;const ce=T.__responsiveChildrenKey,Z=ce?`responsive.${ce}.children`:"children",ve=D?`${D}.${Z}.${ie}`:`${ie}`,pe=V._fromBase?V.id||`child-${ie}`:zt(V.id,`child-${ie}`),Ee=!V._fromBase&&O?`${pe}_${O}`:pe;return yt.jsx(Vr,{componentDef:V,dataContext:se,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:y,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:ve,onDragStart:x,onDragEnd:A,layoutKey:O},Ee)})},[T.text,T.children,T.id,e,se,n,r,i,l,c,ge,mt,at,gt,rt,zt,y,v,S,_,D,x,A,O]),dr=I.useMemo(()=>{if(!T.iteration)return null;try{const V=lf(T.iteration.source,se,i);if(!Array.isArray(V))return lt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,V),null;const ie=oa();return ie?.isEnabled()&&ie.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,V.length),V.map((ce,Z)=>{const ve={...se,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:Z};T.iteration.index_var&&(ve[T.iteration.index_var]=Z);const pe=Z===0||Z===V.length-1;ie?.isEnabled()&&pe&&ie.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(se),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ce,...T.iteration.index_var?{[T.iteration.index_var]:Z}:{}}},depth:1});const Ee={...T,iteration:void 0,responsive:void 0},xe=D?`${D}.iteration.${Z}`:`iteration.${Z}`,Ke=`${zt(T.id,"item")}-${Z}`;return yt.jsx(Vr,{componentDef:Ee,dataContext:ve,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:xe,onDragStart:x,onDragEnd:A,layoutKey:O},Ke)})}catch(V){return lt.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,V),null}},[T.iteration,T.children,T.id,e,se,n,r,i,l,c,ge,mt,zt,v,S,_,D,x,A,O]),[Ot,Li]=I.useState(0),ua=I.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:V,itemTemplate:ie}=T;try{const ce=lf(V.source,se,i);if(!Array.isArray(ce))return lt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const Z=V.itemKey||"id",ve=V.strategy||"verticalList",pe=V.itemVar||"$item",Ee=V.indexVar||"$index",xe=V.handle,Ke=V.wrapperElement,ke=(tt,Pe)=>{const Ve=T.actions?.filter(Ce=>Ce.event==="onSortEnd"||Ce.type==="onSortEnd");if(Li(Ce=>Ce+1),Ve&&Ve.length>0&&c){const Ce={...se,$sortedItems:tt,$sortEvent:Pe};Ve.forEach(He=>{try{const nt=c.createHandler(He,Ce,ge),Lt=new Event("sortend");nt(Lt)}catch(nt){lt.error(`onSortEnd action failed: ${He.handler}`,nt)}})}},Me=tt=>{const Pe=T.actions?.filter(Ve=>Ve.event==="onSortStart"||Ve.type==="onSortStart");if(Pe&&Pe.length>0&&c){const Ve={...se,$activeId:tt.activeId};Pe.forEach(Ce=>{try{const He=c.createHandler(Ce,Ve,ge),nt=new Event("sortstart");He(nt)}catch(He){lt.error(`onSortStart action failed: ${Ce.handler}`,He)}})}},Re=ce.map((tt,Pe)=>{const Ve=String(tt[Z]),Ce={...se,[pe]:tt,[Ee]:Pe},He=D?`${D}.sortable.${Pe}`:`sortable.${Pe}`,nt=`${zt(T.id,"sortable-item")}-v${Ot}-${Ve}`;return yt.jsx(wx,{id:Ve,handle:xe,...Ke?{as:Ke}:{},children:(Ke&&ie.children?ie.children:[ie]).map((Lt,Bt)=>yt.jsx(Vr,{componentDef:Lt,dataContext:Ce,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:He,onDragStart:x,onDragEnd:A,layoutKey:O},`${nt}-child-${Bt}`))},nt)});return yt.jsx(bx,{items:ce,itemKey:Z,strategy:ve,onSortEnd:ke,onSortStart:Me,sortVersion:Ot,children:Re})}catch(ce){return lt.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,se,n,r,i,l,c,ge,zt,v,S,_,D,x,A,Ot,O]),bn=I.useRef(!1);I.useEffect(()=>{if(bn.current)return;bn.current=!0;const V=oa();if(V?.isEnabled()&&V.trackMount(s.id,{name:s.name,type:s.type||"component",props:bt}),s.lifecycle?.onMount&&s.lifecycle.onMount.length>0)for(const ce of s.lifecycle.onMount)try{const Z=c.createHandler(ce,se,ge),ve=new Event("mount");Z(ve),lt.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${s.id})`)}catch(Z){lt.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${s.id})`,Z)}const ie=[];if(s.onComponentEvent&&s.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const Z of s.onComponentEvent){if(!Z.event){lt.warn(`onComponentEvent: event name is required (Component: ${s.id})`);continue}const ve=async Ee=>{try{const xe={...se,_eventData:Ee},ke=await c.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},xe,ge)(new CustomEvent(Z.event,{detail:Ee}));return lt.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${s.id})`,{eventData:Ee,result:ke}),ke}catch(xe){throw lt.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${s.id})`,xe),xe}},pe=ce.componentEvent.on(Z.event,ve);ie.push(pe),lt.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${s.id})`)}else lt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${s.id})`)}return()=>{const ce=oa();ce?.isEnabled()&&ce.trackUnmount(s.id);for(const Z of ie)try{Z()}catch(ve){lt.error(`onComponentEvent: Failed to unsubscribe (Component: ${s.id})`,ve)}if(ie.length>0&<.log(`onComponentEvent: Unsubscribed ${ie.length} event(s) (Component: ${s.id})`),s.lifecycle?.onUnmount&&s.lifecycle.onUnmount.length>0)for(const Z of s.lifecycle.onUnmount)try{const ve=c.createHandler(Z,se,ge),pe=new Event("unmount");ve(pe),lt.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${s.id})`)}catch(ve){lt.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${s.id})`,ve)}}},[]);const Mn=I.useMemo(()=>{const V=bt.dataKey,ie=bt.trackChanges,ce=bt.debounce;return V?{dataKey:V,trackChanges:ie??!1,debounce:ce,setState:Ae,state:he}:null},[bt.dataKey,bt.trackChanges,bt.debounce,Ae,he]);I.useEffect(()=>{const V=T.dataKey||bt.dataKey;if(!V)return;const ie=oa();if(!ie?.isEnabled())return;const ce=[],Z=pe=>{if(pe)for(const Ee of pe){const xe=Ee?.props?.name;if(xe&&ce.push({name:xe,type:Ee.name||Ee.type||"unknown"}),Ee?.children&&Z(Ee.children),Ee?.slots)for(const Ke of Object.values(Ee.slots))Array.isArray(Ke)&&Z(Ke)}};if(s.children&&Z(s.children),s.slots)for(const pe of Object.values(s.slots))Array.isArray(pe)&&Z(pe);const ve=s.id||`form-${V}`;return ie.trackForm(ve,V,ce),()=>{ie.untrackForm(ve)}},[T,bt.dataKey,s.id,s.children]);const it=I.useRef(null),Pn=I.useRef(void 0);I.useEffect(()=>{const V=bt?.name;if(!V||!ee.dataKey||!ee.setState||bt?.autoBinding===!1)return;const ie=`${ee.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(ie,(ce.get(ie)??0)+1),()=>{const Z=ce.get(ie)??0;Z<=1?ce.delete(ie):ce.set(ie,Z-1)}},[bt?.name,bt?.autoBinding,ee.dataKey,ee.setState]);const vn=I.useMemo(()=>{const{dataKey:V,trackChanges:ie,debounce:ce,...Z}=bt,ve=Z.name;if(!ve||!ee.dataKey||!ee.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ve,...Ce}=Z;return Ce}const pe=`${ee.dataKey}.${ve}`,Ee=S_(ee.state,pe),xe=Ee!==void 0?Ee:Z.value,ke=r.getMetadata(s.name)?.bindingType,Me=typeof xe=="boolean"&&(ke==="checked"||ke==="checkable"&&["checkbox","radio"].includes(Z?.type)),Re=ee.debounce,tt=Ve=>{const Ce=ee.state||{},He=Ry(Ce,pe,Ve);if(ee.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=Ex(He,window.__g7ForcedLocalFields,pe,Ve),ee.setState(He),ee._isGlobal)return;const nt=window.G7Core,Lt={[pe]:Ve};ee.trackChanges&&(Lt.hasChanges=!0),nt?.state?.setLocal?.(Lt,{render:!1})},Pe=(Ve,Ce)=>{Re&&Re>0?(it.current&&clearTimeout(it.current),it.current=setTimeout(()=>{tt(Ve),it.current=null,Ce&&(Ce(),window.__g7PendingLocalState=null)},Re)):(tt(Ve),Ce&&(Ce(),window.__g7PendingLocalState=null))};if(Me)return{...Z,checked:xe,onChange:Ce=>{const He=Ce.target.checked;tt(He),Z.onChange&&Z.onChange(Ce)}};{const Ve=He=>{const nt=He?.target?.value!==void 0?He.target.value:He;Re&&Re>0&&(Pn.current=nt);const Lt=He?.target?{target:{value:nt,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:nt,name:He.currentTarget.name}:void 0}:He;Pe(nt,()=>{Z.onChange&&Z.onChange(Lt)})};let Ce;return Pn.current!==void 0?it.current!==null?Ce=Pn.current:String(xe??"")===String(Pn.current)?(Pn.current=void 0,Ce=xe??""):Ce=Pn.current:Ce=xe??"",{...Z,value:Ce,onChange:Ve}}},[bt,ee,ee.state,ee.debounce]),da=I.useMemo(()=>{const V=oa();if(V?.isEnabled()&&V.trackRender(s.name),!$e)return T.iteration?dr:null;if(T.sortable&&T.itemTemplate)return ua;if(T.iteration)return dr;if(T.type==="extension_point"){const{layout:ke,columns:Me,gap:Re,className:tt,...Pe}=T.props||{};let Ve=tt||"";return ke==="grid"&&Me?Ve=`${Ve} grid grid-cols-${Me} gap-${Re||4}`.trim():ke==="flex"&&(Ve=`${Ve} flex flex-col gap-${Re||4}`.trim()),yt.jsx("div",{id:qe,className:Ve||void 0,...Pe,children:kn})}const ie=r.getComponent(T.name);if(!ie)return lt.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,Z={...vn,id:vn.id??qe,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(H?.listeners&&H.handle&&vn["data-drag-handle"]!==void 0&&(Object.assign(Z,H.listeners),Z.style={...Z.style,cursor:H.isDragging?"grabbing":"grab"}),v){const ke=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,Me=Pe=>{typeof Pe.preventDefault=="function"&&Pe.preventDefault(),S&&(Pe.stopPropagation(),S(ke,Pe))},Re={"data-editor-id":ke,"data-editor-name":T.name,"data-editor-type":T.type,onClick:Me};D&&(Re["data-editor-path"]=D);const tt=T.__editorSlotName??T.slot;typeof tt=="string"&&(Re["data-editor-slot"]=tt),_&&(Re.onMouseMove=Pe=>{Pe.stopPropagation(),_(ke,Pe)},Re.onMouseLeave=Pe=>{_(null,Pe)}),Object.assign(Z,Re),Z.editorAttrs=Re}const ve=T.type==="basic",pe=T.type==="layout",xe=ve||pe?(()=>{const ke={};for(const[Me,Re]of Object.entries(Z))Me.startsWith("__")||Me==="editorAttrs"&&ve||(ke[Me]=Re);return ke})():Z;let Ke=yt.jsx(ie,{...xe,children:kn});if(mt&&(Ke=yt.jsx(b_,{value:mt,children:Ke})),T.isolatedState){const ke=typeof T.isolatedState=="object"?T.isolatedState:{},Me=e?._isolatedInit,Re=Me?{...ke,...Me}:ke;Ke=yt.jsx(x_,{initialState:Re,scopeId:T.isolatedScopeId,children:Ke})}return Ke},[$e,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,r,vn,kn,dr,ua,H,Mn,v,S,_,x,A,D,e._global?._remountKeys]),fr=I.useMemo(()=>{const V=T.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const Z=at(V);if(Z!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,se,ve)}catch(ve){return lt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${T.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(Ee=>e[Ee]===void 0);if(ue)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(pe=>!Z.includes(pe)&&!pe.startsWith("_")).some(pe=>e[pe]===void 0)}if(ue)return!0;const ie=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!ie.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[T.blur_until_loaded,T.id,ue,e,se,i,at]);if(fr){const V=T.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,pe)=>(ve[pe]=e[pe]===void 0?"UNDEFINED":"LOADED",ve),{}),Z=Object.keys(e).filter(ve=>!ve.startsWith("_"));lt.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",Z)}else lt.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,V)}const un=I.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=Yt?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const ie=[/^(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 pe of ce)ie.some(xe=>xe.test(pe))?Z.push(pe):ve.push(pe);return{wrapperClasses:Z.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Yt?.className]),Rn=window.__slotContextValue;return Te&&Rn?.isEnabled?null:yt.jsx(Ax,{componentId:s.id,componentName:s.name,children:T.blur_until_loaded?yt.jsx("div",{className:[un.wrapperClasses,fr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:da}):da})});Vr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Vr);function xx(s){const e={};try{const r=new URL(s,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const c=r.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function Tx(s){try{return new URL(s,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return s.split("?")[0]}}const Oi=class Oi{constructor(){M(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});M(this,"stateHistory",[]);M(this,"snapshotIdCounter",0);M(this,"stateWatchers",new Map);M(this,"currentLocalState",{});M(this,"currentComputedState",{});M(this,"currentParentContext");M(this,"actionHistory",[]);M(this,"actionWatchers",new Set);M(this,"cacheStats",{hits:0,misses:0,entries:0});M(this,"cacheDecisions",[]);M(this,"cacheDecisionIdCounter",0);M(this,"maxCacheDecisions",200);M(this,"currentRenderCycleId",null);M(this,"isInActionExecution",!1);M(this,"isInIteration",!1);M(this,"mountedComponents",new Map);M(this,"eventListeners",new Map);M(this,"mountWatchers",new Set);M(this,"unmountWatchers",new Set);M(this,"renderCounts",new Map);M(this,"bindingEvalCount",0);M(this,"profilingData",[]);M(this,"isProfiling",!1);M(this,"profilingStartTime",0);M(this,"activeRequests",new Map);M(this,"requestHistory",[]);M(this,"pendingDataSources",new Set);M(this,"requestWatchers",new Set);M(this,"wsConnections",new Map);M(this,"wsMessageHistory",[]);M(this,"wsMessageWatchers",new Set);M(this,"ifConditions",new Map);M(this,"iterations",new Map);M(this,"conditionWatchers",new Set);M(this,"forms",new Map);M(this,"formWatchers",new Set);M(this,"expressionHistory",[]);M(this,"expressionWatchers",new Set);M(this,"expressionIdCounter",0);M(this,"dataSources",new Map);M(this,"dataPathTransforms",[]);M(this,"maxDataPathTransforms",100);M(this,"nestedContexts",[]);M(this,"nestedContextIdCounter",0);M(this,"maxNestedContexts",100);M(this,"formBindingIssues",[]);M(this,"formBindingValidations",[]);M(this,"formBindingIssueIdCounter",0);M(this,"maxFormBindingIssues",100);M(this,"computedProperties",new Map);M(this,"computedRecalcLogs",[]);M(this,"computedRecalcIdCounter",0);M(this,"maxComputedRecalcLogs",100);M(this,"handlers",new Map);M(this,"componentEventSubscriptions",new Map);M(this,"componentEventEmitHistory",[]);M(this,"componentEventIdCounter",0);M(this,"maxComponentEventHistory",100);M(this,"stateRenderingLogs",[]);M(this,"currentStateChangeContext",null);M(this,"stateRenderingIdCounter",0);M(this,"componentRenderCounts",new Map);M(this,"stateToComponentMap",new Map);M(this,"maxStateRenderingLogs",100);M(this,"componentStateSources",new Map);M(this,"contextFlowNodes",new Map);M(this,"dynamicStates",new Map);M(this,"styleIssues",[]);M(this,"componentStyles",new Map);M(this,"authEvents",[]);M(this,"authHeaderHistory",[]);M(this,"authEventIdCounter",0);M(this,"maxAuthEventHistory",50);M(this,"logHistory",[]);M(this,"logIdCounter",0);M(this,"maxLogHistory",500);M(this,"currentLayout",null);M(this,"layoutHistory",[]);M(this,"layoutIdCounter",0);M(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});M(this,"maxLayoutHistory",50);M(this,"executionDetails",new Map);M(this,"stateChangeHistory",[]);M(this,"dataSourceChangeHistory",[]);M(this,"changeAlerts",[]);M(this,"changeExpectations",new Map);M(this,"executionIdCounter",0);M(this,"stateChangeIdCounter",0);M(this,"alertIdCounter",0);M(this,"maxExecutionDetails",100);M(this,"maxStateChangeHistory",200);M(this,"maxChangeAlerts",100);M(this,"sequenceExecutions",[]);M(this,"sequenceExecutionStack",[]);M(this,"sequenceIdCounter",0);M(this,"maxSequenceExecutions",50);M(this,"staleClosureWarnings",[]);M(this,"staleClosureIdCounter",0);M(this,"maxStaleClosureWarnings",100);M(this,"stateCaptureRegistry",new Map);M(this,"modalStates",new Map);M(this,"modalStateIssues",[]);M(this,"modalStateRelations",[]);M(this,"modalStateChangeLogs",[]);M(this,"modalStateIssueIdCounter",0);M(this,"modalStateChangeLogIdCounter",0);M(this,"maxModalStateIssues",100);M(this,"maxModalStateChangeLogs",200);M(this,"namedActionDefinitions",{});M(this,"namedActionRefLogs",[]);M(this,"namedActionRefIdCounter",0);M(this,"maxNamedActionRefLogs",200);M(this,"debounceActionHistory",[]);M(this,"dataSourceUpdateHistory",[]);M(this,"debounceActionIdCounter",0);M(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return Oi.instance||(Oi.instance=new Oi),Oi.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 r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._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?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r: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 r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=r?`${r}.${c}`:c,f=e?.[c],h=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=h&&typeof h=="object"&&!Array.isArray(h);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,h,d));else{const v=f===void 0?"__undefined__":JSON.stringify(f),S=h===void 0?"__undefined__":JSON.stringify(h);v!==S&&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(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=r?`${r}.${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=r?`${r}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.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(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[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:r}}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,r=0,i=0,l=0;const c={},d={};for(const h of e)h.decision==="cache_hit"?n++:h.decision==="cache_miss"?r++:h.decision==="skip_cache"?i++:h.decision==="invalidate"&&l++,c[h.reason]=(c[h.reason]||0)+1,h.context.componentId&&(d[h.context.componentId]=(d[h.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.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 r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,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),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.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 r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.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(h=>h.type==="render"),r=this.profilingData.filter(h=>h.type==="binding"),i=this.profilingData.filter(h=>h.type==="action"),l={};for(const h of n)h.component&&(l[h.component]||(l[h.component]={count:0,durations:[]}),l[h.component].count++,h.duration&&l[h.component].durations.push(h.duration));const c=Object.entries(l).map(([h,m])=>({name:h,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,v)=>y+v,0)/m.durations.length:0})).sort((h,m)=>m.renderCount-h.renderCount).slice(0,10),d={};for(const h of r)h.expression&&(d[h.expression]=(d[h.expression]||0)+1);const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,10).map(([h])=>h);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=Tx(e),c=xx(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){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(r)};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 r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.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(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,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(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,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=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._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(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,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(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const h=[];let m=!0;return f.name||(h.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||(h.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:h}});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 r=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:r}}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,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,h={id:f,name:e,expression:n,componentId:c,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,h)}trackComputedRecalc(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,h=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:h,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 r=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),r.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};r.add(m),i.push(m);const v=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(v)for(const _ of v.dependencies)_.type==="computed"?S.push(f(_.path,y+1)):S.push({name:_.path,type:_.type,children:[],depth:y+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:y}},h=f(e,0);return{root:e,tree:h,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const h of this.computedRecalcLogs)e[h.trigger]++,h.valueChanged||l++,n[h.computedName]=(n[h.computedName]||0)+1,r[h.computedName]||(r[h.computedName]=[]),r[h.computedName].push(h.computationTime),i+=h.computationTime;const c=Object.entries(n).sort((h,m)=>m[1]-h[1]).slice(0,5).map(([h,m])=>({name:h,count:m})),d=Object.entries(r).map(([h,m])=>({name:h,avgTime:m.reduce((y,v)=>y+v,0)/m.length})).sort((h,m)=>m.avgTime-h.avgTime).slice(0,5);let f=0;for(const h of this.computedProperties.values())this.analyzeComputedDependencyChain(h.name,h.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 r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.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 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.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 r=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:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&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 r=e.initialState[n],i=e.currentState[n];if(r!==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:r})}}}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},r={"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]++,r[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:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["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 r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);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:r,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(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).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(h=>h.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(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=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 r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,h)=>f+h,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(r){console.error("[G7DevTools] Expression watcher error:",r)}})}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 r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){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(r=>r.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,r){if(!this.config.enabled)return;const i=r.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(r),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(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)r[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:r,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,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=r;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 r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,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(r=>r.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 r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.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 r=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,r+=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:r,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}`,r=[...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:r,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 r=this.nestedContexts.find(i=>i.id===e);r&&r.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 r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=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:r,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,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),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}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,r,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,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,r)=>n+r.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,r,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(r),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,r,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:r,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),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,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),r=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:r,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(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,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(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=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(r>=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,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,r+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._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(r._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[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)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 h=r.values[d];if(JSON.stringify(h)!==JSON.stringify(f)){const m=[],y=[];for(const v of this.componentStateSources.values())v.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(v.stateProvider.type==="dynamicState"?m.push(v.componentName):v.stateProvider.type==="globalState"&&y.push(v.componentName));n.push({path:`_local.${d}`,globalValue:h,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 r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);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,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),c={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],r=[],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 h of c)if(f.startsWith(h)){r.push(f);break}for(const h of d)if(h.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,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:r,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:r,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:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.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,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:r,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 r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=r?.getUser?.();if(d&&(c="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(c="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let h="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?h="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(h="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 v=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.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:v,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:h,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,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.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()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),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,r,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=r,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||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,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,r,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:r,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,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of r.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 r.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 r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let c=!1,d;return!l&&(r==="object"||r==="array")?(c=this.deepEqual(e,n),!c&&r==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:r,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 r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.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 r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.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()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:r,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,r,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(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._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 h=window.__g7PendingLocalState;h&&(f.pendingState=this.safeClone(h)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];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(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||r.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const h=e[f],m=n[f];JSON.stringify(h)!==JSON.stringify(m)&&l.push({path:f,oldValue:h,newValue:m})}return{added:r,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,r=e.filter(h=>h.status==="success").length,i=e.filter(h=>h.status==="error").length,l=e.reduce((h,m)=>h+m.actions.length,0),c=n>0?e.reduce((h,m)=>h+m.totalDuration,0)/n:0,d={};for(const h of e)for(const m of h.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,5).map(([h,m])=>({handler:h,count:m}));return{totalExecutions:n,successCount:r,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(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(r[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[h,m]of c){const y=this.getValueByPath(r,h),v=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&v>0){const S=this.createStaleClosureWarning(i,n,h,m.value,m.capturedAt,y,d,v,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,c,d,f,h,m){const y=this.getStaleClosureSeverity(e,f),{description:v,suggestion:S,docLink:_}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:v,suggestion:S,docLink:_,actionId:h,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,r){const i=r<1e3?`${r}ms`:`${(r/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 r=n.split(".");let i=e;for(const l of r){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 r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({location:f,count:h})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({path:f,count:h}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.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(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};M(Oi,"instance");let za=Oi;const Xn=pt("LayoutLoader");class Rr extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="LayoutLoaderError"}}class ah{constructor(e){M(this,"componentRegistry");M(this,"currentLayout",null);M(this,"layoutCache",new Map);M(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Xn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Xn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,za.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const v=n.replace("__preview__/","");l=Ur(`/api/layouts/preview/${v}`,"json",i)}else l=Ur(`/api/layouts/${e}/${n}`,"json",i);Xn.log("Fetching layout from API:",l);const c=qr(),d=r?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const h=await nc(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await h.json()}catch{m=null}if(!h.ok){if(h.status===401&&!r&&d){Xn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof Rr&&S.details?.status===401?new Rr(S.message,S.code,{...S.details,hadToken:!0}):S}}const v=m?.message||m?.error;throw new Rr(`Failed to fetch layout: ${h.status} ${h.statusText}`,"FETCH_FAILED",{status:h.status,statusText:h.statusText,url:l,apiMessage:v})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,za.getInstance().trackLayoutLoad(n,e,y,"api"),Xn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Rr?i:new Rr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Rr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Rr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Rr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Xn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new Rr("No layout data to render","NO_LAYOUT_DATA");Xn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Xn.log("Layout rendered successfully")}catch(r){Xn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Xn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Xn.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=` + `},U_={onDragStart(s){let{active:e}=s;return"Picked up draggable item "+e.id+"."},onDragOver(s){let{active:e,over:n}=s;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(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(s){let{active:e}=s;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function B_(s){let{announcements:e=U_,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=P_}=s;const{announce:l,announcement:c}=j_(),d=Uo("DndLiveRegion"),[f,h]=I.useState(!1);if(I.useEffect(()=>{h(!0)},[]),H_(I.useMemo(()=>({onDragStart(y){let{active:v}=y;l(e.onDragStart({active:v}))},onDragMove(y){let{active:v,over:S}=y;e.onDragMove&&l(e.onDragMove({active:v,over:S}))},onDragOver(y){let{active:v,over:S}=y;l(e.onDragOver({active:v,over:S}))},onDragEnd(y){let{active:v,over:S}=y;l(e.onDragEnd({active:v,over:S}))},onDragCancel(y){let{active:v,over:S}=y;l(e.onDragCancel({active:v,over:S}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(N_,{id:r,value:i.draggable}),Xe.createElement(I_,{id:d,announcement:c}));return n?ja.createPortal(m,n):m}var ln;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(ln||(ln={}));function Dc(){}function Iy(s,e){return I.useMemo(()=>({sensor:s,options:e??{}}),[s,e])}function q_(){for(var s=arguments.length,e=new Array(s),n=0;n[...e].filter(r=>r!=null),[...e])}const kr=Object.freeze({x:0,y:0});function jy(s,e){return Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2))}function Hy(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return n-r}function G_(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return r-n}function zy(s){let{left:e,top:n,height:r,width:i}=s;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Py(s,e){if(!s||s.length===0)return null;const[n]=s;return n[e]}function Uy(s,e,n){return e===void 0&&(e=s.left),n===void 0&&(n=s.top),{x:e+s.width*.5,y:n+s.height*.5}}const F_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=Uy(e,e.left,e.top),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=jy(Uy(f),i);l.push({id:d,data:{droppableContainer:c,value:h}})}}return l.sort(Hy)},V_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=zy(e),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=zy(f),m=i.reduce((v,S,_)=>v+jy(h[_],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(Hy)};function K_(s,e){const n=Math.max(e.top,s.top),r=Math.max(e.left,s.left),i=Math.min(e.left+e.width,s.left+s.width),l=Math.min(e.top+e.height,s.top+s.height),c=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=[];for(const l of r){const{id:c}=l,d=n.get(c);if(d){const f=K_(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(G_)};function Y_(s,e,n){return{...s,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function By(s,e){return s&&e?{x:s.left-e.left,y:s.top-e.top}:kr}function X_(s){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...c,top:c.top+s*d.y,bottom:c.bottom+s*d.y,left:c.left+s*d.x,right:c.right+s*d.x}),{...n})}}const J_=X_(1);function Q_(s){if(s.startsWith("matrix3d(")){const e=s.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(s.startsWith("matrix(")){const e=s.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Z_(s,e,n){const r=Q_(e);if(!r)return s;const{scaleX:i,scaleY:l,x:c,y:d}=r,f=s.left-c-(1-i)*parseFloat(n),h=s.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?s.width/i:s.width,y=l?s.height/l:s.height;return{width:m,height:y,top:h,right:f+m,bottom:h+y,left:f}}const eA={ignoreTransform:!1};function Es(s,e){e===void 0&&(e=eA);let n=s.getBoundingClientRect();if(e.ignoreTransform){const{transform:h,transformOrigin:m}=Hn(s).getComputedStyle(s);h&&(n=Z_(n,h,m))}const{top:r,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:c,bottom:d,right:f}}function qy(s){return Es(s,{ignoreTransform:!0})}function tA(s){const e=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function nA(s,e){return e===void 0&&(e=Hn(s).getComputedStyle(s)),e.position==="fixed"}function rA(s,e){e===void 0&&(e=Hn(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function Oc(s,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(zf(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Ho(i)||Ly(i)||n.includes(i))return n;const l=Hn(s).getComputedStyle(i);return i!==s&&rA(i,l)&&n.push(i),nA(i,l)?n:r(i.parentNode)}return s?r(s):n}function Gy(s){const[e]=Oc(s,1);return e??null}function Ff(s){return!kc||!s?null:Ss(s)?s:Hf(s)?zf(s)||s===ws(s).scrollingElement?window:Ho(s)?s:null:null}function Fy(s){return Ss(s)?s.scrollX:s.scrollLeft}function Vy(s){return Ss(s)?s.scrollY:s.scrollTop}function Vf(s){return{x:Fy(s),y:Vy(s)}}var mn;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(mn||(mn={}));function Ky(s){return!kc||!s?!1:s===document.scrollingElement}function Wy(s){const e={x:0,y:0},n=Ky(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},i=s.scrollTop<=e.y,l=s.scrollLeft<=e.x,c=s.scrollTop>=r.y,d=s.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:r,minScroll:e}}const aA={x:.2,y:.2};function iA(s,e,n,r,i){let{top:l,left:c,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=aA);const{isTop:h,isBottom:m,isLeft:y,isRight:v}=Wy(s),S={x:0,y:0},_={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!h&&l<=e.top+x.height?(S.y=mn.Backward,_.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=mn.Forward,_.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!v&&d>=e.right-x.width?(S.x=mn.Forward,_.x=r*Math.abs((e.right-x.width-d)/x.width)):!y&&c<=e.left+x.width&&(S.x=mn.Backward,_.x=r*Math.abs((e.left+x.width-c)/x.width)),{direction:S,speed:_}}function sA(s){if(s===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:r,bottom:i}=s.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:s.clientWidth,height:s.clientHeight}}function Yy(s){return s.reduce((e,n)=>Cs(e,Vf(n)),kr)}function oA(s){return s.reduce((e,n)=>e+Fy(n),0)}function lA(s){return s.reduce((e,n)=>e+Vy(n),0)}function cA(s,e){if(e===void 0&&(e=Es),!s)return;const{top:n,left:r,bottom:i,right:l}=e(s);Gy(s)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const uA=[["x",["left","right"],oA],["y",["top","bottom"],lA]];class Kf{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 r=Oc(n),i=Yy(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of uA)for(const f of c)Object.defineProperty(this,f,{get:()=>{const h=d(r),m=i[l]-h;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Go{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function dA(s){const{EventTarget:e}=Hn(s);return s instanceof e?s:ws(s)}function Wf(s,e){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var cr;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(cr||(cr={}));function Xy(s){s.preventDefault()}function fA(s){s.stopPropagation()}var dt;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(dt||(dt={}));const Jy={start:[dt.Space,dt.Enter],cancel:[dt.Esc],end:[dt.Space,dt.Enter,dt.Tab]},hA=(s,e)=>{let{currentCoordinates:n}=e;switch(s.code){case dt.Right:return{...n,x:n.x+25};case dt.Left:return{...n,x:n.x-25};case dt.Down:return{...n,y:n.y+25};case dt.Up:return{...n,y:n.y-25}}};class Yf{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 Go(ws(n)),this.windowListeners=new Go(Hn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(cr.Resize,this.handleCancel),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(cr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&cA(r),n(kr)}handleKeyDown(e){if(qf(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Jy,coordinateGetter:c=hA,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:h}=r.current,m=h?{x:h.left,y:h.top}:kr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:r.current,currentCoordinates:m});if(y){const v=Bo(y,m),S={x:0,y:0},{scrollableAncestors:_}=r.current;for(const x of _){const A=e.code,{isTop:D,isRight:O,isLeft:k,isBottom:L,maxScroll:B,minScroll:q}=Wy(x),z=sA(x),W={x:Math.min(A===dt.Right?z.right-z.width/2:z.right,Math.max(A===dt.Right?z.left:z.left+z.width/2,y.x)),y:Math.min(A===dt.Down?z.bottom-z.height/2:z.bottom,Math.max(A===dt.Down?z.top:z.top+z.height/2,y.y))},de=A===dt.Right&&!O||A===dt.Left&&!k,_e=A===dt.Down&&!L||A===dt.Up&&!D;if(de&&W.x!==y.x){const Se=x.scrollLeft+v.x,Ie=A===dt.Right&&Se<=B.x||A===dt.Left&&Se>=q.x;if(Ie&&!v.y){x.scrollTo({left:Se,behavior:d});return}Ie?S.x=x.scrollLeft-Se:S.x=A===dt.Right?x.scrollLeft-B.x:x.scrollLeft-q.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(_e&&W.y!==y.y){const Se=x.scrollTop+v.y,Ie=A===dt.Down&&Se<=B.y||A===dt.Up&&Se>=q.y;if(Ie&&!v.x){x.scrollTo({top:Se,behavior:d});return}Ie?S.y=x.scrollTop-Se:S.y=A===dt.Down?x.scrollTop-B.y:x.scrollTop-q.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,Cs(Bo(y,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(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()}}Yf.activators=[{eventName:"onKeyDown",handler:(s,e,n)=>{let{keyboardCodes:r=Jy,onActivation:i}=e,{active:l}=n;const{code:c}=s.nativeEvent;if(r.start.includes(c)){const d=l.activatorNode.current;return d&&s.target!==d?!1:(s.preventDefault(),i?.({event:s.nativeEvent}),!0)}return!1}}];function Qy(s){return!!(s&&"distance"in s)}function Zy(s){return!!(s&&"delay"in s)}class Xf{constructor(e,n,r){var i;r===void 0&&(r=dA(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=ws(c),this.documentListeners=new Go(this.document),this.listeners=new Go(r),this.windowListeners=new Go(Hn(c)),this.initialCoordinates=(i=Gf(l))!=null?i:kr,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:r}}}=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(cr.Resize,this.handleCancel),this.windowListeners.add(cr.DragStart,Xy),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),this.windowListeners.add(cr.ContextMenu,Xy),this.documentListeners.add(cr.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Zy(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Qy(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:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(cr.Click,fA,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(cr.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Gf(e))!=null?n:kr,h=Bo(i,f);if(!r&&d){if(Qy(d)){if(d.tolerance!=null&&Wf(h,d.tolerance))return this.handleCancel();if(Wf(h,d.distance))return this.handleStart()}if(Zy(d)&&Wf(h,d.tolerance))return this.handleCancel();this.handlePending(d,h);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===dt.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const pA={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Jf extends Xf{constructor(e){const{event:n}=e,r=ws(n.target);super(e,pA,r)}}Jf.activators=[{eventName:"onPointerDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const gA={move:{name:"mousemove"},end:{name:"mouseup"}};var Qf;(function(s){s[s.RightClick=2]="RightClick"})(Qf||(Qf={}));class mA extends Xf{constructor(e){super(e,gA,ws(e.event.target))}}mA.activators=[{eventName:"onMouseDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return n.button===Qf.RightClick?!1:(r?.({event:n}),!0)}}];const Zf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class yA extends Xf{constructor(e){super(e,Zf)}static setup(){return window.addEventListener(Zf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Zf.move.name,e)};function e(){}}}yA.activators=[{eventName:"onTouchStart",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var Fo;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var Lc;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Lc||(Lc={}));function bA(s){let{acceleration:e,activator:n=Fo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:c=5,order:d=Lc.TreeOrder,pointerCoordinates:f,scrollableAncestors:h,scrollableAncestorRects:m,delta:y,threshold:v}=s;const S=SA({delta:y,disabled:!l}),[_,x]=D_(),A=I.useRef({x:0,y:0}),D=I.useRef({x:0,y:0}),O=I.useMemo(()=>{switch(n){case Fo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Fo.DraggableRect:return i}},[n,i,f]),k=I.useRef(null),L=I.useCallback(()=>{const q=k.current;if(!q)return;const z=A.current.x*D.current.x,W=A.current.y*D.current.y;q.scrollBy(z,W)},[]),B=I.useMemo(()=>d===Lc.TreeOrder?[...h].reverse():h,[d,h]);I.useEffect(()=>{if(!l||!h.length||!O){x();return}for(const q of B){if(r?.(q)===!1)continue;const z=h.indexOf(q),W=m[z];if(!W)continue;const{direction:de,speed:_e}=iA(q,W,O,e,v);for(const Se of["x","y"])S[Se][de[Se]]||(_e[Se]=0,de[Se]=0);if(_e.x>0||_e.y>0){x(),k.current=q,_(L,c),A.current=_e,D.current=de;return}}A.current={x:0,y:0},D.current={x:0,y:0},x()},[e,L,r,x,l,c,JSON.stringify(O),JSON.stringify(S),_,h,B,m,JSON.stringify(v)])}const vA={x:{[mn.Backward]:!1,[mn.Forward]:!1},y:{[mn.Backward]:!1,[mn.Forward]:!1}};function SA(s){let{delta:e,disabled:n}=s;const r=Uf(e);return Po(i=>{if(n||!r||!i)return vA;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[mn.Backward]:i.x[mn.Backward]||l.x===-1,[mn.Forward]:i.x[mn.Forward]||l.x===1},y:{[mn.Backward]:i.y[mn.Backward]||l.y===-1,[mn.Forward]:i.y[mn.Forward]||l.y===1}}},[n,e,r])}function wA(s,e){const n=e!=null?s.get(e):void 0,r=n?n.node.current:null;return Po(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function CA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,r)}));return[...n,...l]},[]),[s,e])}var Vo;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Vo||(Vo={}));var eh;(function(s){s.Optimized="optimized"})(eh||(eh={}));const eb=new Map;function EA(s,e){let{dragging:n,dependencies:r,config:i}=e;const[l,c]=I.useState(null),{frequency:d,measure:f,strategy:h}=i,m=I.useRef(s),y=A(),v=zo(y),S=I.useCallback(function(D){D===void 0&&(D=[]),!v.current&&c(O=>O===null?D:O.concat(D.filter(k=>!O.includes(k))))},[v]),_=I.useRef(null),x=Po(D=>{if(y&&!n)return eb;if(!D||D===eb||m.current!==s||l!=null){const O=new Map;for(let k of s){if(!k)continue;if(l&&l.length>0&&!l.includes(k.id)&&k.rect.current){O.set(k.id,k.rect.current);continue}const L=k.node.current,B=L?new Kf(f(L),L):null;k.rect.current=B,B&&O.set(k.id,B)}return O}return D},[s,l,n,y,f]);return I.useEffect(()=>{m.current=s},[s]),I.useEffect(()=>{y||S()},[n,y]),I.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),I.useEffect(()=>{y||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{S(),_.current=null},d))},[d,y,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function A(){switch(h){case Vo.Always:return!1;case Vo.BeforeDragging:return n;default:return!n}}}function tb(s,e){return Po(n=>s?n||(typeof e=="function"?e(s):s):null,[e,s])}function _A(s,e){return tb(s,e)}function AA(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function $c(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function xA(s){return new Kf(Es(s),s)}function nb(s,e,n){e===void 0&&(e=xA);const[r,i]=I.useState(null);function l(){i(f=>{if(!s)return null;if(s.isConnected===!1){var h;return(h=f??n)!=null?h:null}const m=e(s);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=AA({callback(f){if(s)for(const h of f){const{type:m,target:y}=h;if(m==="childList"&&y instanceof HTMLElement&&y.contains(s)){l();break}}}}),d=$c({callback:l});return Fr(()=>{l(),s?(d?.observe(s),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[s]),r}function TA(s){const e=tb(s);return By(s,e)}const rb=[];function kA(s){const e=I.useRef(s),n=Po(r=>s?r&&r!==rb&&s&&e.current&&s.parentNode===e.current.parentNode?r:Oc(s):rb,[s]);return I.useEffect(()=>{e.current=s},[s]),n}function RA(s){const[e,n]=I.useState(null),r=I.useRef(s),i=I.useCallback(l=>{const c=Ff(l.target);c&&n(d=>d?(d.set(c,Vf(c)),new Map(d)):null)},[]);return I.useEffect(()=>{const l=r.current;if(s!==l){c(l);const d=s.map(f=>{const h=Ff(f);return h?(h.addEventListener("scroll",i,{passive:!0}),[h,Vf(h)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=s}return()=>{c(s),c(l)};function c(d){d.forEach(f=>{const h=Ff(f);h?.removeEventListener("scroll",i)})}},[i,s]),I.useMemo(()=>s.length?e?Array.from(e.values()).reduce((l,c)=>Cs(l,c),kr):Yy(s):kr,[s,e])}function ab(s,e){e===void 0&&(e=[]);const n=I.useRef(null);return I.useEffect(()=>{n.current=null},e),I.useEffect(()=>{const r=s!==kr;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?Bo(s,n.current):kr}function DA(s){I.useEffect(()=>{if(!kc)return;const e=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},s.map(e=>{let{sensor:n}=e;return n}))}function OA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=c=>{l(c,e)},n},{}),[s,e])}function ib(s){return I.useMemo(()=>s?tA(s):null,[s])}const sb=[];function LA(s,e){e===void 0&&(e=Es);const[n]=s,r=ib(n?Hn(n):null),[i,l]=I.useState(sb);function c(){l(()=>s.length?s.map(f=>Ky(f)?r:new Kf(e(f),f)):sb)}const d=$c({callback:c});return Fr(()=>{d?.disconnect(),c(),s.forEach(f=>d?.observe(f))},[s]),i}function $A(s){if(!s)return null;if(s.children.length>1)return s;const e=s.children[0];return Ho(e)?e:s}function MA(s){let{measure:e}=s;const[n,r]=I.useState(null),i=I.useCallback(h=>{for(const{target:m}of h)if(Ho(m)){r(y=>{const v=e(m);return y?{...y,width:v.width,height:v.height}:v});break}},[e]),l=$c({callback:i}),c=I.useCallback(h=>{const m=$A(h);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Rc(c);return I.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const NA=[{sensor:Jf,options:{}},{sensor:Yf,options:{}}],IA={current:{}},Mc={draggable:{measure:qy},droppable:{measure:qy,strategy:Vo.WhileDragging,frequency:eh.Optimized},dragOverlay:{measure:Es}};class Ko 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,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const jA={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ko,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Dc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Mc,measureDroppableContainers:Dc,windowRect:null,measuringScheduled:!1},HA={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Dc,draggableNodes:new Map,over:null,measureDroppableContainers:Dc},Nc=I.createContext(HA),ob=I.createContext(jA);function zA(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ko}}}function PA(s,e){switch(e.type){case ln.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case ln.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:e.coordinates.x-s.draggable.initialCoordinates.x,y:e.coordinates.y-s.draggable.initialCoordinates.y}}};case ln.DragEnd:case ln.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ln.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Ko(s.droppable.containers);return i.set(r,n),{...s,droppable:{...s.droppable,containers:i}}}case ln.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=s.droppable.containers.get(n);if(!l||r!==l.key)return s;const c=new Ko(s.droppable.containers);return c.set(n,{...l,disabled:i}),{...s,droppable:{...s.droppable,containers:c}}}case ln.UnregisterDroppable:{const{id:n,key:r}=e,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Ko(s.droppable.containers);return l.delete(n),{...s,droppable:{...s.droppable,containers:l}}}default:return s}}function UA(s){let{disabled:e}=s;const{active:n,activatorEvent:r,draggableNodes:i}=I.useContext(Nc),l=Uf(r),c=Uf(n?.id);return I.useEffect(()=>{if(!e&&!r&&l&&c!=null){if(!qf(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:h}=d;if(!f.current&&!h.current)return;requestAnimationFrame(()=>{for(const m of[f.current,h.current]){if(!m)continue;const y=$_(m);if(y){y.focus();break}}})}},[r,e,i,c,l]),null}function BA(s,e){let{transform:n,...r}=e;return s!=null&&s.length?s.reduce((i,l)=>l({transform:i,...r}),n):n}function qA(s){return I.useMemo(()=>({draggable:{...Mc.draggable,...s?.draggable},droppable:{...Mc.droppable,...s?.droppable},dragOverlay:{...Mc.dragOverlay,...s?.dragOverlay}}),[s?.draggable,s?.droppable,s?.dragOverlay])}function GA(s){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=s;const l=I.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Fr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!r)return;const h=e?.node.current;if(!h||h.isConnected===!1)return;const m=n(h),y=By(m,r);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const v=Gy(h);v&&v.scrollBy({top:y.y,left:y.x})}},[e,c,d,r,n])}const lb=I.createContext({...kr,scaleX:1,scaleY:1});var Ha;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Ha||(Ha={}));const FA=I.memo(function(e){var n,r,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:h,sensors:m=NA,collisionDetection:y=W_,measuring:v,modifiers:S,..._}=e;const x=I.useReducer(PA,void 0,zA),[A,D]=x,[O,k]=z_(),[L,B]=I.useState(Ha.Uninitialized),q=L===Ha.Initialized,{draggable:{active:z,nodes:W,translate:de},droppable:{containers:_e}}=A,Se=z!=null?W.get(z):null,Ie=I.useRef({initial:null,translated:null}),Fe=I.useMemo(()=>{var pe;return z!=null?{id:z,data:(pe=Se?.data)!=null?pe:IA,rect:Ie}:null},[z,Se]),ze=I.useRef(null),[Et,Q]=I.useState(null),[ue,De]=I.useState(null),ee=zo(_,Object.values(_)),me=Uo("DndDescribedBy",c),H=I.useMemo(()=>_e.getEnabled(),[_e]),T=qA(v),{droppableRects:fe,measureDroppableContainers:he,measuringScheduled:Ae}=EA(H,{dragging:q,dependencies:[de.x,de.y],config:T.droppable}),se=wA(W,z),ge=I.useMemo(()=>ue?Gf(ue):null,[ue]),$e=ve(),Te=_A(se,T.draggable.measure);GA({activeNode:z!=null?W.get(z):null,config:$e.layoutShiftCompensation,initialRect:Te,measure:T.draggable.measure});const je=nb(se,T.draggable.measure,Te),xt=nb(se?se.parentElement:null),rt=I.useRef({activatorEvent:null,active:null,activeNode:se,collisionRect:null,collisions:null,droppableRects:fe,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:_e,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),gt=_e.getNodeFor((n=rt.current.over)==null?void 0:n.id),at=MA({measure:T.dragOverlay.measure}),Yt=(r=at.nodeRef.current)!=null?r:se,Ht=q?(i=at.rect)!=null?i:je:null,bt=!!(at.nodeRef.current&&at.rect),qe=TA(bt?null:je),mt=ib(Yt?Hn(Yt):null),Dt=kA(q?gt??se:null),zt=LA(Dt),kn=BA(S,{transform:{x:de.x-qe.x,y:de.y-qe.y,scaleX:1,scaleY:1},activatorEvent:ue,active:Fe,activeNodeRect:je,containerNodeRect:xt,draggingNodeRect:Ht,over:rt.current.over,overlayNodeRect:at.rect,scrollableAncestors:Dt,scrollableAncestorRects:zt,windowRect:mt}),dr=ge?Cs(ge,de):null,Ot=RA(Dt),$i=ab(Ot),ua=ab(Ot,[je]),bn=Cs(kn,$i),Mn=Ht?J_(Ht,kn):null,it=Fe&&Mn?y({active:Fe,collisionRect:Mn,droppableRects:fe,droppableContainers:H,pointerCoordinates:dr}):null,Pn=Py(it,"id"),[vn,da]=I.useState(null),fr=bt?kn:Cs(kn,ua),un=Y_(fr,(l=vn?.rect)!=null?l:null,je),Rn=I.useRef(null),dn=I.useCallback((pe,Ee)=>{let{sensor:xe,options:Ke}=Ee;if(ze.current==null)return;const ke=W.get(ze.current);if(!ke)return;const Me=pe.nativeEvent,Re=new xe({active:ze.current,activeNode:ke,event:Me,options:Ke,context:rt,onAbort(Pe){if(!W.get(Pe))return;const{onDragAbort:Ce}=ee.current,He={id:Pe};Ce?.(He),O({type:"onDragAbort",event:He})},onPending(Pe,Ve,Ce,He){if(!W.get(Pe))return;const{onDragPending:Lt}=ee.current,Bt={id:Pe,constraint:Ve,initialCoordinates:Ce,offset:He};Lt?.(Bt),O({type:"onDragPending",event:Bt})},onStart(Pe){const Ve=ze.current;if(Ve==null)return;const Ce=W.get(Ve);if(!Ce)return;const{onDragStart:He}=ee.current,nt={activatorEvent:Me,active:{id:Ve,data:Ce.data,rect:Ie}};ja.unstable_batchedUpdates(()=>{He?.(nt),B(Ha.Initializing),D({type:ln.DragStart,initialCoordinates:Pe,active:Ve}),O({type:"onDragStart",event:nt}),Q(Rn.current),De(Me)})},onMove(Pe){D({type:ln.DragMove,coordinates:Pe})},onEnd:tt(ln.DragEnd),onCancel:tt(ln.DragCancel)});Rn.current=Re;function tt(Pe){return async function(){const{active:Ce,collisions:He,over:nt,scrollAdjustedTranslate:Lt}=rt.current;let Bt=null;if(Ce&&Lt){const{cancelDrop:Nn}=ee.current;Bt={activatorEvent:Me,active:Ce,collisions:He,delta:Lt,over:nt},Pe===ln.DragEnd&&typeof Nn=="function"&&await Promise.resolve(Nn(Bt))&&(Pe=ln.DragCancel)}ze.current=null,ja.unstable_batchedUpdates(()=>{D({type:Pe}),B(Ha.Uninitialized),da(null),Q(null),De(null),Rn.current=null;const Nn=Pe===ln.DragEnd?"onDragEnd":"onDragCancel";if(Bt){const Gt=ee.current[Nn];Gt?.(Bt),O({type:Nn,event:Bt})}})}}},[W]),V=I.useCallback((pe,Ee)=>(xe,Ke)=>{const ke=xe.nativeEvent,Me=W.get(Ke);if(ze.current!==null||!Me||ke.dndKit||ke.defaultPrevented)return;const Re={active:Me};pe(xe,Ee.options,Re)===!0&&(ke.dndKit={capturedBy:Ee.sensor},ze.current=Ke,dn(xe,Ee))},[W,dn]),ie=CA(m,V);DA(m),Fr(()=>{je&&L===Ha.Initializing&&B(Ha.Initialized)},[je,L]),I.useEffect(()=>{const{onDragMove:pe}=ee.current,{active:Ee,activatorEvent:xe,collisions:Ke,over:ke}=rt.current;if(!Ee||!xe)return;const Me={active:Ee,activatorEvent:xe,collisions:Ke,delta:{x:bn.x,y:bn.y},over:ke};ja.unstable_batchedUpdates(()=>{pe?.(Me),O({type:"onDragMove",event:Me})})},[bn.x,bn.y]),I.useEffect(()=>{const{active:pe,activatorEvent:Ee,collisions:xe,droppableContainers:Ke,scrollAdjustedTranslate:ke}=rt.current;if(!pe||ze.current==null||!Ee||!ke)return;const{onDragOver:Me}=ee.current,Re=Ke.get(Pn),tt=Re&&Re.rect.current?{id:Re.id,rect:Re.rect.current,data:Re.data,disabled:Re.disabled}:null,Pe={active:pe,activatorEvent:Ee,collisions:xe,delta:{x:ke.x,y:ke.y},over:tt};ja.unstable_batchedUpdates(()=>{da(tt),Me?.(Pe),O({type:"onDragOver",event:Pe})})},[Pn]),Fr(()=>{rt.current={activatorEvent:ue,active:Fe,activeNode:se,collisionRect:Mn,collisions:it,droppableRects:fe,draggableNodes:W,draggingNode:Yt,draggingNodeRect:Ht,droppableContainers:_e,over:vn,scrollableAncestors:Dt,scrollAdjustedTranslate:bn},Ie.current={initial:Ht,translated:Mn}},[Fe,se,it,Mn,W,Yt,Ht,fe,_e,vn,Dt,bn]),bA({...$e,delta:de,draggingRect:Mn,pointerCoordinates:dr,scrollableAncestors:Dt,scrollableAncestorRects:zt});const ce=I.useMemo(()=>({active:Fe,activeNode:se,activeNodeRect:je,activatorEvent:ue,collisions:it,containerNodeRect:xt,dragOverlay:at,draggableNodes:W,droppableContainers:_e,droppableRects:fe,over:vn,measureDroppableContainers:he,scrollableAncestors:Dt,scrollableAncestorRects:zt,measuringConfiguration:T,measuringScheduled:Ae,windowRect:mt}),[Fe,se,je,ue,it,xt,at,W,_e,fe,vn,he,Dt,zt,T,Ae,mt]),Z=I.useMemo(()=>({activatorEvent:ue,activators:ie,active:Fe,activeNodeRect:je,ariaDescribedById:{draggable:me},dispatch:D,draggableNodes:W,over:vn,measureDroppableContainers:he}),[ue,ie,Fe,je,D,me,W,vn,he]);return Xe.createElement(Ny.Provider,{value:k},Xe.createElement(Nc.Provider,{value:Z},Xe.createElement(ob.Provider,{value:ce},Xe.createElement(lb.Provider,{value:un},h)),Xe.createElement(UA,{disabled:d?.restoreFocus===!1})),Xe.createElement(B_,{...d,hiddenTextDescribedById:me}));function ve(){const pe=Et?.autoScrollEnabled===!1,Ee=typeof f=="object"?f.enabled===!1:f===!1,xe=q&&!pe&&!Ee;return typeof f=="object"?{...f,enabled:xe}:{enabled:xe}}}),VA=I.createContext(null),cb="button",KA="Draggable";function WA(s){let{id:e,data:n,disabled:r=!1,attributes:i}=s;const l=Uo(KA),{activators:c,activatorEvent:d,active:f,activeNodeRect:h,ariaDescribedById:m,draggableNodes:y,over:v}=I.useContext(Nc),{role:S=cb,roleDescription:_="draggable",tabIndex:x=0}=i??{},A=f?.id===e,D=I.useContext(A?lb:VA),[O,k]=Rc(),[L,B]=Rc(),q=OA(c,e),z=zo(n);Fr(()=>(y.set(e,{id:e,key:l,node:O,activatorNode:L,data:z}),()=>{const de=y.get(e);de&&de.key===l&&y.delete(e)}),[y,e]);const W=I.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":A&&S===cb?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[r,S,x,A,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:h,attributes:W,isDragging:A,listeners:r?void 0:q,node:O,over:v,setNodeRef:k,setActivatorNodeRef:B,transform:D}}function YA(){return I.useContext(ob)}const XA="Droppable",JA={timeout:25};function QA(s){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=s;const l=Uo(XA),{active:c,dispatch:d,over:f,measureDroppableContainers:h}=I.useContext(Nc),m=I.useRef({disabled:n}),y=I.useRef(!1),v=I.useRef(null),S=I.useRef(null),{disabled:_,updateMeasurementsFor:x,timeout:A}={...JA,...i},D=zo(x??r),O=I.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{h(Array.isArray(D.current)?D.current:[D.current]),S.current=null},A)},[A]),k=$c({callback:O,disabled:_||!c}),L=I.useCallback((W,de)=>{k&&(de&&(k.unobserve(de),y.current=!1),W&&k.observe(W))},[k]),[B,q]=Rc(L),z=zo(e);return I.useEffect(()=>{!k||!B.current||(k.disconnect(),y.current=!1,k.observe(B.current))},[B,k]),I.useEffect(()=>(d({type:ln.RegisterDroppable,element:{id:r,key:l,disabled:n,node:B,rect:v,data:z}}),()=>d({type:ln.UnregisterDroppable,key:l,id:r})),[r]),I.useEffect(()=>{n!==m.current.disabled&&(d({type:ln.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:c,rect:v,isOver:f?.id===r,node:B,over:f,setNodeRef:q}}function th(s,e,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function ZA(s,e){return s.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(s.length))}function Ic(s){return s!==null&&s>=0}function ex(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:c}=s;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=rx(n,c,i);if(c===i){const h=n[l];return h?{x:ii&&c<=l?{x:-d.width-f,y:0,...jc}:c=l?{x:d.width+f,y:0,...jc}:{x:0,y:0,...jc}};function rx(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=s;const l=th(e,r,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}},Hc={scaleX:1,scaleY:1},ax=s=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:c}=s;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const h=l[c];return h?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...Hc}:i=c?{x:0,y:d.height+f,...Hc}:{x:0,y:0,...Hc}};function ix(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return r?nr.map(q=>typeof q=="object"&&"id"in q?q.id:q),[r]),_=c!=null,x=c?S.indexOf(c.id):-1,A=h?S.indexOf(h.id):-1,D=I.useRef(S),O=!ex(S,D.current),k=A!==-1&&x===-1||O,L=tx(l);Fr(()=>{O&&_&&m(S)},[O,S,_,m]),I.useEffect(()=>{D.current=S},[S]);const B=I.useMemo(()=>({activeIndex:x,containerId:y,disabled:L,disableTransforms:k,items:S,overIndex:A,useDragOverlay:v,sortedRects:ZA(S,f),strategy:i}),[x,y,L.draggable,L.droppable,k,S,A,f,v,i]);return Xe.createElement(db.Provider,{value:B},e)}const ox=s=>{let{id:e,items:n,activeIndex:r,overIndex:i}=s;return th(n,r,i).indexOf(e)},lx=s=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:h}=s;return!h||!r||d!==l&&i===c?!1:n?!0:c!==i&&e===f},cx={duration:200,easing:"ease"},fb="transform",ux=qo.Transition.toString({property:fb,duration:0,easing:"linear"}),dx={roleDescription:"sortable"};function fx(s){let{disabled:e,index:n,node:r,rect:i}=s;const[l,c]=I.useState(null),d=I.useRef(n);return Fr(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const h=Es(r.current,{ignoreTransform:!0}),m={x:f.left-h.left,y:f.top-h.top,scaleX:f.width/h.width,scaleY:f.height/h.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),I.useEffect(()=>{l&&c(null)},[l]),l}function hx(s){let{animateLayoutChanges:e=lx,attributes:n,disabled:r,data:i,getNewIndex:l=ox,id:c,strategy:d,resizeObserverConfig:f,transition:h=cx}=s;const{items:m,containerId:y,activeIndex:v,disabled:S,disableTransforms:_,sortedRects:x,overIndex:A,useDragOverlay:D,strategy:O}=I.useContext(db),k=px(r,S),L=m.indexOf(c),B=I.useMemo(()=>({sortable:{containerId:y,index:L,items:m},...i}),[y,i,L,m]),q=I.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:z,node:W,isOver:de,setNodeRef:_e}=QA({id:c,data:B,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:q,...f}}),{active:Se,activatorEvent:Ie,activeNodeRect:Fe,attributes:ze,setNodeRef:Et,listeners:Q,isDragging:ue,over:De,setActivatorNodeRef:ee,transform:me}=WA({id:c,data:B,attributes:{...dx,...n},disabled:k.draggable}),H=R_(_e,Et),T=!!Se,fe=T&&!_&&Ic(v)&&Ic(A),he=!D&&ue,Ae=he&&fe?me:null,ge=fe?Ae??(d??O)({rects:x,activeNodeRect:Fe,activeIndex:v,overIndex:A,index:L}):null,$e=Ic(v)&&Ic(A)?l({id:c,items:m,activeIndex:v,overIndex:A}):L,Te=Se?.id,je=I.useRef({activeId:Te,items:m,newIndex:$e,containerId:y}),xt=m!==je.current.items,rt=e({active:Se,containerId:y,isDragging:ue,isSorting:T,id:c,index:L,items:m,newIndex:je.current.newIndex,previousItems:je.current.items,previousContainerId:je.current.containerId,transition:h,wasDragging:je.current.activeId!=null}),gt=fx({disabled:!rt,index:L,node:W,rect:z});return I.useEffect(()=>{T&&je.current.newIndex!==$e&&(je.current.newIndex=$e),y!==je.current.containerId&&(je.current.containerId=y),m!==je.current.items&&(je.current.items=m)},[T,$e,y,m]),I.useEffect(()=>{if(Te===je.current.activeId)return;if(Te!=null&&je.current.activeId==null){je.current.activeId=Te;return}const Yt=setTimeout(()=>{je.current.activeId=Te},50);return()=>clearTimeout(Yt)},[Te]),{active:Se,activeIndex:v,attributes:ze,data:B,rect:z,index:L,newIndex:$e,items:m,isOver:de,isSorting:T,isDragging:ue,listeners:Q,node:W,overIndex:A,over:De,setNodeRef:H,setActivatorNodeRef:ee,setDroppableNodeRef:_e,setDraggableNodeRef:Et,transform:gt??ge,transition:at()};function at(){if(gt||xt&&je.current.newIndex===L)return ux;if(!(he&&!qf(Ie)||!h)&&(T||rt))return qo.Transition.toString({...h,property:fb})}}function px(s,e){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s?.draggable)!=null?n:e.draggable,droppable:(r=s?.droppable)!=null?r:e.droppable}}function zc(s){if(!s)return!1;const e=s.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const gx=[dt.Down,dt.Right,dt.Up,dt.Left],mx=(s,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(gx.includes(s.code)){if(s.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const v=i.get(y.id);if(v)switch(s.code){case dt.Down:r.topv.top&&f.push(y);break;case dt.Left:r.left>v.left&&f.push(y);break;case dt.Right:r.left1&&(m=h[1].id),m!=null){const y=l.get(n.id),v=l.get(m),S=v?i.get(v.id):null,_=v?.node.current;if(_&&S&&y&&v){const A=Oc(_).some((q,z)=>d[z]!==q),D=hb(y,v),O=yx(y,v),k=A||!D?{x:0,y:0}:{x:O?r.width-S.width:0,y:O?r.height-S.height:0},L={x:S.left,y:S.top};return k.x&&k.y?L:Bo(L,k)}}}};function hb(s,e){return!zc(s)||!zc(e)?!1:s.data.current.sortable.containerId===e.data.current.sortable.containerId}function yx(s,e){return!zc(s)||!zc(e)||!hb(s,e)?!1:s.data.current.sortable.index{const d=I.useId(),f=I.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),h=q_(Iy(Jf,{activationConstraint:{distance:5}}),Iy(Yf,{coordinateGetter:mx})),m=I.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=I.useCallback(S=>{const{active:_,over:x}=S,A=Date.now();if(!x||_.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:D,lastActiveId:O,inProgress:k}=f.current;if(O===_.id&&A-D<500&&!k)return;f.current={inProgress:!1,lastSortTime:A,lastActiveId:_.id};const L=s.findIndex(q=>String(q[e])===String(_.id)),B=s.findIndex(q=>String(q[e])===String(x.id));if(L!==-1&&B!==-1&&L!==B){const q=th(s,L,B);i?.(q,{oldIndex:L,newIndex:B})}},[s,e,i]),v=s.map(S=>String(S[e]));return yt.jsx(FA,{id:d,sensors:h,collisionDetection:F_,onDragStart:m,onDragEnd:y,children:yt.jsx(sx,{items:v,strategy:bx[n],children:r})},c!==void 0?`${d}-v${c}`:d)},pb=I.createContext(null),Sx=({value:s,children:e})=>yt.jsx(pb.Provider,{value:s,children:e}),wx=()=>I.useContext(pb),Cx=({id:s,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:h}=hx({id:s}),m={transform:qo.Transform.toString(d),transition:f,opacity:h?.5:1,position:"relative"};return yt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(s),"data-dragging":h,children:yt.jsx(Sx,{value:{listeners:l,handle:e,isDragging:h},children:r})})},lt=pt("DynamicRenderer");function oa(){try{return window.G7Core?.devTools}catch{return}}function rh(s,e,n,r){if(typeof s=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(s))try{return e.resolveTranslations(s,n,r)}catch{return s}return s}if(Array.isArray(s))return s.map(i=>rh(i,e,n,r));if(s&&typeof s=="object"){const i={};for(const[l,c]of Object.entries(s))i[l]=rh(c,e,n,r);return i}return s}function Ex(s){const e=Object.keys(s);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const ur=(s,e)=>{const n=["errors"],r={...s};for(const i of Object.keys(e)){const l=e[i],c=s[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&Ex(l)){const d=Object.keys(l).map(h=>parseInt(h,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)r[i]={...l};else{const h=[...c];for(const[m,y]of Object.entries(l)){const v=parseInt(m,10);v>=0&&v=h.length&&(h[v]=y)}r[i]=h}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?r[i]=ur(c,l):r[i]=l}return r},_x=(s,e,n,r)=>{if(!e||typeof e!="object"||Array.isArray(e))return s;const i=ur(s,e);return Ry(i,n,r)},Pc=(s,e)=>{let n=null;const r=()=>(n===null&&(n={...s}),n);for(const i of Object.keys(e)){if(!(i in s))continue;const l=e[i],c=s[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Pc(c,l);if(d===c)continue;Object.keys(d).length===0?delete r()[i]:r()[i]=d}else delete r()[i]}return n??s},Ax=s=>{const e={},n=s.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),c=r.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,h)=>h.toUpperCase());e[d]=c}}return e};class xx extends I.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){lt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:yt.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:[yt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),yt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&yt.jsxs("details",{className:"mt-2",children:[yt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),yt.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 Vr=I.memo(({componentDef:s,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:h,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:v=!1,onComponentSelect:S,onComponentHover:_,onDragStart:x,onDragEnd:A,componentPath:D,layoutKey:O})=>{const[k,L]=I.useState({loadingActions:{}});I.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const B=I.useRef(null);I.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:ie,...ce}=e._localInit,Z=`${JSON.stringify(ce)}:${V||"no-force"}`;if(B.current!==Z){B.current=Z;const ve=ie||"shallow",Ee=window.G7Core?.state?.get?.()?._local||{},xe=window.__g7PendingLocalState||{},Ke={...Ee,...xe};ve==="replace"?window.__g7PendingLocalState={loadingActions:Ke.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=ur(Ke,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Ke,...ce,hasChanges:!1};const ke=window.__g7SetLocalOverrideKeys;ke&&typeof ke=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ur(ke,{...ce,hasChanges:!1}))}}}),I.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){L(ve=>Pc(ve,V));const ie=V,ce=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ie&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const q=I.useRef(O);I.useEffect(()=>{s._fromBase&&O&&q.current!==O&&(q.current=O,L({loadingActions:{}}))},[O,s._fromBase]);const z=I.useRef(""),W=I.useRef(!1),de=I.useRef(null),_e=I.useRef(null),Se=I.useRef({}),Ie=I.useRef({}),Fe=I.useRef(h),ze=k_(),Et=i_(),Q=Et?.getParentDataContext()??h;I.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...ie}=e._localInit,ce=JSON.stringify(ie),Z=V!==void 0,ve=Nf(),pe=`${ce}:${V||"no-force"}`,Ee=h_({globalTrackedKey:ve.hash,instanceHandledKey:_e.current,trackingKey:pe});if(Ee==="apply"){_e.current=pe,ve.hash=pe,ve.timestamp=V,z.current=ce,Z&&(W.current=!0);const{_merge:Ke,...ke}=ie,Me=Ke||"shallow";L(Re=>Me==="replace"?{loadingActions:Re.loadingActions||{},...ke,hasChanges:!1}:Me==="deep"?ur(Re,{...ke,hasChanges:!1}):{...Re,...ke,hasChanges:!1}),e._globalSetState&&e._globalSetState(Re=>{const tt=Re?._local||{};let Pe;return Me==="replace"?Pe={...ke,hasChanges:!1}:Me==="deep"?Pe=ur(tt,{...ke,hasChanges:!1}):Pe={...tt,...ke,hasChanges:!1},{...Re,_local:Pe}}),i.invalidateCacheByKeys(["_local"]),lt.log("_localInit applied (data changed):",Object.keys(ie))}else if(Ee==="prune"){_e.current=pe;const{_merge:Ke,...ke}=ie;L(Re=>Pc(Re,ke)),Pc(k,ke)!==k&&(i.invalidateCacheByKeys(["_local"]),lt.log("_localInit pruned (applied by another renderer):",Object.keys(ke)))}de.current=e._localInit,d_(e._localInit)}},[e._localInit,h,i]);const{isTransitioning:ue}=Ay(),De=S_(),ee=f??De,{width:me}=jf(),H=wx(),T=I.useMemo(()=>{let V=s;if(s.type==="iterator"&&s.data){const{data:Z,itemName:ve,indexName:pe,...Ee}=s;V={...Ee,iteration:{source:Z,item_var:ve||"item",index_var:pe}}}if(!V.responsive)return V;const ie=Ci.getMatchingKey(V.responsive,me);if(!ie)return V;const ce=V.responsive[ie];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?ie:void 0}},[s,me]),fe=I.useCallback(V=>{const ie=V?.__setStateId;if(L(ce=>{const Z=window.__g7PendingLocalState,pe=window.__g7SetLocalOverrideKeys||Z,Ee=pe?ur(ce,pe):ce;if(typeof V=="function"){const Re=V(Ee);return ur(Ee,Re)}const{__mergeMode:xe,__setStateId:Ke,...ke}=V;let Me;if(xe==="replace"?Me=ke:xe==="shallow"?Me={...Ee,...ke}:Me=ur(Ee,ke),xe!==void 0){const Re=window.__g7ForcedLocalFields;Re&&(window.__g7ForcedLocalFields={...Re,...ke})}return Me}),ie){const ce=oa();if(ce?.isEnabled()){const Z=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(Z,ve,0,["_local"],[]),ce.completeStateChange?.(ie)},0)}}},[T.id,T.name]),he=d?.state??k,Ae=d?.setState??fe,se=I.useMemo(()=>{const V=e._localInit&&e._localInit!==de.current;let ie;V&&e._local?ie=e._local:ie=e._local?ur(e._local,he):he;const ce=window.__g7ForcedLocalFields;ce&&(ie=ur(ie,ce));const Z={...e,_local:ie},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const pe=new $n,Ee={...Z,...ze?{_isolated:ze.state}:{}},xe={},Ke=oa(),ke=Ke?.isEnabled()??!1;for(const[Me,Re]of Object.entries(ve)){const tt=ke?Date.now():0,Pe=ke?e._computed?.[Me]:void 0;let Ve;try{if(typeof Re=="string")if(Re.startsWith("{{")&&Re.endsWith("}}")){const Ce=Re.slice(2,-2).trim(),He=Wn(Ce)?pe.evaluatePipeExpression(Ce,Ee,{skipCache:!0}):pe.evaluateExpression(Ce,Ee,{skipCache:!0});xe[Me]=He}else xe[Me]=Re;else if(Re&&typeof Re=="object"&&"$switch"in Re){const Ce=pe.resolveSwitch(Re,Ee,{skipCache:!0});xe[Me]=Ce}}catch(Ce){lt.warn(`Failed to recalculate computed value: ${Me}`,Ce),xe[Me]=e._computed?.[Me],Ve=Ce instanceof Error?Ce.message:String(Ce)}if(ke&&(Ve||Pe!==xe[Me])){const He=Date.now()-tt;Ke.trackComputedProperty?.(Me,typeof Re=="string"?Re:JSON.stringify(Re),[{type:"_local",path:"_local",value:Z._local}],xe[Me],He,T.id,Ve),Pe!==xe[Me]&&Ke.trackComputedRecalc?.(Me,"dependency-change",Pe,xe[Me],He,{type:"_local",path:"_local"},T.id)}}Z._computed=xe}if(ze&&(Z._isolated=ze.state),Q&&(Z.$parent=Q),s.extensionPointProps){const pe=i.resolveObject(s.extensionPointProps,Z,y?{skipCache:!0}:void 0);Z.extensionPointProps=v&&l?rh(pe,l,n,Z):pe}return s.extensionPointCallbacks&&(Z.extensionPointCallbacks=s.extensionPointCallbacks),v&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,he,ze?.state,Q,Et?.version,s.extensionPointProps,s.extensionPointCallbacks]);Se.current=se._local,Ie.current=se._computed||{},Fe.current=Q,I.useEffect(()=>{const V=oa();if(!V?.isEnabled())return;const ie=se._local;ie&&V.updateLocalState(ie);const ce=se._computed;ce&&V.updateComputedState(ce),Q&&V.updateParentContext?.(Q);const Z=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",pe={global:Object.keys(e._global||{}),local:Object.keys(ie||{}),context:d?Object.keys(d.state||{}):[]},Ee={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(Z,ve,pe,Ee),he&&Object.keys(he).length>0&&V.trackDynamicState?.(Z,he);const xe=!!(T.expandChildren||T.props?.expandChildren);V.trackContextFlow?.(Z,ve,!!d,xe,!0)},[se._local,e,T.id,T.name,d,he,T.expandChildren,T.props?.expandChildren,Q]);const ge=I.useMemo(()=>({state:{...se._local},setState:Ae,stateRef:Se,computedRef:Ie,isolatedContext:ze,parentDataContext:se}),[se._local,Ae,k,ze,se]),$e=I.useMemo(()=>{const V=fs({if:T.if,condition:T.condition,conditions:T.conditions},se,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=oa();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,V)}return V},[T.if,T.conditions,se,i,T.id]),Te=I.useMemo(()=>{if(!T.slot)return null;const V=T.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const ie=V.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},Z=Wn(ie)?i.evaluatePipeExpression(ie,se,void 0,ce):i.evaluateExpression(ie,se,ce);return lt.log(`[Slot] 표현식 평가: "${ie}" => "${Z}" (컴포넌트: ${T.id})`),typeof Z=="string"?Z:null}catch(ce){return lt.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return lt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${T.id})`),V},[T.slot,T.id,se,i]),je=I.useMemo(()=>!Te||!T.id?"":`${T.id}-${Te}-${JSON.stringify(T.slotOrder??0)}`,[Te,T.id,T.slotOrder]),xt=I.useRef(null);I.useEffect(()=>{const V=window.__slotContextValue,ie=V?.isEnabled??!1;if(T.slot&<.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${ie}, shouldRender: ${$e}, resolvedSlotId: ${Te}`),!ie||!$e){T.slot&<.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ie}, shouldRender: ${$e}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}if(!Te||!T.id){T.slot&<.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${T.id}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}xt.current&&xt.current!==Te&&V.unregisterFromSlot(xt.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>ge,translationContext:n,registrationKey:je}),xt.current=Te,()=>{const Z=window.__slotContextValue;Te&&T.id&&Z&&Z.unregisterFromSlot(Te,T.id)}},[$e,Te,T,e,f,ge,n,je]);const rt=I.useCallback(V=>{if(typeof V=="string"){if(ic(V))return Yd(V);if(sc(V)){const ie=[],ce=V.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(ve,pe)=>(ie.push(pe),`${$a}${ie.length-1}${$a}`));let Z=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(Z=l.resolveTranslations(ce,n,se)),Z.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(ve,pe)=>ie[parseInt(pe)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const ie=V.trim();return ie.startsWith("{")&&ie.endsWith("}")||ie.startsWith("[")&&ie.endsWith("]")?V:l.resolveTranslations(V,n,se)}return V}if(Array.isArray(V))return V.map(ie=>rt(ie));if(V&&typeof V=="object"){const ie={};for(const[ce,Z]of Object.entries(V))ie[ce]=rt(Z);return ie}return V},[l,n,se]),gt=I.useCallback(V=>yo(V),[]),at=I.useCallback(V=>La(V),[]),Yt=I.useMemo(()=>{let V={...T.props||{}};const ie=["cellChildren","expandChildren","expandContext","render"],Z=r.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...ie,...Z])],pe=y?{skipCache:!0}:void 0,Ee={...pe??{},skipBindingKeys:ve},xe=Ce=>{if(pe)return pe;if(Ce.startsWith("_computed")||Ce.startsWith("$computed"))return{skipCache:!0}};for(const[Ce,He]of Object.entries(V))if(!ve.includes(Ce))if(typeof He=="string"){const nt=at(He);if(nt!==null){let Lt=!1,Bt=nt;nt.startsWith(sr)&&(Lt=!0,Bt=nt.slice(sr.length));const Nn={componentId:T.id,componentName:T.name,propName:Ce};let Gt;if(Wn(Bt))try{Gt=i.evaluatePipeExpression(Bt,se,xe(Bt),Nn)}catch(Ft){lt.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else if(gt(Bt))try{Gt=i.evaluateExpression(Bt,se,Nn)}catch(Ft){lt.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else Gt=i.resolve(Bt,se,xe(Bt),Nn);V[Ce]=Lt&&Gt!=null?ds(Gt):Gt}else{const Lt={componentId:T.id,componentName:T.name,propName:Ce};V[Ce]=i.resolveBindings(He,se,pe,Lt)}}else Array.isArray(He)?V[Ce]=He.map(nt=>typeof nt=="string"?i.resolveBindings(nt,se,pe):typeof nt=="object"&&nt!==null?i.resolveObject(nt,se,Ee):nt):He&&typeof He=="object"&&(V[Ce]=i.resolveObject(He,se,Ee));for(const[Ce,He]of Object.entries(V))V[Ce]=rt(He);if(typeof V.style=="string"&&(V.style=Ax(V.style)),V=cf(V,v?void 0:T.actions,se,{componentContext:ge,actionDispatcher:c}),T.classMap){const Ce=K0(T.classMap,se,i,{skipCache:!0});if(Ce){const He=V.className||"";V.className=He?`${He} ${Ce}`:Ce}}T.style&&(V.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(V,he),T.component_layout&&(V.__componentLayoutDefs=T.component_layout);const Ke=T.expandChildren||T.props?.expandChildren,ke=T.props?.cellChildren,Me=T.children&&T.children.length>0,Re=T.component_layout,tt=T.slot,Pe=T.props?.modalId,Ve=T.type==="composite";return(Ke||ke||Me||Re||tt||Pe||Ve)&&(V.__componentContext=ge),V},[T.props,T.actions,T.style,T.classMap,T.id,se,n,i,l,ge,he,rt,gt,at,y]),Ht=I.useRef(null),bt=I.useMemo(()=>Ht.current&&Ty(Ht.current,Yt)?Ht.current:(Ht.current=Yt,Yt),[Yt]),qe=I.useMemo(()=>{const V=T.id;if(typeof V!="string"||!V.includes("{{"))return V;const ie=i.resolveBindings(V,se,{skipCache:!0});return typeof ie=="string"?ie:V},[T.id,se,i]),mt=I.useMemo(()=>{const V=T.dataKey,ie=T.trackChanges,ce=T.debounce;if(V){const Z=V.startsWith("_global."),ve=Z?V.slice(8):V,pe=Z?e._global:se._local;return{dataKey:ve,trackChanges:ie??!1,debounce:ce,setState:Z?xe=>{e._globalSetState?e._globalSetState(xe):lt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:Ae,state:pe??{},_isGlobal:Z}}if(ee.dataKey)return ee},[T.dataKey,T.trackChanges,T.debounce,T.id,Ae,se._local,e._global,e._globalSetState,ee]),Dt=I.useRef(new Set);I.useEffect(()=>{Dt.current.clear()},[e._global?._remountKeys]);const zt=I.useCallback((V,ie)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!Dt.current.has(V)?(Dt.current.add(V),`${V}-remount-${ce[V]}`):V||ie},[e._global?._remountKeys]),kn=I.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const V=T.text;let ie=V;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},Z=at(V);if(Z!==null){let ve=!1,pe=Z;if(Z.startsWith(sr)&&(ve=!0,pe=Z.slice(sr.length)),Wn(pe))try{ie=i.evaluatePipeExpression(pe,se,{skipCache:!0},ce)}catch(Ee){lt.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else if(gt(pe))try{ie=i.evaluateExpression(pe,se,ce)}catch(Ee){lt.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else ie=i.resolve(pe,se,{skipCache:!0},ce);ve&&ie!=null&&(ie=ds(ie))}else V.includes("{{")&&(ie=i.resolveBindings(V,se,{skipCache:!0},ce));return ie=rt(ie),ie??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((V,ie)=>{if(typeof V=="string")return V;const ce=T.__responsiveChildrenKey,Z=ce?`responsive.${ce}.children`:"children",ve=D?`${D}.${Z}.${ie}`:`${ie}`,pe=V._fromBase?V.id||`child-${ie}`:zt(V.id,`child-${ie}`),Ee=!V._fromBase&&O?`${pe}_${O}`:pe;return yt.jsx(Vr,{componentDef:V,dataContext:se,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:y,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:ve,onDragStart:x,onDragEnd:A,layoutKey:O},Ee)})},[T.text,T.children,T.id,e,se,n,r,i,l,c,ge,mt,at,gt,rt,zt,y,v,S,_,D,x,A,O]),dr=I.useMemo(()=>{if(!T.iteration)return null;try{const V=lf(T.iteration.source,se,i);if(!Array.isArray(V))return lt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,V),null;const ie=oa();return ie?.isEnabled()&&ie.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,V.length),V.map((ce,Z)=>{const ve={...se,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:Z};T.iteration.index_var&&(ve[T.iteration.index_var]=Z);const pe=Z===0||Z===V.length-1;ie?.isEnabled()&&pe&&ie.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(se),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ce,...T.iteration.index_var?{[T.iteration.index_var]:Z}:{}}},depth:1});const Ee={...T,iteration:void 0,responsive:void 0},xe=D?`${D}.iteration.${Z}`:`iteration.${Z}`,Ke=`${zt(T.id,"item")}-${Z}`;return yt.jsx(Vr,{componentDef:Ee,dataContext:ve,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:xe,onDragStart:x,onDragEnd:A,layoutKey:O},Ke)})}catch(V){return lt.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,V),null}},[T.iteration,T.children,T.id,e,se,n,r,i,l,c,ge,mt,zt,v,S,_,D,x,A,O]),[Ot,$i]=I.useState(0),ua=I.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:V,itemTemplate:ie}=T;try{const ce=lf(V.source,se,i);if(!Array.isArray(ce))return lt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const Z=V.itemKey||"id",ve=V.strategy||"verticalList",pe=V.itemVar||"$item",Ee=V.indexVar||"$index",xe=V.handle,Ke=V.wrapperElement,ke=(tt,Pe)=>{const Ve=T.actions?.filter(Ce=>Ce.event==="onSortEnd"||Ce.type==="onSortEnd");if($i(Ce=>Ce+1),Ve&&Ve.length>0&&c){const Ce={...se,$sortedItems:tt,$sortEvent:Pe};Ve.forEach(He=>{try{const nt=c.createHandler(He,Ce,ge),Lt=new Event("sortend");nt(Lt)}catch(nt){lt.error(`onSortEnd action failed: ${He.handler}`,nt)}})}},Me=tt=>{const Pe=T.actions?.filter(Ve=>Ve.event==="onSortStart"||Ve.type==="onSortStart");if(Pe&&Pe.length>0&&c){const Ve={...se,$activeId:tt.activeId};Pe.forEach(Ce=>{try{const He=c.createHandler(Ce,Ve,ge),nt=new Event("sortstart");He(nt)}catch(He){lt.error(`onSortStart action failed: ${Ce.handler}`,He)}})}},Re=ce.map((tt,Pe)=>{const Ve=String(tt[Z]),Ce={...se,[pe]:tt,[Ee]:Pe},He=D?`${D}.sortable.${Pe}`:`sortable.${Pe}`,nt=`${zt(T.id,"sortable-item")}-v${Ot}-${Ve}`;return yt.jsx(Cx,{id:Ve,handle:xe,...Ke?{as:Ke}:{},children:(Ke&&ie.children?ie.children:[ie]).map((Lt,Bt)=>yt.jsx(Vr,{componentDef:Lt,dataContext:Ce,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:He,onDragStart:x,onDragEnd:A,layoutKey:O},`${nt}-child-${Bt}`))},nt)});return yt.jsx(vx,{items:ce,itemKey:Z,strategy:ve,onSortEnd:ke,onSortStart:Me,sortVersion:Ot,children:Re})}catch(ce){return lt.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,se,n,r,i,l,c,ge,zt,v,S,_,D,x,A,Ot,O]),bn=I.useRef(!1);I.useEffect(()=>{if(bn.current)return;bn.current=!0;const V=oa();if(V?.isEnabled()&&V.trackMount(s.id,{name:s.name,type:s.type||"component",props:bt}),s.lifecycle?.onMount&&s.lifecycle.onMount.length>0)for(const ce of s.lifecycle.onMount)try{const Z=c.createHandler(ce,se,ge),ve=new Event("mount");Z(ve),lt.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${s.id})`)}catch(Z){lt.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${s.id})`,Z)}const ie=[];if(s.onComponentEvent&&s.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const Z of s.onComponentEvent){if(!Z.event){lt.warn(`onComponentEvent: event name is required (Component: ${s.id})`);continue}const ve=async Ee=>{try{const xe={...se,_eventData:Ee},ke=await c.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},xe,ge)(new CustomEvent(Z.event,{detail:Ee}));return lt.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${s.id})`,{eventData:Ee,result:ke}),ke}catch(xe){throw lt.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${s.id})`,xe),xe}},pe=ce.componentEvent.on(Z.event,ve);ie.push(pe),lt.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${s.id})`)}else lt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${s.id})`)}return()=>{const ce=oa();ce?.isEnabled()&&ce.trackUnmount(s.id);for(const Z of ie)try{Z()}catch(ve){lt.error(`onComponentEvent: Failed to unsubscribe (Component: ${s.id})`,ve)}if(ie.length>0&<.log(`onComponentEvent: Unsubscribed ${ie.length} event(s) (Component: ${s.id})`),s.lifecycle?.onUnmount&&s.lifecycle.onUnmount.length>0)for(const Z of s.lifecycle.onUnmount)try{const ve=c.createHandler(Z,se,ge),pe=new Event("unmount");ve(pe),lt.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${s.id})`)}catch(ve){lt.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${s.id})`,ve)}}},[]);const Mn=I.useMemo(()=>{const V=bt.dataKey,ie=bt.trackChanges,ce=bt.debounce;return V?{dataKey:V,trackChanges:ie??!1,debounce:ce,setState:Ae,state:he}:null},[bt.dataKey,bt.trackChanges,bt.debounce,Ae,he]);I.useEffect(()=>{const V=T.dataKey||bt.dataKey;if(!V)return;const ie=oa();if(!ie?.isEnabled())return;const ce=[],Z=pe=>{if(pe)for(const Ee of pe){const xe=Ee?.props?.name;if(xe&&ce.push({name:xe,type:Ee.name||Ee.type||"unknown"}),Ee?.children&&Z(Ee.children),Ee?.slots)for(const Ke of Object.values(Ee.slots))Array.isArray(Ke)&&Z(Ke)}};if(s.children&&Z(s.children),s.slots)for(const pe of Object.values(s.slots))Array.isArray(pe)&&Z(pe);const ve=s.id||`form-${V}`;return ie.trackForm(ve,V,ce),()=>{ie.untrackForm(ve)}},[T,bt.dataKey,s.id,s.children]);const it=I.useRef(null),Pn=I.useRef(void 0);I.useEffect(()=>{const V=bt?.name;if(!V||!ee.dataKey||!ee.setState||bt?.autoBinding===!1)return;const ie=`${ee.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(ie,(ce.get(ie)??0)+1),()=>{const Z=ce.get(ie)??0;Z<=1?ce.delete(ie):ce.set(ie,Z-1)}},[bt?.name,bt?.autoBinding,ee.dataKey,ee.setState]);const vn=I.useMemo(()=>{const{dataKey:V,trackChanges:ie,debounce:ce,...Z}=bt,ve=Z.name;if(!ve||!ee.dataKey||!ee.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ve,...Ce}=Z;return Ce}const pe=`${ee.dataKey}.${ve}`,Ee=w_(ee.state,pe),xe=Ee!==void 0?Ee:Z.value,ke=r.getMetadata(s.name)?.bindingType,Me=typeof xe=="boolean"&&(ke==="checked"||ke==="checkable"&&["checkbox","radio"].includes(Z?.type)),Re=ee.debounce,tt=Ve=>{const Ce=ee.state||{},He=Ry(Ce,pe,Ve);if(ee.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=_x(He,window.__g7ForcedLocalFields,pe,Ve),ee.setState(He),ee._isGlobal)return;const nt=window.G7Core,Lt={[pe]:Ve};ee.trackChanges&&(Lt.hasChanges=!0),nt?.state?.setLocal?.(Lt,{render:!1})},Pe=(Ve,Ce)=>{Re&&Re>0?(it.current&&clearTimeout(it.current),it.current=setTimeout(()=>{tt(Ve),it.current=null,Ce&&(Ce(),window.__g7PendingLocalState=null)},Re)):(tt(Ve),Ce&&(Ce(),window.__g7PendingLocalState=null))};if(Me)return{...Z,checked:xe,onChange:Ce=>{const He=Ce.target.checked;tt(He),Z.onChange&&Z.onChange(Ce)}};{const Ve=He=>{const nt=He?.target?.value!==void 0?He.target.value:He;Re&&Re>0&&(Pn.current=nt);const Lt=He?.target?{target:{value:nt,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:nt,name:He.currentTarget.name}:void 0}:He;Pe(nt,()=>{Z.onChange&&Z.onChange(Lt)})};let Ce;return Pn.current!==void 0?it.current!==null?Ce=Pn.current:String(xe??"")===String(Pn.current)?(Pn.current=void 0,Ce=xe??""):Ce=Pn.current:Ce=xe??"",{...Z,value:Ce,onChange:Ve}}},[bt,ee,ee.state,ee.debounce]),da=I.useMemo(()=>{const V=oa();if(V?.isEnabled()&&V.trackRender(s.name),!$e)return T.iteration?dr:null;if(T.sortable&&T.itemTemplate)return ua;if(T.iteration)return dr;if(T.type==="extension_point"){const{layout:ke,columns:Me,gap:Re,className:tt,...Pe}=T.props||{};let Ve=tt||"";return ke==="grid"&&Me?Ve=`${Ve} grid grid-cols-${Me} gap-${Re||4}`.trim():ke==="flex"&&(Ve=`${Ve} flex flex-col gap-${Re||4}`.trim()),yt.jsx("div",{id:qe,className:Ve||void 0,...Pe,children:kn})}const ie=r.getComponent(T.name);if(!ie)return lt.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,Z={...vn,id:vn.id??qe,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(H?.listeners&&H.handle&&vn["data-drag-handle"]!==void 0&&(Object.assign(Z,H.listeners),Z.style={...Z.style,cursor:H.isDragging?"grabbing":"grab"}),v){const ke=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,Me=Pe=>{typeof Pe.preventDefault=="function"&&Pe.preventDefault(),S&&(Pe.stopPropagation(),S(ke,Pe))},Re={"data-editor-id":ke,"data-editor-name":T.name,"data-editor-type":T.type,onClick:Me};D&&(Re["data-editor-path"]=D);const tt=T.__editorSlotName??T.slot;typeof tt=="string"&&(Re["data-editor-slot"]=tt),_&&(Re.onMouseMove=Pe=>{Pe.stopPropagation(),_(ke,Pe)},Re.onMouseLeave=Pe=>{_(null,Pe)}),Object.assign(Z,Re),Z.editorAttrs=Re}const ve=T.type==="basic",pe=T.type==="layout",xe=ve||pe?(()=>{const ke={};for(const[Me,Re]of Object.entries(Z))Me.startsWith("__")||Me==="editorAttrs"&&ve||(ke[Me]=Re);return ke})():Z;let Ke=yt.jsx(ie,{...xe,children:kn});if(mt&&(Ke=yt.jsx(v_,{value:mt,children:Ke})),T.isolatedState){const ke=typeof T.isolatedState=="object"?T.isolatedState:{},Me=e?._isolatedInit,Re=Me?{...ke,...Me}:ke;Ke=yt.jsx(T_,{initialState:Re,scopeId:T.isolatedScopeId,children:Ke})}return Ke},[$e,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,r,vn,kn,dr,ua,H,Mn,v,S,_,x,A,D,e._global?._remountKeys]),fr=I.useMemo(()=>{const V=T.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const Z=at(V);if(Z!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,se,ve)}catch(ve){return lt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${T.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(Ee=>e[Ee]===void 0);if(ue)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(pe=>!Z.includes(pe)&&!pe.startsWith("_")).some(pe=>e[pe]===void 0)}if(ue)return!0;const ie=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!ie.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[T.blur_until_loaded,T.id,ue,e,se,i,at]);if(fr){const V=T.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,pe)=>(ve[pe]=e[pe]===void 0?"UNDEFINED":"LOADED",ve),{}),Z=Object.keys(e).filter(ve=>!ve.startsWith("_"));lt.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",Z)}else lt.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,V)}const un=I.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=Yt?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const ie=[/^(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 pe of ce)ie.some(xe=>xe.test(pe))?Z.push(pe):ve.push(pe);return{wrapperClasses:Z.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Yt?.className]),Rn=window.__slotContextValue;return Te&&Rn?.isEnabled?null:yt.jsx(xx,{componentId:s.id,componentName:s.name,children:T.blur_until_loaded?yt.jsx("div",{className:[un.wrapperClasses,fr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:da}):da})});Vr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Vr);function Tx(s){const e={};try{const r=new URL(s,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const c=r.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function kx(s){try{return new URL(s,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return s.split("?")[0]}}const Li=class Li{constructor(){M(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});M(this,"stateHistory",[]);M(this,"snapshotIdCounter",0);M(this,"stateWatchers",new Map);M(this,"currentLocalState",{});M(this,"currentComputedState",{});M(this,"currentParentContext");M(this,"actionHistory",[]);M(this,"actionWatchers",new Set);M(this,"cacheStats",{hits:0,misses:0,entries:0});M(this,"cacheDecisions",[]);M(this,"cacheDecisionIdCounter",0);M(this,"maxCacheDecisions",200);M(this,"currentRenderCycleId",null);M(this,"isInActionExecution",!1);M(this,"isInIteration",!1);M(this,"mountedComponents",new Map);M(this,"eventListeners",new Map);M(this,"mountWatchers",new Set);M(this,"unmountWatchers",new Set);M(this,"renderCounts",new Map);M(this,"bindingEvalCount",0);M(this,"profilingData",[]);M(this,"isProfiling",!1);M(this,"profilingStartTime",0);M(this,"activeRequests",new Map);M(this,"requestHistory",[]);M(this,"pendingDataSources",new Set);M(this,"requestWatchers",new Set);M(this,"wsConnections",new Map);M(this,"wsMessageHistory",[]);M(this,"wsMessageWatchers",new Set);M(this,"ifConditions",new Map);M(this,"iterations",new Map);M(this,"conditionWatchers",new Set);M(this,"forms",new Map);M(this,"formWatchers",new Set);M(this,"expressionHistory",[]);M(this,"expressionWatchers",new Set);M(this,"expressionIdCounter",0);M(this,"dataSources",new Map);M(this,"dataPathTransforms",[]);M(this,"maxDataPathTransforms",100);M(this,"nestedContexts",[]);M(this,"nestedContextIdCounter",0);M(this,"maxNestedContexts",100);M(this,"formBindingIssues",[]);M(this,"formBindingValidations",[]);M(this,"formBindingIssueIdCounter",0);M(this,"maxFormBindingIssues",100);M(this,"computedProperties",new Map);M(this,"computedRecalcLogs",[]);M(this,"computedRecalcIdCounter",0);M(this,"maxComputedRecalcLogs",100);M(this,"handlers",new Map);M(this,"componentEventSubscriptions",new Map);M(this,"componentEventEmitHistory",[]);M(this,"componentEventIdCounter",0);M(this,"maxComponentEventHistory",100);M(this,"stateRenderingLogs",[]);M(this,"currentStateChangeContext",null);M(this,"stateRenderingIdCounter",0);M(this,"componentRenderCounts",new Map);M(this,"stateToComponentMap",new Map);M(this,"maxStateRenderingLogs",100);M(this,"componentStateSources",new Map);M(this,"contextFlowNodes",new Map);M(this,"dynamicStates",new Map);M(this,"styleIssues",[]);M(this,"componentStyles",new Map);M(this,"authEvents",[]);M(this,"authHeaderHistory",[]);M(this,"authEventIdCounter",0);M(this,"maxAuthEventHistory",50);M(this,"logHistory",[]);M(this,"logIdCounter",0);M(this,"maxLogHistory",500);M(this,"currentLayout",null);M(this,"layoutHistory",[]);M(this,"layoutIdCounter",0);M(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});M(this,"maxLayoutHistory",50);M(this,"executionDetails",new Map);M(this,"stateChangeHistory",[]);M(this,"dataSourceChangeHistory",[]);M(this,"changeAlerts",[]);M(this,"changeExpectations",new Map);M(this,"executionIdCounter",0);M(this,"stateChangeIdCounter",0);M(this,"alertIdCounter",0);M(this,"maxExecutionDetails",100);M(this,"maxStateChangeHistory",200);M(this,"maxChangeAlerts",100);M(this,"sequenceExecutions",[]);M(this,"sequenceExecutionStack",[]);M(this,"sequenceIdCounter",0);M(this,"maxSequenceExecutions",50);M(this,"staleClosureWarnings",[]);M(this,"staleClosureIdCounter",0);M(this,"maxStaleClosureWarnings",100);M(this,"stateCaptureRegistry",new Map);M(this,"modalStates",new Map);M(this,"modalStateIssues",[]);M(this,"modalStateRelations",[]);M(this,"modalStateChangeLogs",[]);M(this,"modalStateIssueIdCounter",0);M(this,"modalStateChangeLogIdCounter",0);M(this,"maxModalStateIssues",100);M(this,"maxModalStateChangeLogs",200);M(this,"namedActionDefinitions",{});M(this,"namedActionRefLogs",[]);M(this,"namedActionRefIdCounter",0);M(this,"maxNamedActionRefLogs",200);M(this,"debounceActionHistory",[]);M(this,"dataSourceUpdateHistory",[]);M(this,"debounceActionIdCounter",0);M(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return Li.instance||(Li.instance=new Li),Li.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 r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._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?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r: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 r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=r?`${r}.${c}`:c,f=e?.[c],h=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=h&&typeof h=="object"&&!Array.isArray(h);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,h,d));else{const v=f===void 0?"__undefined__":JSON.stringify(f),S=h===void 0?"__undefined__":JSON.stringify(h);v!==S&&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(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=r?`${r}.${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=r?`${r}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.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(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[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:r}}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,r=0,i=0,l=0;const c={},d={};for(const h of e)h.decision==="cache_hit"?n++:h.decision==="cache_miss"?r++:h.decision==="skip_cache"?i++:h.decision==="invalidate"&&l++,c[h.reason]=(c[h.reason]||0)+1,h.context.componentId&&(d[h.context.componentId]=(d[h.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.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 r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,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),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.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 r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.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(h=>h.type==="render"),r=this.profilingData.filter(h=>h.type==="binding"),i=this.profilingData.filter(h=>h.type==="action"),l={};for(const h of n)h.component&&(l[h.component]||(l[h.component]={count:0,durations:[]}),l[h.component].count++,h.duration&&l[h.component].durations.push(h.duration));const c=Object.entries(l).map(([h,m])=>({name:h,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,v)=>y+v,0)/m.durations.length:0})).sort((h,m)=>m.renderCount-h.renderCount).slice(0,10),d={};for(const h of r)h.expression&&(d[h.expression]=(d[h.expression]||0)+1);const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,10).map(([h])=>h);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=kx(e),c=Tx(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){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(r)};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 r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.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(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,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(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,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=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._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(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,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(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const h=[];let m=!0;return f.name||(h.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||(h.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:h}});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 r=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:r}}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,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,h={id:f,name:e,expression:n,componentId:c,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,h)}trackComputedRecalc(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,h=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:h,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 r=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),r.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};r.add(m),i.push(m);const v=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(v)for(const _ of v.dependencies)_.type==="computed"?S.push(f(_.path,y+1)):S.push({name:_.path,type:_.type,children:[],depth:y+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:y}},h=f(e,0);return{root:e,tree:h,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const h of this.computedRecalcLogs)e[h.trigger]++,h.valueChanged||l++,n[h.computedName]=(n[h.computedName]||0)+1,r[h.computedName]||(r[h.computedName]=[]),r[h.computedName].push(h.computationTime),i+=h.computationTime;const c=Object.entries(n).sort((h,m)=>m[1]-h[1]).slice(0,5).map(([h,m])=>({name:h,count:m})),d=Object.entries(r).map(([h,m])=>({name:h,avgTime:m.reduce((y,v)=>y+v,0)/m.length})).sort((h,m)=>m.avgTime-h.avgTime).slice(0,5);let f=0;for(const h of this.computedProperties.values())this.analyzeComputedDependencyChain(h.name,h.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 r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.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 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.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 r=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:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&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 r=e.initialState[n],i=e.currentState[n];if(r!==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:r})}}}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},r={"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]++,r[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:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["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 r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);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:r,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(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).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(h=>h.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(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=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 r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,h)=>f+h,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(r){console.error("[G7DevTools] Expression watcher error:",r)}})}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 r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){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(r=>r.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,r){if(!this.config.enabled)return;const i=r.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(r),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(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)r[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:r,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,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=r;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 r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,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(r=>r.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 r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.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 r=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,r+=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:r,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}`,r=[...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:r,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 r=this.nestedContexts.find(i=>i.id===e);r&&r.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 r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=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:r,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,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),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}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,r,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,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,r)=>n+r.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,r,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(r),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,r,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:r,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),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,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),r=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:r,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(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,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(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=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(r>=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,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,r+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._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(r._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[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)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 h=r.values[d];if(JSON.stringify(h)!==JSON.stringify(f)){const m=[],y=[];for(const v of this.componentStateSources.values())v.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(v.stateProvider.type==="dynamicState"?m.push(v.componentName):v.stateProvider.type==="globalState"&&y.push(v.componentName));n.push({path:`_local.${d}`,globalValue:h,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 r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);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,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),c={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],r=[],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 h of c)if(f.startsWith(h)){r.push(f);break}for(const h of d)if(h.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,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:r,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:r,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:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.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,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:r,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 r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=r?.getUser?.();if(d&&(c="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(c="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let h="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?h="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(h="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 v=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.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:v,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:h,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,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.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()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),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,r,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=r,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||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,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,r,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:r,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,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of r.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 r.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 r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let c=!1,d;return!l&&(r==="object"||r==="array")?(c=this.deepEqual(e,n),!c&&r==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:r,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 r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.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 r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.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()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:r,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,r,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(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._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 h=window.__g7PendingLocalState;h&&(f.pendingState=this.safeClone(h)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];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(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||r.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const h=e[f],m=n[f];JSON.stringify(h)!==JSON.stringify(m)&&l.push({path:f,oldValue:h,newValue:m})}return{added:r,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,r=e.filter(h=>h.status==="success").length,i=e.filter(h=>h.status==="error").length,l=e.reduce((h,m)=>h+m.actions.length,0),c=n>0?e.reduce((h,m)=>h+m.totalDuration,0)/n:0,d={};for(const h of e)for(const m of h.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,5).map(([h,m])=>({handler:h,count:m}));return{totalExecutions:n,successCount:r,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(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(r[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[h,m]of c){const y=this.getValueByPath(r,h),v=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&v>0){const S=this.createStaleClosureWarning(i,n,h,m.value,m.capturedAt,y,d,v,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,c,d,f,h,m){const y=this.getStaleClosureSeverity(e,f),{description:v,suggestion:S,docLink:_}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:v,suggestion:S,docLink:_,actionId:h,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,r){const i=r<1e3?`${r}ms`:`${(r/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 r=n.split(".");let i=e;for(const l of r){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 r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({location:f,count:h})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({path:f,count:h}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.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(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};M(Li,"instance");let za=Li;const Xn=pt("LayoutLoader");class Rr extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="LayoutLoaderError"}}class ah{constructor(e){M(this,"componentRegistry");M(this,"currentLayout",null);M(this,"layoutCache",new Map);M(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Xn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Xn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,za.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const v=n.replace("__preview__/","");l=Ur(`/api/layouts/preview/${v}`,"json",i)}else l=Ur(`/api/layouts/${e}/${n}`,"json",i);Xn.log("Fetching layout from API:",l);const c=qr(),d=r?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const h=await nc(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await h.json()}catch{m=null}if(!h.ok){if(h.status===401&&!r&&d){Xn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof Rr&&S.details?.status===401?new Rr(S.message,S.code,{...S.details,hadToken:!0}):S}}const v=m?.message||m?.error;throw new Rr(`Failed to fetch layout: ${h.status} ${h.statusText}`,"FETCH_FAILED",{status:h.status,statusText:h.statusText,url:l,apiMessage:v})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,za.getInstance().trackLayoutLoad(n,e,y,"api"),Xn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Rr?i:new Rr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Rr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Rr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Rr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Xn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new Rr("No layout data to render","NO_LAYOUT_DATA");Xn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Xn.log("Layout rendered successfully")}catch(r){Xn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Xn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Xn.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}

@@ -105,8 +105,8 @@ Error generating stack: `+u.message+` " >페이지 새로고침 - `,Xn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Xn.log("Layout data and cache cleared")}}const kx=pt("TranslationContext"),ih=I.createContext(null),Uc=({children:s,translationEngine:e,translationContext:n})=>{const r=I.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,h])=>`${f}=${h}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=I.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return yt.jsx(ih.Provider,{value:i,children:s})},gb=()=>{const s=I.useContext(ih);return s||(kx.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Pa=pt("SlotContext"),Rx={registerToSlot:()=>{Pa.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Pa.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},Dx=I.createContext(Rx),sh=({children:s})=>{const e=I.useRef(new Map),n=I.useRef(new Map),r=I.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(v=>{try{v()}catch(S){Pa.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=I.useCallback((m,y,v)=>{if(!m||!y){Pa.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),_=S.get(y);_&&_.registrationKey===v.registrationKey||(S.set(y,v),Pa.log(`Component registered to slot: ${y} -> ${m} (order: ${v.order})`),r(m))},[r]),l=I.useCallback((m,y)=>{const v=e.current.get(m);v&&v.has(y)&&(v.delete(y),Pa.log(`Component unregistered from slot: ${y} <- ${m}`),v.size===0&&e.current.delete(m),r(m))},[r]),c=I.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((v,S)=>v.order-S.order):[]},[]),d=I.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const v=n.current.get(m);return v.add(y),()=>{v.delete(y),v.size===0&&n.current.delete(m)}},[]),f=I.useCallback(()=>{e.current.forEach((m,y)=>{r(y)}),e.current.clear(),n.current.clear(),Pa.log("All slots cleared")},[r]),h=I.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return I.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=h,Pa.log("SlotContext exposed to window.__slotContextValue"))},[h]),yt.jsx(Dx.Provider,{value:h,children:s})};class oh{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 mb{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 Ox(s){try{return Reflect.construct(String,[],s),!0}catch{return!1}}class lh extends oh{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,this.eventFormatter=new mb(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,r)=>{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,r)}),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 yb extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class Lx extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class $x extends yb{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),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 bb extends oh{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,this.eventFormatter=new mb(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]=(r,i)=>{this.name===r&&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(r=>r!==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 vb extends bb{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class Mx extends vb{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.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 Bc extends oh{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 Sb extends Bc{whisper(e,n){return this}}class Nx extends Bc{whisper(e,n){return this}}class Ix extends Sb{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Jc=class Jc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Jc._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}};Jc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Wo=Jc;class qc extends Wo{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,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new lh(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new yb(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new Lx(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new $x(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())},r=["state_change","connected","disconnected"];return r.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{r.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class jx extends Wo{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,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new bb(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new vb(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Mx(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())},r=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return r.forEach(i=>{this.socket.on(i,n)}),()=>{r.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class wb extends Wo{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new Bc}channel(e){return new Bc}privateChannel(e){return new Sb}encryptedPrivateChannel(e){return new Nx}presenceChannel(e){return new Ix}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class Hx{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 qc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new qc(this.options);else if(this.options.broadcaster==="ably")this.connector=new qc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new jx(this.options);else if(this.options.broadcaster==="null")this.connector=new wb(this.options);else if(typeof this.options.broadcaster=="function"&&Ox(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,r){return this.connector.listen(e,n,r)}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 qc||e instanceof wb}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,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var ch={exports:{}};var Cb;function zx(){return Cb||(Cb=1,(function(s,e){(function(r,i){s.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var O=function(k,L){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,q){B.__proto__=q}||function(B,q){for(var z in q)q.hasOwnProperty(z)&&(B[z]=q[z])},O(k,L)};return function(k,L){O(k,L);function B(){this.constructor=k}k.prototype=L===null?Object.create(L):(B.prototype=L.prototype,new B)}})();Object.defineProperty(d,"__esModule",{value:!0});var h=256,m=(function(){function O(k){k===void 0&&(k="="),this._paddingCharacter=k}return O.prototype.encodedLength=function(k){return this._paddingCharacter?(k+2)/3*4|0:(k*8+5)/6|0},O.prototype.encode=function(k){for(var L="",B=0;B>>18&63),L+=this._encodeByte(q>>>12&63),L+=this._encodeByte(q>>>6&63),L+=this._encodeByte(q>>>0&63)}var z=k.length-B;if(z>0){var q=k[B]<<16|(z===2?k[B+1]<<8:0);L+=this._encodeByte(q>>>18&63),L+=this._encodeByte(q>>>12&63),z===2?L+=this._encodeByte(q>>>6&63):L+=this._paddingCharacter||"",L+=this._paddingCharacter||""}return L},O.prototype.maxDecodedLength=function(k){return this._paddingCharacter?k/4*3|0:(k*6+7)/8|0},O.prototype.decodedLength=function(k){return this.maxDecodedLength(k.length-this._getPaddingLength(k))},O.prototype.decode=function(k){if(k.length===0)return new Uint8Array(0);for(var L=this._getPaddingLength(k),B=k.length-L,q=new Uint8Array(this.maxDecodedLength(B)),z=0,W=0,de=0,_e=0,Se=0,Ie=0,Fe=0;W>>4,q[z++]=Se<<4|Ie>>>2,q[z++]=Ie<<6|Fe,de|=_e&h,de|=Se&h,de|=Ie&h,de|=Fe&h;if(W>>4,de|=_e&h,de|=Se&h),W>>2,de|=Ie&h),W>>8&6,L+=51-k>>>8&-75,L+=61-k>>>8&-15,L+=62-k>>>8&3,String.fromCharCode(L)},O.prototype._decodeChar=function(k){var L=h;return L+=(42-k&k-44)>>>8&-h+k-43+62,L+=(46-k&k-48)>>>8&-h+k-47+63,L+=(47-k&k-58)>>>8&-h+k-48+52,L+=(64-k&k-91)>>>8&-h+k-65+0,L+=(96-k&k-123)>>>8&-h+k-97+26,L},O.prototype._getPaddingLength=function(k){var L=0;if(this._paddingCharacter){for(var B=k.length-1;B>=0&&k[B]===this._paddingCharacter;B--)L++;if(k.length<4||L>2)throw new Error("Base64Coder: incorrect padding")}return L},O})();d.Coder=m;var y=new m;function v(O){return y.encode(O)}d.encode=v;function S(O){return y.decode(O)}d.decode=S;var _=(function(O){f(k,O);function k(){return O!==null&&O.apply(this,arguments)||this}return k.prototype._encodeByte=function(L){var B=L;return B+=65,B+=25-L>>>8&6,B+=51-L>>>8&-75,B+=61-L>>>8&-13,B+=62-L>>>8&49,String.fromCharCode(B)},k.prototype._decodeChar=function(L){var B=h;return B+=(44-L&L-46)>>>8&-h+L-45+62,B+=(94-L&L-96)>>>8&-h+L-95+63,B+=(47-L&L-58)>>>8&-h+L-48+52,B+=(64-L&L-91)>>>8&-h+L-65+0,B+=(96-L&L-123)>>>8&-h+L-97+26,B},k})(m);d.URLSafeCoder=_;var x=new _;function A(O){return x.encode(O)}d.encodeURLSafe=A;function D(O){return x.decode(O)}d.decodeURLSafe=D,d.encodedLength=function(O){return y.encodedLength(O)},d.maxDecodedLength=function(O){return y.maxDecodedLength(O)},d.decodedLength=function(O){return y.decodedLength(O)}},978(c,d){var f="utf8: invalid source encoding";function h(m){for(var y=[],v=0;v=m.length)throw new Error(f);var x=m[++v];if((x&192)!==128)throw new Error(f);S=(S&31)<<6|x&63,_=128}else if(S<240){if(v>=m.length-1)throw new Error(f);var x=m[++v],A=m[++v];if((x&192)!==128||(A&192)!==128)throw new Error(f);S=(S&15)<<12|(x&63)<<6|A&63,_=2048}else if(S<248){if(v>=m.length-2)throw new Error(f);var x=m[++v],A=m[++v],D=m[++v];if((x&192)!==128||(A&192)!==128||(D&192)!==128)throw new Error(f);S=(S&15)<<18|(x&63)<<12|(A&63)<<6|D&63,_=65536}else throw new Error(f);if(S<_||S>=55296&&S<=57343)throw new Error(f);if(S>=65536){if(S>1114111)throw new Error(f);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}d.D4=h},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>Is});class h{constructor(b,w){this.lastId=0,this.prefix=b,this.name=w}create(b){this.lastId++;var w=this.lastId,$=this.prefix+w,N=this.name+"["+w+"]",ne=!1,ye=function(){ne||(b.apply(null,arguments),ne=!0)};return this[w]=ye,{number:w,id:$,name:N,callback:ye}}remove(b){delete this[b.number]}}var m=new h("_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 v=y;class S{constructor(b){this.options=b,this.receivers=b.receivers||m,this.loading={}}load(b,w,$){var N=this;if(N.loading[b]&&N.loading[b].length>0)N.loading[b].push($);else{N.loading[b]=[$];var ne=Ue.createScriptRequest(N.getPath(b,w)),ye=N.receivers.create(function(Le){if(N.receivers.remove(ye),N.loading[b]){var We=N.loading[b];delete N.loading[b];for(var ft=function(Vt){Vt||ne.cleanup()},vt=0;vt>>6)+Q(128|b&63):Q(224|b>>>12&15)+Q(128|b>>>6&63)+Q(128|b&63)},ee=function(E){return E.replace(/[^\x00-\x7F]/g,De)},me=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),$=[ue.charAt(w>>>18),ue.charAt(w>>>12&63),b>=2?"=":ue.charAt(w>>>6&63),b>=1?"=":ue.charAt(w&63)];return $.join("")},H=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,me)};class T{constructor(b,w,$,N){this.clear=w,this.timer=b(()=>{this.timer&&(this.timer=N(this.timer))},$)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const fe=T;function he(E){window.clearTimeout(E)}function Ae(E){window.clearInterval(E)}class se extends fe{constructor(b,w){super(setTimeout,he,b,function($){return w(),null})}}class ge extends fe{constructor(b,w){super(setInterval,Ae,b,function($){return w(),$})}}var $e={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new se(0,E)},method(E,...b){var w=Array.prototype.slice.call(arguments,1);return function($){return $[E].apply($,w.concat(arguments))}}};const Te=$e;function je(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 $=xt.apply(this,arguments);Is.log?Is.log($):Is.logToConsole&&b.bind(this)($)}}const it=new Mn;var Pn=function(E,b,w,$,N){(w.headers!==void 0||w.headersProvider!=null)&&it.warn(`To send headers with the ${$.toString()} request, you must use AJAX, rather than JSONP.`);var ne=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var ye=E.getDocument(),Le=ye.createElement("script");E.auth_callbacks[ne]=function(vt){N(null,vt)};var We="Pusher.auth_callbacks['"+ne+"']";Le.src=w.endpoint+"?callback="+encodeURIComponent(We)+"&"+b;var ft=ye.getElementsByTagName("head")[0]||ye.documentElement;ft.insertBefore(Le,ft.firstChild)};const vn=Pn;class da{constructor(b){this.src=b}send(b){var w=this,$="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($)},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+"('"+$+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var N=document.getElementsByTagName("head")[0];N.insertBefore(w.script,N.firstChild),w.errorScript&&N.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 fr{constructor(b,w){this.url=b,this.data=w}send(b){if(!this.request){var w=Li(this.data),$=this.url+"/"+b.number+"?"+w;this.request=Ue.createScriptRequest($),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var un=function(E,b){return function(w,$){var N="http"+(b?"s":"")+"://",ne=N+(E.host||E.options.host)+E.options.path,ye=Ue.createJSONPRequest(ne,w),Le=Ue.ScriptReceivers.create(function(We,ft){m.remove(Le),ye.cleanup(),ft&&ft.host&&(E.host=ft.host),$&&$(We,ft)});ye.send(Le)}},Rn={name:"jsonp",getAgent:un};const dn=Rn;function V(E,b,w){var $=E+(b.useTLS?"s":""),N=b.useTLS?b.hostTLS:b.hostNonTLS;return $+"://"+N+w}function ie(E,b){var w="/app/"+E,$="?protocol="+v.PROTOCOL+"&client=js&version="+v.VERSION+(b?"&"+b:"");return w+$}var ce={getInitial:function(E,b){var w=(b.httpPath||"")+ie(E,"flash=false");return V("ws",b,w)}},Z={getInitial:function(E,b){var w=(b.httpPath||"/pusher")+ie(E);return V("http",b,w)}},ve={getInitial:function(E,b){return V("http",b,b.httpPath||"/pusher")},getPath:function(E,b){return ie(E)}};class pe{constructor(){this._callbacks={}}get(b){return this._callbacks[Ee(b)]}add(b,w,$){var N=Ee(b);this._callbacks[N]=this._callbacks[N]||[],this._callbacks[N].push({fn:w,context:$})}remove(b,w,$){if(!b&&!w&&!$){this._callbacks={};return}var N=b?[Ee(b)]:at(this._callbacks);w||$?this.removeCallback(N,w,$):this.removeAllCallbacks(N)}removeCallback(b,w,$){Ht(b,function(N){this._callbacks[N]=mt(this._callbacks[N]||[],function(ne){return w&&w!==ne.fn||$&&$!==ne.context}),this._callbacks[N].length===0&&delete this._callbacks[N]},this)}removeAllCallbacks(b){Ht(b,function(w){delete this._callbacks[w]},this)}}function Ee(E){return"_"+E}class xe{constructor(b){this.callbacks=new pe,this.global_callbacks=[],this.failThrough=b}bind(b,w,$){return this.callbacks.add(b,w,$),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,w,$){return this.callbacks.remove(b,w,$),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,$){for(var N=0;N0)for(var N=0;N{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),it.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"?(Te.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 je({cid:this.id},b)}}class ke{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,w,$,N){return new Ke(this.hooks,b,w,$,N)}}var Me=new ke({urls:ce,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Ue.getWebSocketAPI()},isSupported:function(){return!!Ue.getWebSocketAPI()},getSocket:function(E){return Ue.createWebSocket(E)}}),Re={urls:Z,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},tt=je({getSocket:function(E){return Ue.HTTPFactory.createStreamingSocket(E)}},Re),Pe=je({getSocket:function(E){return Ue.HTTPFactory.createPollingSocket(E)}},Re),Ve={isSupported:function(){return Ue.isXHRSupported()}},Ce=new ke(je({},tt,Ve)),He=new ke(je({},Pe,Ve)),nt={ws:Me,xhr_streaming:Ce,xhr_polling:He};const Lt=nt;var Bt=new ke({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:x.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(E,b){E.send(JSON.stringify({path:b}))}}),Nn={isSupported:function(E){var b=Ue.isXDRSupported(E.useTLS);return b}},Gt=new ke(je({},tt,Nn)),Ft=new ke(je({},Pe,Nn));Lt.xdr_streaming=Gt,Lt.xdr_polling=Ft,Lt.sockjs=Bt;const Dn=Lt;class Ba extends xe{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 rl=new Ba;class mh{constructor(b,w,$){this.manager=b,this.transport=w,this.minPingDelay=$.minPingDelay,this.maxPingDelay=$.maxPingDelay,this.pingDelay=void 0}createConnection(b,w,$,N){N=je({},N,{activityTimeout:this.pingDelay});var ne=this.transport.createConnection(b,w,$,N),ye=null,Le=function(){ne.unbind("open",Le),ne.bind("closed",We),ye=Te.now()},We=ft=>{if(ne.unbind("closed",We),ft.code===1002||ft.code===1003)this.manager.reportDeath();else if(!ft.wasClean&&ye){var vt=Te.now()-ye;vt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(vt/2,this.minPingDelay))}};return ne.bind("open",Le),ne}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const Zc={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 $={event:b.event,channel:b.channel,data:w};return b.user_id&&($.user_id=b.user_id),$}catch(N){throw{type:"MessageParseError",error:N,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var b=Zc.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}},Yr=Zc;class $i extends xe{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,$){var N={event:b,data:w};return $&&(N.channel=$),it.debug("Event sent",N),this.send(Yr.encodeMessage(N))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:$=>{var N;try{N=Yr.decodeMessage($)}catch(ne){this.emit("error",{type:"MessageParseError",error:ne,data:$.data})}if(N!==void 0){switch(it.debug("Event recd",N),N.event){case"pusher:error":this.emit("error",{type:"PusherError",data:N.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",N)}},activity:()=>{this.emit("activity")},error:$=>{this.emit("error",$)},closed:$=>{w(),$&&$.code&&this.handleCloseEvent($),this.transport=null,this.emit("closed")}},w=()=>{gt(b,($,N)=>{this.transport.unbind(N,$)})};gt(b,($,N)=>{this.transport.bind(N,$)})}handleCloseEvent(b){var w=Yr.getCloseAction(b),$=Yr.getCloseError(b);$&&this.emit("error",$),w&&this.emit(w,{action:w,error:$})}}class al{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=Yr.processHandshake(b)}catch($){this.finish("error",{error:$}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new $i(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var w=Yr.getCloseAction(b)||"backoff",$=Yr.getCloseError(b);this.finish(w,{error:$})},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(je({transport:this.transport,action:b},w))}}class qa{constructor(b,w){this.timeline=b,this.options=w||{}}send(b,w){this.timeline.isEmpty()||this.timeline.send(Ue.TimelineTransport.getAgent(this,b),w)}}class Xr extends xe{constructor(b,w){super(function($,N){it.debug("No callbacks on "+b+" for "+$)}),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 L("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var $=O.buildLogSuffix("triggeringClientEvents");it.warn(`Client event triggered before channel 'subscription_succeeded' event . ${$}`)}return this.pusher.send_event(b,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var w=b.event,$=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 N={};this.emit(w,$,N)}}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,it.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof Ie?{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 fa extends Xr{authorize(b,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},w)}}class Ga{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){gt(this.members,(w,$)=>{b(this.get($))})}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 nn=function(E,b,w,$){function N(ne){return ne instanceof w?ne:new w(function(ye){ye(ne)})}return new(w||(w=Promise))(function(ne,ye){function Le(vt){try{ft($.next(vt))}catch(Vt){ye(Vt)}}function We(vt){try{ft($.throw(vt))}catch(Vt){ye(Vt)}}function ft(vt){vt.done?ne(vt.value):N(vt.value).then(Le,We)}ft(($=$.apply(E,b||[])).next())})};class eu extends fa{constructor(b,w){super(b,w),this.members=new Ga}authorize(b,w){super.authorize(b,($,N)=>nn(this,void 0,void 0,function*(){if(!$)if(N=N,N.channel_data!=null){var ne=JSON.parse(N.channel_data);this.members.setMyID(ne.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 ye=O.buildLogSuffix("authorizationEndpoint");it.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),w("Invalid auth response");return}w($,N)}))}handleEvent(b){var w=b.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var $=b.data,N={};b.user_id&&(N.user_id=b.user_id),this.emit(w,$,N)}}handleInternalEvent(b){var w=b.event,$=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 N=this.members.addMember($);this.emit("pusher:member_added",N);break;case"pusher_internal:member_removed":var ne=this.members.removeMember($);ne&&this.emit("pusher:member_removed",ne);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 tu=f(978),$r=f(594);class Fa extends fa{constructor(b,w,$){super(b,w),this.key=null,this.nacl=$}authorize(b,w){super.authorize(b,($,N)=>{if($){w($,N);return}let ne=N.shared_secret;if(!ne){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,$r.decode)(ne),delete N.shared_secret,w(null,N)})}trigger(b,w){throw new de("Client events are not currently supported for encrypted channels")}handleEvent(b){var w=b.event,$=b.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(w,$)}handleEncryptedEvent(b,w){if(!this.key){it.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){it.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let $=(0,$r.decode)(w.ciphertext);if($.length{if(ye){it.error(`Failed to make a request to the authEndpoint: ${Le}. Unable to fetch new key, so dropping encrypted event`);return}if(ne=this.nacl.secretbox.open($,N,this.key),ne===null){it.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(ne))});return}this.emit(b,this.getDataToEmit(ne))}getDataToEmit(b){let w=(0,tu.D4)(b);try{return JSON.parse(w)}catch{return w}}}class yh extends xe{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 $=Ue.getNetwork();$.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),$.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,$){return this.connection?this.connection.send_event(b,w,$):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(w,$)=>{w?this.runner=this.strategy.connect(0,b):$.action==="error"?(this.emit("error",{type:"HandshakeError",error:$.error}),this.timeline.error({handshakeError:$.error})):(this.abortConnecting(),this.handshakeCallbacks[$.action]($))};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 se(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new se(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new se(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 se(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return je({},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 je({},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=>$=>{$.error&&this.emit("error",{type:"WebSocketError",error:$.error}),w($)};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 $=this.state;if(this.state=b,$!==b){var N=b;N==="connected"&&(N+=" with new socket ID "+w.socket_id),it.debug("State changed",$+" -> "+N),this.timeline.info({state:b,params:w}),this.emit("state_change",{previous:$,current:b}),this.emit(b,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class nu{constructor(){this.channels={}}add(b,w){return this.channels[b]||(this.channels[b]=ru(b,w)),this.channels[b]}all(){return Yt(this.channels)}find(b){return this.channels[b]}remove(b){var w=this.channels[b];return delete this.channels[b],w}disconnect(){gt(this.channels,function(b){b.disconnect()})}}function ru(E,b){if(E.indexOf("private-encrypted-")===0){if(b.config.nacl)return Un.createEncryptedChannel(E,b,b.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",$=O.buildLogSuffix("encryptedChannelSupport");throw new de(`${w}. ${$}`)}else{if(E.indexOf("private-")===0)return Un.createPrivateChannel(E,b);if(E.indexOf("presence-")===0)return Un.createPresenceChannel(E,b);if(E.indexOf("#")===0)throw new B('Cannot create a channel with name "'+E+'".');return Un.createChannel(E,b)}}var bh={createChannels(){return new nu},createConnectionManager(E,b){return new yh(E,b)},createChannel(E,b){return new Xr(E,b)},createPrivateChannel(E,b){return new fa(E,b)},createPresenceChannel(E,b){return new eu(E,b)},createEncryptedChannel(E,b,w){return new Fa(E,b,w)},createTimelineSender(E,b){return new qa(E,b)},createHandshake(E,b){return new al(E,b)},createAssistantToTheTransportManager(E,b,w){return new mh(E,b,w)}};const Un=bh;class Mi{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return Un.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Sn{constructor(b,w){this.strategies=b,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){var $=this.strategies,N=0,ne=this.timeout,ye=null,Le=(We,ft)=>{ft?w(null,ft):(N=N+1,this.loop&&(N=N%$.length),N<$.length?(ne&&(ne=ne*2,this.timeoutLimit&&(ne=Math.min(ne,this.timeoutLimit))),ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le)):w(!0))};return ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le),{abort:function(){ye.abort()},forceMinPriority:function(We){b=We,ye&&ye.forceMinPriority(We)}}}tryStrategy(b,w,$,N){var ne=null,ye=null;return $.timeout>0&&(ne=new se($.timeout,function(){ye.abort(),N(!0)})),ye=b.connect(w,function(Le,We){Le&&ne&&ne.isRunning()&&!$.failFast||(ne&&ne.ensureAborted(),N(Le,We))}),{abort:function(){ne&&ne.ensureAborted(),ye.abort()},forceMinPriority:function(Le){ye.forceMinPriority(Le)}}}}class On{constructor(b){this.strategies=b}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){return au(this.strategies,b,function($,N){return function(ne,ye){if(N[$].error=ne,ne){vh(N)&&w(!0);return}Ht(N,function(Le){Le.forceMinPriority(ye.transport.priority)}),w(null,ye)}})}}function au(E,b,w){var $=bt(E,function(N,ne,ye,Le){return N.connect(b,w(ne,Le))});return{abort:function(){Ht($,il)},forceMinPriority:function(N){Ht($,function(ne){ne.forceMinPriority(N)})}}}function vh(E){return dr(E,function(b){return!!b.error})}function il(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class iu{constructor(b,w,$){this.strategy=b,this.transports=w,this.ttl=$.ttl||18e5,this.usingTLS=$.useTLS,this.timeline=$.timeline}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.usingTLS,N=Sh($),ne=N&&N.cacheSkipCount?N.cacheSkipCount:0,ye=[this.strategy];if(N&&N.timestamp+this.ttl>=Te.now()){var Le=this.transports[N.transport];Le&&(["ws","wss"].includes(N.transport)||ne>3?(this.timeline.info({cached:!0,transport:N.transport,latency:N.latency}),ye.push(new Sn([Le],{timeout:N.latency*2+1e3,failFast:!0}))):ne++)}var We=Te.now(),ft=ye.pop().connect(b,function vt(Vt,jr){Vt?(Os($),ye.length>0?(We=Te.now(),ft=ye.pop().connect(b,vt)):w(Vt)):(Bn($,jr.transport.name,Te.now()-We,ne),w(null,jr))});return{abort:function(){ft.abort()},forceMinPriority:function(vt){b=vt,ft&&ft.forceMinPriority(vt)}}}}function Va(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Sh(E){var b=Ue.getLocalStorage();if(b)try{var w=b[Va(E)];if(w)return JSON.parse(w)}catch{Os(E)}return null}function Bn(E,b,w,$){var N=Ue.getLocalStorage();if(N)try{N[Va(E)]=bn({timestamp:Te.now(),transport:b,latency:w,cacheSkipCount:$})}catch{}}function Os(E){var b=Ue.getLocalStorage();if(b)try{delete b[Va(E)]}catch{}}class Ni{constructor(b,{delay:w}){this.strategy=b,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy,N,ne=new se(this.options.delay,function(){N=$.connect(b,w)});return{abort:function(){ne.ensureAborted(),N&&N.abort()},forceMinPriority:function(ye){b=ye,N&&N.forceMinPriority(ye)}}}}class ha{constructor(b,w,$){this.test=b,this.trueBranch=w,this.falseBranch=$}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,w){var $=this.test()?this.trueBranch:this.falseBranch;return $.connect(b,w)}}class Ka{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy.connect(b,function(N,ne){ne&&$.abort(),w(N,ne)});return $}}function Wa(E){return function(){return E.isSupported()}}var su=function(E,b,w){var $={};function N(vl,Su,wu,Uh,Bh){var Cu=w(E,vl,Su,wu,Uh,Bh);return $[vl]=Cu,Cu}var ne=Object.assign({},b,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),ye=Object.assign({},ne,{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},ft=new Mi({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),vt=new Mi({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),Vt=N("ws","ws",3,ne,ft),jr=N("wss","ws",3,ye,ft),Hh=N("sockjs","sockjs",1,Le),bu=N("xhr_streaming","xhr_streaming",1,Le,vt),zh=N("xdr_streaming","xdr_streaming",1,Le,vt),ml=N("xhr_polling","xhr_polling",1,Le),vu=N("xdr_polling","xdr_polling",1,Le),Ja=new Sn([Vt],We),Ui=new Sn([jr],We),Ph=new Sn([Hh],We),Bi=new Sn([new ha(Wa(bu),bu,zh)],We),yl=new Sn([new ha(Wa(ml),ml,vu)],We),bl=new Sn([new ha(Wa(Bi),new On([Bi,new Ni(yl,{delay:4e3})]),yl)],We),qi=new ha(Wa(bl),bl,Ph),Gi;return b.useTLS?Gi=new On([Ja,new Ni(qi,{delay:2e3})]):Gi=new On([Ja,new Ni(Ui,{delay:2e3}),new Ni(qi,{delay:5e3})]),new iu(new Ka(new ha(Wa(Vt),Gi,qi)),$,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})};const Ya=su;function wh(){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"),x.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 ou={getRequest:function(E){var b=new window.XDomainRequest;return b.ontimeout=function(){E.emit("error",new q),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 lu=ou,sl=256*1024;class Ch extends xe{constructor(b,w,$){super(),this.hooks=b,this.method=w,this.url=$}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Ue.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&&(Ue.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,w){for(;;){var $=this.advanceBuffer(w);if($)this.emit("chunk",{status:b,data:$});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(b){var w=b.slice(this.position),$=w.indexOf(` -`);return $!==-1?(this.position+=$+1,w.slice(0,$)):null}isBufferTooLong(b){return this.position===b.length&&b.length>sl}}var ol;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(ol||(ol={}));const hr=ol;var Mr=1;class ll{constructor(b,w){this.hooks=b,this.session=Ls(1e3)+"/"+uu(8),this.location=cl(w),this.readyState=hr.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===hr.OPEN)try{return Ue.createSocketRequest("POST",pa(Xa(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,w,$){this.closeStream(),this.readyState=hr.CLOSED,this.onclose&&this.onclose({code:b,reason:w,wasClean:$})}onChunk(b){if(b.status===200){this.readyState===hr.OPEN&&this.onActivity();var w,$=b.data.slice(0,1);switch($){case"o":w=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(b.data.slice(1)||"[]");for(var N=0;N{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){Te.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 cl(E){var b=/([^\?]*)\/*(\??.*)/.exec(E);return{base:b[1],queryString:b[2]}}function Xa(E,b){return E.base+"/"+b+"/xhr_send"}function pa(E){var b=E.indexOf("?")===-1?"?":"&";return E+b+"t="+ +new Date+"&n="+Mr++}function cu(E,b){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+b+w[3]}function Ls(E){return Ue.randomInt(E)}function uu(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 $s=dl;var du={createStreamingSocket(E){return this.createSocket(ul,E)},createPollingSocket(E){return this.createSocket(Jr,E)},createSocket(E,b){return new Ii(E,b)},createXHR(E,b){return this.createRequest($s,E,b)},createRequest(E,b,w){return new Ch(E,b,w)}};const Hi=du;Hi.createXDR=function(E,b){return this.createRequest(lu,E,b)};var fu={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Ya,Transports:Dn,transportConnectionInitializer:wh,HTTPFactory:Hi,TimelineTransport:dn,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():x.load("json2",{},b)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:ze,jsonp:vn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,b){return new fr(E,b)},createScriptRequest(E){return new da(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 rl},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 $;do $=b.getRandomValues(new Uint32Array(1))[0];while($>=w);return $%E}};const Ue=fu;var Ir;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Ir||(Ir={}));const ga=Ir;class zi{constructor(b,w,$){this.key=b,this.session=w,this.events=[],this.options=$||{},this.sent=0,this.uniqueID=0}log(b,w){b<=this.options.level&&(this.events.push(je({},w,{timestamp:Te.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ga.ERROR,b)}info(b){this.log(ga.INFO,b)}debug(b){this.log(ga.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,w){var $=je({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($,(N,ne)=>{N||this.sent++,w&&w(N,ne)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Eh{constructor(b,w,$,N){this.name=b,this.priority=w,this.transport=$,this.options=N||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,w){if(this.isSupported()){if(this.priority{$||(vt(),ne?ne.close():N.close())},forceMinPriority:Vt=>{$||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},Ah=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=_h(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.UserAuthentication,w)}},pl=(E,b)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},xh=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=pl(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.ChannelAuthorization,w)}},Th=(E,b,w)=>{const $={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(N,ne)=>{const ye=E.channel(N.channelName);w(ye,$).authorize(N.socketId,ne)}};function pu(E,b){let w={activityTimeout:E.activityTimeout||v.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||v.httpPath,httpPort:E.httpPort||v.httpPort,httpsPort:E.httpsPort||v.httpsPort,pongTimeout:E.pongTimeout||v.pongTimeout,statsHost:E.statsHost||v.stats_host,unavailableTimeout:E.unavailableTimeout||v.unavailableTimeout,wsPath:E.wsPath||v.wsPath,wsPort:E.wsPort||v.wsPort,wssPort:E.wssPort||v.wssPort,enableStats:Oh(E),httpHost:kh(E),useTLS:Dh(E),wsHost:gu(E),userAuthenticator:gl(E),channelAuthorizer:$h(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 kh(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:v.httpHost}function gu(E){return E.wsHost?E.wsHost:Rh(E.cluster)}function Rh(E){return`ws-${E}.pusher.com`}function Dh(E){return Ue.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Oh(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const mu=E=>"customHandler"in E&&E.customHandler!=null;function gl(E){const b=Object.assign(Object.assign({},v.userAuthentication),E.userAuthentication);return mu(b)?b.customHandler:Ah(b)}function Lh(E,b){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},v.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||v.authTransport,endpoint:E.authEndpoint||v.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=Th(b,w,E.authorizer))),w}function $h(E,b){const w=Lh(E,b);return mu(w)?w.customHandler:xh(w)}class Mh extends xe{constructor(b){super(function(w,$){it.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 yu(){let E,b;return{promise:new Promise(($,N)=>{E=$,b=N}),resolve:E,reject:b}}const Nh=yu;class Ih extends xe{constructor(b){super(function(w,$){it.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,$)=>{if(w){it.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Ie?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:$.auth,user_data:$.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:w,current:$})=>{w!=="connected"&&$==="connected"&&this._signin(),w==="connected"&&$!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Mh(b),this.pusher.connection.bind("message",w=>{var $=w.event;$==="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{it.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){it.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 Xr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,$)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,$)}),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}=Nh();b.done=!1;const $=()=>{b.done=!0};b.then($).catch($),this.signinDonePromise=b,this._signinDoneResolve=w}}class fn{static ready(){fn.isReady=!0;for(var b=0,w=fn.instances.length;bUe.getDefaultStrategy(this.config,N,Pi);this.connection=Un.createConnectionManager(this.key,{getStrategy:$,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",N=>{var ne=N.event,ye=ne.indexOf("pusher_internal:")===0;if(N.channel){var Le=this.channel(N.channel);Le&&Le.handleEvent(N)}ye||this.global_emitter.emit(N.event,N.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",N=>{it.warn(N)}),fn.instances.push(this),this.timeline.info({instances:fn.instances.length}),this.user=new Ih(this),fn.isReady&&this.connect()}switchCluster(b){const{appKey:w,cluster:$}=b;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:$}),this.config=pu(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 ge(6e4,function(){w.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,w,$){return this.global_emitter.bind(b,w,$),this}unbind(b,w,$){return this.global_emitter.unbind(b,w,$),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,$){return this.connection.send_event(b,w,$)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}fn.instances=[],fn.isReady=!1,fn.logToConsole=!1,fn.Runtime=Ue,fn.ScriptReceivers=Ue.ScriptReceivers,fn.DependenciesReceivers=Ue.DependenciesReceivers,fn.auth_callbacks=Ue.auth_callbacks;const Is=fn;function jh(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}Ue.setup(fn)}},r={};function i(c){var d=r[c];if(d!==void 0)return d.exports;var f=r[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})())})(ch)),ch.exports}var Px=zx();const Eb=ra(Px),Kt=pt("WebSocketManager");class Ux{constructor(){M(this,"echo",null);M(this,"subscriptions",new Map);M(this,"initialized",!1);M(this,"config",null)}configure(e){if(this.initialized){Kt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Kt.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){Kt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(r)||80,d=i==="https";Kt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=Eb;const f=localStorage.getItem("auth_token"),h={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"}}};Kt.log("[WebSocketManager] Pusher 옵션:",h);const m=new Eb(e,h);m.connection.bind("connecting",()=>{Kt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Kt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Kt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{Kt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{Kt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{Kt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Kt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Kt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new Hx({broadcaster:"reverb",client:m}),Kt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Kt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return Kt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return Kt.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}`,r),this.subscriptions.set(c,d),Kt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){Kt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Kt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),Kt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Kt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Gc=new Ux,Ct=pt("DataSourceManager"),_b=new $n;function Fc(s,e){const n=La(s);if(n!==null)try{return Wn(n)?_b.evaluatePipeExpression(n,e,{skipCache:!0}):_b.evaluateExpression(n,e)}catch(r){return Ct.error("Failed to evaluate param expression:",n,r),s}return fs(s,e,{skipCache:!0})}function Ab(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function Bx(){try{return window.G7Core?.devTools}catch{return}}const Qc=class Qc{constructor(e={}){M(this,"options");M(this,"dataCache",new Map);M(this,"bindingEngine");M(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new $n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Fc(c,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}ds({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(ds({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return Ct.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){Ct.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(h=>(d||h.auto_fetch!==!1)&&h.type!=="websocket");return await Promise.all(f.map(async h=>{try{const m=await this.fetchDataSource(h,n,r,i,l);c[h.id]=m,this.dataCache.set(h.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(h,m);if(y!==null){const v={status:y,message:`Error condition matched for ${h.id}`,data:m},S=Tr(),_=S.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(_.handler)try{await S.execute(_.handler,v)}catch(x){Ct.error(`Error executing errorCondition handler for ${h.id}:`,x)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id} (errorCondition)`));return}if(h.onSuccess)try{const v={data:m,sourceId:h.id};await this.executeOnSuccessHandler(h.onSuccess,v)}catch(v){Ct.error(`Error executing onSuccess handler for ${h.id}:`,v)}}catch(m){Ct.error(`Failed to fetch data source: ${h.id}`,m);const y=m?.response?.status||m?.status||500,v=m?.response?.data,S=v?.message||m.message||"Unknown error",_={status:y,message:S,errors:v?.errors,data:v,statusText:m?.response?.statusText},x=Tr(),A=x.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(A.handler)try{await x.execute(A.handler,_)}catch(D){Ct.error(`Error executing error handler for ${h.id}:`,D)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id}`)),this.options.onError&&this.options.onError(m,h)}})),c}async fetchDataSourcesWithResults(e,n={},r=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(", ");Ct.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,r,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const v=this.checkErrorCondition(m,y);if(v!==null){const S={status:v,message:`Error condition matched for ${m.id}`,data:y},_=Tr(),x=_.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let A=!1;if(x.handler)if(m.loading_strategy==="blocking")_.execute(x.handler,S).catch(D=>{Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}),A=!0;else try{await _.execute(x.handler,S),A=!0}catch(D){Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.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: ${v}`),errorCode:v,errorHandled:A}}if(m.onSuccess)try{const S={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){Ct.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:y}}catch(y){Ct.error(`Failed to fetch data source: ${m.id}`,y);const v=y?.response?.status||y?.status||500,S=y?.response?.data,_=S?.message||y.message||"Unknown error",x={status:v,message:_,errors:S?.errors,data:S,statusText:y?.response?.statusText},A=Tr(),D=A.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let O=!1;if(D.handler)if(m.loading_strategy==="blocking")A.execute(D.handler,x).catch(k=>{Ct.error(`Error executing error handler for ${m.id}:`,k)}),O=!0;else try{await A.execute(D.handler,x),O=!0}catch(k){Ct.error(`Error executing error handler for ${m.id}:`,k)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.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:v,errorHandled:O})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,r).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const h={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Tr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,h)}catch(v){Ct.error(`Error executing errorCondition handler for ${c.id}:`,v)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const h={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,h)}catch(h){Ct.error(`Error executing onSuccess handler for ${c.id}:`,h)}i&&i(c.id,d)}).catch(async d=>{Ct.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,h=d?.response?.data,m=h?.message||d.message||"Unknown error",y={status:f,message:m,errors:h?.errors,data:h,statusText:d?.response?.statusText},v=Tr(),S=v.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await v.execute(S.handler,y)}catch(_){Ct.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.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,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Ab(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,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:Ab(r)};i&&(c._global=i),l&&(c._local=l);let d=fs(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?fs(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(([_,x])=>{typeof x=="string"&&(y[_]=Fc(x,c))}),Object.keys(y).forEach(_=>{y[_]===""&&delete y[_]});const v=Bx();let S=null;if(v?.isEnabled()){v.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 x=new URLSearchParams;Object.entries(y).forEach(([D,O])=>{Array.isArray(O)?O.forEach(k=>x.append(D,String(k))):O!=null&&x.append(D,String(O))});const A=x.toString();_=A?`${d}?${A}`:d}S=v.trackRequest(_,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),v.trackDataSourceLoading(e.id)}try{let _;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),A=Ar.getInstance().isAuthenticated();if(x==="required"&&!A){Ct.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),v?.isEnabled()&&(v.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&v.failRequest(S,"Skipped: not authenticated"));const O=new Error("Auth required but not authenticated");throw O.response={status:401,statusText:"Unauthorized",data:null},O.status=401,O._authSkipped=!0,O}const D=x==="required"||x==="optional"&&A;if(D){const O=qr(),k=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&Ct.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${k}`);const L=this.getMatchingGlobalHeaders(d,c),B={};e.headers&&Object.entries(e.headers).forEach(([de,_e])=>{const Se=Fc(_e,c);Se!=null&&Se!==""&&(B[de]=String(Se))});const q={...L,...B},z=Object.keys(q).length>0,W=m?this.toFormData(y):y;switch(f){case"GET":_=await O.get(k,{params:y,...z&&{headers:q}});break;case"POST":z?_=await O.post(k,W,{headers:q}):_=await O.post(k,W);break;case"PUT":z?_=await O.put(k,W,{headers:q}):_=await O.put(k,W);break;case"PATCH":z?_=await O.patch(k,W,{headers:q}):_=await O.patch(k,W);break;case"DELETE":_=await O.delete(k,{params:y,...z&&{headers:q}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let O=d;if(f==="GET"){const W=new URLSearchParams(y).toString();O=W?`${d}?${W}`:d}const k={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const W=localStorage.getItem("g7_locale");W&&(k["Accept-Language"]=W)}const L=this.getMatchingGlobalHeaders(d,c);Object.assign(k,L),e.headers&&Object.entries(e.headers).forEach(([W,de])=>{const _e=Fc(de,c);_e!=null&&_e!==""&&(k[W]=String(_e))});let B;f!=="GET"&&(m?(B=this.toFormData(y),delete k["Content-Type"]):B=JSON.stringify(y));const q=await fetch(O,{method:f,headers:k,body:B});let z;try{z=await q.json()}catch{z=null}if(S&&v?.isEnabled()&&(v.completeRequest(S,q.status,z),S=null),!q.ok){v?.isEnabled()&&v.trackDataSourceError(e.id,`HTTP ${q.status}: ${q.statusText}`);const W=new Error(`HTTP error! status: ${q.status}`);throw W.response={status:q.status,statusText:q.statusText,data:z},W.status=q.status,W}_=z,v?.isEnabled()&&v.trackDataSourceLoaded(e.id,_)}return D&&S&&v?.isEnabled()&&(v.completeRequest(S,200,_),v.trackDataSourceLoaded(e.id,_)),_}catch(_){if(S&&v?.isEnabled()){const x=_;x?.response?v.completeRequest(S,x.response.status,x.response.data):v.failRequest(S,_ instanceof Error?_.message:String(_)),v.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Qc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){Ct.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=fs(c.channel,r,{skipCache:!0}),f=fs(c.event,r,{skipCache:!0})}catch(y){Ct.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const h=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(h(d)||h(f)){Ct.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(r).join(", ")}]`);return}const m=Gc.subscribe(d,f,y=>{const v=c.target_source||c.id;this.dataCache.set(v,{data:y,timestamp:Date.now()}),n(v,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Gc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??Cy();if(!r){Ct.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw Ct.error("Failed to execute onSuccess handler:",c),c}}};M(Qc,"DATA_CACHE_TTL",3e5);let Dr=Qc;const qx=new Dr,ki=pt("ModalDataSourceWrapper");function Gx(s,e){if(!s||!e)return s;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,h=[];d&&h.push(d);const m=f.match(/\[\d+\]/g);return m&&h.push(...m),h}return[l]}).filter(l=>l!=="");let i=s;for(const l of r){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 xb=({isOpen:s,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,h]=I.useState(!1),[m,y]=I.useState(!1),v=I.useRef(!1),S=I.useRef(null);S.current||(S.current=new Dr);const _=I.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){h(!0);try{const x=r.route||{},A=new URLSearchParams(window.location.search),D=n.map(k=>{let L={...k};if(k.endpoint&&l){const B=l.resolveBindings(k.endpoint,r,{skipCache:!0});L.endpoint=B}if(k.params&&l){const B={};Object.entries(k.params).forEach(([q,z])=>{typeof z=="string"?B[q]=l.resolveBindings(z,r,{skipCache:!0}):B[q]=z}),L.params=B}return L});c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,D.map(k=>({id:k.id,endpoint:k.endpoint})));const O=await S.current.fetchDataSourcesWithResults(D,x,A);i&&O.forEach(k=>{if(k.state==="success"&&k.data!==void 0){const L=D.find(B=>B.id===k.id);if(L?.initGlobal){const B=k.data?.data??k.data,q=Array.isArray(L.initGlobal)?L.initGlobal:[L.initGlobal];for(const z of q)if(typeof z=="string")i({[z]:B}),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${k.id}.data -> _global.${z}`);else if(typeof z=="object"&&z.key){const{key:W,path:de}=z,_e=de?Gx(B,de):B;i({[W]:_e}),c&&ki.log(`Modal "${e}" initGlobal: ${k.id}.data${de?"."+de:""} -> _global.${W}`)}}}else k.state==="error"&&ki.error(`Modal "${e}" data source error:`,k.id,k.error)}),c&&ki.log(`Modal "${e}" data sources fetched successfully`)}catch(x){ki.error(`Modal "${e}" data source fetch error:`,x)}finally{h(!1),y(!0)}}},[n,r,i,l,e,c]);return I.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),I.useEffect(()=>{!s&&v.current&&(y(!1),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),s&&!v.current&&n&&n.length>0&&!m&&_(),v.current=s},[s,n,m,_,e,c]),yt.jsx(yt.Fragment,{children:d})};class Vc extends Error{constructor(n,r,i={}){super(r);M(this,"code");M(this,"userMessageKey");M(this,"showStack");M(this,"icon");M(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,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,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class Fx extends Vc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Tb(s){if(s instanceof Vc)return s;if(s instanceof Error){const e=new Vc("TEMPLATE_INIT_ERROR",s.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=s.stack,e}return new Vc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const Vx=pt("ErrorDisplay");class uh{static render(e,n){const r=document.getElementById(e);if(!r){Vx.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` + `,Xn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Xn.log("Layout data and cache cleared")}}const Rx=pt("TranslationContext"),ih=I.createContext(null),Uc=({children:s,translationEngine:e,translationContext:n})=>{const r=I.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,h])=>`${f}=${h}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=I.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return yt.jsx(ih.Provider,{value:i,children:s})},gb=()=>{const s=I.useContext(ih);return s||(Rx.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Pa=pt("SlotContext"),Dx={registerToSlot:()=>{Pa.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Pa.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},Ox=I.createContext(Dx),sh=({children:s})=>{const e=I.useRef(new Map),n=I.useRef(new Map),r=I.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(v=>{try{v()}catch(S){Pa.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=I.useCallback((m,y,v)=>{if(!m||!y){Pa.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),_=S.get(y);_&&_.registrationKey===v.registrationKey||(S.set(y,v),Pa.log(`Component registered to slot: ${y} -> ${m} (order: ${v.order})`),r(m))},[r]),l=I.useCallback((m,y)=>{const v=e.current.get(m);v&&v.has(y)&&(v.delete(y),Pa.log(`Component unregistered from slot: ${y} <- ${m}`),v.size===0&&e.current.delete(m),r(m))},[r]),c=I.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((v,S)=>v.order-S.order):[]},[]),d=I.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const v=n.current.get(m);return v.add(y),()=>{v.delete(y),v.size===0&&n.current.delete(m)}},[]),f=I.useCallback(()=>{e.current.forEach((m,y)=>{r(y)}),e.current.clear(),n.current.clear(),Pa.log("All slots cleared")},[r]),h=I.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return I.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=h,Pa.log("SlotContext exposed to window.__slotContextValue"))},[h]),yt.jsx(Ox.Provider,{value:h,children:s})};class oh{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 mb{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 Lx(s){try{return Reflect.construct(String,[],s),!0}catch{return!1}}class lh extends oh{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,this.eventFormatter=new mb(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,r)=>{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,r)}),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 yb extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class $x extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class Mx extends yb{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),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 bb extends oh{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,this.eventFormatter=new mb(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]=(r,i)=>{this.name===r&&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(r=>r!==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 vb extends bb{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class Nx extends vb{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.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 Bc extends oh{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 Sb extends Bc{whisper(e,n){return this}}class Ix extends Bc{whisper(e,n){return this}}class jx extends Sb{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Jc=class Jc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Jc._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}};Jc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Wo=Jc;class qc extends Wo{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,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new lh(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new yb(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 Mx(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())},r=["state_change","connected","disconnected"];return r.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{r.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class Hx extends Wo{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,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new bb(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new vb(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Nx(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())},r=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return r.forEach(i=>{this.socket.on(i,n)}),()=>{r.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class wb extends Wo{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new Bc}channel(e){return new Bc}privateChannel(e){return new Sb}encryptedPrivateChannel(e){return new Ix}presenceChannel(e){return new jx}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class zx{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 qc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new qc(this.options);else if(this.options.broadcaster==="ably")this.connector=new qc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new Hx(this.options);else if(this.options.broadcaster==="null")this.connector=new wb(this.options);else if(typeof this.options.broadcaster=="function"&&Lx(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,r){return this.connector.listen(e,n,r)}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 qc||e instanceof wb}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,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var ch={exports:{}};var Cb;function Px(){return Cb||(Cb=1,(function(s,e){(function(r,i){s.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var O=function(k,L){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,q){B.__proto__=q}||function(B,q){for(var z in q)q.hasOwnProperty(z)&&(B[z]=q[z])},O(k,L)};return function(k,L){O(k,L);function B(){this.constructor=k}k.prototype=L===null?Object.create(L):(B.prototype=L.prototype,new B)}})();Object.defineProperty(d,"__esModule",{value:!0});var h=256,m=(function(){function O(k){k===void 0&&(k="="),this._paddingCharacter=k}return O.prototype.encodedLength=function(k){return this._paddingCharacter?(k+2)/3*4|0:(k*8+5)/6|0},O.prototype.encode=function(k){for(var L="",B=0;B>>18&63),L+=this._encodeByte(q>>>12&63),L+=this._encodeByte(q>>>6&63),L+=this._encodeByte(q>>>0&63)}var z=k.length-B;if(z>0){var q=k[B]<<16|(z===2?k[B+1]<<8:0);L+=this._encodeByte(q>>>18&63),L+=this._encodeByte(q>>>12&63),z===2?L+=this._encodeByte(q>>>6&63):L+=this._paddingCharacter||"",L+=this._paddingCharacter||""}return L},O.prototype.maxDecodedLength=function(k){return this._paddingCharacter?k/4*3|0:(k*6+7)/8|0},O.prototype.decodedLength=function(k){return this.maxDecodedLength(k.length-this._getPaddingLength(k))},O.prototype.decode=function(k){if(k.length===0)return new Uint8Array(0);for(var L=this._getPaddingLength(k),B=k.length-L,q=new Uint8Array(this.maxDecodedLength(B)),z=0,W=0,de=0,_e=0,Se=0,Ie=0,Fe=0;W>>4,q[z++]=Se<<4|Ie>>>2,q[z++]=Ie<<6|Fe,de|=_e&h,de|=Se&h,de|=Ie&h,de|=Fe&h;if(W>>4,de|=_e&h,de|=Se&h),W>>2,de|=Ie&h),W>>8&6,L+=51-k>>>8&-75,L+=61-k>>>8&-15,L+=62-k>>>8&3,String.fromCharCode(L)},O.prototype._decodeChar=function(k){var L=h;return L+=(42-k&k-44)>>>8&-h+k-43+62,L+=(46-k&k-48)>>>8&-h+k-47+63,L+=(47-k&k-58)>>>8&-h+k-48+52,L+=(64-k&k-91)>>>8&-h+k-65+0,L+=(96-k&k-123)>>>8&-h+k-97+26,L},O.prototype._getPaddingLength=function(k){var L=0;if(this._paddingCharacter){for(var B=k.length-1;B>=0&&k[B]===this._paddingCharacter;B--)L++;if(k.length<4||L>2)throw new Error("Base64Coder: incorrect padding")}return L},O})();d.Coder=m;var y=new m;function v(O){return y.encode(O)}d.encode=v;function S(O){return y.decode(O)}d.decode=S;var _=(function(O){f(k,O);function k(){return O!==null&&O.apply(this,arguments)||this}return k.prototype._encodeByte=function(L){var B=L;return B+=65,B+=25-L>>>8&6,B+=51-L>>>8&-75,B+=61-L>>>8&-13,B+=62-L>>>8&49,String.fromCharCode(B)},k.prototype._decodeChar=function(L){var B=h;return B+=(44-L&L-46)>>>8&-h+L-45+62,B+=(94-L&L-96)>>>8&-h+L-95+63,B+=(47-L&L-58)>>>8&-h+L-48+52,B+=(64-L&L-91)>>>8&-h+L-65+0,B+=(96-L&L-123)>>>8&-h+L-97+26,B},k})(m);d.URLSafeCoder=_;var x=new _;function A(O){return x.encode(O)}d.encodeURLSafe=A;function D(O){return x.decode(O)}d.decodeURLSafe=D,d.encodedLength=function(O){return y.encodedLength(O)},d.maxDecodedLength=function(O){return y.maxDecodedLength(O)},d.decodedLength=function(O){return y.decodedLength(O)}},978(c,d){var f="utf8: invalid source encoding";function h(m){for(var y=[],v=0;v=m.length)throw new Error(f);var x=m[++v];if((x&192)!==128)throw new Error(f);S=(S&31)<<6|x&63,_=128}else if(S<240){if(v>=m.length-1)throw new Error(f);var x=m[++v],A=m[++v];if((x&192)!==128||(A&192)!==128)throw new Error(f);S=(S&15)<<12|(x&63)<<6|A&63,_=2048}else if(S<248){if(v>=m.length-2)throw new Error(f);var x=m[++v],A=m[++v],D=m[++v];if((x&192)!==128||(A&192)!==128||(D&192)!==128)throw new Error(f);S=(S&15)<<18|(x&63)<<12|(A&63)<<6|D&63,_=65536}else throw new Error(f);if(S<_||S>=55296&&S<=57343)throw new Error(f);if(S>=65536){if(S>1114111)throw new Error(f);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}d.D4=h},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>Is});class h{constructor(b,w){this.lastId=0,this.prefix=b,this.name=w}create(b){this.lastId++;var w=this.lastId,$=this.prefix+w,N=this.name+"["+w+"]",ne=!1,ye=function(){ne||(b.apply(null,arguments),ne=!0)};return this[w]=ye,{number:w,id:$,name:N,callback:ye}}remove(b){delete this[b.number]}}var m=new h("_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 v=y;class S{constructor(b){this.options=b,this.receivers=b.receivers||m,this.loading={}}load(b,w,$){var N=this;if(N.loading[b]&&N.loading[b].length>0)N.loading[b].push($);else{N.loading[b]=[$];var ne=Ue.createScriptRequest(N.getPath(b,w)),ye=N.receivers.create(function(Le){if(N.receivers.remove(ye),N.loading[b]){var We=N.loading[b];delete N.loading[b];for(var ft=function(Vt){Vt||ne.cleanup()},vt=0;vt>>6)+Q(128|b&63):Q(224|b>>>12&15)+Q(128|b>>>6&63)+Q(128|b&63)},ee=function(E){return E.replace(/[^\x00-\x7F]/g,De)},me=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),$=[ue.charAt(w>>>18),ue.charAt(w>>>12&63),b>=2?"=":ue.charAt(w>>>6&63),b>=1?"=":ue.charAt(w&63)];return $.join("")},H=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,me)};class T{constructor(b,w,$,N){this.clear=w,this.timer=b(()=>{this.timer&&(this.timer=N(this.timer))},$)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const fe=T;function he(E){window.clearTimeout(E)}function Ae(E){window.clearInterval(E)}class se extends fe{constructor(b,w){super(setTimeout,he,b,function($){return w(),null})}}class ge extends fe{constructor(b,w){super(setInterval,Ae,b,function($){return w(),$})}}var $e={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new se(0,E)},method(E,...b){var w=Array.prototype.slice.call(arguments,1);return function($){return $[E].apply($,w.concat(arguments))}}};const Te=$e;function je(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 $=xt.apply(this,arguments);Is.log?Is.log($):Is.logToConsole&&b.bind(this)($)}}const it=new Mn;var Pn=function(E,b,w,$,N){(w.headers!==void 0||w.headersProvider!=null)&&it.warn(`To send headers with the ${$.toString()} request, you must use AJAX, rather than JSONP.`);var ne=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var ye=E.getDocument(),Le=ye.createElement("script");E.auth_callbacks[ne]=function(vt){N(null,vt)};var We="Pusher.auth_callbacks['"+ne+"']";Le.src=w.endpoint+"?callback="+encodeURIComponent(We)+"&"+b;var ft=ye.getElementsByTagName("head")[0]||ye.documentElement;ft.insertBefore(Le,ft.firstChild)};const vn=Pn;class da{constructor(b){this.src=b}send(b){var w=this,$="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($)},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+"('"+$+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var N=document.getElementsByTagName("head")[0];N.insertBefore(w.script,N.firstChild),w.errorScript&&N.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 fr{constructor(b,w){this.url=b,this.data=w}send(b){if(!this.request){var w=$i(this.data),$=this.url+"/"+b.number+"?"+w;this.request=Ue.createScriptRequest($),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var un=function(E,b){return function(w,$){var N="http"+(b?"s":"")+"://",ne=N+(E.host||E.options.host)+E.options.path,ye=Ue.createJSONPRequest(ne,w),Le=Ue.ScriptReceivers.create(function(We,ft){m.remove(Le),ye.cleanup(),ft&&ft.host&&(E.host=ft.host),$&&$(We,ft)});ye.send(Le)}},Rn={name:"jsonp",getAgent:un};const dn=Rn;function V(E,b,w){var $=E+(b.useTLS?"s":""),N=b.useTLS?b.hostTLS:b.hostNonTLS;return $+"://"+N+w}function ie(E,b){var w="/app/"+E,$="?protocol="+v.PROTOCOL+"&client=js&version="+v.VERSION+(b?"&"+b:"");return w+$}var ce={getInitial:function(E,b){var w=(b.httpPath||"")+ie(E,"flash=false");return V("ws",b,w)}},Z={getInitial:function(E,b){var w=(b.httpPath||"/pusher")+ie(E);return V("http",b,w)}},ve={getInitial:function(E,b){return V("http",b,b.httpPath||"/pusher")},getPath:function(E,b){return ie(E)}};class pe{constructor(){this._callbacks={}}get(b){return this._callbacks[Ee(b)]}add(b,w,$){var N=Ee(b);this._callbacks[N]=this._callbacks[N]||[],this._callbacks[N].push({fn:w,context:$})}remove(b,w,$){if(!b&&!w&&!$){this._callbacks={};return}var N=b?[Ee(b)]:at(this._callbacks);w||$?this.removeCallback(N,w,$):this.removeAllCallbacks(N)}removeCallback(b,w,$){Ht(b,function(N){this._callbacks[N]=mt(this._callbacks[N]||[],function(ne){return w&&w!==ne.fn||$&&$!==ne.context}),this._callbacks[N].length===0&&delete this._callbacks[N]},this)}removeAllCallbacks(b){Ht(b,function(w){delete this._callbacks[w]},this)}}function Ee(E){return"_"+E}class xe{constructor(b){this.callbacks=new pe,this.global_callbacks=[],this.failThrough=b}bind(b,w,$){return this.callbacks.add(b,w,$),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,w,$){return this.callbacks.remove(b,w,$),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,$){for(var N=0;N0)for(var N=0;N{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),it.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"?(Te.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 je({cid:this.id},b)}}class ke{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,w,$,N){return new Ke(this.hooks,b,w,$,N)}}var Me=new ke({urls:ce,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Ue.getWebSocketAPI()},isSupported:function(){return!!Ue.getWebSocketAPI()},getSocket:function(E){return Ue.createWebSocket(E)}}),Re={urls:Z,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},tt=je({getSocket:function(E){return Ue.HTTPFactory.createStreamingSocket(E)}},Re),Pe=je({getSocket:function(E){return Ue.HTTPFactory.createPollingSocket(E)}},Re),Ve={isSupported:function(){return Ue.isXHRSupported()}},Ce=new ke(je({},tt,Ve)),He=new ke(je({},Pe,Ve)),nt={ws:Me,xhr_streaming:Ce,xhr_polling:He};const Lt=nt;var Bt=new ke({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:x.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(E,b){E.send(JSON.stringify({path:b}))}}),Nn={isSupported:function(E){var b=Ue.isXDRSupported(E.useTLS);return b}},Gt=new ke(je({},tt,Nn)),Ft=new ke(je({},Pe,Nn));Lt.xdr_streaming=Gt,Lt.xdr_polling=Ft,Lt.sockjs=Bt;const Dn=Lt;class Ba extends xe{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 rl=new Ba;class mh{constructor(b,w,$){this.manager=b,this.transport=w,this.minPingDelay=$.minPingDelay,this.maxPingDelay=$.maxPingDelay,this.pingDelay=void 0}createConnection(b,w,$,N){N=je({},N,{activityTimeout:this.pingDelay});var ne=this.transport.createConnection(b,w,$,N),ye=null,Le=function(){ne.unbind("open",Le),ne.bind("closed",We),ye=Te.now()},We=ft=>{if(ne.unbind("closed",We),ft.code===1002||ft.code===1003)this.manager.reportDeath();else if(!ft.wasClean&&ye){var vt=Te.now()-ye;vt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(vt/2,this.minPingDelay))}};return ne.bind("open",Le),ne}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const Zc={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 $={event:b.event,channel:b.channel,data:w};return b.user_id&&($.user_id=b.user_id),$}catch(N){throw{type:"MessageParseError",error:N,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var b=Zc.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}},Yr=Zc;class Mi extends xe{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,$){var N={event:b,data:w};return $&&(N.channel=$),it.debug("Event sent",N),this.send(Yr.encodeMessage(N))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:$=>{var N;try{N=Yr.decodeMessage($)}catch(ne){this.emit("error",{type:"MessageParseError",error:ne,data:$.data})}if(N!==void 0){switch(it.debug("Event recd",N),N.event){case"pusher:error":this.emit("error",{type:"PusherError",data:N.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",N)}},activity:()=>{this.emit("activity")},error:$=>{this.emit("error",$)},closed:$=>{w(),$&&$.code&&this.handleCloseEvent($),this.transport=null,this.emit("closed")}},w=()=>{gt(b,($,N)=>{this.transport.unbind(N,$)})};gt(b,($,N)=>{this.transport.bind(N,$)})}handleCloseEvent(b){var w=Yr.getCloseAction(b),$=Yr.getCloseError(b);$&&this.emit("error",$),w&&this.emit(w,{action:w,error:$})}}class al{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=Yr.processHandshake(b)}catch($){this.finish("error",{error:$}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new Mi(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var w=Yr.getCloseAction(b)||"backoff",$=Yr.getCloseError(b);this.finish(w,{error:$})},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(je({transport:this.transport,action:b},w))}}class qa{constructor(b,w){this.timeline=b,this.options=w||{}}send(b,w){this.timeline.isEmpty()||this.timeline.send(Ue.TimelineTransport.getAgent(this,b),w)}}class Xr extends xe{constructor(b,w){super(function($,N){it.debug("No callbacks on "+b+" for "+$)}),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 L("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var $=O.buildLogSuffix("triggeringClientEvents");it.warn(`Client event triggered before channel 'subscription_succeeded' event . ${$}`)}return this.pusher.send_event(b,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var w=b.event,$=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 N={};this.emit(w,$,N)}}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,it.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof Ie?{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 fa extends Xr{authorize(b,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},w)}}class Ga{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){gt(this.members,(w,$)=>{b(this.get($))})}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 nn=function(E,b,w,$){function N(ne){return ne instanceof w?ne:new w(function(ye){ye(ne)})}return new(w||(w=Promise))(function(ne,ye){function Le(vt){try{ft($.next(vt))}catch(Vt){ye(Vt)}}function We(vt){try{ft($.throw(vt))}catch(Vt){ye(Vt)}}function ft(vt){vt.done?ne(vt.value):N(vt.value).then(Le,We)}ft(($=$.apply(E,b||[])).next())})};class eu extends fa{constructor(b,w){super(b,w),this.members=new Ga}authorize(b,w){super.authorize(b,($,N)=>nn(this,void 0,void 0,function*(){if(!$)if(N=N,N.channel_data!=null){var ne=JSON.parse(N.channel_data);this.members.setMyID(ne.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 ye=O.buildLogSuffix("authorizationEndpoint");it.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),w("Invalid auth response");return}w($,N)}))}handleEvent(b){var w=b.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var $=b.data,N={};b.user_id&&(N.user_id=b.user_id),this.emit(w,$,N)}}handleInternalEvent(b){var w=b.event,$=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 N=this.members.addMember($);this.emit("pusher:member_added",N);break;case"pusher_internal:member_removed":var ne=this.members.removeMember($);ne&&this.emit("pusher:member_removed",ne);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 tu=f(978),$r=f(594);class Fa extends fa{constructor(b,w,$){super(b,w),this.key=null,this.nacl=$}authorize(b,w){super.authorize(b,($,N)=>{if($){w($,N);return}let ne=N.shared_secret;if(!ne){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,$r.decode)(ne),delete N.shared_secret,w(null,N)})}trigger(b,w){throw new de("Client events are not currently supported for encrypted channels")}handleEvent(b){var w=b.event,$=b.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(w,$)}handleEncryptedEvent(b,w){if(!this.key){it.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){it.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let $=(0,$r.decode)(w.ciphertext);if($.length{if(ye){it.error(`Failed to make a request to the authEndpoint: ${Le}. Unable to fetch new key, so dropping encrypted event`);return}if(ne=this.nacl.secretbox.open($,N,this.key),ne===null){it.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(ne))});return}this.emit(b,this.getDataToEmit(ne))}getDataToEmit(b){let w=(0,tu.D4)(b);try{return JSON.parse(w)}catch{return w}}}class yh extends xe{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 $=Ue.getNetwork();$.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),$.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,$){return this.connection?this.connection.send_event(b,w,$):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(w,$)=>{w?this.runner=this.strategy.connect(0,b):$.action==="error"?(this.emit("error",{type:"HandshakeError",error:$.error}),this.timeline.error({handshakeError:$.error})):(this.abortConnecting(),this.handshakeCallbacks[$.action]($))};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 se(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new se(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new se(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 se(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return je({},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 je({},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=>$=>{$.error&&this.emit("error",{type:"WebSocketError",error:$.error}),w($)};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 $=this.state;if(this.state=b,$!==b){var N=b;N==="connected"&&(N+=" with new socket ID "+w.socket_id),it.debug("State changed",$+" -> "+N),this.timeline.info({state:b,params:w}),this.emit("state_change",{previous:$,current:b}),this.emit(b,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class nu{constructor(){this.channels={}}add(b,w){return this.channels[b]||(this.channels[b]=ru(b,w)),this.channels[b]}all(){return Yt(this.channels)}find(b){return this.channels[b]}remove(b){var w=this.channels[b];return delete this.channels[b],w}disconnect(){gt(this.channels,function(b){b.disconnect()})}}function ru(E,b){if(E.indexOf("private-encrypted-")===0){if(b.config.nacl)return Un.createEncryptedChannel(E,b,b.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",$=O.buildLogSuffix("encryptedChannelSupport");throw new de(`${w}. ${$}`)}else{if(E.indexOf("private-")===0)return Un.createPrivateChannel(E,b);if(E.indexOf("presence-")===0)return Un.createPresenceChannel(E,b);if(E.indexOf("#")===0)throw new B('Cannot create a channel with name "'+E+'".');return Un.createChannel(E,b)}}var bh={createChannels(){return new nu},createConnectionManager(E,b){return new yh(E,b)},createChannel(E,b){return new Xr(E,b)},createPrivateChannel(E,b){return new fa(E,b)},createPresenceChannel(E,b){return new eu(E,b)},createEncryptedChannel(E,b,w){return new Fa(E,b,w)},createTimelineSender(E,b){return new qa(E,b)},createHandshake(E,b){return new al(E,b)},createAssistantToTheTransportManager(E,b,w){return new mh(E,b,w)}};const Un=bh;class Ni{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return Un.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Sn{constructor(b,w){this.strategies=b,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){var $=this.strategies,N=0,ne=this.timeout,ye=null,Le=(We,ft)=>{ft?w(null,ft):(N=N+1,this.loop&&(N=N%$.length),N<$.length?(ne&&(ne=ne*2,this.timeoutLimit&&(ne=Math.min(ne,this.timeoutLimit))),ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le)):w(!0))};return ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le),{abort:function(){ye.abort()},forceMinPriority:function(We){b=We,ye&&ye.forceMinPriority(We)}}}tryStrategy(b,w,$,N){var ne=null,ye=null;return $.timeout>0&&(ne=new se($.timeout,function(){ye.abort(),N(!0)})),ye=b.connect(w,function(Le,We){Le&&ne&&ne.isRunning()&&!$.failFast||(ne&&ne.ensureAborted(),N(Le,We))}),{abort:function(){ne&&ne.ensureAborted(),ye.abort()},forceMinPriority:function(Le){ye.forceMinPriority(Le)}}}}class On{constructor(b){this.strategies=b}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){return au(this.strategies,b,function($,N){return function(ne,ye){if(N[$].error=ne,ne){vh(N)&&w(!0);return}Ht(N,function(Le){Le.forceMinPriority(ye.transport.priority)}),w(null,ye)}})}}function au(E,b,w){var $=bt(E,function(N,ne,ye,Le){return N.connect(b,w(ne,Le))});return{abort:function(){Ht($,il)},forceMinPriority:function(N){Ht($,function(ne){ne.forceMinPriority(N)})}}}function vh(E){return dr(E,function(b){return!!b.error})}function il(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class iu{constructor(b,w,$){this.strategy=b,this.transports=w,this.ttl=$.ttl||18e5,this.usingTLS=$.useTLS,this.timeline=$.timeline}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.usingTLS,N=Sh($),ne=N&&N.cacheSkipCount?N.cacheSkipCount:0,ye=[this.strategy];if(N&&N.timestamp+this.ttl>=Te.now()){var Le=this.transports[N.transport];Le&&(["ws","wss"].includes(N.transport)||ne>3?(this.timeline.info({cached:!0,transport:N.transport,latency:N.latency}),ye.push(new Sn([Le],{timeout:N.latency*2+1e3,failFast:!0}))):ne++)}var We=Te.now(),ft=ye.pop().connect(b,function vt(Vt,jr){Vt?(Os($),ye.length>0?(We=Te.now(),ft=ye.pop().connect(b,vt)):w(Vt)):(Bn($,jr.transport.name,Te.now()-We,ne),w(null,jr))});return{abort:function(){ft.abort()},forceMinPriority:function(vt){b=vt,ft&&ft.forceMinPriority(vt)}}}}function Va(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Sh(E){var b=Ue.getLocalStorage();if(b)try{var w=b[Va(E)];if(w)return JSON.parse(w)}catch{Os(E)}return null}function Bn(E,b,w,$){var N=Ue.getLocalStorage();if(N)try{N[Va(E)]=bn({timestamp:Te.now(),transport:b,latency:w,cacheSkipCount:$})}catch{}}function Os(E){var b=Ue.getLocalStorage();if(b)try{delete b[Va(E)]}catch{}}class Ii{constructor(b,{delay:w}){this.strategy=b,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy,N,ne=new se(this.options.delay,function(){N=$.connect(b,w)});return{abort:function(){ne.ensureAborted(),N&&N.abort()},forceMinPriority:function(ye){b=ye,N&&N.forceMinPriority(ye)}}}}class ha{constructor(b,w,$){this.test=b,this.trueBranch=w,this.falseBranch=$}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,w){var $=this.test()?this.trueBranch:this.falseBranch;return $.connect(b,w)}}class Ka{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy.connect(b,function(N,ne){ne&&$.abort(),w(N,ne)});return $}}function Wa(E){return function(){return E.isSupported()}}var su=function(E,b,w){var $={};function N(vl,Su,wu,Uh,Bh){var Cu=w(E,vl,Su,wu,Uh,Bh);return $[vl]=Cu,Cu}var ne=Object.assign({},b,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),ye=Object.assign({},ne,{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},ft=new Ni({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),vt=new Ni({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),Vt=N("ws","ws",3,ne,ft),jr=N("wss","ws",3,ye,ft),Hh=N("sockjs","sockjs",1,Le),bu=N("xhr_streaming","xhr_streaming",1,Le,vt),zh=N("xdr_streaming","xdr_streaming",1,Le,vt),ml=N("xhr_polling","xhr_polling",1,Le),vu=N("xdr_polling","xdr_polling",1,Le),Ja=new Sn([Vt],We),Bi=new Sn([jr],We),Ph=new Sn([Hh],We),qi=new Sn([new ha(Wa(bu),bu,zh)],We),yl=new Sn([new ha(Wa(ml),ml,vu)],We),bl=new Sn([new ha(Wa(qi),new On([qi,new Ii(yl,{delay:4e3})]),yl)],We),Gi=new ha(Wa(bl),bl,Ph),Fi;return b.useTLS?Fi=new On([Ja,new Ii(Gi,{delay:2e3})]):Fi=new On([Ja,new Ii(Bi,{delay:2e3}),new Ii(Gi,{delay:5e3})]),new iu(new Ka(new ha(Wa(Vt),Fi,Gi)),$,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})};const Ya=su;function wh(){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"),x.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 ou={getRequest:function(E){var b=new window.XDomainRequest;return b.ontimeout=function(){E.emit("error",new q),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 lu=ou,sl=256*1024;class Ch extends xe{constructor(b,w,$){super(),this.hooks=b,this.method=w,this.url=$}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Ue.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&&(Ue.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,w){for(;;){var $=this.advanceBuffer(w);if($)this.emit("chunk",{status:b,data:$});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(b){var w=b.slice(this.position),$=w.indexOf(` +`);return $!==-1?(this.position+=$+1,w.slice(0,$)):null}isBufferTooLong(b){return this.position===b.length&&b.length>sl}}var ol;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(ol||(ol={}));const hr=ol;var Mr=1;class ll{constructor(b,w){this.hooks=b,this.session=Ls(1e3)+"/"+uu(8),this.location=cl(w),this.readyState=hr.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===hr.OPEN)try{return Ue.createSocketRequest("POST",pa(Xa(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,w,$){this.closeStream(),this.readyState=hr.CLOSED,this.onclose&&this.onclose({code:b,reason:w,wasClean:$})}onChunk(b){if(b.status===200){this.readyState===hr.OPEN&&this.onActivity();var w,$=b.data.slice(0,1);switch($){case"o":w=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(b.data.slice(1)||"[]");for(var N=0;N{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){Te.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 cl(E){var b=/([^\?]*)\/*(\??.*)/.exec(E);return{base:b[1],queryString:b[2]}}function Xa(E,b){return E.base+"/"+b+"/xhr_send"}function pa(E){var b=E.indexOf("?")===-1?"?":"&";return E+b+"t="+ +new Date+"&n="+Mr++}function cu(E,b){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+b+w[3]}function Ls(E){return Ue.randomInt(E)}function uu(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 $s=dl;var du={createStreamingSocket(E){return this.createSocket(ul,E)},createPollingSocket(E){return this.createSocket(Jr,E)},createSocket(E,b){return new ji(E,b)},createXHR(E,b){return this.createRequest($s,E,b)},createRequest(E,b,w){return new Ch(E,b,w)}};const zi=du;zi.createXDR=function(E,b){return this.createRequest(lu,E,b)};var fu={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Ya,Transports:Dn,transportConnectionInitializer:wh,HTTPFactory:zi,TimelineTransport:dn,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():x.load("json2",{},b)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:ze,jsonp:vn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,b){return new fr(E,b)},createScriptRequest(E){return new da(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 rl},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 $;do $=b.getRandomValues(new Uint32Array(1))[0];while($>=w);return $%E}};const Ue=fu;var Ir;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Ir||(Ir={}));const ga=Ir;class Pi{constructor(b,w,$){this.key=b,this.session=w,this.events=[],this.options=$||{},this.sent=0,this.uniqueID=0}log(b,w){b<=this.options.level&&(this.events.push(je({},w,{timestamp:Te.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ga.ERROR,b)}info(b){this.log(ga.INFO,b)}debug(b){this.log(ga.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,w){var $=je({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($,(N,ne)=>{N||this.sent++,w&&w(N,ne)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Eh{constructor(b,w,$,N){this.name=b,this.priority=w,this.transport=$,this.options=N||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,w){if(this.isSupported()){if(this.priority{$||(vt(),ne?ne.close():N.close())},forceMinPriority:Vt=>{$||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},Ah=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=_h(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.UserAuthentication,w)}},pl=(E,b)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},xh=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=pl(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.ChannelAuthorization,w)}},Th=(E,b,w)=>{const $={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(N,ne)=>{const ye=E.channel(N.channelName);w(ye,$).authorize(N.socketId,ne)}};function pu(E,b){let w={activityTimeout:E.activityTimeout||v.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||v.httpPath,httpPort:E.httpPort||v.httpPort,httpsPort:E.httpsPort||v.httpsPort,pongTimeout:E.pongTimeout||v.pongTimeout,statsHost:E.statsHost||v.stats_host,unavailableTimeout:E.unavailableTimeout||v.unavailableTimeout,wsPath:E.wsPath||v.wsPath,wsPort:E.wsPort||v.wsPort,wssPort:E.wssPort||v.wssPort,enableStats:Oh(E),httpHost:kh(E),useTLS:Dh(E),wsHost:gu(E),userAuthenticator:gl(E),channelAuthorizer:$h(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 kh(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:v.httpHost}function gu(E){return E.wsHost?E.wsHost:Rh(E.cluster)}function Rh(E){return`ws-${E}.pusher.com`}function Dh(E){return Ue.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Oh(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const mu=E=>"customHandler"in E&&E.customHandler!=null;function gl(E){const b=Object.assign(Object.assign({},v.userAuthentication),E.userAuthentication);return mu(b)?b.customHandler:Ah(b)}function Lh(E,b){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},v.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||v.authTransport,endpoint:E.authEndpoint||v.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=Th(b,w,E.authorizer))),w}function $h(E,b){const w=Lh(E,b);return mu(w)?w.customHandler:xh(w)}class Mh extends xe{constructor(b){super(function(w,$){it.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 yu(){let E,b;return{promise:new Promise(($,N)=>{E=$,b=N}),resolve:E,reject:b}}const Nh=yu;class Ih extends xe{constructor(b){super(function(w,$){it.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,$)=>{if(w){it.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Ie?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:$.auth,user_data:$.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:w,current:$})=>{w!=="connected"&&$==="connected"&&this._signin(),w==="connected"&&$!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Mh(b),this.pusher.connection.bind("message",w=>{var $=w.event;$==="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{it.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){it.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 Xr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,$)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,$)}),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}=Nh();b.done=!1;const $=()=>{b.done=!0};b.then($).catch($),this.signinDonePromise=b,this._signinDoneResolve=w}}class fn{static ready(){fn.isReady=!0;for(var b=0,w=fn.instances.length;bUe.getDefaultStrategy(this.config,N,Ui);this.connection=Un.createConnectionManager(this.key,{getStrategy:$,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",N=>{var ne=N.event,ye=ne.indexOf("pusher_internal:")===0;if(N.channel){var Le=this.channel(N.channel);Le&&Le.handleEvent(N)}ye||this.global_emitter.emit(N.event,N.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",N=>{it.warn(N)}),fn.instances.push(this),this.timeline.info({instances:fn.instances.length}),this.user=new Ih(this),fn.isReady&&this.connect()}switchCluster(b){const{appKey:w,cluster:$}=b;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:$}),this.config=pu(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 ge(6e4,function(){w.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,w,$){return this.global_emitter.bind(b,w,$),this}unbind(b,w,$){return this.global_emitter.unbind(b,w,$),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,$){return this.connection.send_event(b,w,$)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}fn.instances=[],fn.isReady=!1,fn.logToConsole=!1,fn.Runtime=Ue,fn.ScriptReceivers=Ue.ScriptReceivers,fn.DependenciesReceivers=Ue.DependenciesReceivers,fn.auth_callbacks=Ue.auth_callbacks;const Is=fn;function jh(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}Ue.setup(fn)}},r={};function i(c){var d=r[c];if(d!==void 0)return d.exports;var f=r[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})())})(ch)),ch.exports}var Ux=Px();const Eb=ra(Ux),Kt=pt("WebSocketManager");class Bx{constructor(){M(this,"echo",null);M(this,"subscriptions",new Map);M(this,"initialized",!1);M(this,"config",null)}configure(e){if(this.initialized){Kt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Kt.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){Kt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(r)||80,d=i==="https";Kt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=Eb;const f=localStorage.getItem("auth_token"),h={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"}}};Kt.log("[WebSocketManager] Pusher 옵션:",h);const m=new Eb(e,h);m.connection.bind("connecting",()=>{Kt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Kt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Kt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{Kt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{Kt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{Kt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Kt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Kt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new zx({broadcaster:"reverb",client:m}),Kt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Kt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return Kt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return Kt.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}`,r),this.subscriptions.set(c,d),Kt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){Kt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Kt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),Kt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Kt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Gc=new Bx,Ct=pt("DataSourceManager"),_b=new $n;function Fc(s,e){const n=La(s);if(n!==null)try{return Wn(n)?_b.evaluatePipeExpression(n,e,{skipCache:!0}):_b.evaluateExpression(n,e)}catch(r){return Ct.error("Failed to evaluate param expression:",n,r),s}return hs(s,e,{skipCache:!0})}function Ab(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function qx(){try{return window.G7Core?.devTools}catch{return}}const Qc=class Qc{constructor(e={}){M(this,"options");M(this,"dataCache",new Map);M(this,"bindingEngine");M(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new $n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Fc(c,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}fs({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(fs({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return Ct.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){Ct.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(h=>(d||h.auto_fetch!==!1)&&h.type!=="websocket");return await Promise.all(f.map(async h=>{try{const m=await this.fetchDataSource(h,n,r,i,l);c[h.id]=m,this.dataCache.set(h.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(h,m);if(y!==null){const v={status:y,message:`Error condition matched for ${h.id}`,data:m},S=Tr(),_=S.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(_.handler)try{await S.execute(_.handler,v)}catch(x){Ct.error(`Error executing errorCondition handler for ${h.id}:`,x)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id} (errorCondition)`));return}if(h.onSuccess)try{const v={data:m,sourceId:h.id};await this.executeOnSuccessHandler(h.onSuccess,v)}catch(v){Ct.error(`Error executing onSuccess handler for ${h.id}:`,v)}}catch(m){Ct.error(`Failed to fetch data source: ${h.id}`,m);const y=m?.response?.status||m?.status||500,v=m?.response?.data,S=v?.message||m.message||"Unknown error",_={status:y,message:S,errors:v?.errors,data:v,statusText:m?.response?.statusText},x=Tr(),A=x.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(A.handler)try{await x.execute(A.handler,_)}catch(D){Ct.error(`Error executing error handler for ${h.id}:`,D)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id}`)),this.options.onError&&this.options.onError(m,h)}})),c}async fetchDataSourcesWithResults(e,n={},r=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(", ");Ct.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,r,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const v=this.checkErrorCondition(m,y);if(v!==null){const S={status:v,message:`Error condition matched for ${m.id}`,data:y},_=Tr(),x=_.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let A=!1;if(x.handler)if(m.loading_strategy==="blocking")_.execute(x.handler,S).catch(D=>{Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}),A=!0;else try{await _.execute(x.handler,S),A=!0}catch(D){Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.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: ${v}`),errorCode:v,errorHandled:A}}if(m.onSuccess)try{const S={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){Ct.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:y}}catch(y){Ct.error(`Failed to fetch data source: ${m.id}`,y);const v=y?.response?.status||y?.status||500,S=y?.response?.data,_=S?.message||y.message||"Unknown error",x={status:v,message:_,errors:S?.errors,data:S,statusText:y?.response?.statusText},A=Tr(),D=A.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let O=!1;if(D.handler)if(m.loading_strategy==="blocking")A.execute(D.handler,x).catch(k=>{Ct.error(`Error executing error handler for ${m.id}:`,k)}),O=!0;else try{await A.execute(D.handler,x),O=!0}catch(k){Ct.error(`Error executing error handler for ${m.id}:`,k)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.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:v,errorHandled:O})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,r).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const h={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Tr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,h)}catch(v){Ct.error(`Error executing errorCondition handler for ${c.id}:`,v)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const h={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,h)}catch(h){Ct.error(`Error executing onSuccess handler for ${c.id}:`,h)}i&&i(c.id,d)}).catch(async d=>{Ct.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,h=d?.response?.data,m=h?.message||d.message||"Unknown error",y={status:f,message:m,errors:h?.errors,data:h,statusText:d?.response?.statusText},v=Tr(),S=v.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await v.execute(S.handler,y)}catch(_){Ct.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.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,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Ab(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,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:Ab(r)};i&&(c._global=i),l&&(c._local=l);let d=hs(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?hs(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(([_,x])=>{typeof x=="string"&&(y[_]=Fc(x,c))}),Object.keys(y).forEach(_=>{y[_]===""&&delete y[_]});const v=qx();let S=null;if(v?.isEnabled()){v.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 x=new URLSearchParams;Object.entries(y).forEach(([D,O])=>{Array.isArray(O)?O.forEach(k=>x.append(D,String(k))):O!=null&&x.append(D,String(O))});const A=x.toString();_=A?`${d}?${A}`:d}S=v.trackRequest(_,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),v.trackDataSourceLoading(e.id)}try{let _;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),A=Ar.getInstance().isAuthenticated();if(x==="required"&&!A){Ct.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),v?.isEnabled()&&(v.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&v.failRequest(S,"Skipped: not authenticated"));const O=new Error("Auth required but not authenticated");throw O.response={status:401,statusText:"Unauthorized",data:null},O.status=401,O._authSkipped=!0,O}const D=x==="required"||x==="optional"&&A;if(D){const O=qr(),k=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&Ct.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${k}`);const L=this.getMatchingGlobalHeaders(d,c),B={};e.headers&&Object.entries(e.headers).forEach(([de,_e])=>{const Se=Fc(_e,c);Se!=null&&Se!==""&&(B[de]=String(Se))});const q={...L,...B},z=Object.keys(q).length>0,W=m?this.toFormData(y):y;switch(f){case"GET":_=await O.get(k,{params:y,...z&&{headers:q}});break;case"POST":z?_=await O.post(k,W,{headers:q}):_=await O.post(k,W);break;case"PUT":z?_=await O.put(k,W,{headers:q}):_=await O.put(k,W);break;case"PATCH":z?_=await O.patch(k,W,{headers:q}):_=await O.patch(k,W);break;case"DELETE":_=await O.delete(k,{params:y,...z&&{headers:q}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let O=d;if(f==="GET"){const W=new URLSearchParams(y).toString();O=W?`${d}?${W}`:d}const k={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const W=localStorage.getItem("g7_locale");W&&(k["Accept-Language"]=W)}const L=this.getMatchingGlobalHeaders(d,c);Object.assign(k,L),e.headers&&Object.entries(e.headers).forEach(([W,de])=>{const _e=Fc(de,c);_e!=null&&_e!==""&&(k[W]=String(_e))});let B;f!=="GET"&&(m?(B=this.toFormData(y),delete k["Content-Type"]):B=JSON.stringify(y));const q=await fetch(O,{method:f,headers:k,body:B});let z;try{z=await q.json()}catch{z=null}if(S&&v?.isEnabled()&&(v.completeRequest(S,q.status,z),S=null),!q.ok){v?.isEnabled()&&v.trackDataSourceError(e.id,`HTTP ${q.status}: ${q.statusText}`);const W=new Error(`HTTP error! status: ${q.status}`);throw W.response={status:q.status,statusText:q.statusText,data:z},W.status=q.status,W}_=z,v?.isEnabled()&&v.trackDataSourceLoaded(e.id,_)}return D&&S&&v?.isEnabled()&&(v.completeRequest(S,200,_),v.trackDataSourceLoaded(e.id,_)),_}catch(_){if(S&&v?.isEnabled()){const x=_;x?.response?v.completeRequest(S,x.response.status,x.response.data):v.failRequest(S,_ instanceof Error?_.message:String(_)),v.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Qc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){Ct.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=hs(c.channel,r,{skipCache:!0}),f=hs(c.event,r,{skipCache:!0})}catch(y){Ct.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const h=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(h(d)||h(f)){Ct.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(r).join(", ")}]`);return}const m=Gc.subscribe(d,f,y=>{const v=c.target_source||c.id;this.dataCache.set(v,{data:y,timestamp:Date.now()}),n(v,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Gc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??Cy();if(!r){Ct.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw Ct.error("Failed to execute onSuccess handler:",c),c}}};M(Qc,"DATA_CACHE_TTL",3e5);let Dr=Qc;const Gx=new Dr,ki=pt("ModalDataSourceWrapper");function Fx(s,e){if(!s||!e)return s;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,h=[];d&&h.push(d);const m=f.match(/\[\d+\]/g);return m&&h.push(...m),h}return[l]}).filter(l=>l!=="");let i=s;for(const l of r){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 xb=({isOpen:s,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,h]=I.useState(!1),[m,y]=I.useState(!1),v=I.useRef(!1),S=I.useRef(null);S.current||(S.current=new Dr);const _=I.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){h(!0);try{const x=r.route||{},A=new URLSearchParams(window.location.search),D=n.map(k=>{let L={...k};if(k.endpoint&&l){const B=l.resolveBindings(k.endpoint,r,{skipCache:!0});L.endpoint=B}if(k.params&&l){const B={};Object.entries(k.params).forEach(([q,z])=>{typeof z=="string"?B[q]=l.resolveBindings(z,r,{skipCache:!0}):B[q]=z}),L.params=B}return L});c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,D.map(k=>({id:k.id,endpoint:k.endpoint})));const O=await S.current.fetchDataSourcesWithResults(D,x,A);i&&O.forEach(k=>{if(k.state==="success"&&k.data!==void 0){const L=D.find(B=>B.id===k.id);if(L?.initGlobal){const B=k.data?.data??k.data,q=Array.isArray(L.initGlobal)?L.initGlobal:[L.initGlobal];for(const z of q)if(typeof z=="string")i({[z]:B}),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${k.id}.data -> _global.${z}`);else if(typeof z=="object"&&z.key){const{key:W,path:de}=z,_e=de?Fx(B,de):B;i({[W]:_e}),c&&ki.log(`Modal "${e}" initGlobal: ${k.id}.data${de?"."+de:""} -> _global.${W}`)}}}else k.state==="error"&&ki.error(`Modal "${e}" data source error:`,k.id,k.error)}),c&&ki.log(`Modal "${e}" data sources fetched successfully`)}catch(x){ki.error(`Modal "${e}" data source fetch error:`,x)}finally{h(!1),y(!0)}}},[n,r,i,l,e,c]);return I.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),I.useEffect(()=>{!s&&v.current&&(y(!1),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),s&&!v.current&&n&&n.length>0&&!m&&_(),v.current=s},[s,n,m,_,e,c]),yt.jsx(yt.Fragment,{children:d})};class Vc extends Error{constructor(n,r,i={}){super(r);M(this,"code");M(this,"userMessageKey");M(this,"showStack");M(this,"icon");M(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,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,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class Vx extends Vc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Tb(s){if(s instanceof Vc)return s;if(s instanceof Error){const e=new Vc("TEMPLATE_INIT_ERROR",s.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=s.stack,e}return new Vc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const Kx=pt("ErrorDisplay");class uh{static render(e,n){const r=document.getElementById(e);if(!r){Kx.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; @@ -227,4 +227,4 @@ Error generating stack: `+u.message+` `:""} - `}static renderFromError(e,n,r,i=!1,l,c,d){let f,h;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?h=m.details.apiMessage:m.response?.data?.message&&(h=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:h,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 Es=pt("Router");class Kx{constructor(e){M(this,"routes",[]);M(this,"templateIdentifier");M(this,"eventHandlers",new Map);M(this,"pendingNavigation",null);M(this,"isNavigating",!1);M(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 r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Ur(`/api/templates/${this.templateIdentifier}/routes`,"json",n));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,Es.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw Es.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,Es.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,h)=>(r.push(h),"([^/]+)"));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 r.forEach((f,h)=>{d[f]=c[h+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,r=this.match(e);if(!r){Es.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){Es.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const c=this.getAuthType(r.route,e),d=Ar.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const h=d.getLoginRedirectUrl(c,e+n);Es.log(`Not authenticated, redirecting to: ${h}`),window.location.href=h;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: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 n=this.pendingNavigation;this.executeNavigation(n)}}}}const Wx=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function kb(s){const e=Wx.exec(s);return e?{templateIdentifier:e[1]}:null}const Wt=pt("ErrorPageHandler");class Yx{constructor(e){M(this,"templateId");M(this,"layoutLoader");M(this,"locale");M(this,"debug");M(this,"renderFunction");M(this,"dataSourceManager");M(this,"globalState");M(this,"errorConfig",null);M(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(Ur(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Wt.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&&Wt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Wt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Wt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Wt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Wt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Wt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Wt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Wt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Wt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Wt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),y=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...y];if(v.length>0)try{c=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&Wt.log("Data sources fetched:",Object.keys(c))}catch(S){Wt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Wt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const h={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:h,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Wt.log(`Error page ${e} rendered successfully`),!0}catch(r){return Wt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){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")r[i.initLocal]=c,Wt.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(c,f):c,Wt.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,Wt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:h,path:m}=f;this.globalState[h]=m?this.getValueByPath(c,m):c,Wt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${h}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Wt.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&&Wt.log("Config cache cleared")}}const Kc=pt("AssetFailureNotice"),Rb="g7-asset-failure-notice",Xx="g7-system-banners",Kr=new Map;let _s=!1,Wc=!1,Yo=null;function As(s,e,n){try{const r=window?.G7Core?.t;if(typeof r=="function"){const i=r(s,n);if(typeof i=="string"&&i!==s&&!i.startsWith("core.assets."))return i}}catch{}return Jx(e,n)}function Jx(s,e){return e?Object.entries(e).reduce((n,[r,i])=>n.split("{"+r+"}").join(String(i)),s):s}function xs(s){!s||!s.id||(Kr.set(s.id,s),Wc=!1,Kc.warn(`Asset failure notified: ${s.id} (${s.label})`),Ts())}function Db(s){Kr.delete(s)&&(Kc.log(`Asset failure cleared: ${s}`),Ts())}function Ob(){Kr.size!==0&&(Kr.clear(),Ts())}function Qx(){return Array.from(Kr.values())}async function Lb(){if(_s)return;_s=!0,Wc=!1,Ts();const s=Array.from(Kr.values()).filter(n=>typeof n.retry=="function");let e=!1;for(const n of s)try{await n.retry(),Kr.delete(n.id)}catch(r){e=!0,Kc.warn(`Asset retry failed: ${n.id}`,r)}_s=!1,Wc=e,Ts()}function Zx(){try{return document.documentElement.classList.contains("dark")}catch{return!1}}function Ts(){if(typeof document>"u"||!document.body)return;const s=document.getElementById(Rb);if(Kr.size===0){s?.remove(),sT();return}const e=s??eT();tT(e),e.replaceChildren(nT()),iT()}function eT(){const s=document.createElement("div");return s.id=Rb,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),document.body.appendChild(s),s}function tT(s){const n=document.getElementById(Xx)?.offsetHeight??0;s.style.cssText=["position:fixed",`top:${n}px`,"left:0","right:0","z-index:9998","display:flex","justify-content:center","pointer-events:none"].join(";")}function nT(){const s=Zx(),e=Array.from(Kr.values()),n=typeof window<"u"&&window.innerWidth<768,r=document.createElement("div");return r.style.cssText=["pointer-events:auto","box-sizing:border-box","width:100%","max-width:960px","margin:8px","padding:12px 16px","border-radius:8px",`border:1px solid ${s?"#78350f":"#fcd34d"}`,`background:${s?"#451a03":"#fffbeb"}`,`color:${s?"#fef3c7":"#78350f"}`,"box-shadow:0 4px 12px rgba(0,0,0,0.12)","font-size:14px","line-height:1.5","display:flex",n?"flex-direction:column":"flex-direction:row",n?"align-items:stretch":"align-items:center","gap:12px"].join(";"),r.style.background=s?"#451a03":"#fffbeb",r.style.color=s?"#fef3c7":"#78350f",r.style.borderColor=s?"#78350f":"#fcd34d",r.appendChild(rT(e,n)),r.appendChild(aT(e,n,s)),r}function rT(s,e){const n=document.createElement("div");n.style.cssText=["flex:1 1 auto","min-width:0","display:flex","gap:8px"].join(";");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⚠",r.style.cssText="flex:0 0 auto;font-size:16px;line-height:1.4",n.appendChild(r);const i=document.createElement("div");if(i.style.cssText="flex:1 1 auto;min-width:0",s.length===1){const l=s[0],c=document.createElement("div");c.setAttribute("data-asset-failure-id",l.id),c.textContent=l.message??As("core.assets.load_failed","{label}을(를) 불러오지 못했습니다.",{label:l.label}),i.appendChild(c)}else{const l=document.createElement("div");l.style.cssText="font-weight:600",l.textContent=As("core.assets.load_failed_multiple","{count}개 항목을 불러오지 못했습니다.",{count:s.length}),i.appendChild(l);const c=document.createElement("div");c.style.cssText="margin-top:2px;opacity:0.9;word-break:break-word",c.textContent=s.map(d=>d.label).join(", "),i.appendChild(c)}if(Wc){const l=document.createElement("div");l.style.cssText="margin-top:4px;font-weight:600",l.textContent=As("core.assets.retry_failed","다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요."),i.appendChild(l)}return n.appendChild(i),e&&(n.style.alignItems="flex-start"),n}function aT(s,e,n){const r=document.createElement("div");if(r.style.cssText=["flex:0 0 auto","display:flex","gap:8px",e?"width:100%":"","align-items:center"].filter(Boolean).join(";"),s.some(c=>typeof c.retry=="function")){const c=document.createElement("button");c.type="button",c.dataset.action="retry",c.disabled=_s,c.textContent=_s?As("core.assets.retrying","다시 시도 중..."):As("core.assets.retry","다시 시도"),c.style.cssText=[e?"flex:1 1 auto":"","padding:6px 14px","border-radius:6px","font-size:14px","font-weight:600","cursor:pointer",`border:1px solid ${n?"#b45309":"#d97706"}`,`background:${n?"#b45309":"#f59e0b"}`,`color:${n?"#fffbeb":"#451a03"}`,_s?"opacity:0.6":""].filter(Boolean).join(";"),c.addEventListener("click",()=>{Lb()}),r.appendChild(c)}const l=document.createElement("button");return l.type="button",l.dataset.action="close",l.setAttribute("aria-label",As("core.assets.close","닫기")),l.textContent="✕",l.style.cssText=["padding:6px 10px","border-radius:6px","font-size:14px","cursor:pointer","border:1px solid transparent","background:transparent",`color:${n?"#fef3c7":"#78350f"}`].join(";"),l.addEventListener("click",()=>{Ob()}),r.appendChild(l),r}function iT(){Yo||typeof MutationObserver>"u"||(Yo=new MutationObserver(()=>{Kr.size>0&&Ts()}),Yo.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function sT(){Yo?.disconnect(),Yo=null}function oT(){const s=window,e=r=>({id:String(r?.id??""),label:String(r?.label??r?.url??"asset"),retry:typeof r?.retry=="function"?r.retry:void 0}),n=Array.isArray(s.__g7ExternalAssetFailures)?s.__g7ExternalAssetFailures:[];n.forEach(r=>{r?.id&&xs(e(r))}),s.__g7ExternalAssetSink=r=>{r?.id&&xs(e(r))},Kc.log(`템플릿 externals 실패 대기열 ${n.length}건 반영`)}const Rt=pt("ModuleAssetLoader");class lT{constructor(){M(this,"loadedAssets",new Map);M(this,"loadingPromises",new Map);M(this,"failedJsAssets",new Set);M(this,"failedCssAssets",new Set)}getFailedCssAssets(){return[...this.failedCssAssets]}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Rt.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Rt.log("Loading module assets:",n.map(d=>d.identifier));const r=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([...r,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Rt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Rt.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Rt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadCustomAssets(){const e=cT();if(e.length!==0)for(const n of e){const r=`g7-custom-${n.type}-${uT(n.id)}`;if(document.getElementById(r))continue;const i=`${n.type==="style"?"custom CSS":"custom JS"}: ${n.id}`,l=(d,f)=>n.type==="style"?ia(Ln(d),{id:r},{label:i,retries:f}):Cr(Ln(d),{id:r},{label:i,retries:f}),c=jd(n.url);try{if(c!==null)try{await l(n.url,0)}catch{Rt.warn(`Custom asset static miss, falling back to API: ${n.id} (${n.url} -> ${c})`),await l(c)}else await l(n.url);Rt.log(`Custom asset loaded: ${n.id}`)}catch(d){Rt.warn(`Failed to load custom asset: ${n.id} (${n.url})`,d),xs({id:`custom-asset:${n.id}`,label:n.id.split(":").pop()??n.id,retry:async()=>{document.getElementById(r)?.remove(),await l(c??n.url)}})}}}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Rt.log(`Bundle CSS already loaded: ${e}`);return}const i=jd(n);try{if(i!==null)try{await ia(n,{id:r},{label:`bundle CSS: ${e}`,retries:0})}catch{Rt.warn(`Bundle CSS static miss, falling back to API: ${e} (${n} -> ${i})`),await ia(Ln(i),{id:r},{label:`bundle CSS: ${e}`})}else await ia(n,{id:r},{label:`bundle CSS: ${e}`});Rt.log(`Bundle CSS loaded: ${e}`);const l=document.getElementById(r);l&&this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l})}catch(l){this.surfaceCssFailure(`bundle-${e}`,e,i!==null?Ln(i):n,l)}}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Rt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`Bundle JS already loading: ${e}`),i;const l=jd(n),d=(l!==null?Cr(n,{id:r},{label:`bundle JS: ${e}`,retries:0}).catch(()=>(Rt.warn(`Bundle JS static miss, falling back to API: ${e} (${n} -> ${l})`),Cr(Ln(l),{id:r},{label:`bundle JS: ${e}`}))):Cr(n,{id:r},{label:`bundle JS: ${e}`})).then(()=>{Rt.log(`Bundle JS loaded: ${e}`);const f=document.getElementById(r);f&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:f}),this.loadingPromises.delete(r)}).catch(f=>{throw Rt.warn(`Failed to load bundle JS: ${e} (${n})`,f),this.failedJsAssets.add(e),this.loadingPromises.delete(r),f});return this.loadingPromises.set(r,d),d}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Rt.log(`CSS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`CSS already loading: ${e}`),i;const l=ia(n,{id:r},{label:`CSS: ${e}`}).then(()=>{Rt.log(`CSS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"css",element:c}),this.loadingPromises.delete(r)}).catch(c=>{this.loadingPromises.delete(r),this.surfaceCssFailure(e,e,n,c)});return this.loadingPromises.set(r,l),l}surfaceCssFailure(e,n,r,i){Rt.warn(`Failed to load CSS after retries: ${e} (${r})`,i),this.failedCssAssets.add(e),xs({id:`ext-css:${e}`,label:n,retry:async()=>{document.getElementById(`module-css-${e}`)?.remove(),document.getElementById(`ext-bundle-css-${e.replace(/^bundle-/,"")}`)?.remove(),await ia(r,{},{label:`CSS retry: ${e}`}),this.failedCssAssets.delete(e)}})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Rt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Rt.log(`JS already loading: ${e}`),i;const l=Cr(n,{id:r},{label:`JS: ${e}`}).then(()=>{Rt.log(`JS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Rt.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 r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Rt.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Rt.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Rt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Rt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let dh=null;function cT(){const s=window?.G7Config?.customAssets;return Array.isArray(s)?s.filter(e=>e&&typeof e.id=="string"&&typeof e.url=="string"&&(e.type==="style"||e.type==="script")):[]}function uT(s){return s.replace(/[^A-Za-z0-9_-]/g,"-")}function fh(){return dh||(dh=new lT),dh}function dT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(s.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}function fT(){if(typeof window>"u")return null;const s=window.G7Config;if(!s?.bundleUrls)return null;const e=s.bundleUrls;return{moduleJs:e.moduleJs?Ln(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ln(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ln(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ln(e.pluginCss):e.pluginCss}}function hT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(s.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}const hh=pt("SystemBannerManager");class Yc{static show(e){this.banners.set(e.id,e),this.render(),hh.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),hh.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),hh.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)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),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`:"")}}M(Yc,"banners",new Map),M(Yc,"containerId","g7-system-banners");const U=pt("TemplateApp");function $b(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Lr=class Lr{constructor(e){M(this,"router",null);M(this,"layoutLoader",null);M(this,"errorPageHandler",null);M(this,"config");M(this,"globalState");M(this,"globalStateListeners",new Set);M(this,"currentRouteChangeId",0);M(this,"failedLayoutScripts",new Set);M(this,"currentDataSources",[]);M(this,"currentRawDataSources",[]);M(this,"currentRouteParams",{});M(this,"currentQueryParams",new URLSearchParams);M(this,"currentFetchedData",{});M(this,"currentLayoutName","");M(this,"templateErrorHandling",null);M(this,"currentWebSocketSubscriptions",[]);M(this,"extensionCacheVersion",0);M(this,"currentGlobalHeaders",[]);M(this,"transitionOverlayEl",null);M(this,"skeletonOverlayRoot",null);M(this,"skeletonOverlayContainer",null);M(this,"_spinnerState",null);M(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!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,U.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,U.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,U.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,U.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new $n,r={_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,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(U.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,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(U.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 r=localStorage.getItem(n);r&&r!==localStorage.getItem(Lr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Lr.LOCALE_STORAGE_KEY,r),U.log(`Migrated locale from '${n}' to '${Lr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){U.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{po.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),v0();const e=Er.getInstance(),n=Ar.getInstance(),r=typeof window<"u"&&Number(window.G7Config?.cache_version)||0,i=r>0?r:this.loadCacheVersionFromStorage()||0,[l,c,d,f,h]=await Promise.all([tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:i}),e.loadComponents(this.config.templateId,this.config.templateType,i),rc(i>0?go(`templates/${this.config.templateId}/routes.json`,i):null,Ur(`/api/templates/${this.config.templateId}/routes`,"json",i>0?i: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 U.error("Error loading routes:",A),A}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Ur(`/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=>(U.warn("Error loading template config:",A),null))]);if(U.log("Template Engine initialized"),U.log("ComponentRegistry loaded"),U.log("Routes data loaded"),U.log("User info preloaded"),U.log("Template config loaded:",h),h?.cache_version!==void 0){const A=i>0?i:null;if(this.extensionCacheVersion=h.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),U.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){U.log("Cache version changed, reloading routes...");const D=await rc(go(`templates/${this.config.templateId}/routes.json`,this.extensionCacheVersion),Ur(`/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(D.routes)&&(D.routes=this.resolveRouteExpressions(D.routes),Object.assign(d,D),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>Jg),k=O.getInstance();k.setCacheVersion(this.extensionCacheVersion);const L=this.config.locale||"ko",B="en";await k.loadTranslations(this.config.templateId,L,"/api",!0),L!==B&&await k.loadTranslations(this.config.templateId,B,"/api",!0),U.log("Translations reloaded with new cache version")}catch(O){U.error("Failed to reload translations:",O)}}}h?.errorHandling&&(this.templateErrorHandling=h.errorHandling,Tr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{U.log("User logged out")}),n.on("authStateChange",A=>{U.log("Auth state changed:",A)}),U.log("AuthManager event handlers registered");const m=qr(),y=this.config.templateType==="admin"?"admin":"user",v=n.getConfig(y);m.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),m.removeToken();const A=window.location.pathname+window.location.search,D=n.getLoginRedirectUrl(y,A,"session_expired");window.location.href=D}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ah(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Dr({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Yx({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Rs,dataSourceManager:S,globalState:this.globalState}),U.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){U.log("Server error handled, skipping normal initialization");return}if(this.router=new Kx(this.config.templateId),Array.isArray(d.routes)){const A=this.resolveRouteExpressions(d.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");U.log("Router initialized:",this.router),U.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:_}=await Promise.resolve().then(()=>Wr),x=_();if(x&&(x.setDefaultContext({navigate:A=>this.router?.navigate(A)}),x.setGlobalStateUpdater((A,D)=>this.setGlobalState(A,D)),U.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"&&kb(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await Rs({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),U.log("Template App initialized successfully")}catch(e){U.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=fh(),n=fT();if(!n){await this.loadExtensionAssetsIndividually(),await e.loadCustomAssets();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),await e.loadCustomAssets(),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=fh(),n=dT();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=hT();r.length>0&&(U.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}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(U.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 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(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=Tr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},h=new URLSearchParams;for(const[ee,me]of Object.entries(f))if(Array.isArray(me))for(const H of me)h.append(ee,H);else h.set(ee,me);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:v}=await Promise.resolve().then(()=>Wr),S=new y;if(i){const ee=v();ee&&ee.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Yc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),U.log("Preview mode activated")}else{const ee=v();ee?.isPreviewMode()&&(ee.setPreviewMode(!1),Yc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const ee=v();ee&&ee.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(me=>me.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const ee=v();ee&&ee.setNamedActions(l.named_actions)}const _=S.filterByCondition(d,m);d.length!==_.length&&U.log("Data sources filtered by condition:",{before:d.map(ee=>ee.id),after:_.map(ee=>ee.id)});const x=_.filter(ee=>ee.loading_strategy==="blocking"),A=_.filter(ee=>(ee.loading_strategy||"progressive")!=="blocking"&&ee.type!=="websocket"),D=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],O=D.length>0&&_.some(ee=>D.includes(ee.id)&&ee.type!=="websocket"&&(ee.loading_strategy||"progressive")!=="background");if((x.length>0||O)&&l.transition_overlay){const ee=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;ee.enabled&&ee.style==="skeleton"&&ee.skeleton?.component&&ee.target?this.renderSkeletonOverlay(ee.target,ee.skeleton,l,ee.fallback_target):ee.enabled&&ee.style==="spinner"&&ee.target&&this.renderSpinnerOverlay(ee.target,ee.spinner,ee.fallback_target)}let k={},L={},B={},q={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=h,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,h.toString()),x.length>0&&(U.log("Fetching blocking data sources:",x.map(me=>me.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},h)).forEach(me=>{if(me.state==="success"&&me.data!==void 0)k[me.id]=me.data;else if(me.state==="error"&&me.error){const H=me.error,T=H.response?.data?.message;L[me.id]={message:T||me.error.message,status:H.response?.status||H.status}}}),this.processInitOptions(x,k,B,q),this.currentFetchedData={...k},U.log("Blocking data loaded:",Object.keys(k)),Object.keys(L).length>0&&U.log("Data source errors:",L),Object.keys(B).length>0&&U.log("Local state init (blocking):",Object.keys(B)),Object.keys(q).length>0&&U.log("Isolated state init (blocking):",Object.keys(q)));const z=A.length>0;if(z&&(Gr.setPending(!0),U.log("Transition started before rendering")),n!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:W}=await Promise.resolve().then(()=>Wr),de=W().currentDataContext||{},_e=A.map(ee=>ee.id),Se={};if(z){_e.forEach(me=>{de[me]!==void 0?Se[me]=de[me]:Se[me]=void 0});const ee=Object.keys(Se).filter(me=>Se[me]!==void 0);ee.length>0&&U.log("Preserving previous progressive data:",ee),U.log("Progressive data sources initialized:",_e)}const Ie=l.defines||{},Fe={...Se,...e.params,...k,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:ee=>this.setGlobalState(ee),_dataSourceErrors:Object.keys(L).length>0?L:void 0,_localInit:Object.keys(B).length>0?B:void 0,_isolatedInit:Object.keys(q).length>0?q:void 0,_defines:Object.keys(Ie).length>0?Ie:void 0};if(l.computed&&Object.keys(l.computed).length>0){const ee=this.calculateComputed(l.computed,Fe);Object.keys(ee).length>0&&(Fe._computed=ee,this.globalState._computed=ee,U.log("Computed values calculated:",Object.keys(ee))),Fe._computedDefinitions=l.computed}const ze=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==ze&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:ze}),this.globalState._local={},c_()),this.currentLayoutName=ze;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[ee,me]of Object.entries(Q))this.globalState._local[ee]===void 0&&(this.globalState._local[ee]=JSON.parse(JSON.stringify(me)));Fe._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[ee,me]of Object.entries(l.initGlobal))this.globalState[ee]===void 0&&(this.globalState[ee]=JSON.parse(JSON.stringify(me)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[ee,me]of Object.entries(l.initIsolated))q[ee]===void 0&&(q[ee]=JSON.parse(JSON.stringify(me)));U.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),U.log("initActions executed before render");const ee=this.globalState;if(ee._local){if(Object.keys(B).length>0){for(const[me,H]of Object.entries(B))ee._local[me]!==void 0?ee._local[me]=this.deepMerge(ee._local[me],H):ee._local[me]=H;U.log("localInit merged into _local after initActions:",Object.keys(B))}Fe._local=ee._local,U.log("_local merged into dataContext:",ee._local)}if(Fe._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const me=this.calculateComputed(l.computed,Fe);Object.keys(me).length>0&&(Fe._computed=me,this.globalState._computed=me,U.log("Computed values recalculated after init_actions:",Object.keys(me)))}if(Object.keys(this.currentFetchedData).length>0){for(const[me,H]of Object.entries(this.currentFetchedData))Fe[me]=H;U.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 Rs({containerId:"app",layoutJson:l,dataContext:Fe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),A.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Gr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",A.map(H=>H.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr);try{const H=A.map(async T=>{try{const he=(await S.fetchDataSourcesWithResults([T],e.params||{},h,this.globalState))[0];if(!he){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(he.state==="success"&&he.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=he.data;const Ae={};this.processInitOptions([T],{[T.id]:he.data},Ae);const se=me();if(se.bindingEngine){const $e=[T.id];T.initGlobal&&$e.push("_global"),T.initLocal&&$e.push("_local"),se.bindingEngine.invalidateCacheByKeys($e)}const ge={[T.id]:he.data};Object.keys(Ae).length>0&&(ge._localInit=Ae,Object.assign(B,Ae)),T.initGlobal&&(ge._global={...this.globalState}),ee(ge)}else if(he.state==="error"&&he.error){const Ae=he.error,se=Ae.response?.data?.message;L[T.id]={message:se||he.error.message,status:Ae.response?.status||Ae.status},U.log(`Progressive data source error: ${T.id}`,L[T.id]),ee({[T.id]:null,_dataSourceErrors:{...L}})}}catch(fe){U.error(`Failed to fetch data source: ${T.id}`,fe)}});if(await Promise.all(H),n!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",n);return}U.log("All progressive data sources loaded")}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const De=_.filter(ee=>ee.type==="websocket");if(De.length>0){U.log("Subscribing WebSocket data sources:",De.map(T=>T.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr),H={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};U.log("WebSocket binding context keys:",Object.keys(H)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(_,(T,fe)=>{U.log(`WebSocket data received for: ${T}`,fe),this.currentFetchedData[T]=fe;const he=_.find($e=>$e.id===T),Ae=me();if(Ae.bindingEngine){const $e=[T];he?.initGlobal&&$e.push("_global"),he?.initLocal&&$e.push("_local"),Ae.bindingEngine.invalidateCacheByKeys($e)}ee({[T]:fe});const ge=_.find($e=>$e.type==="websocket"&&($e.target_source||$e.id)===T)?.onReceive;Array.isArray(ge)&&ge.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Te of ge)try{const je=this.getActionDispatcher?.();je&&await je.dispatchAction(Te,{navigate:this.getRouter?.()?(xt,rt)=>this.getRouter().navigate(xt,rt):void 0,setState:xt=>this.setGlobalState(xt),state:this.globalState,data:{...this.globalState,$args:[fe],$event:fe},_isDispatchFallbackContext:!0})}catch(je){U.error(`WebSocket onReceive action failed for ${T}:`,je)}})()},H),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(r){U.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(r._forceLocalInit=Date.now(),U.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 h=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);h={...y,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof h=="object"?(r[c.initLocal]=this.deepMerge(m,h),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(r[c.initLocal]=h,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:h,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const S=this.evaluateDefaults(c.initLocalDefaults,n);y={...S,...y},U.log(`initLocalDefaults applied for ${h}:`,Object.keys(S))}const v=this.globalState._local?.[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(r[h]=this.deepMerge(v,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${h}`)):(r[h]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${h}`))}else if(typeof c.initLocal=="object"){const h=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,c.id);if(y.includes(".")){const _=y.split(".")[0];r[_]===void 0&&this.globalState._local?.[_]!==void 0&&(r[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(r,y,S,h),U.log(`initLocal map (${h}): ${c.id} ${v} -> _local.${y}`)}else{const _=this.globalState._local?.[y];h==="replace"?(r[y]=S,U.log(`initLocal map (replace): ${c.id} ${v} -> _local.${y}`)):h==="shallow"?_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]={..._,...S},U.log(`initLocal map (shallow): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _local.${y}`)):_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]=this.deepMerge(_,S),U.log(`initLocal map (deep): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _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"){U.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=v,U.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 v=this.globalState[y];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(v,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,U.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:v,path:S}=y,_=S?this.extractValueByPathOrExpression(f,S,c.id):f,x=this.globalState[v];x!==void 0&&typeof x=="object"&&typeof _=="object"?(this.globalState[v]=this.deepMerge(x,_),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=_,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const h=i[c.initIsolated];h!==void 0&&typeof h=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(h,f),U.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,U.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:h,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${h}`))}else if(typeof c.initIsolated=="object")for(const[h,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${h}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${h}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();r[i]=this.evaluateExpression(c,n)}else r[i]=l;return r}evaluateExpression(e,n){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(n,i);if(l!=null)return l}return}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,h]=d,m=[];f&&m.push(f);const y=h.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,r){const i=La(n);if(i!==null){const l=new $n,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Wn(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ds({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){U.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){U.log(`Script already loaded: ${i.id}`);continue}if(!this.isAllowedScriptSrc(i.src)){U.warn(`Blocked untrusted external script src (same-origin path or declared trusted host required): ${i.id} (${i.src})`);continue}r.push(this.loadLayoutScript(i))}r.length>0&&(await Promise.all(r),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}async loadLayoutScript(e){const n=e.src.startsWith("/")?Ln(e.src):e.src;try{await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id),Db(`layout-script:${e.id}`),U.log(`Script loaded successfully: ${e.id}`)}catch(r){this.failedLayoutScripts.add(e.id),U.warn(`Failed to load script after retries: ${e.id} (${n})`,r),xs({id:`layout-script:${e.id}`,label:e.id,retry:async()=>{document.getElementById(e.id)?.remove(),await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id)}})}}getFailedLayoutScripts(){return Array.from(this.failedLayoutScripts)}isAllowedScriptSrc(e){return Io(e)}static normalizeScriptSrcForOriginCheck(e){return by(e)}extractScriptHost(e){return vy(e)}getTrustedScriptHosts(){return ys()}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return!!af(r,n)}return!!e}catch(r){return U.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(tc()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=Tb(e);uh.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=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(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(r.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(r.target){const d=`#${CSS.escape(r.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 h=f.indexOf(":");h!==-1&&d.style.setProperty(f.slice(0,h).trim(),f.slice(h+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const c=Er.getInstance().getComponent(n.component);if(!c){U.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){U.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,v=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${v}{position:relative;z-index:0;}${v}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;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 k=d.getBoundingClientRect(),L=window.scrollX||document.documentElement.scrollLeft,B=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${k.top+B}px`,`left:${k.left+L}px`,`width:${k.width}px`,`height:${k.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const x=r.components||[];let A;if(f==="fullpage")A=x;else{const k=f==="fallback"?i:e;A=this.findComponentChildrenById(x,k)}const D=Od.createRoot(_);this.skeletonOverlayRoot=D,ja.flushSync(()=>{D.render(Xe.createElement(c,{components:A,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const O=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${O}] with "${n.component}" (${A.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=r(l.children);if(c!==null)return c}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?r: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 h=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:h},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,y=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=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=Er.getInstance().getComponent(n.component);if(c){const d=Od.createRoot(i);this.skeletonOverlayRoot=d,ja.flushSync(()=>{d.render(Xe.createElement(c,{options:{text:r}}))});return}U.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 r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),U.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 Rr&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!qr().getToken()||e.details?.hadToken===!0,f=Ar.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=Tb(e);uh.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;U.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"))?(U.log(`${e.code} error page rendered successfully`),!0):(U.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return U.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){U.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"))){U.log("404 error page rendered successfully");return}U.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){U.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(){U.log("reloadExtensionState: start");let e;try{const n=await fetch(Ur(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){U.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(U.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),U.log("reloadExtensionState: routes reloaded"))}catch(n){U.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(n){U.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>Jg),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(n){U.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}}),U.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){U.warn("reloadExtensionState: supportedLocales refresh failed",n)}U.log("reloadExtensionState: done")}getActionDispatcher(){return la().actionDispatcher}async changeLocale(e){try{if(U.log("Changing locale to:",e),this.config.locale===e){U.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),U.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),U.log("ErrorPageHandler locale updated")),Xc(),await tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),U.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Wr),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),U.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),U.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),U.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),U.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),U.log("Locale changed successfully to",e)}catch(n){throw U.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Lr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Lr.LOCALE_STORAGE_KEY,e)}catch(n){U.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){U.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(r,{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?U.log("Locale saved to DB:",e):U.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){U.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(Lr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return U.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Lr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){U.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),U.log(`Module handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),U.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(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),U.log(`Plugin handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},U.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Wr).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 r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){r=l;break}}if(!r){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Gr.setPending(!0);try{const i=new Dr;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=la(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},h=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,h,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const v={};this.processInitOptions([r],{[e]:y.data},v);const S=la();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const _={[e]:y.data};return Object.keys(v).length>0&&(_._localInit=v),r.initGlobal&&(_._global={...this.globalState}),Ds(_,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){U.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Gr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),U.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Wr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},h=this.currentFetchedData[e];if(!h)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=h;for(const _ of m)if(y=y?.[_],y===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const v=y.findIndex(_=>String(_[c])===String(r));if(v===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${r}' not found`),!1;d?y[v]=this.deepMerge(y[v],i):y[v]={...y[v],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Wr).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.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 r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let c=e;for(let h=0;h0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const h=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(h.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${h.length} auto_fetch data sources`),Gr.setPending(!0);const m=la().currentLayoutJson,y=m?.transition_overlay,v=Array.isArray(y?.wait_for)?y.wait_for:[],S=h.some(x=>(x.loading_strategy||"progressive")==="blocking"),_=v.length>0&&h.some(x=>v.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||_)&&y&&typeof y=="object"){const x=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&x?this.renderSkeletonOverlay(x,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&x&&this.renderSpinnerOverlay(x,y.spinner,y.fallback_target)}try{const x=new Dr;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const A=la(),D=A.currentDataContext?._global||{},O=await x.fetchDataSourcesWithResults(h,this.currentRouteParams,this.currentQueryParams,D,void 0,{ignoreAutoFetch:!1}),k={},L={},B=new Map(h.map(q=>[q.id,q]));for(const q of O){const z=B.get(q.id);if(!z){U.warn(`Refetch result id not found in autoFetchDataSources: ${q.id}`);continue}const W=q.id;q.state==="success"&&q.data!==void 0?(this.currentFetchedData[W]=q.data,k[W]=q.data,this.processInitOptions([z],{[W]:q.data},L),U.log(`Data source refetched: ${W}`)):q.state==="error"&&U.error(`Failed to refetch data source: ${W}`,q.error)}if(A.bindingEngine){const q=Object.keys(k);q.push("query"),A.bindingEngine.invalidateCacheByKeys(q)}if(Object.keys(L).length>0&&(k._localInit=L),Object.keys(k).length>0){if(k.query=$b(this.currentQueryParams),A.currentLayoutJson?.computed&&Object.keys(A.currentLayoutJson.computed).length>0){const q={...A.currentDataContext,...k,query:k.query},z=this.calculateComputed(A.currentLayoutJson.computed,q);Object.keys(z).length>0&&(k._computed=z,this.globalState._computed=z,U.log("Computed values recalculated in updateQueryParams:",Object.keys(z)))}Ds(k,{sync:!0}),U.log("Template data updated with new query params")}}catch(x){U.error("Error in updateQueryParams:",x)}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new $n;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;r[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return af(e,n)}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Wr),i=r();if(!i){U.warn("ActionDispatcher not available for init_actions");return}U.log("Executing init_actions:",e.map(d=>d.handler)),U.log("Init actions dataContext:",n),U.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},h=i.createHandler(f,c),m=new Event("init");await h(m),U.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},U.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){U.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=fh().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),h=n.filter(y=>!e.customHandlers?.has(y)),m=h.length>0&&h.every(y=>d.some(v=>y.startsWith(`${v}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:h,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const h=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(h,l)};h()})}};M(Lr,"LOCALE_STORAGE_KEY","g7_locale"),M(Lr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Xo=Lr;function ph(s){const e=new Xo(s);return s.websocket&&(Gc.configure(s.websocket),U.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=ph,window.G7Core.dataSource={refetch:async(s,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(s,e)},get:s=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(s)}});function pT(s={}){const{checked:e,value:n,name:r,type:i="checkbox"}=s,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:r??"",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 gT(s={}){const{button:e=0,clientX:n=0,clientY:r=0}=s;return{button:e,clientX:n,clientY:r,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 mT(){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 yT(s,e="keydown"){return{key:s,code:s.length===1?`Key${s.toUpperCase()}`:s,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:s}),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 bT={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 Mb(s){const e=s.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(bT))if(r.test(e))return n;return null}function Nb(s){const e=s.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function vT(s,e){if(!e||e.trim()==="")return s;if(!s||s.trim()==="")return e;const n=s.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of r){const d=Mb(c);if(d){const f=Nb(c),h=`${d}:${f}`;i.set(h,c)}}return[...n.filter(c=>{const d=Mb(c);if(!d)return!0;const f=Nb(c),h=`${d}:${f}`;return!i.has(h)}),...r].join(" ")}function ST(s){return Object.entries(s).filter(([,e])=>e).map(([e])=>e).join(" ")}function wT(...s){return s.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=pt("G7CoreGlobals");function CT(){window.React=Xe,window.ReactDOM={...Ld,createPortal:ja.createPortal,unstable_batchedUpdates:s=>s()},window.ReactJSXRuntime=r_,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function ET(s){const e=new Map,n=za.getInstance();s.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async h=>{try{return await h(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(h){d=h instanceof Error?h:new Error(String(h))}if(n.trackEventEmit(r,i,c,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function _T(s){s.__runtime||(s.__runtime={DynamicRenderer:Vr,ComponentRegistry:Er,TranslationEngine:Oa,DataSourceManager:Dr,dataSourceManager:qx,DataBindingEngine:$n,dataBindingEngine:of,ActionDispatcher:jo,TranslationReactContext:ih,TranslationProvider:Uc,useTranslation:gb,ResponsiveContext:If,ResponsiveProvider:Tc,useResponsive:jf,responsiveManager:Ci,BREAKPOINT_PRESETS:lc,AuthManager:Ar,createLogger:pt,G7DevToolsCore:za},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function AT(s){if(s.layoutEditor&&s.layoutEditor.__isStub!==!0||s.layoutEditor&&s.layoutEditor.__isStub===!0)return;const e=[],n=[];s.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function xT(s){s.asset={template:(e,n,r)=>d0(e,n,r),templateDir:(e,n)=>f0(e,n),module:(e,n,r)=>h0(e,n,r),plugin:(e,n,r)=>p0(e,n,r),convertToCurrentMode:e=>Ln(e),loadScript:(e,n,r)=>Io(e,ys())?Cr(e,n,r):Promise.reject(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`)),isAllowedScriptSrc:e=>Io(e,ys()),loadStylesheet:(e,n,r)=>ia(e,n,r)},s.assets={notifyFailure:xs,clearFailure:Db,clearAll:Ob,getFailures:Qx,retryAll:Lb},oT(),be.log("전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨")}function TT(s,e){s.useTranslation=gb,s.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function kT(s,e){s.createChangeEvent=pT,s.createClickEvent=gT,s.createSubmitEvent=mT,s.createKeyboardEvent=yT,s.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),s.createLogger=pt,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),s.renderItemChildren=(n,r,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},y=new Set,v=(_,x)=>{const A=m._global?._remountKeys;return _&&A?.[_]&&!y.has(_)?(y.add(_),`${_}-remount-${A[_]}`):_||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:v,...c};return Eo(n,m,i,l,S)},s.evaluateCondition=(n,r)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...r||{}},f=i.bindingEngine??of;return dm(n,d,f)},s.getComponentMap=()=>Er.getInstance().getComponentMap(),s.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=Er.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},h={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,y=(v,S)=>{const _=h._global?._remountKeys;return v&&_?.[v]&&!m.has(v)?(m.add(v),`${v}-remount-${_[v]}`):v||S};return Eo(n,h,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},s.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||Er.getInstance().getComponentMap(),h=e.getState(),m=s.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},v={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},_=h.bindingEngine??s.getDataBindingEngine?.(),x={...m,_local:v,_computed:S,row:i,item:i,$item:i};let A={};if(l&&typeof l=="object"&&_)try{for(const[L,B]of Object.entries(l))if(typeof B=="string"){const q=La(B);if(q!==null)try{A[L]=Wn(q)?_.evaluatePipeExpression(q,x,{skipCache:!0}):_.evaluateExpression(q,x,{skipCache:!0})}catch{A[L]=void 0}else A[L]=_.resolveBindings(B,x,{skipCache:!0})}else A[L]=B}catch(L){be.warn("renderExpandContent: expandContext 평가 오류:",L)}const D={row:i,item:i,$item:i,_local:v,_global:m._global||{},_computed:m._computed||{},...A},O=new Set,k=(L,B)=>{const q=D._global?._remountKeys;return L&&q?.[L]&&!O.has(L)?(O.add(L),`${L}-remount-${q[L]}`):L||B};return Eo(r,D,f,d,{translationContext:h.translationContext,translationEngine:h.translationEngine??void 0,bindingEngine:h.bindingEngine??void 0,actionDispatcher:h.actionDispatcher,componentContext:c,getRemountKey:k})},s.$get=function(r,i,l=void 0){if(r==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return r;let d=r;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},be.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),be.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),be.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),be.log("전역 객체 window.G7Core.$get에 노출됨")}function RT(s){s.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),c=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),h=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=h?.state??c;m&&h&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let v=h?.data??c;m&&h?.data?._local&&(v={...h.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(_,x)=>l.navigate(_,x):void 0,setState:h?.setState??d,state:y,data:v,_isDispatchFallbackContext:!h?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,x,()=>{const{debounce:A,debounceKey:D,...O}=e;i.dispatchAction(O,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(_){return be.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Jo(s){const e={};for(const[n,r]of Object.entries(s))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Jn(s,e){if(Array.isArray(s)&&!Array.isArray(e)&&DT(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=s.length+r.length+10)){const l=[...s];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={...s};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=Jn(n[r],i):n[r]={...i}:n[r]=i;return n}function OT(s){s.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Jo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...r.getGlobalState(),...l};else{const d=r.getGlobalState();c=Jn(d,l)}r.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const A=window.__g7AutoBindingPaths;A&&A.size>0&&Ib(Jo(e)).some(O=>A.has(O))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const A=r?.getActionDispatcher?.();if(A){const D=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:O,debounceKey:k,...L}=n;A.debouncedCall(D,n.debounce,()=>{s.state.setLocal(e,L)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Jo(e);if(i==="parent"||i==="root"){const A=window.__g7LayoutContextStack||[];if(A.length>0){const D=i==="parent"?A[A.length-1]:A[0];if(D?.setState){D.setState(O=>l==="replace"?d:l==="shallow"?{...O||{},...d}:Jn(O||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,h=r?.getGlobalState?.()?._local||{},v=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=v?Mo(h,v):h,_=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={..._,...d}:x=Jn(_,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,be.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const A=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(A,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const A=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Jn(A,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(A=>l==="replace"?d:l==="shallow"?{...A||{},...d}:Jn(A||{},d)),r?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Jn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Jn(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(be.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,r)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=r):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:r);const d=c?.merge||"deep",f=Jo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const h=window.__g7ActionContext;h?.isolatedContext?.mergeState?h.isolatedContext.mergeState(f,d):be.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return be.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||s.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){be.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){be.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=r):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",h=Jo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let v;f==="replace"?v=h:f==="shallow"?v={...y,...h}:v=Jn(y,h),window.__g7PendingLocalState=v;const S=window.__templateApp;if(S?.setGlobalState){const _=S.getGlobalState?.()?._local,A=f!=="replace"&&!!_&&typeof _=="object"&&!Array.isArray(_)?f==="shallow"?{..._,...h}:Jn(_,h):void 0;S.setGlobalState({_local:A?Mo(A,v):v})}if(l.setState(v),m?l.state._local=v:l.state=v,l.dataContext&&(l.dataContext._local=v),f==="replace")window.__g7ForcedLocalFields=h;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(_,h)}$f()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,s.state.set(r),be.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),s.state.getGlobal=s.state.get,s.state.setGlobal=s.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function LT(s){s.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,r,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return be.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return be.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,h=null;if(n){const y=n.split(".");h=y.pop();for(const v of y)if(f&&typeof f=="object"&&v in f)f=f[v];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[h]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&h?(f[h]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function $T(s,e){s.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function MT(s){s.toast={show:(e,n)=>{s.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{s.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{s.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{s.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{s.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function NT(s){s.modal={open:e=>{s.dispatch({handler:"openModal",target:e})},close:e=>{s.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{s.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=s.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>s.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function IT(s){s.style={mergeClasses:vT,conditionalClass:ST,joinClasses:wT},be.log("전역 객체 window.G7Core.style에 노출됨")}function jT(s,e){const{webSocketManager:n}=e;s.websocket={manager:n,subscribe:(r,i,l,c)=>n.subscribe(r,i,l,c),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function HT(s,e){const{transitionManager:n}=e;s.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(r(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function zT(s){s.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function PT(s){s.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function UT(s,e){const{transitionManager:n,responsiveManager:r}=e;s.AuthManager=Ar,s.api=qr(),s.TransitionManager=n,s.useTransitionState=Ay,s.ResponsiveManager=r,s.useResponsive=jf,s.useControllableState=m_,s.shallowArrayEqual=y_,s.shallowObjectEqual=Ty,s.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);be.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},be.log("전역 객체 window.G7Core.AuthManager에 노출됨"),be.log("전역 객체 window.G7Core.api에 노출됨"),be.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),be.log("전역 객체 window.G7Core.useResponsive에 노출됨"),be.log("전역 객체 window.G7Core.useControllableState에 노출됨"),be.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function BT(s,e){s.getSlotContext=()=>window.__slotContextValue??null,s.getDynamicRenderer=()=>window.__DynamicRenderer??null,s.getComponentRegistry=()=>e.getComponentRegistry?.()??Er.getInstance(),s.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,s.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,s.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function qT(s){s.identity={setLauncher:At.setLauncher.bind(At),handle:At.handle.bind(At),isIdentityRequired:At.isIdentityRequired.bind(At),hasLauncher:At.hasLauncher.bind(At),markDomainNoticeShown:At.markDomainNoticeShown.bind(At),redirectExternally:At.redirectExternally.bind(At),createDeferred:At.createDeferred.bind(At),resolveDeferred:At.resolveDeferred.bind(At),reset:At.reset.bind(At),redirectStashKey:Tf},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function GT(s){if(typeof window>"u")return;CT(),window.G7Core||(window.G7Core={});const e=window.G7Core;_T(e),ET(e),AT(e),UT(e,s),xT(e),TT(e,s),kT(e,s),RT(e),OT(e),LT(e),$T(e,s),MT(e),NT(e),IT(e),jT(e,s),HT(e,s),zT(e),PT(e),BT(e,s),qT(e),be.log("G7Core 전역 객체 초기화 완료")}function FT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>za.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,c)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,c):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,c,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,c)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,c,d,f)}catch{}},trackComponentStyle:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,c)}catch{}},trackAuthEvent:(r,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,c)}catch{}},trackAuthHeader:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,c,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,c,d)}catch{}},captureSequenceActionAfter:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,c,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,c,d,f,h)}catch{}},trackComputedRecalc:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,c,d,f,h)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};s.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Qo=null;function VT(){const s=window.G7Core;return s?.__devtools?Promise.resolve(s.__devtools):Qo||(Qo=new Promise((e,n)=>{const r=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 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Qo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Qo)}function KT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=za.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Md(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}WT(s,e)}async function WT(s,e){let n;try{n=await VT()}catch(h){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",h),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},Md();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;FT(),Md();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(h){be.warn("StyleTracker 활성화 실패:",h)}const c=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(h,m)=>e.watchState(h,m)},actions:{getHistory:()=>e.getActionHistory(),watch:h=>e.watchActions(h),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:h=>{const m=s.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(h,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:h=>c.analyze(h),suggestFix:h=>c.suggestFix(h),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:h=>c.getRulesByCategory(h)},server:{dumpState:h=>d.dumpState(h),sendLog:h=>d.sendLog(h),sendError:(h,m)=>d.sendError(h,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:h=>e.setLogLevel(h),setMaxHistory:h=>e.setMaxHistory(h)},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,s.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),YT(n.DevToolsPanel)}function YT(s){if(document.getElementById("g7-devtools-root")){be.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Ld.createRoot(e).render(Xe.createElement(s)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Qe=pt("TemplateEngine"),ae={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 Zo=!1;const el=[];async function XT(s){try{Qe.log("템플릿 메타데이터 로드 중...",s);const e=s.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Qe.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Qe.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Qe.error("템플릿 메타데이터 로드 실패",e),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function jb(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=ae.templateMetadata?.locales;return{$locale:ae.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:ae.templateId}}async function tl(s){try{if(Qe.log("템플릿 엔진 초기화 시작",s),ae.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!s.templateId)throw new Fx;Zo=s.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Zo),KT(),ae.templateId=s.templateId,ae.locale=s.locale||"ko",Qe.log("엔진 인스턴스 생성 중..."),ae.registry=Er.getInstance(),ae.bindingEngine=new $n,ae.translationEngine=Oa.getInstance(),s.cacheVersion!==void 0&&s.cacheVersion>0&&ae.translationEngine.setCacheVersion(s.cacheVersion),ae.translationContext={templateId:s.templateId,locale:ae.locale},ae.actionDispatcher=new jo({},ae.translationEngine,ae.translationContext),o_(ae.actionDispatcher),Qe.log("다국어 파일 로드 중...",s.templateId,ae.locale);const e="en",n=[ae.translationEngine.loadTranslations(s.templateId,ae.locale).then(()=>{Qe.log(`다국어 파일 로드 완료: ${ae.locale}`)}).catch(r=>{Qe.warn(`다국어 파일 로드 실패 (${ae.locale}):`,r instanceof Error?r.message:r)})];ae.locale!==e&&n.push(ae.translationEngine.loadTranslations(s.templateId,e).then(()=>{Qe.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Qe.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),Qe.log("템플릿 메타데이터 로드 중...",s.templateId),ae.templateMetadata=await XT(s.templateId),ae.isInitialized=!0,Qe.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Qe.error("템플릿 엔진 초기화 실패",e),ae.isInitialized=!1,ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,e}}let ks=null;const Hb="g7-layout-editor-bundle";function gh(){const s=window.G7Core;return s?.__LayoutEditorChrome?Promise.resolve(s.__LayoutEditorChrome):ks||(ks=(async()=>{const e=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js";document.getElementById(Hb)?.remove(),window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=()=>{};try{await Cr(e,{id:Hb},{label:"layout-editor bundle"})}catch(r){throw ks=null,Qe.error(`편집기 번들 로드 실패 (${e})`,r),new Error("편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.")}const n=window.G7Core?.__LayoutEditorChrome;if(!n)throw ks=null,Qe.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${e})`),new Error("편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.");return n})(),ks)}async function Rs(s){try{if(Qe.log("템플릿 렌더링 시작",s),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!s.containerId)throw new Error("containerId는 필수입니다.");if(!s.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(s.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${s.containerId}`);const n=jb();if(ae.containerId=s.containerId,ae.currentLayoutJson=s.layoutJson,ae.currentDataContext={...n,...s.dataContext||{}},ae.translationContext=s.translationContext||{templateId:ae.templateId||"",locale:ae.locale},ae.reactRoot||(Qe.log("React Root 생성"),ae.reactRoot=Ld.createRoot(e)),typeof window<"u"){const l=kb(window.location.pathname);if(l){Qe.log("레이아웃 편집기 모드 진입",l);let c;try{c=await gh()}catch(f){Qe.error("레이아웃 편집기 번들 로드 실패",f),uh.render(s.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Zo});return}const d=Xe.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ae.locale});ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext,children:Xe.createElement(Mf,{children:Xe.createElement(Tc,{children:Xe.createElement(sh,{children:d})})})}));return}}const r=s.layoutJson.components||[];if(r.length===0){Qe.warn("렌더링할 컴포넌트가 없습니다.");return}const i=s.layoutJson.modals||[];if(Qe.log("modals 배열:",i),Qe.log("modals 개수:",i.length),Qe.log("DynamicRenderer로 렌더링 시작"),ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...r.map((l,c)=>{const d=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),Xe.createElement(yy,{key:"__modal_parent_context_provider"},i.map(l=>{const c=ae.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||ae.currentDataContext._global?.activeModal===l.id,h=c.indexOf(l.id),m=h>=0?50+h:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,_=Xe.createElement(Vr,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?Xe.createElement(xb,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:_}):_}))]))))),Qe.log("템플릿 렌더링 완료"),el.length>0){Qe.log(`대기 중인 데이터 업데이트 ${el.length}건 적용`);const l=[...el];el.length=0;for(const{data:c,options:d}of l)Ds(c,d)}}catch(e){throw Qe.error("템플릿 렌더링 실패",e),e}}function Ds(s,e){try{if(Qe.log("템플릿 데이터 업데이트 시작",Object.keys(s)),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ae.reactRoot||!ae.currentLayoutJson){Qe.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(s)),el.push({data:s,options:e});return}const n=jb(),r={...ae.currentDataContext._global||{},...s._global||{}},i=p_(ae.currentDataContext._localInit,s._localInit);ae.currentDataContext={...n,...ae.currentDataContext,...s,_global:r,_localInit:i},r._local!==void 0&&(ae.currentDataContext._local=r._local),r._computed!==void 0&&(ae.currentDataContext._computed=r._computed);const l=ae.currentLayoutJson.components||[],c=ae.currentLayoutJson.modals||[];Qe.log("updateTemplateData - modals 배열:",c),Qe.log("updateTemplateData - modals 개수:",c.length),Qe.log("updateTemplateData - activeModal:",ae.currentDataContext._global?.activeModal);const d=()=>{ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...l.map((f,h)=>{const m=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:h===0,layoutKey:m})}),Xe.createElement(yy,{key:"__modal_parent_context_provider_update"},c.map(f=>{const h=ae.currentDataContext._global?.modalStack||[],y=h.includes(f.id)||ae.currentDataContext._global?.activeModal===f.id,v=h.indexOf(f.id),S=v>=0?50+v:50,_=window.__g7LayoutContextStack||[],A=_[_.length-1]?.dataContext,D=Xe.createElement(Vr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:S},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:A});return f.data_sources&&f.data_sources.length>0?Xe.createElement(xb,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:D}):D}))])))))};e?.sync?(Qe.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Qe.log("재렌더링 시작 (with startTransition)"),I.startTransition(()=>{d()})),Qe.log("템플릿 데이터 업데이트 완료")}catch(n){throw Qe.error("템플릿 데이터 업데이트 실패",n),n}}function Xc(){try{Qe.log("템플릿 정리 시작"),ae.reactRoot&&(Qe.log("React Root 언마운트"),ae.reactRoot.unmount(),ae.reactRoot=null),ae.templateId=null,ae.locale="ko",ae.isInitialized=!1,ae.containerId=null,ae.currentLayoutJson=null,ae.currentDataContext={},ae.translationContext={templateId:"",locale:"ko"},ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,ae.templateMetadata=null,Qe.log("템플릿 정리 완료")}catch(s){throw Qe.error("템플릿 정리 실패",s),s}}function la(){return Object.freeze({...ae})}function zb(){return ae.actionDispatcher}const nl={initTemplateEngine:tl,renderTemplate:Rs,updateTemplateData:Ds,destroyTemplate:Xc,getState:la};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=nl,GT({getState:()=>({translationEngine:ae.translationEngine,translationContext:ae.translationContext,bindingEngine:ae.bindingEngine,actionDispatcher:ae.actionDispatcher,templateMetadata:ae.templateMetadata}),transitionManager:Gr,responsiveManager:Ci,webSocketManager:Gc}),Qe.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Wr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Dr,LayoutLoader:ah,TemplateApp:Xo,TemplateEngine:nl,default:nl,destroyTemplate:Xc,getActionDispatcher:zb,getState:la,initTemplateApp:ph,initTemplateEngine:tl,loadLayoutEditorBundle:gh,renderTemplate:Rs,updateTemplateData:Ds},Symbol.toStringTag,{value:"Module"}));tn.DataSourceManager=Dr,tn.LayoutLoader=ah,tn.TemplateApp=Xo,tn.TemplateEngine=nl,tn.default=nl,tn.destroyTemplate=Xc,tn.getActionDispatcher=zb,tn.getState=la,tn.initTemplateApp=ph,tn.initTemplateEngine=tl,tn.loadLayoutEditorBundle=gh,tn.renderTemplate=Rs,tn.updateTemplateData=Ds,Object.defineProperties(tn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); + `}static renderFromError(e,n,r,i=!1,l,c,d){let f,h;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?h=m.details.apiMessage:m.response?.data?.message&&(h=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:h,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 _s=pt("Router");class Wx{constructor(e){M(this,"routes",[]);M(this,"templateIdentifier");M(this,"eventHandlers",new Map);M(this,"pendingNavigation",null);M(this,"isNavigating",!1);M(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 r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Ur(`/api/templates/${this.templateIdentifier}/routes`,"json",n));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,_s.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw _s.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,_s.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,h)=>(r.push(h),"([^/]+)"));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 r.forEach((f,h)=>{d[f]=c[h+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,r=this.match(e);if(!r){_s.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){_s.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const c=this.getAuthType(r.route,e),d=Ar.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const h=d.getLoginRedirectUrl(c,e+n);_s.log(`Not authenticated, redirecting to: ${h}`),window.location.href=h;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: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 n=this.pendingNavigation;this.executeNavigation(n)}}}}const Yx=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function kb(s){const e=Yx.exec(s);return e?{templateIdentifier:e[1]}:null}const Wt=pt("ErrorPageHandler");class Xx{constructor(e){M(this,"templateId");M(this,"layoutLoader");M(this,"locale");M(this,"debug");M(this,"renderFunction");M(this,"dataSourceManager");M(this,"globalState");M(this,"errorConfig",null);M(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(Ur(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Wt.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&&Wt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Wt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Wt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Wt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Wt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Wt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Wt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Wt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Wt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Wt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),y=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...y];if(v.length>0)try{c=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&Wt.log("Data sources fetched:",Object.keys(c))}catch(S){Wt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Wt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const h={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:h,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Wt.log(`Error page ${e} rendered successfully`),!0}catch(r){return Wt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){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")r[i.initLocal]=c,Wt.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(c,f):c,Wt.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,Wt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:h,path:m}=f;this.globalState[h]=m?this.getValueByPath(c,m):c,Wt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${h}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Wt.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&&Wt.log("Config cache cleared")}}const Kc=pt("AssetFailureNotice"),Rb="g7-asset-failure-notice",Jx="g7-system-banners",Kr=new Map;let As=!1,Wc=!1,Yo=null;function Ri(s,e,n){try{const r=window?.G7Core?.t;if(typeof r=="function"){const i=r(s,n);if(typeof i=="string"&&i!==s&&!i.startsWith("core.assets."))return i}}catch{}return Qx(e,n)}function Qx(s,e){return e?Object.entries(e).reduce((n,[r,i])=>n.split("{"+r+"}").join(String(i)),s):s}function xs(s){!s||!s.id||(Kr.set(s.id,s),Wc=!1,Kc.warn(`Asset failure notified: ${s.id} (${s.label})`),Ts())}function Db(s){Kr.delete(s)&&(Kc.log(`Asset failure cleared: ${s}`),Ts())}function Ob(){Kr.size!==0&&(Kr.clear(),Ts())}function Zx(){return Array.from(Kr.values())}function Lb(s,e,n){return Ri(s,e,n)}async function $b(){if(As)return;As=!0,Wc=!1,Ts();const s=Array.from(Kr.values()).filter(n=>typeof n.retry=="function");let e=!1;for(const n of s)try{await n.retry(),Kr.delete(n.id)}catch(r){e=!0,Kc.warn(`Asset retry failed: ${n.id}`,r)}As=!1,Wc=e,Ts()}function eT(){try{return document.documentElement.classList.contains("dark")}catch{return!1}}function Ts(){if(typeof document>"u"||!document.body)return;const s=document.getElementById(Rb);if(Kr.size===0){s?.remove(),oT();return}const e=s??tT();nT(e),e.replaceChildren(rT()),sT()}function tT(){const s=document.createElement("div");return s.id=Rb,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),document.body.appendChild(s),s}function nT(s){const n=document.getElementById(Jx)?.offsetHeight??0;s.style.cssText=["position:fixed",`top:${n}px`,"left:0","right:0","z-index:9998","display:flex","justify-content:center","pointer-events:none"].join(";")}function rT(){const s=eT(),e=Array.from(Kr.values()),n=typeof window<"u"&&window.innerWidth<768,r=document.createElement("div");return r.style.cssText=["pointer-events:auto","box-sizing:border-box","width:100%","max-width:960px","margin:8px","padding:12px 16px","border-radius:8px",`border:1px solid ${s?"#78350f":"#fcd34d"}`,`background:${s?"#451a03":"#fffbeb"}`,`color:${s?"#fef3c7":"#78350f"}`,"box-shadow:0 4px 12px rgba(0,0,0,0.12)","font-size:14px","line-height:1.5","display:flex",n?"flex-direction:column":"flex-direction:row",n?"align-items:stretch":"align-items:center","gap:12px"].join(";"),r.style.background=s?"#451a03":"#fffbeb",r.style.color=s?"#fef3c7":"#78350f",r.style.borderColor=s?"#78350f":"#fcd34d",r.appendChild(aT(e,n)),r.appendChild(iT(e,n,s)),r}function aT(s,e){const n=document.createElement("div");n.style.cssText=["flex:1 1 auto","min-width:0","display:flex","gap:8px"].join(";");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⚠",r.style.cssText="flex:0 0 auto;font-size:16px;line-height:1.4",n.appendChild(r);const i=document.createElement("div");if(i.style.cssText="flex:1 1 auto;min-width:0",s.length===1){const l=s[0],c=document.createElement("div");c.setAttribute("data-asset-failure-id",l.id),c.textContent=l.message??Ri("core.assets.load_failed","{label}을(를) 불러오지 못했습니다.",{label:l.label}),i.appendChild(c)}else{const l=document.createElement("div");l.style.cssText="font-weight:600",l.textContent=Ri("core.assets.load_failed_multiple","{count}개 항목을 불러오지 못했습니다.",{count:s.length}),i.appendChild(l);const c=document.createElement("div");c.style.cssText="margin-top:2px;opacity:0.9;word-break:break-word",c.textContent=s.map(d=>d.label).join(", "),i.appendChild(c)}if(Wc){const l=document.createElement("div");l.style.cssText="margin-top:4px;font-weight:600",l.textContent=Ri("core.assets.retry_failed","다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요."),i.appendChild(l)}return n.appendChild(i),e&&(n.style.alignItems="flex-start"),n}function iT(s,e,n){const r=document.createElement("div");if(r.style.cssText=["flex:0 0 auto","display:flex","gap:8px",e?"width:100%":"","align-items:center"].filter(Boolean).join(";"),s.some(c=>typeof c.retry=="function")){const c=document.createElement("button");c.type="button",c.dataset.action="retry",c.disabled=As,c.textContent=As?Ri("core.assets.retrying","다시 시도 중..."):Ri("core.assets.retry","다시 시도"),c.style.cssText=[e?"flex:1 1 auto":"","padding:6px 14px","border-radius:6px","font-size:14px","font-weight:600","cursor:pointer",`border:1px solid ${n?"#b45309":"#d97706"}`,`background:${n?"#b45309":"#f59e0b"}`,`color:${n?"#fffbeb":"#451a03"}`,As?"opacity:0.6":""].filter(Boolean).join(";"),c.addEventListener("click",()=>{$b()}),r.appendChild(c)}const l=document.createElement("button");return l.type="button",l.dataset.action="close",l.setAttribute("aria-label",Ri("core.assets.close","닫기")),l.textContent="✕",l.style.cssText=["padding:6px 10px","border-radius:6px","font-size:14px","cursor:pointer","border:1px solid transparent","background:transparent",`color:${n?"#fef3c7":"#78350f"}`].join(";"),l.addEventListener("click",()=>{Ob()}),r.appendChild(l),r}function sT(){Yo||typeof MutationObserver>"u"||(Yo=new MutationObserver(()=>{Kr.size>0&&Ts()}),Yo.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function oT(){Yo?.disconnect(),Yo=null}function lT(){const s=window,e=r=>({id:String(r?.id??""),label:String(r?.label??r?.url??"asset"),retry:typeof r?.retry=="function"?r.retry:void 0}),n=Array.isArray(s.__g7ExternalAssetFailures)?s.__g7ExternalAssetFailures:[];n.forEach(r=>{r?.id&&xs(e(r))}),s.__g7ExternalAssetSink=r=>{r?.id&&xs(e(r))},Kc.log(`템플릿 externals 실패 대기열 ${n.length}건 반영`)}const Rt=pt("ModuleAssetLoader");function cT(s){return s==="plugin"?Lb("core.assets.plugin_styles","플러그인 스타일"):Lb("core.assets.module_styles","모듈 스타일")}class uT{constructor(){M(this,"loadedAssets",new Map);M(this,"loadingPromises",new Map);M(this,"failedJsAssets",new Set);M(this,"failedCssAssets",new Set)}getFailedCssAssets(){return[...this.failedCssAssets]}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Rt.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Rt.log("Loading module assets:",n.map(d=>d.identifier));const r=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([...r,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Rt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Rt.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Rt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadCustomAssets(){const e=dT();if(e.length!==0)for(const n of e){const r=`g7-custom-${n.type}-${fT(n.id)}`;if(document.getElementById(r))continue;const i=`${n.type==="style"?"custom CSS":"custom JS"}: ${n.id}`,l=(d,f)=>n.type==="style"?ia(Ln(d),{id:r},{label:i,retries:f}):Cr(Ln(d),{id:r},{label:i,retries:f}),c=jd(n.url);try{if(c!==null)try{await l(n.url,0)}catch{Rt.warn(`Custom asset static miss, falling back to API: ${n.id} (${n.url} -> ${c})`),await l(c)}else await l(n.url);Rt.log(`Custom asset loaded: ${n.id}`)}catch(d){Rt.warn(`Failed to load custom asset: ${n.id} (${n.url})`,d),xs({id:`custom-asset:${n.id}`,label:n.id.split(":").pop()??n.id,retry:async()=>{document.getElementById(r)?.remove(),await l(c??n.url)}})}}}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Rt.log(`Bundle CSS already loaded: ${e}`);return}const i=jd(n);try{if(i!==null)try{await ia(n,{id:r},{label:`bundle CSS: ${e}`,retries:0})}catch{Rt.warn(`Bundle CSS static miss, falling back to API: ${e} (${n} -> ${i})`),await ia(Ln(i),{id:r},{label:`bundle CSS: ${e}`})}else await ia(n,{id:r},{label:`bundle CSS: ${e}`});Rt.log(`Bundle CSS loaded: ${e}`);const l=document.getElementById(r);l&&this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l})}catch(l){this.surfaceCssFailure(`bundle-${e}`,cT(e),i!==null?Ln(i):n,l)}}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Rt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`Bundle JS already loading: ${e}`),i;const l=jd(n),d=(l!==null?Cr(n,{id:r},{label:`bundle JS: ${e}`,retries:0}).catch(()=>(Rt.warn(`Bundle JS static miss, falling back to API: ${e} (${n} -> ${l})`),Cr(Ln(l),{id:r},{label:`bundle JS: ${e}`}))):Cr(n,{id:r},{label:`bundle JS: ${e}`})).then(()=>{Rt.log(`Bundle JS loaded: ${e}`);const f=document.getElementById(r);f&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:f}),this.loadingPromises.delete(r)}).catch(f=>{throw Rt.warn(`Failed to load bundle JS: ${e} (${n})`,f),this.failedJsAssets.add(e),this.loadingPromises.delete(r),f});return this.loadingPromises.set(r,d),d}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Rt.log(`CSS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`CSS already loading: ${e}`),i;const l=ia(n,{id:r},{label:`CSS: ${e}`}).then(()=>{Rt.log(`CSS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"css",element:c}),this.loadingPromises.delete(r)}).catch(c=>{this.loadingPromises.delete(r),this.surfaceCssFailure(e,e,n,c)});return this.loadingPromises.set(r,l),l}surfaceCssFailure(e,n,r,i){Rt.warn(`Failed to load CSS after retries: ${e} (${r})`,i),this.failedCssAssets.add(e),xs({id:`ext-css:${e}`,label:n,retry:async()=>{document.getElementById(`module-css-${e}`)?.remove(),document.getElementById(`ext-bundle-css-${e.replace(/^bundle-/,"")}`)?.remove(),await ia(r,{},{label:`CSS retry: ${e}`}),this.failedCssAssets.delete(e)}})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Rt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Rt.log(`JS already loading: ${e}`),i;const l=Cr(n,{id:r},{label:`JS: ${e}`}).then(()=>{Rt.log(`JS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Rt.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 r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Rt.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Rt.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Rt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Rt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let dh=null;function dT(){const s=window?.G7Config?.customAssets;return Array.isArray(s)?s.filter(e=>e&&typeof e.id=="string"&&typeof e.url=="string"&&(e.type==="style"||e.type==="script")):[]}function fT(s){return s.replace(/[^A-Za-z0-9_-]/g,"-")}function fh(){return dh||(dh=new uT),dh}function hT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(s.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}function pT(){if(typeof window>"u")return null;const s=window.G7Config;if(!s?.bundleUrls)return null;const e=s.bundleUrls;return{moduleJs:e.moduleJs?Ln(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ln(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ln(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ln(e.pluginCss):e.pluginCss}}function gT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(s.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}const hh=pt("SystemBannerManager");class Yc{static show(e){this.banners.set(e.id,e),this.render(),hh.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),hh.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),hh.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)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),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`:"")}}M(Yc,"banners",new Map),M(Yc,"containerId","g7-system-banners");const U=pt("TemplateApp");function Mb(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Lr=class Lr{constructor(e){M(this,"router",null);M(this,"layoutLoader",null);M(this,"errorPageHandler",null);M(this,"config");M(this,"globalState");M(this,"globalStateListeners",new Set);M(this,"currentRouteChangeId",0);M(this,"failedLayoutScripts",new Set);M(this,"currentDataSources",[]);M(this,"currentRawDataSources",[]);M(this,"currentRouteParams",{});M(this,"currentQueryParams",new URLSearchParams);M(this,"currentFetchedData",{});M(this,"currentLayoutName","");M(this,"templateErrorHandling",null);M(this,"currentWebSocketSubscriptions",[]);M(this,"extensionCacheVersion",0);M(this,"currentGlobalHeaders",[]);M(this,"transitionOverlayEl",null);M(this,"skeletonOverlayRoot",null);M(this,"skeletonOverlayContainer",null);M(this,"_spinnerState",null);M(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!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,U.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,U.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,U.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,U.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new $n,r={_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,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(U.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,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(U.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 r=localStorage.getItem(n);r&&r!==localStorage.getItem(Lr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Lr.LOCALE_STORAGE_KEY,r),U.log(`Migrated locale from '${n}' to '${Lr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){U.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{po.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),S0();const e=Er.getInstance(),n=Ar.getInstance(),r=typeof window<"u"&&Number(window.G7Config?.cache_version)||0,i=r>0?r:this.loadCacheVersionFromStorage()||0,[l,c,d,f,h]=await Promise.all([tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:i}),e.loadComponents(this.config.templateId,this.config.templateType,i),rc(i>0?go(`templates/${this.config.templateId}/routes.json`,i):null,Ur(`/api/templates/${this.config.templateId}/routes`,"json",i>0?i: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 U.error("Error loading routes:",A),A}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Ur(`/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=>(U.warn("Error loading template config:",A),null))]);if(U.log("Template Engine initialized"),U.log("ComponentRegistry loaded"),U.log("Routes data loaded"),U.log("User info preloaded"),U.log("Template config loaded:",h),h?.cache_version!==void 0){const A=i>0?i:null;if(this.extensionCacheVersion=h.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),U.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){U.log("Cache version changed, reloading routes...");const D=await rc(go(`templates/${this.config.templateId}/routes.json`,this.extensionCacheVersion),Ur(`/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(D.routes)&&(D.routes=this.resolveRouteExpressions(D.routes),Object.assign(d,D),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>Jg),k=O.getInstance();k.setCacheVersion(this.extensionCacheVersion);const L=this.config.locale||"ko",B="en";await k.loadTranslations(this.config.templateId,L,"/api",!0),L!==B&&await k.loadTranslations(this.config.templateId,B,"/api",!0),U.log("Translations reloaded with new cache version")}catch(O){U.error("Failed to reload translations:",O)}}}h?.errorHandling&&(this.templateErrorHandling=h.errorHandling,Tr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{U.log("User logged out")}),n.on("authStateChange",A=>{U.log("Auth state changed:",A)}),U.log("AuthManager event handlers registered");const m=qr(),y=this.config.templateType==="admin"?"admin":"user",v=n.getConfig(y);m.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),m.removeToken();const A=window.location.pathname+window.location.search,D=n.getLoginRedirectUrl(y,A,"session_expired");window.location.href=D}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ah(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Dr({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Xx({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Rs,dataSourceManager:S,globalState:this.globalState}),U.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){U.log("Server error handled, skipping normal initialization");return}if(this.router=new Wx(this.config.templateId),Array.isArray(d.routes)){const A=this.resolveRouteExpressions(d.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");U.log("Router initialized:",this.router),U.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:_}=await Promise.resolve().then(()=>Wr),x=_();if(x&&(x.setDefaultContext({navigate:A=>this.router?.navigate(A)}),x.setGlobalStateUpdater((A,D)=>this.setGlobalState(A,D)),U.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"&&kb(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await Rs({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),U.log("Template App initialized successfully")}catch(e){U.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=fh(),n=pT();if(!n){await this.loadExtensionAssetsIndividually(),await e.loadCustomAssets();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),await e.loadCustomAssets(),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=fh(),n=hT();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=gT();r.length>0&&(U.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}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(U.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 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(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=Tr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},h=new URLSearchParams;for(const[ee,me]of Object.entries(f))if(Array.isArray(me))for(const H of me)h.append(ee,H);else h.set(ee,me);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:v}=await Promise.resolve().then(()=>Wr),S=new y;if(i){const ee=v();ee&&ee.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Yc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),U.log("Preview mode activated")}else{const ee=v();ee?.isPreviewMode()&&(ee.setPreviewMode(!1),Yc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const ee=v();ee&&ee.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(me=>me.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const ee=v();ee&&ee.setNamedActions(l.named_actions)}const _=S.filterByCondition(d,m);d.length!==_.length&&U.log("Data sources filtered by condition:",{before:d.map(ee=>ee.id),after:_.map(ee=>ee.id)});const x=_.filter(ee=>ee.loading_strategy==="blocking"),A=_.filter(ee=>(ee.loading_strategy||"progressive")!=="blocking"&&ee.type!=="websocket"),D=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],O=D.length>0&&_.some(ee=>D.includes(ee.id)&&ee.type!=="websocket"&&(ee.loading_strategy||"progressive")!=="background");if((x.length>0||O)&&l.transition_overlay){const ee=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;ee.enabled&&ee.style==="skeleton"&&ee.skeleton?.component&&ee.target?this.renderSkeletonOverlay(ee.target,ee.skeleton,l,ee.fallback_target):ee.enabled&&ee.style==="spinner"&&ee.target&&this.renderSpinnerOverlay(ee.target,ee.spinner,ee.fallback_target)}let k={},L={},B={},q={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=h,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,h.toString()),x.length>0&&(U.log("Fetching blocking data sources:",x.map(me=>me.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},h)).forEach(me=>{if(me.state==="success"&&me.data!==void 0)k[me.id]=me.data;else if(me.state==="error"&&me.error){const H=me.error,T=H.response?.data?.message;L[me.id]={message:T||me.error.message,status:H.response?.status||H.status}}}),this.processInitOptions(x,k,B,q),this.currentFetchedData={...k},U.log("Blocking data loaded:",Object.keys(k)),Object.keys(L).length>0&&U.log("Data source errors:",L),Object.keys(B).length>0&&U.log("Local state init (blocking):",Object.keys(B)),Object.keys(q).length>0&&U.log("Isolated state init (blocking):",Object.keys(q)));const z=A.length>0;if(z&&(Gr.setPending(!0),U.log("Transition started before rendering")),n!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:W}=await Promise.resolve().then(()=>Wr),de=W().currentDataContext||{},_e=A.map(ee=>ee.id),Se={};if(z){_e.forEach(me=>{de[me]!==void 0?Se[me]=de[me]:Se[me]=void 0});const ee=Object.keys(Se).filter(me=>Se[me]!==void 0);ee.length>0&&U.log("Preserving previous progressive data:",ee),U.log("Progressive data sources initialized:",_e)}const Ie=l.defines||{},Fe={...Se,...e.params,...k,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:ee=>this.setGlobalState(ee),_dataSourceErrors:Object.keys(L).length>0?L:void 0,_localInit:Object.keys(B).length>0?B:void 0,_isolatedInit:Object.keys(q).length>0?q:void 0,_defines:Object.keys(Ie).length>0?Ie:void 0};if(l.computed&&Object.keys(l.computed).length>0){const ee=this.calculateComputed(l.computed,Fe);Object.keys(ee).length>0&&(Fe._computed=ee,this.globalState._computed=ee,U.log("Computed values calculated:",Object.keys(ee))),Fe._computedDefinitions=l.computed}const ze=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==ze&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:ze}),this.globalState._local={},u_()),this.currentLayoutName=ze;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[ee,me]of Object.entries(Q))this.globalState._local[ee]===void 0&&(this.globalState._local[ee]=JSON.parse(JSON.stringify(me)));Fe._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[ee,me]of Object.entries(l.initGlobal))this.globalState[ee]===void 0&&(this.globalState[ee]=JSON.parse(JSON.stringify(me)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[ee,me]of Object.entries(l.initIsolated))q[ee]===void 0&&(q[ee]=JSON.parse(JSON.stringify(me)));U.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),U.log("initActions executed before render");const ee=this.globalState;if(ee._local){if(Object.keys(B).length>0){for(const[me,H]of Object.entries(B))ee._local[me]!==void 0?ee._local[me]=this.deepMerge(ee._local[me],H):ee._local[me]=H;U.log("localInit merged into _local after initActions:",Object.keys(B))}Fe._local=ee._local,U.log("_local merged into dataContext:",ee._local)}if(Fe._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const me=this.calculateComputed(l.computed,Fe);Object.keys(me).length>0&&(Fe._computed=me,this.globalState._computed=me,U.log("Computed values recalculated after init_actions:",Object.keys(me)))}if(Object.keys(this.currentFetchedData).length>0){for(const[me,H]of Object.entries(this.currentFetchedData))Fe[me]=H;U.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 Rs({containerId:"app",layoutJson:l,dataContext:Fe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),A.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Gr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",A.map(H=>H.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr);try{const H=A.map(async T=>{try{const he=(await S.fetchDataSourcesWithResults([T],e.params||{},h,this.globalState))[0];if(!he){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(he.state==="success"&&he.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=he.data;const Ae={};this.processInitOptions([T],{[T.id]:he.data},Ae);const se=me();if(se.bindingEngine){const $e=[T.id];T.initGlobal&&$e.push("_global"),T.initLocal&&$e.push("_local"),se.bindingEngine.invalidateCacheByKeys($e)}const ge={[T.id]:he.data};Object.keys(Ae).length>0&&(ge._localInit=Ae,Object.assign(B,Ae)),T.initGlobal&&(ge._global={...this.globalState}),ee(ge)}else if(he.state==="error"&&he.error){const Ae=he.error,se=Ae.response?.data?.message;L[T.id]={message:se||he.error.message,status:Ae.response?.status||Ae.status},U.log(`Progressive data source error: ${T.id}`,L[T.id]),ee({[T.id]:null,_dataSourceErrors:{...L}})}}catch(fe){U.error(`Failed to fetch data source: ${T.id}`,fe)}});if(await Promise.all(H),n!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",n);return}U.log("All progressive data sources loaded")}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const De=_.filter(ee=>ee.type==="websocket");if(De.length>0){U.log("Subscribing WebSocket data sources:",De.map(T=>T.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr),H={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};U.log("WebSocket binding context keys:",Object.keys(H)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(_,(T,fe)=>{U.log(`WebSocket data received for: ${T}`,fe),this.currentFetchedData[T]=fe;const he=_.find($e=>$e.id===T),Ae=me();if(Ae.bindingEngine){const $e=[T];he?.initGlobal&&$e.push("_global"),he?.initLocal&&$e.push("_local"),Ae.bindingEngine.invalidateCacheByKeys($e)}ee({[T]:fe});const ge=_.find($e=>$e.type==="websocket"&&($e.target_source||$e.id)===T)?.onReceive;Array.isArray(ge)&&ge.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Te of ge)try{const je=this.getActionDispatcher?.();je&&await je.dispatchAction(Te,{navigate:this.getRouter?.()?(xt,rt)=>this.getRouter().navigate(xt,rt):void 0,setState:xt=>this.setGlobalState(xt),state:this.globalState,data:{...this.globalState,$args:[fe],$event:fe},_isDispatchFallbackContext:!0})}catch(je){U.error(`WebSocket onReceive action failed for ${T}:`,je)}})()},H),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(r){U.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(r._forceLocalInit=Date.now(),U.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 h=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);h={...y,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof h=="object"?(r[c.initLocal]=this.deepMerge(m,h),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(r[c.initLocal]=h,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:h,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const S=this.evaluateDefaults(c.initLocalDefaults,n);y={...S,...y},U.log(`initLocalDefaults applied for ${h}:`,Object.keys(S))}const v=this.globalState._local?.[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(r[h]=this.deepMerge(v,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${h}`)):(r[h]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${h}`))}else if(typeof c.initLocal=="object"){const h=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,c.id);if(y.includes(".")){const _=y.split(".")[0];r[_]===void 0&&this.globalState._local?.[_]!==void 0&&(r[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(r,y,S,h),U.log(`initLocal map (${h}): ${c.id} ${v} -> _local.${y}`)}else{const _=this.globalState._local?.[y];h==="replace"?(r[y]=S,U.log(`initLocal map (replace): ${c.id} ${v} -> _local.${y}`)):h==="shallow"?_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]={..._,...S},U.log(`initLocal map (shallow): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _local.${y}`)):_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]=this.deepMerge(_,S),U.log(`initLocal map (deep): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _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"){U.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=v,U.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 v=this.globalState[y];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(v,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,U.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:v,path:S}=y,_=S?this.extractValueByPathOrExpression(f,S,c.id):f,x=this.globalState[v];x!==void 0&&typeof x=="object"&&typeof _=="object"?(this.globalState[v]=this.deepMerge(x,_),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=_,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const h=i[c.initIsolated];h!==void 0&&typeof h=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(h,f),U.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,U.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:h,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${h}`))}else if(typeof c.initIsolated=="object")for(const[h,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${h}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${h}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();r[i]=this.evaluateExpression(c,n)}else r[i]=l;return r}evaluateExpression(e,n){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(n,i);if(l!=null)return l}return}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,h]=d,m=[];f&&m.push(f);const y=h.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,r){const i=La(n);if(i!==null){const l=new $n,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Wn(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!fs({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){U.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){U.log(`Script already loaded: ${i.id}`);continue}if(!this.isAllowedScriptSrc(i.src)){U.warn(`Blocked untrusted external script src (same-origin path or declared trusted host required): ${i.id} (${i.src})`);continue}r.push(this.loadLayoutScript(i))}r.length>0&&(await Promise.all(r),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}async loadLayoutScript(e){const n=e.src.startsWith("/")?Ln(e.src):e.src;try{await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id),Db(`layout-script:${e.id}`),U.log(`Script loaded successfully: ${e.id}`)}catch(r){this.failedLayoutScripts.add(e.id),U.warn(`Failed to load script after retries: ${e.id} (${n})`,r),xs({id:`layout-script:${e.id}`,label:e.id,retry:async()=>{document.getElementById(e.id)?.remove(),await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id)}})}}getFailedLayoutScripts(){return Array.from(this.failedLayoutScripts)}isAllowedScriptSrc(e){return Io(e)}static normalizeScriptSrcForOriginCheck(e){return by(e)}extractScriptHost(e){return vy(e)}getTrustedScriptHosts(){return bs()}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return!!af(r,n)}return!!e}catch(r){return U.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(tc()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=Tb(e);uh.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=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(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(r.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(r.target){const d=`#${CSS.escape(r.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 h=f.indexOf(":");h!==-1&&d.style.setProperty(f.slice(0,h).trim(),f.slice(h+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const c=Er.getInstance().getComponent(n.component);if(!c){U.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){U.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,v=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${v}{position:relative;z-index:0;}${v}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;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 k=d.getBoundingClientRect(),L=window.scrollX||document.documentElement.scrollLeft,B=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${k.top+B}px`,`left:${k.left+L}px`,`width:${k.width}px`,`height:${k.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const x=r.components||[];let A;if(f==="fullpage")A=x;else{const k=f==="fallback"?i:e;A=this.findComponentChildrenById(x,k)}const D=Od.createRoot(_);this.skeletonOverlayRoot=D,ja.flushSync(()=>{D.render(Xe.createElement(c,{components:A,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const O=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${O}] with "${n.component}" (${A.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=r(l.children);if(c!==null)return c}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?r: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 h=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:h},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,y=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=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=Er.getInstance().getComponent(n.component);if(c){const d=Od.createRoot(i);this.skeletonOverlayRoot=d,ja.flushSync(()=>{d.render(Xe.createElement(c,{options:{text:r}}))});return}U.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 r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),U.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 Rr&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!qr().getToken()||e.details?.hadToken===!0,f=Ar.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=Tb(e);uh.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;U.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"))?(U.log(`${e.code} error page rendered successfully`),!0):(U.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return U.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){U.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"))){U.log("404 error page rendered successfully");return}U.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){U.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(){U.log("reloadExtensionState: start");let e;try{const n=await fetch(Ur(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){U.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(U.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),U.log("reloadExtensionState: routes reloaded"))}catch(n){U.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(n){U.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>Jg),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(n){U.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}}),U.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){U.warn("reloadExtensionState: supportedLocales refresh failed",n)}U.log("reloadExtensionState: done")}getActionDispatcher(){return la().actionDispatcher}async changeLocale(e){try{if(U.log("Changing locale to:",e),this.config.locale===e){U.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),U.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),U.log("ErrorPageHandler locale updated")),Xc(),await tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),U.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Wr),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),U.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),U.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),U.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),U.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),U.log("Locale changed successfully to",e)}catch(n){throw U.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Lr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Lr.LOCALE_STORAGE_KEY,e)}catch(n){U.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){U.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(r,{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?U.log("Locale saved to DB:",e):U.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){U.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(Lr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return U.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Lr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){U.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),U.log(`Module handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),U.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(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),U.log(`Plugin handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},U.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Wr).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 r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){r=l;break}}if(!r){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Gr.setPending(!0);try{const i=new Dr;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=la(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},h=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,h,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const v={};this.processInitOptions([r],{[e]:y.data},v);const S=la();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const _={[e]:y.data};return Object.keys(v).length>0&&(_._localInit=v),r.initGlobal&&(_._global={...this.globalState}),Ds(_,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){U.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Gr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),U.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Wr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},h=this.currentFetchedData[e];if(!h)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=h;for(const _ of m)if(y=y?.[_],y===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const v=y.findIndex(_=>String(_[c])===String(r));if(v===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${r}' not found`),!1;d?y[v]=this.deepMerge(y[v],i):y[v]={...y[v],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Wr).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.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 r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let c=e;for(let h=0;h0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const h=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(h.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${h.length} auto_fetch data sources`),Gr.setPending(!0);const m=la().currentLayoutJson,y=m?.transition_overlay,v=Array.isArray(y?.wait_for)?y.wait_for:[],S=h.some(x=>(x.loading_strategy||"progressive")==="blocking"),_=v.length>0&&h.some(x=>v.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||_)&&y&&typeof y=="object"){const x=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&x?this.renderSkeletonOverlay(x,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&x&&this.renderSpinnerOverlay(x,y.spinner,y.fallback_target)}try{const x=new Dr;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const A=la(),D=A.currentDataContext?._global||{},O=await x.fetchDataSourcesWithResults(h,this.currentRouteParams,this.currentQueryParams,D,void 0,{ignoreAutoFetch:!1}),k={},L={},B=new Map(h.map(q=>[q.id,q]));for(const q of O){const z=B.get(q.id);if(!z){U.warn(`Refetch result id not found in autoFetchDataSources: ${q.id}`);continue}const W=q.id;q.state==="success"&&q.data!==void 0?(this.currentFetchedData[W]=q.data,k[W]=q.data,this.processInitOptions([z],{[W]:q.data},L),U.log(`Data source refetched: ${W}`)):q.state==="error"&&U.error(`Failed to refetch data source: ${W}`,q.error)}if(A.bindingEngine){const q=Object.keys(k);q.push("query"),A.bindingEngine.invalidateCacheByKeys(q)}if(Object.keys(L).length>0&&(k._localInit=L),Object.keys(k).length>0){if(k.query=Mb(this.currentQueryParams),A.currentLayoutJson?.computed&&Object.keys(A.currentLayoutJson.computed).length>0){const q={...A.currentDataContext,...k,query:k.query},z=this.calculateComputed(A.currentLayoutJson.computed,q);Object.keys(z).length>0&&(k._computed=z,this.globalState._computed=z,U.log("Computed values recalculated in updateQueryParams:",Object.keys(z)))}Ds(k,{sync:!0}),U.log("Template data updated with new query params")}}catch(x){U.error("Error in updateQueryParams:",x)}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new $n;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;r[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return af(e,n)}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Wr),i=r();if(!i){U.warn("ActionDispatcher not available for init_actions");return}U.log("Executing init_actions:",e.map(d=>d.handler)),U.log("Init actions dataContext:",n),U.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},h=i.createHandler(f,c),m=new Event("init");await h(m),U.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},U.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){U.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=fh().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),h=n.filter(y=>!e.customHandlers?.has(y)),m=h.length>0&&h.every(y=>d.some(v=>y.startsWith(`${v}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:h,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const h=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(h,l)};h()})}};M(Lr,"LOCALE_STORAGE_KEY","g7_locale"),M(Lr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Xo=Lr;function ph(s){const e=new Xo(s);return s.websocket&&(Gc.configure(s.websocket),U.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=ph,window.G7Core.dataSource={refetch:async(s,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(s,e)},get:s=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(s)}});function mT(s={}){const{checked:e,value:n,name:r,type:i="checkbox"}=s,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:r??"",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 yT(s={}){const{button:e=0,clientX:n=0,clientY:r=0}=s;return{button:e,clientX:n,clientY:r,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 bT(){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 vT(s,e="keydown"){return{key:s,code:s.length===1?`Key${s.toUpperCase()}`:s,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:s}),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 ST={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 Nb(s){const e=s.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(ST))if(r.test(e))return n;return null}function Ib(s){const e=s.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function wT(s,e){if(!e||e.trim()==="")return s;if(!s||s.trim()==="")return e;const n=s.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of r){const d=Nb(c);if(d){const f=Ib(c),h=`${d}:${f}`;i.set(h,c)}}return[...n.filter(c=>{const d=Nb(c);if(!d)return!0;const f=Ib(c),h=`${d}:${f}`;return!i.has(h)}),...r].join(" ")}function CT(s){return Object.entries(s).filter(([,e])=>e).map(([e])=>e).join(" ")}function ET(...s){return s.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=pt("G7CoreGlobals");function _T(){window.React=Xe,window.ReactDOM={...Ld,createPortal:ja.createPortal,unstable_batchedUpdates:s=>s()},window.ReactJSXRuntime=a_,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function AT(s){const e=new Map,n=za.getInstance();s.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async h=>{try{return await h(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(h){d=h instanceof Error?h:new Error(String(h))}if(n.trackEventEmit(r,i,c,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function xT(s){s.__runtime||(s.__runtime={DynamicRenderer:Vr,ComponentRegistry:Er,TranslationEngine:Oa,DataSourceManager:Dr,dataSourceManager:Gx,DataBindingEngine:$n,dataBindingEngine:of,ActionDispatcher:jo,TranslationReactContext:ih,TranslationProvider:Uc,useTranslation:gb,ResponsiveContext:If,ResponsiveProvider:Tc,useResponsive:jf,responsiveManager:Ci,BREAKPOINT_PRESETS:lc,AuthManager:Ar,createLogger:pt,G7DevToolsCore:za},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function TT(s){if(s.layoutEditor&&s.layoutEditor.__isStub!==!0||s.layoutEditor&&s.layoutEditor.__isStub===!0)return;const e=[],n=[];s.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function kT(s){s.asset={template:(e,n,r)=>f0(e,n,r),templateDir:(e,n)=>h0(e,n),module:(e,n,r)=>p0(e,n,r),plugin:(e,n,r)=>g0(e,n,r),convertToCurrentMode:e=>Ln(e),loadScript:(e,n,r)=>Io(e,bs())?Cr(e,n,r):Promise.reject(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`)),isAllowedScriptSrc:e=>Io(e,bs()),loadStylesheet:(e,n,r)=>ia(e,n,r)},s.assets={notifyFailure:xs,clearFailure:Db,clearAll:Ob,getFailures:Zx,retryAll:$b},lT(),be.log("전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨")}function RT(s,e){s.useTranslation=gb,s.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function DT(s,e){s.createChangeEvent=mT,s.createClickEvent=yT,s.createSubmitEvent=bT,s.createKeyboardEvent=vT,s.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),s.createLogger=pt,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),s.renderItemChildren=(n,r,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},y=new Set,v=(_,x)=>{const A=m._global?._remountKeys;return _&&A?.[_]&&!y.has(_)?(y.add(_),`${_}-remount-${A[_]}`):_||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:v,...c};return Eo(n,m,i,l,S)},s.evaluateCondition=(n,r)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...r||{}},f=i.bindingEngine??of;return dm(n,d,f)},s.getComponentMap=()=>Er.getInstance().getComponentMap(),s.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=Er.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},h={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,y=(v,S)=>{const _=h._global?._remountKeys;return v&&_?.[v]&&!m.has(v)?(m.add(v),`${v}-remount-${_[v]}`):v||S};return Eo(n,h,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},s.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||Er.getInstance().getComponentMap(),h=e.getState(),m=s.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},v={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},_=h.bindingEngine??s.getDataBindingEngine?.(),x={...m,_local:v,_computed:S,row:i,item:i,$item:i};let A={};if(l&&typeof l=="object"&&_)try{for(const[L,B]of Object.entries(l))if(typeof B=="string"){const q=La(B);if(q!==null)try{A[L]=Wn(q)?_.evaluatePipeExpression(q,x,{skipCache:!0}):_.evaluateExpression(q,x,{skipCache:!0})}catch{A[L]=void 0}else A[L]=_.resolveBindings(B,x,{skipCache:!0})}else A[L]=B}catch(L){be.warn("renderExpandContent: expandContext 평가 오류:",L)}const D={row:i,item:i,$item:i,_local:v,_global:m._global||{},_computed:m._computed||{},...A},O=new Set,k=(L,B)=>{const q=D._global?._remountKeys;return L&&q?.[L]&&!O.has(L)?(O.add(L),`${L}-remount-${q[L]}`):L||B};return Eo(r,D,f,d,{translationContext:h.translationContext,translationEngine:h.translationEngine??void 0,bindingEngine:h.bindingEngine??void 0,actionDispatcher:h.actionDispatcher,componentContext:c,getRemountKey:k})},s.$get=function(r,i,l=void 0){if(r==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return r;let d=r;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},be.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),be.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),be.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),be.log("전역 객체 window.G7Core.$get에 노출됨")}function OT(s){s.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),c=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),h=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=h?.state??c;m&&h&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let v=h?.data??c;m&&h?.data?._local&&(v={...h.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(_,x)=>l.navigate(_,x):void 0,setState:h?.setState??d,state:y,data:v,_isDispatchFallbackContext:!h?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,x,()=>{const{debounce:A,debounceKey:D,...O}=e;i.dispatchAction(O,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(_){return be.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Jo(s){const e={};for(const[n,r]of Object.entries(s))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Jn(s,e){if(Array.isArray(s)&&!Array.isArray(e)&<(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=s.length+r.length+10)){const l=[...s];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={...s};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=Jn(n[r],i):n[r]={...i}:n[r]=i;return n}function $T(s){s.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Jo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...r.getGlobalState(),...l};else{const d=r.getGlobalState();c=Jn(d,l)}r.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const A=window.__g7AutoBindingPaths;A&&A.size>0&&jb(Jo(e)).some(O=>A.has(O))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const A=r?.getActionDispatcher?.();if(A){const D=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:O,debounceKey:k,...L}=n;A.debouncedCall(D,n.debounce,()=>{s.state.setLocal(e,L)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Jo(e);if(i==="parent"||i==="root"){const A=window.__g7LayoutContextStack||[];if(A.length>0){const D=i==="parent"?A[A.length-1]:A[0];if(D?.setState){D.setState(O=>l==="replace"?d:l==="shallow"?{...O||{},...d}:Jn(O||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,h=r?.getGlobalState?.()?._local||{},v=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=v?Mo(h,v):h,_=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={..._,...d}:x=Jn(_,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,be.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const A=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(A,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const A=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Jn(A,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(A=>l==="replace"?d:l==="shallow"?{...A||{},...d}:Jn(A||{},d)),r?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Jn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Jn(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(be.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,r)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=r):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:r);const d=c?.merge||"deep",f=Jo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const h=window.__g7ActionContext;h?.isolatedContext?.mergeState?h.isolatedContext.mergeState(f,d):be.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return be.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||s.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){be.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){be.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=r):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",h=Jo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let v;f==="replace"?v=h:f==="shallow"?v={...y,...h}:v=Jn(y,h),window.__g7PendingLocalState=v;const S=window.__templateApp;if(S?.setGlobalState){const _=S.getGlobalState?.()?._local,A=f!=="replace"&&!!_&&typeof _=="object"&&!Array.isArray(_)?f==="shallow"?{..._,...h}:Jn(_,h):void 0;S.setGlobalState({_local:A?Mo(A,v):v})}if(l.setState(v),m?l.state._local=v:l.state=v,l.dataContext&&(l.dataContext._local=v),f==="replace")window.__g7ForcedLocalFields=h;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(_,h)}$f()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,s.state.set(r),be.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),s.state.getGlobal=s.state.get,s.state.setGlobal=s.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function MT(s){s.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,r,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return be.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return be.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,h=null;if(n){const y=n.split(".");h=y.pop();for(const v of y)if(f&&typeof f=="object"&&v in f)f=f[v];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[h]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&h?(f[h]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function NT(s,e){s.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function IT(s){s.toast={show:(e,n)=>{s.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{s.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{s.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{s.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{s.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function jT(s){s.modal={open:e=>{s.dispatch({handler:"openModal",target:e})},close:e=>{s.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{s.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=s.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>s.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function HT(s){s.style={mergeClasses:wT,conditionalClass:CT,joinClasses:ET},be.log("전역 객체 window.G7Core.style에 노출됨")}function zT(s,e){const{webSocketManager:n}=e;s.websocket={manager:n,subscribe:(r,i,l,c)=>n.subscribe(r,i,l,c),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function PT(s,e){const{transitionManager:n}=e;s.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(r(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function UT(s){s.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function BT(s){s.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function qT(s,e){const{transitionManager:n,responsiveManager:r}=e;s.AuthManager=Ar,s.api=qr(),s.TransitionManager=n,s.useTransitionState=Ay,s.ResponsiveManager=r,s.useResponsive=jf,s.useControllableState=y_,s.shallowArrayEqual=b_,s.shallowObjectEqual=Ty,s.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);be.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},be.log("전역 객체 window.G7Core.AuthManager에 노출됨"),be.log("전역 객체 window.G7Core.api에 노출됨"),be.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),be.log("전역 객체 window.G7Core.useResponsive에 노출됨"),be.log("전역 객체 window.G7Core.useControllableState에 노출됨"),be.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function GT(s,e){s.getSlotContext=()=>window.__slotContextValue??null,s.getDynamicRenderer=()=>window.__DynamicRenderer??null,s.getComponentRegistry=()=>e.getComponentRegistry?.()??Er.getInstance(),s.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,s.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,s.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function FT(s){s.identity={setLauncher:At.setLauncher.bind(At),handle:At.handle.bind(At),isIdentityRequired:At.isIdentityRequired.bind(At),hasLauncher:At.hasLauncher.bind(At),markDomainNoticeShown:At.markDomainNoticeShown.bind(At),redirectExternally:At.redirectExternally.bind(At),createDeferred:At.createDeferred.bind(At),resolveDeferred:At.resolveDeferred.bind(At),reset:At.reset.bind(At),redirectStashKey:Tf},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function VT(s){if(typeof window>"u")return;_T(),window.G7Core||(window.G7Core={});const e=window.G7Core;xT(e),AT(e),TT(e),qT(e,s),kT(e),RT(e,s),DT(e,s),OT(e),$T(e),MT(e),NT(e,s),IT(e),jT(e),HT(e),zT(e,s),PT(e,s),UT(e),BT(e),GT(e,s),FT(e),be.log("G7Core 전역 객체 초기화 완료")}function KT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>za.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,c)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,c):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,c,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,c)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,c,d,f)}catch{}},trackComponentStyle:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,c)}catch{}},trackAuthEvent:(r,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,c)}catch{}},trackAuthHeader:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,c,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,c,d)}catch{}},captureSequenceActionAfter:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,c,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,c,d,f,h)}catch{}},trackComputedRecalc:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,c,d,f,h)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};s.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Qo=null;function WT(){const s=window.G7Core;return s?.__devtools?Promise.resolve(s.__devtools):Qo||(Qo=new Promise((e,n)=>{const r=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 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Qo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Qo)}function YT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=za.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Md(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}XT(s,e)}async function XT(s,e){let n;try{n=await WT()}catch(h){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",h),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},Md();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;KT(),Md();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(h){be.warn("StyleTracker 활성화 실패:",h)}const c=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(h,m)=>e.watchState(h,m)},actions:{getHistory:()=>e.getActionHistory(),watch:h=>e.watchActions(h),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:h=>{const m=s.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(h,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:h=>c.analyze(h),suggestFix:h=>c.suggestFix(h),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:h=>c.getRulesByCategory(h)},server:{dumpState:h=>d.dumpState(h),sendLog:h=>d.sendLog(h),sendError:(h,m)=>d.sendError(h,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:h=>e.setLogLevel(h),setMaxHistory:h=>e.setMaxHistory(h)},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,s.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),JT(n.DevToolsPanel)}function JT(s){if(document.getElementById("g7-devtools-root")){be.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Ld.createRoot(e).render(Xe.createElement(s)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Qe=pt("TemplateEngine"),ae={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 Zo=!1;const el=[];async function QT(s){try{Qe.log("템플릿 메타데이터 로드 중...",s);const e=s.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Qe.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Qe.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Qe.error("템플릿 메타데이터 로드 실패",e),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function Hb(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=ae.templateMetadata?.locales;return{$locale:ae.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:ae.templateId}}async function tl(s){try{if(Qe.log("템플릿 엔진 초기화 시작",s),ae.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!s.templateId)throw new Vx;Zo=s.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Zo),YT(),ae.templateId=s.templateId,ae.locale=s.locale||"ko",Qe.log("엔진 인스턴스 생성 중..."),ae.registry=Er.getInstance(),ae.bindingEngine=new $n,ae.translationEngine=Oa.getInstance(),s.cacheVersion!==void 0&&s.cacheVersion>0&&ae.translationEngine.setCacheVersion(s.cacheVersion),ae.translationContext={templateId:s.templateId,locale:ae.locale},ae.actionDispatcher=new jo({},ae.translationEngine,ae.translationContext),l_(ae.actionDispatcher),Qe.log("다국어 파일 로드 중...",s.templateId,ae.locale);const e="en",n=[ae.translationEngine.loadTranslations(s.templateId,ae.locale).then(()=>{Qe.log(`다국어 파일 로드 완료: ${ae.locale}`)}).catch(r=>{Qe.warn(`다국어 파일 로드 실패 (${ae.locale}):`,r instanceof Error?r.message:r)})];ae.locale!==e&&n.push(ae.translationEngine.loadTranslations(s.templateId,e).then(()=>{Qe.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Qe.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),Qe.log("템플릿 메타데이터 로드 중...",s.templateId),ae.templateMetadata=await QT(s.templateId),ae.isInitialized=!0,Qe.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Qe.error("템플릿 엔진 초기화 실패",e),ae.isInitialized=!1,ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,e}}let ks=null;const zb="g7-layout-editor-bundle";function gh(){const s=window.G7Core;return s?.__LayoutEditorChrome?Promise.resolve(s.__LayoutEditorChrome):ks||(ks=(async()=>{const e=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js";document.getElementById(zb)?.remove(),window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=()=>{};try{await Cr(e,{id:zb},{label:"layout-editor bundle"})}catch(r){throw ks=null,Qe.error(`편집기 번들 로드 실패 (${e})`,r),new Error("편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.")}const n=window.G7Core?.__LayoutEditorChrome;if(!n)throw ks=null,Qe.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${e})`),new Error("편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.");return n})(),ks)}async function Rs(s){try{if(Qe.log("템플릿 렌더링 시작",s),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!s.containerId)throw new Error("containerId는 필수입니다.");if(!s.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(s.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${s.containerId}`);const n=Hb();if(ae.containerId=s.containerId,ae.currentLayoutJson=s.layoutJson,ae.currentDataContext={...n,...s.dataContext||{}},ae.translationContext=s.translationContext||{templateId:ae.templateId||"",locale:ae.locale},ae.reactRoot||(Qe.log("React Root 생성"),ae.reactRoot=Ld.createRoot(e)),typeof window<"u"){const l=kb(window.location.pathname);if(l){Qe.log("레이아웃 편집기 모드 진입",l);let c;try{c=await gh()}catch(f){Qe.error("레이아웃 편집기 번들 로드 실패",f),uh.render(s.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Zo});return}const d=Xe.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ae.locale});ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext,children:Xe.createElement(Mf,{children:Xe.createElement(Tc,{children:Xe.createElement(sh,{children:d})})})}));return}}const r=s.layoutJson.components||[];if(r.length===0){Qe.warn("렌더링할 컴포넌트가 없습니다.");return}const i=s.layoutJson.modals||[];if(Qe.log("modals 배열:",i),Qe.log("modals 개수:",i.length),Qe.log("DynamicRenderer로 렌더링 시작"),ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...r.map((l,c)=>{const d=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),Xe.createElement(yy,{key:"__modal_parent_context_provider"},i.map(l=>{const c=ae.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||ae.currentDataContext._global?.activeModal===l.id,h=c.indexOf(l.id),m=h>=0?50+h:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,_=Xe.createElement(Vr,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?Xe.createElement(xb,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:_}):_}))]))))),Qe.log("템플릿 렌더링 완료"),el.length>0){Qe.log(`대기 중인 데이터 업데이트 ${el.length}건 적용`);const l=[...el];el.length=0;for(const{data:c,options:d}of l)Ds(c,d)}}catch(e){throw Qe.error("템플릿 렌더링 실패",e),e}}function Ds(s,e){try{if(Qe.log("템플릿 데이터 업데이트 시작",Object.keys(s)),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ae.reactRoot||!ae.currentLayoutJson){Qe.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(s)),el.push({data:s,options:e});return}const n=Hb(),r={...ae.currentDataContext._global||{},...s._global||{}},i=g_(ae.currentDataContext._localInit,s._localInit);ae.currentDataContext={...n,...ae.currentDataContext,...s,_global:r,_localInit:i},r._local!==void 0&&(ae.currentDataContext._local=r._local),r._computed!==void 0&&(ae.currentDataContext._computed=r._computed);const l=ae.currentLayoutJson.components||[],c=ae.currentLayoutJson.modals||[];Qe.log("updateTemplateData - modals 배열:",c),Qe.log("updateTemplateData - modals 개수:",c.length),Qe.log("updateTemplateData - activeModal:",ae.currentDataContext._global?.activeModal);const d=()=>{ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...l.map((f,h)=>{const m=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:h===0,layoutKey:m})}),Xe.createElement(yy,{key:"__modal_parent_context_provider_update"},c.map(f=>{const h=ae.currentDataContext._global?.modalStack||[],y=h.includes(f.id)||ae.currentDataContext._global?.activeModal===f.id,v=h.indexOf(f.id),S=v>=0?50+v:50,_=window.__g7LayoutContextStack||[],A=_[_.length-1]?.dataContext,D=Xe.createElement(Vr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:S},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:A});return f.data_sources&&f.data_sources.length>0?Xe.createElement(xb,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:D}):D}))])))))};e?.sync?(Qe.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Qe.log("재렌더링 시작 (with startTransition)"),I.startTransition(()=>{d()})),Qe.log("템플릿 데이터 업데이트 완료")}catch(n){throw Qe.error("템플릿 데이터 업데이트 실패",n),n}}function Xc(){try{Qe.log("템플릿 정리 시작"),ae.reactRoot&&(Qe.log("React Root 언마운트"),ae.reactRoot.unmount(),ae.reactRoot=null),ae.templateId=null,ae.locale="ko",ae.isInitialized=!1,ae.containerId=null,ae.currentLayoutJson=null,ae.currentDataContext={},ae.translationContext={templateId:"",locale:"ko"},ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,ae.templateMetadata=null,Qe.log("템플릿 정리 완료")}catch(s){throw Qe.error("템플릿 정리 실패",s),s}}function la(){return Object.freeze({...ae})}function Pb(){return ae.actionDispatcher}const nl={initTemplateEngine:tl,renderTemplate:Rs,updateTemplateData:Ds,destroyTemplate:Xc,getState:la};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=nl,VT({getState:()=>({translationEngine:ae.translationEngine,translationContext:ae.translationContext,bindingEngine:ae.bindingEngine,actionDispatcher:ae.actionDispatcher,templateMetadata:ae.templateMetadata}),transitionManager:Gr,responsiveManager:Ci,webSocketManager:Gc}),Qe.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Wr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Dr,LayoutLoader:ah,TemplateApp:Xo,TemplateEngine:nl,default:nl,destroyTemplate:Xc,getActionDispatcher:Pb,getState:la,initTemplateApp:ph,initTemplateEngine:tl,loadLayoutEditorBundle:gh,renderTemplate:Rs,updateTemplateData:Ds},Symbol.toStringTag,{value:"Module"}));tn.DataSourceManager=Dr,tn.LayoutLoader=ah,tn.TemplateApp=Xo,tn.TemplateEngine=nl,tn.default=nl,tn.destroyTemplate=Xc,tn.getActionDispatcher=Pb,tn.getState=la,tn.initTemplateApp=ph,tn.initTemplateEngine=tl,tn.loadLayoutEditorBundle=gh,tn.renderTemplate=Rs,tn.updateTemplateData=Ds,Object.defineProperties(tn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); diff --git a/resources/js/core/assets/AssetFailureNotice.ts b/resources/js/core/assets/AssetFailureNotice.ts index 226a9d42..4fd5871a 100644 --- a/resources/js/core/assets/AssetFailureNotice.ts +++ b/resources/js/core/assets/AssetFailureNotice.ts @@ -174,6 +174,22 @@ export function getAssetFailures(): AssetFailure[] { return Array.from(failures.values()); } +/** + * 자산 실패 안내에 쓰는 사용자 어휘를 번역합니다 (배너 밖 호출자용). + * + * 항목명(label)은 사용자 어휘여야 한다 — 내부 구분 키·식별자를 그대로 넘기면 배너에 + * "module을(를) 불러오지 못했습니다" 처럼 내부 이름이 노출된다. + * + * @param key 번역 키 + * @param fallback 번역 엔진 부재 시 사용할 문구 + * @param params 치환 파라미터 + * @return string 번역된 문자열 + * @since engine-v1.64.7 + */ +export function assetText(key: string, fallback: string, params?: Record): string { + return t(key, fallback, params); +} + /** * 등록된 실패 중 재시도 가능한 것을 모두 재시도합니다. * diff --git a/resources/js/core/modules/ModuleAssetLoader.ts b/resources/js/core/modules/ModuleAssetLoader.ts index 98fb320e..6fb38a91 100644 --- a/resources/js/core/modules/ModuleAssetLoader.ts +++ b/resources/js/core/modules/ModuleAssetLoader.ts @@ -9,10 +9,26 @@ import { createLogger } from '../utils/Logger'; import { loadScriptWithRetry, loadStylesheetWithRetry } from '../template-engine/networkResilience'; import { convertToCurrentMode, staticToLegacy } from '../support/assetUrl'; -import { notifyAssetFailure } from '../assets/AssetFailureNotice'; +import { assetText, notifyAssetFailure } from '../assets/AssetFailureNotice'; const logger = createLogger('ModuleAssetLoader'); +/** + * 병합 CSS 번들의 실패 안내 항목명 (사용자 어휘). + * + * 번들 구분 키(`module`/`plugin`)는 내부 이름이다. 그대로 배너에 넘기면 + * "module을(를) 불러오지 못했습니다" 처럼 사용자가 해석할 수 없는 문구가 된다. + * + * @param key 번들 구분 키 ('module' | 'plugin') + * @return string 사용자 어휘 항목명 + * @since engine-v1.64.7 + */ +function bundleCssLabel(key: string): string { + return key === 'plugin' + ? assetText('core.assets.plugin_styles', '플러그인 스타일') + : assetText('core.assets.module_styles', '모듈 스타일'); +} + /** * 모듈 에셋 정보 인터페이스 */ @@ -321,7 +337,7 @@ export class ModuleAssetLoader { // 항상 실패한다 — 버튼은 있는데 아무것도 고치지 못하는 상태가 된다. this.surfaceCssFailure( `bundle-${key}`, - key, + bundleCssLabel(key), legacyUrl !== null ? convertToCurrentMode(legacyUrl) : url, error ); diff --git a/resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts b/resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts index ddd2f5a6..2adfc005 100644 --- a/resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts +++ b/resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts @@ -5,7 +5,8 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { ModuleAssetLoader, type ModuleAsset } from '../ModuleAssetLoader'; +import { ModuleAssetLoader, parseBundleUrlsFromConfig, type ModuleAsset } from '../ModuleAssetLoader'; +import { clearAllAssetFailures, getAssetFailures } from '../../assets/AssetFailureNotice'; describe('ModuleAssetLoader', () => { let loader: ModuleAssetLoader; @@ -310,6 +311,9 @@ describe('ModuleAssetLoader', () => { }); describe('loadBundle (서버측 병합 번들)', () => { + /** + * @effects loadbundle_single_script_single_link_append + */ it('단일 script + 단일 link 를 1개씩만 append 한다', async () => { const scriptAppends: string[] = []; const linkAppends: string[] = []; @@ -350,6 +354,9 @@ describe('ModuleAssetLoader', () => { appendSpy.mockRestore(); }); + /** + * @effects loadbundle_dedup_guard_no_double_load + */ it('같은 key 를 중복 로드하지 않는다 (중복 가드)', async () => { let scriptCount = 0; // 실제 DOM 에 삽입해 element id 가 등록되어야 getElementById 중복 가드가 동작 @@ -370,6 +377,9 @@ describe('ModuleAssetLoader', () => { appendSpy.mockRestore(); }); + /** + * @effects loadbundle_null_urls_noop + */ it('jsUrl/cssUrl 모두 null 이면 no-op', async () => { const appendSpy = vi.spyOn(document.head, 'appendChild'); await expect(loader.loadBundle('module', null, null)).resolves.toBeUndefined(); @@ -379,6 +389,9 @@ describe('ModuleAssetLoader', () => { }); describe('concat 자가등록 (IIFE 병합 계약)', () => { + /** + * @effects concat_iife_self_registration_preserved + */ it(';\\n 로 이어붙인 2개 IIFE 가 모두 실행되어 레지스트리에 자가등록된다', () => { // 모의 IIFE 2개 — ecommerce IIFE 처럼 세미콜론 없이 끝나도 `\n;\n` 구분자로 ASI 경계 보호 const registry: Record = {}; @@ -478,6 +491,83 @@ describe('ModuleAssetLoader', () => { loader.loadBundle('module', null, '/api/modules/bundle.css') ).resolves.toBeUndefined(); }); + + /** + * 배너 항목명은 사용자 어휘여야 한다 — 내부 구분 키(module/plugin)를 그대로 + * 넘기면 "module을(를) 불러오지 못했습니다" 처럼 해석 불가한 문구가 노출된다. + * + * 테스트 환경에는 G7Core.t 가 없으므로 폴백 문구가 쓰인다. + * + * @effects bundle_css_failure_banner_uses_user_vocabulary + * @since engine-v1.64.7 + */ + it('번들 CSS 실패 안내 항목명이 사용자 어휘다 (모듈)', async () => { + clearAllAssetFailures(); + stubAssetLoading(['error', 'error', 'error']); + + await loader.loadBundle('module', null, '/api/modules/bundle.css'); + + const failure = getAssetFailures().find(f => f.id === 'ext-css:bundle-module'); + + expect(failure).toBeDefined(); + expect(failure!.label).toBe('모듈 스타일'); + expect(failure!.label).not.toBe('module'); + }); + + /** + * @effects bundle_css_failure_banner_uses_user_vocabulary + * @since engine-v1.64.7 + */ + it('번들 CSS 실패 안내 항목명이 사용자 어휘다 (플러그인)', async () => { + clearAllAssetFailures(); + stubAssetLoading(['error', 'error', 'error']); + + await loader.loadBundle('plugin', null, '/api/plugins/bundle.css'); + + const failure = getAssetFailures().find(f => f.id === 'ext-css:bundle-plugin'); + + expect(failure).toBeDefined(); + expect(failure!.label).toBe('플러그인 스타일'); + expect(failure!.label).not.toBe('plugin'); + }); + }); + + /** + * bundleUrls 부재(구버전 blade) 시 개별 로딩으로 폴백한다. + * + * 폴백 판정은 파싱 결과가 null 인지로 이뤄진다(TemplateApp.loadExtensionAssets). + * null 이 아닌데 폴백하거나 그 반대면 확장 에셋이 통째로 로드되지 않는데, 오류도 + * 경고도 남지 않는다. + * + * @effects missing_bundle_urls_falls_back_to_individual_loading + */ + describe('bundleUrls 부재 폴백 판정', () => { + afterEach(() => { + delete (window as any).G7Config; + }); + + it('G7Config 자체가 없으면 null 이다 (개별 로딩 폴백)', () => { + delete (window as any).G7Config; + + expect(parseBundleUrlsFromConfig()).toBeNull(); + }); + + it('G7Config 는 있으나 bundleUrls 가 없으면 null 이다 (개별 로딩 폴백)', () => { + (window as any).G7Config = { moduleAssets: [] }; + + expect(parseBundleUrlsFromConfig()).toBeNull(); + }); + + it('bundleUrls 가 있으면 폴백하지 않는다 (번들 경로)', () => { + (window as any).G7Config = { + bundleUrls: { moduleJs: '/api/modules/bundle.js', moduleCss: null, pluginJs: null, pluginCss: null }, + }; + + const urls = parseBundleUrlsFromConfig(); + + expect(urls).not.toBeNull(); + expect(urls!.moduleJs).toContain('/api/modules/bundle'); + }); }); describe('loadCSS in-flight Promise 공유', () => { diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 46a6bd6a..8afe53a5 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.64.7] - 2026-09-04 + +### Fixed + +#### 확장 번들 스타일 실패 안내에 내부 구분 이름이 노출되던 문제 + +- 병합 CSS 번들 로드에 끝내 실패했을 때 안내 배너의 항목명이 번들 구분 키(`module`/`plugin`)였다. 사용자 어휘(`core.assets.module_styles` · `core.assets.plugin_styles`, 번역 미적재 시 폴백 문구)로 바꾼다 (ModuleAssetLoader.ts, AssetFailureNotice.ts) + ## [engine-v1.64.0] - 2026-09-02 ### Security diff --git a/templates/_bundled/gnuboard7-hello_admin_template/AGENTS.md b/templates/_bundled/gnuboard7-hello_admin_template/AGENTS.md index 7417390b..cd90ae9c 100644 --- a/templates/_bundled/gnuboard7-hello_admin_template/AGENTS.md +++ b/templates/_bundled/gnuboard7-hello_admin_template/AGENTS.md @@ -107,6 +107,7 @@ SSoT 는 코어 `config/template.php` 의 `required_admin_components` 입니다. - [ ] `_bundled` 에서만 수정하고 `php artisan template:update gnuboard7-hello_admin_template --force` 로 반영 - [ ] manifest version 상향 시 `package.json` · `package-lock.json` 동기화 + CHANGELOG 기재 +- [ ] `template.json` 의 `assets` 경로는 실제 산출물을 가리켜야 한다 — 없는 경로를 선언하면 검색엔진용(봇) 화면이 404 를 가리키는 `` 를 싣고, 일반 화면에는 흔적이 남지 않는다 - [ ] 레이아웃 JSON 변경 시 빌드 없이 update 만 — 신규 Tailwind 클래스는 빌드된 CSS 에 존재하는지 확인 - [ ] TSX/TS 변경 시 `--production` 재빌드 후 `dist/` 커밋 (sourceMappingURL 잔존 금지) - [ ] 다국어 키 추가 시 ko·en 동시 반영 + 번들 ja 언어팩 증분 동기화 diff --git a/templates/_bundled/gnuboard7-hello_admin_template/CHANGELOG.md b/templates/_bundled/gnuboard7-hello_admin_template/CHANGELOG.md index 4e85cd69..90bd792b 100644 --- a/templates/_bundled/gnuboard7-hello_admin_template/CHANGELOG.md +++ b/templates/_bundled/gnuboard7-hello_admin_template/CHANGELOG.md @@ -13,6 +13,10 @@ - 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다. - 문서의 제품 표기를 「그누보드7」로 통일했습니다. +### Fixed + +- 설정 파일의 스크립트 경로가 실제 빌드 산출물과 달랐던 것을 정정했습니다. + ## [0.1.0] - 2026-07-01 ### Changed diff --git a/templates/_bundled/gnuboard7-hello_admin_template/template.json b/templates/_bundled/gnuboard7-hello_admin_template/template.json index 3367f6ad..201946a7 100644 --- a/templates/_bundled/gnuboard7-hello_admin_template/template.json +++ b/templates/_bundled/gnuboard7-hello_admin_template/template.json @@ -30,7 +30,7 @@ }, "assets": { "js": [ - "dist/components.js" + "dist/js/components.iife.js" ] }, "components": { diff --git a/templates/_bundled/gnuboard7-hello_user_template/AGENTS.md b/templates/_bundled/gnuboard7-hello_user_template/AGENTS.md index 0f80b452..3ed6d977 100644 --- a/templates/_bundled/gnuboard7-hello_user_template/AGENTS.md +++ b/templates/_bundled/gnuboard7-hello_user_template/AGENTS.md @@ -107,6 +107,7 @@ User 템플릿은 자기가 그리고 싶은 화면에 필요한 API 를 `data_s - [ ] `_bundled` 에서만 수정하고 `php artisan template:update gnuboard7-hello_user_template --force` 로 반영 - [ ] manifest version 상향 시 `package.json` · `package-lock.json` 동기화 + CHANGELOG 기재 +- [ ] `template.json` 의 `assets` 경로는 실제 산출물을 가리켜야 한다 — 없는 경로를 선언하면 검색엔진용(봇) 화면이 404 를 가리키는 `` 를 싣고, 일반 화면에는 흔적이 남지 않는다 - [ ] 레이아웃 JSON 변경 시 빌드 없이 update 만 — 신규 Tailwind 클래스는 빌드된 CSS 에 존재하는지 확인 - [ ] TSX/TS 변경 시 `--production` 재빌드 후 `dist/` 커밋 (sourceMappingURL 잔존 금지) - [ ] 다국어 키 추가 시 ko·en 동시 반영 + 번들 ja 언어팩 증분 동기화 diff --git a/templates/_bundled/gnuboard7-hello_user_template/CHANGELOG.md b/templates/_bundled/gnuboard7-hello_user_template/CHANGELOG.md index fff4251d..5d995f65 100644 --- a/templates/_bundled/gnuboard7-hello_user_template/CHANGELOG.md +++ b/templates/_bundled/gnuboard7-hello_user_template/CHANGELOG.md @@ -13,6 +13,10 @@ - 확장 문서에 「레이아웃 편집기 스펙」 항목을 추가했습니다. 이 확장이 레이아웃 편집기에 무엇을 선언했는지와, 화면 요소나 데이터를 추가할 때 편집기 쪽에서 함께 해야 할 일을 담습니다. - 문서의 제품 표기를 「그누보드7」로 통일했습니다. +### Fixed + +- 설정 파일이 존재하지 않는 스타일 파일을 선언해 검색엔진용 화면이 없는 주소를 참조하던 문제를 수정했습니다. + ## [0.1.0] - 2026-07-01 ### Changed diff --git a/templates/_bundled/gnuboard7-hello_user_template/template.json b/templates/_bundled/gnuboard7-hello_user_template/template.json index 8c66d0b0..4e3430bc 100644 --- a/templates/_bundled/gnuboard7-hello_user_template/template.json +++ b/templates/_bundled/gnuboard7-hello_user_template/template.json @@ -31,9 +31,7 @@ "plugins": {} }, "assets": { - "css": [ - "dist/css/components.css" - ], + "css": [], "js": [ "dist/js/components.iife.js" ], diff --git a/templates/_bundled/sirsoft-admin_basic/AGENTS.md b/templates/_bundled/sirsoft-admin_basic/AGENTS.md index 17a45d3a..32475ec1 100644 --- a/templates/_bundled/sirsoft-admin_basic/AGENTS.md +++ b/templates/_bundled/sirsoft-admin_basic/AGENTS.md @@ -96,6 +96,7 @@ admin/`)이 이 템플릿의 베이스(`_admin_base`)를 extends 하고 이 템 - [ ] `_bundled` 에서만 수정하고 `php artisan template:update sirsoft-admin_basic --force` 로 반영 - [ ] manifest version 상향 시 `package.json` · `package-lock.json` 동기화 + CHANGELOG 기재 +- [ ] `template.json` 의 `assets` 경로는 실제 산출물을 가리켜야 한다 — 없는 경로를 선언하면 검색엔진용(봇) 화면이 404 를 가리키는 `` 를 싣고, 일반 화면에는 흔적이 남지 않는다 - [ ] 레이아웃 JSON 변경 시 빌드 없이 update 만 — 신규 Tailwind 클래스는 빌드된 CSS 에 존재하는지 확인 - [ ] TSX/TS 변경 시 `--production` 재빌드 후 `dist/` 커밋 (sourceMappingURL 잔존 금지) - [ ] 다국어 키 추가 시 ko·en 동시 반영 + 번들 ja 언어팩 증분 동기화 diff --git a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md index 87385472..c950639a 100644 --- a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md +++ b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md @@ -25,6 +25,7 @@ ### Fixed +- 설정 파일의 자산 항목이 실제 파일 위치와 달랐던 것을 정정했습니다. 존재하지 않는 글꼴·이미지 폴더 항목은 제거했습니다. - 환경설정 > 일반의 「자산 URL 방식 자동 감지」가 감지 결과를 선택 항목과 저장 내용에 반영합니다. 종전에는 버튼을 눌러도 선택이 그대로였고 진행·결과 안내도 표시되지 않았습니다. - 대시보드 알림 중 일부 경고가 일반 안내와 같은 회색으로 표시되어 경고로 보이지 않던 문제를 수정했습니다. 이제 알림의 심각도에 따라 색이 정해집니다. - 경고 등급 알림을 대시보드 맨 아래 「시스템 알림」 칸이 아니라 **화면 상단**에 표시합니다. 종전에는 스크롤을 끝까지 내려야 보여, 화면이 정상으로 보이는 상황에서는 조치가 필요하다는 사실을 지나치기 쉬웠습니다. 경고가 아닌 안내는 종전대로 하단에 남으며, 같은 알림이 두 곳에 중복으로 뜨지 않습니다. diff --git a/templates/_bundled/sirsoft-admin_basic/template.json b/templates/_bundled/sirsoft-admin_basic/template.json index 4c39e33f..4df15051 100644 --- a/templates/_bundled/sirsoft-admin_basic/template.json +++ b/templates/_bundled/sirsoft-admin_basic/template.json @@ -29,18 +29,13 @@ }, "assets": { "css": [ - "assets/css/main.css", - "assets/css/ui-system.css" + "dist/css/components.css" ], "js": [ - "dist/components.js" + "dist/js/components.iife.js" ], - "fonts": [ - "assets/fonts/" - ], - "images": [ - "assets/images/" - ] + "fonts": [], + "images": [] }, "components": { "basic": [ diff --git a/tests/Feature/Api/Public/ExtensionBundleServingTest.php b/tests/Feature/Api/Public/ExtensionBundleServingTest.php index eac7d01f..1b22b2b0 100644 --- a/tests/Feature/Api/Public/ExtensionBundleServingTest.php +++ b/tests/Feature/Api/Public/ExtensionBundleServingTest.php @@ -4,6 +4,7 @@ namespace Tests\Feature\Api\Public; use App\Services\ExtensionBundleService; use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Log; use Mockery; use Tests\TestCase; @@ -40,24 +41,37 @@ class ExtensionBundleServingTest extends TestCase /** * 번들 서비스를 모킹합니다. * - * `$memoryContent` / `$declaredCount` 는 빈 경로(`$returnPath === ''`)일 때의 분기를 - * 정한다 — 디스크 캐시 실패(메모리 폴백)인지, 선언 0개(정상 빈 번들)인지, - * 선언은 있는데 결과가 0인지(장애)를 컨트롤러가 이 둘로 가른다. + * `$memoryContent` / `$declaredCount` / `$missing` 은 빈 경로(`$returnPath === ''`)일 때의 + * 분기를 정한다 — 디스크 캐시 실패(메모리 폴백)인지, 병합 결과가 정당하게 비었는지 + * (선언 0 이거나 선언한 산출물이 전부 존재하되 비어 있음), 선언한 산출물이 소실됐는지 + * (장애)를 컨트롤러가 이 셋으로 가른다. + * + * 503 의 근거는 `$declaredCount` 가 아니라 `$missing` 이다. 선언만으로 판정하면 + * "스타일이 비어 있는 확장" 의 정당한 상태가 배포 장애와 구분되지 않는다. * * @param string $returnPath getBundleFilePath 반환값 * @param string $memoryContent buildBundleContent 반환값 * @param int $declaredCount countAssetDeclaringExtensions 반환값 + * @param list $missing findMissingDeclaredAssets 반환값 (소실 산출물 절대 경로) */ - private function bindBundleService(string $returnPath, string $memoryContent = '', int $declaredCount = 0): void - { + private function bindBundleService( + string $returnPath, + string $memoryContent = '', + int $declaredCount = 0, + array $missing = [] + ): void { $mock = Mockery::mock(ExtensionBundleService::class); $mock->shouldReceive('getCurrentVersion')->andReturn(777); $mock->shouldReceive('getBundleFilePath')->andReturn($returnPath); $mock->shouldReceive('buildBundleContent')->andReturn($memoryContent); $mock->shouldReceive('countAssetDeclaringExtensions')->andReturn($declaredCount); + $mock->shouldReceive('findMissingDeclaredAssets')->andReturn($missing); $this->app->instance(ExtensionBundleService::class, $mock); } + /** + * @effects bundle_endpoint_serves_with_etag_and_304 + */ public function test_module_bundle_js_serves_merged_file_with_etag(): void { $path = $this->fixtureDir.'/module.777.js'; @@ -73,6 +87,9 @@ class ExtensionBundleServingTest extends TestCase $this->assertStringContainsString("\n;\n", $response->streamedContent() ?? $response->getContent()); } + /** + * @effects bundle_endpoint_serves_with_etag_and_304 + */ public function test_bundle_returns_304_on_matching_etag(): void { $path = $this->fixtureDir.'/plugin.777.js'; @@ -88,6 +105,9 @@ class ExtensionBundleServingTest extends TestCase $second->assertStatus(304); } + /** + * @effects empty_bundle_returns_empty_path_and_empty_ok_response + */ public function test_empty_bundle_returns_empty_ok_response(): void { // 에셋을 선언한 활성 확장이 0개 → 빈 번들이 정상이다 → 빈 200 @@ -125,23 +145,90 @@ class ExtensionBundleServingTest extends TestCase } /** - * 선언은 있는데 병합 결과가 비면 503 이다 (E2). + * 선언한 산출물이 소실됐는데 병합 결과가 비면 503 이다 (E2). * * 배포 중 `dist` 가 잠깐 비면 **모든 확장이 빠진 빈 번들**이 200 으로 나가고, 프론트는 * 404 도 오류도 받지 못한 채 한참 뒤 "Unknown action handler" 로 죽는다 — 그 시점에는 * 원인이 번들이라는 사실이 화면에도 로그에도 남아 있지 않다. * - * @effects bundle_empty_with_declared_assets_returns_503 + * 판정 근거는 선언 축이 아니라 **소실 축**이다. 선언 축만 보면 스타일이 비어 있는 + * 확장(정당한 0바이트 산출물)까지 장애로 잡혀 기본 구성이 503 이 된다. + * + * // @scenario ext_type=module, asset_kind=js, active_combo=multiple, file_state=one_missing + * + * @effects bundle_empty_with_declared_assets_returns_503, empty_result_with_missing_declared_artifact_returns_503 */ public function test_empty_bundle_with_declared_assets_returns_503(): void { - $this->bindBundleService('', memoryContent: '', declaredCount: 3); + $this->bindBundleService('', memoryContent: '', declaredCount: 3, missing: ['/x/dist/js/a.js']); $response = $this->get('/api/modules/bundle.js?v=777'); $response->assertStatus(503); } + /** + * 선언한 산출물이 **존재하되 비어 있으면** 정상 빈 200 이다 (이 이슈의 재현). + * + * 스타일 소스가 자리표시 주석뿐이라 0바이트 CSS 를 내보내는 확장은 정당한 상태다. + * 종전 판정은 "선언 > 0 && 병합 결과 0" 을 곧 배포 장애로 등치해, 그런 확장만 설치된 + * 기본 구성의 사용자 화면마다 실패 안내가 떴다. + * + * // @scenario ext_type=module, asset_kind=css, active_combo=one, file_state=present_empty + * + * @effects empty_result_with_present_empty_artifacts_returns_200 + */ + public function test_empty_result_with_present_empty_artifacts_returns_200(): void + { + $this->bindBundleService('', memoryContent: '', declaredCount: 1, missing: []); + + $response = $this->get('/api/modules/bundle.css?v=777'); + + $response->assertOk(); + $this->assertStringStartsWith('text/css', $response->headers->get('Content-Type')); + $this->assertSame('', $response->getContent()); + } + + /** + * 플러그인 경로도 같은 판정을 쓴다 — 존재하되 비어 있으면 빈 200. + * + * // @scenario ext_type=plugin, asset_kind=css, active_combo=one, file_state=present_empty + * + * @effects bundle_decision_is_shared_across_extension_types, empty_result_with_present_empty_artifacts_returns_200 + */ + public function test_plugin_bundle_returns_200_when_declared_artifacts_present_but_empty(): void + { + $this->bindBundleService('', memoryContent: '', declaredCount: 1, missing: []); + + $response = $this->get('/api/plugins/bundle.css?v=777'); + + $response->assertOk(); + $this->assertSame('', $response->getContent()); + } + + /** + * 503 로그가 **어느 산출물이 없는지**를 싣는다. + * + * 경로가 없으면 운영자는 조치 대상을 짚을 수 없다 — 선언 수만으로는 어느 확장의 + * 어느 파일인지 알 수 없다. + * + * // @scenario ext_type=module, asset_kind=css, active_combo=one, file_state=one_missing + * + * @effects missing_artifact_paths_are_logged + */ + public function test_503_log_lists_missing_artifact_paths(): void + { + Log::spy(); + + $this->bindBundleService('', memoryContent: '', declaredCount: 1, missing: ['/x/dist/css/a.css']); + + $this->get('/api/modules/bundle.css?v=777')->assertStatus(503); + + Log::shouldHaveReceived('error')->withArgs( + fn ($message, $context) => ($context['missing'] ?? null) === ['/x/dist/css/a.css'] + )->once(); + } + /** * 플러그인 경로도 같은 판정을 쓴다 — 두 컨트롤러가 갈라지지 않는다 (장애 쪽). * @@ -149,7 +236,7 @@ class ExtensionBundleServingTest extends TestCase */ public function test_plugin_bundle_returns_503_when_declared_but_empty(): void { - $this->bindBundleService('', memoryContent: '', declaredCount: 1); + $this->bindBundleService('', memoryContent: '', declaredCount: 1, missing: ['/x/dist/css/a.css']); $this->get('/api/plugins/bundle.css?v=777')->assertStatus(503); } diff --git a/tests/Playwright/specs/extension-bundle-loading.spec.ts b/tests/Playwright/specs/extension-bundle-loading.spec.ts index 97e80a1f..a6466fcc 100644 --- a/tests/Playwright/specs/extension-bundle-loading.spec.ts +++ b/tests/Playwright/specs/extension-bundle-loading.spec.ts @@ -2,8 +2,8 @@ * E2E: 확장 프론트엔드 병합 번들 로딩 회귀 검증 * * @scenario extension-bundle-loading - * @effects bundle_js_requested_once_per_type, individual_iife_requests_absent, - * gdpr_interceptor_still_active, extension_handlers_registered + * @effects individual_iife_requests_absent_in_browser, bundle_url_same_origin_only, + * gdpr_interceptor_still_active_after_merge, extension_handlers_registered_no_console_error * * 배경: 활성 모듈/플러그인 IIFE 를 서버측에서 종류별 1개 번들로 병합 서빙한다. * 실제 페이지 로드 시 (1) 개별 `*.iife.js` 요청이 사라지고 `bundle.js` 로 대체되는지, @@ -22,8 +22,8 @@ test.describe('확장 병합 번들 로딩', () => { await page.goto('/'); await page.waitForLoadState('networkidle', { timeout: 30_000 }); - const moduleBundle = requestedUrls.filter((u) => /\/api\/modules\/bundle\.js/.test(u)); - const pluginBundle = requestedUrls.filter((u) => /\/api\/plugins\/bundle\.js/.test(u)); + const moduleBundle = requestedUrls.filter((u) => /\/api\/modules\/bundle[./]js/.test(u)); + const pluginBundle = requestedUrls.filter((u) => /\/api\/plugins\/bundle[./]js/.test(u)); // 활성 확장이 있으면 번들이 요청되고, 종류별로 1건씩만 나가야 한다 const individualIife = requestedUrls.filter((u) => /\/api\/(modules|plugins)\/assets\/.*\.iife\.js/.test(u)); @@ -39,7 +39,7 @@ test.describe('확장 병합 번들 로딩', () => { test('@smoke 병합 번들 응답이 정상(200/304)이고 same-origin 이다', async ({ page }) => { const bundleResponses: { url: string; status: number }[] = []; page.on('response', (res) => { - if (/\/api\/(modules|plugins)\/bundle\.(js|css)/.test(res.url())) { + if (/\/api\/(modules|plugins)\/bundle[./](js|css)/.test(res.url())) { bundleResponses.push({ url: res.url(), status: res.status() }); } }); @@ -75,4 +75,51 @@ test.describe('확장 병합 번들 로딩', () => { ); expect(parseErrors, `번들 실행 관련 콘솔 에러: ${parseErrors.join(' | ')}`).toHaveLength(0); }); + + /** + * 정상 구성에서는 자산 실패 안내가 뜨지 않는다. + * + * 스타일이 비어 있는 확장(0바이트 CSS)만 설치된 기본 구성에서 번들 CSS 가 503 이 되어 + * 사용자 화면마다 안내 배너가 떴다. 서버가 그 상태를 정상 빈 200 으로 판정한 뒤로는 + * 배너가 없어야 한다. + * + * // @scenario ext_type=module, asset_kind=css, active_combo=one, file_state=present_empty + * + * @effects empty_result_with_present_empty_artifacts_returns_200 + */ + test('@smoke 정상 로드 시 자산 실패 안내가 없다', async ({ page }) => { + await page.goto('/'); + await page.waitForLoadState('networkidle', { timeout: 30_000 }); + + await expect(page.locator('#g7-asset-failure-notice')).toHaveCount(0); + + const failures = await page.evaluate( + () => (window as any).G7Core?.assets?.getFailures?.() ?? [], + ); + expect(failures, `자산 실패가 남아있음: ${JSON.stringify(failures)}`).toHaveLength(0); + }); + + /** + * 진짜 소실(503)일 때의 안내 항목명은 사용자 어휘여야 한다. + * + * 종전에는 번들 구분 키가 그대로 나와 "module을(를) 불러오지 못했습니다" 로 보였다. + * + * // @scenario ext_type=module, asset_kind=css, active_combo=one, file_state=one_missing + * + * @effects bundle_css_failure_banner_uses_user_vocabulary + */ + test('번들 CSS 가 503 이면 안내 항목명이 사용자 어휘다', async ({ page }) => { + await page.route(/\/api\/(modules|plugins)\/bundle[./]css/, (route) => + route.fulfill({ status: 503, contentType: 'text/css', body: '' }), + ); + + await page.goto('/'); + + const notice = page.locator('#g7-asset-failure-notice'); + await expect(notice).toBeVisible({ timeout: 30_000 }); + + const text = (await notice.innerText()).replace(/\s+/g, ' '); + expect(text, `배너 문구: ${text}`).toContain('모듈 스타일'); + expect(text, `내부 구분 키가 노출됨: ${text}`).not.toContain('module을(를)'); + }); }); diff --git a/tests/Unit/Extension/AbstractModuleDeclaredAssetsTest.php b/tests/Unit/Extension/AbstractModuleDeclaredAssetsTest.php new file mode 100644 index 00000000..bc1279c1 --- /dev/null +++ b/tests/Unit/Extension/AbstractModuleDeclaredAssetsTest.php @@ -0,0 +1,122 @@ +moduleDir = storage_path('framework/testing/declared-assets-module/vendor-sample'); + File::ensureDirectoryExists($this->moduleDir); + } + + protected function tearDown(): void + { + File::deleteDirectory(dirname($this->moduleDir)); + parent::tearDown(); + } + + /** + * 임시 디렉토리를 모듈 루트로 쓰는 익명 서브클래스를 만든다. + * + * @param array $assets 매니페스트 assets 선언 + */ + private function moduleWithAssets(array $assets): AbstractModule + { + File::put( + $this->moduleDir.'/module.json', + json_encode(['name' => 'sample', 'version' => '1.0.0', 'assets' => $assets], JSON_UNESCAPED_UNICODE) + ); + + $root = $this->moduleDir; + + return new class($root) extends AbstractModule + { + public function __construct(private readonly string $root) {} + + protected function getModulePath(): string + { + return $this->root; + } + }; + } + + /** + * 산출물이 하나도 없어도 선언한 kind 마다 절대 경로가 나온다. + */ + public function test_returns_declared_paths_even_when_files_are_absent(): void + { + $module = $this->moduleWithAssets([ + 'js' => ['output' => 'dist/js/module.iife.js'], + 'css' => ['output' => 'dist/css/module.css'], + ]); + + $declared = $module->getDeclaredAssetAbsolutePaths(); + + $this->assertSame( + [ + 'js' => $this->moduleDir.'/dist/js/module.iife.js', + 'css' => $this->moduleDir.'/dist/css/module.css', + ], + $declared + ); + // 존재 게이트를 타는 게터는 같은 상태에서 비어 있다 — 두 축이 다르다 + $this->assertSame([], $module->getBuiltAssetAbsolutePaths()); + } + + /** + * 선언하지 않은 kind 는 키 자체가 없다. + */ + public function test_omits_undeclared_kinds(): void + { + $module = $this->moduleWithAssets(['js' => ['output' => 'dist/js/module.iife.js']]); + + $declared = $module->getDeclaredAssetAbsolutePaths(); + + $this->assertArrayHasKey('js', $declared); + $this->assertArrayNotHasKey('css', $declared); + } + + /** + * `output` 이 비어 있으면 선언으로 보지 않는다 (빈 문자열·빈 배열). + */ + public function test_treats_empty_output_as_undeclared(): void + { + $module = $this->moduleWithAssets([ + 'js' => ['output' => ''], + 'css' => [], + ]); + + $this->assertSame([], $module->getDeclaredAssetAbsolutePaths()); + } + + /** + * 산출물이 존재하되 0바이트여도 경로는 그대로 나온다 — 존재 판정은 호출자 몫이다. + */ + public function test_returns_path_for_present_zero_byte_artifact(): void + { + $module = $this->moduleWithAssets(['css' => ['output' => 'dist/css/module.css']]); + File::ensureDirectoryExists($this->moduleDir.'/dist/css'); + File::put($this->moduleDir.'/dist/css/module.css', ''); + + $path = $module->getDeclaredAssetAbsolutePaths()['css']; + + $this->assertSame($this->moduleDir.'/dist/css/module.css', $path); + $this->assertTrue(is_file($path)); + $this->assertSame(0, filesize($path)); + } +} diff --git a/tests/Unit/Extension/AbstractPluginDeclaredAssetsTest.php b/tests/Unit/Extension/AbstractPluginDeclaredAssetsTest.php new file mode 100644 index 00000000..db187345 --- /dev/null +++ b/tests/Unit/Extension/AbstractPluginDeclaredAssetsTest.php @@ -0,0 +1,119 @@ +pluginDir = storage_path('framework/testing/declared-assets-plugin/vendor-sample'); + File::ensureDirectoryExists($this->pluginDir); + } + + protected function tearDown(): void + { + File::deleteDirectory(dirname($this->pluginDir)); + parent::tearDown(); + } + + /** + * 임시 디렉토리를 플러그인 루트로 쓰는 익명 서브클래스를 만든다. + * + * @param array $assets 매니페스트 assets 선언 + */ + private function pluginWithAssets(array $assets): AbstractPlugin + { + File::put( + $this->pluginDir.'/plugin.json', + json_encode(['name' => 'sample', 'version' => '1.0.0', 'assets' => $assets], JSON_UNESCAPED_UNICODE) + ); + + $root = $this->pluginDir; + + return new class($root) extends AbstractPlugin + { + public function __construct(private readonly string $root) {} + + protected function getPluginPath(): string + { + return $this->root; + } + }; + } + + /** + * 산출물이 하나도 없어도 선언한 kind 마다 절대 경로가 나온다. + */ + public function test_returns_declared_paths_even_when_files_are_absent(): void + { + $plugin = $this->pluginWithAssets([ + 'js' => ['output' => 'dist/js/plugin.iife.js'], + 'css' => ['output' => 'dist/css/plugin.css'], + ]); + + $this->assertSame( + [ + 'js' => $this->pluginDir.'/dist/js/plugin.iife.js', + 'css' => $this->pluginDir.'/dist/css/plugin.css', + ], + $plugin->getDeclaredAssetAbsolutePaths() + ); + $this->assertSame([], $plugin->getBuiltAssetAbsolutePaths()); + } + + /** + * 선언하지 않은 kind 는 키 자체가 없다. + */ + public function test_omits_undeclared_kinds(): void + { + $plugin = $this->pluginWithAssets(['css' => ['output' => 'dist/css/plugin.css']]); + + $declared = $plugin->getDeclaredAssetAbsolutePaths(); + + $this->assertArrayHasKey('css', $declared); + $this->assertArrayNotHasKey('js', $declared); + } + + /** + * `output` 이 비어 있으면 선언으로 보지 않는다. + */ + public function test_treats_empty_output_as_undeclared(): void + { + $plugin = $this->pluginWithAssets([ + 'js' => ['output' => ''], + 'css' => [], + ]); + + $this->assertSame([], $plugin->getDeclaredAssetAbsolutePaths()); + } + + /** + * 산출물이 존재하되 0바이트여도 경로는 그대로 나온다. + */ + public function test_returns_path_for_present_zero_byte_artifact(): void + { + $plugin = $this->pluginWithAssets(['css' => ['output' => 'dist/css/plugin.css']]); + File::ensureDirectoryExists($this->pluginDir.'/dist/css'); + File::put($this->pluginDir.'/dist/css/plugin.css', ''); + + $path = $plugin->getDeclaredAssetAbsolutePaths()['css']; + + $this->assertSame($this->pluginDir.'/dist/css/plugin.css', $path); + $this->assertTrue(is_file($path)); + $this->assertSame(0, filesize($path)); + } +} diff --git a/tests/Unit/Extension/BundledManifestAssetDeclarationTest.php b/tests/Unit/Extension/BundledManifestAssetDeclarationTest.php new file mode 100644 index 00000000..f12f2961 --- /dev/null +++ b/tests/Unit/Extension/BundledManifestAssetDeclarationTest.php @@ -0,0 +1,133 @@ +` 를 싣는다 — 일반 화면에는 흔적이 없다. + * + * 0바이트 산출물은 **정당한 상태**다(스타일이 비어 있는 확장). 이 테스트는 존재만 + * 본다 — 크기를 보면 그 확장이 다시 배포 장애로 오판된다. + * + * 모집단은 glob 으로 파생한다. 손으로 적은 목록은 확장이 늘어날 때 조용히 낡는다. + */ +class BundledManifestAssetDeclarationTest extends TestCase +{ + /** + * 모듈·플러그인 매니페스트의 `assets.{js,css}` 는 객체이며 산출물이 실재해야 한다. + */ + public function test_module_and_plugin_asset_declarations_are_objects_pointing_to_existing_files(): void + { + $manifests = []; + + foreach ([['module', 'modules/_bundled'], ['plugin', 'plugins/_bundled']] as [$type, $root]) { + foreach (glob(base_path($root).'/*/'.$type.'.json') as $manifestPath) { + $manifests[] = [$manifestPath, dirname($manifestPath)]; + } + } + + // 모집단 하한 가드 — glob 이 0건이면 이 테스트는 아무것도 잠그지 않는다 + $this->assertGreaterThanOrEqual( + 10, + count($manifests), + '번들 모듈/플러그인 매니페스트 모집단이 비었거나 지나치게 작다 — 경로 규약이 바뀐 것이 아닌지 확인하라' + ); + + $violations = []; + + foreach ($manifests as [$manifestPath, $extensionDir]) { + $manifest = json_decode((string) file_get_contents($manifestPath), true) ?? []; + $assets = $manifest['assets'] ?? null; + + if ($assets === null) { + continue; + } + + $this->assertIsArray($assets, $manifestPath.': assets 는 객체여야 한다'); + + foreach (['js', 'css'] as $kind) { + if (! array_key_exists($kind, $assets)) { + continue; + } + + $declaration = $assets[$kind]; + $relative = base_path().DIRECTORY_SEPARATOR; + $shortManifest = str_replace($relative, '', $manifestPath); + + if (! is_array($declaration) || ! isset($declaration['output']) || ! is_string($declaration['output']) || $declaration['output'] === '') { + $violations[] = sprintf( + '%s: assets.%s 는 { "output": "..." } 객체여야 한다 (현재: %s)', + $shortManifest, + $kind, + json_encode($declaration, JSON_UNESCAPED_UNICODE) + ); + + continue; + } + + $artifact = $extensionDir.'/'.$declaration['output']; + + if (! is_file($artifact)) { + $violations[] = sprintf( + '%s: assets.%s.output 이 가리키는 산출물이 없다 — %s', + $shortManifest, + $kind, + $declaration['output'] + ); + } + } + } + + $this->assertSame([], $violations, "번들 확장 매니페스트 자산 선언 위반:\n".implode("\n", $violations)); + } + + /** + * 템플릿 매니페스트의 `assets` 경로도 실재해야 한다. + * + * `css`/`js` 는 파일, `fonts`/`images` 는 디렉토리로 본다. 빈 배열은 "선언 없음" 이라 + * 정상이다. + */ + public function test_template_asset_declarations_point_to_existing_files(): void + { + $manifests = glob(base_path('templates/_bundled').'/*/template.json'); + + $this->assertGreaterThanOrEqual( + 3, + count($manifests), + '번들 템플릿 매니페스트 모집단이 비었거나 지나치게 작다' + ); + + $violations = []; + $directoryKinds = ['fonts', 'images']; + + foreach ($manifests as $manifestPath) { + $manifest = json_decode((string) file_get_contents($manifestPath), true) ?? []; + $templateDir = dirname($manifestPath); + $shortManifest = str_replace(base_path().DIRECTORY_SEPARATOR, '', $manifestPath); + + foreach (($manifest['assets'] ?? []) as $kind => $paths) { + foreach ((array) $paths as $candidate) { + $absolute = $templateDir.'/'.$candidate; + $exists = in_array($kind, $directoryKinds, true) + ? is_dir($absolute) + : is_file($absolute); + + if (! $exists) { + $violations[] = sprintf('%s: assets.%s 의 %s 가 없다', $shortManifest, $kind, $candidate); + } + } + } + } + + $this->assertSame([], $violations, "번들 템플릿 매니페스트 자산 선언 위반:\n".implode("\n", $violations)); + } +} diff --git a/tests/Unit/Seo/SeoRendererTemplateCssGateTest.php b/tests/Unit/Seo/SeoRendererTemplateCssGateTest.php new file mode 100644 index 00000000..5a6b5eef --- /dev/null +++ b/tests/Unit/Seo/SeoRendererTemplateCssGateTest.php @@ -0,0 +1,105 @@ +` 로 실으면 봇 화면에서만 404 가 나고 일반 화면에는 흔적이 없다 — + * 서버 로그에도 남지 않으므로 운영자가 알 방법이 없다. + */ +class SeoRendererTemplateCssGateTest extends TestCase +{ + private string $templateRoot; + + protected function setUp(): void + { + parent::setUp(); + $this->templateRoot = storage_path('framework/testing/seo-template-css/vendor-sample'); + File::ensureDirectoryExists($this->templateRoot); + } + + protected function tearDown(): void + { + File::deleteDirectory(dirname($this->templateRoot)); + parent::tearDown(); + } + + /** + * 임시 디렉토리를 템플릿 루트로 쓰는 익명 서브클래스를 만든다. + * + * @param list $cssPaths template.json 의 assets.css 선언 + */ + private function rendererWithTemplateCss(array $cssPaths): SeoRenderer + { + File::put( + $this->templateRoot.'/template.json', + json_encode(['name' => 'sample', 'assets' => ['css' => $cssPaths]], JSON_UNESCAPED_UNICODE) + ); + + $root = $this->templateRoot; + + // 부모 생성자(의존 12개)는 호출하지 않는다 — getTemplateCssUrls 는 그 의존을 + // 하나도 쓰지 않으므로 미초기화 프로퍼티에 닿지 않는다. + return new class($root) extends SeoRenderer + { + public function __construct(private readonly string $root) {} + + protected function templateRootPath(string $identifier): string + { + return $this->root; + } + }; + } + + /** + * @param list $cssPaths + * @return list + */ + private function cssUrls(array $cssPaths): array + { + $renderer = $this->rendererWithTemplateCss($cssPaths); + $method = new ReflectionMethod(SeoRenderer::class, 'getTemplateCssUrls'); + + return $method->invoke($renderer, 'vendor-sample'); + } + + /** + * 존재하는 CSS 만 URL 로 나온다 — 없는 경로는 조용히 빠진다. + */ + public function test_only_existing_css_paths_become_urls(): void + { + File::ensureDirectoryExists($this->templateRoot.'/dist/css'); + File::put($this->templateRoot.'/dist/css/components.css', '.a{color:red}'); + + $urls = $this->cssUrls(['dist/css/components.css', 'dist/css/absent.css']); + + $this->assertCount(1, $urls); + $this->assertStringContainsString('css/components.css', $urls[0]); + } + + /** + * 선언한 CSS 가 하나도 없으면 빈 배열이다 (404 링크를 만들지 않는다). + */ + public function test_absent_css_declaration_yields_no_urls(): void + { + $this->assertSame([], $this->cssUrls(['dist/css/components.css'])); + } + + /** + * 0바이트 CSS 는 존재하므로 링크한다 — 존재 여부만 본다. + */ + public function test_present_zero_byte_css_is_still_linked(): void + { + File::ensureDirectoryExists($this->templateRoot.'/dist/css'); + File::put($this->templateRoot.'/dist/css/components.css', ''); + + $this->assertCount(1, $this->cssUrls(['dist/css/components.css'])); + } +} diff --git a/tests/Unit/Services/ExtensionBundleServiceTest.php b/tests/Unit/Services/ExtensionBundleServiceTest.php index 52d2a522..9aa5d1f5 100644 --- a/tests/Unit/Services/ExtensionBundleServiceTest.php +++ b/tests/Unit/Services/ExtensionBundleServiceTest.php @@ -110,16 +110,26 @@ class ExtensionBundleServiceTest extends TestCase /** * 에셋 **매니페스트 선언**(`getAssets()`)을 노출하는 가짜 확장 인스턴스를 만든다. * - * 산출물 경로(`getBuiltAssetAbsolutePaths`)는 존재하지 않는 파일을 가리킨다 — + * 산출물 경로(`getBuiltAssetAbsolutePaths`)는 기본적으로 존재하지 않는 파일을 가리킨다 — * "선언은 있는데 산출물이 없다"(dist 소실) 상태를 그대로 재현하기 위해서다. * + * 선언 축 게터(`getDeclaredAssetAbsolutePaths`)는 파일 존재와 무관하게 선언된 kind 마다 + * 경로를 돌려준다. `$declaredPaths` 로 그 경로를 지정하면 실제로 만들어 둔 fixture 파일을 + * 가리키게 해 "존재하되 비어 있음" 상태를 만들 수 있다. + * * @param string $identifier 확장 식별자 * @param int $priority 로딩 우선순위 * @param array $assets 매니페스트 assets 선언 * @param string $strategy 로딩 전략 + * @param array|null $declaredPaths kind => 절대 경로 (미지정 시 fixtureDir 의 부재 경로) */ - private function fakeExtensionWithAssets(string $identifier, int $priority, array $assets, string $strategy = 'global'): object - { + private function fakeExtensionWithAssets( + string $identifier, + int $priority, + array $assets, + string $strategy = 'global', + ?array $declaredPaths = null + ): object { $ext = Mockery::mock(); $ext->shouldReceive('hasAssets')->andReturn($assets !== []); $ext->shouldReceive('getIdentifier')->andReturn($identifier); @@ -136,6 +146,12 @@ class ExtensionBundleServiceTest extends TestCase array_map(fn () => 'dist/css/module.css', $assets) ); + $declared = $declaredPaths ?? array_combine( + array_keys($assets), + array_map(fn ($kind) => $this->fixtureDir.'/declared-'.$identifier.'.'.$kind, array_keys($assets)) + ); + $ext->shouldReceive('getDeclaredAssetAbsolutePaths')->andReturn($declared); + return $ext; } @@ -174,10 +190,17 @@ class ExtensionBundleServiceTest extends TestCase $this->assertSame(1, $service->countAssetDeclaringExtensions('module', 'css')); // 산출물은 하나도 존재하지 않는다 → 병합 결과는 빈 문자열. - // "선언 > 0 && 결과 0" 이 곧 컨트롤러의 503 조건이다. + // 이 값은 **선언 축**이다 — 컨트롤러의 503 판정은 소실 축(findMissingDeclaredAssets)이 + // 한다. 선언 > 0 그 자체는 장애 조건이 아니다(존재하되 비어 있으면 정상 빈 200). $this->assertSame('', $service->getBundleFilePath('module', 'js', 12345)); } + /** + * 실행 순서는 오직 manifest `loading.priority` 오름차순이다 — 확장 이름을 지목하는 + * 분기를 두지 않는다. + * + * @effects ordered_by_priority_ascending_only_no_name_hardcode + */ public function test_orders_global_assets_by_priority_ascending(): void { $a = $this->writeFixture('a.js', '(function(){})()'); @@ -195,6 +218,11 @@ class ExtensionBundleServiceTest extends TestCase $this->assertSame(['ext-a', 'ext-b', 'ext-c'], array_keys($ordered)); } + /** + * global 전략이 아닌 확장은 번들 모집단이 아니다 (레이아웃/지연 로딩이 따로 처리한다). + * + * @effects non_global_strategy_excluded_from_bundle + */ public function test_skips_non_global_strategy(): void { $g = $this->writeFixture('g.js', '(function(){})()'); @@ -211,6 +239,11 @@ class ExtensionBundleServiceTest extends TestCase $this->assertArrayNotHasKey('ext-layout', $ordered); } + /** + * IIFE 사이는 `\n;\n` 로 잇는다 — 구분자가 없으면 ASI 경계가 깨져 번들 전체가 죽는다. + * + * @effects js_iife_joined_with_semicolon_newline_separator + */ public function test_js_bundle_joins_iife_with_semicolon_newline_separator(): void { // 세미콜론 없이 끝나는 IIFE 2개 (ecommerce 형태) @@ -232,6 +265,9 @@ class ExtensionBundleServiceTest extends TestCase $this->assertLessThan(strpos($js, 'window.B=2'), strpos($js, 'window.A=1')); } + /** + * @effects prod_strips_source_mapping_url + */ public function test_prod_strips_source_mapping_url(): void { $this->app['env'] = 'production'; @@ -248,6 +284,9 @@ class ExtensionBundleServiceTest extends TestCase $this->assertStringNotContainsString('sourceMappingURL', $js); } + /** + * @effects dev_rewrites_source_mapping_url_to_asset_serving_path + */ public function test_dev_rewrites_source_mapping_url_to_asset_serving_path(): void { // 자산 URL 표기(경로형 vs `?file=` 쿼리형)는 사이트 설정이 정한다. 이 테스트가 보려는 @@ -300,6 +339,11 @@ class ExtensionBundleServiceTest extends TestCase $this->assertStringContainsString('sourceMappingURL', $bundle); } + /** + * 한 확장의 읽기 실패가 번들 전체를 소실시키지 않는다 — 그 확장만 빠지고 나머지는 병합된다. + * + * @effects per_extension_fault_tolerance_skips_missing_file_keeps_rest + */ public function test_per_extension_fault_tolerance_skips_missing_file(): void { $good = $this->writeFixture('good.js', '(function(){window.GOOD=1})()'); @@ -323,6 +367,8 @@ class ExtensionBundleServiceTest extends TestCase * 적었지만, 번들 URL 이 내려오면 프론트는 개별 로딩을 아예 타지 않는다 * (TemplateApp.loadExtensionAssets). 즉 제외 = 그 확장 스타일이 하나도 적용되지 않음 * 이었고, 오류도 로그 흔적도 화면 경고도 남지 않았다. + * + * @effects css_with_relative_url_rewritten_not_excluded */ public function test_css_with_relative_url_is_rewritten_not_excluded(): void { @@ -370,6 +416,9 @@ class ExtensionBundleServiceTest extends TestCase $this->assertStringContainsString('url(data:image/gif;base64,AA==)', $css); } + /** + * @effects empty_bundle_returns_empty_path_and_empty_ok_response + */ public function test_empty_bundle_returns_empty_path(): void { $this->moduleManager->shouldReceive('getActiveModules')->andReturn([]); @@ -379,6 +428,9 @@ class ExtensionBundleServiceTest extends TestCase $this->assertSame('', $path); } + /** + * @effects prod_writes_versioned_cache_file_and_reuses_on_same_version + */ public function test_prod_writes_versioned_cache_file_and_reuses_it(): void { $this->app['env'] = 'production'; @@ -402,6 +454,42 @@ class ExtensionBundleServiceTest extends TestCase $this->assertSame($path1, $path2); } + /** + * 비프로덕션은 같은 version 이어도 매 요청 다시 병합한다 (캐시 재사용 없음). + * + * 프로덕션은 같은 version 캐시가 있으면 그대로 재사용하지만, 비프로덕션에서 그러면 + * 개발 중 rebuild 가 반영되지 않는다. 소스를 바꿨는데 화면이 그대로인 상태는 오류도 + * 로그도 남지 않아 원인을 짚을 수 없다. + * + * @effects non_production_rebuilds_every_request_no_disk_cache + */ + public function test_non_production_rebuilds_every_request_without_cache_reuse(): void + { + $this->assertFalse(app()->environment('production')); + + $a = $this->writeFixture('nonprod.js', '(function(){window.A=1})()'); + $this->moduleManager->shouldReceive('getActiveModules')->andReturn([ + 'ext-a' => $this->fakeExtension('ext-a', 10, $a, null), + ]); + + $svc = $this->service(); + + $path1 = $svc->getBundleFilePath('module', 'js', 4242); + $this->assertStringContainsString('window.A=1', (string) file_get_contents($path1)); + + // 소스를 바꾸고 **같은 version** 으로 다시 요청 → 재병합되어야 한다 + File::put($a, '(function(){window.A=2})()'); + $path2 = $svc->getBundleFilePath('module', 'js', 4242); + + $this->assertSame($path1, $path2); + $this->assertStringContainsString('window.A=2', (string) file_get_contents($path2)); + + @unlink($path1); + } + + /** + * @effects cleanup_removes_stale_version_bundles_only + */ public function test_cleanup_removes_stale_version_bundles_only(): void { $bundleDir = storage_path('app/ext-bundles'); @@ -421,6 +509,9 @@ class ExtensionBundleServiceTest extends TestCase $this->assertFileDoesNotExist($bundleDir.'/plugin.100.css'); } + /** + * @effects clear_bundles_by_type_scopes_to_prefix + */ public function test_clear_bundles_by_type(): void { $bundleDir = storage_path('app/ext-bundles'); @@ -498,6 +589,9 @@ class ExtensionBundleServiceTest extends TestCase } } + /** + * @effects plugin_bundle_gdpr_first_when_priority_lowest + */ public function test_plugin_bundle_orders_by_priority_gdpr_first_when_lowest(): void { // gdpr 가 priority 50 으로 최상단(제약 1 회귀 가드) — 이름 하드코딩 아닌 선언 결과 @@ -516,4 +610,105 @@ class ExtensionBundleServiceTest extends TestCase $js = $this->service()->buildJsBundle('plugin'); $this->assertLessThan(strpos($js, 'window.OTHER=1'), strpos($js, 'window.GDPR=1')); } + + /** + * 선언한 산출물이 **존재하되 0바이트**면 소실 목록에 넣지 않는다. + * + * 스타일 소스가 자리표시 주석뿐인 확장은 0바이트 CSS 를 내보내는 정당한 상태다. + * 이것을 소실로 세면 그 확장만 설치된 기본 구성이 통째로 503 이 된다. + * + * @effects empty_result_with_present_empty_artifacts_returns_200 + */ + public function test_find_missing_declared_assets_ignores_present_zero_byte_files(): void + { + $cssPath = $this->writeFixture('present-empty.css', ''); + + $this->moduleManager->shouldReceive('getActiveModules')->andReturn([ + 'ext-empty-css' => $this->fakeExtensionWithAssets( + 'ext-empty-css', + 100, + ['css' => ['output' => 'dist/css/module.css']], + 'global', + ['css' => $cssPath] + ), + ]); + + $service = $this->service(); + + $this->assertSame(0, filesize($cssPath)); + $this->assertSame([], $service->findMissingDeclaredAssets('module', 'css')); + // 선언 축은 그대로 1 — 두 축이 다른 것을 잰다 + $this->assertSame(1, $service->countAssetDeclaringExtensions('module', 'css')); + // 병합 결과는 빈 문자열이지만 장애가 아니다 + $this->assertSame('', $service->buildCssBundle('module')); + } + + /** + * 선언한 산출물이 **없으면** 그 절대 경로를 소실 목록으로 돌려준다. + * + * non-global 전략 확장은 병합 모집단이 아니므로 소실 판정에서도 제외된다 — + * 두 판정이 같은 모집단을 써야 한쪽만 장애로 보는 어긋남이 생기지 않는다. + * + * @effects empty_result_with_missing_declared_artifact_returns_503 + */ + public function test_find_missing_declared_assets_lists_absent_files(): void + { + $absent = $this->fixtureDir.'/absent-module.css'; + $absentLayout = $this->fixtureDir.'/absent-layout.css'; + @unlink($absent); + @unlink($absentLayout); + + $this->moduleManager->shouldReceive('getActiveModules')->andReturn([ + 'ext-gone' => $this->fakeExtensionWithAssets( + 'ext-gone', + 100, + ['css' => ['output' => 'dist/css/module.css']], + 'global', + ['css' => $absent] + ), + 'ext-layout' => $this->fakeExtensionWithAssets( + 'ext-layout', + 100, + ['css' => ['output' => 'dist/css/module.css']], + 'layout', + ['css' => $absentLayout] + ), + ]); + + $missing = $this->service()->findMissingDeclaredAssets('module', 'css'); + + $this->assertSame([$absent], $missing); + $this->assertNotContains($absentLayout, $missing); + } + + /** + * 플러그인 축도 같은 판정을 쓴다 — 모집단만 다르다. + * + * @effects bundle_decision_is_shared_across_extension_types + */ + public function test_find_missing_declared_assets_covers_plugins(): void + { + $absent = $this->fixtureDir.'/absent-plugin.js'; + @unlink($absent); + $present = $this->writeFixture('present-plugin.js', ''); + + $this->pluginManager->shouldReceive('getActivePlugins')->andReturn([ + 'plg-gone' => $this->fakeExtensionWithAssets( + 'plg-gone', + 100, + ['js' => ['output' => 'dist/js/plugin.iife.js']], + 'global', + ['js' => $absent] + ), + 'plg-empty' => $this->fakeExtensionWithAssets( + 'plg-empty', + 100, + ['js' => ['output' => 'dist/js/plugin.iife.js']], + 'global', + ['js' => $present] + ), + ]); + + $this->assertSame([$absent], $this->service()->findMissingDeclaredAssets('plugin', 'js')); + } } diff --git a/tests/scenarios/extension-bundle-loading.yaml b/tests/scenarios/extension-bundle-loading.yaml index 1ed66ef7..d922321e 100644 --- a/tests/scenarios/extension-bundle-loading.yaml +++ b/tests/scenarios/extension-bundle-loading.yaml @@ -1,4 +1,4 @@ -# audit:allow test-scenario-coverage reason: 서버측 확장 번들 병합 도입 회귀 가드. 입력 axis(활성 조합·환경·에셋 종류)의 cross-product 는 test_files 의 Unit/Feature 가 cover 하고, effects 는 병합 계약(순서/구분자/소스맵/캐시/폴백)과 브라우저 실측(요청수/gdpr race)을 enumerate. +# audit:allow test-scenario-coverage[cross_product] reason: 입력 axis 의 완전 cross-product(11축)는 조합 폭발이라 대표 조합만 마킹한다. effects 축은 면제하지 않는다 — 모든 effect 가 테스트 마킹으로 도달해야 한다. feature: 확장(모듈/플러그인) 프론트엔드 IIFE/CSS 서버측 번들 병합 @@ -24,7 +24,7 @@ axes: version_state: [first_request, cache_hit, version_bumped] source_map_state: [present, absent] css_url_state: [no_url, absolute_url, relative_url] - file_state: [all_present, one_missing] + file_state: [all_present, present_empty, one_missing] priority_order: [ascending, gdpr_lowest] bundle_urls_present: [present, absent_fallback] @@ -39,7 +39,7 @@ effects: - prod_strips_source_mapping_url - dev_rewrites_source_mapping_url_to_asset_serving_path - per_extension_fault_tolerance_skips_missing_file_keeps_rest - - css_with_relative_url_excluded_from_bundle + - css_with_relative_url_rewritten_not_excluded - empty_bundle_returns_empty_path_and_empty_ok_response - prod_writes_versioned_cache_file_and_reuses_on_same_version - non_production_rebuilds_every_request_no_disk_cache @@ -56,9 +56,21 @@ effects: - individual_iife_requests_absent_in_browser - gdpr_interceptor_still_active_after_merge - extension_handlers_registered_no_console_error + - bundle_empty_with_declared_assets_returns_503 + - asset_declaration_count_reads_manifest_not_built_files + - bundle_decision_is_shared_across_extension_types + - bundle_disk_write_failure_falls_back_to_memory + - bundle_script_static_miss_falls_back_to_api + - empty_result_with_present_empty_artifacts_returns_200 + - empty_result_with_missing_declared_artifact_returns_503 + - missing_artifact_paths_are_logged + - bundle_css_failure_banner_uses_user_vocabulary test_files: - tests/Unit/Services/ExtensionBundleServiceTest.php + - tests/Unit/Extension/AbstractModuleDeclaredAssetsTest.php + - tests/Unit/Extension/AbstractPluginDeclaredAssetsTest.php + - tests/Unit/Extension/BundledManifestAssetDeclarationTest.php - tests/Feature/Api/Public/ExtensionBundleServingTest.php - resources/js/core/modules/__tests__/ModuleAssetLoader.test.ts - tests/Playwright/specs/extension-bundle-loading.spec.ts