diff --git a/.env.example b/.env.example index ad1164be..d0848527 100644 --- a/.env.example +++ b/.env.example @@ -3,7 +3,7 @@ APP_ENV=production APP_KEY= APP_DEBUG=false APP_URL=http://localhost -APP_VERSION=7.0.1 +APP_VERSION=7.0.2 APP_LOCALE=ko APP_FALLBACK_LOCALE=ko diff --git a/.env.testing.example b/.env.testing.example index 889ac45f..4df97e96 100644 --- a/.env.testing.example +++ b/.env.testing.example @@ -3,7 +3,7 @@ APP_ENV=testing APP_KEY= APP_DEBUG=false APP_URL=http://localhost -APP_VERSION=7.0.1 +APP_VERSION=7.0.2 APP_LOCALE=ko APP_FALLBACK_LOCALE=ko diff --git a/.gitignore b/.gitignore index ee76dad5..b2a79076 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,9 @@ node_modules/ # Settings JSON files (환경별 설정) /storage/app/settings/ +# 확장 프론트엔드 병합 번들 캐시 (version-in-path, 런타임 생성) +/storage/app/ext-bundles/ + # Bootstrap cache (auto-generated) /bootstrap/cache/* !/bootstrap/cache/.gitkeep diff --git a/AGENTS.md b/AGENTS.md index 98717a21..4ffdec6a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -788,6 +788,18 @@ php artisan plugin:update sirsoft-payment --force lazy 번들(편집기/devtools)이 코어 런타임(DynamicRenderer·엔진 싱글톤·React Context·DevTools 코어)을 재사용할 때는 재번들하지 않고 `window.G7Core.__runtime` 을 빌려 쓴다 — React/컨텍스트/싱글톤 인스턴스 동일성이 강제되기 때문(사본이 둘이면 "Invalid hook call"·컨텍스트 미매칭). 메인 번들이 `G7CoreGlobals` 에서 공유 대상을 `G7Core.__runtime` 에 노출하고, lazy 번들 vite config 는 React 4종(`react`/`react-dom`/`react-dom/client`/`react/jsx-runtime`)을 external→window 로, 코어 런타임 모듈을 `resolveId` 플러그인으로 `__runtime-shims/` 로 치환한다. +### 확장 번들 병합 (서버측 concat) + +활성 모듈/플러그인의 프론트엔드 IIFE JS·CSS 는 타입별로 서버에서 하나의 번들로 병합해 서빙한다(`/api/{modules,plugins}/bundle.{js,css}?v={version}`). `ExtensionBundleService` 가 정렬·필터·concat·캐시를 전담하고, 프론트는 `window.G7Config.bundleUrls` 를 읽어 모듈 번들 → 플러그인 번들 순으로 로드한다. 병합 규율: + +- priority 순서는 선언형 — 실행 순서는 오직 manifest `loading.priority` 오름차순(`uasort`). 특정 확장 이름을 지목하는 분기를 두지 않는다. +- IIFE 사이는 `\n;\n`(JS)/`\n`(CSS) 로 잇는다. 미사용 시 ASI 경계가 깨져 번들 전체 파싱 에러가 난다. +- 소스맵은 prod strip, dev 는 개별 에셋 서빙 절대 URL 로 rewrite. 개별 에셋 서빙 라우트(`*.map` 포함)는 존치한다. +- 번들 URL 은 반드시 same-origin(`/api/...`). 외부 origin/CDN·protocol-relative 는 gdpr preblocker 에 자기 차단된다. +- 확장 에셋 절대경로는 `getBuiltAssetAbsolutePaths()`(=`getModulePath()`/`getPluginPath()`) 만 쓴다. `base_path("modules"|"plugins")` 직접 조립은 `_bundled` 경로 오해석 → 빈 번들. +- concat 루프는 확장별 try/catch — 실패 확장만 skip 하고 나머지 병합을 지속한다. +- 번들 파일명에 확장 캐시 버전을 포함(`{type}.{version}.{js,css}`). 조합 변경 시 version bump → 새 파일명 → 자동 재생성. 구파일 GC 는 `ext-bundles:cleanup` + `{module,plugin,template}:cache-clear` 가 담당한다. prod 은 version-in-path 디스크 캐시, 비프로덕션은 매 요청 concat. + ### 빌드 명령어 (Artisan) ```bash diff --git a/CHANGELOG.md b/CHANGELOG.md index 05784da4..809f4247 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [7.0.2] - 2026-07-05 + +### Added + +- 설치된 모듈·플러그인이 늘어날수록 화면마다 개별로 내려받던 확장 스크립트·스타일 요청을 종류별로 하나로 묶어 내려받도록 개선해, 확장이 많은 사이트의 초기 로딩 요청 수를 크게 줄였습니다. 확장을 설치·활성화·비활성화하면 묶음이 자동으로 다시 만들어져 항상 현재 활성 상태와 일치합니다. + +### Changed + +- 화면·데이터를 내려받을 때의 전송 용량을 줄여 초기 로딩과 페이지 이동 속도를 개선했습니다. + - 모듈·플러그인의 묶음 스크립트·스타일이 지금까지 압축 없이 전송되던 것을 압축 전송하도록 바꿔, 확장이 많은 사이트에서 첫 화면에 받는 용량을 크게 줄였습니다. + - 한글 등 다국어 텍스트가 응답에 불필요하게 부풀려 담기던 것을 원래 형태 그대로 담도록 바꿔, 특히 다국어 번역 데이터의 전송 용량을 줄였습니다. + - 화면을 그리는 데 쓰이지 않는 개발용 설명 주석을 화면 정보 응답에서 빼도록 해 응답 용량을 추가로 줄였습니다. + +### Fixed + +- 코어 업데이트 시 레이아웃 편집기·개발자 진단도구 번들의 빌드 설정 파일이 갱신 대상에서 누락되던 문제를 수정했습니다. 이제 코어를 업데이트하면 이 파일들도 최신 내용으로 반영됩니다. + ## [7.0.1] - 2026-07-03 ### Changed diff --git a/INSTALL.md b/INSTALL.md index dc5e17d6..4c4d2f2b 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -246,7 +246,7 @@ unzip g7-release.zip # 압축 해제 결과 확인 — 루트 디렉토리가 g7이 아니면 이름 변경 ls -la -# (필요 시) mv g7-7.0.1 g7 +# (필요 시) mv g7-7.0.2 g7 # ZIP 파일 정리 (선택) rm g7-release.zip diff --git a/README.md b/README.md index c21b4c51..8514de61 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@
-
+
diff --git a/app/Console/Commands/CleanupExtensionBundlesCommand.php b/app/Console/Commands/CleanupExtensionBundlesCommand.php
new file mode 100644
index 00000000..cf1ac59b
--- /dev/null
+++ b/app/Console/Commands/CleanupExtensionBundlesCommand.php
@@ -0,0 +1,43 @@
+getCurrentVersion();
+ $deleted = $service->cleanupStaleBundles($currentVersion);
+
+ $this->info("오래된 확장 번들 {$deleted}건이 삭제되었습니다. (현재 version: {$currentVersion})");
+
+ return self::SUCCESS;
+ }
+}
diff --git a/app/Console/Commands/Module/ClearModuleCacheCommand.php b/app/Console/Commands/Module/ClearModuleCacheCommand.php
index 1fad57b9..6c2d5362 100644
--- a/app/Console/Commands/Module/ClearModuleCacheCommand.php
+++ b/app/Console/Commands/Module/ClearModuleCacheCommand.php
@@ -5,6 +5,7 @@ namespace App\Console\Commands\Module;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\ModuleRepositoryInterface;
use App\Extension\ModuleManager;
+use App\Services\ExtensionBundleService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
@@ -27,7 +28,8 @@ class ClearModuleCacheCommand extends Command
public function __construct(
private ModuleManager $moduleManager,
private ModuleRepositoryInterface $moduleRepository,
- private CacheInterface $cache
+ private CacheInterface $cache,
+ private ExtensionBundleService $bundleService
) {
parent::__construct();
}
@@ -86,6 +88,9 @@ class ClearModuleCacheCommand extends Command
$clearedCount += $this->clearModuleCache($module->getIdentifier());
}
+ // 모듈 프론트엔드 병합 번들 파일 삭제 (캐시 키 forget 만으로는 미삭제)
+ $clearedCount += $this->bundleService->clearBundles('module');
+
$this->info('✅ '.__('modules.commands.cache_clear.success_all', ['count' => $clearedCount]));
}
diff --git a/app/Console/Commands/Plugin/ClearPluginCacheCommand.php b/app/Console/Commands/Plugin/ClearPluginCacheCommand.php
index 1fd77bb3..0dd0aa42 100644
--- a/app/Console/Commands/Plugin/ClearPluginCacheCommand.php
+++ b/app/Console/Commands/Plugin/ClearPluginCacheCommand.php
@@ -5,6 +5,7 @@ namespace App\Console\Commands\Plugin;
use App\Contracts\Extension\CacheInterface;
use App\Contracts\Repositories\PluginRepositoryInterface;
use App\Extension\PluginManager;
+use App\Services\ExtensionBundleService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
@@ -27,7 +28,8 @@ class ClearPluginCacheCommand extends Command
public function __construct(
private PluginManager $pluginManager,
private PluginRepositoryInterface $pluginRepository,
- private CacheInterface $cache
+ private CacheInterface $cache,
+ private ExtensionBundleService $bundleService
) {
parent::__construct();
}
@@ -86,6 +88,9 @@ class ClearPluginCacheCommand extends Command
$clearedCount += $this->clearPluginCache($plugin->getIdentifier());
}
+ // 플러그인 프론트엔드 병합 번들 파일 삭제 (캐시 키 forget 만으로는 미삭제)
+ $clearedCount += $this->bundleService->clearBundles('plugin');
+
$this->info('✅ '.__('plugins.commands.cache_clear.success_all', ['count' => $clearedCount]));
}
diff --git a/app/Console/Commands/Template/ClearTemplateCacheCommand.php b/app/Console/Commands/Template/ClearTemplateCacheCommand.php
index 8c8a8632..ca13ec43 100644
--- a/app/Console/Commands/Template/ClearTemplateCacheCommand.php
+++ b/app/Console/Commands/Template/ClearTemplateCacheCommand.php
@@ -6,6 +6,7 @@ use App\Contracts\Extension\CacheInterface;
use App\Extension\TemplateManager;
use App\Models\Template;
use App\Models\TemplateLayout;
+use App\Services\ExtensionBundleService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
@@ -27,7 +28,8 @@ class ClearTemplateCacheCommand extends Command
*/
public function __construct(
private TemplateManager $templateManager,
- private CacheInterface $cache
+ private CacheInterface $cache,
+ private ExtensionBundleService $bundleService
) {
parent::__construct();
}
@@ -153,6 +155,9 @@ class ClearTemplateCacheCommand extends Command
$this->cache->forget('templates.active.user');
$clearedCount += 2;
+ // 5. 확장 프론트엔드 병합 번들 파일 전체 삭제 (템플릿 캐시 정리는 페이지 전면 갱신)
+ $clearedCount += $this->bundleService->clearBundles();
+
$this->info('✅ '.__('templates.commands.cache_clear.success_all', [
'count' => $clearedCount,
]));
diff --git a/app/Extension/AbstractModule.php b/app/Extension/AbstractModule.php
index 8a72e698..c7a3f532 100644
--- a/app/Extension/AbstractModule.php
+++ b/app/Extension/AbstractModule.php
@@ -1190,6 +1190,29 @@ abstract class AbstractModule implements CacheableExtensionInterface, ModuleInte
return $result;
}
+ /**
+ * 빌드된 에셋의 절대 파일 경로를 반환합니다.
+ *
+ * `getBuiltAssetPaths()` 는 module.json 의 상대 output 경로를 돌려주므로
+ * 파일을 실제로 읽으려면 모듈 루트(`getModulePath()`: 활성 dir 또는 `_bundled`
+ * 실제 위치)를 앞에 붙여야 한다. 서버측 번들 병합(ExtensionBundleService)이
+ * `getAssetFilePath()` 의 `base_path("modules/{id}/...")` 하드코딩을 복제하지
+ * 않고 `_bundled` 확장에서도 정확한 경로를 얻도록 이 게터를 SSoT 로 쓴다.
+ *
+ * @return array 빌드된 에셋 절대 경로 배열 ['js' => '...', 'css' => '...']
+ */
+ public function getBuiltAssetAbsolutePaths(): array
+ {
+ $relative = $this->getBuiltAssetPaths();
+ $result = [];
+
+ foreach ($relative as $kind => $output) {
+ $result[$kind] = $this->getModulePath().'/'.$output;
+ }
+
+ return $result;
+ }
+
/**
* 모듈 스토리지 드라이버 인스턴스 반환
*
diff --git a/app/Extension/AbstractPlugin.php b/app/Extension/AbstractPlugin.php
index 5dd4ad10..1e76a1b8 100644
--- a/app/Extension/AbstractPlugin.php
+++ b/app/Extension/AbstractPlugin.php
@@ -1011,6 +1011,30 @@ abstract class AbstractPlugin implements CacheableExtensionInterface, PluginInte
return $result;
}
+ /**
+ * 빌드된 에셋의 절대 파일 경로를 반환합니다.
+ *
+ * `getBuiltAssetPaths()` 는 plugin.json 의 상대 output 경로를 돌려주므로
+ * 파일을 실제로 읽으려면 플러그인 루트(`getPluginPath()`: 활성 dir 또는
+ * `_bundled` 실제 위치)를 앞에 붙여야 한다. 서버측 번들 병합
+ * (ExtensionBundleService)이 `getAssetFilePath()` 의
+ * `base_path("plugins/{id}/...")` 하드코딩을 복제하지 않고 `_bundled`
+ * 확장에서도 정확한 경로를 얻도록 이 게터를 SSoT 로 쓴다.
+ *
+ * @return array 빌드된 에셋 절대 경로 배열 ['js' => '...', 'css' => '...']
+ */
+ public function getBuiltAssetAbsolutePaths(): array
+ {
+ $relative = $this->getBuiltAssetPaths();
+ $result = [];
+
+ foreach ($relative as $kind => $output) {
+ $result[$kind] = $this->getPluginPath().'/'.$output;
+ }
+
+ return $result;
+ }
+
/**
* 플러그인이 설정 페이지를 가지고 있는지 확인합니다.
*
diff --git a/app/Helpers/ResponseHelper.php b/app/Helpers/ResponseHelper.php
index e7114513..f83a3ea6 100644
--- a/app/Helpers/ResponseHelper.php
+++ b/app/Helpers/ResponseHelper.php
@@ -9,14 +9,23 @@ use Illuminate\Support\Facades\App;
class ResponseHelper
{
+ /**
+ * JSON 응답 인코딩 옵션.
+ *
+ * JSON_UNESCAPED_UNICODE: 한글 등 멀티바이트 문자를 `\uXXXX` (6바이트) 로
+ * 이스케이프하지 않고 raw UTF-8 (한글 3바이트) 로 직렬화하여 응답 크기를 줄인다.
+ * 특히 다국어 팩(lang) 응답에서 전송량 절감 효과가 크다.
+ */
+ public const JSON_ENCODE_OPTIONS = JSON_UNESCAPED_UNICODE;
+
/**
* 성공 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키 (기본값: 'messages.success')
- * @param mixed $data 응답 데이터
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 메시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 메시지 키 (기본값: 'messages.success')
+ * @param mixed $data 응답 데이터
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 메시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function success(
@@ -29,18 +38,18 @@ class ResponseHelper
return response()->json([
'success' => true,
'message' => self::trans($messageKey, $messageParams, $domain),
- 'data' => $data
- ], $statusCode);
+ 'data' => $data,
+ ], $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 실패 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키 (기본값: 'messages.failed')
- * @param int $statusCode HTTP 상태 코드 (기본값: 400)
- * @param mixed $errors 오류 정보
- * @param array $messageParams 메시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 메시지 키 (기본값: 'messages.failed')
+ * @param int $statusCode HTTP 상태 코드 (기본값: 400)
+ * @param mixed $errors 오류 정보
+ * @param array $messageParams 메시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function error(
@@ -59,28 +68,28 @@ class ResponseHelper
if (config('app.debug')) {
// messageParams에 이미 에러 메시지가 포함된 경우 중복 방지
if (empty($messageParams)) {
- $response['message'] .= ': ' . $errors->getMessage();
+ $response['message'] .= ': '.$errors->getMessage();
}
$response['debug'] = self::formatException($errors);
}
} elseif ($errors !== null) {
- if ($statusCode >= 500 && is_string($errors) && !config('app.debug')) {
+ if ($statusCode >= 500 && is_string($errors) && ! config('app.debug')) {
// 프로덕션 500+ 에러의 string errors 차단 (내부 예외 메시지 노출 방지)
} else {
$response['errors'] = $errors;
}
}
- return response()->json($response, $statusCode);
+ return response()->json($response, $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 입력 검증 실패 응답을 생성합니다.
*
- * @param mixed $errors 검증 오류 정보
- * @param string $messageKey 메시지 키 (기본값: 'messages.validation_failed')
- * @param array $messageParams 메시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param mixed $errors 검증 오류 정보
+ * @param string $messageKey 메시지 키 (기본값: 'messages.validation_failed')
+ * @param array $messageParams 메시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 422 상태 코드를 가진 JSON 응답
*/
public static function validationError(
@@ -92,16 +101,16 @@ class ResponseHelper
return response()->json([
'success' => false,
'message' => self::trans($messageKey, $messageParams, $domain),
- 'errors' => $errors
- ], 422);
+ 'errors' => $errors,
+ ], 422, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 인증 실패 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키 (기본값: 'messages.unauthorized')
- * @param array $messageParams 메시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 메시지 키 (기본값: 'messages.unauthorized')
+ * @param array $messageParams 메시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 401 상태 코드를 가진 JSON 응답
*/
public static function unauthorized(
@@ -111,16 +120,16 @@ class ResponseHelper
): JsonResponse {
return response()->json([
'success' => false,
- 'message' => self::trans($messageKey, $messageParams, $domain)
- ], 401);
+ 'message' => self::trans($messageKey, $messageParams, $domain),
+ ], 401, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 권한 부족 응답을 생성합니다.
*
- * @param string $messageKey 멤시지 키 (기본값: 'messages.forbidden')
- * @param array $messageParams 멤시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 멤시지 키 (기본값: 'messages.forbidden')
+ * @param array $messageParams 멤시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 403 상태 코드를 가진 JSON 응답
*/
public static function forbidden(
@@ -130,16 +139,16 @@ class ResponseHelper
): JsonResponse {
return response()->json([
'success' => false,
- 'message' => self::trans($messageKey, $messageParams, $domain)
- ], 403);
+ 'message' => self::trans($messageKey, $messageParams, $domain),
+ ], 403, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 리소스를 찾을 수 없음 응답을 생성합니다.
*
- * @param string $messageKey 멤시지 키 (기본값: 'messages.not_found')
- * @param array $messageParams 멤시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 멤시지 키 (기본값: 'messages.not_found')
+ * @param array $messageParams 멤시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 404 상태 코드를 가진 JSON 응답
*/
public static function notFound(
@@ -149,17 +158,17 @@ class ResponseHelper
): JsonResponse {
return response()->json([
'success' => false,
- 'message' => self::trans($messageKey, $messageParams, $domain)
- ], 404);
+ 'message' => self::trans($messageKey, $messageParams, $domain),
+ ], 404, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 서버 내부 오류 응답을 생성합니다.
*
- * @param string $messageKey 멤시지 키 (기본값: 'messages.error_occurred')
- * @param mixed $error 오류 정보 (디버그 모드에서만 표시)
- * @param array $messageParams 멤시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 멤시지 키 (기본값: 'messages.error_occurred')
+ * @param mixed $error 오류 정보 (디버그 모드에서만 표시)
+ * @param array $messageParams 멤시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 500 상태 코드를 가진 JSON 응답
*/
public static function serverError(
@@ -175,22 +184,22 @@ class ResponseHelper
if ($error instanceof \Throwable) {
if (config('app.debug')) {
- $response['message'] .= ': ' . $error->getMessage();
+ $response['message'] .= ': '.$error->getMessage();
$response['debug'] = self::formatException($error);
}
} elseif ($error !== null && config('app.debug')) {
$response['error'] = $error;
}
- return response()->json($response, 500);
+ return response()->json($response, 500, [], self::JSON_ENCODE_OPTIONS);
}
/**
* 다국어 메시지를 변환합니다.
*
- * @param string $key 번역 키
- * @param array $params 번역 매개변수
- * @param string $domain 번역 도메인
+ * @param string $key 번역 키
+ * @param array $params 번역 매개변수
+ * @param string $domain 번역 도메인
* @return string 번역된 메시지
*/
private static function trans(
@@ -199,10 +208,10 @@ class ResponseHelper
string $domain = 'core'
): string {
$locale = self::getUserLocale();
-
+
// 도메인별로 다른 경로에서 번역 파일 로드
$translationKey = $domain === 'core' ? $key : "{$domain}::{$key}";
-
+
return __($translationKey, $params, $locale);
}
@@ -225,7 +234,7 @@ class ResponseHelper
/**
* 예외 정보를 디버그용 배열로 변환합니다.
*
- * @param \Throwable $e 예외 인스턴스
+ * @param \Throwable $e 예외 인스턴스
* @return array 디버그 정보 배열
*/
private static function formatException(\Throwable $e): array
@@ -238,7 +247,7 @@ class ResponseHelper
'trace' => collect($e->getTrace())->take(10)->map(fn ($frame) => [
'file' => $frame['file'] ?? null,
'line' => $frame['line'] ?? null,
- 'function' => ($frame['class'] ?? '') . ($frame['type'] ?? '') . ($frame['function'] ?? ''),
+ 'function' => ($frame['class'] ?? '').($frame['type'] ?? '').($frame['function'] ?? ''),
])->toArray(),
];
}
@@ -246,11 +255,11 @@ class ResponseHelper
/**
* 모듈별 성공 응답을 생성합니다.
*
- * @param string $module 모듈명
- * @param string $messageKey 멤시지 키
- * @param mixed $data 응답 데이터
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 멤시지 매개변수
+ * @param string $module 모듈명
+ * @param string $messageKey 멤시지 키
+ * @param mixed $data 응답 데이터
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleSuccess(
@@ -266,11 +275,11 @@ class ResponseHelper
/**
* 모듈별 실패 응답을 생성합니다.
*
- * @param string $module 모듈명
- * @param string $messageKey 멤시지 키
- * @param int $statusCode HTTP 상태 코드 (기본값: 400)
- * @param mixed $errors 오류 정보
- * @param array $messageParams 멤시지 매개변수
+ * @param string $module 모듈명
+ * @param string $messageKey 멤시지 키
+ * @param int $statusCode HTTP 상태 코드 (기본값: 400)
+ * @param mixed $errors 오류 정보
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleError(
@@ -286,11 +295,11 @@ class ResponseHelper
/**
* 플러그인별 성공 응답을 생성합니다.
*
- * @param string $plugin 플러그인명
- * @param string $messageKey 멤시지 키
- * @param mixed $data 응답 데이터
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 멤시지 매개변수
+ * @param string $plugin 플러그인명
+ * @param string $messageKey 멤시지 키
+ * @param mixed $data 응답 데이터
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginSuccess(
@@ -306,11 +315,11 @@ class ResponseHelper
/**
* 플러그인별 실패 응답을 생성합니다.
*
- * @param string $plugin 플러그인명
- * @param string $messageKey 멤시지 키
- * @param int $statusCode HTTP 상태 코드 (기본값: 400)
- * @param mixed $errors 오류 정보
- * @param array $messageParams 멤시지 매개변수
+ * @param string $plugin 플러그인명
+ * @param string $messageKey 멤시지 키
+ * @param int $statusCode HTTP 상태 코드 (기본값: 400)
+ * @param mixed $errors 오류 정보
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginError(
@@ -326,11 +335,11 @@ class ResponseHelper
/**
* JSON Resource를 사용한 성공 응답을 생성합니다.
*
- * @param string $messageKey 멤시지 키 (기본값: 'messages.success')
- * @param JsonResource|ResourceCollection|null $resource JSON 리소스
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 멤시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 멤시지 키 (기본값: 'messages.success')
+ * @param JsonResource|ResourceCollection|null $resource JSON 리소스
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 멤시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse JSON 응답
*/
public static function successWithResource(
@@ -341,22 +350,22 @@ class ResponseHelper
string $domain = 'core'
): JsonResponse {
$data = $resource ? $resource->resolve() : null;
-
+
return response()->json([
'success' => true,
'message' => self::trans($messageKey, $messageParams, $domain),
- 'data' => $data
- ], $statusCode);
+ 'data' => $data,
+ ], $statusCode, [], self::JSON_ENCODE_OPTIONS);
}
/**
* JSON Resource를 사용한 모듈 성공 응답을 생성합니다.
*
- * @param string $module 모듈명
- * @param string $messageKey 멤시지 키
- * @param JsonResource|ResourceCollection|null $resource JSON 리소스
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 멤시지 매개변수
+ * @param string $module 모듈명
+ * @param string $messageKey 멤시지 키
+ * @param JsonResource|ResourceCollection|null $resource JSON 리소스
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function moduleSuccessWithResource(
@@ -372,11 +381,11 @@ class ResponseHelper
/**
* JSON Resource를 사용한 플러그인 성공 응답을 생성합니다.
*
- * @param string $plugin 플러그인명
- * @param string $messageKey 멤시지 키
- * @param JsonResource|ResourceCollection|null $resource JSON 리소스
- * @param int $statusCode HTTP 상태 코드 (기본값: 200)
- * @param array $messageParams 멤시지 매개변수
+ * @param string $plugin 플러그인명
+ * @param string $messageKey 멤시지 키
+ * @param JsonResource|ResourceCollection|null $resource JSON 리소스
+ * @param int $statusCode HTTP 상태 코드 (기본값: 200)
+ * @param array $messageParams 멤시지 매개변수
* @return JsonResponse JSON 응답
*/
public static function pluginSuccessWithResource(
@@ -392,21 +401,21 @@ class ResponseHelper
/**
* 페이지네이션된 리소스 응답을 생성합니다.
*
- * @param string $messageKey 멤시지 키 (기본값: 'messages.success')
- * @param ResourceCollection|null $collection 페이지네이션된 리소스 컬렉션
- * @param array $messageParams 멤시지 매개변수
- * @param string $domain 번역 도메인 (기본값: 'core')
+ * @param string $messageKey 멤시지 키 (기본값: 'messages.success')
+ * @param ResourceCollection|null $collection 페이지네이션된 리소스 컬렉션
+ * @param array $messageParams 멤시지 매개변수
+ * @param string $domain 번역 도메인 (기본값: 'core')
* @return JsonResponse 페이지네이션 메타 데이터를 포함한 JSON 응답
*/
public static function successWithPagination(
string $messageKey = 'messages.success',
- ResourceCollection|null $collection = null,
+ ?ResourceCollection $collection = null,
array $messageParams = [],
string $domain = 'core'
): JsonResponse {
$response = [
'success' => true,
- 'message' => self::trans($messageKey, $messageParams, $domain)
+ 'message' => self::trans($messageKey, $messageParams, $domain),
];
if ($collection) {
@@ -424,7 +433,7 @@ class ResponseHelper
$response['links'] = $paginationData['links'] ?? null;
}
- return response()->json($response);
+ return response()->json($response, 200, [], self::JSON_ENCODE_OPTIONS);
}
/**
@@ -444,6 +453,6 @@ class ResponseHelper
'error_code' => 'identity_verification_required',
'message' => self::trans('identity.errors.verification_required', [], 'core'),
'verification' => $verification,
- ], 428);
+ ], 428, [], self::JSON_ENCODE_OPTIONS);
}
}
diff --git a/app/Http/Controllers/Api/Base/BaseApiController.php b/app/Http/Controllers/Api/Base/BaseApiController.php
index 84e57b35..c8f4e2f5 100644
--- a/app/Http/Controllers/Api/Base/BaseApiController.php
+++ b/app/Http/Controllers/Api/Base/BaseApiController.php
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Base;
use App\Helpers\ResponseHelper;
use App\Http\Controllers\Controller;
+use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
@@ -20,11 +21,11 @@ abstract class BaseApiController extends Controller
/**
* 성공 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param mixed $data 응답 데이터
- * @param int $statusCode HTTP 상태 코드
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param mixed $data 응답 데이터
+ * @param int $statusCode HTTP 상태 코드
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function success(
string $messageKey = 'common.success',
@@ -38,11 +39,11 @@ abstract class BaseApiController extends Controller
/**
* 실패 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param int $statusCode HTTP 상태 코드
- * @param mixed $errors 오류 정보
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param int $statusCode HTTP 상태 코드
+ * @param mixed $errors 오류 정보
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function error(
string $messageKey = 'common.failed',
@@ -56,11 +57,11 @@ abstract class BaseApiController extends Controller
/**
* 리소스와 함께 성공 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param mixed $resource JSON 리소스
- * @param int $statusCode HTTP 상태 코드
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param mixed $resource JSON 리소스
+ * @param int $statusCode HTTP 상태 코드
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function successWithResource(
string $messageKey = 'common.success',
@@ -74,7 +75,7 @@ abstract class BaseApiController extends Controller
/**
* 현재 인증된 사용자를 반환합니다.
*
- * @return \App\Models\User|null
+ * @return User|null
*/
protected function getCurrentUser()
{
@@ -84,9 +85,9 @@ abstract class BaseApiController extends Controller
/**
* Not Found 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function notFound(
string $messageKey = 'common.not_found',
@@ -98,9 +99,9 @@ abstract class BaseApiController extends Controller
/**
* Unauthorized 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function unauthorized(
string $messageKey = 'common.unauthorized',
@@ -112,9 +113,9 @@ abstract class BaseApiController extends Controller
/**
* Forbidden 응답을 생성합니다.
*
- * @param string $messageKey 메시지 키
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param string $messageKey 메시지 키
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function forbidden(
string $messageKey = 'common.forbidden',
@@ -126,10 +127,10 @@ abstract class BaseApiController extends Controller
/**
* Validation Error 응답을 생성합니다.
*
- * @param mixed $errors 검증 오류
- * @param string $messageKey 메시지 키
- * @param array $messageParams 메시지 매개변수
- * @return \Illuminate\Http\JsonResponse
+ * @param mixed $errors 검증 오류
+ * @param string $messageKey 메시지 키
+ * @param array $messageParams 메시지 매개변수
+ * @return JsonResponse
*/
protected function validationError(
mixed $errors,
@@ -142,9 +143,9 @@ abstract class BaseApiController extends Controller
/**
* 파일 응답을 반환합니다 (ETag 및 캐싱 헤더 포함).
*
- * @param string $filePath 파일 경로
- * @param string $mimeType MIME 타입
- * @param int $maxAge 캐시 유지 시간 (초, 기본: 1년)
+ * @param string $filePath 파일 경로
+ * @param string $mimeType MIME 타입
+ * @param int $maxAge 캐시 유지 시간 (초, 기본: 1년)
*/
protected function fileResponse(string $filePath, string $mimeType, int $maxAge = 31536000): BinaryFileResponse|Response
{
@@ -176,35 +177,35 @@ abstract class BaseApiController extends Controller
/**
* JSON 응답을 반환합니다 (캐싱 헤더 포함).
*
- * @param mixed $data JSON으로 변환할 데이터
- * @param int $maxAge 캐시 유지 시간 (초, 기본: 1시간)
- * @param int $status HTTP 상태 코드
+ * @param mixed $data JSON으로 변환할 데이터
+ * @param int $maxAge 캐시 유지 시간 (초, 기본: 1시간)
+ * @param int $status HTTP 상태 코드
* @return JsonResponse JSON 응답
*/
protected function cachedJsonResponse(mixed $data, int $maxAge = 3600, int $status = 200): JsonResponse
{
return response()->json($data, $status, [
'Cache-Control' => "public, max-age={$maxAge}",
- ]);
+ ], ResponseHelper::JSON_ENCODE_OPTIONS);
}
/**
* ETag를 생성합니다.
*
- * @param mixed $data 해시할 데이터
+ * @param mixed $data 해시할 데이터
* @return string ETag 값 (따옴표 포함)
*/
protected function generateETag(mixed $data): string
{
$content = is_string($data) ? $data : json_encode($data);
- return '"' . md5($content) . '"';
+ return '"'.md5($content).'"';
}
/**
* 클라이언트 캐시가 유효한지 확인합니다.
*
- * @param string $etag 현재 ETag 값
+ * @param string $etag 현재 ETag 값
* @return bool 캐시가 유효하면 true
*/
protected function isNotModified(string $etag): bool
@@ -217,8 +218,8 @@ abstract class BaseApiController extends Controller
/**
* 304 Not Modified 응답을 반환합니다.
*
- * @param string $etag ETag 값
- * @param int $maxAge 캐시 TTL (초)
+ * @param string $etag ETag 값
+ * @param int $maxAge 캐시 TTL (초)
* @return Response 304 응답
*/
protected function notModifiedResponse(string $etag, int $maxAge = 3600): Response
@@ -233,10 +234,10 @@ abstract class BaseApiController extends Controller
*
* 클라이언트의 ETag가 일치하면 304 Not Modified를 반환합니다.
*
- * @param string $messageKey 메시지 키
- * @param mixed $data 응답 데이터
- * @param int $maxAge 캐시 TTL (초, 기본: 1시간)
- * @param array $messageParams 메시지 매개변수
+ * @param string $messageKey 메시지 키
+ * @param mixed $data 응답 데이터
+ * @param int $maxAge 캐시 TTL (초, 기본: 1시간)
+ * @param array $messageParams 메시지 매개변수
* @return JsonResponse|Response JSON 응답 또는 304 응답
*/
protected function successWithCache(
@@ -256,7 +257,7 @@ abstract class BaseApiController extends Controller
'success' => true,
'message' => __($messageKey, $messageParams),
'data' => $data,
- ])
+ ], 200, [], ResponseHelper::JSON_ENCODE_OPTIONS)
->header('ETag', $etag)
->header('Cache-Control', "public, max-age={$maxAge}")
->header('Vary', 'Accept-Encoding, Accept-Language');
diff --git a/app/Http/Controllers/Api/Public/PublicModuleController.php b/app/Http/Controllers/Api/Public/PublicModuleController.php
index cf46e435..85de88f1 100644
--- a/app/Http/Controllers/Api/Public/PublicModuleController.php
+++ b/app/Http/Controllers/Api/Public/PublicModuleController.php
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Public;
use App\Http\Controllers\Api\Base\PublicBaseController;
use App\Http\Requests\Public\Module\ServeModuleAssetRequest;
+use App\Services\ExtensionBundleService;
use App\Services\ModuleService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
@@ -17,11 +18,54 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
class PublicModuleController extends PublicBaseController
{
public function __construct(
- private readonly ModuleService $moduleService
+ private readonly ModuleService $moduleService,
+ private readonly ExtensionBundleService $bundleService
) {
parent::__construct();
}
+ /**
+ * 활성 모듈 프론트엔드 IIFE 병합 번들(JS)을 서빙합니다.
+ *
+ * 활성 global 모듈 에셋이 없으면 빈 200 응답(text/javascript)을 반환한다
+ * (프론트는 빈 스크립트 로드로 무해). 그 외에는 병합 파일을 fileResponse 로
+ * 서빙(ETag/304/환경별 Cache-Control 재사용).
+ *
+ * @return BinaryFileResponse|Response 병합 JS 파일 응답 또는 빈 응답
+ */
+ public function serveBundleJs(): BinaryFileResponse|Response
+ {
+ $this->logApiUsage('modules.bundle', ['kind' => 'js']);
+
+ $version = $this->bundleService->getCurrentVersion();
+ $path = $this->bundleService->getBundleFilePath('module', 'js', $version);
+
+ if ($path === '') {
+ return response('', 200)->header('Content-Type', 'text/javascript');
+ }
+
+ return $this->fileResponse($path, 'text/javascript', 31536000);
+ }
+
+ /**
+ * 활성 모듈 프론트엔드 병합 번들(CSS)을 서빙합니다.
+ *
+ * @return BinaryFileResponse|Response 병합 CSS 파일 응답 또는 빈 응답
+ */
+ public function serveBundleCss(): BinaryFileResponse|Response
+ {
+ $this->logApiUsage('modules.bundle', ['kind' => 'css']);
+
+ $version = $this->bundleService->getCurrentVersion();
+ $path = $this->bundleService->getBundleFilePath('module', 'css', $version);
+
+ if ($path === '') {
+ return response('', 200)->header('Content-Type', 'text/css');
+ }
+
+ return $this->fileResponse($path, 'text/css', 31536000);
+ }
+
/**
* 모듈 에셋 서빙
*
diff --git a/app/Http/Controllers/Api/Public/PublicPluginController.php b/app/Http/Controllers/Api/Public/PublicPluginController.php
index bb3e0f7b..b187f984 100644
--- a/app/Http/Controllers/Api/Public/PublicPluginController.php
+++ b/app/Http/Controllers/Api/Public/PublicPluginController.php
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Public;
use App\Http\Controllers\Api\Base\PublicBaseController;
use App\Http\Requests\Public\Plugin\ServePluginAssetRequest;
+use App\Services\ExtensionBundleService;
use App\Services\PluginService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
@@ -17,11 +18,53 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
class PublicPluginController extends PublicBaseController
{
public function __construct(
- private readonly PluginService $pluginService
+ private readonly PluginService $pluginService,
+ private readonly ExtensionBundleService $bundleService
) {
parent::__construct();
}
+ /**
+ * 활성 플러그인 프론트엔드 IIFE 병합 번들(JS)을 서빙합니다.
+ *
+ * 활성 global 플러그인 에셋이 없으면 빈 200 응답(text/javascript)을 반환한다.
+ * 그 외에는 병합 파일을 fileResponse 로 서빙(ETag/304/환경별 Cache-Control 재사용).
+ *
+ * @return BinaryFileResponse|Response 병합 JS 파일 응답 또는 빈 응답
+ */
+ public function serveBundleJs(): BinaryFileResponse|Response
+ {
+ $this->logApiUsage('plugins.bundle', ['kind' => 'js']);
+
+ $version = $this->bundleService->getCurrentVersion();
+ $path = $this->bundleService->getBundleFilePath('plugin', 'js', $version);
+
+ if ($path === '') {
+ return response('', 200)->header('Content-Type', 'text/javascript');
+ }
+
+ return $this->fileResponse($path, 'text/javascript', 31536000);
+ }
+
+ /**
+ * 활성 플러그인 프론트엔드 병합 번들(CSS)을 서빙합니다.
+ *
+ * @return BinaryFileResponse|Response 병합 CSS 파일 응답 또는 빈 응답
+ */
+ public function serveBundleCss(): BinaryFileResponse|Response
+ {
+ $this->logApiUsage('plugins.bundle', ['kind' => 'css']);
+
+ $version = $this->bundleService->getCurrentVersion();
+ $path = $this->bundleService->getBundleFilePath('plugin', 'css', $version);
+
+ if ($path === '') {
+ return response('', 200)->header('Content-Type', 'text/css');
+ }
+
+ return $this->fileResponse($path, 'text/css', 31536000);
+ }
+
/**
* 플러그인 에셋 서빙
*
diff --git a/app/Http/Middleware/GzipEncodeResponse.php b/app/Http/Middleware/GzipEncodeResponse.php
index e66953d1..f8d56022 100644
--- a/app/Http/Middleware/GzipEncodeResponse.php
+++ b/app/Http/Middleware/GzipEncodeResponse.php
@@ -4,6 +4,7 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
/**
@@ -98,6 +99,15 @@ class GzipEncodeResponse
}
// 최소 크기 이상인지 확인
+ // BinaryFileResponse 는 getContent() 가 false 를 반환하므로 파일 크기로 판정한다.
+ // (번들 JS/CSS 서빙은 response()->file() 로 BinaryFileResponse 를 반환하며,
+ // 이 분기가 없으면 미들웨어가 압축 없이 통과시켜 비압축 전송된다.)
+ if ($response instanceof BinaryFileResponse) {
+ $file = $response->getFile();
+
+ return $file !== null && $file->getSize() >= self::MIN_COMPRESS_SIZE;
+ }
+
$content = $response->getContent();
if ($content === false || strlen($content) < self::MIN_COMPRESS_SIZE) {
return false;
@@ -158,6 +168,12 @@ class GzipEncodeResponse
*/
private function compressResponse(Response $response): Response
{
+ // BinaryFileResponse 는 본문을 setContent() 로 교체할 수 없으므로
+ // 파일 내용을 읽어 일반 Response 로 치환한 뒤 압축한다 (헤더는 승계).
+ if ($response instanceof BinaryFileResponse) {
+ return $this->compressBinaryFileResponse($response);
+ }
+
$content = $response->getContent();
// gzip 압축 적용
@@ -173,14 +189,70 @@ class GzipEncodeResponse
$response->headers->set('Content-Encoding', 'gzip');
$response->headers->set('Content-Length', (string) strlen($compressed));
- // Vary 헤더가 없으면 추가 (캐시 프록시 지원)
+ $this->ensureVaryAcceptEncoding($response);
+
+ return $response;
+ }
+
+ /**
+ * BinaryFileResponse 를 gzip 압축된 일반 Response 로 치환합니다.
+ *
+ * BinaryFileResponse 는 파일 스트림 기반이라 setContent() 로 본문을 교체할 수 없으므로,
+ * 파일 내용을 읽어 gzip 압축한 새 Response 를 생성하고 기존 헤더(Content-Type,
+ * ETag, Cache-Control, Expires 등)를 승계한다. Content-Encoding/Content-Length 는
+ * 압축 결과로 재설정한다.
+ *
+ * @param BinaryFileResponse $response 파일 응답
+ * @return Response gzip 압축된 응답 (실패 시 원본 반환)
+ */
+ private function compressBinaryFileResponse(BinaryFileResponse $response): Response
+ {
+ $file = $response->getFile();
+
+ if ($file === null) {
+ return $response;
+ }
+
+ $content = @file_get_contents($file->getPathname());
+
+ if ($content === false) {
+ // 파일 읽기 실패 시 원본(비압축) 반환
+ return $response;
+ }
+
+ $compressed = gzencode($content, self::COMPRESSION_LEVEL);
+
+ if ($compressed === false) {
+ return $response;
+ }
+
+ // 기존 헤더를 승계한 새 Response 생성 (본문만 압축된 내용으로 교체)
+ $compressedResponse = new Response(
+ $compressed,
+ $response->getStatusCode(),
+ $response->headers->all()
+ );
+
+ $compressedResponse->headers->set('Content-Encoding', 'gzip');
+ $compressedResponse->headers->set('Content-Length', (string) strlen($compressed));
+
+ $this->ensureVaryAcceptEncoding($compressedResponse);
+
+ return $compressedResponse;
+ }
+
+ /**
+ * 응답에 `Vary: Accept-Encoding` 헤더를 보장합니다 (캐시 프록시 지원).
+ *
+ * @param Response $response HTTP 응답
+ */
+ private function ensureVaryAcceptEncoding(Response $response): void
+ {
if (! $response->headers->has('Vary')) {
$response->headers->set('Vary', 'Accept-Encoding');
} elseif (! str_contains($response->headers->get('Vary', ''), 'Accept-Encoding')) {
$currentVary = $response->headers->get('Vary');
$response->headers->set('Vary', $currentVary.', Accept-Encoding');
}
-
- return $response;
}
}
diff --git a/app/Http/View/Composers/TemplateComposer.php b/app/Http/View/Composers/TemplateComposer.php
index ff7c9320..5d565fb3 100644
--- a/app/Http/View/Composers/TemplateComposer.php
+++ b/app/Http/View/Composers/TemplateComposer.php
@@ -99,6 +99,9 @@ class TemplateComposer
// 확장 기능 캐시 버전 (브라우저 캐시 무효화용)
$extensionCacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
+ // 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
+ $bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
+
$view->with('activeAdminTemplate', $activeTemplate);
$view->with('extensionCacheVersion', $extensionCacheVersion);
$view->with('frontendSettings', $frontendSettings);
@@ -106,12 +109,39 @@ class TemplateComposer
$view->with('moduleSettings', $moduleSettings);
$view->with('moduleAssets', $moduleAssets);
$view->with('pluginAssets', $pluginAssets);
+ $view->with('bundleUrls', $bundleUrls);
$view->with('activeModulesMeta', $activeModulesMeta);
$view->with('activePluginsMeta', $activePluginsMeta);
$view->with('appConfig', $appConfig);
$view->with('templateExternals', $templateExternals);
}
+ /**
+ * 확장 프론트엔드 병합 번들 URL을 계산합니다.
+ *
+ * 활성 global 에셋(JS/CSS)이 하나라도 있는 타입만 해당 번들 URL을 채우고,
+ * 없으면 null을 두어 프론트가 로드를 스킵하게 한다. URL은 same-origin
+ * (`/api/...`)이어야 gdpr preblocker 의 same-origin 통과 규칙에 자기 차단되지
+ * 않는다(CDN 호스팅 금지).
+ *
+ * @param array $moduleAssets 수집된 모듈 개별 에셋 맵
+ * @param array $pluginAssets 수집된 플러그인 개별 에셋 맵
+ * @param int $version 확장 캐시 버전
+ * @return array{moduleJs: ?string, moduleCss: ?string, pluginJs: ?string, pluginCss: ?string}
+ */
+ private function buildExtensionBundleUrls(array $moduleAssets, array $pluginAssets, int $version): array
+ {
+ $hasJs = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['js'])));
+ $hasCss = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['css'])));
+
+ return [
+ 'moduleJs' => $hasJs($moduleAssets) ? "/api/modules/bundle.js?v={$version}" : null,
+ 'moduleCss' => $hasCss($moduleAssets) ? "/api/modules/bundle.css?v={$version}" : null,
+ 'pluginJs' => $hasJs($pluginAssets) ? "/api/plugins/bundle.js?v={$version}" : null,
+ 'pluginCss' => $hasCss($pluginAssets) ? "/api/plugins/bundle.css?v={$version}" : null,
+ ];
+ }
+
/**
* 활성화된 모듈의 프론트엔드 에셋 정보를 수집합니다.
*
diff --git a/app/Http/View/Composers/UserTemplateComposer.php b/app/Http/View/Composers/UserTemplateComposer.php
index c6460938..d145b0b1 100644
--- a/app/Http/View/Composers/UserTemplateComposer.php
+++ b/app/Http/View/Composers/UserTemplateComposer.php
@@ -105,6 +105,9 @@ class UserTemplateComposer
// 확장 기능 캐시 버전 (브라우저 캐시 무효화용)
$extensionCacheVersion = ClearsTemplateCaches::getExtensionCacheVersion();
+ // 확장 프론트엔드 병합 번들 URL (상시 ON — 활성 에셋이 없으면 null)
+ $bundleUrls = $this->buildExtensionBundleUrls($moduleAssets, $pluginAssets, $extensionCacheVersion);
+
$view->with('activeUserTemplate', $activeTemplate);
$view->with('extensionCacheVersion', $extensionCacheVersion);
$view->with('frontendSettings', $frontendSettings);
@@ -112,12 +115,39 @@ class UserTemplateComposer
$view->with('moduleSettings', $moduleSettings);
$view->with('moduleAssets', $moduleAssets);
$view->with('pluginAssets', $pluginAssets);
+ $view->with('bundleUrls', $bundleUrls);
$view->with('activeModulesMeta', $activeModulesMeta);
$view->with('activePluginsMeta', $activePluginsMeta);
$view->with('appConfig', $appConfig);
$view->with('templateExternals', $templateExternals);
}
+ /**
+ * 확장 프론트엔드 병합 번들 URL을 계산합니다.
+ *
+ * 활성 global 에셋(JS/CSS)이 하나라도 있는 타입만 해당 번들 URL을 채우고,
+ * 없으면 null을 두어 프론트가 로드를 스킵하게 한다. URL은 same-origin
+ * (`/api/...`)이어야 gdpr preblocker 의 same-origin 통과 규칙에 자기 차단되지
+ * 않는다(CDN 호스팅 금지).
+ *
+ * @param array $moduleAssets 수집된 모듈 개별 에셋 맵
+ * @param array $pluginAssets 수집된 플러그인 개별 에셋 맵
+ * @param int $version 확장 캐시 버전
+ * @return array{moduleJs: ?string, moduleCss: ?string, pluginJs: ?string, pluginCss: ?string}
+ */
+ private function buildExtensionBundleUrls(array $moduleAssets, array $pluginAssets, int $version): array
+ {
+ $hasJs = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['js'])));
+ $hasCss = static fn (array $assets): bool => ! empty(array_filter($assets, fn ($a) => ! empty($a['css'])));
+
+ return [
+ 'moduleJs' => $hasJs($moduleAssets) ? "/api/modules/bundle.js?v={$version}" : null,
+ 'moduleCss' => $hasCss($moduleAssets) ? "/api/modules/bundle.css?v={$version}" : null,
+ 'pluginJs' => $hasJs($pluginAssets) ? "/api/plugins/bundle.js?v={$version}" : null,
+ 'pluginCss' => $hasCss($pluginAssets) ? "/api/plugins/bundle.css?v={$version}" : null,
+ ];
+ }
+
/**
* 활성화된 모듈의 프론트엔드 에셋 정보를 수집합니다.
*
diff --git a/app/Services/ExtensionBundleService.php b/app/Services/ExtensionBundleService.php
new file mode 100644
index 00000000..9966b4c5
--- /dev/null
+++ b/app/Services/ExtensionBundleService.php
@@ -0,0 +1,475 @@
+` 로 실행해도 등록 로직은 동일하게 동작한다.
+ *
+ * 정렬/필터(`hasAssets()` && strategy==='global' + `uasort(priority)`) 는
+ * TemplateComposer 와 공유하는 SSoT 로 이 서비스에 둔다(drift 방지).
+ *
+ * 경로는 절대경로 게터(`getBuiltAssetAbsolutePaths()`)를 재사용한다 —
+ * `ModuleService::getAssetFilePath()` 의 `base_path("modules/{id}/...")`
+ * 하드코딩을 복제하지 않아야 `_bundled` 확장에서도 정확히 읽는다(제약 4).
+ *
+ * @see TemplateComposer
+ */
+class ExtensionBundleService
+{
+ // ext.cache_version 게터 재사용 — 트레이트를 use 해 self:: 로 호출(트레이트명
+ // 직접 정적 호출은 PHP 8.3+ deprecated). 인스턴스 캐시 무효화 메서드는 미사용.
+ use ClearsTemplateCaches;
+
+ /**
+ * 번들 캐시 파일이 저장되는 스토리지 디스크(= storage/app/ext-bundles).
+ */
+ private const BUNDLE_DISK = 'ext-bundles';
+
+ /**
+ * 서비스 주입
+ *
+ * @param ModuleManager $moduleManager 모듈 매니저
+ * @param PluginManager $pluginManager 플러그인 매니저
+ */
+ public function __construct(
+ private readonly ModuleManager $moduleManager,
+ private readonly PluginManager $pluginManager
+ ) {}
+
+ /**
+ * 확장 타입별 global 전략 에셋을 priority 오름차순으로 정렬해 반환합니다.
+ *
+ * TemplateComposer 의 개별 에셋 URL 생성과 번들러의 concat 이 동일한
+ * 필터/정렬을 쓰도록 하는 SSoT. 순서 제어는 오직 manifest
+ * `loading.priority` 숫자 오름차순뿐이며 특정 확장 이름 하드코딩은 없다(제약 1).
+ *
+ * @param string $type 'module' | 'plugin'
+ * @return array