feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)

공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다.

브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도
남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데
자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기
하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발
대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다.
런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다.

자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그
실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML
에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다.
편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다.

두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의
custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에
의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다.
확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을
고치면 그 변경을 감지해 재게시까지 예약된다.

FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접
넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로
나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린
스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과
분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠
화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를
함께 뒀다.

동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에
써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
HeuJung committed 2026-08-27 16:47:14 +09:00
1 parent 72f2e94c1a
commit 3945b6f1b3
1042 files changed
+107435 -947

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
/**
* 개발 대시보드 전용 스타일
*
* 종전에는 Tailwind Play CDN(`cdn.tailwindcss.com`)이 브라우저에서 실시간으로 CSS 를
* 만들어 줬다. 그 요청이 실패하면 대시보드가 스타일 없는 문서로 무너지고, 디버그 모드면
* 프로덕션에서도 접근 가능한 화면이라 외부 의존을 남길 이유가 없다.
*
* 자동 소스 탐지는 끈다(`source(none)`) — 켜 두면 저장소 전체(확장 동봉 자산 포함)를
* 훑어 빌드가 끝나지 않는다. 대시보드 blade 한 파일만 `@source` 로 지정한다.
*/
@import "tailwindcss" source(none);
@source "../views/dev-dashboard.blade.php";
+82 -24
View File
@@ -31,8 +31,13 @@ import { createLogger, Logger } from './utils/Logger';
import { webSocketManager } from './websocket/WebSocketManager';
import { getModuleAssetLoader, parseModuleAssetsFromConfig, parsePluginAssetsFromConfig, parseBundleUrlsFromConfig } from './modules';
import { SystemBannerManager } from './template-engine/SystemBannerManager';
import { installUnloadGuard, isDocumentUnloading } from './template-engine/networkResilience';
import { suffixed, extStaticUrl } from './support/assetUrl';
import {
installUnloadGuard,
isDocumentUnloading,
loadScriptWithRetry,
} from './template-engine/networkResilience';
import { notifyAssetFailure, clearAssetFailure } from './assets/AssetFailureNotice';
import { suffixed, extStaticUrl, convertToCurrentMode } from './support/assetUrl';
import { fetchStaticFirst } from './support/fetchStaticFirst';
import { resetLocalInitTracking } from './template-engine/localInitSlot';
/**
@@ -245,6 +250,14 @@ export class TemplateApp {
private globalStateListeners: Set<(state: GlobalState) => void> = new Set();
/** 현재 진행 중인 라우트 변경 요청 ID (새 요청 시 이전 요청 무시용) */
private currentRouteChangeId: number = 0;
/**
* 재시도까지 실패한 레이아웃 스크립트 id 집합.
*
* 실패를 어딘가에 남기지 않으면 그 스크립트가 등록하는 핸들러가 전부 미등록이어도
* 화면에는 "버튼이 안 눌린다" 로만 나타난다. `ModuleAssetLoader` 의 `failedJsAssets`
* 와 같은 역할이다.
*/
private failedLayoutScripts: Set<string> = new Set();
/** 현재 레이아웃의 데이터 소스 정의 (if 조건으로 필터링된 결과 — refetch용) */
private currentDataSources: any[] = [];
/**
@@ -776,6 +789,8 @@ export class TemplateApp {
// bundleUrls 부재 시 개별 로딩 폴백 (회귀 안전)
if (!bundleUrls) {
await this.loadExtensionAssetsIndividually();
await moduleAssetLoader.loadCustomAssets();
return;
}
@@ -783,6 +798,10 @@ export class TemplateApp {
await moduleAssetLoader.loadBundle('module', bundleUrls.moduleJs, bundleUrls.moduleCss);
await moduleAssetLoader.loadBundle('plugin', bundleUrls.pluginJs, bundleUrls.pluginCss);
// 운영자가 덧붙인 자산은 **마지막**에 붙인다 — CSS 는 나중에 온 규칙이 이기므로,
// 확장 번들보다 뒤에 와야 재정의가 성립한다.
await moduleAssetLoader.loadCustomAssets();
logger.log('Extension bundle assets loaded successfully');
} catch (error) {
// 에셋 로드 실패는 경고만 출력하고 앱 계속 진행
@@ -2067,28 +2086,7 @@ export class TemplateApp {
continue;
}
// 스크립트 동적 로드 (Promise로 래핑)
const loadPromise = new Promise<void>((resolve, reject) => {
const scriptEl = document.createElement('script');
scriptEl.src = script.src;
scriptEl.id = script.id;
scriptEl.async = script.async ?? true;
scriptEl.onload = () => {
logger.log(`Script loaded successfully: ${script.id}`);
resolve();
};
scriptEl.onerror = () => {
logger.warn(`Failed to load script: ${script.id} (${script.src})`);
// 스크립트 로드 실패는 경고만 출력하고 계속 진행
resolve();
};
document.head.appendChild(scriptEl);
});
loadPromises.push(loadPromise);
loadPromises.push(this.loadLayoutScript(script));
}
// 모든 스크립트 로드 완료 대기
@@ -2098,6 +2096,66 @@ export class TemplateApp {
}
}
/**
* 레이아웃 스크립트 1건을 로드합니다 (재시도 + 실패 표면화).
*
* 종전에는 `onerror` 에서 `resolve()` 로 삼켜, 실패가 로그 한 줄 말고는 어디에도
* 남지 않았다. 그 스크립트가 등록하는 핸들러가 전부 미등록이 되어도 사용자에게는
* "버튼이 안 눌린다" 로만 나타났다. 같은 저장소의 `ModuleAssetLoader.loadJS` 는
* 이미 재시도 + 실패 목록 계층을 갖고 있다 — 이 경로만 그 계층이 없었다.
*
* `convertToCurrentMode` 를 거치는 이유: 레이아웃 JSON 의 `src` 는 확장자 형태로
* 굳어 있는데, 확장자를 정적 location 이 가로채는 서버(자산 URL 이중 모드)에서는
* 그 형태가 404 다. 서버가 굳혀 내려준 다른 자산 URL 들과 같은 보정을 받아야 한다.
*
* 실패해도 reject 하지 않는다 — 한 스크립트의 실패가 나머지 스크립트 로드를 막지
* 않는다는 기존 계약을 유지한다. 대신 `failedLayoutScripts` 와 안내 배너로 표면화한다.
*
* @param script 스크립트 정의
* @returns Promise<void> 성공·실패 모두 resolve
*/
private async loadLayoutScript(script: LayoutScript): Promise<void> {
const url = script.src.startsWith('/') ? convertToCurrentMode(script.src) : script.src;
try {
await loadScriptWithRetry(
url,
{ id: script.id },
{ label: `layout-script:${script.id}` }
);
this.failedLayoutScripts.delete(script.id);
clearAssetFailure(`layout-script:${script.id}`);
logger.log(`Script loaded successfully: ${script.id}`);
} catch (error) {
this.failedLayoutScripts.add(script.id);
logger.warn(`Failed to load script after retries: ${script.id} (${url})`, error);
notifyAssetFailure({
id: `layout-script:${script.id}`,
label: script.id,
retry: async () => {
document.getElementById(script.id)?.remove();
await loadScriptWithRetry(
url,
{ id: script.id },
{ label: `layout-script:${script.id}` }
);
this.failedLayoutScripts.delete(script.id);
},
});
}
}
/**
* 끝내 로드하지 못한 레이아웃 스크립트 id 목록을 돌려줍니다.
*
* @returns 실패한 스크립트 id 배열
*/
public getFailedLayoutScripts(): string[] {
return Array.from(this.failedLayoutScripts);
}
/**
* 레이아웃 스크립트 src 가 로드 허용 대상인지 판정합니다
* (KVE-2026-1915 B-2 + 신뢰 출처 허용목록).
@@ -0,0 +1,210 @@
/**
* 구동 자산 로드 실패 안내 배너
*
* 실패를 표면화하지 않으면 사용자에게는 "빈 자리" 로만 나타나고, 자체 서버 로그에도
* 흔적이 남지 않아 운영자가 원인을 특정할 수 없다.
*
* @scenario asset_class=vendored, outcome=failed
* @effects failed_asset_shows_retry_notice, notice_renders_without_host_component_on_standalone_layout
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
notifyAssetFailure,
clearAssetFailure,
clearAllAssetFailures,
getAssetFailures,
retryAssetFailures,
drainExternalAssetFailures,
} from '../assets/AssetFailureNotice';
/** 배너 컨테이너를 돌려줍니다. */
const container = () => document.getElementById('g7-asset-failure-notice');
describe('AssetFailureNotice', () => {
beforeEach(() => {
clearAllAssetFailures();
document.body.innerHTML = '';
document.documentElement.classList.remove('dark');
});
afterEach(() => {
clearAllAssetFailures();
vi.restoreAllMocks();
});
it('호스트 컴포넌트 없이 body 에 직접 배너를 세운다', () => {
notifyAssetFailure({ id: 'editor', label: '편집기' });
const el = container();
expect(el).not.toBeNull();
expect(el?.parentElement).toBe(document.body);
expect(el?.getAttribute('role')).toBe('alert');
expect(el?.getAttribute('aria-live')).toBe('polite');
});
it('caller 가 준 문구를 그대로 보여준다', () => {
notifyAssetFailure({
id: 'editor',
label: '편집기',
message: '편집기를 불러오지 못했습니다. 임시 입력창으로 전환했습니다.',
});
expect(container()?.textContent).toContain('임시 입력창으로 전환했습니다');
});
it('같은 id 는 누적하지 않고 갱신한다', () => {
notifyAssetFailure({ id: 'editor', label: '편집기' });
notifyAssetFailure({ id: 'editor', label: '편집기(갱신)' });
expect(getAssetFailures()).toHaveLength(1);
expect(getAssetFailures()[0].label).toBe('편집기(갱신)');
});
it('여러 자산이 실패하면 건수로 합산하고 항목명을 나열한다', () => {
notifyAssetFailure({ id: 'a', label: '편집기' });
notifyAssetFailure({ id: 'b', label: '아이콘' });
const text = container()?.textContent ?? '';
expect(getAssetFailures()).toHaveLength(2);
expect(text).toContain('2');
expect(text).toContain('편집기');
expect(text).toContain('아이콘');
});
it('retry 가 없으면 다시 시도 버튼을 렌더하지 않는다', () => {
notifyAssetFailure({ id: 'a', label: '아이콘' });
expect(container()?.querySelector('[data-action="retry"]')).toBeNull();
expect(container()?.querySelector('[data-action="close"]')).not.toBeNull();
});
it('닫기 버튼은 배너를 제거한다 (자동 소멸하지 않고 사용자가 닫을 때까지 유지)', () => {
notifyAssetFailure({ id: 'a', label: '아이콘' });
(container()?.querySelector('[data-action="close"]') as HTMLButtonElement).click();
expect(container()).toBeNull();
expect(getAssetFailures()).toHaveLength(0);
});
it('재시도가 성공하면 그 항목만 해제된다', async () => {
const retry = vi.fn().mockResolvedValue(undefined);
notifyAssetFailure({ id: 'a', label: '편집기', retry });
notifyAssetFailure({ id: 'b', label: '아이콘' });
await retryAssetFailures();
expect(retry).toHaveBeenCalledTimes(1);
expect(getAssetFailures().map(f => f.id)).toEqual(['b']);
});
it('재시도가 실패하면 배너를 유지하고 재시도 실패를 알린다', async () => {
const retry = vi.fn().mockRejectedValue(new Error('여전히 실패'));
notifyAssetFailure({ id: 'a', label: '편집기', retry });
await retryAssetFailures();
expect(getAssetFailures()).toHaveLength(1);
expect(container()?.textContent ?? '').toContain('다시 시도');
});
it('clearFailure 는 지정한 항목만 해제한다', () => {
notifyAssetFailure({ id: 'a', label: '편집기' });
notifyAssetFailure({ id: 'b', label: '아이콘' });
clearAssetFailure('a');
expect(getAssetFailures().map(f => f.id)).toEqual(['b']);
expect(container()).not.toBeNull();
});
it('모든 항목이 해제되면 컨테이너를 제거한다', () => {
notifyAssetFailure({ id: 'a', label: '편집기' });
clearAssetFailure('a');
expect(container()).toBeNull();
});
it('다크 모드에서 배경색이 달라진다', () => {
// 색은 개별 프로퍼티로 설정되므로 일괄 문자열 파싱 여부와 무관하게 관측된다.
notifyAssetFailure({ id: 'a', label: '편집기' });
const light = (container()?.firstElementChild as HTMLElement).style.background;
clearAllAssetFailures();
document.documentElement.classList.add('dark');
notifyAssetFailure({ id: 'a', label: '편집기' });
const dark = (container()?.firstElementChild as HTMLElement).style.background;
expect(light).not.toBe('');
expect(dark).not.toBe('');
expect(light).not.toBe(dark);
});
it('id 가 없는 호출은 무시한다', () => {
notifyAssetFailure({ id: '', label: '편집기' });
expect(getAssetFailures()).toHaveLength(0);
expect(container()).toBeNull();
});
});
describe('서버가 심은 템플릿 externals 의 실패', () => {
beforeEach(() => {
clearAllAssetFailures();
document.body.innerHTML = '';
delete (window as any).__g7ExternalAssetFailures;
delete (window as any).__g7ExternalAssetSink;
});
afterEach(() => {
clearAllAssetFailures();
delete (window as any).__g7ExternalAssetFailures;
delete (window as any).__g7ExternalAssetSink;
});
it('엔진보다 먼저 쌓인 대기열을 배너로 흘려보낸다', () => {
// 이 태그들은 엔진 번들보다 먼저 평가되므로, 실패가 대기열에 쌓인 채 도착한다.
// 여기서 비우지 않으면 아이콘 폰트 실패가 화면에 영영 드러나지 않는다.
(window as any).__g7ExternalAssetFailures = [
{ id: 'template-external:https://x/fa.css', label: 'fontawesome', retry: () => Promise.resolve() },
];
drainExternalAssetFailures();
expect(getAssetFailures().map(f => f.label)).toEqual(['fontawesome']);
expect(container()).not.toBeNull();
expect(container()!.textContent).toContain('fontawesome');
});
it('엔진이 뜬 뒤에 생긴 실패도 곧바로 배너로 간다', () => {
drainExternalAssetFailures();
expect(typeof (window as any).__g7ExternalAssetSink).toBe('function');
(window as any).__g7ExternalAssetSink({
id: 'template-external:https://x/pretendard.css',
label: 'pretendard',
});
expect(getAssetFailures().map(f => f.label)).toEqual(['pretendard']);
});
it('id 가 없는 항목은 배너에 싣지 않는다 (식별 불가 항목이 누적되지 않도록)', () => {
(window as any).__g7ExternalAssetFailures = [{ label: '이름만 있는 항목' }];
drainExternalAssetFailures();
expect(getAssetFailures()).toEqual([]);
});
it('대기열이 비어 있어도 sink 는 걸린다 (정상 부팅에서 배너를 만들지 않는다)', () => {
drainExternalAssetFailures();
expect(getAssetFailures()).toEqual([]);
expect(container()).toBeNull();
expect(typeof (window as any).__g7ExternalAssetSink).toBe('function');
});
});
@@ -1592,3 +1592,81 @@ describe('G7Core.state.getIsolated/setIsolated API', () => {
});
});
});
/**
* G7Core.asset / G7Core.assets — 확장이 자기 자산을 다루는 seam
*
* 확장 IIFE 번들은 코어의 `assetUrl.ts` 를 import 할 수 없다. 이 seam 이 없으면 확장은
* URL 을 문자열로 조립하는 수밖에 없고, 그러면 확장자를 정적 location 이 가로채는
* 서버에서 그 자산만 404 가 된다 — 지금 CDN 이 죽었을 때와 같은 증상이다.
*/
describe('G7CoreGlobals - 자산 API', () => {
let G7Core: any;
beforeEach(() => {
delete (window as any).G7Core;
(window as any).G7Config = {};
initializeG7CoreGlobals(createMockDependencies());
G7Core = (window as any).G7Core;
});
afterEach(() => {
delete (window as any).G7Core;
delete (window as any).G7Config;
});
/**
* @scenario asset_class=vendored
* @effects runtime_asset_served_same_origin
*/
it('확장 타입별 자산 URL 생성기를 노출한다', () => {
expect(typeof G7Core.asset.template).toBe('function');
expect(typeof G7Core.asset.module).toBe('function');
expect(typeof G7Core.asset.plugin).toBe('function');
expect(typeof G7Core.asset.templateDir).toBe('function');
expect(typeof G7Core.asset.convertToCurrentMode).toBe('function');
});
it('플러그인 자산 URL 은 same-origin API 경로다', () => {
const url = G7Core.asset.plugin('sirsoft-ckeditor5', 'dist/vendor/ckeditor5/43.3.1/ckeditor5.umd.js');
expect(url.startsWith('/api/plugins/assets/sirsoft-ckeditor5')).toBe(true);
expect(url).not.toMatch(/^https?:/);
});
it('템플릿 자산 URL 은 dist/ 를 포함하지 않는다 (서버가 자동 부가)', () => {
const url = G7Core.asset.template('sirsoft-basic', 'vendor/font-awesome/6.4.0/css/all.inlined.css');
expect(url).toContain('vendor/font-awesome/6.4.0/css/all.inlined.css');
expect(url).not.toContain('/dist/');
});
it('디렉토리 URL 은 뒤에 파일 경로를 이어 붙일 수 있는 형태다 (AMD 로더용)', () => {
const dir = G7Core.asset.templateDir('sirsoft-admin_basic', 'vendor/monaco-editor/0.54.0/vs');
expect(dir.endsWith('/vs')).toBe(true);
expect(dir).not.toContain('?file=');
});
it('재시도 로더를 함께 노출한다 (확장이 자기 자산을 직접 로드할 때)', () => {
expect(typeof G7Core.asset.loadScript).toBe('function');
expect(typeof G7Core.asset.loadStylesheet).toBe('function');
});
/**
* @scenario asset_class=vendored, outcome=failed
* @effects failed_asset_shows_retry_notice
*/
it('자산 실패 안내 API 를 노출한다', () => {
expect(typeof G7Core.assets.notifyFailure).toBe('function');
expect(typeof G7Core.assets.clearFailure).toBe('function');
expect(typeof G7Core.assets.getFailures).toBe('function');
expect(typeof G7Core.assets.retryAll).toBe('function');
G7Core.assets.notifyFailure({ id: 'probe', label: '탐침' });
expect(G7Core.assets.getFailures().map((f: any) => f.id)).toEqual(['probe']);
G7Core.assets.clearAll();
expect(G7Core.assets.getFailures()).toEqual([]);
});
});
@@ -0,0 +1,181 @@
/**
* 사용자 추가 에셋(`custom/`) 로드
*
* 운영자가 덧붙인 자산은 확장 병합 번들 **뒤**에 붙어야 한다 — CSS 는 나중에 온 규칙이
* 이기므로, 앞에 붙으면 운영자의 재정의가 확장 스타일에 밀린다.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ModuleAssetLoader, parseCustomAssetsFromConfig } from '../modules/ModuleAssetLoader';
import { getAssetFailures, clearAllAssetFailures } from '../assets/AssetFailureNotice';
describe('ModuleAssetLoader.loadCustomAssets', () => {
let loader: ModuleAssetLoader;
let requested: Array<{ tag: string; url: string }>;
/**
* head.appendChild 를 가로채 결과를 발화시킵니다.
*
* @param decide url 을 받아 결과를 돌려주는 판정 함수
* @return void
*/
function stub(decide: (url: string) => 'load' | 'error' = () => 'load'): void {
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName !== 'SCRIPT' && node.tagName !== 'LINK') {
return node;
}
const url = String(node.getAttribute('src') ?? node.getAttribute('href') ?? '');
requested.push({ tag: node.tagName, url });
document.body.appendChild(node);
const outcome = decide(url);
queueMicrotask(() => {
if (outcome === 'error') {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
return node;
}) as any);
}
beforeEach(() => {
loader = new ModuleAssetLoader();
requested = [];
clearAllAssetFailures();
delete (window as any).G7Config;
});
afterEach(() => {
vi.restoreAllMocks();
clearAllAssetFailures();
document.querySelectorAll('[id^="g7-custom-"]').forEach(el => el.remove());
delete (window as any).G7Config;
});
describe('parseCustomAssetsFromConfig', () => {
it('설정이 없으면 빈 배열', () => {
expect(parseCustomAssetsFromConfig()).toEqual([]);
});
it('형식이 어긋난 항목은 버린다', () => {
(window as any).G7Config = {
customAssets: [
{ id: 'a', type: 'style', url: '/a.css' },
{ id: 'b', type: 'unknown', url: '/b.css' },
{ id: 'c', type: 'script' },
null,
],
};
expect(parseCustomAssetsFromConfig().map(a => a.id)).toEqual(['a']);
});
});
/**
* @scenario custom_source=convention_scan, custom_asset=css
* @effects custom_asset_loaded_after_extension_bundles
*/
it('목록이 비면 아무 요청도 하지 않는다', async () => {
stub();
await loader.loadCustomAssets();
expect(requested).toHaveLength(0);
});
it('선언 순서대로 로드하고 타입에 맞는 태그를 쓴다', async () => {
(window as any).G7Config = {
customAssets: [
{ id: 'custom:templates:t:a.css', type: 'style', url: '/a.css' },
{ id: 'custom:templates:t:b.js', type: 'script', url: '/b.js' },
],
};
stub();
await loader.loadCustomAssets();
expect(requested.map(r => r.tag)).toEqual(['LINK', 'SCRIPT']);
expect(requested.map(r => r.url)).toEqual(['/a.css', '/b.js']);
});
it('이미 로드된 항목은 다시 요청하지 않는다', async () => {
(window as any).G7Config = {
customAssets: [{ id: 'custom:templates:t:a.css', type: 'style', url: '/a.css' }],
};
stub();
await loader.loadCustomAssets();
await loader.loadCustomAssets();
expect(requested).toHaveLength(1);
});
/**
* @scenario custom_source=convention_scan, custom_asset=css, outcome=failed
* @effects failed_asset_shows_retry_notice
*/
it('실패한 항목은 안내로 표면화하되 나머지는 계속 로드한다', async () => {
(window as any).G7Config = {
customAssets: [
{ id: 'custom:templates:t:bad.css', type: 'style', url: '/bad.css' },
{ id: 'custom:templates:t:ok.css', type: 'style', url: '/ok.css' },
],
};
stub(url => (url.includes('/bad.css') ? 'error' : 'load'));
await expect(loader.loadCustomAssets()).resolves.toBeUndefined();
expect(loader.getFailedCssAssets()).toEqual([]);
expect(getAssetFailures().map(f => f.id)).toContain('custom-asset:custom:templates:t:bad.css');
expect(requested.some(r => r.url === '/ok.css')).toBe(true);
});
/**
* 게시본이 GC 로 사라지면 정적 URL 은 404 가 확정된 주소다. 같은 URL 을 재시도해도
* 복구되지 않으므로 종전 API URL 로 전환해야 한다 — 형제 경로(`loadBundleCss`)가
* 이미 갖춘 계층이다. 이 계층이 없으면 화면은 정상인데 운영자 자산만 조용히 빠진다.
*
* 세 확장 타입 전부를 건다. 템플릿만 역변환하던 상태에서는 모듈·플러그인이 통과하지
* 못한다.
*/
it.each([
['templates', 'sirsoft-basic', '/api/templates/assets/sirsoft-basic/custom/x.css'],
['modules', 'sirsoft-page', '/api/modules/assets/sirsoft-page/custom/x.css'],
['plugins', 'sirsoft-gdpr', '/api/plugins/assets/sirsoft-gdpr/custom/x.css'],
])('정적 게시 미스는 %s 도 종전 API URL 로 전환한다', async (type, identifier, expectedApi) => {
const staticUrl = `/build/ext/1234/${type}/${identifier}/assets/custom/x.css`;
(window as any).G7Config = {
customAssets: [
{ id: `custom:${type}:${identifier}:x.css`, type: 'style', url: staticUrl },
],
};
stub(url => (url.startsWith('/build/ext/') ? 'error' : 'load'));
await loader.loadCustomAssets();
// 정적 → API 순서로 정확히 두 번 요청한다
expect(requested.map(r => r.url)).toEqual([staticUrl, `${expectedApi}?v=1234`]);
// 폴백이 성공했으므로 실패 배너는 뜨지 않는다
expect(getAssetFailures()).toEqual([]);
});
it('정적 게시 URL 이 아니면 폴백 없이 그대로 재시도한다', async () => {
(window as any).G7Config = {
customAssets: [
{ id: 'custom:templates:t:x.css', type: 'style', url: '/api/templates/assets/t/custom/x.css' },
],
};
stub(() => 'load');
await loader.loadCustomAssets();
expect(requested.map(r => r.url)).toEqual(['/api/templates/assets/t/custom/x.css']);
});
});
@@ -0,0 +1,241 @@
/**
* TemplateApp.loadLayoutScripts — 레이아웃 스크립트 로드의 재시도·모드 보정·실패 표면화
*
* 종전에는 `onerror` 에서 `resolve()` 로 삼켜, 그 스크립트가 등록하는 핸들러가 전부
* 미등록이어도 사용자에게는 "버튼이 안 눌린다" 로만 나타났다. `src` 도 확장자 형태로
* 굳어 있어, 확장자를 정적 location 이 가로채는 서버에서는 자체 제공 자산이 404 였다.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { TemplateApp } from '../TemplateApp';
import type { TemplateAppConfig } from '../TemplateApp';
import { AuthManager } from '../auth/AuthManager';
const mockApiClient = {
post: vi.fn().mockResolvedValue({}),
get: vi.fn().mockResolvedValue({}),
removeToken: vi.fn(),
setToken: vi.fn(),
getToken: vi.fn().mockReturnValue(null),
setOnUnauthorized: vi.fn(),
};
vi.mock('../api/ApiClient', () => ({
getApiClient: () => mockApiClient,
}));
const { sharedActionDispatcher } = vi.hoisted(() => ({
sharedActionDispatcher: {
setNavigate: vi.fn(),
setGlobalState: vi.fn(),
setDefaultContext: vi.fn(),
setGlobalStateUpdater: vi.fn(),
registerHandler: vi.fn(),
customHandlers: new Map(),
},
}));
vi.mock('../template-engine', () => ({
initTemplateEngine: vi.fn().mockResolvedValue(undefined),
renderTemplate: vi.fn().mockResolvedValue(undefined),
destroyTemplate: vi.fn(),
getActionDispatcher: vi.fn().mockReturnValue(sharedActionDispatcher),
getState: vi.fn().mockReturnValue({
actionDispatcher: sharedActionDispatcher,
reactRoot: null,
currentLayoutJson: null,
}),
}));
vi.mock('../template-engine/TransitionManager', () => ({
transitionManager: {
setPending: vi.fn(),
getIsPending: vi.fn(() => false),
subscribe: vi.fn(() => vi.fn()),
clearSubscribers: vi.fn(),
},
}));
vi.mock('../routing/Router', () => ({
Router: vi.fn(function (this: any) {
this.loadRoutes = vi.fn().mockResolvedValue(undefined);
this.on = vi.fn();
this.navigateToCurrentPath = vi.fn();
this.getRoutes = vi.fn().mockReturnValue([]);
}),
}));
vi.mock('../template-engine/LayoutLoader', async () => {
const actual = await vi.importActual<any>('../template-engine/LayoutLoader');
return {
...actual,
LayoutLoader: vi.fn(function (this: any) {
this.loadLayout = vi.fn().mockResolvedValue({ components: [] });
}),
};
});
vi.mock('../template-engine/ComponentRegistry', () => {
const mockInstance = {
loadComponents: vi.fn().mockResolvedValue(undefined),
getComponent: vi.fn().mockReturnValue(() => null),
hasComponent: vi.fn().mockReturnValue(true),
getInstance: vi.fn(),
};
mockInstance.getInstance.mockReturnValue(mockInstance);
return {
ComponentRegistry: {
getInstance: vi.fn(() => mockInstance),
},
};
});
vi.mock('../support/assetUrl', async () => {
const actual = await vi.importActual<any>('../support/assetUrl');
return { ...actual, convertToCurrentMode: vi.fn((url: string) => `${url}#converted`) };
});
import { convertToCurrentMode } from '../support/assetUrl';
import { getAssetFailures, clearAllAssetFailures } from '../assets/AssetFailureNotice';
describe('TemplateApp.loadLayoutScripts', () => {
let app: TemplateApp;
let created: HTMLScriptElement[];
const build = (trustedScriptHosts: string[] = []): TemplateApp => {
(window as any).G7Config = { trustedScriptHosts };
const config: TemplateAppConfig = {
templateId: 'sirsoft-admin_basic',
templateType: 'admin',
locale: 'ko',
debug: false,
};
return new TemplateApp(config);
};
/**
* head.appendChild 를 가로채 결과를 발화시킵니다.
*
* 스크립트는 병렬로 로드되므로 "시도 순서" 인덱스로는 어느 스크립트의 시도인지
* 특정할 수 없다 — URL 로 판정한다.
*
* @param decide src 를 받아 결과를 돌려주는 판정 함수
*/
const stub = (decide: (src: string, attempt: number) => 'load' | 'error'): void => {
const attempts = new Map<string, number>();
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName !== 'SCRIPT') return node;
created.push(node);
const src = String(node.getAttribute('src') ?? '');
const attempt = (attempts.get(src) ?? 0) + 1;
attempts.set(src, attempt);
const outcome = decide(src, attempt);
queueMicrotask(() => {
if (outcome === 'error') {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
return node;
}) as any);
};
/** 언제나 성공하는 판정 */
const alwaysLoad = () => 'load' as const;
const load = (app: TemplateApp, scripts: any[]) =>
(app as any).loadLayoutScripts(scripts, {});
beforeEach(() => {
document.body.innerHTML = '<div id="app"></div>';
created = [];
clearAllAssetFailures();
app = build();
});
afterEach(() => {
vi.restoreAllMocks();
clearAllAssetFailures();
document.querySelectorAll('script[id^="s-"]').forEach(el => el.remove());
delete (window as any).G7Config;
});
/**
* @scenario asset_class=vendored, outcome=loaded
* @effects layout_script_url_converted_to_current_mode
*/
it('same-origin 경로는 현재 자산 URL 모드로 보정해 로드한다', async () => {
stub(alwaysLoad);
await load(app, [{ id: 's-1', src: '/api/plugins/assets/x/dist/a.js' }]);
expect(convertToCurrentMode).toHaveBeenCalledWith('/api/plugins/assets/x/dist/a.js');
expect(created[0].src).toContain('#converted');
});
it('외부 신뢰 호스트 스크립트는 모드 보정 대상이 아니다', async () => {
app = build(['t1.daumcdn.net']);
stub(alwaysLoad);
await load(app, [{ id: 's-2', src: 'https://t1.daumcdn.net/a.js' }]);
expect(created[0].src).toBe('https://t1.daumcdn.net/a.js');
});
/**
* @scenario asset_class=vendored, outcome=failed
* @effects layout_script_retries_before_failing
*/
it('일시 실패는 재시도해 복구한다', async () => {
stub((_src, attempt) => (attempt === 1 ? 'error' : 'load'));
await load(app, [{ id: 's-3', src: '/a.js' }]);
expect(created).toHaveLength(2);
expect(app.getFailedLayoutScripts()).toEqual([]);
});
/**
* @effects failed_layout_script_recorded_and_others_continue, failed_asset_shows_retry_notice
*/
it('끝내 실패하면 기록·안내하되 다른 스크립트는 계속 로드한다', async () => {
// /fail.js 는 몇 번을 시도해도 실패, /ok.js 는 성공 — 병렬 로드라 URL 로 판정한다
stub(src => (src.includes('/fail.js') ? 'error' : 'load'));
await load(app, [
{ id: 's-4', src: '/fail.js' },
{ id: 's-5', src: '/ok.js' },
]);
expect(app.getFailedLayoutScripts()).toEqual(['s-4']);
expect(getAssetFailures().map(f => f.id)).toContain('layout-script:s-4');
// 실패해도 reject 하지 않는다 (여기까지 도달한 것 자체가 계약 충족)
expect(created.filter(el => String(el.getAttribute('src')).includes('/ok.js'))).toHaveLength(1);
});
it('이미 로드된 id 는 건너뛴다', async () => {
const existing = document.createElement('script');
existing.id = 's-6';
document.body.appendChild(existing);
stub(alwaysLoad);
await load(app, [{ id: 's-6', src: '/a.js' }]);
expect(created).toHaveLength(0);
});
it('미선언 외부 origin 은 로드하지 않는다', async () => {
stub(alwaysLoad);
await load(app, [{ id: 's-7', src: 'https://evil.example.com/a.js' }]);
expect(created).toHaveLength(0);
});
});
@@ -6,7 +6,8 @@
* - 이미 로드됨(__LayoutEditorChrome 존재) → 즉시 반환, <script> 미주입 (멱등)
* - 미로드 → <script> 1회 주입, load 이벤트 후 컴포넌트 반환
* - 동시 다중 호출 → in-flight promise 병합 (중복 주입 없음)
* - 로드 실패(error) → reject + 재시도 가능
* - 로드 실패(error) → 재시도(기본 3시도) 후 reject + 재시도 가능
* - 실패 문구에 번들 경로 미노출 (engine-v1.63.0)
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
@@ -94,13 +95,64 @@ describe('loadLayoutEditorBundle — 편집기 lazy 번들 로더', () => {
expect(r3).toBe(fakeChrome);
});
it('로드 실패(error) → reject 한다', async () => {
it('로드 실패 → 3시도 후 reject 한다 (재시도 계층)', async () => {
vi.useFakeTimers();
const promise = loadLayoutEditorBundle();
expect(appendedScripts).toHaveLength(1);
const rejection = expect(promise).rejects.toThrow(/불러오지 못했습니다/);
// 네트워크 실패 시뮬레이션
appendedScripts[0].dispatchEvent(new Event('error'));
// 1회차 실패 → 백오프 대기 후 2회차 주입 → … 총 3회 시도
for (let attempt = 1; attempt <= 3; attempt++) {
expect(appendedScripts).toHaveLength(attempt);
appendedScripts[attempt - 1].dispatchEvent(new Event('error'));
await vi.advanceTimersByTimeAsync(3000);
}
await expect(promise).rejects.toThrow(/편집기 번들 로드 실패/);
expect(appendedScripts).toHaveLength(3);
await rejection;
vi.useRealTimers();
});
it('실패 문구에 번들 경로를 싣지 않는다', async () => {
vi.useFakeTimers();
const promise = loadLayoutEditorBundle();
const captured = promise.catch((e: Error) => e);
for (let attempt = 1; attempt <= 3; attempt++) {
appendedScripts[attempt - 1].dispatchEvent(new Event('error'));
await vi.advanceTimersByTimeAsync(3000);
}
const error = (await captured) as Error;
expect(error.message).not.toContain('layout-editor.min.js');
expect(error.message).not.toContain('/build/core');
vi.useRealTimers();
});
it('실패 후 재호출하면 다시 주입한다 (in-flight promise 초기화)', async () => {
vi.useFakeTimers();
const first = loadLayoutEditorBundle();
const firstSettled = first.catch(() => undefined);
for (let attempt = 1; attempt <= 3; attempt++) {
appendedScripts[attempt - 1].dispatchEvent(new Event('error'));
await vi.advanceTimersByTimeAsync(3000);
}
await firstSettled;
const fakeChrome = () => null;
const second = loadLayoutEditorBundle();
expect(appendedScripts).toHaveLength(4);
(window as any).G7Core.__LayoutEditorChrome = fakeChrome;
appendedScripts[3].dispatchEvent(new Event('load'));
await expect(second).resolves.toBe(fakeChrome);
vi.useRealTimers();
});
});
@@ -0,0 +1,558 @@
/**
* 구동 자산 로드 실패 안내 배너
*
* 화면을 그리는 데 필요한 자산(에디터 본체·아이콘 폰트·코드 편집기 등)을 끝내
* 불러오지 못했을 때, 사용자가 그 사실을 알고 조치할 수 있게 하는 배너다.
*
* 종전에는 이 계층이 아예 없었다 — 로드 실패는 `console.warn` 이나 조용한 `resolve()`
* 로 삼켜져, 사용자에게는 "버튼이 안 눌린다" · "입력창 자리가 비어 있다" 로만 나타났다.
* 자체 서버 로그에도 흔적이 없어 운영자가 원인을 특정할 수 없었다.
*
* 이 모듈은 호스트 컴포넌트에 의존하지 않고 DOM 에 직접 주입한다. Toast·Modal 은
* 베이스 레이아웃이 마운트한 호스트 컴포넌트가 있어야 화면에 뜨는데, 독립 레이아웃
* (`extends` 없음 — 예: `admin_login.json`)에는 그 호스트가 없다. 자산 실패는 바로
* 그런 화면에서도 알려야 한다.
*
* Tailwind 클래스가 아니라 인라인 스타일을 쓰는 이유: 이 번들(코어 엔진)은 템플릿의
* Tailwind 빌드 CSS 와 별개라, 여기서 처음 등장하는 클래스는 어느 템플릿의 CSS 에도
* 컴파일되어 있지 않다. 자산이 실패한 상황에서 스타일까지 없으면 안내 자체가 안 보인다.
*
* @module AssetFailureNotice
* @since engine-v1.62.0
*/
import { createLogger } from '../utils/Logger';
const logger = createLogger('AssetFailureNotice');
/** 배너 컨테이너 element id */
const CONTAINER_ID = 'g7-asset-failure-notice';
/** 시스템 배너(SystemBannerManager) 컨테이너 id — 겹치지 않게 아래로 내리기 위해 참조 */
const SYSTEM_BANNER_CONTAINER_ID = 'g7-system-banners';
/**
* 자산 로드 실패 1건
*
* @since engine-v1.62.0
*/
export interface AssetFailure {
/** 중복 누적을 막는 식별자 (같은 id 는 갱신) */
id: string;
/** 짧은 항목명 (여러 건 합산 표시에 쓰인다) */
label: string;
/** 사용자에게 보일 안내 문장. 생략하면 label 기반 기본 문구 */
message?: string;
/**
* [다시 시도] 동작. 생략하면 버튼을 렌더하지 않는다.
* resolve 되면 해당 실패를 해제하고, reject 되면 배너를 유지한 채 재시도 실패를 알린다.
*/
retry?: () => void | Promise<void>;
}
/** 등록된 실패 목록 (id → 실패) */
const failures = new Map<string, AssetFailure>();
/** 재시도 진행 중 여부 */
let retrying = false;
/** 마지막 재시도가 실패했는지 */
let retryFailed = false;
/** documentElement 의 다크 클래스 변화를 감시하는 옵저버 */
let themeObserver: MutationObserver | null = null;
/**
* 번역 문자열을 얻습니다.
*
* 자산 실패는 부팅 초기에도 발생할 수 있어 번역 엔진이 아직 없을 수 있다.
* 그때는 키 대신 읽을 수 있는 폴백 문구를 쓴다 — 안내 배너에 `core.assets.retry`
* 같은 키가 그대로 노출되면 안내로서 기능하지 못한다.
*
* @param key 번역 키
* @param fallback 번역 엔진 부재 시 사용할 문구
* @param params 치환 파라미터
* @return string 번역된 문자열
* @since engine-v1.62.0
*/
function t(key: string, fallback: string, params?: Record<string, string | number>): string {
try {
const translate = (window as any)?.G7Core?.t;
if (typeof translate === 'function') {
const result = translate(key, params);
// 번역 미적재 시 키 자체가 돌아온다 — 그 경우 폴백을 쓴다
if (typeof result === 'string' && result !== key && !result.startsWith('core.assets.')) {
return result;
}
}
} catch {
// 번역 실패는 안내 표시를 막을 이유가 못 된다
}
return substitute(fallback, params);
}
/**
* 폴백 문구의 자리표시자를 치환합니다.
*
* @param text 원본 문구
* @param params 치환 파라미터
* @return string 치환된 문구
* @since engine-v1.62.0
*/
function substitute(text: string, params?: Record<string, string | number>): string {
if (!params) {
return text;
}
return Object.entries(params).reduce(
(acc, [key, value]) => acc.split('{' + key + '}').join(String(value)),
text
);
}
/**
* 자산 로드 실패를 알립니다.
*
* 같은 `id` 로 다시 호출하면 누적하지 않고 갱신한다.
*
* @param failure 실패 정보
* @return void
* @since engine-v1.62.0
*/
export function notifyAssetFailure(failure: AssetFailure): void {
if (!failure || !failure.id) {
return;
}
failures.set(failure.id, failure);
retryFailed = false;
logger.warn(`Asset failure notified: ${failure.id} (${failure.label})`);
render();
}
/**
* 자산 실패를 해제합니다 (복구되었을 때).
*
* @param id 실패 식별자
* @return void
* @since engine-v1.62.0
*/
export function clearAssetFailure(id: string): void {
if (failures.delete(id)) {
logger.log(`Asset failure cleared: ${id}`);
render();
}
}
/**
* 모든 자산 실패를 해제합니다.
*
* @return void
* @since engine-v1.62.0
*/
export function clearAllAssetFailures(): void {
if (failures.size === 0) {
return;
}
failures.clear();
render();
}
/**
* 현재 등록된 자산 실패 목록을 돌려줍니다.
*
* 테스트·E2E 가 "실패가 표면화되었는가" 를 화면 문자열이 아니라 상태로 단언할 수 있게 한다.
*
* @return AssetFailure[] 실패 목록 (등록 순서)
* @since engine-v1.62.0
*/
export function getAssetFailures(): AssetFailure[] {
return Array.from(failures.values());
}
/**
* 등록된 실패 중 재시도 가능한 것을 모두 재시도합니다.
*
* @return Promise<void>
* @since engine-v1.62.0
*/
export async function retryAssetFailures(): Promise<void> {
if (retrying) {
return;
}
retrying = true;
retryFailed = false;
render();
const targets = Array.from(failures.values()).filter(item => typeof item.retry === 'function');
let anyFailed = false;
for (const target of targets) {
try {
await target.retry!();
failures.delete(target.id);
} catch (error) {
anyFailed = true;
logger.warn(`Asset retry failed: ${target.id}`, error);
}
}
retrying = false;
retryFailed = anyFailed;
render();
}
/**
* 다크 모드 여부를 판정합니다.
*
* @return bool 다크 모드이면 true
* @since engine-v1.62.0
*/
function isDarkMode(): boolean {
try {
return document.documentElement.classList.contains('dark');
} catch {
return false;
}
}
/**
* 배너를 DOM 에 렌더링합니다.
*
* @return void
* @since engine-v1.62.0
*/
function render(): void {
if (typeof document === 'undefined' || !document.body) {
return;
}
const existing = document.getElementById(CONTAINER_ID);
if (failures.size === 0) {
existing?.remove();
stopThemeObserver();
return;
}
const container = existing ?? createContainer();
applyContainerStyle(container);
container.replaceChildren(buildContent());
startThemeObserver();
}
/**
* 배너 컨테이너를 생성해 body 에 붙입니다.
*
* @return HTMLElement 컨테이너
* @since engine-v1.62.0
*/
function createContainer(): HTMLElement {
const container = document.createElement('div');
container.id = CONTAINER_ID;
container.setAttribute('role', 'alert');
container.setAttribute('aria-live', 'polite');
document.body.appendChild(container);
return container;
}
/**
* 컨테이너 스타일을 적용합니다.
*
* 시스템 배너(유지보수·프리뷰)가 떠 있으면 그 아래로 내려 겹치지 않게 한다.
* 콘텐츠는 밀어내지 않는다 — 자산 실패는 화면 레이아웃을 바꿔야 할 만큼의 사건이 아니고,
* 밀어내면 폴백 입력창의 위치가 흔들린다.
*
* @param container 컨테이너 element
* @return void
* @since engine-v1.62.0
*/
function applyContainerStyle(container: HTMLElement): void {
const systemBanners = document.getElementById(SYSTEM_BANNER_CONTAINER_ID);
const offset = systemBanners?.offsetHeight ?? 0;
container.style.cssText = [
'position:fixed',
`top:${offset}px`,
'left:0',
'right:0',
'z-index:9998',
'display:flex',
'justify-content:center',
'pointer-events:none',
].join(';');
}
/**
* 배너 본문을 구성합니다.
*
* `innerHTML` 을 쓰지 않고 element 를 조립한다 — 문구에 확장이 넘긴 label 이 섞이므로
* 문자열 조립은 주입 경로가 된다.
*
* @return HTMLElement 본문 element
* @since engine-v1.62.0
*/
function buildContent(): HTMLElement {
const dark = isDarkMode();
const items = Array.from(failures.values());
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768;
const box = document.createElement('div');
box.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 ${dark ? '#78350f' : '#fcd34d'}`,
`background:${dark ? '#451a03' : '#fffbeb'}`,
`color:${dark ? '#fef3c7' : '#78350f'}`,
'box-shadow:0 4px 12px rgba(0,0,0,0.12)',
'font-size:14px',
'line-height:1.5',
'display:flex',
isMobile ? 'flex-direction:column' : 'flex-direction:row',
isMobile ? 'align-items:stretch' : 'align-items:center',
'gap:12px',
].join(';');
// 테마 색은 개별 프로퍼티로 한 번 더 못 박는다. 일괄 문자열(cssText)은 파서가
// 모르는 선언 하나로 전체가 버려지는 환경이 있어(테스트 환경의 jsdom 이 그렇다)
// 색이 통째로 빠질 수 있다 — 안내 배너가 배경 없이 뜨면 안내로서 기능하지 못한다.
box.style.background = dark ? '#451a03' : '#fffbeb';
box.style.color = dark ? '#fef3c7' : '#78350f';
box.style.borderColor = dark ? '#78350f' : '#fcd34d';
box.appendChild(buildMessageArea(items, isMobile));
box.appendChild(buildActions(items, isMobile, dark));
return box;
}
/**
* 문구 영역을 구성합니다.
*
* @param items 실패 목록
* @param isMobile 모바일 폭 여부
* @return HTMLElement 문구 영역
* @since engine-v1.62.0
*/
function buildMessageArea(items: AssetFailure[], isMobile: boolean): HTMLElement {
const wrap = document.createElement('div');
wrap.style.cssText = ['flex:1 1 auto', 'min-width:0', 'display:flex', 'gap:8px'].join(';');
const icon = document.createElement('span');
icon.setAttribute('aria-hidden', 'true');
icon.textContent = '⚠';
icon.style.cssText = 'flex:0 0 auto;font-size:16px;line-height:1.4';
wrap.appendChild(icon);
const texts = document.createElement('div');
texts.style.cssText = 'flex:1 1 auto;min-width:0';
if (items.length === 1) {
const only = items[0];
const line = document.createElement('div');
line.setAttribute('data-asset-failure-id', only.id);
line.textContent =
only.message ??
t('core.assets.load_failed', '{label}을(를) 불러오지 못했습니다.', { label: only.label });
texts.appendChild(line);
} else {
const head = document.createElement('div');
head.style.cssText = 'font-weight:600';
head.textContent = t('core.assets.load_failed_multiple', '{count}개 항목을 불러오지 못했습니다.', {
count: items.length,
});
texts.appendChild(head);
const list = document.createElement('div');
list.style.cssText = 'margin-top:2px;opacity:0.9;word-break:break-word';
list.textContent = items.map(item => item.label).join(', ');
texts.appendChild(list);
}
if (retryFailed) {
const failedLine = document.createElement('div');
failedLine.style.cssText = 'margin-top:4px;font-weight:600';
failedLine.textContent = t(
'core.assets.retry_failed',
'다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요.'
);
texts.appendChild(failedLine);
}
wrap.appendChild(texts);
if (isMobile) {
wrap.style.alignItems = 'flex-start';
}
return wrap;
}
/**
* 버튼 영역을 구성합니다.
*
* @param items 실패 목록
* @param isMobile 모바일 폭 여부
* @param dark 다크 모드 여부
* @return HTMLElement 버튼 영역
* @since engine-v1.62.0
*/
function buildActions(items: AssetFailure[], isMobile: boolean, dark: boolean): HTMLElement {
const actions = document.createElement('div');
actions.style.cssText = [
'flex:0 0 auto',
'display:flex',
'gap:8px',
isMobile ? 'width:100%' : '',
'align-items:center',
]
.filter(Boolean)
.join(';');
const hasRetry = items.some(item => typeof item.retry === 'function');
if (hasRetry) {
const retryButton = document.createElement('button');
retryButton.type = 'button';
retryButton.dataset.action = 'retry';
retryButton.disabled = retrying;
retryButton.textContent = retrying
? t('core.assets.retrying', '다시 시도 중...')
: t('core.assets.retry', '다시 시도');
retryButton.style.cssText = [
isMobile ? 'flex:1 1 auto' : '',
'padding:6px 14px',
'border-radius:6px',
'font-size:14px',
'font-weight:600',
'cursor:pointer',
`border:1px solid ${dark ? '#b45309' : '#d97706'}`,
`background:${dark ? '#b45309' : '#f59e0b'}`,
`color:${dark ? '#fffbeb' : '#451a03'}`,
retrying ? 'opacity:0.6' : '',
]
.filter(Boolean)
.join(';');
retryButton.addEventListener('click', () => {
void retryAssetFailures();
});
actions.appendChild(retryButton);
}
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.dataset.action = 'close';
closeButton.setAttribute('aria-label', t('core.assets.close', '닫기'));
closeButton.textContent = '✕';
closeButton.style.cssText = [
'padding:6px 10px',
'border-radius:6px',
'font-size:14px',
'cursor:pointer',
'border:1px solid transparent',
'background:transparent',
`color:${dark ? '#fef3c7' : '#78350f'}`,
].join(';');
closeButton.addEventListener('click', () => {
clearAllAssetFailures();
});
actions.appendChild(closeButton);
return actions;
}
/**
* 다크 모드 전환을 감시해 배너 색을 따라가게 합니다.
*
* @return void
* @since engine-v1.62.0
*/
function startThemeObserver(): void {
if (themeObserver || typeof MutationObserver === 'undefined') {
return;
}
themeObserver = new MutationObserver(() => {
if (failures.size > 0) {
render();
}
});
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
}
/**
* 다크 모드 감시를 중단합니다.
*
* @return void
* @since engine-v1.62.0
*/
function stopThemeObserver(): void {
themeObserver?.disconnect();
themeObserver = null;
}
/**
* 서버가 HTML 에 직접 심은 템플릿 externals 의 로드 실패를 배너로 흘려보냅니다.
*
* 그 태그들은 엔진 번들보다 먼저 평가되므로, 실패는 `template-externals-head` 가 심어 둔
* 부트스트랩의 대기열에 쌓인다. 엔진이 뜬 뒤 그 대기열을 비우고, 이후의 실패는 곧바로
* 배너로 가도록 sink 를 건다.
*
* 이 통로가 없으면 아이콘 폰트·글꼴 CSS 실패가 "아이콘이 0×0 으로 사라진 화면" 으로만
* 나타난다 — 아이콘만으로 조작하는 버튼이 있는 화면에서는 곧 조작 불능이고, 자체 서버
* 로그에도 흔적이 없어 운영자가 원인을 특정할 수 없다.
*
* @return void
* @since engine-v1.63.0
*/
export function drainExternalAssetFailures(): void {
const globalScope = window as any;
/**
* 부트스트랩 대기열 항목을 배너 실패 항목으로 옮깁니다.
*
* @param entry 대기열 항목
* @return 배너 실패 항목
*/
const toFailure = (entry: any): AssetFailure => ({
id: String(entry?.id ?? ''),
label: String(entry?.label ?? entry?.url ?? 'asset'),
retry: typeof entry?.retry === 'function' ? entry.retry : undefined,
});
const queue: any[] = Array.isArray(globalScope.__g7ExternalAssetFailures)
? globalScope.__g7ExternalAssetFailures
: [];
queue.forEach(entry => {
if (entry?.id) {
notifyAssetFailure(toFailure(entry));
}
});
globalScope.__g7ExternalAssetSink = (entry: any) => {
if (entry?.id) {
notifyAssetFailure(toFailure(entry));
}
};
logger.log(`템플릿 externals 실패 대기열 ${queue.length}건 반영`);
}
+227 -43
View File
@@ -7,8 +7,9 @@
*/
import { createLogger } from '../utils/Logger';
import { loadScriptWithRetry } from '../template-engine/networkResilience';
import { loadScriptWithRetry, loadStylesheetWithRetry } from '../template-engine/networkResilience';
import { convertToCurrentMode, staticToLegacy } from '../support/assetUrl';
import { notifyAssetFailure } from '../assets/AssetFailureNotice';
const logger = createLogger('ModuleAssetLoader');
@@ -72,6 +73,27 @@ export class ModuleAssetLoader {
*/
private failedJsAssets: Set<string> = new Set();
/**
* 로드에 최종 실패한 CSS 번들/확장 식별자 집합
*
* CSS 실패는 로드 흐름을 멈추지 않지만(스타일이 없어도 화면은 동작한다) 사실은
* 남긴다 — 아이콘만 있는 버튼이 다수인 화면에서는 스타일 소실이 곧 조작 불능이라,
* 원인을 특정할 근거가 필요하다.
*
* @since engine-v1.62.0
*/
private failedCssAssets: Set<string> = new Set();
/**
* CSS 에셋 로드에 최종 실패한 식별자 목록을 반환합니다.
*
* @return string[] 실패한 번들 키/확장 식별자 목록
* @since engine-v1.62.0
*/
getFailedCssAssets(): string[] {
return [...this.failedCssAssets];
}
/**
* JS 에셋 로드에 최종 실패한 확장이 하나라도 있는지 반환합니다.
*
@@ -177,6 +199,77 @@ export class ModuleAssetLoader {
await Promise.all(promises);
}
/**
* 운영자가 덧붙인 사용자 추가 에셋(`custom/`)을 로드합니다.
*
* 목록은 서버가 `window.G7Config.customAssets` 로 내려준다 — 활성 확장의 `custom/`
* 디렉토리를 서버가 해석한 결과이며, 출처(파일 선언·규약 스캔·향후 설정 입력)에
* 관계없이 같은 모양의 서술자다.
*
* 확장 번들이 모두 끝난 뒤 호출해야 한다. CSS 는 나중에 온 규칙이 이기므로,
* 운영자 스타일이 확장 스타일보다 뒤에 붙어야 재정의가 성립한다.
*
* 실패해도 throw 하지 않는다 — 운영자 추가 자산 하나가 실패했다고 앱 부팅을
* 중단시킬 이유가 없다. 대신 안내 배너로 표면화한다.
*
* @return Promise<void>
* @since engine-v1.62.0
*/
async loadCustomAssets(): Promise<void> {
const assets = parseCustomAssetsFromConfig();
if (assets.length === 0) {
return;
}
for (const asset of assets) {
const elementId = `g7-custom-${asset.type}-${cssEscapeId(asset.id)}`;
if (document.getElementById(elementId)) {
continue;
}
const label = `${asset.type === 'style' ? 'custom CSS' : 'custom JS'}: ${asset.id}`;
const load = (url: string, retries?: number) =>
asset.type === 'style'
? loadStylesheetWithRetry(convertToCurrentMode(url), { id: elementId }, { label, retries })
: loadScriptWithRetry(convertToCurrentMode(url), { id: elementId }, { label, retries });
// 정적 게시(bake) URL 이면 1회만 시도하고, 미스 시 종전 API URL 로 전환한다 —
// 형제 경로(`loadBundleCss`)가 이미 갖춘 계층이다. 게시 디렉토리는 GC(현재+직전
// 1개 보존) 대상이라 캐시된 HTML 의 구버전 정적 URL 이 404 가 될 수 있고, 같은
// 정적 URL 재시도는 그 상태를 복구하지 못한다. 이 계층이 없으면 운영자 자산만
// 조용히 빠진 화면이 남는다.
const legacyUrl = staticToLegacy(asset.url);
try {
if (legacyUrl !== null) {
try {
await load(asset.url, 0);
} catch {
logger.warn(`Custom asset static miss, falling back to API: ${asset.id} (${asset.url} -> ${legacyUrl})`);
await load(legacyUrl);
}
} else {
await load(asset.url);
}
logger.log(`Custom asset loaded: ${asset.id}`);
} catch (error) {
logger.warn(`Failed to load custom asset: ${asset.id} (${asset.url})`, error);
notifyAssetFailure({
id: `custom-asset:${asset.id}`,
label: asset.id.split(':').pop() ?? asset.id,
retry: async () => {
document.getElementById(elementId)?.remove();
// 죽은 정적 URL 을 다시 부르지 않는다 — 복구 가능한 쪽으로 재시도한다
await load(legacyUrl ?? asset.url);
},
});
}
}
}
/**
* 병합 CSS 번들을 단일 `<link>` 로 로드합니다(중복 가드).
*
@@ -191,37 +284,48 @@ export class ModuleAssetLoader {
return;
}
return new Promise<void>((resolve) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.id = elementId;
// 정적 게시(bake) URL 이면 1회만 시도하고, 미스 시 종전 API URL 로 전환한다 (#122).
// 게시 디렉토리는 GC(현재+직전 1개 보존) 대상이라 캐시된 HTML 의 구버전 정적 URL 이
// 404 가 될 수 있고, 같은 정적 URL 재시도는 그 상태를 복구하지 못한다.
const legacyUrl = staticToLegacy(url);
link.onload = () => {
logger.log(`Bundle CSS loaded: ${key}`);
this.registerLoadedAsset(`bundle-${key}`, { type: 'css', element: link });
resolve();
};
link.onerror = () => {
// 정적 게시(bake) URL 미스 → 종전 API URL 로 1회 전환 (#122).
// 게시 디렉토리는 GC(현재+직전 1개 보존) 대상이라, 캐시된 HTML 의 구버전
// 정적 URL 이 404 가 될 수 있다 — fetchStaticFirst 와 동일한 즉시 폴백.
const legacy = staticToLegacy(link.getAttribute('href') ?? url);
if (legacy !== null && link.dataset.g7StaticFallback !== '1') {
link.dataset.g7StaticFallback = '1';
logger.warn(`Bundle CSS static miss, falling back to API: ${key} (${url} -> ${legacy})`);
link.href = convertToCurrentMode(legacy);
return;
try {
if (legacyUrl !== null) {
try {
await loadStylesheetWithRetry(
url,
{ id: elementId },
{ label: `bundle CSS: ${key}`, retries: 0 }
);
} catch {
logger.warn(`Bundle CSS static miss, falling back to API: ${key} (${url} -> ${legacyUrl})`);
await loadStylesheetWithRetry(
convertToCurrentMode(legacyUrl),
{ id: elementId },
{ label: `bundle CSS: ${key}` }
);
}
} else {
await loadStylesheetWithRetry(url, { id: elementId }, { label: `bundle CSS: ${key}` });
}
logger.warn(`Failed to load bundle CSS: ${key} (${url})`);
resolve();
};
logger.log(`Bundle CSS loaded: ${key}`);
document.head.appendChild(link);
});
const link = document.getElementById(elementId);
if (link) {
this.registerLoadedAsset(`bundle-${key}`, { type: 'css', element: link });
}
} catch (error) {
// 배너의 [다시 시도] 에는 **복구 가능한 URL** 을 넘긴다. 정적 미스로 여기 왔다면
// 원본 정적 URL 은 이미 404 가 확정된 주소라, 그대로 넘기면 재시도가 구조적으로
// 항상 실패한다 — 버튼은 있는데 아무것도 고치지 못하는 상태가 된다.
this.surfaceCssFailure(
`bundle-${key}`,
key,
legacyUrl !== null ? convertToCurrentMode(legacyUrl) : url,
error
);
}
}
/**
@@ -305,25 +409,47 @@ export class ModuleAssetLoader {
return;
}
return new Promise<void>((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.id = elementId;
try {
await loadStylesheetWithRetry(url, { id: elementId }, { label: `CSS: ${identifier}` });
link.onload = () => {
logger.log(`CSS loaded: ${identifier}`);
logger.log(`CSS loaded: ${identifier}`);
const link = document.getElementById(elementId);
if (link) {
this.registerLoadedAsset(identifier, { type: 'css', element: link });
resolve();
};
}
} catch (error) {
this.surfaceCssFailure(identifier, identifier, url, error);
}
}
link.onerror = () => {
logger.warn(`Failed to load CSS: ${identifier} (${url})`);
// CSS 로드 실패는 경고만 출력하고 계속 진행
resolve();
};
/**
* CSS 로드 최종 실패를 표면화합니다.
*
* JS 와 달리 **throw 하지 않는다** — 스타일이 없어도 화면은 동작하므로, 한 확장의
* CSS 실패로 나머지 확장 로드를 중단시키지 않는다는 기존 계약을 유지한다. 대신
* 실패 사실을 `failedCssAssets` 와 안내 배너에 남긴다. 종전에는 `console.warn`
* 한 줄이 전부여서, 아이콘만 있는 버튼이 조작 불능이 되어도 원인을 알 수 없었다.
*
* @param assetKey 실패 목록에 기록할 키
* @param label 사용자에게 보일 항목명
* @param url 실패한 URL
* @param error 마지막 시도의 에러
* @since engine-v1.62.0
*/
private surfaceCssFailure(assetKey: string, label: string, url: string, error: unknown): void {
logger.warn(`Failed to load CSS after retries: ${assetKey} (${url})`, error);
this.failedCssAssets.add(assetKey);
document.head.appendChild(link);
notifyAssetFailure({
id: `ext-css:${assetKey}`,
label,
retry: async () => {
document.getElementById(`module-css-${assetKey}`)?.remove();
document.getElementById(`ext-bundle-css-${assetKey.replace(/^bundle-/, '')}`)?.remove();
await loadStylesheetWithRetry(url, {}, { label: `CSS retry: ${assetKey}` });
this.failedCssAssets.delete(assetKey);
},
});
}
@@ -449,6 +575,64 @@ let moduleAssetLoaderInstance: ModuleAssetLoader | null = null;
/**
* ModuleAssetLoader 싱글톤 인스턴스를 반환합니다.
*/
/**
* 사용자 추가 에셋 서술자
*
* 서버(`App\Support\CustomAssets`)가 만든 것과 같은 모양이다. 소비자는 `source` 를
* 보지 않는다 — 파일에서 왔든, 선언에서 왔든, 나중에 설정 화면에서 왔든 같은 규칙으로
* 로드된다.
*
* @since engine-v1.62.0
*/
export interface CustomAsset {
/** 중복 로드 방지 식별자 */
id: string;
/** 자산 종류 */
type: 'style' | 'script';
/** 로드할 URL */
url: string;
/** 캐시 무효화 버전 (파일 수정 시각 등) */
version?: number | null;
/** 출처 (진단용 — 로드 규칙에는 영향을 주지 않는다) */
source?: string;
}
/**
* `window.G7Config.customAssets` 를 파싱합니다.
*
* @return CustomAsset[] 서술자 목록 (없으면 빈 배열)
* @since engine-v1.62.0
*/
export function parseCustomAssetsFromConfig(): CustomAsset[] {
const raw = (window as any)?.G7Config?.customAssets;
if (!Array.isArray(raw)) {
return [];
}
return raw.filter(
(item: any): item is CustomAsset =>
item
&& typeof item.id === 'string'
&& typeof item.url === 'string'
&& (item.type === 'style' || item.type === 'script')
);
}
/**
* 서술자 id 를 element id 에 쓸 수 있는 형태로 바꿉니다.
*
* 서술자 id 는 `custom:templates:sirsoft-basic:custom.css` 형태라 콜론·점을 포함한다.
* 그대로 두면 `document.getElementById` 는 되지만 CSS 선택자로 못 쓴다.
*
* @param id 서술자 id
* @return string 안전한 id 조각
* @since engine-v1.62.0
*/
function cssEscapeId(id: string): string {
return id.replace(/[^A-Za-z0-9_-]/g, '-');
}
export function getModuleAssetLoader(): ModuleAssetLoader {
if (!moduleAssetLoaderInstance) {
moduleAssetLoaderInstance = new ModuleAssetLoader();
@@ -18,7 +18,9 @@ describe('ModuleAssetLoader', () => {
afterEach(() => {
vi.restoreAllMocks();
document.head.querySelectorAll('[id^="module-js-"],[id^="module-css-"],[id^="ext-bundle-js-"],[id^="ext-bundle-css-"]')
// head 뿐 아니라 문서 전체를 훑는다 — appendChild 를 가로채는 테스트는 노드를
// body 에 붙이므로, head 만 치우면 다음 테스트의 "이미 로드됨" 가드에 걸린다.
document.querySelectorAll('[id^="module-js-"],[id^="module-css-"],[id^="ext-bundle-js-"],[id^="ext-bundle-css-"]')
.forEach(el => el.remove());
});
@@ -54,32 +56,35 @@ describe('ModuleAssetLoader', () => {
it('정적 번들 CSS 실패 시 레거시 API URL 로 전환한다', async () => {
const hrefs: string[] = [];
let appendedLink: any = null;
// 정적 1회차는 실패, 그 다음 시도는 성공시킨다.
// 단언 대상은 element 동일성이 아니라 **요청된 URL 의 순서**다 — 재시도 로더가
// 시도마다 새 <link> 를 만드는 것은 구현이고, 계약은 "정적 미스 → 레거시" 다.
const appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName === 'LINK') {
appendedLink = node;
hrefs.push(node.getAttribute('href'));
// 정적 fast path 미스 — 1회차 onerror
queueMicrotask(() => node.onerror?.(new Event('error')));
document.body.appendChild(node);
const isFirstAttempt = hrefs.length === 1;
queueMicrotask(() => {
if (isFirstAttempt) {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
}
return node;
}) as any);
const done = loader.loadBundle('module', null, '/build/ext/1787637589/bundles/modules.css');
try {
await loader.loadBundle('module', null, '/build/ext/1787637589/bundles/modules.css');
// 1회차 onerror 처리(마이크로태스크) 후 — 같은 link 의 href 가 레거시로 교체돼야 한다
await Promise.resolve();
await Promise.resolve();
expect(hrefs[0]).toBe('/build/ext/1787637589/bundles/modules.css');
expect(appendedLink?.getAttribute('href')).toBe('/api/modules/bundle.css?v=1787637589');
// 레거시 로드 성공 → resolve
appendedLink?.onload?.(new Event('load'));
await done;
appendSpy.mockRestore();
expect(hrefs[0]).toBe('/build/ext/1787637589/bundles/modules.css');
expect(hrefs[1]).toBe('/api/modules/bundle.css?v=1787637589');
} finally {
appendSpy.mockRestore();
}
});
it('정적 경로가 아닌 번들 URL 은 종전 재시도 계약 그대로다', async () => {
@@ -203,6 +203,11 @@ describe('자산 URL 자가 복구 불변식 (§12)', () => {
'/build/ext/1234/templates/sirsoft-basic/routes.json',
'/build/ext/1234/templates/sirsoft-basic/components.json',
'/build/ext/1234/templates/sirsoft-basic/lang/ko.json',
// 운영자 추가 에셋 — 모듈·플러그인도 `{type}/{id}/assets/**` 로 게시된다.
// 이 케이스가 없으면 한 타입만 역변환하는 드리프트가 잡히지 않는다.
'/build/ext/1234/templates/sirsoft-basic/assets/custom/custom.css',
'/build/ext/1234/modules/sirsoft-page/assets/custom/10-override.css',
'/build/ext/1234/plugins/sirsoft-gdpr/assets/custom/custom.js',
];
it('모든 정적 게시 URL 에서 두 구현의 결과가 동일하다', () => {
+41 -3
View File
@@ -178,6 +178,38 @@ export function templateAsset(identifier: string, path: string, version?: number
return extensionAsset('templates', identifier, path, version);
}
/**
* 템플릿 자산 **디렉토리** URL 을 생성합니다.
*
* AMD 로더나 웹 워커처럼 "디렉토리 접두에 파일명을 이어 붙이는" 소비자를 위한 것이다
* (예: Monaco 의 `paths.vs`). 그런 소비자에게는 확장자 없는 모드의 `?file=` 쿼리 형태를
* 줄 수 없다 — 뒤에 `/editor/editor.main.js` 를 이어 붙이면 쿼리 값 안에 경로가 들어간
* 엉뚱한 URL 이 된다.
*
* 그래서 우선순위가 다르다:
* 1. 정적 게시본이 있으면 그 경로 — 웹서버가 직접 서빙하는 **실제 디렉토리**라
* 자산 URL 모드와 무관하게 하위 파일이 그대로 해석된다.
* 2. 없으면 확장자 형태의 API 경로. 확장자를 가로채는 서버에서는 이 경로가 404 이므로
* **소비자가 폴백을 갖춰야 한다** (Monaco 는 textarea 폴백을 갖는다).
*
* @param identifier 템플릿 식별자
* @param path `dist/` 이하 디렉토리 경로 (예: `vendor/monaco-editor/0.54.0/vs`)
* @returns 디렉토리 URL (뒤에 `/` 는 붙이지 않는다)
* @since engine-v1.62.0
*/
export function templateAssetDir(identifier: string, path: string): string {
const normalizedPath = path.replace(/^\/+/, '').replace(/\/+$/, '');
const id = encodeURIComponent(identifier);
const staticUrl = extStaticUrl(`templates/${identifier}/assets/${normalizedPath}`);
if (staticUrl !== null) {
return staticUrl;
}
return `/api/templates/assets/${id}/${normalizedPath}`;
}
/**
* 모듈 자산 URL 을 생성합니다.
*
@@ -404,9 +436,15 @@ export function staticToLegacy(url: string): string | null {
const version = match[1];
const rest = match[2].split('?')[0];
const templateAssetMatch = rest.match(/^templates\/([^/]+)\/assets\/(.+)$/);
if (templateAssetMatch) {
return `/api/templates/assets/${templateAssetMatch[1]}/${templateAssetMatch[2]}?v=${version}`;
// 세 확장 타입이 같은 형태로 게시된다 — 템플릿은 `dist/**`, 모듈·플러그인은
// 운영자의 `custom/**` 이 각각 `{type}/{id}/assets/**` 로 실린다. 한 타입만 역변환하면
// 나머지 타입의 게시본이 GC 로 사라졌을 때 복구 경로가 없어, 화면은 정상인데 그 확장의
// 자산만 조용히 빠진다.
const extensionAssetMatch = rest.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);
if (extensionAssetMatch) {
const [, type, identifier, assetPath] = extensionAssetMatch;
return `/api/${type}/assets/${identifier}/${assetPath}?v=${version}`;
}
const bundleMatch = rest.match(/^bundles\/(modules|plugins)\.(js|css)$/);
+40 -39
View File
@@ -31,6 +31,7 @@ import { createLogger } from './utils/Logger';
import { webSocketManager } from './websocket/WebSocketManager';
import { initializeG7CoreGlobals, initDevToolsAPI } from './template-engine/G7CoreGlobals';
import { checkLayoutEditorMode } from './template-engine/layout-editor/hooks/useEditorMode';
import { loadScriptWithRetry } from './template-engine/networkResilience';
// LayoutEditorChrome 은 정적 import 하지 않는다 — 편집기는 별도 lazy 번들
// (layout-editor.min.js)로 분리되어 `/admin/layout-editor/*` 진입 시에만 로드된다.
// @since engine-v1.51.0
@@ -378,14 +379,24 @@ async function initTemplateEngine(options: InitOptions): Promise<void> {
* @since engine-v1.51.0
*
* 편집기는 메인 코어 번들에서 분리되어 `/admin/layout-editor/*` 진입 시에만 로드된다.
* 이미 로드돼 있으면 즉시 반환(멱등), 아니면 `<script>` 를 1회 주입하고 로드 완료를 대기한다.
* 이미 로드돼 있으면 즉시 반환(멱등), 아니면 `<script>` 를 주입하고 로드 완료를 대기한다.
* 동시 다중 호출은 in-flight promise 로 병합해 중복 주입을 막는다.
*
* 주입은 `loadScriptWithRetry` 에 위임한다 — 종전에는 이 경로만 재시도 계층이 없어,
* 일시적 네트워크 유실 한 번에 편집기가 통째로 열리지 않았다. 다른 모든 자산 경로
* (레이아웃 스크립트·확장 번들·CSS)가 이미 이 로더를 쓰므로 편집기만 예외일 이유가 없다.
*
* 실패 문구에는 번들 경로를 싣지 않는다. 사용자가 고칠 수 있는 정보가 아니고,
* 내부 배치 구조를 화면에 노출한다. 경로는 콘솔 로그로만 남긴다.
*
* @returns LayoutEditorChrome React 컴포넌트
* @throws {Error} 스크립트 로드 실패 또는 컴포넌트 미노출 시
*/
let layoutEditorLoadPromise: Promise<any> | null = null;
/** 편집기 번들 `<script>` element id */
const LAYOUT_EDITOR_SCRIPT_ID = 'g7-layout-editor-bundle';
function loadLayoutEditorBundle(): Promise<any> {
const g7 = (window as any).G7Core;
@@ -399,54 +410,44 @@ function loadLayoutEditorBundle(): Promise<any> {
return layoutEditorLoadPromise;
}
layoutEditorLoadPromise = new Promise((resolve, reject) => {
layoutEditorLoadPromise = (async () => {
// 번들 URL — blade 가 주입한 버전 포함 URL 우선, 폴백은 표준 경로
const src =
(window as any).G7Config?.coreEditorAsset || '/build/core/layout-editor.min.js';
const scriptId = 'g7-layout-editor-bundle';
// 이미 주입된 <script> 재사용
const existing = document.getElementById(scriptId) as HTMLScriptElement | null;
// 앞선 시도가 남긴 element 제거 — 남겨두면 IIFE 가 두 번 실행된다
document.getElementById(LAYOUT_EDITOR_SCRIPT_ID)?.remove();
const onReady = () => {
const chrome = (window as any).G7Core?.__LayoutEditorChrome;
if (chrome) {
resolve(chrome);
} else {
reject(new Error('편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출'));
}
// 편집기 엔트리가 컴포넌트 노출 직후 호출하는 준비 완료 콜백 (주입 전에 등록)
(window as any).G7Core = (window as any).G7Core || {};
(window as any).G7Core.__onChromeReady = () => {
/* 노출 시점 통지 — 실제 대기는 script load 이벤트가 담당한다 */
};
// 편집기 엔트리가 컴포넌트 노출 직후 호출할 준비 완료 콜백 (onload fallback 병행)
(window as any).G7Core = (window as any).G7Core || {};
(window as any).G7Core.__onChromeReady = onReady;
if (existing) {
// 주입돼 있으나 아직 실행 전 — load 이벤트 대기
existing.addEventListener('load', onReady, { once: true });
existing.addEventListener(
'error',
() => reject(new Error(`편집기 번들 로드 실패: ${src}`)),
{ once: true }
try {
await loadScriptWithRetry(
src,
{ id: LAYOUT_EDITOR_SCRIPT_ID },
{ label: 'layout-editor bundle' }
);
return;
} catch (error) {
layoutEditorLoadPromise = null; // 재시도 가능하도록 초기화
logger.error(`편집기 번들 로드 실패 (${src})`, error);
throw new Error('편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.');
}
const script = document.createElement('script');
script.id = scriptId;
script.src = src;
script.async = false; // 로드 순서 보존 (메인 번들 이후)
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
layoutEditorLoadPromise = null; // 재시도 가능하도록 초기화
reject(new Error(`편집기 번들 로드 실패: ${src}`));
},
{ once: true }
);
document.head.appendChild(script);
});
const chrome = (window as any).G7Core?.__LayoutEditorChrome;
if (!chrome) {
layoutEditorLoadPromise = null;
logger.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${src})`);
throw new Error('편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.');
}
return chrome;
})();
return layoutEditorLoadPromise;
}
@@ -5,6 +5,55 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.63.1] - 2026-08-27
### Fixed
#### 정적 게시 미스에서 운영자 추가 자산이 복구되지 않던 문제 (#123)
- `staticToLegacy()` 가 세 확장 타입을 모두 역변환한다 — 종전에는 `templates/{id}/assets/**` 만 처리했다. 모듈·플러그인의 `custom/**` 도 같은 형태(`{type}/{id}/assets/**`)로 게시되는데 그 규칙이 없어, 게시본이 GC(현재+직전 1개 보존)로 사라지면 되돌릴 주소를 만들지 못했다. blade 인라인 복구기(`partials/asset-url-recovery.blade.php`)도 동형으로 갱신했다 — 두 구현이 갈리면 코어 번들 로드 전 경로만 조용히 다르게 동작한다.
- `ModuleAssetLoader.loadCustomAssets()` 가 정적 → 종전 API 폴백 계층을 갖는다. 형제 경로(`loadBundleCss`)는 이미 갖고 있었고 이 경로만 비어 있었다: 정적 URL 이 404 가 확정된 뒤에도 같은 URL 을 3회 재시도할 뿐이라 복구가 원리상 불가능했고, 화면은 정상 렌더되면서 운영자가 덧붙인 스타일만 조용히 빠졌다.
- 자산 실패 배너의 [다시 시도]가 **복구 가능한 주소**를 다시 부른다. 종전에는 정적 미스로 실패한 경우에도 원본 정적 URL 을 넘겨, 버튼은 있는데 눌러도 구조적으로 항상 실패했다.
## [engine-v1.63.0] - 2026-08-26
### Added
#### 서버가 심은 템플릿 externals 의 로드 실패 표면화 (#123)
- `drainExternalAssetFailures()` 신설 — 템플릿 `externals`(아이콘 폰트 CSS·웹폰트·부팅 스크립트)는 서버가 HTML 에 직접 심으므로 엔진 번들보다 먼저 평가된다. 실패해도 자바스크립트에는 아무 신호가 오지 않아, engine-v1.62.0 이 세운 실패 표면화 계층이 **이 경로만 통째로 비어 있었다**: 아이콘 58개가 0×0 으로 사라진 화면이 배너도 로그도 없이 남았고(아이콘만으로 조작하는 버튼이 있는 화면에서는 곧 조작 불능), 자체 서버 로그에도 흔적이 없어 운영자가 원인을 특정할 수 없었다. 이제 각 태그의 `onerror` 가 부트스트랩 대기열에 쌓이고, 엔진이 뜨면 그 대기열을 배너로 흘려보낸 뒤 이후 실패용 sink 를 건다. 배너의 [다시 시도]는 해당 태그를 캐시 무효화 쿼리와 함께 다시 심어 복구되면 배너를 해제한다.
- 힌트(`preload`/`preconnect`/`dns-prefetch`)는 대상에서 제외한다 — 실패해도 화면 기능이 사라지지 않으므로, 여기까지 알리면 안내가 잡음이 되어 정작 조작 불능을 만드는 실패가 묻힌다.
#### 커스텀 자산 관리가 모듈·플러그인까지 확장 (#123)
- 편집기 [커스텀 자산] 모달이 **대상 선택기**를 갖는다 — 편집 중인 템플릿과 활성 모듈·플러그인을 오간다. 같은 기능이 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없고, 모듈·플러그인 `custom/` 은 그동안 FTP 말고 경로가 없었다.
- 관리 API 가 확장 공통 엔드포인트(`/api/admin/extensions/{type}/{id}/custom-assets`)로 재편됐다. 타입별로 나누면 같은 검증·문서·테스트가 세 벌로 갈리고, 그중 하나만 약해지면 그 경로가 조용한 우회로가 된다.
- 대상을 바꾸면 이전 확장의 선택·초안을 버린다. 남겨 두면 A 확장에서 열어 둔 본문을 B 확장에 저장하게 되고, 경로가 유효하면 서버는 정상 200 으로 받아들인다.
### Changed
#### 레이아웃 편집기 번들 로드의 재시도 계층 + 실패 문구 정리 (#123)
- `loadLayoutEditorBundle()` 이 `loadScriptWithRetry` 를 쓴다 — 이 경로만 재시도 계층이 없어(원시 `<script>` + `onerror` 1회), 일시적 네트워크 유실 한 번에 편집기가 통째로 열리지 않았다. 다른 모든 자산 경로(레이아웃 스크립트·확장 병합 번들·CSS)가 이미 이 로더를 쓰고 있었다.
- 실패 화면 문구에서 번들 경로를 걷어냈다. 종전에는 `편집기 번들 로드 실패: /build/core/layout-editor.min.js` 처럼 내부 배치 구조가 그대로 노출됐는데, 사용자가 고칠 수 있는 정보가 아니다. 경로는 콘솔 로그로만 남기고, 화면에는 다음 행동(네트워크 확인 · 새로고침)을 안내한다.
## [engine-v1.62.0] - 2026-08-25
### Added
#### 구동 자산 자체 제공 seam + 로드 실패 표면화 (#123)
- `networkResilience.loadStylesheetWithRetry()` 신설 — `loadScriptWithRetry` 와 동형(3시도·지수 백오프·재시도 전 element 제거·**최종 실패 시 reject**). CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다: `onerror` 를 아예 걸지 않거나 `resolve()` 로 삼켜, 스타일이 붙지 않은 화면(아이콘 소실·본문 서식 붕괴)이 오류 없이 남았다.
- `G7Core.asset.{template,templateDir,module,plugin,convertToCurrentMode,loadScript,loadStylesheet}` 신설 — 확장 IIFE 번들은 코어의 `assetUrl.ts` 를 import 할 수 없어 URL 을 문자열로 조립하는 수밖에 없었고, 그 조립은 자산 URL 이중 모드(확장자를 정적 location 이 가로채는 서버)에서 그 자산만 404 로 만든다.
- `templateAssetDir()` — AMD 로더·워커처럼 **디렉토리 접두에 파일명을 이어 붙이는** 소비자용. 정적 게시본이 있으면 그 실경로를 우선하고(모드와 무관하게 하위 파일이 해석된다), 없으면 확장자 형태 API 경로를 돌려준다. 확장자를 가로채는 서버에서는 후자가 404 이므로 소비자가 폴백을 갖춰야 한다.
- `G7Core.assets.{notifyFailure,clearFailure,clearAll,getFailures,retryAll}` + `assets/AssetFailureNotice.ts` — 자산 로드 실패를 사용자에게 알리고 재시도를 제공한다. **호스트 컴포넌트에 의존하지 않고 DOM 에 직접 주입**한다: Toast·Modal 은 베이스 레이아웃이 마운트한 호스트가 있어야 뜨는데, 독립 레이아웃(`extends` 없음 — 예: `admin_login.json`)에는 그 호스트가 없고 자산 실패는 바로 그런 화면에서도 알려야 한다. 테마 색은 일괄 문자열(cssText)이 아니라 개별 프로퍼티로도 못 박는다 — 파서가 모르는 선언 하나로 전체가 버려지는 환경에서 배너가 배경 없이 뜨면 안내로서 기능하지 못한다.
- `ModuleAssetLoader.loadCustomAssets()` + `parseCustomAssetsFromConfig()` — 운영자가 확장 `custom/` 에 덧붙인 자산을 확장 병합 번들 **뒤**에 로드한다. CSS 는 나중에 온 규칙이 이기므로 앞에 붙이면 운영자의 재정의가 확장 스타일에 밀린다.
### Changed
- `TemplateApp.loadLayoutScripts` — ① same-origin 경로에 `convertToCurrentMode` 적용(종전 미적용: 확장자를 가로채는 서버에서 자체 제공 자산이 404) ② `loadScriptWithRetry` 로 교체 ③ 최종 실패를 `failedLayoutScripts` 에 기록하고 안내 배너로 표면화. "한 스크립트의 실패가 나머지 로드를 막지 않는다" 는 기존 계약은 유지한다.
- `ModuleAssetLoader` 의 `loadCSS`/`loadBundleCss` 가 재시도 계층을 갖는다. 최종 실패는 `failedCssAssets` 와 안내 배너에 남기되 **throw 하지 않는다** — 스타일이 없어도 화면은 동작하므로 한 확장의 CSS 실패로 나머지 확장 로드를 중단시키지 않는다. 병합 CSS 의 정적 게시 미스 폴백은 종전 "같은 `<link>` 의 href 1회 교체"(재시도 예산 없음)에서 레거시 URL 에 대한 정규 재시도로 바뀌었다.
## [engine-v1.61.0] - 2026-08-25
### Added
@@ -55,6 +55,22 @@ import {
} from '../hooks/useControllableState';
import { triggerModalParentUpdate } from './ParentContextProvider';
import { IdentityGuardInterceptor, IDENTITY_REDIRECT_STASH_KEY } from '../identity/IdentityGuardInterceptor';
import { loadScriptWithRetry, loadStylesheetWithRetry } from './networkResilience';
import {
templateAsset,
templateAssetDir,
moduleAsset,
pluginAsset,
convertToCurrentMode,
} from '../support/assetUrl';
import {
notifyAssetFailure,
drainExternalAssetFailures,
clearAssetFailure,
clearAllAssetFailures,
getAssetFailures,
retryAssetFailures,
} from '../assets/AssetFailureNotice';
const logger = createLogger('G7CoreGlobals');
@@ -857,6 +873,86 @@ function initLayoutEditorStub(G7Core: any): void {
logger.log('전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨');
}
/**
* 자산 URL·자산 실패 안내 API 초기화
*
* 확장(모듈·플러그인·템플릿)의 IIFE 번들은 코어의 `assetUrl.ts` 를 import 할 수 없다
* — 별도 번들이라 모듈 그래프가 이어지지 않는다. 그래서 확장이 자기 동봉 자산의 URL 을
* 만들려면 `/api/plugins/assets/...` 를 **문자열로 조립**하는 수밖에 없었는데, 그러면
* 자산 URL 이중 모드(확장자 없는 서버)에서 그 자산만 404 가 된다.
*
* `G7Core.asset.*` 이 그 seam 이다 — 서버측 `AssetUrl` 과 같은 규약으로 URL 을 만든다.
* `G7Core.assets.*` 는 그 자산을 끝내 못 불러왔을 때의 안내·재시도 표면이다.
*
* @param G7Core 전역 객체
* @return void
* @since engine-v1.62.0
*/
function initAssetUrlAPI(G7Core: any): void {
/**
* 확장 자산 URL 생성기.
*
* 템플릿은 서버가 `dist/` 를 자동 부가하므로 `path` 에 `dist/` 를 포함하지 않는다
* (모듈·플러그인은 확장 루트 기준이라 `dist/` 를 직접 포함 — 서버측과 동일한 비대칭).
*/
G7Core.asset = {
/** 템플릿 자산 URL (`dist/` 이하 경로) */
template: (identifier: string, path: string, version?: number | string | null): string =>
templateAsset(identifier, path, version),
/**
* 템플릿 자산 **디렉토리** URL — AMD 로더·워커처럼 디렉토리 접두에 파일명을
* 이어 붙이는 소비자용. 확장자 없는 모드에서 404 일 수 있으므로 폴백이 필요하다.
*/
templateDir: (identifier: string, path: string): string => templateAssetDir(identifier, path),
/** 모듈 자산 URL (모듈 루트 기준 경로) */
module: (identifier: string, path: string, version?: number | string | null): string =>
moduleAsset(identifier, path, version),
/** 플러그인 자산 URL (플러그인 루트 기준 경로) */
plugin: (identifier: string, path: string, version?: number | string | null): string =>
pluginAsset(identifier, path, version),
/** 서버가 확장자 형태로 굳혀 내려준 URL 을 현재 모드로 보정 */
convertToCurrentMode: (url: string): string => convertToCurrentMode(url),
/**
* 재시도 계층을 갖춘 스크립트 로더.
*
* 확장이 자기 자산을 런타임에 직접 로드할 때 쓴다. 확장 번들이 코어 모듈을
* import 할 수 없어 각자 `document.createElement('script')` 를 쓰면, 코어가
* 갖춘 재시도·실패 표면화 계층이 그 경로에만 없게 된다.
*/
loadScript: (
url: string,
attrs?: Record<string, string>,
options?: Record<string, unknown>
): Promise<void> => loadScriptWithRetry(url, attrs, options as any),
/** 재시도 계층을 갖춘 스타일시트 로더 */
loadStylesheet: (
url: string,
attrs?: Record<string, string>,
options?: Record<string, unknown>
): Promise<void> => loadStylesheetWithRetry(url, attrs, options as any),
};
/**
* 자산 로드 실패 안내.
*
* 실패를 화면에 표면화하지 않으면 사용자에게는 "빈 자리" 로만 나타나고, 자체 서버
* 로그에도 흔적이 남지 않아 운영자가 원인을 특정할 수 없다.
*/
G7Core.assets = {
notifyFailure: notifyAssetFailure,
clearFailure: clearAssetFailure,
clearAll: clearAllAssetFailures,
getFailures: getAssetFailures,
retryAll: retryAssetFailures,
};
// 서버가 심은 템플릿 externals 는 엔진보다 먼저 평가되므로 실패가 대기열에 쌓여 있다.
// 여기서 비우지 않으면 아이콘 폰트·글꼴 실패가 화면에 영영 드러나지 않는다.
drainExternalAssetFailures();
logger.log('전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨');
}
/**
* 번역 관련 API 초기화
*/
@@ -3148,6 +3244,7 @@ export function initializeG7CoreGlobals(deps: G7CoreDependencies): void {
// 레이아웃 편집기 확장점 예약 접수함(편집기 lazy 로드 전 템플릿 등록을 큐에 보존)
initLayoutEditorStub(G7Core);
initCoreAPIs(G7Core, deps);
initAssetUrlAPI(G7Core);
initTranslationAPI(G7Core, deps);
initHelperAPIs(G7Core, deps);
initDispatchAPI(G7Core);
@@ -0,0 +1,129 @@
/**
* loadStylesheetWithRetry — CSS 로드의 재시도 계층
*
* CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다. 아이콘만으로 조작하는 버튼이
* 있는 화면에서는 스타일 소실이 곧 조작 불능이다.
*
* @scenario asset_class=vendored, outcome=failed
* @scenario asset_class=translation, outcome=failed
* @effects stylesheet_failure_retries_then_surfaces
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { loadStylesheetWithRetry } from '../networkResilience';
describe('loadStylesheetWithRetry', () => {
let appendSpy: ReturnType<typeof vi.spyOn>;
let created: HTMLLinkElement[];
/**
* head.appendChild 를 가로채 시도별 결과를 발화시킵니다.
*
* @param outcomes 시도 순서대로의 결과
* @return void
*/
function stub(outcomes: Array<'load' | 'error'>): void {
appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName !== 'LINK') {
return node;
}
created.push(node);
const outcome = outcomes[created.length - 1] ?? 'load';
queueMicrotask(() => {
if (outcome === 'error') {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
return node;
}) as any);
}
beforeEach(() => {
created = [];
});
afterEach(() => {
vi.restoreAllMocks();
document.querySelectorAll('link[id^="test-css"]').forEach(el => el.remove());
});
it('첫 시도에 성공하면 재시도하지 않는다', async () => {
stub(['load']);
await expect(loadStylesheetWithRetry('/a.css')).resolves.toBeUndefined();
expect(created).toHaveLength(1);
});
it('rel 과 href 를 설정하고 전달한 속성을 붙인다', async () => {
stub(['load']);
await loadStylesheetWithRetry('/a.css', { id: 'test-css-1', media: 'screen' });
expect(created[0].rel).toBe('stylesheet');
expect(created[0].getAttribute('href')).toBe('/a.css');
expect(created[0].id).toBe('test-css-1');
expect(created[0].getAttribute('media')).toBe('screen');
});
it('일시 실패 후 성공하면 최종 resolve 한다', async () => {
stub(['error', 'load']);
await expect(
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1, maxDelayMs: 2 })
).resolves.toBeUndefined();
expect(created).toHaveLength(2);
});
it('모든 시도가 실패하면 reject 한다 (실패를 resolve 로 은폐하지 않는다)', async () => {
stub(['error', 'error', 'error']);
await expect(
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1, maxDelayMs: 2 })
).rejects.toThrow(/Failed to load stylesheet/);
expect(created).toHaveLength(3);
});
it('retries 옵션으로 시도 횟수를 조정할 수 있다', async () => {
stub(['error']);
await expect(
loadStylesheetWithRetry('/a.css', {}, { retries: 0 })
).rejects.toThrow();
expect(created).toHaveLength(1);
});
it('재시도 전 실패한 element 를 문서에서 제거한다 (누적 방지)', async () => {
// 실제 DOM 에 붙여 제거 여부를 관측한다
appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName !== 'LINK') return node;
created.push(node);
document.body.appendChild(node);
const isFirst = created.length === 1;
queueMicrotask(() => {
if (isFirst) {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
return node;
}) as any);
await loadStylesheetWithRetry('/a.css', { id: 'test-css-2' }, { baseDelayMs: 1 });
// 실패분은 제거되고 성공분만 남는다
expect(document.querySelectorAll('#test-css-2')).toHaveLength(1);
expect(created[0].isConnected).toBe(false);
});
});
@@ -385,3 +385,67 @@ describe('[사례 3] 확장 부재 시 5초 백지 + 내부 식별자 raw 노출
expect(normalError.unknownHandler).toBe(false);
});
});
/**
* 사례 4: CSS 로더에 `onerror` 가 없으면 스타일 소실이 완전히 무음이다
*
* `<script>` 경로에는 재시도·실패 표면화 계층이 이미 있었는데 CSS 경로만 그 계층이
* 없었다. 같은 저장소 안에서 형제 경로의 계층이 어긋나 있으면, 그 차이는 사고가 나기
* 전까지 드러나지 않는다.
*/
describe('[사례 4] CSS 로드 실패의 무음 처리', () => {
/**
* head.appendChild 를 가로채 시도별 결과를 발화시킵니다.
*
* @param decide 시도 회차를 받아 결과를 돌려주는 판정 함수
* @return 생성된 link element 목록
*/
function stubStylesheet(decide: (attempt: number) => 'load' | 'error'): HTMLLinkElement[] {
const created: HTMLLinkElement[] = [];
vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName !== 'LINK') return node;
created.push(node);
const outcome = decide(created.length);
queueMicrotask(() => {
if (outcome === 'error') {
node.onerror?.(new Event('error'));
} else {
node.onload?.(new Event('load'));
}
});
return node;
}) as any);
return created;
}
afterEach(() => {
vi.restoreAllMocks();
});
it('CSS 실패는 재시도된다 (일시 실패가 스타일 소실로 굳지 않는다)', async () => {
const { loadStylesheetWithRetry } = await import('../networkResilience');
const created = stubStylesheet(attempt => (attempt === 1 ? 'error' : 'load'));
await expect(
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1 })
).resolves.toBeUndefined();
expect(created).toHaveLength(2);
});
it('CSS 최종 실패는 reject 된다 (resolve 로 위장하지 않는다)', async () => {
const { loadStylesheetWithRetry } = await import('../networkResilience');
stubStylesheet(() => 'error');
// 성공으로 위장하면 호출부의 try/catch 가 무력화되고, 스타일이 없다는 사실이
// 어디에도 남지 않는다 — 사례 2 와 동형의 결함이다.
await expect(
loadStylesheetWithRetry('/a.css', {}, { baseDelayMs: 1 })
).rejects.toThrow(/Failed to load stylesheet/);
});
});
@@ -28,6 +28,7 @@ import { LayoutAttachmentManager } from './components/property-controls/LayoutAt
import { CustomTranslationManager } from './components/property-controls/CustomTranslationManager';
import { PageSettingsModal } from './components/page-settings/PageSettingsModal';
import { VersionHistoryModal } from './components/VersionHistoryModal';
import { CustomAssetsModal } from './components/CustomAssetsModal';
import type { VersionTarget } from './hooks/useLayoutVersions';
import { ShortcutHelpModal } from './components/ShortcutHelpModal';
import { collectReferencedCustomKeys } from './utils/customTranslations';
@@ -521,6 +522,69 @@ function LayoutEditorChromeBody({
[templateIdentifier, activeDocument.isDirty, t],
);
// 커스텀 자산 관리 모달 — 운영자 CSS·JS·폰트·이미지를 화면에서 직접 넣고 고친다.
// 권한은 서버가 판정하므로 여기서 버튼을 감추지 않는다(모달이 403 을 안내로 바꾼다).
const handleManageCustomAssets = useCallback(() => {
const id = modal.open({
ariaLabel: t('layout_editor.custom_assets.title'),
width: 860,
maxHeightRatio: 0.86,
content: React.createElement(CustomAssetsModal, {
templateIdentifier,
t,
onClose: () => modal.close(id),
}),
});
}, [modal, templateIdentifier, t]);
// 사용자 추가 에셋(`custom/`) 적용 토글 — 탈출구(D33).
//
// 운영자가 넣은 CSS 한 줄이 화면을 조작 불능으로 만들면, 그것을 고칠 편집기에도
// 그 CSS 가 실려 있어 스스로 갇힌다. `?custom=off` 로 다시 열면 서버가 목록을
// 비워 자산이 페이지에 **도달하지 않는다** — 이미 깨진 화면에서 자바스크립트가
// 돌기를 기대하지 않아도 된다.
//
// DOM 에서 `<link>` 를 떼는 방식을 쓰지 않는 이유: 이미 실행된 custom JS 는 되돌릴
// 수 없어 절반만 꺼진다. 나가기·템플릿 전환과 같은 dirty 가드를 태운다.
//
// 현재 상태는 **서버가 실제로 한 일**(`G7Config.customAssetsDisabled`)로 판정한다.
// URL 로 판정하면 안 된다 — SPA 부팅이 주소를 다시 쓰면서 `?custom=off` 를 지우므로,
// 자산은 꺼졌는데 버튼은 "켜져 있음" 으로 표시되고 되돌릴 방법이 화면에서 사라진다.
// URL 검사는 서버가 그 값을 심지 않는 구형 렌더용 폴백으로만 남긴다.
const customAssetsDisabled =
typeof window !== 'undefined' &&
(!!(window as any).G7Config?.customAssetsDisabled ||
new URLSearchParams(window.location.search).get('custom') === 'off');
const handleToggleCustomAssets = useCallback(() => {
if (typeof window === 'undefined') return;
if (activeDocument.isDirty) {
const proceed = window.confirm(t('layout_editor.chrome.dirty_guard.message'));
if (!proceed) return;
}
const url = new URL(window.location.href);
if (customAssetsDisabled) {
url.searchParams.delete('custom');
// 주소가 이미 파라미터를 잃은 상태라면 같은 주소로의 이동은 아무 일도 하지 않는다.
// 그 경우 다시 요청하는 것 자체가 되돌리는 동작이다.
if (url.toString() === window.location.href) {
window.location.reload();
return;
}
} else {
url.searchParams.set('custom', 'off');
}
(window as any).G7Core?.dispatch?.({
handler: 'openWindow',
params: { path: `${url.pathname}${url.search}${url.hash}`, target: '_self' },
});
}, [activeDocument.isDirty, customAssetsDisabled, t]);
// 코드편집 — 기존 텍스트 레이아웃 편집기 화면을 새 창으로 연다(위지윅 편집은
// 유지한 채 코드 편집을 별도 창에서). 본체는 별도 라우트로 이미 존재
// (admin_template_layout_edit). 위지윅에서 선택 중이던 라우트 path 를 `?route=` 쿼리로
@@ -890,6 +954,9 @@ function LayoutEditorChromeBody({
templateVersion={templateVersion}
templateList={templateList}
onSwitchTemplate={handleSwitchTemplate}
onToggleCustomAssets={handleToggleCustomAssets}
customAssetsDisabled={customAssetsDisabled}
onManageCustomAssets={handleManageCustomAssets}
/>
<SaveFeedbackBanner
result={saveResult}
@@ -0,0 +1,327 @@
/**
* CustomAssetsModal + 툴바 커스텀 자산 버튼 테스트 (#123, D32·D33)
*
* 잠그는 계약:
* - 목록 403 은 오류 문구가 아니라 **안내**로 바뀐다 (권한이 부족하다는 사실과 무엇을
* 요청해야 하는지가 화면에 나와야 한다 — "HTTP 403" 은 그 둘 다 말해 주지 않는다)
* - 저장은 PUT `custom-assets/content` 로 나가고 성공 후 목록을 다시 읽는다
* - 편집 불가(바이너리) 파일은 본문 편집기를 열지 않고 교체 안내를 보여 준다
* - 툴바 토글은 `?custom=off` 상태를 문구·`aria-pressed` 로 드러낸다
*/
import React from 'react';
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { CustomAssetsModal } from '../../components/CustomAssetsModal';
import { EditorToolbar } from '../../components/EditorToolbar';
import { LayoutEditorProvider } from '../../LayoutEditorContext';
import { TranslationProvider } from '../../../TranslationContext';
import { TranslationEngine } from '../../../TranslationEngine';
/** 키를 그대로 돌려주는 t — 문구가 아니라 어떤 키가 쓰였는지를 단언한다 */
const t = (key: string): string => key;
function wrapToolbar(node: React.ReactElement): React.ReactElement {
const engine = new TranslationEngine();
return (
<TranslationProvider
translationEngine={engine}
translationContext={{ templateId: 'sirsoft-basic', locale: 'ko' }}
>
<LayoutEditorProvider templateIdentifier="sirsoft-basic" initialLocale="ko">
{node}
</LayoutEditorProvider>
</TranslationProvider>
);
}
function jsonResponse(status: number, body: unknown): Response {
return {
ok: status >= 200 && status < 300,
status,
json: async () => body,
} as unknown as Response;
}
const listBody = {
data: {
files: [
{
path: '10-overrides.css',
name: '10-overrides.css',
extension: 'css',
size: 42,
modified_at: '2026-08-26T00:00:00+00:00',
editable: true,
loaded: true,
},
{
path: 'fonts/brand.woff2',
name: 'brand.woff2',
extension: 'woff2',
size: 1024,
modified_at: '2026-08-26T00:00:00+00:00',
editable: false,
loaded: false,
},
],
editable_extensions: ['css', 'js', 'mjs', 'json'],
uploadable_extensions: ['css', 'js', 'png', 'woff2'],
max_text_bytes: 524288,
max_upload_bytes: 5242880,
},
};
describe('CustomAssetsModal', () => {
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
// 대상 목록은 서버가 심은 활성 확장 메타에서 만들어진다.
(window as any).G7Config = {
activeModules: [{ identifier: 'sirsoft-page', display_name: { ko: '페이지' } }],
activePlugins: [{ identifier: 'sirsoft-gdpr', display_name: 'GDPR' }],
};
});
afterEach(() => {
delete (window as any).G7Config;
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
/** @effects custom_asset_manager_surfaces_permission_denial_as_guidance */
it('403 은 오류 문구가 아니라 안내로 바뀐다', async () => {
fetchMock.mockResolvedValue(jsonResponse(403, { message: 'This action is unauthorized.' }));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
await waitFor(() => {
expect(screen.getByTestId('g7le-custom-assets-forbidden')).toBeTruthy();
});
// 원시 상태 코드가 아니라 안내 키가 화면에 있어야 한다
expect(screen.getByTestId('g7le-custom-assets-forbidden').textContent).toBe(
'layout_editor.custom_assets.forbidden',
);
expect(screen.queryByTestId('g7le-custom-assets-error')).toBeNull();
});
it('목록을 읽어 파일 행을 그린다', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
await waitFor(() => {
expect(screen.getByTestId('g7le-custom-asset-row-10-overrides.css')).toBeTruthy();
});
expect(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2')).toBeTruthy();
expect(
screen.getByTestId('g7le-custom-asset-row-10-overrides.css').getAttribute('data-loaded'),
).toBe('true');
});
/** @effects custom_asset_binary_file_offers_replace_not_text_edit */
it('편집 불가 파일은 본문 편집기를 열지 않고 교체를 안내한다', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
await waitFor(() => {
expect(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2')).toBeTruthy();
});
fireEvent.click(screen.getByTestId('g7le-custom-asset-row-fonts/brand.woff2'));
await waitFor(() => {
expect(screen.queryByTestId('g7le-custom-assets-content')).toBeNull();
});
// 본문을 읽으러 가지 않는다 — 바이너리를 텍스트로 열면 저장 시 손상된다
const readCalls = fetchMock.mock.calls.filter(([url]) => String(url).includes('/content'));
expect(readCalls).toHaveLength(0);
});
/** @effects custom_asset_editor_save_invalidates_published_copy */
it('저장은 PUT content 로 나가고 성공 후 목록을 다시 읽는다', async () => {
fetchMock.mockImplementation((url: string, init?: RequestInit) => {
if (init?.method === 'PUT') {
return Promise.resolve(jsonResponse(200, { data: { path: 'new.css', size: 5 } }));
}
return Promise.resolve(jsonResponse(200, listBody));
});
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
await waitFor(() => {
expect(screen.getByTestId('g7le-custom-assets-path')).toBeTruthy();
});
fireEvent.change(screen.getByTestId('g7le-custom-assets-path'), {
target: { value: 'new.css' },
});
fireEvent.change(screen.getByTestId('g7le-custom-assets-content'), {
target: { value: 'body{}' },
});
fireEvent.click(screen.getByTestId('g7le-custom-assets-save'));
await waitFor(() => {
const put = fetchMock.mock.calls.find(([, init]) => (init as RequestInit)?.method === 'PUT');
expect(put).toBeTruthy();
expect(String(put?.[0])).toContain('/api/admin/extensions/template/sirsoft-basic/custom-assets/content');
expect(JSON.parse(String((put?.[1] as RequestInit).body))).toEqual({
path: 'new.css',
content: 'body{}',
});
});
// 저장 후 목록 재조회 — 새 파일이 목록에 나타나야 한다
await waitFor(() => {
const listCalls = fetchMock.mock.calls.filter(
([url, init]) => !(init as RequestInit)?.method && String(url).endsWith('/custom-assets'),
);
expect(listCalls.length).toBeGreaterThanOrEqual(2);
});
});
/**
* 대상은 템플릿뿐 아니라 활성 모듈·플러그인도 고를 수 있어야 한다.
*
* 같은 기능이 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없다.
*
* @effects custom_asset_manage_all_extension_types_parity
*/
it('대상 선택기에 활성 모듈·플러그인이 함께 오른다', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
const select = (await screen.findByTestId('g7le-custom-assets-target')) as HTMLSelectElement;
const values = Array.from(select.options).map((o) => o.value);
expect(values).toEqual([
'template:sirsoft-basic',
'module:sirsoft-page',
'plugin:sirsoft-gdpr',
]);
});
/** @effects custom_asset_manage_all_extension_types_parity */
it('대상을 바꾸면 그 확장의 경로로 다시 읽는다', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
const select = (await screen.findByTestId('g7le-custom-assets-target')) as HTMLSelectElement;
fireEvent.change(select, { target: { value: 'module:sirsoft-page' } });
await waitFor(() => {
const called = fetchMock.mock.calls.map(([url]) => String(url));
expect(
called.some((u) => u.includes('/api/admin/extensions/module/sirsoft-page/custom-assets')),
).toBe(true);
});
});
/**
* 대상 전환은 이전 확장의 선택·초안을 버려야 한다.
*
* 남겨 두면 A 확장에서 열어 둔 본문을 B 확장에 저장하게 되고, 경로가 유효하면 서버는
* 정상 200 으로 받아들인다 — 오류가 남지 않는 종류의 사고다.
*
* @effects custom_asset_manage_all_extension_types_parity
*/
it('대상을 바꾸면 선택과 초안을 버린다', async () => {
fetchMock.mockResolvedValue(jsonResponse(200, listBody));
render(<CustomAssetsModal templateIdentifier="sirsoft-basic" t={t} onClose={() => {}} />);
await waitFor(() => {
expect(screen.getByTestId('g7le-custom-asset-row-10-overrides.css')).toBeTruthy();
});
fireEvent.click(screen.getByTestId('g7le-custom-asset-row-10-overrides.css'));
await waitFor(() => {
expect((screen.getByTestId('g7le-custom-assets-path') as HTMLInputElement).readOnly).toBe(true);
});
fireEvent.change(screen.getByTestId('g7le-custom-assets-target'), {
target: { value: 'plugin:sirsoft-gdpr' },
});
await waitFor(() => {
const path = screen.getByTestId('g7le-custom-assets-path') as HTMLInputElement;
expect(path.readOnly).toBe(false);
expect(path.value).toBe('');
});
});
});
describe('EditorToolbar — 커스텀 자산 (D32·D33)', () => {
it('관리 버튼은 핸들러 미제공 시 disabled', () => {
render(wrapToolbar(<EditorToolbar />));
expect((screen.getByTestId('g7le-toolbar-custom-assets') as HTMLButtonElement).disabled).toBe(
true,
);
});
it('관리 버튼 클릭이 핸들러를 호출한다', () => {
const onManage = vi.fn();
render(wrapToolbar(<EditorToolbar onManageCustomAssets={onManage} />));
fireEvent.click(screen.getByTestId('g7le-toolbar-custom-assets'));
expect(onManage).toHaveBeenCalledTimes(1);
});
/**
* 상태 판정의 출처는 서버다.
*
* SPA 부팅이 주소를 다시 쓰면서 `?custom=off` 를 지우므로, URL 로 판정하면 자산은
* 꺼졌는데 버튼은 "켜져 있음" 으로 표시되고 되돌릴 방법이 화면에서 사라진다.
*
* @effects custom_assets_disabled_by_request_parameter
*/
it('주소에 파라미터가 없어도 서버가 껐다고 하면 꺼짐으로 표시한다', () => {
render(
wrapToolbar(<EditorToolbar onToggleCustomAssets={() => {}} customAssetsDisabled={true} />),
);
const button = screen.getByTestId('g7le-toolbar-toggle-custom-assets');
expect(window.location.search).not.toContain('custom=off');
expect(button.getAttribute('aria-pressed')).toBe('true');
expect(button.textContent).toContain('custom_assets_on');
});
/** @effects custom_assets_disabled_by_request_parameter */
it('토글이 현재 끔 상태를 문구와 aria-pressed 로 드러낸다', () => {
const onToggle = vi.fn();
const { rerender } = render(
wrapToolbar(<EditorToolbar onToggleCustomAssets={onToggle} customAssetsDisabled={false} />),
);
const button = () => screen.getByTestId('g7le-toolbar-toggle-custom-assets');
expect(button().getAttribute('aria-pressed')).toBe('false');
expect(button().getAttribute('data-custom-disabled')).toBe('false');
rerender(
wrapToolbar(<EditorToolbar onToggleCustomAssets={onToggle} customAssetsDisabled={true} />),
);
// 지금 화면이 평소와 다른 상태임이 보이지 않으면, 운영자가 "내 CSS 가 사라졌다" 를
// 새 결함으로 오인한다
expect(button().getAttribute('aria-pressed')).toBe('true');
expect(button().getAttribute('data-custom-disabled')).toBe('true');
fireEvent.click(button());
expect(onToggle).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,533 @@
/**
* CustomAssetsModal.tsx — 사용자 추가 에셋(`custom/`) 관리 모달
*
* 운영자가 확장의 `custom/` 디렉토리에 자기 CSS·JS 를 넣고 고치고, 그 CSS 가 참조할
* 폰트·이미지를 올린다. 종전에는 FTP 나 서버 셸이 유일한 경로였다 — 그 접근이 없는
* 운영자에게는 기능 자체가 없는 것과 같았다.
*
* 권한(`core.extensions.custom_assets.manage`)은 서버가 판정한다. 403 은 오류 문구가
* 아니라 **안내**로 바꿔 보여 준다 — "HTTP 403" 만 띄우면 운영자는 무엇이 부족한지
* 알 수 없다.
*
* 대상은 편집 중인 템플릿뿐 아니라 **활성 모듈·플러그인**도 고를 수 있다. 같은 기능이
* 확장 타입에 따라 화면에서 되고 안 되면 운영자는 그 이유를 알 수 없고, 모듈·플러그인
* `custom/` 은 그동안 FTP 말고 경로가 없었다.
*
* 편집기 코어 위젯이므로 `g7le-*` + 인라인 스타일만 쓴다(CSS 라이브러리 비종속).
* 자산이 깨진 상황에서도 이 화면만은 떠야 하기 때문이다.
*
* @since engine-v1.63.0
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
useCustomAssets,
type CustomAssetFile,
type CustomAssetTarget,
} from '../hooks/useCustomAssets';
export interface CustomAssetsModalProps {
/** 편집 대상 템플릿 식별자 — 대상 목록의 기본 선택 */
templateIdentifier: string;
/** 다국어 해석 함수 */
t: (key: string, params?: Record<string, string | number>) => string;
/** 모달 닫기 */
onClose: () => void;
}
const wrap: React.CSSProperties = {
display: 'flex',
flexDirection: 'column',
height: '100%',
minHeight: 0,
};
const header: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
gap: 8,
padding: '12px 16px',
borderBottom: '1px solid #e2e8f0',
background: '#f8fafc',
fontWeight: 600,
color: '#0f172a',
};
const closeBtn: React.CSSProperties = {
marginLeft: 'auto',
border: 'none',
background: 'transparent',
fontSize: 16,
color: '#64748b',
cursor: 'pointer',
outline: 'none',
};
const body: React.CSSProperties = {
flex: 1,
minHeight: 0,
display: 'flex',
};
const listPane: React.CSSProperties = {
width: 260,
flexShrink: 0,
borderRight: '1px solid #e2e8f0',
overflowY: 'auto',
padding: 8,
};
const editPane: React.CSSProperties = {
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
padding: 12,
gap: 8,
};
const rowBase: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
gap: 6,
width: '100%',
padding: '6px 8px',
borderRadius: 6,
borderWidth: 1,
borderStyle: 'solid',
borderColor: 'transparent',
backgroundColor: 'transparent',
fontSize: 12,
color: '#334155',
cursor: 'pointer',
textAlign: 'left',
};
const rowSelected: React.CSSProperties = {
...rowBase,
backgroundColor: '#eff6ff',
borderColor: '#bfdbfe',
color: '#1d4ed8',
fontWeight: 600,
};
const noticeBox: React.CSSProperties = {
margin: 16,
padding: 16,
borderRadius: 8,
border: '1px solid #fcd34d',
background: '#fffbeb',
color: '#92400e',
fontSize: 13,
lineHeight: 1.7,
};
const errorBar: React.CSSProperties = {
padding: '8px 12px',
borderRadius: 6,
border: '1px solid #fecaca',
background: '#fef2f2',
color: '#b91c1c',
fontSize: 12,
};
const textarea: React.CSSProperties = {
flex: 1,
minHeight: 220,
width: '100%',
boxSizing: 'border-box',
padding: 10,
borderRadius: 6,
borderWidth: 1,
borderStyle: 'solid',
borderColor: '#cbd5e1',
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
fontSize: 12,
lineHeight: 1.6,
resize: 'vertical',
};
const actionRow: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
gap: 8,
flexWrap: 'wrap',
};
const button: React.CSSProperties = {
padding: '6px 12px',
borderRadius: 6,
borderWidth: 1,
borderStyle: 'solid',
borderColor: '#cbd5e1',
backgroundColor: '#ffffff',
color: '#334155',
fontSize: 12,
cursor: 'pointer',
};
const primary: React.CSSProperties = {
...button,
backgroundColor: '#2563eb',
borderColor: '#2563eb',
color: '#ffffff',
fontWeight: 600,
};
const danger: React.CSSProperties = {
...button,
borderColor: '#fca5a5',
color: '#b91c1c',
};
const inputStyle: React.CSSProperties = {
...button,
cursor: 'text',
minWidth: 200,
};
const selectStyle: React.CSSProperties = {
...button,
cursor: 'pointer',
minWidth: 220,
};
/**
* 확장 표시 이름을 뽑습니다 (다국어 객체 또는 문자열).
*
* @param value display_name 값
* @param fallback 이름이 없을 때 쓸 식별자
* @returns 표시 이름
*/
function displayNameOf(value: unknown, fallback: string): string {
if (typeof value === 'string' && value !== '') return value;
if (value && typeof value === 'object') {
const map = value as Record<string, unknown>;
const locale = (window as any)?.G7Config?.locale ?? 'ko';
const picked = map[locale] ?? map.ko ?? map.en ?? Object.values(map)[0];
if (typeof picked === 'string' && picked !== '') return picked;
}
return fallback;
}
/**
* 관리 가능한 대상 목록을 만듭니다 — 편집 중인 템플릿 + 활성 모듈·플러그인.
*
* **활성** 확장만 싣는다. 자산 서빙이 활성 확장에만 응답하므로, 비활성 확장의 파일을
* 넣어 봐야 저장은 되는데 화면에는 영영 나타나지 않는다.
*
* @param templateIdentifier 편집 중인 템플릿 식별자
* @returns 대상 목록 (템플릿 → 모듈 → 플러그인)
*/
function buildTargets(
templateIdentifier: string,
): Array<CustomAssetTarget & { label: string }> {
const config = (typeof window !== 'undefined' ? (window as any).G7Config : null) ?? {};
const list: Array<CustomAssetTarget & { label: string }> = [
{ type: 'template', identifier: templateIdentifier, label: templateIdentifier },
];
for (const [type, rows] of [
['module', config.activeModules],
['plugin', config.activePlugins],
] as const) {
if (!Array.isArray(rows)) continue;
for (const row of rows) {
const identifier = typeof row?.identifier === 'string' ? row.identifier : '';
if (!identifier) continue;
list.push({
type,
identifier,
label: displayNameOf(row?.display_name, identifier),
});
}
}
return list;
}
/**
* 바이트를 읽기 쉬운 크기로 바꿉니다.
*
* @param bytes 바이트
* @returns 표시 문자열
*/
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function CustomAssetsModal(props: CustomAssetsModalProps): React.ReactElement {
const { templateIdentifier, t, onClose } = props;
const targets = useMemo(() => buildTargets(templateIdentifier), [templateIdentifier]);
const [targetKey, setTargetKey] = useState(`template:${templateIdentifier}`);
const target = useMemo(
() => targets.find((x) => `${x.type}:${x.identifier}` === targetKey) ?? targets[0],
[targets, targetKey],
);
const assets = useCustomAssets({ type: target.type, identifier: target.identifier });
const { reload } = assets;
const [selected, setSelected] = useState<CustomAssetFile | null>(null);
const [draft, setDraft] = useState('');
const [newPath, setNewPath] = useState('');
const [isBusy, setIsBusy] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
void reload();
}, [reload]);
// 대상이 바뀌면 이전 확장의 선택·초안을 버린다. 남겨 두면 A 확장에서 열어 둔 본문을
// B 확장에 저장하게 되고, 경로가 유효하면 서버는 정상 200 으로 받아들인다.
useEffect(() => {
setSelected(null);
setDraft('');
setNewPath('');
}, [targetKey]);
const openFile = useCallback(
async (file: CustomAssetFile) => {
setSelected(file);
if (!file.editable) {
setDraft('');
return;
}
setIsBusy(true);
const content = await assets.read(file.path);
setIsBusy(false);
setDraft(content ?? '');
},
[assets],
);
const handleSave = useCallback(async () => {
const path = selected?.path ?? newPath.trim();
if (!path) return;
setIsBusy(true);
const ok = await assets.save(path, draft);
setIsBusy(false);
if (ok && !selected) {
setNewPath('');
setSelected({
path,
name: path.split('/').pop() ?? path,
extension: (path.split('.').pop() ?? '').toLowerCase(),
size: draft.length,
modified_at: new Date().toISOString(),
editable: true,
loaded: true,
});
}
}, [assets, selected, newPath, draft]);
const handleDelete = useCallback(async () => {
if (!selected) return;
// 되돌릴 수 없는 조작이라 확인을 받는다. 편집기 코어 위젯이므로 모달 스택을
// 더 쌓지 않고 브라우저 확인을 쓴다(나가기·템플릿 전환과 같은 방식).
if (typeof window !== 'undefined' && !window.confirm(t('layout_editor.custom_assets.delete_confirm'))) {
return;
}
setIsBusy(true);
const ok = await assets.remove(selected.path);
setIsBusy(false);
if (ok) {
setSelected(null);
setDraft('');
}
}, [assets, selected, t]);
const handleUpload = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
setIsBusy(true);
await assets.upload(file);
setIsBusy(false);
// 같은 파일을 다시 고를 수 있도록 입력을 비운다 (change 이벤트가 재발화되지 않는다)
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
},
[assets],
);
return (
<div className="g7le-custom-assets" style={wrap} data-testid="g7le-custom-assets-modal">
<div style={header}>
<span>🎨 {t('layout_editor.custom_assets.title')}</span>
<select
value={targetKey}
onChange={(event) => setTargetKey(event.target.value)}
style={selectStyle}
aria-label={t('layout_editor.custom_assets.target_label')}
data-testid="g7le-custom-assets-target"
>
{targets.map((option) => (
<option key={`${option.type}:${option.identifier}`} value={`${option.type}:${option.identifier}`}>
{t(`layout_editor.custom_assets.type_${option.type}`)} · {option.label}
</option>
))}
</select>
<button
type="button"
style={closeBtn}
onClick={onClose}
aria-label={t('layout_editor.custom_assets.close')}
data-testid="g7le-custom-assets-close"
>
✕
</button>
</div>
{assets.forbidden ? (
<div style={noticeBox} data-testid="g7le-custom-assets-forbidden">
{t('layout_editor.custom_assets.forbidden')}
</div>
) : (
<div style={body}>
<div style={listPane} data-testid="g7le-custom-assets-list">
{assets.isLoading && assets.files.length === 0 ? (
<div style={{ padding: 12, color: '#94a3b8', fontSize: 12 }}>
{t('layout_editor.custom_assets.loading')}
</div>
) : null}
{!assets.isLoading && assets.files.length === 0 ? (
<div style={{ padding: 12, color: '#94a3b8', fontSize: 12 }}>
{t('layout_editor.custom_assets.empty')}
</div>
) : null}
{assets.files.map((file) => (
<button
key={file.path}
type="button"
style={selected?.path === file.path ? rowSelected : rowBase}
onClick={() => void openFile(file)}
data-testid={`g7le-custom-asset-row-${file.path}`}
data-loaded={file.loaded ? 'true' : 'false'}
>
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>
{file.path}
</span>
<span style={{ color: '#94a3b8', fontSize: 11 }}>{formatSize(file.size)}</span>
</button>
))}
</div>
<div style={editPane}>
{assets.error ? (
<div style={errorBar} data-testid="g7le-custom-assets-error">
{assets.error}
</div>
) : null}
<div style={actionRow}>
<input
type="text"
value={selected ? selected.path : newPath}
readOnly={!!selected}
onChange={(event) => setNewPath(event.target.value)}
placeholder={t('layout_editor.custom_assets.new_path_placeholder')}
style={inputStyle}
aria-label={t('layout_editor.custom_assets.path_label')}
data-testid="g7le-custom-assets-path"
/>
{selected ? (
<button
type="button"
style={button}
onClick={() => {
setSelected(null);
setDraft('');
}}
data-testid="g7le-custom-assets-new"
>
{t('layout_editor.custom_assets.new_file')}
</button>
) : null}
</div>
{selected && !selected.editable ? (
<div style={{ color: '#64748b', fontSize: 12, lineHeight: 1.7 }}>
{t('layout_editor.custom_assets.binary_hint', { extension: selected.extension })}
</div>
) : (
<textarea
value={draft}
onChange={(event) => setDraft(event.target.value)}
style={textarea}
spellCheck={false}
aria-label={t('layout_editor.custom_assets.content_label')}
data-testid="g7le-custom-assets-content"
/>
)}
<div style={actionRow}>
<button
type="button"
style={primary}
disabled={isBusy || (selected ? !selected.editable : newPath.trim() === '')}
onClick={() => void handleSave()}
data-testid="g7le-custom-assets-save"
>
{t('layout_editor.custom_assets.save')}
</button>
<button
type="button"
style={button}
disabled={isBusy}
onClick={() => fileInputRef.current?.click()}
data-testid="g7le-custom-assets-upload"
>
{t('layout_editor.custom_assets.upload')}
</button>
<input
ref={fileInputRef}
type="file"
style={{ display: 'none' }}
onChange={(event) => void handleUpload(event)}
data-testid="g7le-custom-assets-file-input"
/>
<button
type="button"
style={danger}
disabled={isBusy || !selected}
onClick={() => void handleDelete()}
data-testid="g7le-custom-assets-delete"
>
{t('layout_editor.custom_assets.delete')}
</button>
<span style={{ color: '#94a3b8', fontSize: 11 }}>
{t('layout_editor.custom_assets.apply_hint')}
</span>
</div>
</div>
</div>
)}
</div>
);
}
@@ -360,6 +360,23 @@ export interface EditorToolbarProps {
onPreview?: () => void | Promise<void>;
/** 버전 히스토리 클릭 — 현재 레이아웃 저장 버전 목록·복원 모달 */
onShowVersions?: () => void;
/**
* 사용자 추가 에셋(`custom/`) 적용 토글 — 탈출구(D33).
*
* 끄기는 `?custom=off` 를 붙여 페이지를 **다시 여는** 방식이다. DOM 에서 `<link>` 를
* 떼는 방식이 아닌 이유: 이미 실행된 custom JS 는 되돌릴 수 없어 절반만 꺼진다.
* 서버가 목록을 비우면 CSS·JS 가 애초에 페이지에 도달하지 않는다.
*/
onToggleCustomAssets?: () => void;
/** 현재 요청이 `?custom=off` 상태인지 (버튼 문구·상태 표시) */
customAssetsDisabled?: boolean;
/**
* 커스텀 자산 관리 모달 열기.
*
* 버튼을 권한으로 감추지 않는다 — 서버가 403 을 돌려주면 모달이 "무엇이 부족한지"를
* 문장으로 알린다. 보이지 않는 버튼은 권한이 없다는 사실조차 알려 주지 못한다.
*/
onManageCustomAssets?: () => void;
}
export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElement {
@@ -379,6 +396,9 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
templateVersion,
templateList,
onSwitchTemplate,
onToggleCustomAssets,
customAssetsDisabled = false,
onManageCustomAssets,
} = props;
// 저장 진행 상태 — onSave 가 Promise 면 완료까지 스피너 + disabled.
@@ -467,6 +487,15 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
fontWeight: 600,
};
// custom 자산이 꺼진 동안의 토글 강조 — 지금 화면이 평소와 다른 상태임을 알린다.
// 이 사실이 안 보이면 운영자가 "내 CSS 가 사라졌다" 를 새 결함으로 오인한다.
const activeToggleStyle: React.CSSProperties = {
backgroundColor: '#fef3c7',
borderColor: '#f59e0b',
color: '#92400e',
fontWeight: 600,
};
const ghostButton: React.CSSProperties = {
...buttonBase,
borderColor: '#e2e8f0',
@@ -694,6 +723,38 @@ export function EditorToolbar(props: EditorToolbarProps = {}): React.ReactElemen
>
🌐 {t('layout_editor.chrome.toolbar.translations')}
</ToolbarButton>
<ToolbarButton
data-testid="g7le-toolbar-custom-assets"
disabled={!onManageCustomAssets}
onClick={() => onManageCustomAssets?.()}
title={t('layout_editor.chrome.toolbar.custom_assets_hint')}
baseStyle={buttonBase}
hoverStyle={buttonHover}
>
🎨 {t('layout_editor.chrome.toolbar.custom_assets')}
</ToolbarButton>
<ToolbarButton
data-testid="g7le-toolbar-toggle-custom-assets"
data-custom-disabled={customAssetsDisabled ? 'true' : 'false'}
disabled={!onToggleCustomAssets}
onClick={() => onToggleCustomAssets?.()}
aria-pressed={customAssetsDisabled}
title={t(
customAssetsDisabled
? 'layout_editor.chrome.toolbar.custom_assets_on_hint'
: 'layout_editor.chrome.toolbar.custom_assets_off_hint'
)}
baseStyle={buttonBase}
hoverStyle={buttonHover}
style={customAssetsDisabled ? { ...buttonBase, ...activeToggleStyle } : undefined}
>
{customAssetsDisabled ? '👁' : '🚫'}{' '}
{t(
customAssetsDisabled
? 'layout_editor.chrome.toolbar.custom_assets_on'
: 'layout_editor.chrome.toolbar.custom_assets_off'
)}
</ToolbarButton>
<ToolbarButton
data-testid="g7le-toolbar-page-settings"
disabled={
@@ -0,0 +1,290 @@
/**
* useCustomAssets.ts — 사용자 추가 에셋(`custom/`) 조회·편집 hook
*
* 운영자가 자기 CSS·JS·폰트·이미지를 화면에서 직접 넣고 고칠 수 있게 하는 관리 API 를
* 감싼다. 종전에는 FTP 나 서버 셸이 유일한 경로였고, 그 접근이 없는 운영자에게는 기능
* 자체가 없는 것과 같았다.
*
* - GET /api/admin/extensions/{type}/{id}/custom-assets (목록 + 편집기 메타)
* - GET /api/admin/extensions/{type}/{id}/custom-assets/content (본문)
* - PUT /api/admin/extensions/{type}/{id}/custom-assets/content (본문 저장·생성)
* - POST /api/admin/extensions/{type}/{id}/custom-assets/upload (바이너리 업로드)
* - DELETE /api/admin/extensions/{type}/{id}/custom-assets (삭제)
*
* `{type}` 은 `module` | `plugin` | `template`. 세 타입이 한 엔드포인트를 공유하므로
* 이 훅도 타입을 인자로 받는다 — 타입별 훅을 세 벌 두면 그중 하나만 고쳐 놓는 상태가 된다.
*
* 권한(`core.extensions.custom_assets.manage`)은 서버가 판정한다. 403 은 오류가 아니라
* **상태**로 취급해 호출자가 안내 문구로 바꿀 수 있게 별도 플래그(`forbidden`)로 알린다 —
* "HTTP 403" 을 그대로 띄우면 운영자는 무엇이 부족한지 알 수 없다.
*
* @since engine-v1.63.0
*/
import { useCallback, useState } from 'react';
import { buildAuthHeaders } from '../utils/authToken';
/** 목록 항목 1건 */
export interface CustomAssetFile {
/** `custom/` 기준 상대 경로 */
path: string;
/** 파일명 */
name: string;
/** 소문자 확장자 */
extension: string;
/** 바이트 크기 */
size: number;
/** 최종 수정 시각 (ISO 8601) */
modified_at: string;
/** 편집기에서 본문을 열 수 있는지 */
editable: boolean;
/** 실제로 페이지에 실리는지 (규약 스캔·선언 파일 결과) */
loaded: boolean;
}
/** 목록 응답의 편집기 메타 */
export interface CustomAssetMeta {
editable_extensions: string[];
uploadable_extensions: string[];
max_text_bytes: number;
max_upload_bytes: number;
}
/** 훅 반환 */
export interface UseCustomAssetsResult {
files: CustomAssetFile[];
meta: CustomAssetMeta | null;
isLoading: boolean;
/** 권한 부족 — 오류 문구가 아니라 안내로 바꿔야 하는 상태 */
forbidden: boolean;
error: string | null;
reload: () => Promise<void>;
read: (path: string) => Promise<string | null>;
save: (path: string, content: string) => Promise<boolean>;
upload: (file: File, directory?: string) => Promise<boolean>;
remove: (path: string) => Promise<boolean>;
}
/** 관리 대상 확장 — 타입 + 식별자. */
export interface CustomAssetTarget {
type: 'module' | 'plugin' | 'template';
identifier: string;
}
/**
* 관리 API base URL 을 만듭니다.
*
* @param target 관리 대상 확장
* @returns base URL
*/
function baseUrl(target: CustomAssetTarget): string {
return `/api/admin/extensions/${encodeURIComponent(target.type)}/${encodeURIComponent(target.identifier)}/custom-assets`;
}
/**
* 응답 본문에서 사용자에게 보일 메시지를 뽑습니다.
*
* 서버가 다국어 키를 해석해 문장으로 내려주므로 그것을 그대로 쓴다. 없을 때만
* 상태 코드로 폴백한다 — 그 경우에도 "HTTP 500" 이 안내로서 최소한의 단서는 된다.
*
* @param body 파싱된 응답 본문
* @param status HTTP 상태 코드
* @returns 메시지
*/
function messageOf(body: unknown, status: number): string {
const message = (body as { message?: unknown })?.message;
return typeof message === 'string' && message !== '' ? message : `HTTP ${status}`;
}
/**
* 사용자 추가 에셋 관리 hook.
*
* @param target 관리 대상 확장 (타입 + 식별자)
* @returns 목록 상태 + 조작 함수
*/
export function useCustomAssets(target: CustomAssetTarget): UseCustomAssetsResult {
const [files, setFiles] = useState<CustomAssetFile[]>([]);
const [meta, setMeta] = useState<CustomAssetMeta | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [forbidden, setForbidden] = useState(false);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(async (): Promise<void> => {
setIsLoading(true);
setError(null);
try {
const response = await fetch(baseUrl(target), {
credentials: 'same-origin',
headers: buildAuthHeaders(),
});
const body = await response.json().catch(() => null);
if (response.status === 401 || response.status === 403) {
setForbidden(true);
setFiles([]);
return;
}
setForbidden(false);
if (!response.ok) {
setError(messageOf(body, response.status));
setFiles([]);
return;
}
const data = (body as { data?: Record<string, unknown> })?.data ?? {};
const list = data.files;
setFiles(Array.isArray(list) ? (list as CustomAssetFile[]) : []);
setMeta({
editable_extensions: (data.editable_extensions as string[]) ?? [],
uploadable_extensions: (data.uploadable_extensions as string[]) ?? [],
max_text_bytes: (data.max_text_bytes as number) ?? 0,
max_upload_bytes: (data.max_upload_bytes as number) ?? 0,
});
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'network error');
setFiles([]);
} finally {
setIsLoading(false);
}
}, [target.type, target.identifier]);
const read = useCallback(
async (path: string): Promise<string | null> => {
setError(null);
try {
const url = `${baseUrl(target)}/content?path=${encodeURIComponent(path)}`;
const response = await fetch(url, {
credentials: 'same-origin',
headers: buildAuthHeaders(),
});
const body = await response.json().catch(() => null);
if (!response.ok) {
setError(messageOf(body, response.status));
return null;
}
const content = (body as { data?: { content?: unknown } })?.data?.content;
return typeof content === 'string' ? content : '';
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'network error');
return null;
}
},
[target.type, target.identifier],
);
const save = useCallback(
async (path: string, content: string): Promise<boolean> => {
setError(null);
try {
const response = await fetch(`${baseUrl(target)}/content`, {
method: 'PUT',
credentials: 'same-origin',
headers: buildAuthHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ path, content }),
});
const body = await response.json().catch(() => null);
if (!response.ok) {
setError(messageOf(body, response.status));
return false;
}
await reload();
return true;
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'network error');
return false;
}
},
[target.type, target.identifier, reload],
);
const upload = useCallback(
async (file: File, directory?: string): Promise<boolean> => {
setError(null);
try {
const form = new FormData();
form.append('file', file);
if (directory) {
form.append('directory', directory);
}
// multipart 는 boundary 를 브라우저가 붙이므로 Content-Type 을 명시하지 않는다.
const response = await fetch(`${baseUrl(target)}/upload`, {
method: 'POST',
credentials: 'same-origin',
headers: buildAuthHeaders(),
body: form,
});
const body = await response.json().catch(() => null);
if (!response.ok) {
setError(messageOf(body, response.status));
return false;
}
await reload();
return true;
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'network error');
return false;
}
},
[target.type, target.identifier, reload],
);
const remove = useCallback(
async (path: string): Promise<boolean> => {
setError(null);
try {
const url = `${baseUrl(target)}?path=${encodeURIComponent(path)}`;
const response = await fetch(url, {
method: 'DELETE',
credentials: 'same-origin',
headers: buildAuthHeaders(),
});
const body = await response.json().catch(() => null);
if (!response.ok) {
setError(messageOf(body, response.status));
return false;
}
await reload();
return true;
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'network error');
return false;
}
},
[target.type, target.identifier, reload],
);
return { files, meta, isLoading, forbidden, error, reload, read, save, upload, remove };
}
@@ -357,3 +357,110 @@ function loadScriptOnce(url: string, attrs: Record<string, string>): Promise<voi
document.head.appendChild(script);
});
}
/**
* `<link rel="stylesheet">` 로드를 재시도하는 로더입니다.
*
* `loadScriptWithRetry` 와 동형이다 — 3시도(기본) · 지수 백오프 · **최종 실패 시 reject**.
* CSS 경로만 이 계층이 없어 실패가 통째로 무음이었다: `onerror` 를 아예 걸지 않거나
* `resolve()` 로 삼켜, 스타일이 붙지 않은 화면(아이콘 소실·본문 서식 붕괴)이 오류 없이
* 남았다. 아이콘만으로 조작하는 버튼이 있는 화면에서는 그것이 곧 조작 불능이다.
*
* `<link>` 의 `onerror` 도 사유를 주지 않으므로 모든 실패를 재시도 대상으로 본다.
* 재시도 전 기존 element 를 제거한다 — 남겨두면 실패한 `<link>` 가 누적되고, id 를
* 지정한 경우 다음 시도와 충돌한다.
*
* @param url 스타일시트 URL
* @param attrs link element 에 부여할 속성 (id, media, crossorigin 등)
* @param options 재시도 옵션
* @return Promise<void> 로드 성공 시 resolve
* @throws Error 모든 시도가 실패한 경우
* @since engine-v1.62.0
*/
export async function loadStylesheetWithRetry(
url: string,
attrs: Record<string, string> = {},
options: RetryOptions = {}
): Promise<void> {
const {
retries = DEFAULT_RETRIES,
baseDelayMs = DEFAULT_BASE_DELAY_MS,
maxDelayMs = DEFAULT_MAX_DELAY_MS,
label = url,
} = options;
const maxAttempts = retries + 1;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
let link: HTMLLinkElement | null = null;
try {
link = createStylesheetElement(url, attrs);
await loadStylesheetOnce(link);
return;
} catch (error) {
// 실패한 element 를 제거한다 (누적 방지 + 다음 시도의 id 충돌 방지)
link?.remove();
if (attrs.id) {
document.getElementById(attrs.id)?.remove();
}
if (isDocumentUnloading()) {
logger.warn(`Document unloading, aborting stylesheet retries: ${label}`);
throw error;
}
const isLastAttempt = attempt === maxAttempts - 1;
if (isLastAttempt) {
logger.warn(`All ${maxAttempts} stylesheet attempts failed: ${label}`);
throw error;
}
const waitMs = computeBackoffDelay(attempt, baseDelayMs, maxDelayMs);
logger.warn(
`Stylesheet load failed (attempt ${attempt + 1}/${maxAttempts}), retrying in ${waitMs}ms: ${label}`
);
await delay(waitMs);
}
}
}
/**
* `<link rel="stylesheet">` element 를 생성해 head 에 추가합니다.
*
* @param url 스타일시트 URL
* @param attrs link element 속성
* @return HTMLLinkElement 생성된 element
* @since engine-v1.62.0
*/
function createStylesheetElement(url: string, attrs: Record<string, string>): HTMLLinkElement {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
for (const [key, value] of Object.entries(attrs)) {
if (key === 'id') {
link.id = value;
} else {
link.setAttribute(key, value);
}
}
document.head.appendChild(link);
return link;
}
/**
* `<link>` 1회 로드를 시도합니다 (재시도 없음).
*
* @param link head 에 이미 추가된 link element
* @return Promise<void> 로드 성공 시 resolve, 실패 시 reject
* @since engine-v1.62.0
*/
function loadStylesheetOnce(link: HTMLLinkElement): Promise<void> {
return new Promise<void>((resolve, reject) => {
link.onload = () => resolve();
link.onerror = () => reject(new Error(`Failed to load stylesheet: ${link.href}`));
});
}
+4
View File
@@ -47,6 +47,10 @@
moduleAssets: @json($moduleAssets ?? []),
pluginAssets: @json($pluginAssets ?? []),
bundleUrls: @json($bundleUrls ?? null),
customAssets: @json($customAssets ?? []),
{{-- 이번 렌더가 `?custom=off` 로 자산을 껐는지. URL 은 SPA 부팅이 다시 쓰면서
쿼리를 잃을 수 있으므로, 화면은 URL 이 아니라 **서버가 실제로 한 일**을 본다. --}}
customAssetsDisabled: @json($customAssetsDisabled ?? false),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
trustedScriptHosts: @json($trustedScriptHosts ?? []),
+4
View File
@@ -47,6 +47,10 @@
moduleAssets: @json($moduleAssets ?? []),
pluginAssets: @json($pluginAssets ?? []),
bundleUrls: @json($bundleUrls ?? null),
customAssets: @json($customAssets ?? []),
{{-- 이번 렌더가 `?custom=off` 로 자산을 껐는지. URL 은 SPA 부팅이 다시 쓰면서
쿼리를 잃을 수 있으므로, 화면은 URL 이 아니라 **서버가 실제로 한 일**을 본다. --}}
customAssetsDisabled: @json($customAssetsDisabled ?? false),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
trustedScriptHosts: @json($trustedScriptHosts ?? []),
+2 -1
View File
@@ -534,7 +534,8 @@ if (isset($_GET['ajax_action'])) {
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ config('app.name', '그누보드7') }}</title>
<script src="https://cdn.tailwindcss.com"></script>
{{-- 스타일: 자체 빌드 CSS (종전 Tailwind Play CDN 대체 — 외부 도달 실패 시 화면이 무너졌다) --}}
<link rel="stylesheet" href="{{ asset('build/core/dev-dashboard.css') }}">
<style>
.card-hover { transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); }
.card-hover:hover { transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3); }
@@ -127,11 +127,12 @@
var version = match[1];
var rest = match[2].split('?')[0];
var templateAsset = rest.match(/^templates\/([^/]+)\/assets\/(.+)$/);
if (templateAsset) {
// 세 확장 타입이 같은 형태로 게시된다 (템플릿 dist/**, 모듈·플러그인 custom/**).
var extensionAsset = rest.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);
if (extensionAsset) {
// audit:allow asset-url-builder-required reason: 코어 번들 로드 전 인라인 복구기 —
// import 불가라 규칙 사본을 직접 조립한다. 드리프트는 assetUrlRecovery.test.ts 대조가 잠근다.
return '/api/templates/assets/' + templateAsset[1] + '/' + templateAsset[2] + '?v=' + version;
return '/api/' + extensionAsset[1] + '/assets/' + extensionAsset[2] + '/' + extensionAsset[3] + '?v=' + version;
}
var bundle = rest.match(/^bundles\/(modules|plugins)\.(js|css)$/);
@@ -4,6 +4,70 @@
$headLinks = \App\Support\TemplateExternals::headLinks($templateExternals);
$headScripts = \App\Support\TemplateExternals::scriptsForPosition($templateExternals, 'head');
@endphp
{{-- 자산 실패 신호 부트스트랩.
아래 externals 는 서버가 HTML 에 직접 심으므로 브라우저가 자산에 도달하지 못해도
자바스크립트에는 아무 신호가 오지 않는다. 실패는 "아이콘이 안 보인다" 로만 나타나고
자체 서버 로그에도 흔적이 남지 않는다. 각 태그의 onerror 가 여기로 들어온다.
엔진 번들보다 먼저 실행되므로 대기열에 쌓아 두고, 엔진이 뜨면 배너로 흘려보낸다. --}}
<script>
(function () {
var queue = window.__g7ExternalAssetFailures = window.__g7ExternalAssetFailures || [];
window.__g7RetryExternalAsset = function (el, url) {
return new Promise(function (resolve, reject) {
var fresh = document.createElement(el.tagName);
var bust = url + (url.indexOf('?') === -1 ? '?' : '&') + '_g7retry=' + Date.now();
if (el.tagName === 'LINK') {
fresh.rel = el.rel || 'stylesheet';
if (el.media) { fresh.media = el.media; }
if (el.crossOrigin) { fresh.crossOrigin = el.crossOrigin; }
fresh.href = bust;
} else {
if (el.crossOrigin) { fresh.crossOrigin = el.crossOrigin; }
fresh.src = bust;
}
fresh.onload = function () {
if (el.parentNode) { el.parentNode.removeChild(el); }
resolve();
};
fresh.onerror = function () {
if (fresh.parentNode) { fresh.parentNode.removeChild(fresh); }
reject(new Error('external asset retry failed'));
};
(el.parentNode || document.head).appendChild(fresh);
});
};
window.__g7ExternalAssetFailed = function (el, label) {
if (!el) { return; }
var url = el.tagName === 'LINK' ? el.href : el.src;
var id = 'template-external:' + url;
for (var i = 0; i < queue.length; i++) {
if (queue[i].id === id) { return; }
}
var entry = {
id: id,
label: label || url,
url: url,
retry: function () { return window.__g7RetryExternalAsset(el, url); }
};
queue.push(entry);
if (typeof window.__g7ExternalAssetSink === 'function') {
window.__g7ExternalAssetSink(entry);
}
};
})();
</script>
@foreach($resourceHints as $external)
<link{!! \App\Support\TemplateExternals::renderAttributes(\App\Support\TemplateExternals::linkAttributes($external)) !!}>
@endforeach