Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cf8f02bfca | |||
| 92aa4f19c7 | |||
| 3708ca3521 | |||
| 7bf16bfeee | |||
| 0eb056e6b5 | |||
| ed7f6189eb | |||
| 689edeaf24 | |||
| 13439a384f | |||
| a5b0f07f2a | |||
| 7e7eb1be15 | |||
| 2d6afaf665 | |||
| 31eaa9343a | |||
| 032372bb01 | |||
| 176568f976 | |||
| 6a9a7939b2 | |||
| 894acbb6a1 | |||
| 899a1ba1a6 | |||
| f385966f87 | |||
| c4d46a5de3 | |||
| 2caffe9950 | |||
| 8757809928 | |||
| 39c64e3acd | |||
| df5786e418 | |||
| 76889080e8 | |||
| 68c8c8ff15 | |||
| 9b8fbd6360 | |||
| 8ada2d1947 | |||
| 1a405a54fa | |||
| 5c23cf3873 | |||
| cc2b3039a3 | |||
| 0561c5d63c | |||
| e6c897a863 | |||
| 39318dd40d | |||
| be80f9339b | |||
| df41aac2b1 | |||
| a620ff970a | |||
| 524abda49c | |||
| fe62656d37 | |||
| 8ad3a9e677 | |||
| e9a87773ea | |||
| 678b081364 | |||
| 46a9c5c83d | |||
| 6c86e1cf85 | |||
| a16541e90d | |||
| aaea43f2cc | |||
| 3f7bf3f1c8 | |||
| bc29faf60c | |||
| 4b9627d4ee | |||
| 26a3b43d28 | |||
| a476756a6c | |||
| 6ff27295e6 | |||
| 8d5501d927 | |||
| cd8ae32203 | |||
| 7110db8a4a | |||
| 7b36e14b65 | |||
| 32a760dd9a | |||
| 3d2f1dc8d4 | |||
| a957401a59 | |||
| 9cc5db5d28 | |||
| 16da17e533 | |||
| 8205215c17 | |||
| 36514286aa | |||
| cc271abedb | |||
| 8297002dc5 | |||
| 25ed57da53 | |||
| 90e410f49e | |||
| 14a3d32480 | |||
| 19b8becc30 |
@@ -0,0 +1,37 @@
|
||||
name: Auto Label PR
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
jobs:
|
||||
add-automerge-label:
|
||||
runs-on: [macos, host]
|
||||
steps:
|
||||
- name: Add 'automerge' label to PR
|
||||
env:
|
||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||
GITEA_BASE_URL: https://gitea.jaybe.dev
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${CI_TOKEN:-}" ]; then
|
||||
echo "CI_TOKEN not set; skipping labeling"; exit 0; fi
|
||||
OWNER=$(echo "$REPO" | cut -d'/' -f1)
|
||||
NAME=$(echo "$REPO" | cut -d'/' -f2)
|
||||
echo "Resolving existing label id for 'automerge' in $OWNER/$NAME (no creation)"
|
||||
curl -sS -o /tmp/labels.json -H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/labels?limit=1000" || true
|
||||
# Extract all ids whose name == automerge, prefer the smallest id (oldest)
|
||||
LID=$(tr '\n' ' ' < /tmp/labels.json | \
|
||||
grep -o '"id":[0-9][0-9]*[^\}]*"name":"automerge"' | \
|
||||
sed -E 's/.*"id":([0-9]+).*/\1/' | sort -n | head -n1 || true)
|
||||
if [ -z "${LID:-}" ]; then
|
||||
echo "No existing 'automerge' label found; skipping labeling"; exit 0; fi
|
||||
echo "Labeling PR #$PR_NUMBER with id $LID"
|
||||
curl -sS -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/issues/${PR_NUMBER}/labels" \
|
||||
-d '{"labels":['"${LID}"']}' || true
|
||||
@@ -0,0 +1,76 @@
|
||||
name: Auto PR
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'feat/**'
|
||||
|
||||
jobs:
|
||||
open-pr:
|
||||
runs-on: [macos, host]
|
||||
steps:
|
||||
- name: Create Pull Request via Gitea API
|
||||
env:
|
||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||
GITEA_BASE_URL: https://gitea.jaybe.dev
|
||||
REPO: ${{ github.repository }}
|
||||
HEAD_BRANCH: ${{ github.ref_name }}
|
||||
BASE_BRANCH: main
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${CI_TOKEN:-}" ]; then
|
||||
echo "GITEA_TOKEN not set; skipping auto-pr"; exit 0; fi
|
||||
OWNER=$(echo "$REPO" | cut -d'/' -f1)
|
||||
NAME=$(echo "$REPO" | cut -d'/' -f2)
|
||||
TITLE="auto: PR for $HEAD_BRANCH"
|
||||
BODY="Automated PR created on push to $HEAD_BRANCH"
|
||||
echo "Creating PR $HEAD_BRANCH -> $BASE_BRANCH for $OWNER/$NAME"
|
||||
HTTP_CODE=$(curl -sS -o /tmp/pr_resp.json -w "%{http_code}" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/pulls" \
|
||||
-d "{\"head\":\"${HEAD_BRANCH}\",\"base\":\"${BASE_BRANCH}\",\"title\":\"${TITLE}\",\"body\":\"${BODY}\"}") || true
|
||||
echo "API status: $HTTP_CODE"
|
||||
if [ "$HTTP_CODE" = "201" ]; then
|
||||
echo "PR created"; cat /tmp/pr_resp.json
|
||||
PR_NUMBER=$(cat /tmp/pr_resp.json | sed -n 's/.*"number":\([0-9]*\).*/\1/p' | head -n1)
|
||||
else
|
||||
echo "PR not created (possibly exists). Response:"; cat /tmp/pr_resp.json || true
|
||||
fi
|
||||
|
||||
# Retry to resolve PR number by listing open PRs and matching head/base
|
||||
i=0
|
||||
while [ -z "${PR_NUMBER:-}" ] && [ $i -lt 10 ]; do
|
||||
i=$((i+1))
|
||||
echo "[retry $i] Resolving PR number for $HEAD_BRANCH -> $BASE_BRANCH"
|
||||
curl -sS -o /tmp/pr_list.json -H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/pulls?state=open" || true
|
||||
# Extract PR number matching head.ref==HEAD_BRANCH and base.ref==BASE_BRANCH
|
||||
PR_NUMBER=$(awk -v hb="$HEAD_BRANCH" -v bb="$BASE_BRANCH" 'BEGIN{RS="},"; pr=""} {
|
||||
if($0 ~ /\"head\":\{[^}]*\"ref\":\"" hb "\"/ && $0 ~ /\"base\":\{[^}]*\"ref\":\"" bb "\"/){
|
||||
if (match($0, /\"number\":([0-9]+)/, m)) { print m[1]; exit }
|
||||
}
|
||||
}' /tmp/pr_list.json)
|
||||
if [ -z "${PR_NUMBER:-}" ]; then sleep 2; fi
|
||||
done
|
||||
|
||||
if [ -n "${PR_NUMBER:-}" ]; then
|
||||
echo "Resolving existing label id for 'automerge' in $OWNER/$NAME (no creation)"
|
||||
curl -sS -o /tmp/labels.json -H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/labels?limit=1000" || true
|
||||
LID=$(tr '\n' ' ' < /tmp/labels.json | \
|
||||
grep -o '"id":[0-9][0-9]*[^\}]*"name":"automerge"' | \
|
||||
sed -E 's/.*"id":([0-9]+).*/\1/' | sort -n | head -n1 || true)
|
||||
if [ -n "${LID:-}" ]; then
|
||||
echo "Adding 'automerge' (id=$LID) label to PR #$PR_NUMBER"
|
||||
curl -sS -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/issues/${PR_NUMBER}/labels" \
|
||||
-d '{"labels":['"${LID}"']}' || true
|
||||
else
|
||||
echo "No existing 'automerge' label found; skipping label add"
|
||||
fi
|
||||
else
|
||||
echo "PR number could not be determined; skipping label add"
|
||||
fi
|
||||
@@ -42,3 +42,41 @@ jobs:
|
||||
path: playwright-report
|
||||
if-no-files-found: ignore
|
||||
retention-days: 3
|
||||
|
||||
- name: Auto-merge PR on green
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
env:
|
||||
CI_TOKEN: ${{ secrets.CI_TOKEN }}
|
||||
GITEA_BASE_URL: https://gitea.jaybe.dev
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${CI_TOKEN:-}" ]; then
|
||||
echo "CI_TOKEN not set; skipping auto-merge"; exit 0; fi
|
||||
OWNER=$(echo "$REPO" | cut -d'/' -f1)
|
||||
NAME=$(echo "$REPO" | cut -d'/' -f2)
|
||||
echo "Checking labels for PR #$PR_NUMBER on $OWNER/$NAME"
|
||||
LABELS_JSON=$(curl -sS -X GET \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/issues/${PR_NUMBER}")
|
||||
echo "labels payload (first 200 chars):"; echo "$LABELS_JSON" | cut -c1-200 || true
|
||||
if ! echo "$LABELS_JSON" | grep -qi '"name":"automerge"'; then
|
||||
echo "Label 'automerge' not present; skipping merge"; exit 0; fi
|
||||
echo "Label 'automerge' present; proceeding to merge"
|
||||
# ensure PR is open
|
||||
PR_JSON=$(curl -sS -X GET \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/pulls/${PR_NUMBER}")
|
||||
STATE=$(echo "$PR_JSON" | sed -n 's/.*"state":"\([^"]*\)".*/\1/p')
|
||||
echo "PR state: ${STATE:-unknown}"
|
||||
if [ "${STATE:-}" != "open" ]; then
|
||||
echo "PR state is not open; skipping merge"; exit 0; fi
|
||||
echo "Merging PR #$PR_NUMBER for $OWNER/$NAME"
|
||||
HTTP_CODE=$(curl -sS -o /tmp/merge_resp.json -w "%{http_code}" -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
"${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${NAME}/pulls/${PR_NUMBER}/merge" \
|
||||
-d '{"Do":"merge","MergeMessage":"auto-merge: CI green"}' || true)
|
||||
echo "merge http: $HTTP_CODE"
|
||||
echo "merge resp:"; cat /tmp/merge_resp.json || true
|
||||
|
||||
@@ -39,3 +39,4 @@ yarn-error.log*
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
MAIN_PLAN.md
|
||||
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
# 메인플랜: 랜딩 페이지 빌더
|
||||
|
||||
## 목표
|
||||
- 비개발자도 사용 가능한 단일 페이지 랜딩 페이지 빌더.
|
||||
- 결과물: 정적 ZIP(HTML/CSS/JS) 다운로드. 이미지: 외부 URL 또는 로컬 업로드(서버 저장 없음, ZIP에 패키징). 폰트는 외부 CDN 허용.
|
||||
- 폼: 다양한 필드 타입(파일 업로드 제외), 커스텀 name, action URL 설정. action 미지정 시 Google Sheets 저장.
|
||||
- 다국어 지원(i18n), 접근성 준수, SEO/OG 메타, 분석 스니펫 삽입.
|
||||
|
||||
## 확정 요구사항
|
||||
- 단일 페이지 기준.
|
||||
- 이미지: 외부 URL 또는 로컬 업로드 허용(서버 저장 없음, ZIP 패키징). CDN 허용(예: Google Fonts 등).
|
||||
- 폼 필드 타입: 텍스트/이메일/전화/셀렉트/라디오/체크박스/텍스트에어리어/날짜 등(파일 업로드는 추후).
|
||||
- 검증 규칙 필요. 스팸 방지: 기본(honeypot, 제출지연 타임스탬프).
|
||||
- 제출 경로: 1) 사용자가 action URL 지정 → 2) 미지정 시 Google Sheets.
|
||||
- 기본: Google Apps Script 웹앱 템플릿 가이드 제공(사용자 배포 URL 사용)。
|
||||
- 대안: 서비스계정 + Google Sheets API(선택).
|
||||
- 다국어 지원 필요. 접근성 준수. SEO/OG 포함. 분석 스니펫 삽입 기능 필요.
|
||||
- 스택: React 기반. Next.js(App Router) + TS + Tailwind + shadcn/ui 권장.
|
||||
|
||||
## 아키텍처 개요
|
||||
- 빌더 앱: Next.js(App Router, TS), Tailwind, shadcn/ui, dnd-kit, Zustand.
|
||||
- 도메인 스키마: Page → Section[] → Block[] → Form(fields, validation, actionUrl) → Theme.
|
||||
- 에셋 매니저: 사용자가 업로드한 이미지를 메모리/브라우저에서 관리, 파일명 해싱 후 `assets/` 경로로 참조 재작성.
|
||||
- HTML Exporter: JSON 스키마 → 정적 HTML/CSS/JS 생성. 로컬 업로드 이미지는 `assets/`로 참조, 외부 URL은 그대로 유지.
|
||||
- 제출 경로: action 사용 또는 Google Sheets(기본 Apps Script 템플릿 제공).
|
||||
- i18n: next-intl. a11y: Testing Library + axe-core 스모크. SEO/OG 메타 생성.
|
||||
- 내보내기: ZIP(브라우저 JSZip 우선). 필요 시 서버(API Route) 대안 제공. 로컬 업로드 이미지는 ZIP 내 `assets/` 폴더에 파일로 포함.
|
||||
|
||||
## UI/UX 리디자인 계획(합의안)
|
||||
- **정보 구조(3패널)**
|
||||
- 좌: 컴포넌트 패널(Hero/FAQ/CTA + Form 프리셋)
|
||||
- 중: 캔버스(dnd-kit, 섹션/필드 배치·정렬·삭제)
|
||||
- 우: 인스펙터(선택 요소 속성/검증/스타일 편집)
|
||||
- **상단 툴바**: 언어, 테마, 프리셋, Export ZIP
|
||||
- **프리뷰**: 실시간 렌더, 반응형 뷰포트 토글
|
||||
- **계약 고정**: 스키마(섹션/폼/검증), 상태 인터페이스, Exporter 입·출력
|
||||
|
||||
### 단계별 TDD 진행
|
||||
1) 레이아웃 스캐폴딩(shadcn/ui) + 접근성 라벨링 테스트
|
||||
2) dnd 캔버스 1차: 섹션 드래그 정렬/삭제 테스트 → 최소 구현
|
||||
3) 인스펙터 1차: 선택 섹션/필드 기본 속성 편집 테스트 → 연동
|
||||
4) 컴포넌트 패널: 카드 추가(섹션/필드 프리셋) 테스트 → 드래그 추가
|
||||
5) 프리뷰 강화: 실시간 반영/뷰포트 토글 스모크 테스트
|
||||
|
||||
### 현재 상태(MVP)
|
||||
- 섹션 추가/삭제, 폼 필드 구성(옵션/필수/패턴/최대길이), i18n, ZIP Export, 로컬 에셋 포함 동작 확인
|
||||
- Next.js 16: `middleware` → `proxy` 마이그레이션 완료
|
||||
- dnd 상호작용 테스트 및 구현 안정화(정렬/삭제 버튼 폴백 포함)
|
||||
- 섹션 프리셋 확장: Features/Testimonials 카드 추가 및 프리뷰/Exporter 스텁 반영 완료
|
||||
- SEO/Analytics/OG 인스펙터 추가 및 프리뷰 반영
|
||||
- Exporter: og:image 메타 태그 반영 및 테스트 추가
|
||||
- a11y: jest-axe 스모크 테스트 통과(FormBuilderPanel), dnd-kit 라이브 리전/안내 존재 검증
|
||||
- 라벨-id 매핑 강화(중앙 입력/인스펙터/FAQ/CTA/Features/Testimonials)
|
||||
- 프리뷰 뷰포트 토글(Desktop/Mobile) + localStorage 영속화
|
||||
- Features/Testimonials 인스펙터 편집 UI(리스트 추가/삭제/편집) + 테스트
|
||||
- Exporter 타입 보강(any 제거) 및 CSS 보강(Features/Testimonials)
|
||||
- E2E(Playwright):
|
||||
- 기본 플로우(섹션 추가→편집→프리뷰→Export 클릭)
|
||||
- dnd 키보드 폴백(Up/Down) 재정렬
|
||||
- SEO/Analytics/OG 프리뷰 반영 검증
|
||||
- Export ZIP 메타(SEO/OG/Analytics) 검증(테스트 훅 사용)
|
||||
- 프리뷰 뷰포트 토글(aria-pressed/키보드 접근) 검증
|
||||
|
||||
### a11y/반응형 정책(Exporter)
|
||||
- 문서 내비게이션: skip link, `<main id="main" role="main">` 적용
|
||||
- 섹션 식별: `aria-labelledby` + 섹션 헤딩 id(features/testimonials/faq)
|
||||
- 이미지 대체텍스트: hero img `alt` = heading 파생
|
||||
- 포커스 표시: 포커스 가능한 요소 outline 표시
|
||||
- 반응형: 모바일 컨테이너 패딩 축소, grid 자동 칼럼, `prefers-reduced-motion` 준수
|
||||
|
||||
### 최근 보강 내역(접근성/테스트)
|
||||
- 인스펙터 입력에 `aria-describedby` 연결(SEO/Analytics/OG/Hero/CTA)
|
||||
- SEO/Analytics/OG/Hero/CTA/FAQ 헬프텍스트 추가
|
||||
- Exporter 구조 스냅샷 강화: `<main>` 내부 섹션/폼 포함 검증
|
||||
- Exporter CSS 토큰 스냅샷: skip-link/focus outline/반응형/모션 감소 토큰 존재 검증
|
||||
- Features/Testimonials `aria-labelledby`/헤딩 id 일치 검증 추가
|
||||
- Exporter 헤딩 레벨 일관성 전수 테스트(hero=h1, others=h2, FAQ=h3) 추가
|
||||
- Exporter 색상/타이포그래피 토큰 스모크 테스트 추가
|
||||
- Exporter(Form): helptext ↔ aria-describedby 연결 TDD 완료
|
||||
- 각 필드 `id=field-<name>`와 `<label for>` 연결
|
||||
- `help`가 있을 경우 `id=field-<name>-help` 요소 생성 및 컨트롤에 `aria-describedby` 부여
|
||||
- 라디오 그룹은 `fieldset`에 `aria-describedby` 적용, 옵션별 `id/htmlFor` 연결
|
||||
- next-intl 기본 timeZone 설정: `Asia/Seoul`로 ENVIRONMENT_FALLBACK 경고 제거
|
||||
- a11y 색/폰트 최소 기준 스모크(본문 컬러/폰트 패밀리/모바일 h1 폰트 크기) 추가
|
||||
- CTA 섹션에 `aria-labelledby` + `<h2 id="cta-heading">` 추가(헤딩 레벨 일관성)
|
||||
- 전체 테스트 그린(유닛/컴포넌트/E2E)
|
||||
- Inspector a11y 스모크: SEO/Analytics/OG 입력과 헬프텍스트의 `aria-describedby` 연결 검증
|
||||
- Exporter CSS 스모크: 본문 텍스트 컬러/포커스 outline/모바일 h1 폰트 크기/MQ 토큰 존재 검증
|
||||
- FAQ 인스펙터 Q/A 입력 `aria-describedby`(ins-faq-help) 연결 보강
|
||||
- Inspector 키보드 UX 스모크: Features/Testimonials 항목 추가( Space/Enter ) 검증 추가
|
||||
- Inspector 키보드 UX 스모크: Features/Testimonials 항목 삭제(Remove) Enter/Space 검증 추가
|
||||
- 인스펙터 Remove 버튼 키보드 처리(onKeyDown/onKeyUp) 반영
|
||||
- Exporter 회귀 스냅샷: heading/ARIA/반응형 토큰 통합 검증 추가
|
||||
- Preview 토글 ARIA 회귀 스냅샷(Desktop/Mobile: aria-pressed/controls/describedby)
|
||||
- Exporter CSS 토큰 회귀 확대(:root --primary, body font, skip-link base/focus, focus outline, reduced-motion)
|
||||
- 컴포넌트 i18n 회귀 스냅샷(en/ko 주요 라벨/버튼 키 존재)
|
||||
- 섹션 a11y 자동 검증 템플릿(testUtils/sectionA11y) 도입 및 템플릿 테스트 추가
|
||||
- 신규 섹션 추가: Benefits
|
||||
- 스키마 확장(`benefits`): props.items:string[]
|
||||
- Exporter 렌더 추가: `<section class="benefits" aria-labelledby>`, `<h2 id="benefits-heading">`, 리스트 렌더
|
||||
- 테스트: sections.benefits.test.ts (h2/aria-labelledby/리스트 아이템 검증)
|
||||
- 섹션 회귀 스냅샷(benefits 포함) 보강: sections.regression.benefits.test.ts 추가(ARIA/헤딩/리스트 구조 전수 검증)
|
||||
- 섹션 회귀 스냅샷(CTA/Testimonials): sections.regression.cta-testimonials.test.ts 추가(figure/blockquote/figcaption, CTA 링크 클래스/URL 검증)
|
||||
- 섹션 회귀 스냅샷(Features/FAQ): sections.regression.features-faq.test.ts 추가(리스트/클래스/아이템 수 검증)
|
||||
- Exporter 이스케이프 회귀: sections.escape.regression.test.ts 추가(특수문자 <, >, &, ") 안전 이스케이프 검증)
|
||||
- 인스펙터 a11y 자동 체크 헬퍼 도입: components/testUtils/inspectorA11y.ts + 템플릿 테스트 2종(InspectorA11y.template/sections)
|
||||
- i18n 회귀 확장: Sidebar Add 버튼군(en/ko) 라벨 스모크(i18n.sidebar.actions.test.tsx)
|
||||
- E2E 스모크: 프리뷰/Export 마커(heading/ARIA/반응형 CSS) 존재 검증 추가
|
||||
- SEO description 기본값 설정으로 Export 스키마 안정화
|
||||
- 프리뷰 토글 버튼에 `aria-controls="preview-container"` 추가로 제어 영역 명시
|
||||
- 프리뷰 토글에 sr-only 설명 추가 및 두 토글 버튼 `aria-describedby` 연결
|
||||
- SectionCanvas 제어 버튼 `aria-label` 스모크(Select/Up/Down/Remove) 추가
|
||||
- CSS focus-visible 토큰 스모크(3px solid + HEX 컬러) 추가
|
||||
- 인스펙터 Add 버튼 title 보조 힌트 추가(Features/Testimonials/FAQ) 및 일관성 테스트
|
||||
- SectionCanvas 버튼 title/aria-label 일관성 스모크
|
||||
- 전역 버튼 네이밍 일관성 보강: Inspector Add/Remove 및 SectionCanvas Select/Up/Down/Remove의 title/aria-label 일치 확인 및 스모크 완료
|
||||
- a11y 커버리지 최종 점검: 전 섹션 인스펙터 입력 aria-describedby 연결 확인(체크리스트 충족)
|
||||
|
||||
### 다음 작업(계획)
|
||||
- Exporter 헤딩 레벨 일관성 테스트: hero는 h1, 나머지 섹션은 h2, FAQ 항목은 h3 검증
|
||||
- a11y 색/폰트 최소 기준 스모크: 대비/폰트크기 관련 CSS 토큰/규칙 존재 여부 스냅샷
|
||||
|
||||
### Inspector a11y 커버리지 체크리스트
|
||||
- [x] Hero: `Hero Heading` 입력 `aria-describedby` → `ins-hero-heading-help`
|
||||
- [x] CTA: `CTA Text`/`CTA Href` 입력 `aria-describedby` → `ins-cta-text-help`/`ins-cta-href-help`
|
||||
- [x] FAQ: `FAQ Q n`/`FAQ A n` 입력 `aria-describedby` → `ins-faq-help`
|
||||
- [x] Features: `Feature n` 입력 `aria-describedby` → `ins-features-help`
|
||||
- [x] Testimonials: `Author n`/`Quote n` 입력 `aria-describedby` → `ins-testimonials-help`
|
||||
- [x] Preview 토글: sr-only 설명(`preview-toggle-help`)과 버튼 `aria-describedby` 연결, `aria-controls="preview-container"`
|
||||
|
||||
### CI/테스트 실행
|
||||
- 유닛/컴포넌트: `npm test` (Vitest)
|
||||
- E2E: `npm run test:e2e` (Playwright)
|
||||
- 로컬 개발 서버는 Playwright 설정에서 자동 기동(webServer: `npm run dev`)
|
||||
- GitHub Actions 워크플로: `.github/workflows/ci.yml`
|
||||
- Node 20 + `npm ci`
|
||||
- Vitest 실행 → Playwright 브라우저 설치(`npx playwright install --with-deps`) → E2E 실행
|
||||
|
||||
### CI 최종 점검
|
||||
- main/master 브랜치 푸시/PR 시 워크플로 자동 실행 확인
|
||||
- 새로 추가된 테스트(헤딩 레벨 전수, 색/폰트 스모크) CI 통합 확인
|
||||
- 작업 브랜치 푸시 완료: `chore/ci-verify-a11y-headings` (원격: origin)
|
||||
- PR 생성 및 Actions 결과 기록 예정(base: main)
|
||||
- CI verification note: 러너 온라인 이후, 사소 변경으로 CI 트리거 검증 예정
|
||||
- CI rerun: 워크플로 재실행용 ping 커밋
|
||||
|
||||
### PR/CI 결과(2025-11-14)
|
||||
- PR: feat/ci-verify-run → main 머지 완료
|
||||
- CI: Vitest + Playwright 전부 그린
|
||||
- E2E 추가: Exported page skip-link focus 표시 회귀 테스트 포함
|
||||
- 워크플로: self-hosted runner [macos, host], Playwright 보고서 업로드 아티팩트 활성화
|
||||
- 제안: 다음 릴리스 태그(v0.2.0)로 회귀 커버리지/Benefits 섹션 추가 반영
|
||||
|
||||
#### 결과: CI 통과 (self-hosted Gitea Actions)
|
||||
- PR: https://gitea.jaybe.dev/jaybe/landing-builder/pulls/2
|
||||
- 러너: self-hosted, labels: [macos, host]
|
||||
- 테스트: Unit/Component + E2E 총 7/7 green
|
||||
- 수정 요약(E2E 포커스):
|
||||
- 초기 포커스 선점 방지: `body` 클릭으로 포커스 부여
|
||||
- 스킵링크 등 선행 포커서블 회피: Desktop 버튼에 명시적 `focus()`
|
||||
- 키보드 시나리오: Tab → Mobile 포커스 확인 → Space로 토글 → Shift+Tab → Enter
|
||||
|
||||
##### 추가 CI 결과(2025-11-14)
|
||||
- E2E a11y 스모크 추가: 포커스 아웃라인(3px solid, 브랜드 컬러), 스킵링크 탭 순서(main 포커스 이동)
|
||||
- Exporter JS에 스킵링크 클릭 시 `#main`에 `tabindex="-1"` 부여 후 `focus()` 처리 → CI 그린 통과
|
||||
|
||||
#### 머지 상태
|
||||
- 머지 방식: Squash and merge
|
||||
- 브랜치 정리: `feat/ci-verify-run` 삭제 완료
|
||||
|
||||
### 다음 스프린트 후보 과제
|
||||
- Exporter 회귀 스냅샷 보강(폼 토큰/검증 토큰 범위 확대)
|
||||
- 인스펙터 신규 섹션 추가 시 a11y 베이스라인 재사용 가이드 마련
|
||||
- 버튼 네이밍 일관성 전수 스캔 스모크 범위 확대
|
||||
- node 20 + npm ci
|
||||
- Vitest 실행 → Playwright 브라우저 설치 → E2E 실행
|
||||
|
||||
## 마일스톤
|
||||
1. 스캐폴딩 및 테스트 환경 구성
|
||||
2. 스키마 정의(Zod) 및 HTML Exporter TDD
|
||||
3. 컴포넌트/상태관리(Zustand) 및 인스펙터 기본 기능
|
||||
4. 접근성/키보드 네비게이션 강화 및 테스트 안정화
|
||||
5. CI/CD(Self-hosted Gitea) 연동 및 그린 검증
|
||||
|
||||
## 릴리스
|
||||
### v0.1.0
|
||||
- CI 검증 완료(Self-hosted Gitea runner, labels: [macos, host])
|
||||
- E2E 안정화: 초기 포커스 이슈 제거(Desktop 명시 focus), 스킵링크 고려
|
||||
- Exporter(Form) a11y: helptext ↔ aria-describedby, id/htmlFor 연결, 라디오 fieldset 설명 연결
|
||||
- i18n: en/ko 중첩 구조, 누락 키 보강(builder.action.*, builder.form.*)
|
||||
- next-intl: 기본 timeZone=Asia/Seoul 설정으로 ENVIRONMENT_FALLBACK 경고 제거
|
||||
- 태그: v0.1.0
|
||||
|
||||
## 접근성 베이스라인 가이드(신규 섹션/인스펙터 적용 규칙)
|
||||
- **레이블 연결**: 모든 입력은 `id=ins-...` 또는 `id=field-...` 부여, `<label for>`로 연결
|
||||
- **헬프텍스트 연결**: 헬프 요소 `id=...-help` 생성, 입력에 `aria-describedby`로 연결
|
||||
- **라디오 그룹**: 개별 `<input>` 대신 `<fieldset>`에 `aria-describedby` 적용, 옵션은 `id/htmlFor`로 연결
|
||||
- **버튼 네이밍**: 보이는 텍스트 또는 `aria-label`로 안정적 접근 가능한 이름 제공
|
||||
- **키보드 활성화**: Enter/Space 활성(onClick와 동일 동작), `focus-visible` 스타일 유지
|
||||
- **스킵링크**: `<a class="skip-link">` 제공, 포커스 시 화면 내 표시
|
||||
- **헤딩 레벨**: hero=h1, 1뎁스 섹션=h2, FAQ 항목=h3 일관성 유지
|
||||
- **미리보기 토글**: 토글 버튼에 `aria-pressed`, `aria-controls`, `aria-describedby` 연결
|
||||
- **i18n 키**: 중첩 객체 구조, 신규 키 추가 시 en/ko 동시 보강
|
||||
- **테스트 원칙**: TDD로 유닛/컴포넌트/E2E 및 스냅샷 추가. 포커스/ARIA/토큰 스모크 포함
|
||||
|
||||
### 적용 가이드(신규 섹션 추가 시)
|
||||
- **1) 섹션 구현**: `<section class="<name>" aria-labelledby="<name>-heading">`와 `<h2 id="<name>-heading">` 구성
|
||||
- **2) 인스펙터 입력**: `id=ins-...`, `<label for>`, 헬프텍스트 `...-help` + `aria-describedby` 연결
|
||||
- **3) Exporter 반영**: 섹션 렌더 함수에 위 구조/속성 부여
|
||||
- **4) 테스트 추가**:
|
||||
- 공통 템플릿 사용: `lib/exporter/testUtils/sectionA11y.ts` → `assertSectionA11y(html)`
|
||||
- 샘플: `lib/exporter/sectionA11y.template.test.ts` 참고하여 새 섹션 추가해 검증
|
||||
- 필요 시 개별 스냅샷/스모크: 헤딩/ARIA/키보드/토큰 추가 검증
|
||||
|
||||
## 다음 단계(E2E 초안)
|
||||
- 시나리오: 섹션 추가(Hero/FAQ/Features/Testimonials/CTA) → 인스펙터 편집 → Export ZIP 생성 → HTML 메타/섹션/폼 렌더 확인
|
||||
- 환경: Playwright
|
||||
- 체크리스트:
|
||||
- 섹션 추가/정렬/삭제 동작
|
||||
- 인스펙터 편집 반영(미리보기/Export HTML)
|
||||
- i18n 라벨 안정성(data-testid 사용)
|
||||
- a11y 스모크 무결성 유지
|
||||
|
||||
## TDD 전략
|
||||
- 각 기능 단위로: 실패 테스트 작성 → 최소 구현 → 리팩터 → 커버리지 확인.
|
||||
- 단위: Vitest + Testing Library + jsdom. E2E: Playwright.
|
||||
- 접근성: axe-core 스모크 테스트.
|
||||
|
||||
## 작업 보드(요약)
|
||||
- 스키마/도메인(Zod)
|
||||
- HTML Exporter
|
||||
- 에셋 매니저
|
||||
- 폼 엔진
|
||||
- Sheets 연동
|
||||
- 빌더 UI
|
||||
- 내보내기 ZIP
|
||||
- i18n
|
||||
- a11y/SEO/OG/Analytics
|
||||
|
||||
## 오류/버그 기록
|
||||
- [2025-11-13 22:55] BuilderClientPage 렌더 중 ref 접근 경고 / useRef.current를 렌더 중 참조하여 ESLint 경고 발생 / FormBuilderPanel 통합 시 `useRef(createFormStore())` 사용 / `useMemo(() => createFormStore(), [])`로 스토어 인스턴스 고정하고 `useSyncExternalStore`에 직접 주입하여 해결 / 렌더 중 ref 접근 금지 원칙 재확인
|
||||
- [2025-11-14 09:35] Vitest 로그에서 i18n 누락 메시지 경고 확인(en: `builder.action.addSelect/addRadio`, `builder.form.actionUrl/honeypot/minSeconds`) → `messages/en.json`에 키 존재 여부 점검 및 누락 보완 후 재실행, 모든 테스트 그린 유지
|
||||
- [2025-11-14 09:45] 프리뷰 텍스트 매칭 불안정으로 테스트 실패 → `data-testid` 기반 안정화(`preview-seo-title` 등) 및 텍스트 매칭 지점 `Title:`→`Locale:`로 조정, 전면 그린
|
||||
- [2025-11-14 20:30] E2E 실패: 스킵링크 활성화 후 main 포커스 미이동 → Exporter JS에 스킵링크 클릭 핸들러 추가(`tabindex=-1` + `focus()`) → 로컬/CI 모두 그린
|
||||
|
||||
- [2025-11-14 23:45] Gitea 라벨 중복 생성/페이로드 오류 → 워크플로 수정
|
||||
- auto-label.yml/auto-pr.yml에서 라벨 생성 로직 제거(기존 레이블만 사용)
|
||||
- 라벨 지정 시 JSON 페이로드를 `{"labels":[id]}` 형태로 고정
|
||||
- 다중 동일 라벨 존재 시 가장 작은 ID를 선택하도록 정렬 적용
|
||||
- ci.yml 자동 머지 가드: PR 라벨 조회 후 `automerge` 존재시에만 머지
|
||||
|
||||
## CI 파이프라인 자동화 결과(automerge)
|
||||
- 브랜치 푸시 → auto-pr로 PR 생성 → auto-label로 `automerge` 부여(기존 레이블만) → ci.yml에서 테스트 그린 시 자동 머지
|
||||
- 안전장치: `automerge` 라벨 없으면 머지 스킵, PR 닫힘/드래프트 시 머지 스킵
|
||||
- 진단 로그: API status/라벨 JSON 일부/머지 응답 코드 출력으로 디버그 용이성 확보
|
||||
|
||||
## 충돌 해결 기록
|
||||
- [2025-11-14 23:50] `.gitea/workflows/auto-pr.yml` main 병합 충돌 해결
|
||||
- 충돌 마커 제거, 메시지 통일: "기존 'automerge' 라벨만, 생성 금지"
|
||||
- PR 번호 해석 재시도 루프 유지 및 라벨 ID 해석 로직 안정화
|
||||
|
||||
## ZIP 검증 TDD(자산/메타)
|
||||
- 통합/메타 테스트 추가: `zip.validation.integrated.test.ts`, `zip.validation.meta.test.ts`
|
||||
- exportPage + buildZip 통합: 자산 경로 재작성 및 포함, 하위 폴더 포함 검증
|
||||
|
||||
### ZIP 검증 TDD Phase4(루트 파일/manifest)
|
||||
- 테스트: `zip.validation.phase4.test.ts`
|
||||
- ZIP 루트에 `favicon.ico` / `site.webmanifest` / `robots.txt` 포함 검증
|
||||
- `site.webmanifest` JSON 파싱 유효성 검증(잘못된 JSON 시 에러)
|
||||
- 구현: `lib/exporter/zip.ts`
|
||||
- `BuildZipInput.extras` 추가(루트 파일 수집)
|
||||
- manifest JSON 파싱 검증 로직 추가
|
||||
- 브랜치/PR: `feat/manifest-robots-auto` → CI 트리거 및 자동 머지 대상(automerge 라벨 조건)
|
||||
|
||||
### SEO/Perf 개선(TDD): theme-color, hero width/height
|
||||
- 테스트: `lib/exporter/seoPerf.themeColor.heroDims.test.ts`
|
||||
- `<meta name="theme-color" content="#0ea5e9" />` 헤드 포함 검증(page.theme.primaryColor 사용)
|
||||
- hero 이미지에 `width`/`height` 속성 존재 검증(CLS 저감)
|
||||
- 구현: `lib/exporter/html.ts`
|
||||
- `buildHead`에 theme-color 메타 추가
|
||||
- `renderHero` 이미지 태그에 width/height 기본값 추가(1200x675)
|
||||
- 브랜치/PR: `feat/seo-perf-themecolor-hero-dims` → CI 트리거 및 자동 머지 대상
|
||||
|
||||
### Export 옵션 기반(TDD): extras 오버라이드(robots/manifest)
|
||||
- 테스트: `lib/exporter/extras.overrides.test.ts`
|
||||
- robots.txt 내용 오버라이드(Disallow 경로) 반영 검증
|
||||
- manifest 필드(name/short_name/start_url/display/theme_color) 오버라이드 검증
|
||||
- 구현: `lib/exporter/extras.ts`
|
||||
- `buildExtrasForPage(page, overrides?)` 시그니처로 확장
|
||||
- `overrides.robotsText`/`overrides.manifest` 병합 적용, 기본값 유지
|
||||
- 브랜치/PR: `feat/export-options-overrides` → CI 트리거 및 자동 머지 대상
|
||||
### ZIP 검증 TDD Phase5(extras 내용 검증)
|
||||
- 테스트: `lib/exporter/zip.validation.phase5.test.ts`
|
||||
- `robots.txt` 텍스트 베이스라인 확인(`User-agent: *`)
|
||||
- `site.webmanifest` JSON 파싱 및 필수 키(`start_url`, `display`) 확인
|
||||
- 구현: 기존 `buildExtrasForPage`/`buildZip` 경로 사용(추가 구현 불필요)
|
||||
- 브랜치/PR: `feat/zip-validation-phase5` → CI 트리거 및 자동 머지 대상
|
||||
|
||||
### Export 옵션 UI 폴리시(TDD): display 드롭다운 + theme_color HEX 검증
|
||||
- 테스트: `components/ExportOptions.polish.ui.test.tsx`
|
||||
- Manifest `display` 입력이 드롭다운(select)으로 제공되고 옵션 값(`standalone`/`minimal-ui`/`browser`) 중에서만 선택됨을 검증
|
||||
- `theme_color`는 `#RGB`/`#RRGGBB` 형식의 HEX만 허용하며, 잘못된 값은 오버라이드에 반영되지 않음을 검증
|
||||
- 구현:
|
||||
- `components/BuilderClientPage.tsx`
|
||||
- `display` 입력을 `<select>`로 변경하고 옵션 추가
|
||||
- `theme_color`는 정규식 `^#([0-9a-fA-F]{3}){1,2}$` 통과 시에만 `manifestOverrideBase.theme_color`에 반영
|
||||
- 결과: 전체 테스트 그린(유닛/컴포넌트/E2E)
|
||||
- 브랜치/PR 제안: `feat/export-ui-polish` → CI 트리거 및 자동 머지 대상(automerge 라벨 조건)
|
||||
|
||||
### 폰트 최적화(TDD)
|
||||
- 테스트: `lib/exporter/font.optimization.test.ts`
|
||||
- head에 `<link rel="preconnect" href="https://fonts.googleapis.com">`, `<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>` 존재 검증
|
||||
- CSS에 `system-ui` 폴백 포함 검증
|
||||
- 구현: `lib/exporter/html.ts`
|
||||
- head에 googleapis/gstatic preconnect 추가
|
||||
- CSS body `font-family`에 system-ui 폴백 유지
|
||||
- 브랜치/PR: `feat/font-optimization` → CI 트리거 및 자동 머지 대상(automerge 라벨 조건)
|
||||
|
||||
### 폼 제출: Google Sheets 템플릿 Export 포함(TDD)
|
||||
- 테스트: `lib/exporter/sheets.template.test.ts`
|
||||
- actionUrl 미지정 시 ZIP extras에 `sheets/Code.gs`, `sheets/README.txt` 포함 검증
|
||||
- actionUrl 지정 시 extras에 포함되지 않음 검증
|
||||
- 구현: `lib/exporter/extras.ts`
|
||||
- `buildExtrasForPage(page)`로 extras 생성
|
||||
- Apps Script Code.gs/README.txt 기본 템플릿 제공
|
||||
- 브랜치/PR: `feat/form-sheets-template` → CI 트리거 및 자동 머지 대상(automerge 라벨 조건)
|
||||
|
||||
### site.webmanifest/robots.txt 자동 생성(TDD)
|
||||
- 테스트: `lib/exporter/manifest.robots.auto.test.ts`
|
||||
- extras에 `site.webmanifest`/`robots.txt` 자동 포함 검증
|
||||
- manifest 파생 키 검사(name/short_name/start_url/display/theme_color)
|
||||
- 구현: `lib/exporter/extras.ts`
|
||||
- `buildExtrasForPage(page)`에서 robots.txt/manifest 자동 생성 및 포함
|
||||
- 브랜치/PR: `feat/manifest-robots-auto` → CI 트리거 및 자동 머지 대상(automerge 라벨 조건)
|
||||
|
||||
## 의사결정 기록(ADR)
|
||||
- [YYYY-MM-DD] Next.js(App Router) 채택: 생태계/배포/서버리스/SEO 편의성.
|
||||
- [YYYY-MM-DD] Sheets 기본 방안: Apps Script 웹앱 템플릿(사용자 편의/트래픽 분산).
|
||||
- [YYYY-MM-DD] 로컬 이미지 업로드 허용: 서버 저장 없이 ZIP에 `assets/`로 패키징(브라우저 JSZip 우선).
|
||||
|
||||
- [ci] automerge 재검증용 ping (2025-11-14 21:36:38)
|
||||
|
||||
- [ci] auto-pr 라벨 자동부여 재검증 ping (2025-11-14 21:45:14)
|
||||
|
||||
- [ci] auto-label 재트리거 ping (2025-11-14 21:56:22)
|
||||
|
||||
- [ci] automerge 라벨 수동부여 후 재트리거 ping (2025-11-14 22:01:41)
|
||||
|
||||
- [ci] full auto pipeline 재검증 ping (2025-11-14 22:09:02)
|
||||
|
||||
- [ci] auto-label payload fix 재검증 ping (2025-11-14 22:15:14)
|
||||
|
||||
- [ci] auto pipeline 최종 재검증 최종 ping (2025-11-14 22:26:59)
|
||||
|
||||
|
||||
## Export ZIP 무결성 강화(Option2) 진행 현황
|
||||
|
||||
### 목표
|
||||
- Export ZIP 무결성 강화: 자산 무결성 지표와 번들 검증 체계 구축
|
||||
- CI/CD(Gitea)에서 PR 자동화, 라벨링, 조건부 머지 적용
|
||||
- 모든 개발은 TDD로 진행하고, 기능 단위 커밋/대브랜치 단위 푸쉬
|
||||
|
||||
### 브랜치 전략
|
||||
- 대범위 기능 묶음 브랜치: `feat/export-bundle-integrity`
|
||||
- 관련 기능 완료까지 로컬 커밋만 진행, 완료 시점에 일괄 푸쉬
|
||||
|
||||
### 진행 현황
|
||||
- SHA-256(base64) 무결성 구현 및 `assets.integrity.index.json` 생성
|
||||
- `assets.index.json` 그룹 정렬/경로 전략(grouped/flat) 커버리지 확장
|
||||
- `referencedAt` 추적(HTML 내 `rewriteUrl('local:...')`) 매트릭스 테스트
|
||||
- `verifyIntegrity` 유틸 구현 및 TDD(정상/변조/누락/번들해시 불일치) 통과
|
||||
- Export Options(폰트 프리커넥트/프리로드, 이미지 로딩/디코딩, robots 메타) UI/문서화
|
||||
- 브랜치 푸쉬 완료: `feat/export-bundle-integrity`
|
||||
|
||||
### TDD 계획 및 상태
|
||||
- 테스트 선작성 → 최소 구현 → 리팩터/문서화
|
||||
- 현재 테스트: 110 files / 173 tests 모두 통과
|
||||
- 무결성 인덱스/검증에 대한 정상/오류 케이스 커버 완료
|
||||
|
||||
### 오류/디버깅 로그 요약
|
||||
- 그룹 경로(other) 정규식 기대값 수정으로 테스트 안정화
|
||||
- SHA-256 재계산 불일치 회피: 테스트에서 중복 해시 구현 제거, 산출물 기준 비교
|
||||
- Node/브라우저 호환 btoa/atob 제거, 안전한 변환 로직 적용
|
||||
|
||||
### 다음 작업
|
||||
1) PR 생성(템플릿/라벨): `feat/export-bundle-integrity` → `main`
|
||||
2) CI 무결성 검증 스텝 추가: `verifyIntegrity`로 빌드 산출물 검사
|
||||
3) PR 라벨 자동화 및 조건부 머지(Gitea Actions/웹훅)
|
||||
4) README에 사용 가이드 보완(verifyIntegrity 활용 예시)
|
||||
|
||||
### CI/CD 계획(초안)
|
||||
- PR 오픈 시: 라벨 자동 지정, 테스트/빌드, 무결성 검증 스텝 실행
|
||||
- main 머지 조건: 테스트/빌드 통과 + 무결성 검증 통과 + 최소 라벨 셋 충족
|
||||
|
||||
### 커밋/푸쉬 원칙
|
||||
- 기능 단위 커밋은 한국어 메시지
|
||||
- 대범위 브랜치 완료 전에 푸쉬 금지(현 단계는 완료되어 푸쉬 수행)
|
||||
@@ -34,3 +34,81 @@ You can check out [the Next.js GitHub repository](https://github.com/vercel/next
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
|
||||
## Export Bundle (Landing ZIP)
|
||||
|
||||
The Builder can export a production-ready ZIP that contains:
|
||||
|
||||
- index.html, styles.css, app.js
|
||||
- assets/ hashed assets (optionally grouped by type)
|
||||
- site.webmanifest, robots.txt
|
||||
- Optional: sheets/ (Google Apps Script template)
|
||||
- Metadata files: assets.json, assets.index.json
|
||||
- Integrity: assets.integrity.index.json
|
||||
|
||||
### Export Options UI
|
||||
|
||||
- Manifest
|
||||
- Name, Short Name, Start URL, Display (dropdown), Theme Color (HEX only)
|
||||
- Robots
|
||||
- Disallow lines (textarea). Each line becomes a `Disallow:` rule.
|
||||
- Robots Meta: `<meta name="robots" content="...">` value (e.g. `noindex, nofollow`). Empty disables the tag.
|
||||
- Google Sheets Template Mode
|
||||
- Auto: include when `form.actionUrl` is empty
|
||||
- Include: always include
|
||||
- Exclude: never include
|
||||
- Font Optimization
|
||||
- Preconnect: toggle inclusion of Google Fonts preconnect links.
|
||||
- Preload: preload & load Google Fonts stylesheet with `media="print" onload` pattern.
|
||||
- Image Options
|
||||
- Loading: `lazy` (default) or `eager` for `<img loading>`
|
||||
- Decoding: `async` (default) or `sync` for `<img decoding>`
|
||||
|
||||
### site.webmanifest and robots.txt
|
||||
|
||||
- `site.webmanifest` is derived from page data; Export Options can override fields.
|
||||
- `robots.txt` defaults to a permissive header and adds `Disallow` lines from UI.
|
||||
- `meta name="robots"` can be injected via Export Options and is written in `<head>`.
|
||||
|
||||
### Asset paths and grouping
|
||||
|
||||
- AssetManager writes files to `assets/` with stable hash-based filenames.
|
||||
- Path strategy can be configured:
|
||||
- `flat` (default): `assets/<hash>.<ext>`
|
||||
- `grouped`: `assets/images/...`, `assets/fonts/...`, `assets/other/...`
|
||||
|
||||
### assets.json
|
||||
|
||||
Structured metadata for all assets. Example fields per entry:
|
||||
|
||||
- originalName, mimeType, size
|
||||
- hash8, ext, zipPath
|
||||
- integrity: `sha256-<base64>` (placeholder, base64 of bytes)
|
||||
- group: `images|fonts|other`
|
||||
- referencedAt: array of `local:<originalName>` when referenced by the page
|
||||
|
||||
### assets.index.json
|
||||
|
||||
Simple index to quickly find assets by group:
|
||||
|
||||
- images: string[] of zip paths
|
||||
- fonts: string[] of zip paths
|
||||
- other: string[] of zip paths
|
||||
|
||||
### assets.integrity.index.json
|
||||
|
||||
- entries: array of `{ path, integrity }`
|
||||
- `path`: asset `zipPath` (e.g. `assets/abcd1234.png` or grouped `assets/images/...`)
|
||||
- `integrity`: `sha256-<base64>` (real SHA-256 of the asset bytes)
|
||||
- bundleHash: `sha256-<base64>` over a deterministic join of `path` and `integrity` for all entries
|
||||
|
||||
Usage:
|
||||
- Verify file-level integrity by recomputing SHA-256(base64) of each asset and comparing with `entries[].integrity`.
|
||||
- Verify bundle integrity by recomputing `bundleHash` from sorted entries; useful for quick tamper detection.
|
||||
|
||||
### Google Sheets template (optional)
|
||||
|
||||
- When included, ZIP contains:
|
||||
- `sheets/Code.gs`: minimal Apps Script handler (Web App)
|
||||
- `sheets/README.txt`: setup instructions
|
||||
- Inclusion is controlled by `sheetsMode` (Auto/Include/Exclude) and `form.actionUrl` in Auto mode.
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import BuilderClientPage from '@/components/BuilderClientPage'
|
||||
|
||||
declare global {
|
||||
interface Window { __exportPreview?: () => { html: string } }
|
||||
}
|
||||
|
||||
describe('BuilderClientPage 이미지 옵션 UI 연동', () => {
|
||||
beforeEach(() => {
|
||||
// JSDOM 환경 초기화용
|
||||
window.__exportPreview = undefined
|
||||
})
|
||||
|
||||
it('기본값으로 img에 loading="lazy" decoding="async"가 포함된다', async () => {
|
||||
render(
|
||||
<NextIntlClientProvider locale="en" messages={{}}>
|
||||
<BuilderClientPage />
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
// Ensure a hero section with image is present
|
||||
const addHeroBtn = screen.getByTestId('btn-add-hero')
|
||||
addHeroBtn.click()
|
||||
expect(typeof window.__exportPreview).toBe('function')
|
||||
await waitFor(() => {
|
||||
const out = window.__exportPreview!()
|
||||
expect(out.html).toContain('loading="lazy"')
|
||||
expect(out.html).toContain('decoding="async"')
|
||||
})
|
||||
})
|
||||
|
||||
it('UI에서 eager/sync로 변경 시 preview HTML에 반영된다', async () => {
|
||||
render(
|
||||
<NextIntlClientProvider locale="en" messages={{}}>
|
||||
<BuilderClientPage />
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
const addHeroBtn = screen.getByTestId('btn-add-hero')
|
||||
addHeroBtn.click()
|
||||
const loadingSelect = screen.getByLabelText('Image Loading') as HTMLSelectElement
|
||||
const decodingSelect = screen.getByLabelText('Image Decoding') as HTMLSelectElement
|
||||
|
||||
fireEvent.change(loadingSelect, { target: { value: 'eager' } })
|
||||
fireEvent.change(decodingSelect, { target: { value: 'sync' } })
|
||||
|
||||
await waitFor(() => {
|
||||
const out = window.__exportPreview!()
|
||||
expect(out.html).toContain('loading="eager"')
|
||||
expect(out.html).toContain('decoding="sync"')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import BuilderClientPage from '@/components/BuilderClientPage'
|
||||
|
||||
declare global {
|
||||
interface Window { __exportPreview?: () => { html: string } }
|
||||
}
|
||||
|
||||
describe('BuilderClientPage robots meta UI 연동', () => {
|
||||
beforeEach(() => {
|
||||
window.__exportPreview = undefined
|
||||
})
|
||||
|
||||
it('기본값에서는 robots meta가 존재하지 않는다', async () => {
|
||||
render(
|
||||
<NextIntlClientProvider locale="en" messages={{}}>
|
||||
<BuilderClientPage />
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
// Hero 추가(렌더 내용 명확화)
|
||||
const addHeroBtn = screen.getByTestId('btn-add-hero')
|
||||
addHeroBtn.click()
|
||||
|
||||
expect(typeof window.__exportPreview).toBe('function')
|
||||
await waitFor(() => {
|
||||
const out = window.__exportPreview!()
|
||||
expect(out.html).not.toContain('<meta name="robots"')
|
||||
})
|
||||
})
|
||||
|
||||
it('UI 입력값이 head robots meta에 반영된다', async () => {
|
||||
render(
|
||||
<NextIntlClientProvider locale="en" messages={{}}>
|
||||
<BuilderClientPage />
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
const addHeroBtn = screen.getByTestId('btn-add-hero')
|
||||
addHeroBtn.click()
|
||||
|
||||
const robotsInput = screen.getByLabelText('Robots Meta') as HTMLInputElement
|
||||
fireEvent.change(robotsInput, { target: { value: 'noindex, nofollow' } })
|
||||
|
||||
await waitFor(() => {
|
||||
const out = window.__exportPreview!()
|
||||
expect(out.html).toContain('<meta name="robots" content="noindex, nofollow"')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,10 @@ import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
|
||||
import { buildAssetsIndex } from '@/lib/exporter/assets.index'
|
||||
import { buildAssetsIntegrityIndex } from '@/lib/exporter/assets.integrity.index'
|
||||
import type { Section } from '@/lib/state/store'
|
||||
import { createFormStore, type FormState } from '@/lib/state/formStore'
|
||||
import FormBuilderPanel from '@/components/FormBuilderPanel'
|
||||
@@ -47,6 +51,21 @@ export default function BuilderClientPage() {
|
||||
const [ogImage, setOgImage] = useState<string>('')
|
||||
const [ga4MeasurementId, setGa4MeasurementId] = useState<string>('')
|
||||
const [metaPixelId, setMetaPixelId] = useState<string>('')
|
||||
// Export Options (manifest/robots overrides)
|
||||
const [manifestName, setManifestName] = useState<string>('')
|
||||
const [manifestShortName, setManifestShortName] = useState<string>('')
|
||||
const [manifestStartUrl, setManifestStartUrl] = useState<string>('')
|
||||
const [manifestDisplay, setManifestDisplay] = useState<string>('')
|
||||
const [manifestThemeColor, setManifestThemeColor] = useState<string>('')
|
||||
const [robotsDisallow, setRobotsDisallow] = useState<string>('')
|
||||
const [robotsMeta, setRobotsMeta] = useState<string>('')
|
||||
const [sheetsMode, setSheetsMode] = useState<'auto' | 'include' | 'exclude'>('auto')
|
||||
const [assetPathStrategy, setAssetPathStrategy] = useState<'flat' | 'grouped'>('flat')
|
||||
// Font optimization: allow toggling Google Fonts preconnect links in exported HTML
|
||||
const [fontPreconnect, setFontPreconnect] = useState<boolean>(true)
|
||||
const [fontPreload, setFontPreload] = useState<boolean>(false)
|
||||
const [imageLoading, setImageLoading] = useState<'lazy' | 'eager'>('lazy')
|
||||
const [imageDecoding, setImageDecoding] = useState<'async' | 'sync'>('async')
|
||||
const [viewport, setViewport] = useState<'desktop' | 'mobile'>(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
try {
|
||||
@@ -165,9 +184,22 @@ export default function BuilderClientPage() {
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
const w = window as unknown as { __exportPreview?: () => { html: string; css: string; js: string } }
|
||||
// Build an effective AssetManager based on selected path strategy
|
||||
const buildEffectiveAm = (): AssetManager | undefined => {
|
||||
const base = am ?? undefined
|
||||
if (!base) return undefined
|
||||
if (assetPathStrategy === 'flat') return base
|
||||
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
|
||||
for (const ref of base.list()) {
|
||||
// re-add to apply new path strategy and recreate byOriginal mapping
|
||||
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
|
||||
}
|
||||
return clone
|
||||
}
|
||||
w.__exportPreview = () => {
|
||||
try {
|
||||
return exportPage(pageSchema.parse(pageData), { assetManager: am ?? undefined })
|
||||
// Export preview with current optimization options
|
||||
return exportPage(pageSchema.parse(pageData), { assetManager: buildEffectiveAm(), fontPreconnect, fontPreload, imageLoading, imageDecoding, robotsMeta: robotsMeta.trim() || undefined })
|
||||
} catch {
|
||||
const fixed: Page = {
|
||||
...pageData,
|
||||
@@ -177,16 +209,41 @@ export default function BuilderClientPage() {
|
||||
spamProtection: pageData.form?.spamProtection ?? { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
|
||||
},
|
||||
}
|
||||
return exportPage(pageSchema.parse(fixed), { assetManager: am ?? undefined })
|
||||
return exportPage(pageSchema.parse(fixed), { assetManager: buildEffectiveAm(), fontPreconnect, fontPreload, imageLoading, imageDecoding, robotsMeta: robotsMeta.trim() || undefined })
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}, [pageData, am])
|
||||
}, [pageData, am, fontPreconnect, fontPreload, imageLoading, imageDecoding, robotsMeta, assetPathStrategy])
|
||||
|
||||
const doExport = useCallback(async () => {
|
||||
const valid = pageSchema.parse(pageData)
|
||||
const exported = exportPage(valid, { assetManager: am ?? undefined })
|
||||
let valid = pageData as Page
|
||||
try {
|
||||
valid = pageSchema.parse(pageData)
|
||||
} catch {
|
||||
const fixed: Page = {
|
||||
...pageData,
|
||||
form: {
|
||||
actionUrl: pageData.form?.actionUrl ?? '',
|
||||
fields: pageData.form?.fields ?? [],
|
||||
spamProtection: pageData.form?.spamProtection ?? { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
|
||||
},
|
||||
} as Page
|
||||
valid = pageSchema.parse(fixed)
|
||||
}
|
||||
// Build an effective AssetManager based on selected path strategy
|
||||
const buildEffectiveAm = (): AssetManager | undefined => {
|
||||
const base = am ?? undefined
|
||||
if (!base) return undefined
|
||||
if (assetPathStrategy === 'flat') return base
|
||||
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
|
||||
for (const ref of base.list()) {
|
||||
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
|
||||
}
|
||||
return clone
|
||||
}
|
||||
// Respect font, image, robots meta optimization toggles when exporting
|
||||
const exported = exportPage(valid, { assetManager: buildEffectiveAm(), fontPreconnect, fontPreload, imageLoading, imageDecoding, robotsMeta: robotsMeta.trim() || undefined })
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
const w = window as unknown as { __captureExport?: boolean; __lastExport?: { html: string; css: string; js: string } }
|
||||
@@ -195,10 +252,49 @@ export default function BuilderClientPage() {
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
const assets = am ? am.toZipStructure() : {}
|
||||
const zipBytes = await buildZip({ html: exported.html, css: exported.css, js: exported.js, assets })
|
||||
const effectiveAm = (() => {
|
||||
const base = am ?? undefined
|
||||
if (!base) return undefined
|
||||
if (assetPathStrategy === 'flat') return base
|
||||
const clone = new AssetManager({ maxBytes: 10 * 1024 * 1024, allowedExts: ['png', 'jpg', 'jpeg', 'webp', 'svg'], pathStrategy: assetPathStrategy })
|
||||
for (const ref of base.list()) {
|
||||
clone.add({ name: ref.originalName, type: ref.mimeType, bytes: ref.bytes })
|
||||
}
|
||||
return clone
|
||||
})()
|
||||
const assets = effectiveAm ? effectiveAm.toZipStructure() : {}
|
||||
// Build overrides from UI options
|
||||
const manifestOverrideBase: Record<string, string> = {}
|
||||
if (manifestName && manifestName.trim().length > 0) manifestOverrideBase.name = manifestName.trim()
|
||||
if (manifestShortName && manifestShortName.trim().length > 0) manifestOverrideBase.short_name = manifestShortName.trim()
|
||||
if (manifestStartUrl && manifestStartUrl.trim().length > 0) manifestOverrideBase.start_url = manifestStartUrl.trim()
|
||||
if (manifestDisplay && manifestDisplay.trim().length > 0) manifestOverrideBase.display = manifestDisplay.trim()
|
||||
if (manifestThemeColor && manifestThemeColor.trim().length > 0) {
|
||||
const v = manifestThemeColor.trim()
|
||||
const hexOk = /^#([0-9a-fA-F]{3}){1,2}$/.test(v)
|
||||
if (hexOk) {
|
||||
manifestOverrideBase.theme_color = v
|
||||
}
|
||||
}
|
||||
const manifestOverride = Object.keys(manifestOverrideBase).length > 0 ? (manifestOverrideBase as { name?: string; short_name?: string; start_url?: string; display?: string; theme_color?: string }) : undefined
|
||||
const robotsTextOverride = (() => {
|
||||
const lines = (robotsDisallow || '').split(/\n+/).map((s) => s.trim()).filter((s) => s.length > 0)
|
||||
if (lines.length === 0) return undefined
|
||||
const disallowLines = lines.map((l) => (l.startsWith('Disallow:') ? l : `Disallow: ${l}`))
|
||||
return `User-agent: *\n${disallowLines.join('\n')}`
|
||||
})()
|
||||
const baseExtras = buildExtrasForPage(valid, { robotsText: robotsTextOverride, manifest: manifestOverride, sheetsMode })
|
||||
const extras: Record<string, Uint8Array> = {
|
||||
...baseExtras,
|
||||
...(am ? {
|
||||
'assets.json': buildAssetsMetadata(am),
|
||||
'assets.index.json': buildAssetsIndex(am),
|
||||
'assets.integrity.index.json': buildAssetsIntegrityIndex(am),
|
||||
} : {}),
|
||||
}
|
||||
const zipBytes = await buildZip({ html: exported.html, css: exported.css, js: exported.js, assets, extras })
|
||||
download('landing.zip', zipBytes)
|
||||
}, [pageData, am])
|
||||
}, [pageData, am, manifestName, manifestShortName, manifestStartUrl, manifestDisplay, manifestThemeColor, robotsDisallow, sheetsMode, fontPreconnect, fontPreload, imageLoading, imageDecoding, robotsMeta, assetPathStrategy])
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@@ -261,6 +357,168 @@ export default function BuilderClientPage() {
|
||||
onSelect={(i) => setSelectedIndex(i)}
|
||||
/>
|
||||
</div>
|
||||
<div className="border rounded p-3 space-y-2">
|
||||
<h2 className="text-sm font-semibold mb-1">Export Options</h2>
|
||||
{/* Asset path strategy: flat vs grouped */}
|
||||
<label className="block" htmlFor="ins-asset-path-strategy">
|
||||
<span className="sr-only">Asset Path Strategy</span>
|
||||
<select
|
||||
id="ins-asset-path-strategy"
|
||||
aria-label="Asset Path Strategy"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={assetPathStrategy}
|
||||
onChange={(e) => setAssetPathStrategy(e.target.value as 'flat' | 'grouped')}
|
||||
>
|
||||
<option value="flat">Assets Path: Flat</option>
|
||||
<option value="grouped">Assets Path: Grouped (images/fonts/other)</option>
|
||||
</select>
|
||||
</label>
|
||||
{/* Font optimization toggle for Google Fonts preconnect */}
|
||||
<label className="flex items-center gap-2" htmlFor="ins-font-preconnect">
|
||||
<input
|
||||
id="ins-font-preconnect"
|
||||
type="checkbox"
|
||||
aria-label="Font Preconnect"
|
||||
checked={fontPreconnect}
|
||||
onChange={(e) => setFontPreconnect(e.target.checked)}
|
||||
/>
|
||||
<span className="text-sm">Enable font preconnect (Google Fonts)</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2" htmlFor="ins-font-preload">
|
||||
<input
|
||||
id="ins-font-preload"
|
||||
type="checkbox"
|
||||
aria-label="Font Preload"
|
||||
checked={fontPreload}
|
||||
onChange={(e) => setFontPreload(e.target.checked)}
|
||||
/>
|
||||
<span className="text-sm">Enable font preload (Google Fonts)</span>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block" htmlFor="ins-image-loading">
|
||||
<span className="sr-only">Image Loading</span>
|
||||
<select
|
||||
id="ins-image-loading"
|
||||
aria-label="Image Loading"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={imageLoading}
|
||||
onChange={(e) => setImageLoading(e.target.value as 'lazy' | 'eager')}
|
||||
>
|
||||
<option value="lazy">Image Loading: lazy</option>
|
||||
<option value="eager">Image Loading: eager</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-image-decoding">
|
||||
<span className="sr-only">Image Decoding</span>
|
||||
<select
|
||||
id="ins-image-decoding"
|
||||
aria-label="Image Decoding"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={imageDecoding}
|
||||
onChange={(e) => setImageDecoding(e.target.value as 'async' | 'sync')}
|
||||
>
|
||||
<option value="async">Image Decoding: async</option>
|
||||
<option value="sync">Image Decoding: sync</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block" htmlFor="ins-manifest-name">
|
||||
<span className="sr-only">Manifest Name</span>
|
||||
<input
|
||||
id="ins-manifest-name"
|
||||
aria-label="Manifest Name"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={manifestName}
|
||||
onChange={(e) => setManifestName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-manifest-short-name">
|
||||
<span className="sr-only">Manifest Short Name</span>
|
||||
<input
|
||||
id="ins-manifest-short-name"
|
||||
aria-label="Manifest Short Name"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={manifestShortName}
|
||||
onChange={(e) => setManifestShortName(e.target.value)}
|
||||
placeholder="MyApp"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-manifest-start-url">
|
||||
<span className="sr-only">Manifest Start URL</span>
|
||||
<input
|
||||
id="ins-manifest-start-url"
|
||||
aria-label="Manifest Start URL"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={manifestStartUrl}
|
||||
onChange={(e) => setManifestStartUrl(e.target.value)}
|
||||
placeholder="/"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-manifest-display">
|
||||
<span className="sr-only">Manifest Display</span>
|
||||
<select
|
||||
id="ins-manifest-display"
|
||||
aria-label="Manifest Display"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={manifestDisplay}
|
||||
onChange={(e) => setManifestDisplay(e.target.value)}
|
||||
>
|
||||
<option value="">(default)</option>
|
||||
<option value="standalone">standalone</option>
|
||||
<option value="minimal-ui">minimal-ui</option>
|
||||
<option value="browser">browser</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-manifest-theme-color">
|
||||
<span className="sr-only">Manifest Theme Color</span>
|
||||
<input
|
||||
id="ins-manifest-theme-color"
|
||||
aria-label="Manifest Theme Color"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={manifestThemeColor}
|
||||
onChange={(e) => setManifestThemeColor(e.target.value)}
|
||||
placeholder="#0ea5e9"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-robots-disallow">
|
||||
<span className="sr-only">Robots Disallow</span>
|
||||
<textarea
|
||||
id="ins-robots-disallow"
|
||||
aria-label="Robots Disallow"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
rows={3}
|
||||
value={robotsDisallow}
|
||||
onChange={(e) => setRobotsDisallow(e.target.value)}
|
||||
placeholder="/private\n/tmp"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-robots-meta">
|
||||
<span className="sr-only">Robots Meta</span>
|
||||
<input
|
||||
id="ins-robots-meta"
|
||||
aria-label="Robots Meta"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={robotsMeta}
|
||||
onChange={(e) => setRobotsMeta(e.target.value)}
|
||||
placeholder="noindex, nofollow"
|
||||
/>
|
||||
</label>
|
||||
<label className="block" htmlFor="ins-sheets-mode">
|
||||
<span className="sr-only">Google Sheets Template Mode</span>
|
||||
<select
|
||||
id="ins-sheets-mode"
|
||||
aria-label="Google Sheets Template Mode"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={sheetsMode}
|
||||
onChange={(e) => setSheetsMode(e.target.value as 'auto'|'include'|'exclude')}
|
||||
>
|
||||
<option value="auto">Sheets Template: Auto</option>
|
||||
<option value="include">Sheets Template: Include</option>
|
||||
<option value="exclude">Sheets Template: Exclude</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
right={
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import BuilderClientPage from '@/components/BuilderClientPage'
|
||||
|
||||
vi.mock('next-intl', () => {
|
||||
return {
|
||||
useTranslations: () => (key: string) => key,
|
||||
}
|
||||
})
|
||||
|
||||
const buildZipSpy = vi.fn(async (_arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => new Uint8Array([80, 75]))
|
||||
|
||||
vi.mock('@/lib/exporter/zip', () => {
|
||||
return {
|
||||
buildZip: (arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => buildZipSpy(arg),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Export Options UI → manifest fields', () => {
|
||||
it('passes short_name/start_url/display/theme_color to extras manifest JSON', async () => {
|
||||
render(<BuilderClientPage />)
|
||||
|
||||
const shortName = 'MyApp'
|
||||
const startUrl = '/home'
|
||||
const display = 'minimal-ui'
|
||||
const themeColor = '#112233'
|
||||
|
||||
const snInput = await screen.findByLabelText('Manifest Short Name')
|
||||
fireEvent.change(snInput, { target: { value: shortName } })
|
||||
|
||||
const startInput = await screen.findByLabelText('Manifest Start URL')
|
||||
fireEvent.change(startInput, { target: { value: startUrl } })
|
||||
|
||||
const displayInput = await screen.findByLabelText('Manifest Display')
|
||||
fireEvent.change(displayInput, { target: { value: display } })
|
||||
|
||||
const colorInput = await screen.findByLabelText('Manifest Theme Color')
|
||||
fireEvent.change(colorInput, { target: { value: themeColor } })
|
||||
|
||||
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
|
||||
fireEvent.click(exportBtn)
|
||||
|
||||
expect(buildZipSpy).toHaveBeenCalled()
|
||||
const first = buildZipSpy.mock.calls[0]
|
||||
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
|
||||
const td = new TextDecoder()
|
||||
const manifestRaw = td.decode(extras['site.webmanifest'])
|
||||
const manifest = JSON.parse(manifestRaw)
|
||||
|
||||
expect(manifest.short_name).toBe(shortName)
|
||||
expect(manifest.start_url).toBe(startUrl)
|
||||
expect(manifest.display).toBe(display)
|
||||
expect(manifest.theme_color).toBe(themeColor)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import BuilderClientPage from '@/components/BuilderClientPage'
|
||||
|
||||
vi.mock('next-intl', () => {
|
||||
return {
|
||||
useTranslations: () => (key: string) => key,
|
||||
}
|
||||
})
|
||||
|
||||
const buildZipSpy = vi.fn(async (_arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => new Uint8Array([80, 75]))
|
||||
|
||||
vi.mock('@/lib/exporter/zip', () => {
|
||||
return {
|
||||
buildZip: (arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => buildZipSpy(arg),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Export Options UI polish', () => {
|
||||
it('uses a dropdown for Manifest Display and passes selected value', async () => {
|
||||
render(<BuilderClientPage />)
|
||||
|
||||
// choose display = minimal-ui
|
||||
const displaySelect = await screen.findByLabelText('Manifest Display')
|
||||
fireEvent.change(displaySelect, { target: { value: 'minimal-ui' } })
|
||||
|
||||
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
|
||||
fireEvent.click(exportBtn)
|
||||
|
||||
const first = buildZipSpy.mock.calls[0]
|
||||
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
|
||||
const td = new TextDecoder()
|
||||
const manifest = JSON.parse(td.decode(extras['site.webmanifest']))
|
||||
expect(manifest.display).toBe('minimal-ui')
|
||||
})
|
||||
|
||||
it('ignores invalid theme_color override and keeps default theme when not a hex', async () => {
|
||||
render(<BuilderClientPage />)
|
||||
|
||||
const colorInput = await screen.findByLabelText('Manifest Theme Color')
|
||||
fireEvent.change(colorInput, { target: { value: 'blue' } }) // invalid hex
|
||||
|
||||
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
|
||||
fireEvent.click(exportBtn)
|
||||
|
||||
const first = buildZipSpy.mock.calls[0]
|
||||
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
|
||||
const td = new TextDecoder()
|
||||
const manifest = JSON.parse(td.decode(extras['site.webmanifest']))
|
||||
expect(manifest.theme_color).toBe('#0ea5e9') // default from page.theme.primaryColor
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import BuilderClientPage from '@/components/BuilderClientPage'
|
||||
|
||||
vi.mock('next-intl', () => {
|
||||
return {
|
||||
useTranslations: () => (key: string) => key,
|
||||
}
|
||||
})
|
||||
|
||||
const buildZipSpy = vi.fn(async (_arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => new Uint8Array([80, 75]))
|
||||
|
||||
vi.mock('@/lib/exporter/zip', () => {
|
||||
return {
|
||||
buildZip: (arg: {
|
||||
html: string
|
||||
css: string
|
||||
js: string
|
||||
assets: Record<string, Uint8Array>
|
||||
extras?: Record<string, Uint8Array>
|
||||
}) => buildZipSpy(arg),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Export Options UI → extras overrides', () => {
|
||||
it('passes manifest.name and robots Disallow to buildExtrasForPage via buildZip extras', async () => {
|
||||
render(<BuilderClientPage />)
|
||||
|
||||
const manifestName = 'My App Custom'
|
||||
const robotsDisallow = '/private\n/tmp'
|
||||
|
||||
const nameInput = await screen.findByLabelText('Manifest Name')
|
||||
fireEvent.change(nameInput, { target: { value: manifestName } })
|
||||
|
||||
const robotsInput = await screen.findByLabelText('Robots Disallow')
|
||||
fireEvent.change(robotsInput, { target: { value: robotsDisallow } })
|
||||
|
||||
const exportBtn = await screen.findByRole('button', { name: 'builder.action.export' })
|
||||
fireEvent.click(exportBtn)
|
||||
|
||||
expect(buildZipSpy).toHaveBeenCalled()
|
||||
const first = buildZipSpy.mock.calls[0]
|
||||
expect(first && first[0]).toBeTruthy()
|
||||
const extras: Record<string, Uint8Array> = (first![0] as { extras: Record<string, Uint8Array> }).extras
|
||||
const td = new TextDecoder()
|
||||
const manifestRaw = td.decode(extras['site.webmanifest'])
|
||||
const robotsRaw = td.decode(extras['robots.txt'])
|
||||
const manifest = JSON.parse(manifestRaw)
|
||||
|
||||
expect(manifest.name).toBe(manifestName)
|
||||
expect(robotsRaw).toMatch(/Disallow: \/private/)
|
||||
expect(robotsRaw).toMatch(/Disallow: \/tmp/)
|
||||
// integrity index should be included
|
||||
expect(Object.prototype.hasOwnProperty.call(extras, 'assets.integrity.index.json')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
|
||||
|
||||
describe('AssetManager pathStrategy grouped', () => {
|
||||
it('writes assets under assets/images and assets/fonts when grouped', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2'], pathStrategy: 'grouped' })
|
||||
const img = await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
|
||||
const font = await am.add({ name: 'main.woff2', type: 'font/woff2', bytes: u8(12) })
|
||||
expect(img.path).toMatch(/^assets\/images\/[0-9a-f]{8}\.png$/)
|
||||
expect(font.path).toMatch(/^assets\/fonts\/[0-9a-f]{8}\.woff2$/)
|
||||
const zip = am.toZipStructure()
|
||||
const keys = Object.keys(zip)
|
||||
expect(keys.some(k => /^assets\/images\//.test(k))).toBe(true)
|
||||
expect(keys.some(k => /^assets\/fonts\//.test(k))).toBe(true)
|
||||
})
|
||||
|
||||
it('rewriteUrl marks referenced originals and returns grouped path', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png'], pathStrategy: 'grouped' })
|
||||
const img = await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
|
||||
const rewritten = am.rewriteUrl('local:hero.png')
|
||||
expect(rewritten).toBe(img.path)
|
||||
expect(am.referencedList()).toContain('hero.png')
|
||||
})
|
||||
})
|
||||
@@ -16,6 +16,7 @@ export type AssetRef = {
|
||||
export type AssetManagerOptions = {
|
||||
maxBytes: number
|
||||
allowedExts: string[] // e.g., ['png','jpg','jpeg','webp','svg']
|
||||
pathStrategy?: 'flat' | 'grouped'
|
||||
}
|
||||
|
||||
function extOf(name: string): string {
|
||||
@@ -36,12 +37,15 @@ function hash8(bytes: Uint8Array): string {
|
||||
export class AssetManager {
|
||||
private readonly maxBytes: number
|
||||
private readonly allowed: Set<string>
|
||||
private readonly pathStrategy: 'flat' | 'grouped'
|
||||
private byHash = new Map<string, AssetRef>()
|
||||
private byOriginal = new Map<string, string>() // originalName -> path
|
||||
private referenced = new Set<string>() // originalName referenced via rewrite
|
||||
|
||||
constructor(opts: AssetManagerOptions) {
|
||||
this.maxBytes = opts.maxBytes
|
||||
this.allowed = new Set(opts.allowedExts.map((e) => e.toLowerCase()))
|
||||
this.pathStrategy = opts.pathStrategy ?? 'flat'
|
||||
}
|
||||
|
||||
async add(file: AssetInput): Promise<AssetRef> {
|
||||
@@ -60,7 +64,7 @@ export class AssetManager {
|
||||
return existing
|
||||
}
|
||||
|
||||
const path = `assets/${h}.${ext}`
|
||||
const path = this.makePath(h, ext, file.type)
|
||||
const ref: AssetRef = {
|
||||
originalName: file.name,
|
||||
mimeType: file.type,
|
||||
@@ -91,8 +95,23 @@ export class AssetManager {
|
||||
if (urlOrLocalRef.startsWith('local:')) {
|
||||
const key = urlOrLocalRef.slice('local:'.length)
|
||||
const p = this.byOriginal.get(key)
|
||||
if (p) this.referenced.add(key)
|
||||
return p ?? urlOrLocalRef
|
||||
}
|
||||
return urlOrLocalRef
|
||||
}
|
||||
|
||||
referencedList(): string[] {
|
||||
return Array.from(this.referenced)
|
||||
}
|
||||
|
||||
private makePath(hash8: string, ext: string, mime: string): string {
|
||||
if (this.pathStrategy === 'grouped') {
|
||||
let group = 'other'
|
||||
if (mime.startsWith('image/')) group = 'images'
|
||||
else if (mime.startsWith('font/')) group = 'fonts'
|
||||
return `assets/${group}/${hash8}.${ext}`
|
||||
}
|
||||
return `assets/${hash8}.${ext}`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ describe('Exporter a11y/responsive enhancements', () => {
|
||||
test('hero image alt derives from heading', () => {
|
||||
const out = exportPage(makePage())
|
||||
expect(out.html).toContain('<h1 id="hero-heading">Welcome</h1>')
|
||||
expect(out.html).toContain('<img src="https://example.com/img.png" alt="Welcome" />')
|
||||
expect(out.html).toMatch(/<img[^>]*src="https:\/\/example\.com\/img\.png"[^>]*alt="Welcome"[^>]*\/>/)
|
||||
})
|
||||
|
||||
test('responsive and a11y CSS tokens exist', () => {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsIndex } from '@/lib/exporter/assets.index'
|
||||
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
|
||||
|
||||
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
|
||||
|
||||
type IndexShape = { images: string[]; fonts: string[]; other: string[] }
|
||||
|
||||
describe('assets.index.json ↔ assets.json consistency', () => {
|
||||
it.each([
|
||||
{ mode: 'flat' as const },
|
||||
{ mode: 'grouped' as const },
|
||||
])('ensures index paths exist in assets.json zipPath with correct group ($mode)', async ({ mode }) => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt','jpg'], pathStrategy: mode })
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
|
||||
await am.add({ name: 'thumb.jpg', type: 'image/jpeg', bytes: u8(11) })
|
||||
await am.add({ name: 'main.woff2', type: 'font/woff2', bytes: u8(12) })
|
||||
await am.add({ name: 'readme.txt', type: 'text/plain', bytes: u8(1) })
|
||||
|
||||
const indexBytes = buildAssetsIndex(am)
|
||||
const metaBytes = buildAssetsMetadata(am)
|
||||
|
||||
const index = JSON.parse(new TextDecoder().decode(indexBytes)) as IndexShape
|
||||
const meta = JSON.parse(new TextDecoder().decode(metaBytes)) as { assets: Array<{ zipPath: string; group: 'images'|'fonts'|'other' }> }
|
||||
|
||||
const metaByPath = new Map(meta.assets.map(a => [a.zipPath, a.group]))
|
||||
|
||||
for (const p of index.images) {
|
||||
expect(metaByPath.has(p)).toBe(true)
|
||||
expect(metaByPath.get(p)).toBe('images')
|
||||
}
|
||||
for (const p of index.fonts) {
|
||||
expect(metaByPath.has(p)).toBe(true)
|
||||
expect(metaByPath.get(p)).toBe('fonts')
|
||||
}
|
||||
for (const p of index.other) {
|
||||
expect(metaByPath.has(p)).toBe(true)
|
||||
expect(metaByPath.get(p)).toBe('other')
|
||||
}
|
||||
|
||||
// Optional: ensure no extra paths exist in meta that are missing in index groups
|
||||
const indexSet = new Set([...index.images, ...index.fonts, ...index.other])
|
||||
for (const a of meta.assets) {
|
||||
expect(indexSet.has(a.zipPath)).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsIndex } from '@/lib/exporter/assets.index'
|
||||
|
||||
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
|
||||
|
||||
describe('Assets index builder', () => {
|
||||
it('groups assets by mime into images/fonts/other and lists zipPath', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt'] })
|
||||
await am.add({ name: 'a.png', type: 'image/png', bytes: u8(4) })
|
||||
await am.add({ name: 'b.woff2', type: 'font/woff2', bytes: u8(6) })
|
||||
await am.add({ name: 'c.txt', type: 'text/plain', bytes: u8(2) })
|
||||
const bytes = buildAssetsIndex(am)
|
||||
const obj = JSON.parse(new TextDecoder().decode(bytes)) as { images: string[]; fonts: string[]; other: string[] }
|
||||
expect(obj.images.length).toBe(1)
|
||||
expect(obj.fonts.length).toBe(1)
|
||||
expect(obj.other.length).toBe(1)
|
||||
expect(obj.images[0]).toMatch(/^assets\/[0-9a-f]{8}\.png$/)
|
||||
expect(obj.fonts[0]).toMatch(/^assets\/[0-9a-f]{8}\.woff2$/)
|
||||
expect(obj.other[0]).toMatch(/^assets\/[0-9a-f]{8}\.txt$/)
|
||||
})
|
||||
|
||||
it('sorts each group array by path (ascending)', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','txt','woff2'] })
|
||||
// Add in shuffled order so that sort is required
|
||||
await am.add({ name: 'z.png', type: 'image/png', bytes: u8(3) })
|
||||
await am.add({ name: 'a.png', type: 'image/png', bytes: u8(5) })
|
||||
await am.add({ name: 'm.txt', type: 'text/plain', bytes: u8(2) })
|
||||
await am.add({ name: 'b.txt', type: 'text/plain', bytes: u8(4) })
|
||||
await am.add({ name: 'f.woff2', type: 'font/woff2', bytes: u8(6) })
|
||||
await am.add({ name: 'e.woff2', type: 'font/woff2', bytes: u8(7) })
|
||||
const bytes = buildAssetsIndex(am)
|
||||
const obj = JSON.parse(new TextDecoder().decode(bytes)) as { images: string[]; fonts: string[]; other: string[] }
|
||||
const imgs = [...obj.images]
|
||||
const fonts = [...obj.fonts]
|
||||
const others = [...obj.other]
|
||||
const sortedImgs = [...imgs].sort()
|
||||
const sortedFonts = [...fonts].sort()
|
||||
const sortedOthers = [...others].sort()
|
||||
expect(imgs).toEqual(sortedImgs)
|
||||
expect(fonts).toEqual(sortedFonts)
|
||||
expect(others).toEqual(sortedOthers)
|
||||
})
|
||||
|
||||
it('respects grouped pathStrategy and outputs grouped paths in index', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt'], pathStrategy: 'grouped' })
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
|
||||
await am.add({ name: 'main.woff2', type: 'font/woff2', bytes: u8(12) })
|
||||
await am.add({ name: 'readme.txt', type: 'text/plain', bytes: u8(1) })
|
||||
const bytes = buildAssetsIndex(am)
|
||||
const obj = JSON.parse(new TextDecoder().decode(bytes)) as { images: string[]; fonts: string[]; other: string[] }
|
||||
expect(obj.images[0]).toMatch(/^assets\/images\/[0-9a-f]{8}\.png$/)
|
||||
expect(obj.fonts[0]).toMatch(/^assets\/fonts\/[0-9a-f]{8}\.woff2$/)
|
||||
expect(obj.other[0]).toMatch(/^assets\/other\/[0-9a-f]{8}\.txt$/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
export type AssetsIndex = {
|
||||
images: string[]
|
||||
fonts: string[]
|
||||
other: string[]
|
||||
}
|
||||
|
||||
export function buildAssetsIndex(am: AssetManager): Uint8Array {
|
||||
// 그룹별 경로 수집
|
||||
const images: string[] = []
|
||||
const fonts: string[] = []
|
||||
const other: string[] = []
|
||||
for (const ref of am.list()) {
|
||||
if (ref.mimeType.startsWith('image/')) images.push(ref.path)
|
||||
else if (ref.mimeType.startsWith('font/')) fonts.push(ref.path)
|
||||
else other.push(ref.path)
|
||||
}
|
||||
// 경로 사전순 정렬로 일정한 출력 보장
|
||||
images.sort()
|
||||
fonts.sort()
|
||||
other.sort()
|
||||
const obj: AssetsIndex = { images, fonts, other }
|
||||
const json = JSON.stringify(obj, null, 2)
|
||||
return new TextEncoder().encode(json)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsIntegrityIndex } from '@/lib/exporter/assets.integrity.index'
|
||||
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
|
||||
|
||||
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
|
||||
|
||||
describe('assets.integrity.index.json', () => {
|
||||
it('emits path->integrity mapping consistent with assets.json and deterministically across modes and insertion order', async () => {
|
||||
for (const mode of ['flat','grouped'] as const) {
|
||||
// case1: insertion order A,B,C
|
||||
const am1 = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt'], pathStrategy: mode })
|
||||
await am1.add({ name: 'a.png', type: 'image/png', bytes: u8(3) })
|
||||
await am1.add({ name: 'b.woff2', type: 'font/woff2', bytes: u8(4) })
|
||||
await am1.add({ name: 'c.txt', type: 'text/plain', bytes: u8(5) })
|
||||
const idx1 = JSON.parse(new TextDecoder().decode(buildAssetsIntegrityIndex(am1))) as { entries: Array<{path:string; integrity:string}>; bundleHash: string }
|
||||
const meta1 = JSON.parse(new TextDecoder().decode(buildAssetsMetadata(am1))) as { assets: Array<{ zipPath: string; integrity: string }> }
|
||||
const metaMap1 = new Map(meta1.assets.map(a => [a.zipPath, a.integrity]))
|
||||
const paths1 = idx1.entries.map(e => e.path)
|
||||
const sorted1 = [...paths1].sort()
|
||||
expect(paths1).toEqual(sorted1)
|
||||
for (const e of idx1.entries) expect(metaMap1.get(e.path)).toBe(e.integrity)
|
||||
|
||||
// case2: insertion order shuffled C,A,B -> determinism of output
|
||||
const am2 = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2','txt'], pathStrategy: mode })
|
||||
await am2.add({ name: 'c.txt', type: 'text/plain', bytes: u8(5) })
|
||||
await am2.add({ name: 'a.png', type: 'image/png', bytes: u8(3) })
|
||||
await am2.add({ name: 'b.woff2', type: 'font/woff2', bytes: u8(4) })
|
||||
const idx2 = JSON.parse(new TextDecoder().decode(buildAssetsIntegrityIndex(am2))) as { entries: Array<{path:string; integrity:string}>; bundleHash: string }
|
||||
// same entries set and order (sorted by path) -> equality
|
||||
expect(idx2.entries.map(e => e.path)).toEqual(idx1.entries.map(e => e.path))
|
||||
expect(idx2.entries.map(e => e.integrity)).toEqual(idx1.entries.map(e => e.integrity))
|
||||
// bundle hash depends on entries -> equal as well
|
||||
expect(idx2.bundleHash).toBe(idx1.bundleHash)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
export type AssetsIntegrityIndex = {
|
||||
entries: Array<{ path: string; integrity: string }>
|
||||
bundleHash: string
|
||||
}
|
||||
|
||||
// Minimal synchronous SHA-256 implementation returning base64 string.
|
||||
function sha256Base64(bytes: Uint8Array): string {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
|
||||
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
|
||||
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
|
||||
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
|
||||
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
|
||||
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
|
||||
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
|
||||
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
|
||||
])
|
||||
const H = new Uint32Array([
|
||||
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19
|
||||
])
|
||||
const l = bytes.length
|
||||
const bitLenHi = Math.floor((l >>> 29))
|
||||
const bitLenLo = (l << 3) >>> 0
|
||||
const withOne = l + 1
|
||||
const padLen = ((withOne % 64) <= 56) ? (56 - (withOne % 64)) : (56 + 64 - (withOne % 64))
|
||||
const totalLen = withOne + padLen + 8
|
||||
const m = new Uint8Array(totalLen)
|
||||
m.set(bytes)
|
||||
m[l] = 0x80
|
||||
m[totalLen - 8] = (bitLenHi >>> 24) & 0xff
|
||||
m[totalLen - 7] = (bitLenHi >>> 16) & 0xff
|
||||
m[totalLen - 6] = (bitLenHi >>> 8) & 0xff
|
||||
m[totalLen - 5] = (bitLenHi >>> 0) & 0xff
|
||||
m[totalLen - 4] = (bitLenLo >>> 24) & 0xff
|
||||
m[totalLen - 3] = (bitLenLo >>> 16) & 0xff
|
||||
m[totalLen - 2] = (bitLenLo >>> 8) & 0xff
|
||||
m[totalLen - 1] = (bitLenLo >>> 0) & 0xff
|
||||
const W = new Uint32Array(64)
|
||||
for (let i = 0; i < totalLen; i += 64) {
|
||||
for (let t = 0; t < 16; t++) {
|
||||
const j = i + t * 4
|
||||
W[t] = (m[j] << 24) | (m[j + 1] << 16) | (m[j + 2] << 8) | (m[j + 3])
|
||||
}
|
||||
for (let t = 16; t < 64; t++) {
|
||||
const s0 = (rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ (W[t - 15] >>> 3)) >>> 0
|
||||
const s1 = (rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ (W[t - 2] >>> 10)) >>> 0
|
||||
W[t] = (W[t - 16] + s0 + W[t - 7] + s1) >>> 0
|
||||
}
|
||||
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7]
|
||||
for (let t = 0; t < 64; t++) {
|
||||
const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0
|
||||
const ch = ((e & f) ^ (~e & g)) >>> 0
|
||||
const temp1 = (h + S1 + ch + K[t] + W[t]) >>> 0
|
||||
const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0
|
||||
const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
|
||||
const temp2 = (S0 + maj) >>> 0
|
||||
h = g; g = f; f = e; e = (d + temp1) >>> 0; d = c; c = b; b = a; a = (temp1 + temp2) >>> 0
|
||||
}
|
||||
H[0] = (H[0] + a) >>> 0
|
||||
H[1] = (H[1] + b) >>> 0
|
||||
H[2] = (H[2] + c) >>> 0
|
||||
H[3] = (H[3] + d) >>> 0
|
||||
H[4] = (H[4] + e) >>> 0
|
||||
H[5] = (H[5] + f) >>> 0
|
||||
H[6] = (H[6] + g) >>> 0
|
||||
H[7] = (H[7] + h) >>> 0
|
||||
}
|
||||
const out = new Uint8Array(32)
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[i*4+0]=(H[i]>>>24)&0xff; out[i*4+1]=(H[i]>>>16)&0xff; out[i*4+2]=(H[i]>>>8)&0xff; out[i*4+3]=(H[i]>>>0)&0xff
|
||||
}
|
||||
if (typeof Buffer !== 'undefined') return Buffer.from(out).toString('base64')
|
||||
let s = ''; for (let i=0;i<out.length;i++) s += String.fromCharCode(out[i])
|
||||
const btoaFn = (globalThis as unknown as { btoa?: (s: string) => string }).btoa
|
||||
if (!btoaFn) throw new Error('btoa not available')
|
||||
return btoaFn(s)
|
||||
function rotr(x: number, n: number) { return (x >>> n) | (x << (32 - n)) }
|
||||
}
|
||||
|
||||
export function buildAssetsIntegrityIndex(am: AssetManager): Uint8Array {
|
||||
// 1) Collect entries: path + sha256 integrity
|
||||
const entries = am.list().map(ref => ({
|
||||
path: ref.path,
|
||||
integrity: `sha256-${sha256Base64(ref.bytes)}`,
|
||||
}))
|
||||
// 2) Sort entries by path for deterministic output
|
||||
entries.sort((a, b) => a.path.localeCompare(b.path))
|
||||
// 3) Compute bundleHash over sorted lines: path + integrity joined by \n
|
||||
const lines: string[] = []
|
||||
for (const e of entries) { lines.push(e.path); lines.push(e.integrity) }
|
||||
const joined = new TextEncoder().encode(lines.join('\n'))
|
||||
const bundleHash = `sha256-${sha256Base64(joined)}`
|
||||
const obj: AssetsIntegrityIndex = { entries, bundleHash }
|
||||
const json = JSON.stringify(obj, null, 2)
|
||||
return new TextEncoder().encode(json)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsMetadata, type AssetMetaItem } from '@/lib/exporter/assets.meta'
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
function u8pattern(n: number): Uint8Array {
|
||||
const arr = new Uint8Array(n)
|
||||
for (let i = 0; i < n; i++) arr[i] = (i * 131 + 7) & 0xff
|
||||
return arr
|
||||
}
|
||||
|
||||
function sha256B64(bytes: Uint8Array): string {
|
||||
const h = crypto.createHash('sha256')
|
||||
h.update(Buffer.from(bytes))
|
||||
return h.digest('base64')
|
||||
}
|
||||
|
||||
describe('assets.json integrity = real SHA-256(base64)', () => {
|
||||
it('integrity equals sha256-<base64(sha256(bytes))>', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'] })
|
||||
const bytes = u8pattern(64)
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes })
|
||||
const out = buildAssetsMetadata(am)
|
||||
const json = new TextDecoder().decode(out)
|
||||
const obj = JSON.parse(json) as { assets: AssetMetaItem[] }
|
||||
expect(obj.assets.length).toBe(1)
|
||||
const a = obj.assets[0]
|
||||
const expected = 'sha256-' + sha256B64(bytes)
|
||||
expect(a.integrity).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsMetadata } from '@/lib/exporter/assets.meta'
|
||||
import type { AssetMetaItem } from '@/lib/exporter/assets.meta'
|
||||
|
||||
function u8(n: number): Uint8Array {
|
||||
const arr = new Uint8Array(n)
|
||||
for (let i = 0; i < n; i++) arr[i] = (i * 31) & 0xff
|
||||
return arr
|
||||
}
|
||||
|
||||
describe('Assets metadata builder', () => {
|
||||
it('emits assets.json with originalName/mime/size/hash/ext/zipPath', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'] })
|
||||
const bytes = u8(10)
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes })
|
||||
const metaBytes = buildAssetsMetadata(am)
|
||||
const json = new TextDecoder().decode(metaBytes)
|
||||
const obj = JSON.parse(json) as { assets: AssetMetaItem[] }
|
||||
expect(Array.isArray(obj.assets)).toBe(true)
|
||||
expect(obj.assets.length).toBe(1)
|
||||
const a = obj.assets[0]
|
||||
expect(a.originalName).toBe('hero.png')
|
||||
expect(a.mimeType).toBe('image/png')
|
||||
expect(a.size).toBe(bytes.byteLength)
|
||||
expect(a.ext).toBe('png')
|
||||
expect(a.hash8).toMatch(/^[0-9a-f]{8}$/)
|
||||
expect(a.zipPath).toMatch(/^assets\/[0-9a-f]{8}\.png$/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
export type AssetMetaItem = {
|
||||
originalName: string
|
||||
mimeType: string
|
||||
size: number
|
||||
hash8: string
|
||||
ext: string
|
||||
zipPath: string
|
||||
integrity: string
|
||||
group: 'images' | 'fonts' | 'other'
|
||||
referencedAt: string[]
|
||||
}
|
||||
|
||||
// Minimal synchronous SHA-256 implementation returning base64 string.
|
||||
// Derived from the SHA-256 specification. Suitable for small payloads (asset bytes).
|
||||
function sha256Base64(bytes: Uint8Array): string {
|
||||
const K = new Uint32Array([
|
||||
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
|
||||
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
|
||||
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
|
||||
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
|
||||
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
|
||||
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
|
||||
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
|
||||
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
|
||||
])
|
||||
const H = new Uint32Array([
|
||||
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19
|
||||
])
|
||||
const l = bytes.length
|
||||
const bitLenHi = Math.floor((l >>> 29))
|
||||
const bitLenLo = (l << 3) >>> 0
|
||||
// Pre-processing (padding)
|
||||
const withOne = l + 1
|
||||
// pad to congruent 56 mod 64
|
||||
const padLen = ((withOne % 64) <= 56) ? (56 - (withOne % 64)) : (56 + 64 - (withOne % 64))
|
||||
const totalLen = withOne + padLen + 8
|
||||
const m = new Uint8Array(totalLen)
|
||||
m.set(bytes)
|
||||
m[l] = 0x80
|
||||
// append 64-bit big-endian length
|
||||
m[totalLen - 8] = (bitLenHi >>> 24) & 0xff
|
||||
m[totalLen - 7] = (bitLenHi >>> 16) & 0xff
|
||||
m[totalLen - 6] = (bitLenHi >>> 8) & 0xff
|
||||
m[totalLen - 5] = (bitLenHi >>> 0) & 0xff
|
||||
m[totalLen - 4] = (bitLenLo >>> 24) & 0xff
|
||||
m[totalLen - 3] = (bitLenLo >>> 16) & 0xff
|
||||
m[totalLen - 2] = (bitLenLo >>> 8) & 0xff
|
||||
m[totalLen - 1] = (bitLenLo >>> 0) & 0xff
|
||||
const W = new Uint32Array(64)
|
||||
for (let i = 0; i < totalLen; i += 64) {
|
||||
for (let t = 0; t < 16; t++) {
|
||||
const j = i + t * 4
|
||||
W[t] = (m[j] << 24) | (m[j + 1] << 16) | (m[j + 2] << 8) | (m[j + 3])
|
||||
}
|
||||
for (let t = 16; t < 64; t++) {
|
||||
const s0 = (rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ (W[t - 15] >>> 3)) >>> 0
|
||||
const s1 = (rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ (W[t - 2] >>> 10)) >>> 0
|
||||
W[t] = (W[t - 16] + s0 + W[t - 7] + s1) >>> 0
|
||||
}
|
||||
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7]
|
||||
for (let t = 0; t < 64; t++) {
|
||||
const S1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0
|
||||
const ch = ((e & f) ^ (~e & g)) >>> 0
|
||||
const temp1 = (h + S1 + ch + K[t] + W[t]) >>> 0
|
||||
const S0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0
|
||||
const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
|
||||
const temp2 = (S0 + maj) >>> 0
|
||||
h = g
|
||||
g = f
|
||||
f = e
|
||||
e = (d + temp1) >>> 0
|
||||
d = c
|
||||
c = b
|
||||
b = a
|
||||
a = (temp1 + temp2) >>> 0
|
||||
}
|
||||
H[0] = (H[0] + a) >>> 0
|
||||
H[1] = (H[1] + b) >>> 0
|
||||
H[2] = (H[2] + c) >>> 0
|
||||
H[3] = (H[3] + d) >>> 0
|
||||
H[4] = (H[4] + e) >>> 0
|
||||
H[5] = (H[5] + f) >>> 0
|
||||
H[6] = (H[6] + g) >>> 0
|
||||
H[7] = (H[7] + h) >>> 0
|
||||
}
|
||||
const out = new Uint8Array(32)
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[i * 4 + 0] = (H[i] >>> 24) & 0xff
|
||||
out[i * 4 + 1] = (H[i] >>> 16) & 0xff
|
||||
out[i * 4 + 2] = (H[i] >>> 8) & 0xff
|
||||
out[i * 4 + 3] = (H[i] >>> 0) & 0xff
|
||||
}
|
||||
// base64 encode
|
||||
let b64 = ''
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
b64 = Buffer.from(out).toString('base64')
|
||||
} else {
|
||||
let s = ''
|
||||
for (let i = 0; i < out.length; i++) s += String.fromCharCode(out[i])
|
||||
// btoa is available in browsers
|
||||
b64 = btoa(s)
|
||||
}
|
||||
return b64
|
||||
function rotr(x: number, n: number) { return (x >>> n) | (x << (32 - n)) }
|
||||
}
|
||||
|
||||
export function buildAssetsMetadata(am: AssetManager): Uint8Array {
|
||||
const list = am.list()
|
||||
const referenced = new Set(am.referencedList())
|
||||
const items: AssetMetaItem[] = list.map((ref) => {
|
||||
// Compute real SHA-256(base64) integrity synchronously for browser/Node
|
||||
const b64 = sha256Base64(ref.bytes)
|
||||
const group: 'images' | 'fonts' | 'other' = ref.mimeType.startsWith('image/')
|
||||
? 'images'
|
||||
: ref.mimeType.startsWith('font/')
|
||||
? 'fonts'
|
||||
: 'other'
|
||||
const referencedAt = referenced.has(ref.originalName) ? [`local:${ref.originalName}`] : []
|
||||
return {
|
||||
originalName: ref.originalName,
|
||||
mimeType: ref.mimeType,
|
||||
size: ref.bytes.byteLength,
|
||||
hash8: ref.hash8,
|
||||
ext: ref.ext,
|
||||
zipPath: ref.path,
|
||||
integrity: `sha256-${b64}`,
|
||||
group,
|
||||
referencedAt,
|
||||
}
|
||||
})
|
||||
const json = JSON.stringify({ assets: items }, null, 2)
|
||||
return new TextEncoder().encode(json)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Path Strategy',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'local:hero.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('자산 경로 구조 옵션', () => {
|
||||
it('grouped 전략일 때 이미지가 assets/images/ 경로로 렌더된다', async () => {
|
||||
const page = makePage()
|
||||
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'], pathStrategy: 'grouped' })
|
||||
// add hero image asset
|
||||
const bytes = new Uint8Array([1,2,3,4,5])
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes })
|
||||
const out = exportPage(page, { assetManager: am })
|
||||
expect(out.html).toMatch(/assets\/images\/[a-f0-9]{8}\.png/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsMetadata, type AssetMetaItem } from '@/lib/exporter/assets.meta'
|
||||
|
||||
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
|
||||
|
||||
describe('referencedAt matrix across modes and multiple assets', () => {
|
||||
it.each([
|
||||
{ mode: 'flat' as const },
|
||||
{ mode: 'grouped' as const },
|
||||
])('tracks only referenced originals once per asset ($mode)', async ({ mode }) => {
|
||||
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','woff2'], pathStrategy: mode })
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(10) })
|
||||
await am.add({ name: 'logo.png', type: 'image/png', bytes: u8(12) })
|
||||
await am.add({ name: 'main.woff2', type: 'font/woff2', bytes: u8(14) })
|
||||
|
||||
// reference some assets multiple times; leave logo.png unreferenced
|
||||
am.rewriteUrl('local:hero.png')
|
||||
am.rewriteUrl('local:hero.png')
|
||||
am.rewriteUrl('local:main.woff2')
|
||||
|
||||
const metaBytes = buildAssetsMetadata(am)
|
||||
const obj = JSON.parse(new TextDecoder().decode(metaBytes)) as { assets: AssetMetaItem[] }
|
||||
const byName = new Map(obj.assets.map(a => [a.originalName, a]))
|
||||
|
||||
const hero = byName.get('hero.png')!
|
||||
const logo = byName.get('logo.png')!
|
||||
const font = byName.get('main.woff2')!
|
||||
|
||||
expect(Array.isArray(hero.referencedAt)).toBe(true)
|
||||
expect(hero.referencedAt).toContain('local:hero.png')
|
||||
expect(hero.referencedAt.length).toBe(1)
|
||||
|
||||
expect(Array.isArray(font.referencedAt)).toBe(true)
|
||||
expect(font.referencedAt).toContain('local:main.woff2')
|
||||
expect(font.referencedAt.length).toBe(1)
|
||||
|
||||
expect(Array.isArray(logo.referencedAt)).toBe(true)
|
||||
expect(logo.referencedAt.length).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { buildAssetsMetadata, type AssetMetaItem } from '@/lib/exporter/assets.meta'
|
||||
|
||||
function u8(n: number): Uint8Array {
|
||||
const arr = new Uint8Array(n)
|
||||
for (let i = 0; i < n; i++) arr[i] = (i * 17) & 0xff
|
||||
return arr
|
||||
}
|
||||
|
||||
describe('referencedAt is populated when rewriteUrl is used', () => {
|
||||
it('marks originalName as referenced via local:<name>', async () => {
|
||||
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png'] })
|
||||
await am.add({ name: 'hero.png', type: 'image/png', bytes: u8(16) })
|
||||
// use rewriteUrl to simulate page referencing the local asset
|
||||
const rewritten = am.rewriteUrl('local:hero.png')
|
||||
expect(rewritten).toMatch(/assets\//)
|
||||
const metaBytes = buildAssetsMetadata(am)
|
||||
const obj = JSON.parse(new TextDecoder().decode(metaBytes)) as { assets: AssetMetaItem[] }
|
||||
expect(obj.assets.length).toBe(1)
|
||||
const a = obj.assets[0]
|
||||
expect(Array.isArray(a.referencedAt)).toBe(true)
|
||||
expect(a.referencedAt).toContain('local:hero.png')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(overrides: Partial<Page> = {}): Page {
|
||||
const base: Page = {
|
||||
title: 'CTA Edge',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'cta', props: { text: ' ', href: '#' } },
|
||||
{ type: 'features', props: { items: ['One'] } },
|
||||
] as Page['sections'],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
|
||||
seo: { title: 't', description: 'd' },
|
||||
}
|
||||
return pageSchema.parse({ ...base, ...overrides })
|
||||
}
|
||||
|
||||
describe('Exporter - CTA edge cases', () => {
|
||||
it('drops CTA section when text is whitespace-only', () => {
|
||||
const out = exportPage(makePage())
|
||||
expect(out.html).not.toContain('<section class="cta"')
|
||||
expect(out.html).not.toContain('<a class="btn-cta"')
|
||||
})
|
||||
|
||||
it('renders CTA when text is valid after trimming', () => {
|
||||
const out = exportPage(makePage({ sections: [ { type: 'cta', props: { text: ' Buy Now ', href: '#' } } ] as Page['sections'] }))
|
||||
expect(out.html).toContain('<a class="btn-cta" href="#">Buy Now</a>')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Dark Contrast Hover',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Welcome', subheading: 'Sub', imageUrl: 'https://img.example/h.png' } },
|
||||
{ type: 'cta', props: { text: 'Call', href: '#' } },
|
||||
],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Exporter - dark mode hover/cta tokens', () => {
|
||||
it('adds link hover underline and ensures btn-cta readable in dark', () => {
|
||||
const out = exportPage(makePage())
|
||||
const css = out.css
|
||||
|
||||
// underline on hover for links in dark for clearer affordance
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)[\s\S]*a:hover\{[^}]*text-decoration:underline/i)
|
||||
|
||||
// btn-cta has readable foreground/background in dark
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)[\s\S]*\.btn-cta\{[^}]*background:[^;]+;[^}]*color:#fff/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Dark Contrast',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Welcome', subheading: 'Sub', imageUrl: 'https://img.example/h.png' } },
|
||||
{ type: 'faq', props: { items: [{ q: 'Q', a: 'A' }] } },
|
||||
{ type: 'cta', props: { text: 'Go', href: '#' } },
|
||||
],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Exporter - dark mode contrast tokens', () => {
|
||||
it('includes dark mode tokens that improve contrast for links/buttons/faq text', () => {
|
||||
const out = exportPage(makePage())
|
||||
const css = out.css
|
||||
|
||||
// dark mode block exists
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)/)
|
||||
|
||||
// link color token in dark
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)[\s\S]*a\{[^}]*color:#93c5fd/i)
|
||||
|
||||
// button keeps readable foreground/background in dark
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)[\s\S]*button\{[^}]*background:[^;]+;[^}]*color:#fff/i)
|
||||
|
||||
// faq answer text brighter in dark
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)[\s\S]*\.faq-a\{[^}]*color:#cbd5e1/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'My Product',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: '', imageUrl: 'https://example.com/hero.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
function toStr(bytes: Uint8Array) {
|
||||
return new TextDecoder().decode(bytes)
|
||||
}
|
||||
|
||||
describe('extras 자동 보강', () => {
|
||||
it('manifest: 잘못된 theme_color는 무시하고 기본(primaryColor) 사용', () => {
|
||||
const page = makePage()
|
||||
const out = buildExtrasForPage(page, { manifest: { theme_color: 'not-a-hex' } })
|
||||
const manifest = JSON.parse(toStr(out['site.webmanifest']))
|
||||
expect(manifest.theme_color).toBe('#0ea5e9')
|
||||
})
|
||||
|
||||
it('manifest: short_name은 12자 이내로 자동 절단', () => {
|
||||
const page = makePage()
|
||||
const out = buildExtrasForPage(page, { manifest: { name: 'Super Long Product Name' } })
|
||||
const manifest = JSON.parse(toStr(out['site.webmanifest']))
|
||||
expect(manifest.short_name.length).toBeLessThanOrEqual(12)
|
||||
})
|
||||
|
||||
it('robots: 주어진 plain 경로 목록을 자동으로 User-agent 헤더와 Disallow 라인으로 보강', () => {
|
||||
const page = makePage()
|
||||
const robotsPlain = "/admin\n/private"
|
||||
const out = buildExtrasForPage(page, { robotsText: robotsPlain })
|
||||
const robots = toStr(out['robots.txt'])
|
||||
expect(robots).toMatch(/^User-agent: \*/)
|
||||
expect(robots).toMatch(/Disallow: \/admin/)
|
||||
expect(robots).toMatch(/Disallow: \/private/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Overrides',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('extras 오버라이드', () => {
|
||||
it('robots.txt Disallow 오버라이드가 반영된다', () => {
|
||||
const page = makePage()
|
||||
const extras = buildExtrasForPage(page, { robotsText: 'User-agent: *\nDisallow: /admin\nDisallow: /private' })
|
||||
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
|
||||
expect(robots).toContain('User-agent: *')
|
||||
expect(robots).toContain('Disallow: /admin')
|
||||
expect(robots).toContain('Disallow: /private')
|
||||
})
|
||||
|
||||
it('manifest 필드 오버라이드(name/short_name/start_url/display/theme_color)가 반영된다', () => {
|
||||
const page = makePage()
|
||||
const extras = buildExtrasForPage(page, {
|
||||
manifest: {
|
||||
name: 'My App',
|
||||
short_name: 'MyApp',
|
||||
start_url: '/start',
|
||||
display: 'minimal-ui',
|
||||
theme_color: '#123abc',
|
||||
},
|
||||
})
|
||||
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
|
||||
const manifest = JSON.parse(manifestStr)
|
||||
expect(manifest.name).toBe('My App')
|
||||
expect(manifest.short_name).toBe('MyApp')
|
||||
expect(manifest.start_url).toBe('/start')
|
||||
expect(manifest.display).toBe('minimal-ui')
|
||||
expect(manifest.theme_color).toBe('#123abc')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { Page } from '@/lib/schema/page'
|
||||
|
||||
export type ExtrasOverrides = {
|
||||
robotsText?: string
|
||||
manifest?: Partial<{
|
||||
name: string
|
||||
short_name: string
|
||||
start_url: string
|
||||
display: string
|
||||
theme_color: string
|
||||
}>
|
||||
sheetsMode?: 'auto' | 'include' | 'exclude'
|
||||
}
|
||||
|
||||
function toBytes(s: string): Uint8Array {
|
||||
return new TextEncoder().encode(s)
|
||||
}
|
||||
|
||||
function buildRobots(base?: string): string {
|
||||
if (base && base.trim().length > 0) {
|
||||
const s = base.trim()
|
||||
if (/^User-agent:/i.test(s)) return s
|
||||
const lines = s.split(/\n+/).map((l) => l.trim()).filter((l) => l.length > 0)
|
||||
if (lines.length === 0) return 'User-agent: *\n'
|
||||
const disallowLines = lines.map((l) => (l.startsWith('Disallow:') ? l : `Disallow: ${l}`))
|
||||
return `User-agent: *\n${disallowLines.join('\n')}`
|
||||
}
|
||||
return 'User-agent: *\n'
|
||||
}
|
||||
|
||||
function deriveManifest(page: Page) {
|
||||
const name = page.title || 'Landing'
|
||||
const short_name = name.length > 12 ? name.slice(0, 12) : name
|
||||
const start_url = '/'
|
||||
const display = 'standalone'
|
||||
const theme_color = page.theme?.primaryColor || '#0ea5e9'
|
||||
return { name, short_name, start_url, display, theme_color }
|
||||
}
|
||||
|
||||
export function buildExtrasForPage(page: Page, overrides?: ExtrasOverrides): Record<string, Uint8Array> {
|
||||
const out: Record<string, Uint8Array> = {}
|
||||
|
||||
// robots.txt
|
||||
const robotsText = buildRobots(overrides?.robotsText)
|
||||
out['robots.txt'] = toBytes(robotsText)
|
||||
|
||||
// site.webmanifest (auto-enrich and safe-merge)
|
||||
const manifestBase = deriveManifest(page)
|
||||
const ov = overrides?.manifest || {}
|
||||
const name = ov.name && ov.name.trim().length > 0 ? ov.name : manifestBase.name
|
||||
const short_name = ov.short_name && ov.short_name.trim().length > 0
|
||||
? ov.short_name
|
||||
: (name.length > 12 ? name.slice(0, 12) : name)
|
||||
const start_url = ov.start_url && ov.start_url.trim().length > 0 ? ov.start_url : manifestBase.start_url
|
||||
const display = ov.display && ov.display.trim().length > 0 ? ov.display : manifestBase.display
|
||||
const hexOk = ov.theme_color ? /^#([0-9a-fA-F]{3}){1,2}$/.test(ov.theme_color) : false
|
||||
const theme_color = hexOk ? (ov.theme_color as string) : manifestBase.theme_color
|
||||
const manifestMerged = { name, short_name, start_url, display, theme_color }
|
||||
const manifestJson = JSON.stringify(manifestMerged, null, 2)
|
||||
out['site.webmanifest'] = toBytes(manifestJson)
|
||||
|
||||
// Google Sheets 템플릿: 기본 auto. overrides.sheetsMode로 강제 포함/제외 가능
|
||||
const mode = overrides?.sheetsMode ?? 'auto'
|
||||
const action = page.form?.actionUrl?.trim()
|
||||
const hasAction = !!(action && action.length > 0)
|
||||
const shouldInclude = mode === 'include' || (mode === 'auto' && !hasAction)
|
||||
if (shouldInclude) {
|
||||
const code = `/**
|
||||
* Google Apps Script Web App for form submissions
|
||||
* - Deploy as Web App and set URL as form action if needed.
|
||||
*/
|
||||
function doPost(e){
|
||||
// TODO: handle submission to Google Sheets
|
||||
return ContentService.createTextOutput('OK')
|
||||
}
|
||||
`
|
||||
const readme = `Google Sheets Apps Script Template\n\n1) Apps Script에서 새 프로젝트를 만들고 아래 Code.gs를 붙여넣으세요.\n2) 배포 > 웹 앱으로 배포 후 URL을 복사해 사용하세요.`
|
||||
out['sheets/Code.gs'] = toBytes(code)
|
||||
out['sheets/README.txt'] = toBytes(readme)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Font Opt',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('폰트 최적화', () => {
|
||||
it('head에 Google Fonts preconnect 링크가 포함된다', () => {
|
||||
const page = makePage()
|
||||
const out = exportPage(page)
|
||||
expect(out.html).toContain('<link rel="preconnect" href="https://fonts.googleapis.com"')
|
||||
expect(out.html).toContain('<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin')
|
||||
})
|
||||
|
||||
it('CSS에 system-ui 폴백이 포함된다', () => {
|
||||
const page = makePage()
|
||||
const out = exportPage(page)
|
||||
expect(out.css).toMatch(/font-family:[^;]*system-ui/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage, type ExportOptions } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(fontFamily = 'Inter'): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Font Preload',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('폰트 preload 옵션', () => {
|
||||
it('옵션이 true이면 Google Fonts stylesheet preload/link를 head에 포함한다', () => {
|
||||
const page = makePage('Inter')
|
||||
const opts: ExportOptions = { fontPreload: true }
|
||||
const out = exportPage(page, opts)
|
||||
expect(out.html).toContain('rel="preload"')
|
||||
expect(out.html).toContain('as="style"')
|
||||
expect(out.html).toContain('fonts.googleapis.com/css2')
|
||||
expect(out.html).toContain('family=Inter')
|
||||
// onload print hack 포함
|
||||
expect(out.html).toMatch(/rel=\"stylesheet\"[^>]+media=\"print\"[^>]+onload=\"this.media='all'\"/)
|
||||
})
|
||||
|
||||
it('옵션이 false이면 preload/link를 포함하지 않는다', () => {
|
||||
const page = makePage('Inter')
|
||||
const opts: ExportOptions = { fontPreload: false }
|
||||
const out = exportPage(page, opts)
|
||||
expect(out.html).not.toMatch(/fonts.googleapis.com\/css2/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(overrides: Partial<Page> = {}): Page {
|
||||
const base: Page = {
|
||||
title: 'Hero Edge',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Welcome', subheading: ' ', imageUrl: 'https://img.example/h.png' } },
|
||||
] as Page['sections'],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
|
||||
seo: { title: 't', description: 'd' },
|
||||
}
|
||||
return pageSchema.parse({ ...base, ...overrides })
|
||||
}
|
||||
|
||||
describe('Exporter - hero edge cases', () => {
|
||||
it('omits subheading when whitespace-only', () => {
|
||||
const out = exportPage(makePage())
|
||||
expect(out.html).toContain('<h1 id="hero-heading">Welcome</h1>')
|
||||
expect(out.html).not.toMatch(/<div class="text">[\s\S]*<p>\s*<\/p>/)
|
||||
})
|
||||
|
||||
it('trims subheading content', () => {
|
||||
const out = exportPage(makePage({ sections: [ { type: 'hero', props: { heading: 'Welcome', subheading: ' Hello world ', imageUrl: 'https://img.example/h.png' } } ] as Page['sections'] }))
|
||||
expect(out.html).toContain('<p>Hello world</p>')
|
||||
})
|
||||
})
|
||||
+60
-19
@@ -2,10 +2,22 @@ import type { Page, FormField } from '@/lib/schema/page'
|
||||
import type { AssetManager } from '@/lib/assets/assetManager'
|
||||
|
||||
export type Exported = { html: string; css: string; js: string }
|
||||
export type ExportOptions = { assetManager?: AssetManager }
|
||||
export type ExportOptions = {
|
||||
assetManager?: AssetManager
|
||||
fontPreconnect?: boolean
|
||||
fontPreload?: boolean
|
||||
robotsMeta?: string
|
||||
imageLoading?: 'lazy' | 'eager'
|
||||
imageDecoding?: 'async' | 'sync'
|
||||
}
|
||||
|
||||
function renderFaq(section: { props: { items: Array<{ q: string; a: string }> } }) {
|
||||
const items: Array<{ q: string; a: string }> = Array.isArray(section.props.items) ? section.props.items : []
|
||||
const itemsRaw: Array<{ q: string; a: string }> = Array.isArray(section.props.items) ? section.props.items : []
|
||||
const isBlank = (s: string | undefined | null) => !s || s.trim().length === 0
|
||||
const items = itemsRaw
|
||||
.map((it) => ({ q: (it.q || '').trim(), a: (it.a || '').trim() }))
|
||||
// drop when both question and answer are blank
|
||||
.filter((it) => !(isBlank(it.q) && isBlank(it.a)))
|
||||
return `
|
||||
<section class="faq" aria-labelledby="faq-heading">
|
||||
<div class="container">
|
||||
@@ -27,7 +39,9 @@ function renderFaq(section: { props: { items: Array<{ q: string; a: string }> }
|
||||
}
|
||||
|
||||
function renderFeatures(section: { props: { items: string[] } }) {
|
||||
const items: string[] = Array.isArray(section.props?.items) ? section.props.items : []
|
||||
const items: string[] = (Array.isArray(section.props?.items) ? section.props.items : [])
|
||||
.map((s) => String(s ?? '').trim())
|
||||
.filter((s) => s.length > 0)
|
||||
return `
|
||||
<section class="features" aria-labelledby="features-heading">
|
||||
<div class="container">
|
||||
@@ -41,7 +55,9 @@ function renderFeatures(section: { props: { items: string[] } }) {
|
||||
}
|
||||
|
||||
function renderBenefits(section: { props: { items: string[] } }) {
|
||||
const items: string[] = Array.isArray(section.props?.items) ? section.props.items : []
|
||||
const items: string[] = (Array.isArray(section.props?.items) ? section.props.items : [])
|
||||
.map((s) => String(s ?? '').trim())
|
||||
.filter((s) => s.length > 0)
|
||||
return `
|
||||
<section class="benefits" aria-labelledby="benefits-heading">
|
||||
<div class="container">
|
||||
@@ -55,9 +71,12 @@ function renderBenefits(section: { props: { items: string[] } }) {
|
||||
}
|
||||
|
||||
function renderTestimonials(section: { props: { items: Array<{ author: string; quote: string }> } }) {
|
||||
const items: Array<{ author: string; quote: string }> = Array.isArray(section.props?.items)
|
||||
const items: Array<{ author: string; quote: string }> = (Array.isArray(section.props?.items)
|
||||
? section.props.items
|
||||
: []
|
||||
: [])
|
||||
.map((it) => ({ author: (it.author || '').trim(), quote: (it.quote || '').trim() }))
|
||||
// drop when both are blank
|
||||
.filter((it) => !(it.author.length === 0 && it.quote.length === 0))
|
||||
return `
|
||||
<section class="testimonials" aria-labelledby="testimonials-heading">
|
||||
<div class="container">
|
||||
@@ -66,8 +85,8 @@ function renderTestimonials(section: { props: { items: Array<{ author: string; q
|
||||
.map(
|
||||
(it) => `
|
||||
<figure class="testimonial">
|
||||
<blockquote>“${escapeHtml(it.quote || '')}”</blockquote>
|
||||
<figcaption>— ${escapeHtml(it.author || '')}</figcaption>
|
||||
<blockquote>“${escapeHtml(it.quote)}”</blockquote>
|
||||
${it.author.length > 0 ? `<figcaption>— ${escapeHtml(it.author)}</figcaption>` : ''}
|
||||
</figure>`
|
||||
)
|
||||
.join('')}
|
||||
@@ -77,7 +96,9 @@ function renderTestimonials(section: { props: { items: Array<{ author: string; q
|
||||
}
|
||||
|
||||
function renderCta(section: { props: { text: string; href?: string } }) {
|
||||
const { text, href } = section.props
|
||||
const href = section.props.href
|
||||
const text = (section.props.text || '').trim()
|
||||
if (text.length === 0) return ''
|
||||
return `
|
||||
<section class="cta" aria-labelledby="cta-heading">
|
||||
<div class="container">
|
||||
@@ -96,19 +117,23 @@ const escapeHtml = (s: string) =>
|
||||
.replaceAll('"', '"')
|
||||
|
||||
function renderHero(section: { props: { heading: string; subheading?: string; imageUrl: string } }, opts?: ExportOptions) {
|
||||
const { heading, subheading } = section.props
|
||||
const { heading } = section.props
|
||||
const subheadingRaw = section.props.subheading
|
||||
const subheading = subheadingRaw ? subheadingRaw.trim() : ''
|
||||
const am = opts?.assetManager
|
||||
const imageUrlRaw: string = section.props.imageUrl
|
||||
const imageUrl = am ? am.rewriteUrl(imageUrlRaw) : imageUrlRaw
|
||||
const loading = opts?.imageLoading ?? 'lazy'
|
||||
const decoding = opts?.imageDecoding ?? 'async'
|
||||
return `
|
||||
<section class="hero" aria-labelledby="hero-heading">
|
||||
<div class="container">
|
||||
<div class="text">
|
||||
<h1 id="hero-heading">${escapeHtml(heading)}</h1>
|
||||
${subheading ? `<p>${escapeHtml(subheading)}</p>` : ''}
|
||||
${subheading.length > 0 ? `<p>${escapeHtml(subheading)}</p>` : ''}
|
||||
</div>
|
||||
<div class="media">
|
||||
<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" />
|
||||
<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" loading="${escapeHtml(loading)}" decoding="${escapeHtml(decoding)}" width="1200" height="675" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -206,7 +231,7 @@ function renderForm(page: Page) {
|
||||
`
|
||||
}
|
||||
|
||||
function buildHead(page: Page) {
|
||||
function buildHead(page: Page, opts?: ExportOptions) {
|
||||
const ogImage = page.seo.ogImage
|
||||
const analyticsParts: string[] = []
|
||||
const ga = page.analytics?.ga4MeasurementId
|
||||
@@ -234,9 +259,23 @@ function buildHead(page: Page) {
|
||||
</script>`)
|
||||
}
|
||||
const custom = page.analytics?.customHeadHtml || ''
|
||||
const preconnect = opts?.fontPreconnect !== false
|
||||
const robotsMeta = (opts?.robotsMeta && opts.robotsMeta.trim().length > 0) ? `<meta name="robots" content="${escapeHtml(opts!.robotsMeta!)}" />` : ''
|
||||
const fontPreload = opts?.fontPreload === true
|
||||
const rawFamily = (page.theme?.fontFamily || '').trim()
|
||||
const fontHref = rawFamily.length > 0 ? `https://fonts.googleapis.com/css2?family=${encodeURIComponent(rawFamily).replace(/%20/g, '+')}&display=swap` : ''
|
||||
return `
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="canonical" href="/" />
|
||||
${preconnect ? '<link rel="preconnect" href="https://fonts.googleapis.com" />' : ''}
|
||||
${preconnect ? '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />' : ''}
|
||||
${fontPreload && fontHref ? `<link rel="preload" as="style" href="${fontHref}" />` : ''}
|
||||
${fontPreload && fontHref ? `<link rel="stylesheet" href="${fontHref}" media="print" onload="this.media='all'" />` : ''}
|
||||
${fontPreload && fontHref ? `<noscript><link rel="stylesheet" href="${fontHref}" /></noscript>` : ''}
|
||||
<link rel="manifest" href="/site.webmanifest" />
|
||||
<meta name="theme-color" content="${escapeHtml(page.theme.primaryColor)}" />
|
||||
${robotsMeta}
|
||||
<title>${escapeHtml(page.seo.title)}</title>
|
||||
<meta name="description" content="${escapeHtml(page.seo.description)}" />
|
||||
<meta property="og:title" content="${escapeHtml(page.seo.title)}" />
|
||||
@@ -261,17 +300,20 @@ function buildCss(page: Page) {
|
||||
button:focus, a:focus, input:focus, select:focus, textarea:focus{ outline: 3px solid #2563eb; outline-offset:2px }
|
||||
.faq-list{ list-style:none; padding:0; margin:0 }
|
||||
.faq-item{ margin: .75rem 0 }
|
||||
.faq-q{ font-size: 1rem; font-weight:600; }
|
||||
.faq-a{ color:#334155 }
|
||||
.faq-q{ font-size: 1rem; font-weight:600; overflow-wrap:anywhere }
|
||||
.faq-a{ color:#334155; overflow-wrap:anywhere }
|
||||
.btn-cta{ background: var(--primary); color:#fff; padding:.75rem 1rem; border-radius:.5rem; display:inline-block; text-decoration:none }
|
||||
.features{ background:#f8fafc }
|
||||
.features-list{ list-style:none; padding:0; margin:0; display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: .75rem }
|
||||
.feature-item{ background:#fff; border:1px solid #e2e8f0; border-radius:.5rem; padding:.75rem }
|
||||
.feature-item{ background:#fff; border:1px solid #e2e8f0; border-radius:.5rem; padding:.75rem; overflow-wrap:anywhere }
|
||||
.benefits-list{ list-style:none; padding:0; margin:0 }
|
||||
.benefit-item{ overflow-wrap:anywhere }
|
||||
.testimonials{ background:#ffffff }
|
||||
.testimonial{ border-left:4px solid var(--primary); padding:.5rem 1rem; margin: .75rem 0; background:#fefefe }
|
||||
.testimonial blockquote{ margin:0; font-style:italic; color:#1f2937 }
|
||||
.testimonial blockquote{ margin:0; font-style:italic; color:#1f2937; overflow-wrap:anywhere }
|
||||
.testimonial figcaption{ color:#475569; margin-top:.25rem }
|
||||
@media (max-width: 640px){ .container{ padding: 1rem } h1{ font-size: 1.5rem } }
|
||||
@media (prefers-color-scheme: dark){ body{ color:#e5e7eb; background:#0b1020 } .feature-item{ background:#0f172a; border-color:#1f2937 } a{ color:#93c5fd } a:hover{ text-decoration:underline } button{ background: var(--primary); color:#fff } .btn-cta{ background: var(--primary); color:#fff } .faq-a{ color:#cbd5e1 } }
|
||||
@media (prefers-reduced-motion: reduce){ *{ transition: none !important; animation: none !important } }
|
||||
`
|
||||
}
|
||||
@@ -315,8 +357,7 @@ export function exportPage(page: Page, opts?: ExportOptions): Exported {
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="${escapeHtml(page.locale)}">
|
||||
<head>
|
||||
${buildHead(page)}
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
${buildHead(page, opts)}
|
||||
</head>
|
||||
<body>
|
||||
<a href="#main" class="skip-link">Skip to content</a>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage, type ExportOptions } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Img Perf',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('이미지 loading/decoding 토글', () => {
|
||||
it('기본은 loading="lazy", decoding="async"', () => {
|
||||
const page = makePage()
|
||||
const out = exportPage(page)
|
||||
expect(out.html).toContain('loading="lazy"')
|
||||
expect(out.html).toContain('decoding="async"')
|
||||
})
|
||||
|
||||
it('옵션으로 eager/sync로 바꿀 수 있다', () => {
|
||||
const page = makePage()
|
||||
const opts: ExportOptions = { imageLoading: 'eager', imageDecoding: 'sync' }
|
||||
const out = exportPage(page, opts)
|
||||
expect(out.html).toContain('loading="eager"')
|
||||
expect(out.html).toContain('decoding="sync"')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Head Links',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Exporter - head 링크 토큰', () => {
|
||||
it('site.webmanifest 링크를 포함한다', () => {
|
||||
const out = exportPage(makePage())
|
||||
expect(out.html).toMatch(/<link rel="manifest" href="\/site\.webmanifest"\s*\/>/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Auto Extras',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('extras 자동 생성', () => {
|
||||
it('robots.txt와 site.webmanifest가 extras에 포함된다', () => {
|
||||
const page = makePage()
|
||||
const extras = buildExtrasForPage(page)
|
||||
const keys = Object.keys(extras)
|
||||
expect(keys).toContain('robots.txt')
|
||||
expect(keys).toContain('site.webmanifest')
|
||||
|
||||
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
|
||||
expect(robots).toContain('User-agent: *')
|
||||
|
||||
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
|
||||
const manifest = JSON.parse(manifestStr)
|
||||
expect(manifest.start_url).toBeDefined()
|
||||
expect(manifest.display).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage, type ExportOptions } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Meta Robots',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('meta robots', () => {
|
||||
it('기본적으로 head에 robots 메타가 없다', () => {
|
||||
const page = makePage()
|
||||
const out = exportPage(page)
|
||||
expect(out.html).not.toContain('<meta name="robots"')
|
||||
})
|
||||
|
||||
it('옵션으로 robots 메타를 삽입할 수 있다', () => {
|
||||
const page = makePage()
|
||||
const opts: ExportOptions = { robotsMeta: 'noindex,nofollow' }
|
||||
const out = exportPage(page, opts)
|
||||
expect(out.html).toContain('<meta name="robots" content="noindex,nofollow" />')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(overrides: Partial<Page> = {}): Page {
|
||||
const base: Page = {
|
||||
title: 'Edge',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'features', props: { items: ['One', ' ', ' ', 'Two'] } },
|
||||
{ type: 'benefits', props: { items: ['A', ' ', ' ', 'B'] } },
|
||||
{ type: 'faq', props: { items: [
|
||||
{ q: ' ', a: ' ' },
|
||||
{ q: 'Valid Q', a: ' ' },
|
||||
{ q: 'Another', a: 'Answer' },
|
||||
] } },
|
||||
{ type: 'testimonials', props: { items: [
|
||||
{ author: ' ', quote: ' ' },
|
||||
{ author: 'Jane', quote: ' Great product ' },
|
||||
] } },
|
||||
] as Page['sections'],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
|
||||
seo: { title: 't', description: 'd' },
|
||||
}
|
||||
return pageSchema.parse({ ...base, ...overrides })
|
||||
}
|
||||
|
||||
describe('Exporter - sections edge cases', () => {
|
||||
it('filters out whitespace-only items and keeps valid ones', () => {
|
||||
const out = exportPage(makePage())
|
||||
const html = out.html
|
||||
|
||||
// features: only One, Two
|
||||
expect(html).toContain('<li class="feature-item">One</li>')
|
||||
expect(html).toContain('<li class="feature-item">Two</li>')
|
||||
expect(html).not.toMatch(/<li class="feature-item"><\/li>/)
|
||||
|
||||
// benefits: only A, B
|
||||
expect(html).toContain('<li class="benefit-item">A</li>')
|
||||
expect(html).toContain('<li class="benefit-item">B</li>')
|
||||
|
||||
// faq: drop fully empty, keep items even if answer empty when question is valid
|
||||
expect(html).toContain('<h3 class="faq-q">Valid Q</h3>')
|
||||
// testimonials: drop fully empty, keep trimmed quote
|
||||
expect(html).toContain('<blockquote>“Great product”</blockquote>')
|
||||
})
|
||||
|
||||
it('adds word-break tokens to avoid overflow for long words', () => {
|
||||
const out = exportPage(makePage())
|
||||
const css = out.css
|
||||
expect(css).toMatch(/\.feature-item\{[\s\S]*(?:word-break:break-word|overflow-wrap:anywhere)/i)
|
||||
expect(css).toMatch(/\.benefit-item\{[\s\S]*(?:word-break:break-word|overflow-wrap:anywhere)/i)
|
||||
expect(css).toMatch(/\.testimonial blockquote\{[\s\S]*(?:word-break:break-word|overflow-wrap:anywhere)/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(overrides: Partial<Page> = {}): Page {
|
||||
const base: Page = {
|
||||
title: 'Edge P3',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'faq', props: { items: [ { q: 'VeryVeryVeryVeryVeryLongWordWithoutSpaces', a: 'AnotherSuperLongUnbreakableWord' } ] } },
|
||||
{ type: 'testimonials', props: { items: [
|
||||
{ author: ' ', quote: 'Great!' },
|
||||
{ author: 'Alice', quote: 'Nice' },
|
||||
] } },
|
||||
] as Page['sections'],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
|
||||
seo: { title: 't', description: 'd' },
|
||||
}
|
||||
return pageSchema.parse({ ...base, ...overrides })
|
||||
}
|
||||
|
||||
describe('Exporter - phase3 edge cases', () => {
|
||||
it('omits testimonial author line when author is blank', () => {
|
||||
const out = exportPage(makePage())
|
||||
const html = out.html
|
||||
// First item author blank -> no figcaption for that blockquote
|
||||
expect(html).toMatch(/<blockquote>“Great!\”<\/blockquote>[\s\S]*?<\/figure>/)
|
||||
// Ensure the next item with author renders figcaption
|
||||
expect(html).toMatch(/<figcaption>— Alice<\/figcaption>/)
|
||||
})
|
||||
|
||||
it('adds word-break/overflow-wrap for FAQ q/a to avoid overflow', () => {
|
||||
const out = exportPage(makePage())
|
||||
const css = out.css
|
||||
expect(css).toMatch(/\.faq-q\{[\s\S]*(?:overflow-wrap:anywhere|word-break:break-word)/i)
|
||||
expect(css).toMatch(/\.faq-a\{[\s\S]*(?:overflow-wrap:anywhere|word-break:break-word)/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'SEO/Perf 2',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img.example/hero.png' } },
|
||||
],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 'SEO2', description: 'Desc2' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Exporter - theme-color meta and hero image intrinsic size', () => {
|
||||
it('includes theme-color meta using page.theme.primaryColor', () => {
|
||||
const out = exportPage(makePage())
|
||||
const html = out.html
|
||||
expect(html).toMatch(/<meta name="theme-color" content="#0ea5e9"\s*\/>/)
|
||||
})
|
||||
|
||||
it('renders hero image with width/height attributes for CLS reduction', () => {
|
||||
const out = exportPage(makePage())
|
||||
const html = out.html
|
||||
expect(html).toMatch(/<img[^>]*\swidth="[0-9]+"/)
|
||||
expect(html).toMatch(/<img[^>]*\sheight="[0-9]+"/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'SEO/Perf',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Welcome', subheading: 'Sub', imageUrl: 'https://img.example/hero.png' } },
|
||||
],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 'SEO', description: 'Desc' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Exporter - small SEO/Perf improvements', () => {
|
||||
it('includes canonical link and dark mode tokens; hero image lazy/async', () => {
|
||||
const out = exportPage(makePage())
|
||||
const html = out.html
|
||||
const css = out.css
|
||||
|
||||
// canonical link present in head
|
||||
expect(html).toMatch(/<link[^>]+rel="canonical"/)
|
||||
|
||||
// hero image has loading/decoding attributes
|
||||
expect(html).toMatch(/<img[^>]*loading="lazy"/)
|
||||
expect(html).toMatch(/<img[^>]*decoding="async"/)
|
||||
|
||||
// dark mode media query token exists
|
||||
expect(css).toMatch(/@media \(prefers-color-scheme: dark\)/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
|
||||
function makePageNoAction(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Sheets Tpl',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [ { type: 'text', name: 'email', label: 'Email', required: true } ], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
function makePageWithAction(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'Sheets Off',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: 'https://example.com/submit', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('Sheets 템플릿 Export', () => {
|
||||
it('actionUrl 미지정 시 extras에 Sheets 템플릿 파일을 포함한다', async () => {
|
||||
const page = makePageNoAction()
|
||||
const extras = buildExtrasForPage(page)
|
||||
expect(Object.keys(extras)).toContain('sheets/Code.gs')
|
||||
expect(Object.keys(extras)).toContain('sheets/README.txt')
|
||||
|
||||
const out = exportPage(page)
|
||||
const zipBytes = await buildZip({ html: out.html, css: out.css, js: out.js, assets: {}, extras })
|
||||
expect(zipBytes.byteLength).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('actionUrl 지정 시 extras에는 Sheets 템플릿이 포함되지 않는다', () => {
|
||||
const page = makePageWithAction()
|
||||
const extras = buildExtrasForPage(page)
|
||||
expect(Object.keys(extras)).not.toContain('sheets/Code.gs')
|
||||
expect(Object.keys(extras)).not.toContain('sheets/README.txt')
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,8 @@ export type BuildZipInput = {
|
||||
css: string
|
||||
js: string
|
||||
assets?: Record<string, Uint8Array>
|
||||
// root-level extra files like favicon.ico, site.webmanifest, robots.txt
|
||||
extras?: Record<string, Uint8Array>
|
||||
}
|
||||
|
||||
export async function buildZip(input: BuildZipInput): Promise<Uint8Array> {
|
||||
@@ -19,6 +21,22 @@ export async function buildZip(input: BuildZipInput): Promise<Uint8Array> {
|
||||
zip.file(path, buf as unknown as Buffer)
|
||||
}
|
||||
}
|
||||
if (input.extras) {
|
||||
// validate manifest if present
|
||||
if (Object.prototype.hasOwnProperty.call(input.extras, 'site.webmanifest')) {
|
||||
try {
|
||||
const manifestBytes = input.extras['site.webmanifest']
|
||||
const manifestStr = Buffer.from(manifestBytes).toString('utf8')
|
||||
JSON.parse(manifestStr)
|
||||
} catch {
|
||||
throw new Error('Invalid site.webmanifest JSON')
|
||||
}
|
||||
}
|
||||
for (const [path, bytes] of Object.entries(input.extras)) {
|
||||
const buf = Buffer.from(bytes)
|
||||
zip.file(path, buf as unknown as Buffer)
|
||||
}
|
||||
}
|
||||
const content = await zip.generateAsync({ type: 'uint8array' })
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
import { AssetManager } from '@/lib/assets/assetManager'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
|
||||
function makePageWithLocalAsset(): { page: Page; am: AssetManager } {
|
||||
const am = new AssetManager({ maxBytes: 1024 * 1024, allowedExts: ['png','svg','jpg','jpeg','webp'] })
|
||||
// simulate adding a local image and referencing it by original name via local: prefix
|
||||
const bytes = new Uint8Array([7,8,9])
|
||||
// add as "hero.png"
|
||||
am.add({ name: 'hero.png', type: 'image/png', bytes })
|
||||
|
||||
const base: Page = pageSchema.parse({
|
||||
title: 'Integrated ZIP',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [
|
||||
{ type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'local:hero.png' } },
|
||||
{ type: 'cta', props: { text: 'Go', href: '#' } },
|
||||
],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
analytics: { ga4MeasurementId: 'G-TEST', metaPixelId: '', customHeadHtml: '' },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
return { page: base, am }
|
||||
}
|
||||
|
||||
describe('Export ZIP 통합 검증', () => {
|
||||
it('exportPage 출력 + buildZip 결과에서 assets 경로/메타가 보존된다', async () => {
|
||||
const { page, am } = makePageWithLocalAsset()
|
||||
const out = exportPage(page, { assetManager: am })
|
||||
const assets = am.toZipStructure()
|
||||
const zipBytes = await buildZip({ html: out.html, css: out.css, js: out.js, assets })
|
||||
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const names = Object.keys(zip.files)
|
||||
// assets 파일이 존재해야 함
|
||||
const assetKey = Object.keys(assets)[0]
|
||||
expect(names).toContain(assetKey)
|
||||
|
||||
// index.html에 canonical/meta/ga4 스니펫 보존
|
||||
const html = await zip.files['index.html'].async('string')
|
||||
expect(html).toMatch(/<link rel="canonical" href="\//)
|
||||
expect(html).toMatch(/<meta name="description" content="d"/)
|
||||
expect(html).toMatch(/gtag\('config', 'G-TEST'\)/)
|
||||
|
||||
// hero 이미지가 재작성된 경로를 사용한다
|
||||
const match = html.match(/<img[^>]*src="([^"]+)"/)
|
||||
expect(match && match[1]).toBe(assetKey)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
|
||||
describe('Export ZIP 메타 보존 검증', () => {
|
||||
it('index.html의 SEO/OG/Analytics 메타가 그대로 보존된다', async () => {
|
||||
const html = `<!DOCTYPE html><html><head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="canonical" href="/" />
|
||||
<meta name="description" content="desc" />
|
||||
<meta property="og:title" content="OT" />
|
||||
<meta property="og:description" content="OD" />
|
||||
<script>window.dataLayer=[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());</script>
|
||||
</head><body>ok</body></html>`
|
||||
const css = 'body{color:#222}'
|
||||
const js = 'console.log("ok")'
|
||||
|
||||
const zipBytes = await buildZip({ html, css, js, assets: {} })
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const htmlContent = await zip.files['index.html'].async('string')
|
||||
|
||||
expect(htmlContent).toMatch(/<link rel="canonical" href="\//)
|
||||
expect(htmlContent).toMatch(/<meta name="description" content="desc"/)
|
||||
expect(htmlContent).toMatch(/<meta property="og:title" content="OT"/)
|
||||
expect(htmlContent).toMatch(/<meta property="og:description" content="OD"/)
|
||||
expect(htmlContent).toMatch(/window\.dataLayer=\[\];/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
import type { BuildZipInput } from '@/lib/exporter/zip'
|
||||
|
||||
const TE = new TextEncoder()
|
||||
|
||||
describe('Export ZIP 검증 강화 4차: 루트 파일(favicon/manifest/robots)', () => {
|
||||
it('루트 파일들을 포함한다: favicon.ico / site.webmanifest / robots.txt', async () => {
|
||||
const manifest = {
|
||||
name: 'Landing Builder',
|
||||
short_name: 'LB',
|
||||
start_url: '/',
|
||||
display: 'standalone',
|
||||
icons: [{ src: '/favicon.png', sizes: '512x512', type: 'image/png' }],
|
||||
}
|
||||
const input: BuildZipInput = {
|
||||
html: '<!DOCTYPE html><html><head><title>a</title></head><body>ok</body></html>',
|
||||
css: 'body{color:#111}',
|
||||
js: 'console.log("ok")',
|
||||
assets: {},
|
||||
extras: {
|
||||
'favicon.ico': new Uint8Array([0, 1, 2, 3]),
|
||||
'site.webmanifest': TE.encode(JSON.stringify(manifest)),
|
||||
'robots.txt': TE.encode('User-agent: *\nDisallow:'),
|
||||
},
|
||||
}
|
||||
const zipBytes = await buildZip(input)
|
||||
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const names = Object.keys(zip.files)
|
||||
expect(names).toContain('favicon.ico')
|
||||
expect(names).toContain('site.webmanifest')
|
||||
expect(names).toContain('robots.txt')
|
||||
|
||||
const robots = await zip.files['robots.txt'].async('string')
|
||||
expect(robots).toMatch(/User-agent: \*/)
|
||||
|
||||
const parsed = JSON.parse(await zip.files['site.webmanifest'].async('string'))
|
||||
expect(parsed.name).toBe('Landing Builder')
|
||||
expect(parsed.icons[0].type).toBe('image/png')
|
||||
})
|
||||
|
||||
it('잘못된 manifest JSON이면 실패한다', async () => {
|
||||
const badInput: BuildZipInput = {
|
||||
html: '<!DOCTYPE html><html><head><title>a</title></head><body>ok</body></html>',
|
||||
css: 'body{color:#111}',
|
||||
js: 'console.log("ok")',
|
||||
extras: { 'site.webmanifest': TE.encode('{ invalid json') },
|
||||
}
|
||||
await expect(buildZip(badInput)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
import { exportPage } from '@/lib/exporter/html'
|
||||
import { pageSchema, type Page } from '@/lib/schema/page'
|
||||
import { buildExtrasForPage } from '@/lib/exporter/extras'
|
||||
|
||||
function makePage(): Page {
|
||||
return pageSchema.parse({
|
||||
title: 'ZIP Phase5',
|
||||
locale: 'en',
|
||||
theme: { primaryColor: '#2563eb', fontFamily: 'Inter' },
|
||||
sections: [ { type: 'hero', props: { heading: 'Hello', subheading: 'World', imageUrl: 'https://img/h.png' } } ],
|
||||
form: { actionUrl: '', fields: [], spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 } },
|
||||
seo: { title: 't', description: 'd' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('ZIP 검증 Phase5', () => {
|
||||
it('robots.txt 베이스라인과 site.webmanifest JSON 파싱 검증', async () => {
|
||||
const page = makePage()
|
||||
const extras = buildExtrasForPage(page)
|
||||
|
||||
// baseline robots
|
||||
const robots = Buffer.from(extras['robots.txt']).toString('utf8')
|
||||
expect(robots).toContain('User-agent: *')
|
||||
|
||||
// manifest JSON parseable
|
||||
const manifestStr = Buffer.from(extras['site.webmanifest']).toString('utf8')
|
||||
const manifest = JSON.parse(manifestStr)
|
||||
expect(manifest && typeof manifest === 'object').toBe(true)
|
||||
expect(manifest.start_url).toBeDefined()
|
||||
expect(manifest.display).toBeDefined()
|
||||
|
||||
// ZIP build should succeed
|
||||
const out = exportPage(page)
|
||||
const zipBytes = await buildZip({ html: out.html, css: out.css, js: out.js, assets: {}, extras })
|
||||
expect(zipBytes.byteLength).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import JSZip from 'jszip'
|
||||
import { buildZip } from '@/lib/exporter/zip'
|
||||
|
||||
const TE = new TextEncoder()
|
||||
|
||||
describe('Export ZIP 검증 강화', () => {
|
||||
it('assets가 비어있을 때 index.html/styles.css/app.js만 포함한다', async () => {
|
||||
const zipBytes = await buildZip({
|
||||
html: '<!DOCTYPE html><html><head><title>a</title></head><body>ok</body></html>',
|
||||
css: 'body{color:#111}',
|
||||
js: 'console.log("ok")',
|
||||
assets: {},
|
||||
})
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const names = Object.keys(zip.files).sort()
|
||||
expect(names).toEqual(['app.js','index.html','styles.css'])
|
||||
})
|
||||
|
||||
it('assets가 있으면 모든 파일을 그대로 포함한다(서브폴더 포함)', async () => {
|
||||
const assets = {
|
||||
'assets/img/logo.png': new Uint8Array([0,1,2,3]),
|
||||
'assets/svg/icon.svg': TE.encode('<svg></svg>'),
|
||||
'assets/fonts/inter.woff2': new Uint8Array([4,5,6]),
|
||||
}
|
||||
const zipBytes = await buildZip({
|
||||
html: '<!DOCTYPE html><html><head><title>a</title></head><body>ok</body></html>',
|
||||
css: 'body{color:#111}',
|
||||
js: 'console.log("ok")',
|
||||
assets,
|
||||
})
|
||||
const zip = await JSZip.loadAsync(zipBytes)
|
||||
const names = Object.keys(zip.files)
|
||||
expect(names).toContain('index.html')
|
||||
expect(names).toContain('styles.css')
|
||||
expect(names).toContain('app.js')
|
||||
expect(names).toContain('assets/img/logo.png')
|
||||
expect(names).toContain('assets/svg/icon.svg')
|
||||
expect(names).toContain('assets/fonts/inter.woff2')
|
||||
|
||||
const logo = await zip.files['assets/img/logo.png'].async('uint8array')
|
||||
expect(Array.from(logo)).toEqual([0,1,2,3])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user