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
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user