feat(core,extensions): 확장 문서 호칭 통일과 레이아웃 편집기 문서 축 신설

확장 문서의 제품 호칭을 「그누보드7」로 통일했다. 가 지적한 두 문구는
개별 오타가 아니라 생성기가 찍는 정형 문구여서, 산출물이 아니라 방출 지점
세 곳을 먼저 고쳤다 — 그러지 않으면 21번째 확장부터 다시 샌다. 정리 범위는
확장 문서와 그 생성기까지이며, 코어 docs 와 언어팩 표시명은 의도적으로 남긴다.

레이아웃 편집기 대응 문서가 없던 문제는 확장마다 docs/editor-spec.md 를
두어 닫았다. 실측은 EditorSpecCollector 가 유지하며, 합본에 런타임과 같은
EditorSpecAssembler 를 써서 문서가 말하는 스펙과 편집기가 읽는 스펙이
갈라질 경로를 두지 않았다. 스펙을 두지 않은 확장에도 문서를 둔다 — 미보유가
정상일 수 있고, 그 정상 여부를 적을 자리가 없으면 다음 사람이 부재를 누락으로
오해하거나 필요한 시점을 놓친다.

초안이 낸 수치 다섯 건이 틀렸고 전부 오류 없이 "사실" 로 실릴 값이었다.
블록 최상위 키를 세어 팔레트가 79 대신 3 이 되던 것, `_` 접두 일괄 배제가
실제 항목을 삼키던 것 등을 정정했다.

게이트를 인위적으로 깨뜨려 점검한 결과 사각 하나가 드러났다 — 채워 넣으라는
표시만 지우고 서술을 쓰지 않으면 검사를 통과해, 빈 문서가 완비로 집계됐다.
미채움을 두 축으로 만들어 닫았고 되돌림으로 검산했다. 편집기 스펙 편집 시
규정이 주입되지 않던 것과 스캐폴딩 안내가 새 문서를 빠뜨리던 것도 함께 고쳤다.
This commit is contained in:
HeuJung committed 2026-09-01 12:02:55 +09:00
1 parent eb7ff4ec6a
commit 3a0aba85bc
114 files changed
+3433 -129

No files matched your search

