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:
1 parent
72f2e94c1a
commit
3945b6f1b3
1042 files changed
+107435
-947
No files matched your search
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user