@@ -0,0 +1,566 @@
<?php
namespace App\Support\ExtensionDoc;
use App\Extension\Helpers\EditorSpecAssembler;
/**
* 확장 편집기 스펙 수집기
*
* 확장이 `editor-spec.json`(+ 분할 `editor-spec/*.json`)으로 레이아웃 편집기에 선언한
* 표면을 실측합니다. 팔레트 항목·스타일 컨트롤·중첩 규칙·샘플 데이터·레시피가 각각 몇
* 개이고 어떤 ID 를 갖는지가 산출물입니다.
*
* 이 축이 문서에 없으면 확장에 새 화면 요소를 추가해도 편집기 팔레트에 나타나지 않는
* 상태가 오류도 경고도 없이 남습니다 — 편집기는 선언되지 않은 컴포넌트를 "없는 것" 으로
* 다룰 뿐 실패를 보고하지 않기 때문입니다. 스펙을 **갖지 않은** 확장도 그 사실 자체를
* 산출물로 돌려줍니다(`present => false`). 미보유는 정상 상태일 수 있고, 문서는 그
* 정상 여부를 서술할 자리를 가져야 합니다.
*
* 합본은 런타임 서빙과 같은 경로(`EditorSpecAssembler`)를 씁니다. 수집기가 별도 병합
* 규칙을 갖게 되면 문서가 말하는 스펙과 편집기가 읽는 스펙이 갈라집니다.
*/
class EditorSpecCollector
{
/**
* 블록별 **항목이 실제로 담긴 자리**.
*
* 블록 최상위 키를 그대로 세면 안 됩니다 — 블록들은 자기 항목을 `entries` / `groups` /
* `byDataSourceId` 같은 하위 자리에 담고, 최상위에는 `comment` 같은 메타 키를 함께
* 둡니다. 최상위를 세면 팔레트 79개가 3(comment·groups·entries)으로 집계되는데, 그
* 숫자는 오류 없이 문서에 실려 "이 확장은 팔레트 항목이 3개" 라는 사실 주장이 됩니다.
*
* 값이 빈 배열인 블록은 최상위(메타 키 제외)가 곧 항목입니다.
*
* 선언 순서가 곧 문서 표의 행 순서입니다.
*
* @var array<string, array<int, string>> 블록 키 → 항목이 담긴 하위 키 목록
*/
private const ITEM_PATHS = [
'componentPalette' => ['entries', 'groups'],
'controls' => [],
'componentCapabilities' => [],
'nesting' => ['draggable', 'containers'],
'sampleData' => ['byDataSourceId', 'byEndpointPattern'],
'sampleGlobal' => [],
'states' => ['groups'],
'stateLabels' => [],
'actionRecipes' => [],
'conditionRecipes' => ['operators'],
'computedRecipes' => [],
'errorRecipes' => [],
'loadingComponents' => [],
'actionChipCandidates' => [],
];
/**
* 항목이 아니라 설명인 키 — 개수에서 제외한다.
*
* **접두 규칙으로 넓히지 않는다.** `_` 로 시작하는 키를 일괄 배제하면 실제 항목까지
* 삼킨다 — `sampleGlobal._local` 이 그 예이고, 그렇게 빠진 항목은 오류 없이 문서에
* "1개 적은 수" 로 실린다. 설명 키는 실측으로 확인된 것만 이름으로 열거한다.
*
* @var array<int, string> 설명 키 목록
*/
private const META_KEYS = ['comment', '$comment', '$schema', '_propControlsComment'];
/**
* @var array<int, string>|null 번들 템플릿이 커버하는 샘플 ID (프로세스 단위 메모)
*/
private static ?array $fallbackSampleIds = null;
/**
* 확장의 편집기 스펙 표면을 수집합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @param array<int, string> $layoutRelFiles 이 확장의 레이아웃 파일(확장 루트 기준 상대 경로)
* @return array<string, mixed> 편집기 스펙 인벤토리
*/
public function collect(array $record, array $layoutRelFiles = []): array
{
$manifestPath = $record['path'].DIRECTORY_SEPARATOR.'editor-spec.json';
if (! is_file($manifestPath)) {
return $this->absent($record, $layoutRelFiles);
}
$spec = EditorSpecAssembler::assemble($manifestPath);
if ($spec === null) {
// manifest 가 있는데 디코드에 실패한 상태다. "스펙 없음" 과 구분해 보고한다 —
// 뭉뚱그리면 깨진 JSON 이 "이 확장은 편집기 스펙을 두지 않는다" 로 읽힌다.
return $this->absent($record, $layoutRelFiles, malformed: true);
}
$includes = $this->includeMap($manifestPath);
return [
'present' => true,
'malformed' => false,
'manifest' => $record['relPath'].'/editor-spec.json',
'split' => $includes !== [],
'includes' => $includes,
'version' => $this->stringOrNull($spec['version'] ?? null),
'description' => $this->stringOrNull($spec['description'] ?? null),
'styleSystem' => $this->stringOrNull($spec['styleSystem'] ?? null),
'darkMode' => $this->stringOrNull(($spec['darkMode']['strategy'] ?? null)),
'blocks' => $this->blockSummaries($spec, $includes),
'paletteGroups' => $this->paletteGroups($spec['componentPalette'] ?? null),
'sampleDataIds' => $this->idsAt($spec['sampleData'] ?? null, 'byDataSourceId'),
'sampleEndpointPatterns' => $this->idsAt($spec['sampleData'] ?? null, 'byEndpointPattern'),
'stateScopes' => $this->idsAt($spec['states'] ?? null, 'groups'),
'uncovered' => $this->uncoveredDataSources($record, $layoutRelFiles, $spec),
'declaredPaths' => [
'sampleData.byDataSourceId' => $this->hasPath($spec['sampleData'] ?? null, 'byDataSourceId'),
'sampleData.byEndpointPattern' => $this->hasPath($spec['sampleData'] ?? null, 'byEndpointPattern'),
'states.groups' => $this->hasPath($spec['states'] ?? null, 'groups'),
],
];
}
/**
* 스펙 미보유(또는 손상) 상태의 산출물을 만듭니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param array<int, string> $layoutRelFiles 레이아웃 파일 목록
* @param bool $malformed manifest 는 있으나 디코드에 실패했는지 여부
* @return array<string, mixed> 인벤토리
*/
private function absent(array $record, array $layoutRelFiles, bool $malformed = false): array
{
return [
'present' => false,
'malformed' => $malformed,
'manifest' => null,
'split' => false,
'includes' => [],
'version' => null,
'description' => null,
'styleSystem' => null,
'darkMode' => null,
'blocks' => [],
'paletteGroups' => [],
'sampleDataIds' => [],
'sampleEndpointPatterns' => [],
'stateScopes' => [],
'uncovered' => $this->uncoveredDataSources($record, $layoutRelFiles, []),
'declaredPaths' => [],
];
}
/**
* manifest 의 `$include` 맵을 원본 그대로 읽습니다.
*
* 합본 결과에는 `$include` 가 남지 않으므로(assemble 이 벗겨낸다) 분할 여부와 블록
* 파일 경로는 manifest 를 다시 읽어야 알 수 있습니다.
*
* @param string $manifestPath manifest 절대 경로
* @return array<string, string> 블록 키 → 상대 경로
*/
private function includeMap(string $manifestPath): array
{
$decoded = json_decode((string) file_get_contents($manifestPath), true);
if (! is_array($decoded) || ! is_array($decoded['$include'] ?? null)) {
return [];
}
$map = [];
foreach ($decoded['$include'] as $key => $relative) {
if (is_string($key) && is_string($relative) && $relative !== '') {
$map[$key] = $relative;
}
}
return $map;
}
/**
* 블록별 요약(항목 수·출처)을 만듭니다.
*
* 항목이 여러 하위 자리에 나뉜 블록(`nesting`, `sampleData`)은 자리마다 한 행을
* 냅니다. 합산하면 "끌 수 있는 컴포넌트 84 + 담을 수 있는 컨테이너 19 = 103" 처럼
* 뜻이 없는 수가 되고, 그 수는 표에서 사실처럼 읽힙니다.
*
* @param array<string, mixed> $spec 합본 spec
* @param array<string, string> $includes 블록 키 → 분할 파일 상대 경로
* @return array<int, array{key: string, count: int|null, source: string}> 블록 요약
*/
private function blockSummaries(array $spec, array $includes): array
{
$summaries = [];
foreach (self::ITEM_PATHS as $key => $paths) {
if (! array_key_exists($key, $spec)) {
continue;
}
$source = $includes[$key] ?? 'editor-spec.json (인라인)';
$block = $spec[$key];
if ($paths === []) {
$summaries[] = [
'key' => $key,
'count' => $this->countItems($block),
'source' => $source,
];
continue;
}
// 선언된 하위 자리 중 **실제로 있는 것만** 행으로 낸다. 없는 자리를 0 으로
// 내보내면 "선언했는데 비었다" 와 "그 형태를 쓰지 않는다" 가 같은 모양이 된다.
foreach ($paths as $path) {
if (! is_array($block) || ! array_key_exists($path, $block)) {
continue;
}
$summaries[] = [
'key' => $key.'.'.$path,
'count' => $this->countItems($block[$path]),
'source' => $source,
];
}
}
return $summaries;
}
/**
* 값의 항목 수를 셉니다. 맵이면 메타 키를 뺀 나머지, 리스트면 길이입니다.
*
* @param mixed $value 블록 또는 하위 자리의 값
* @return int|null 항목 수 (개수 개념이 없으면 null)
*/
private function countItems(mixed $value): ?int
{
if (! is_array($value)) {
return null;
}
if (array_is_list($value)) {
return count($value);
}
return count($this->withoutMeta($value));
}
/**
* 맵에서 메타 키를 제거합니다.
*
* @param array<string, mixed> $map 대상 맵
* @return array<string, mixed> 메타 키를 뺀 맵
*/
private function withoutMeta(array $map): array
{
return array_filter(
$map,
static fn ($k): bool => ! in_array((string) $k, self::META_KEYS, true),
ARRAY_FILTER_USE_KEY,
);
}
/**
* 팔레트 그룹별 컴포넌트 수를 셉니다.
*
* 팔레트는 `{ groups: [{ label, kind, components[] }], entries: { … } }` 형태입니다.
* `groups` 가 편집기 좌측 목록의 묶음이고, 각 묶음이 담는 컴포넌트 이름이 `components`
* 입니다.
*
* @param mixed $palette componentPalette 블록
* @return array<int, array{group: string, kind: string, count: int}> 그룹 요약
*/
private function paletteGroups(mixed $palette): array
{
if (! is_array($palette) || ! is_array($palette['groups'] ?? null)) {
return [];
}
$out = [];
foreach ($palette['groups'] as $group) {
if (! is_array($group)) {
continue;
}
$out[] = [
'group' => $this->resolveLabel($this->stringOrNull($group['label'] ?? null) ?? '(이름 없음)'),
'kind' => $this->stringOrNull($group['kind'] ?? null) ?? '-',
'count' => is_array($group['components'] ?? null) ? count($group['components']) : 0,
];
}
return $out;
}
/**
* 블록의 하위 자리에서 항목 ID 목록을 뽑습니다.
*
* 맵이면 키가 ID 이고, 리스트면 각 항목의 `id`(없으면 `scope.match`)가 ID 입니다.
* 페이지 상태는 리스트 + `scope` 형태라 키가 없습니다.
*
* @param mixed $block 블록 값
* @param string $path 항목이 담긴 하위 키
* @return array<int, string> ID 목록
*/
private function idsAt(mixed $block, string $path): array
{
if (! is_array($block) || ! is_array($block[$path] ?? null)) {
return [];
}
$items = $block[$path];
if (! array_is_list($items)) {
return array_values(array_map(
static fn ($k): string => (string) $k,
array_keys($this->withoutMeta($items)),
));
}
$ids = [];
foreach ($items as $item) {
if (! is_array($item)) {
continue;
}
$id = $this->stringOrNull($item['id'] ?? null)
?? $this->stringOrNull($item['scope']['match'] ?? null)
?? $this->stringOrNull($item['label'] ?? null);
if ($id !== null) {
$ids[] = $id;
}
}
return $ids;
}
/**
* 이 확장 레이아웃의 `data_source` 중 **프리뷰 샘플이 붙지 않는 것**을 찾습니다.
*
* 편집기 캔버스는 실제 API 를 부르지 않고 `sampleData` 로 화면을 그립니다. 그래서
* 레이아웃에 `data_source` 를 추가하고 샘플을 붙이지 않으면 그 영역만 편집기에서
* 빈 화면이 되는데, 실제 화면은 정상 동작하므로 어긋남이 드러나지 않습니다. 오류도
* 경고도 남지 않아 문서의 이 목록이 유일한 통로입니다.
*
* 커버 판정에는 확장 자신의 스펙뿐 아니라 **번들 템플릿의 스펙**도 넣습니다 —
* `settings` 처럼 여러 확장이 함께 쓰는 공용 ID 는 템플릿 스펙이 대신 채우도록 설계된
* 것이라, 그것까지 미커버로 세면 목록이 잡음으로 가득 차 정작 볼 것이 묻힙니다.
*
* 번들 템플릿은 출하 기본값입니다. 운영자가 다른 템플릿을 쓰면 커버 집합이 달라질 수
* 있으므로, 이 목록은 "반드시 빈다" 가 아니라 "기본 구성에서 빈다" 로 읽습니다.
*
* @param array<string, mixed> $record 확장 레코드
* @param array<int, string> $layoutRelFiles 레이아웃 파일(확장 루트 기준 상대 경로)
* @param array<string, mixed> $spec 이 확장의 합본 spec (없으면 빈 배열)
* @return array<int, string> 샘플이 없는 data_source ID 목록
*/
private function uncoveredDataSources(array $record, array $layoutRelFiles, array $spec): array
{
if ($layoutRelFiles === []) {
return [];
}
$covered = array_flip(array_merge($this->sampleIdsOf($spec), $this->fallbackSampleIds()));
$uncovered = [];
foreach ($layoutRelFiles as $rel) {
$abs = $record['path'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $rel);
$layout = $this->decodeJson($abs);
if ($layout === null) {
continue;
}
foreach ($this->layoutDataSourceIds($layout) as $id) {
if (! isset($covered[$id])) {
$uncovered[$id] = true;
}
}
}
$ids = array_keys($uncovered);
sort($ids);
return $ids;
}
/**
* spec 의 `sampleData.byDataSourceId` 키 목록을 뽑습니다.
*
* @param array<string, mixed> $spec 합본 spec
* @return array<int, string> ID 목록
*/
private function sampleIdsOf(array $spec): array
{
return $this->idsAt($spec['sampleData'] ?? null, 'byDataSourceId');
}
/**
* 번들 템플릿 스펙이 채우는 샘플 ID 집합을 돌려줍니다.
*
* 결과를 프로세스 단위로 기억합니다. 확장 20개를 도는 동안 매번 다시 합본하면 템플릿
* 스펙(팔레트·컨트롤·역량을 담아 수만 줄에 이른다)을 스무 번 메모리에 올리게 되고,
* 메모리 한도가 낮은 실행 환경(테스트 프로세스)에서는 그대로 OOM 이 됩니다. 남기는
* 것은 스펙 전체가 아니라 **ID 문자열 목록**이라 유지 비용도 작습니다.
*
* @return array<int, string> 번들 템플릿이 커버하는 data_source ID 목록
*/
private function fallbackSampleIds(): array
{
if (self::$fallbackSampleIds !== null) {
return self::$fallbackSampleIds;
}
$glob = glob(base_path('templates'.DIRECTORY_SEPARATOR.'_bundled'.DIRECTORY_SEPARATOR.'*'.DIRECTORY_SEPARATOR.'editor-spec.json'));
$ids = [];
foreach ($glob === false ? [] : $glob as $manifest) {
$assembled = EditorSpecAssembler::assemble($manifest);
if (is_array($assembled)) {
$ids = array_merge($ids, $this->sampleIdsOf($assembled));
}
// 합본 결과를 즉시 놓아준다 — 다음 manifest 를 읽기 전에 회수되게 한다.
unset($assembled);
}
return self::$fallbackSampleIds = array_values(array_unique($ids));
}
/**
* 레이아웃 JSON 트리에서 `data_sources[].id` 를 전부 긁습니다.
*
* `data_sources` 는 최상위뿐 아니라 컴포넌트 노드에도 붙을 수 있어 트리 전체를 봅니다.
*
* @param array<string, mixed> $node 레이아웃 노드
* @return array<int, string> data_source ID 목록
*/
private function layoutDataSourceIds(array $node): array
{
$ids = [];
if (is_array($node['data_sources'] ?? null)) {
foreach ($node['data_sources'] as $ds) {
$id = is_array($ds) ? $this->stringOrNull($ds['id'] ?? null) : null;
if ($id !== null) {
$ids[] = $id;
}
}
}
foreach ($node as $value) {
if (is_array($value)) {
$ids = array_merge($ids, $this->layoutDataSourceIds($value));
}
}
return $ids;
}
/**
* `$t:` 접두 다국어 키를 코어 한국어 문자열로 풉니다.
*
* 편집기 스펙의 라벨은 화면에 그대로 나오지 않고 프론트 i18n 을 거칩니다. 문서에 키
* 원문(`$t:layout_editor.palette.group.design`)을 그대로 실으면 읽는 쪽이 그 묶음이
* 무엇인지 알 수 없습니다.
*
* Laravel 의 `__()` 로는 풀리지 않습니다 — 이 키들은 PHP lang 파일이 아니라 프론트
* 다국어 JSON(`lang/ko.json` + `$partial` 분할)에 있고, JSON 번역기는 문자열 전체를
* 키로 쓰기 때문입니다. 그래서 `$partial` 한 홉을 직접 따라갑니다.
*
* 풀리지 않으면 **원문을 그대로 둡니다.** 없는 번역을 지어내는 것보다 키가 드러나는
* 편이 어디를 고쳐야 하는지 알려 주고, 이 해석이 어긋나도 문서가 틀린 사실을 주장하는
* 대신 키만 남습니다.
*
* @param string $label 라벨 원문
* @return string 해석된 라벨 (실패 시 원문)
*/
private function resolveLabel(string $label): string
{
if (! str_starts_with($label, '$t:')) {
return $label;
}
$root = base_path('lang');
$node = $this->langRoot($root);
if ($node === null) {
return $label;
}
foreach (explode('.', substr($label, 3)) as $segment) {
if (is_array($node) && isset($node['$partial']) && is_string($node['$partial'])) {
$node = $this->decodeJson($root.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $node['$partial']));
}
if (! is_array($node) || ! array_key_exists($segment, $node)) {
return $label;
}
$node = $node[$segment];
}
return is_string($node) && $node !== '' ? $node : $label;
}
/**
* 코어 프론트 다국어 루트(`lang/ko.json`)를 읽습니다.
*
* @param string $root `lang` 디렉토리 절대 경로
* @return array<string, mixed>|null 디코드 결과
*/
private function langRoot(string $root): ?array
{
return $this->decodeJson($root.DIRECTORY_SEPARATOR.'ko.json');
}
/**
* JSON 파일을 배열로 읽습니다.
*
* @param string $path 절대 경로
* @return array<string, mixed>|null 디코드 결과 (실패 시 null)
*/
private function decodeJson(string $path): ?array
{
if (! is_file($path)) {
return null;
}
$decoded = json_decode((string) file_get_contents($path), true);
return is_array($decoded) ? $decoded : null;
}
/**
* 블록이 그 하위 자리를 **선언했는지** 봅니다.
*
* 선언하고 비운 것(`0`)과 아예 선언하지 않은 것은 다릅니다 — 전자는 채울 자리가
* 있다는 뜻이고 후자는 그 형태를 쓰지 않는다는 뜻입니다. 뭉뚱그려 `0` 으로 적으면
* 읽는 쪽이 "채워야 할 자리를 비워 뒀다" 로 오해합니다.
*
* @param mixed $block 블록 값
* @param string $path 하위 키
* @return bool 선언 여부
*/
private function hasPath(mixed $block, string $path): bool
{
return is_array($block) && array_key_exists($path, $block);
}
/**
* 비어 있지 않은 문자열만 통과시킵니다.
*
* @param mixed $value 후보 값
* @return string|null 문자열 또는 null
*/
private function stringOrNull(mixed $value): ?string
{
return is_string($value) && $value !== '' ? $value : null;
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Support\ExtensionDoc;
/**
* 확장 문서 수집 컨텍스트 조립기
*
* 문서 블록을 렌더하려면 수집기 여덟 축(선언형 표면·훅·데이터 모델·프론트·테스트·의존
* 관계·편집기 스펙)의 산출물을 한 배열로 묶어야 합니다. 그 조립을 커맨드와 계약 테스트가
* 각자 하고 있으면, 축이 하나 늘 때 한쪽만 갱신되어 **드리프트가 아닌 드리프트**가 보고
* 됩니다 — 테스트가 만든 블록에는 그 축이 없어 파일과 달라지기 때문입니다.
*
* 그 어긋남은 "생성기를 다시 돌려라" 라는 메시지로 나타나는데, 아무리 돌려도 사라지지
* 않습니다. 조립을 이 한 곳이 소유해 그 경로 자체를 없앱니다.
*/
class ExtensionDocContext
{
/**
* 수집기를 주입받습니다.
*
* @param DeclarativeSurfaceCollector $surface 선언형 표면 수집기
* @param HookInventory $hooks 훅 인벤토리
* @param DataModelCollector $data 데이터 모델 수집기
* @param FrontendInventory $frontend 프론트 인벤토리
* @param TestPathCollector $tests 테스트 경로 수집기
* @param DependencyGraphCollector $deps 의존 관계 수집기
* @param EditorSpecCollector $editorSpec 편집기 스펙 수집기
*/
public function __construct(
private readonly DeclarativeSurfaceCollector $surface,
private readonly HookInventory $hooks,
private readonly DataModelCollector $data,
private readonly FrontendInventory $frontend,
private readonly TestPathCollector $tests,
private readonly DependencyGraphCollector $deps,
private readonly EditorSpecCollector $editorSpec,
) {}
/**
* 확장 하나의 수집 컨텍스트를 조립합니다.
*
* @param array<string, mixed> $record ExtensionInventory 레코드
* @return array<string, mixed> 수집 컨텍스트
*/
public function build(array $record): array
{
// 선언형 표면을 먼저 모은다 — 발행 훅의 1차 출처가 그 안의 `getHooks()` 선언이다.
$surface = $this->surface->collect($record);
$declaredHooks = $surface['values']['getHooks'] ?? [];
// 편집기 스펙 수집기는 레이아웃 목록을 받아 "프리뷰 샘플이 없는 data_source" 를
// 판정한다. 레이아웃 경로 규약(모듈·플러그인 `resources/layouts/` ↔ 템플릿
// `layouts/`)은 FrontendInventory 가 단독으로 소유하므로, 그 결과를 넘겨 분기가
// 두 곳에 생기지 않게 한다.
$frontend = $this->frontend->collect($record);
$layoutRelFiles = array_map(
static fn (array $layout): string => $layout['relFile'],
$frontend['layouts'],
);
return [
'record' => $record,
'surface' => $surface,
'hooks' => $this->hooks->collect($record, is_array($declaredHooks) ? $declaredHooks : []),
'data' => $this->data->collect($record),
'frontend' => $frontend,
'tests' => $this->tests->collect($record),
'deps' => $this->deps->collect($record),
'editorSpec' => $this->editorSpec->collect($record, $layoutRelFiles),
];
}
}
@@ -21,6 +21,11 @@ class ExtensionDocScaffolder
*/
public const GEN_PREFIX = '<!-- @generated:';
/**
* @var string 미채움 축 라벨 — 마커를 지우고 서술을 쓰지 않은 빈 `@intent` 블록
*/
public const EMPTY_INTENT_LABEL = '(빈 서술)';
/**
* @var string 미채움 마커 — 설계 의도 / 소개 서술
*/
@@ -166,6 +171,24 @@ class ExtensionDocScaffolder
'부트스트랩' => 'frontend-entry',
],
],
// 편집기 스펙은 **세 유형 모두** 가진다. 스펙을 두지 않은 확장에도 문서를 두는 것은
// 미보유가 곧 정상일 수 있기 때문이다 — "이 확장은 왜 편집기 스펙이 없어도 되는가 /
// 언제 필요해지는가" 를 적을 자리가 없으면, 다음 사람이 그 부재를 누락으로 오해하거나
// 반대로 필요한 시점을 놓친다. 미보유 확장의 블록은 그 사실을 명시하고 사람 서술로
// 이어진다.
'docs/editor-spec.md' => [
'types' => ['module', 'plugin', 'template'],
// 절 ↔ 블록은 **키로** 묶는다. 순번 결합은 절을 하나 끼우는 순간 그 뒤 블록이
// 전부 엉뚱한 헤딩 밑으로 들어가는데, 헤딩 존재·블록 존재를 각각만 보는 게이트는
// 그 어긋남을 잡지 못한다. 필수 절 목록은 이 배열의 키에서 파생한다(중복 정의 없음).
'blocks' => [
'선언 요약' => 'editor-spec-summary',
'선언 블록' => 'editor-spec-blocks',
'컴포넌트 팔레트' => 'editor-spec-palette',
'샘플 데이터와 페이지 상태' => 'editor-spec-samples',
'수정 시 동반 의무' => 'editor-spec-obligations',
],
],
];
/**
@@ -347,6 +370,35 @@ class ExtensionDocScaffolder
];
}
/**
* 본문이 빈 사람 영역(`@intent`) 블록 수를 셉니다.
*
* 미채움은 `TODO:` 마커로만 드러나지 않습니다. 스캐폴딩 직후 마커를 **지우기만 하고**
* 서술을 쓰지 않으면 마커 검사는 0 을 돌려주고 골격·블록 검사도 전부 통과합니다 —
* 결과가 "다 채웠다" 와 구분되지 않아, 비어 있는 문서가 완비로 집계됩니다.
*
* 그래서 마커 잔량과 빈 본문을 **같은 축**(미채움)으로 함께 봅니다.
*
* @param string $content 문서 전문
* @return int 빈 `@intent` 블록 수
*/
public static function emptyIntentBlocks(string $content): int
{
if (preg_match_all('/<!-- @intent START -->(.*?)<!-- @intent END -->/s', $content, $m) === false) {
return 0;
}
$empty = 0;
foreach ($m[1] as $body) {
if (trim($body) === '') {
$empty++;
}
}
return $empty;
}
/**
* 자동 생성 블록을 마커로 감쌉니다.
*
@@ -565,6 +617,11 @@ class ExtensionDocScaffolder
'assets' => $this->renderAssets($ctx),
'components' => $this->renderComponents($ctx),
'layout-map' => $this->renderLayoutMap($ctx),
'editor-spec-summary' => $this->renderEditorSpecSummary($ctx),
'editor-spec-blocks' => $this->renderEditorSpecBlocks($ctx),
'editor-spec-palette' => $this->renderEditorSpecPalette($ctx),
'editor-spec-samples' => $this->renderEditorSpecSamples($ctx),
'editor-spec-obligations' => $this->renderEditorSpecObligations($ctx),
default => $this->none('알 수 없는 블록 키: '.$key),
};
}
@@ -593,7 +650,7 @@ class ExtensionDocScaffolder
$core = $ctx['deps']['coreVersion'] ?? null;
if ($core !== null) {
$badges[] = $this->badge('G7', $core, '1F883D');
$badges[] = $this->badge('그누보드7', $core, '1F883D');
}
$license = $manifest['license'] ?? null;
@@ -639,7 +696,7 @@ class ExtensionDocScaffolder
private function renderRequirements(array $ctx): string
{
$rows = [];
$rows[] = ['G7 코어', $this->code($ctx['deps']['coreVersion'] ?? '(제약 없음)')];
$rows[] = ['그누보드7 코어', $this->code($ctx['deps']['coreVersion'] ?? '(제약 없음)')];
$rows[] = ['PHP', $this->code($this->composerPhp($ctx) ?? '^8.2')];
foreach ($ctx['deps']['requires'] as $dep) {
@@ -826,6 +883,7 @@ class ExtensionDocScaffolder
'docs/components.md' => '템플릿이 제공하는 컴포넌트',
'docs/layouts.md' => '레이아웃 목록과 라우트 매핑',
'docs/handlers.md' => '템플릿 전용 핸들러와 부트스트랩',
'docs/editor-spec.md' => '레이아웃 편집기에 선언한 팔레트·컨트롤·샘플 데이터',
default => '-',
};
}
@@ -2252,7 +2310,7 @@ class ExtensionDocScaffolder
$lines = [];
$lines[] = '# '.$name;
$lines[] = '';
$lines[] = "**G7 {$label} · {$record['id']}**";
$lines[] = "**그누보드7 {$label} · {$record['id']}**";
$lines[] = $this->escape($description);
$lines[] = '';
$lines[] = self::wrap('badges', $this->renderBlock('badges', $ctx));
@@ -2455,10 +2513,284 @@ class ExtensionDocScaffolder
'docs/components.md' => '컴포넌트',
'docs/layouts.md' => '레이아웃',
'docs/handlers.md' => '핸들러',
'docs/editor-spec.md' => '레이아웃 편집기 스펙',
default => basename($doc, '.md'),
};
}
// -----------------------------------------------------------------------
// 편집기 스펙 블록 렌더러
// -----------------------------------------------------------------------
/**
* 편집기 스펙 보유 여부와 형태를 렌더합니다.
*
* 미보유는 결함이 아니라 정상일 수 있으므로 "없음" 을 사실로 적고 사람 서술에 넘깁니다.
* 다만 manifest 가 있는데 읽지 못한 경우(malformed)는 구분해 적습니다 — 뭉뚱그리면
* 깨진 JSON 이 "이 확장은 편집기 스펙을 두지 않는다" 로 굳습니다.
*
* @param array<string, mixed> $ctx 수집 컨텍스트
* @return string 마크다운
*/
private function renderEditorSpecSummary(array $ctx): string
{
$spec = $ctx['editorSpec'] ?? null;
if (! is_array($spec)) {
return $this->none('편집기 스펙을 수집하지 못했습니다.');
}
if (($spec['malformed'] ?? false) === true) {
return $this->none('`editor-spec.json` 이 존재하지만 JSON 으로 읽지 못했습니다 — 편집기가 이 확장의 선언을 무시하고 있습니다.');
}
if (($spec['present'] ?? false) !== true) {
return $this->none('이 확장은 편집기 스펙(`editor-spec.json`)을 두지 않습니다. 편집기는 코어 기본 팔레트와 활성 템플릿의 스펙만으로 이 확장의 화면을 다룹니다.');
}
$rows = [];
$rows[] = ['manifest', $this->code((string) $spec['manifest'])];
$rows[] = ['형태', $spec['split'] === true
? '분할 — manifest + `editor-spec/*.json` '.count($spec['includes']).'개 블록'
: '단일 파일 (인라인)'];
$rows[] = ['스펙 버전', $this->code((string) ($spec['version'] ?? ''))];
$rows[] = ['스타일 시스템', $this->code((string) ($spec['styleSystem'] ?? ''))];
$rows[] = ['다크 모드 전략', $this->code((string) ($spec['darkMode'] ?? ''))];
$table = $this->table(['항목', '값'], $rows);
$description = $spec['description'] ?? null;
if (is_string($description) && $description !== '') {
return $table."\n\n> ".$this->escape($description);
}
return $table;
}
/**
* 스펙이 선언한 블록별 항목 수를 렌더합니다.
*
* @param array<string, mixed> $ctx 수집 컨텍스트
* @return string 마크다운
*/
private function renderEditorSpecBlocks(array $ctx): string
{
$spec = $ctx['editorSpec'] ?? null;
if (! is_array($spec) || ($spec['present'] ?? false) !== true) {
return $this->none('선언된 편집기 스펙 블록이 없습니다.');
}
$rows = [];
foreach ($spec['blocks'] as $block) {
$rows[] = [
$this->code($block['key']),
$this->editorSpecBlockRole($block['key']),
$block['count'] === null ? '-' : (string) $block['count'],
$this->code($block['source']),
];
}
return $this->table(['블록', '역할', '항목 수', '출처'], $rows);
}
/**
* 편집기 스펙 블록의 역할을 한 줄로 설명합니다.
*
* 블록 키는 코어가 정한 어휘이므로 확장마다 다시 설명할 필요가 없고, 반대로 설명이
* 없으면 확장 문서만 읽는 쪽이 키 이름만으로 의미를 추측하게 됩니다.
*
* @param string $key 블록 키
* @return string 역할 설명
*/
private function editorSpecBlockRole(string $key): string
{
return match ($key) {
'componentPalette', 'componentPalette.entries' => '편집기 "요소 추가" 팔레트에 나타나는 항목',
'componentPalette.groups' => '팔레트 좌측 목록의 묶음',
'nesting.draggable' => '캔버스에서 끌어 옮길 수 있는 컴포넌트',
'nesting.containers' => '자식을 담을 수 있는 컴포넌트와 그 허용 규칙',
'sampleData.byDataSourceId' => '레이아웃 `data_sources` ID 로 붙는 프리뷰 응답',
'sampleData.byEndpointPattern' => '엔드포인트 패턴으로 붙는 프리뷰 응답',
'states.groups' => '상태 변종을 적용할 범위(라우트·베이스 레이아웃)',
'conditionRecipes.operators' => '조건 표현식에 쓸 수 있는 연산자',
'controls' => '재사용 스타일 컨트롤 정의',
'componentCapabilities' => '컴포넌트별 편집 역량(어떤 속성을 편집기가 다루는가)',
'nesting' => '어떤 컴포넌트 안에 무엇을 넣을 수 있는가',
'sampleData' => '캔버스 프리뷰용 샘플 응답',
'sampleGlobal' => '`_global.*` 프리뷰 baseline 시드',
'states' => '페이지 상태 변종(빈 목록·오류 등)',
'stateLabels' => '상태값 친화 명칭 카탈로그',
'actionRecipes' => '친화 명칭 → 액션 JSON 레시피',
'conditionRecipes' => '친화 조건 → `if` 표현식 레시피',
'computedRecipes' => '계산값 레시피',
'errorRecipes' => '오류 처리 레시피',
'loadingComponents' => '로딩 표시 컴포넌트 후보',
'actionChipCandidates' => '동작 데이터 칩 컨텍스트 후보',
default => '-',
};
}
/**
* ID 목록을 표 한 칸에 담을 수 있게 줄입니다.
*
* 70개를 한 줄로 늘어놓으면 표가 읽히지 않고, 그렇다고 개수만 남기면 어떤 ID 인지
* 확인할 길이 사라집니다. 앞쪽을 보이고 나머지는 수로 줄입니다.
*
* @param array<int, string> $ids ID 목록
* @param int $limit 나열할 최대 개수
* @return string 마크다운 셀 내용
*/
private function idListCell(array $ids, int $limit = 12): string
{
if ($ids === []) {
return '-';
}
$shown = array_slice($ids, 0, $limit);
$cell = implode(' · ', array_map(fn (string $id): string => $this->code($id), $shown));
$rest = count($ids) - count($shown);
return $rest > 0 ? $cell." … 외 {$rest}개" : $cell;
}
/**
* 팔레트 그룹별 항목 수를 렌더합니다.
*
* @param array<string, mixed> $ctx 수집 컨텍스트
* @return string 마크다운
*/
private function renderEditorSpecPalette(array $ctx): string
{
$spec = $ctx['editorSpec'] ?? null;
if (! is_array($spec) || ($spec['present'] ?? false) !== true) {
return $this->none('이 확장은 편집기 팔레트에 항목을 추가하지 않습니다.');
}
$rows = [];
foreach ($spec['paletteGroups'] as $group) {
$rows[] = [
$this->escape($group['group']),
$this->code($group['kind']),
(string) $group['count'],
];
}
if ($rows === []) {
return $this->none('이 확장은 `componentPalette` 를 선언하지 않습니다 — 편집기 팔레트에 추가되는 항목이 없습니다.');
}
return $this->table(['그룹', '종류', '컴포넌트 수'], $rows);
}
/**
* 샘플 데이터 ID 와 페이지 상태 변종을 렌더합니다.
*
* 이 두 축은 편집기 캔버스가 실제 API 없이 화면을 그릴 때 쓰는 값입니다. 레이아웃의
* `data_sources` ID 와 어긋나면 편집기 프리뷰만 빈 화면이 되는데, 실제 화면은 정상이라
* 어긋남이 드러나지 않습니다.
*
* @param array<string, mixed> $ctx 수집 컨텍스트
* @return string 마크다운
*/
private function renderEditorSpecSamples(array $ctx): string
{
$spec = $ctx['editorSpec'] ?? null;
if (! is_array($spec)) {
return $this->none('편집기 스펙을 수집하지 못했습니다.');
}
// 스펙이 없어도 **미커버 목록은 낸다.** 스펙이 없는 확장이야말로 프리뷰가 비는
// 자리를 가질 가능성이 크고, 여기서 조기 반환하면 정작 필요한 확장에서 그 목록이
// 통째로 사라진다 — 그런데 결과는 "빈 자리가 없다" 와 구분되지 않는다.
$sections = [];
if (($spec['present'] ?? false) === true) {
// 세 자리를 한 행으로 합치지 않는다 — `data_sources` ID 로 붙는 샘플과 엔드포인트
// 패턴으로 붙는 샘플은 어긋났을 때 고칠 자리가 다르고, 페이지 상태는 ID 가 아니라
// 적용 범위(라우트/베이스 레이아웃)로 식별된다.
$rows = [];
foreach ([
['sampleData.byDataSourceId', $spec['sampleDataIds']],
['sampleData.byEndpointPattern', $spec['sampleEndpointPatterns']],
['states.groups', $spec['stateScopes']],
] as [$label, $ids]) {
$declared = ($spec['declaredPaths'][$label] ?? false) === true;
$rows[] = [
$this->code($label),
$this->editorSpecBlockRole($label),
$declared ? (string) count($ids) : '미선언',
$declared ? $this->idListCell($ids) : '-',
];
}
$sections[] = $this->table(['자리', '역할', '개수', 'ID'], $rows);
} else {
$sections[] = $this->none('이 확장은 편집기 스펙을 두지 않아 선언된 샘플 데이터·페이지 상태가 없습니다.');
}
$uncovered = $spec['uncovered'] ?? [];
if ($uncovered === []) {
$sections[] = $this->none('이 확장 레이아웃의 `data_source` 는 전부 프리뷰 샘플이 붙습니다 (이 확장 또는 번들 템플릿 스펙이 커버).');
} else {
$sections[] = '**프리뷰 샘플이 없는 `data_source` '.count($uncovered).'개** — 편집기 캔버스에서 이 자리만 빈 화면이 됩니다. 실제 화면은 정상이라 오류도 경고도 남지 않습니다.'
."\n\n".$this->idListCell($uncovered, 20);
}
return implode("\n\n", $sections);
}
/**
* 편집기 스펙을 함께 고쳐야 하는 변경과 그 절차를 렌더합니다.
*
* 이 표가 없으면 확장에 화면 요소를 추가해도 편집기 팔레트에 나타나지 않는 상태가
* 오류도 경고도 없이 남습니다 — 편집기는 선언되지 않은 컴포넌트를 "없는 것" 으로
* 다룰 뿐 실패를 보고하지 않습니다.
*
* @param array<string, mixed> $ctx 수집 컨텍스트
* @return string 마크다운
*/
private function renderEditorSpecObligations(array $ctx): string
{
$record = $ctx['record'];
$spec = $ctx['editorSpec'] ?? null;
$hasSpec = is_array($spec) && ($spec['present'] ?? false) === true;
$update = "php artisan {$record['type']}:update {$record['id']} --force";
$rows = [
['컴포넌트를 새로 만들었다', '`componentPalette` 에 항목 추가 · `componentCapabilities` 에 편집 역량 선언 · `nesting` 에 담길 자리 규정'],
['레이아웃에 `data_sources` 를 추가했다', '`sampleData` 에 같은 ID 로 프리뷰 응답 추가 (없으면 편집기 캔버스만 빈 화면)'],
['`_global.*` 을 새로 읽는다', '`sampleGlobal` 에 baseline 값 추가'],
['빈 목록·오류 같은 화면 변종을 추가했다', '`states` 에 변종 추가 · `stateLabels` 에 친화 명칭'],
['새 액션·조건 패턴을 도입했다', '`actionRecipes` / `conditionRecipes` 에 친화 명칭 등록'],
];
$table = $this->table(['이런 변경을 했다면', '편집기 스펙에서 함께 할 일'], $rows);
if (! $hasSpec) {
// 스펙이 없는 확장에도 이 표를 남긴다. 지금은 해당 없음이지만, 위 사건 중 하나가
// 일어나는 순간 스펙을 **신설**해야 한다는 것이 이 문서가 전할 내용이다.
return $this->none('이 확장은 아직 편집기 스펙을 두지 않습니다. 아래 변경이 생기면 `editor-spec.json` 을 신설합니다.')
."\n\n".$table;
}
// `_bundled` 편집분은 update 커맨드로 활성 디렉토리에 반영된 뒤에만 편집기에 보인다
// (`EditorSpecAssembler` 는 활성 디렉토리만 합본한다 — `_bundled` 폴백이 없다).
return $table."\n\n"
.'편집기 스펙은 JSON 이므로 빌드가 필요 없습니다. 다만 편집기 서빙은 **활성 디렉토리만** 읽으므로(`_bundled` 폴백 없음) 편집 후 반드시 반영합니다:'
."\n\n```bash\n".$update."\n```";
}
// -----------------------------------------------------------------------
// 마크다운 유틸
// -----------------------------------------------------------------------