Compare commits

..

8 Commits

Author SHA1 Message Date
jaybe ba2ba588f7 feat: 이미지 최적화 2·3차(imageAutoSizes/imageSizesPreset) 및 문서/플랜 반영 (TDD)
Auto PR / open-pr (push) Successful in 15s
Auto Label PR / add-automerge-label (pull_request) Successful in 4s
CI / test (pull_request) Successful in 1m8s
- ExportOptions.imageAutoSizes 추가 및 기본 sizes 자동 적용
- ExportOptions.imageSizesPreset 추가(mobile-first/desktop-fixed)
- 우선순위: imageSizes > preset > auto > none
- 테스트 케이스 확장(image.responsive.options.test.ts)
- README/MAIN_PLAN 업데이트
2025-11-16 20:03:33 +09:00
jaybe 396d0ac7a0 feat: 이미지 최적화 옵션 추가(fetchpriority/srcset/sizes) (TDD)
- ExportOptions에 이미지 옵션 추가
- hero 이미지에 조건부 속성 렌더링
- 테스트: image.responsive.options.test.ts
- 전체 테스트 그린 유지
2025-11-16 18:49:39 +09:00
jaybe 19a39230be feat: verifyIntegrity 리포트 확장(summary) 및 테스트 추가\n\n- VerifyResult에 summary(total/missing/integrityMismatches/sizeMismatches/bundleHashMismatch) 추가\n- verify.integrity.test.ts에 summary 단언 추가\n- 전체 테스트 그린 유지 2025-11-16 18:33:16 +09:00
jaybe c519055e90 feat: Sheets 템플릿 가이드 보강(TDD)
- Code.gs에 @tool/@version 헤더, 필드 매핑 TODO, try/catch 에러 처리 추가
- README.txt에 Web App 배포/필드 매핑 가이드 추가
- 테스트 추가: sheets.template.enhance.test.ts
- 전체 테스트 그린 유지
2025-11-16 18:29:54 +09:00
jaybe 7928f9b6c5 feat: ZIP 경로 가드 추가 및 무결성 size 검증 도입 (TDD)
- buildZip에 경로 하드닝 추가: ../, 절대경로(/), 역슬래시(\) 금지
- assets.integrity.index.json에 size(byte) 필드 추가
- verifyIntegrity에서 size 불일치 검증 추가
- 경로/사이즈 검증 테스트 추가: zip.pathGuard.test.ts
- 전체 테스트 그린 유지
2025-11-16 17:30:47 +09:00
jaybe cf8f02bfca docs: 메인플랜 단일화 및 Option2 진행 현황 통합
Auto PR / open-pr (push) Successful in 15s
Auto Label PR / add-automerge-label (pull_request) Successful in 6s
CI / test (pull_request) Successful in 1m11s
2025-11-16 13:11:47 +09:00
jaybe 92aa4f19c7 Option2 무결성 강화: integrity index 추가, 인덱스 정렬/교차 검증, referencedAt 매트릭스, README 문서화 (TDD)
Auto PR / open-pr (push) Successful in 17s
Auto Label PR / add-automerge-label (pull_request) Successful in 6s
CI / test (pull_request) Successful in 1m18s
2025-11-16 12:30:41 +09:00
jaybe 3708ca3521 Option2-무결성: assets.json SHA-256 무결성 계산 및 referencedAt 추적 TDD/구현 2025-11-16 11:05:00 +09:00
22 changed files with 1346 additions and 7 deletions
+412
View File
@@ -0,0 +1,412 @@
# 메인플랜: 랜딩 페이지 빌더
## 목표
- 비개발자도 사용 가능한 단일 페이지 랜딩 페이지 빌더.
- 결과물: 정적 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) 도입 및 템플릿 테스트 추가
- 이미지 최적화 옵션 1차(TDD): hero 이미지에 `fetchpriority`/`srcset`/`sizes` 조건부 렌더링
- 테스트: `lib/exporter/image.responsive.options.test.ts` (속성 존재 검증)
- 구현: `lib/exporter/html.ts`(`ExportOptions`에 옵션 추가 및 `<img>` 렌더 반영)
- 브랜치: `feat/image-optimization` (로컬 커밋, 푸쉬 보류)
- 이미지 최적화 옵션 2차(TDD): `srcset`만 제공 시 기본 `sizes` 자동 적용(`imageAutoSizes`)
- 기본값: `(max-width: 640px) 100vw, 600px`
- 테스트: `image.responsive.options.test.ts` (auto on/off 케이스)
- 구현: `ExportOptions.imageAutoSizes` 추가 및 `renderHero` 적용
- 신규 섹션 추가: 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(정상/변조/누락/번들해시 불일치) 통과
- `assets.integrity.index.json``size`(byte) 추가, `verifyIntegrity`에서 크기 불일치 검증
- `verifyIntegrity` 결과에 `summary`(total/missing/integrityMismatches/sizeMismatches/bundleHashMismatch) 추가
- Export Options(폰트 프리커넥트/프리로드, 이미지 로딩/디코딩, robots 메타) UI/문서화
- 브랜치 푸쉬 완료: `feat/export-bundle-integrity`
- 이미지 최적화 옵션(1차): `fetchpriority`/`srcset`/`sizes` 추가 및 테스트 그린
### 하드닝
- ZIP 경로 가드: `../`, 절대경로(`/`), 역슬래시(`\`) 차단 (테스트 포함)
### 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 활용 예시)
5) 이미지 최적화 2차: `sizes` 기본 정책 프리셋 및 변환 파이프라인(AVIF/WebP) 설계 초안(TDD 스텁)
### CI/CD 계획(초안)
- PR 오픈 시: 라벨 자동 지정, 테스트/빌드, 무결성 검증 스텝 실행
- main 머지 조건: 테스트/빌드 통과 + 무결성 검증 통과 + 최소 라벨 셋 충족
### 커밋/푸쉬 원칙
- 기능 단위 커밋은 한국어 메시지
- 대범위 브랜치 완료 전에 푸쉬 금지(현 단계는 완료되어 푸쉬 수행)
+35
View File
@@ -44,6 +44,7 @@ The Builder can export a production-ready ZIP that contains:
- 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
@@ -62,6 +63,13 @@ The Builder can export a production-ready ZIP that contains:
- Image Options
- Loading: `lazy` (default) or `eager` for `<img loading>`
- Decoding: `async` (default) or `sync` for `<img decoding>`
- Fetch Priority: optional `high|low` for `<img fetchpriority>`
- Srcset/Sizes: optional responsive sources via `<img srcset>` and `<img sizes>`
- Auto Sizes: when enabled and only `srcset` is provided, a sensible default is applied to `<img sizes>`: `(max-width: 640px) 100vw, 600px`
- Sizes Preset: choose a preset for `<img sizes>` when `imageSizes` is not set.
- `mobile-first`: `(max-width: 640px) 100vw, 800px`
- `desktop-fixed`: `1200px`
- Precedence: explicit `imageSizes` > `imageSizesPreset` > `imageAutoSizes` > none
### site.webmanifest and robots.txt
@@ -94,6 +102,33 @@ Simple index to quickly find assets by group:
- fonts: string[] of zip paths
- other: string[] of zip paths
### assets.integrity.index.json
- entries: array of `{ path, integrity, size }`
- `path`: asset `zipPath` (e.g. `assets/abcd1234.png` or grouped `assets/images/...`)
- `integrity`: `sha256-<base64>` (real SHA-256 of the asset bytes)
- `size`: byte length of the asset
- 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 file size matches `entries[].size`.
- Verify bundle integrity by recomputing `bundleHash` from sorted entries; useful for quick tamper detection.
Example (Node):
```ts
import { verifyIntegrity } from '@/lib/exporter/verify'
// extras must include 'assets.integrity.index.json', assets is a map of zipPath -> bytes
const result = verifyIntegrity(extras, assets)
if (!result.ok) {
console.error('Integrity check failed:', result.errors)
}
console.log('Summary:', result.summary)
// { total, missing, integrityMismatches, sizeMismatches, bundleHashMismatch }
```
### Google Sheets template (optional)
- When included, ZIP contains:
+6 -1
View File
@@ -9,6 +9,7 @@ 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'
@@ -285,7 +286,11 @@ export default function BuilderClientPage() {
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) } : {}),
...(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)
+2
View File
@@ -56,5 +56,7 @@ describe('Export Options UI → extras overrides', () => {
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,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)
}
})
})
+34
View File
@@ -19,4 +19,38 @@ describe('Assets index builder', () => {
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$/)
})
})
+5
View File
@@ -7,6 +7,7 @@ export type AssetsIndex = {
}
export function buildAssetsIndex(am: AssetManager): Uint8Array {
// 그룹별 경로 수집
const images: string[] = []
const fonts: string[] = []
const other: string[] = []
@@ -15,6 +16,10 @@ export function buildAssetsIndex(am: AssetManager): Uint8Array {
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)
}
})
})
+99
View File
@@ -0,0 +1,99 @@
import type { AssetManager } from '@/lib/assets/assetManager'
export type AssetsIntegrityIndex = {
entries: Array<{ path: string; integrity: string; size: number }>
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)}`,
size: ref.bytes.length,
}))
// 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)
})
})
+96 -2
View File
@@ -12,12 +12,106 @@ export type AssetMetaItem = {
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) => {
// Browser-safe synchronous integrity: base64 of bytes as placeholder
const b64 = Buffer.from(ref.bytes).toString('base64')
// 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/')
@@ -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')
})
})
+15 -3
View File
@@ -68,13 +68,25 @@ export function buildExtrasForPage(page: Page, overrides?: ExtrasOverrides): Rec
const code = `/**
* Google Apps Script Web App for form submissions
* - Deploy as Web App and set URL as form action if needed.
* @tool: landing-builder
* @version: 1.0.0
*/
function doPost(e){
// TODO: handle submission to Google Sheets
return ContentService.createTextOutput('OK')
try {
// TODO: map incoming fields to sheet columns
// Example:
// const payload = JSON.parse(e.postData.contents || '{}');
// const row = [payload.name, payload.email, new Date()];
// SpreadsheetApp.openById('YOUR_SHEET_ID').getSheetByName('Sheet1').appendRow(row);
return ContentService.createTextOutput('OK')
} catch (e) {
return ContentService
.createTextOutput('ERROR: ' + (e && (e as any).message ? (e as any).message : 'unknown'))
.setMimeType(ContentService.MimeType.TEXT)
}
}
`
const readme = `Google Sheets Apps Script Template\n\n1) Apps Script에서 새 프로젝트를 만들고 아래 Code.gs를 붙여넣으세요.\n2) 배포 > 웹 앱으로 배포 후 URL을 복사해 사용하세요.`
const readme = `Google Sheets Apps Script Template\n\n1) Apps Script에서 새 프로젝트를 만들고 아래 Code.gs를 붙여넣으세요.\n2) Deploy as Web App로 배포 후 URL을 복사해 사용하세요.\n3) Map fields to columns: 제출 payload의 필드를 시트 컬럼에 매핑하세요.`
out['sheets/Code.gs'] = toBytes(code)
out['sheets/README.txt'] = toBytes(readme)
}
+17 -1
View File
@@ -9,6 +9,11 @@ export type ExportOptions = {
robotsMeta?: string
imageLoading?: 'lazy' | 'eager'
imageDecoding?: 'async' | 'sync'
imageFetchPriority?: 'high' | 'low'
imageSrcset?: string
imageSizes?: string
imageAutoSizes?: boolean
imageSizesPreset?: 'mobile-first' | 'desktop-fixed'
}
function renderFaq(section: { props: { items: Array<{ q: string; a: string }> } }) {
@@ -125,6 +130,17 @@ function renderHero(section: { props: { heading: string; subheading?: string; im
const imageUrl = am ? am.rewriteUrl(imageUrlRaw) : imageUrlRaw
const loading = opts?.imageLoading ?? 'lazy'
const decoding = opts?.imageDecoding ?? 'async'
const fetchpriority = opts?.imageFetchPriority ? ` fetchpriority="${escapeHtml(opts.imageFetchPriority)}"` : ''
const srcset = opts?.imageSrcset ? ` srcset="${escapeHtml(opts.imageSrcset)}"` : ''
const defaultSizes = '(max-width: 640px) 100vw, 600px'
const presetSizes = (() => {
if (!opts?.imageSizesPreset) return ''
if (opts.imageSizesPreset === 'mobile-first') return '(max-width: 640px) 100vw, 800px'
if (opts.imageSizesPreset === 'desktop-fixed') return '1200px'
return ''
})()
const sizesValue = opts?.imageSizes ?? (presetSizes || (opts?.imageSrcset && opts?.imageAutoSizes ? defaultSizes : ''))
const sizes = sizesValue ? ` sizes="${escapeHtml(sizesValue)}"` : ''
return `
<section class="hero" aria-labelledby="hero-heading">
<div class="container">
@@ -133,7 +149,7 @@ function renderHero(section: { props: { heading: string; subheading?: string; im
${subheading.length > 0 ? `<p>${escapeHtml(subheading)}</p>` : ''}
</div>
<div class="media">
<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" loading="${escapeHtml(loading)}" decoding="${escapeHtml(decoding)}" width="1200" height="675" />
<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(heading)}" loading="${escapeHtml(loading)}" decoding="${escapeHtml(decoding)}"${fetchpriority}${srcset}${sizes} width="1200" height="675" />
</div>
</div>
</section>
@@ -0,0 +1,87 @@
import { describe, it, expect } from 'vitest'
import { exportPage } from '@/lib/exporter/html'
import type { ExportOptions } from '@/lib/exporter/html'
import type { Page } from '@/lib/schema/page'
const basePage: Page = {
title: 'Img Test',
locale: 'en',
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
sections: [
{ type: 'hero', props: { heading: 'Hero', subheading: '', imageUrl: 'https://example.com/hero.jpg' } },
],
form: {
actionUrl: '',
fields: [],
spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
},
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
seo: { title: 'T', description: 'D' },
}
describe('image responsive/export options', () => {
it('applies fetchpriority when provided', () => {
const options: ExportOptions = { imageLoading: 'eager', imageDecoding: 'async', imageFetchPriority: 'high' }
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*fetchpriority="high"/)
})
it('applies srcset and sizes when provided', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageSizes: '(max-width: 640px) 100vw, 600px',
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*srcset="https:\/\/example.com\/hero.jpg 1x, https:\/\/example.com\/hero@2x.jpg 2x"/)
expect(html).toMatch(/<img[^>]*sizes="\(max-width: 640px\) 100vw, 600px"/)
})
it('applies default sizes when srcset is provided and imageAutoSizes is true', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageAutoSizes: true,
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*srcset="https:\/\/example.com\/hero.jpg 1x, https:\/\/example.com\/hero@2x.jpg 2x"/)
expect(html).toMatch(/<img[^>]*sizes="\(max-width: 640px\) 100vw, 600px"/)
})
it('does not include sizes when srcset is provided but imageAutoSizes is false and sizes not provided', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageAutoSizes: false,
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*srcset="https:\/\/example.com\/hero.jpg 1x, https:\/\/example.com\/hero@2x.jpg 2x"/)
expect(html).not.toMatch(/<img[^>]*sizes="/)
})
it('applies preset sizes when imageSizesPreset is set (mobile-first)', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageSizesPreset: 'mobile-first',
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*sizes="\(max-width: 640px\) 100vw, 800px"/)
})
it('applies desktop-fixed preset when selected', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageSizesPreset: 'desktop-fixed',
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*sizes="1200px"/)
})
it('explicit imageSizes overrides presets and auto', () => {
const options: ExportOptions = {
imageSrcset: 'https://example.com/hero.jpg 1x, https://example.com/hero@2x.jpg 2x',
imageAutoSizes: true,
imageSizesPreset: 'desktop-fixed',
imageSizes: '(max-width: 768px) 100vw, 700px',
}
const { html } = exportPage(basePage, options)
expect(html).toMatch(/<img[^>]*sizes="\(max-width: 768px\) 100vw, 700px"/)
})
})
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest'
import { buildExtrasForPage } from '@/lib/exporter/extras'
import type { Page } from '@/lib/schema/page'
function td(b: Uint8Array){ return new TextDecoder().decode(b) }
const basePage: Page = {
title: 'Test',
seo: { title: 'T', description: 'D' },
theme: { primaryColor: '#0ea5e9', fontFamily: 'Inter' },
analytics: { ga4MeasurementId: '', metaPixelId: '', customHeadHtml: '' },
sections: [],
form: {
fields: [],
actionUrl: '',
spamProtection: { honeypotFieldName: '_hp', minSubmitSeconds: 2 },
},
locale: 'en',
}
describe('Sheets template enhance', () => {
it('includes version/meta and mapping/error guide in Code.gs and README', () => {
const extras = buildExtrasForPage(basePage, { sheetsMode: 'include' })
const code = td(extras['sheets/Code.gs'])
const readme = td(extras['sheets/README.txt'])
// version/meta header
expect(code).toMatch(/@version:\s*\d+\.\d+\.\d+/)
expect(code).toMatch(/@tool:\s*landing-builder/i)
// field mapping and error handling guides
expect(code).toMatch(/TODO:\s*map incoming fields to sheet columns/i)
expect(code).toMatch(/try\s*\{/)
expect(code).toMatch(/catch\s*\(e\)/)
// README includes setup and mapping hint
expect(readme).toMatch(/Apps Script/i)
expect(readme).toMatch(/Deploy as Web App/i)
expect(readme).toMatch(/Map fields to columns/i)
})
it('respects exclude mode', () => {
const extras = buildExtrasForPage(basePage, { sheetsMode: 'exclude' })
expect(Object.keys(extras).some(k => k.startsWith('sheets/'))).toBe(false)
})
})
+81
View File
@@ -0,0 +1,81 @@
import { describe, it, expect } from 'vitest'
import { AssetManager } from '@/lib/assets/assetManager'
import { buildAssetsIntegrityIndex } from '@/lib/exporter/assets.integrity.index'
import { verifyIntegrity } from '@/lib/exporter/verify'
function u8(n: number): Uint8Array { const a = new Uint8Array(n); for (let i=0;i<n;i++) a[i]=i&0xff; return a }
function td(b: Uint8Array){ return new TextDecoder().decode(b) }
function te(s: string){ return new TextEncoder().encode(s) }
describe('verifyIntegrity', () => {
it('returns ok=true for valid assets and integrity index', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','txt'] })
const a = await am.add({ name: 'a.png', type: 'image/png', bytes: u8(5) })
const b = await am.add({ name: 'b.txt', type: 'text/plain', bytes: u8(7) })
const assets = am.toZipStructure()
const idx = buildAssetsIntegrityIndex(am)
const extras: Record<string, Uint8Array> = { 'assets.integrity.index.json': idx }
const res = verifyIntegrity(extras, assets)
expect(res.ok).toBe(true)
expect(res.errors.length).toBe(0)
// summary
const parsedIdx = JSON.parse(td(idx)) as { entries: Array<{ path: string }> }
expect(res.summary.total).toBe(parsedIdx.entries.length)
expect(res.summary.missing).toBe(0)
expect(res.summary.integrityMismatches).toBe(0)
expect(res.summary.sizeMismatches).toBe(0)
expect(res.summary.bundleHashMismatch).toBe(false)
// sanity: index contains both paths
const parsed = JSON.parse(td(idx)) as { entries: Array<{ path: string }> }
const paths = parsed.entries.map(e => e.path)
expect(paths).toContain(a.path)
expect(paths).toContain(b.path)
})
it('detects byte tampering in an asset', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','txt'] })
await am.add({ name: 'a.png', type: 'image/png', bytes: u8(5) })
await am.add({ name: 'b.txt', type: 'text/plain', bytes: u8(7) })
const assets = am.toZipStructure()
const idx = buildAssetsIntegrityIndex(am)
// tamper one asset byte
const somePath = Object.keys(assets)[0]
const tampered = assets[somePath].slice()
tampered[0] = (tampered[0] ^ 0xff) & 0xff
assets[somePath] = tampered
const res = verifyIntegrity({ 'assets.integrity.index.json': idx }, assets)
expect(res.ok).toBe(false)
expect(res.errors.some((e: string) => e.includes(somePath) && e.toLowerCase().includes('mismatch'))).toBe(true)
expect(res.summary.integrityMismatches).toBeGreaterThanOrEqual(1)
})
it('detects missing entry or missing asset referenced by index', async () => {
const am = new AssetManager({ maxBytes: 1024*1024, allowedExts: ['png','txt'] })
await am.add({ name: 'a.png', type: 'image/png', bytes: u8(5) })
await am.add({ name: 'b.txt', type: 'text/plain', bytes: u8(7) })
const assets = am.toZipStructure()
const idxRaw = buildAssetsIntegrityIndex(am)
const obj = JSON.parse(td(idxRaw)) as { entries: Array<{ path: string; integrity: string }>, bundleHash: string }
// remove one entry
const removed = obj.entries.shift()!
const idx2 = te(JSON.stringify(obj))
const res1 = verifyIntegrity({ 'assets.integrity.index.json': idx2 }, assets)
expect(res1.ok).toBe(false)
expect(res1.errors.some((e: string) => e.toLowerCase().includes('bundlehash'))).toBe(true)
expect(res1.summary.bundleHashMismatch).toBe(true)
// reference a missing path in index
obj.entries.unshift({ path: 'assets/missing.bin', integrity: 'sha256-AAAA' })
const idx3 = te(JSON.stringify(obj))
const res2 = verifyIntegrity({ 'assets.integrity.index.json': idx3 }, assets)
expect(res2.ok).toBe(false)
expect(res2.errors.some((e: string) => e.includes('assets/missing.bin') && e.toLowerCase().includes('missing'))).toBe(true)
expect(res2.summary.missing).toBeGreaterThanOrEqual(1)
// keep lints happy
expect(removed).toBeTruthy()
})
})
+146
View File
@@ -0,0 +1,146 @@
export type VerifyResult = {
ok: boolean;
errors: string[];
summary: {
total: number;
missing: number;
integrityMismatches: number;
sizeMismatches: number;
bundleHashMismatch: boolean;
};
}
// 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 verifyIntegrity(
extras: Record<string, Uint8Array>,
assets: Record<string, Uint8Array>
): VerifyResult {
const errors: string[] = []
const key = 'assets.integrity.index.json'
if (!Object.prototype.hasOwnProperty.call(extras, key)) {
return { ok: false, errors: ['Missing assets.integrity.index.json in extras'], summary: { total: 0, missing: 0, integrityMismatches: 0, sizeMismatches: 0, bundleHashMismatch: false } }
}
let parsed: { entries: Array<{ path: string; integrity: string; size?: number }>; bundleHash: string }
try {
parsed = JSON.parse(new TextDecoder().decode(extras[key]))
} catch {
return { ok: false, errors: ['Invalid assets.integrity.index.json JSON'], summary: { total: 0, missing: 0, integrityMismatches: 0, sizeMismatches: 0, bundleHashMismatch: false } }
}
// verify each entry exists and integrity matches
const recomputedLines: string[] = []
let missing = 0
let integrityMismatches = 0
let sizeMismatches = 0
for (const e of parsed.entries) {
const bytes = assets[e.path]
if (!bytes) {
errors.push(`Missing asset for path in integrity index: ${e.path}`)
missing++
continue
}
// optional size check when present in index
if (typeof e.size === 'number' && e.size !== bytes.length) {
errors.push(`Size mismatch for ${e.path}: expected ${e.size}, got ${bytes.length}`)
sizeMismatches++
}
const b64 = sha256Base64(bytes)
const integ = `sha256-${b64}`
if (integ !== e.integrity) {
errors.push(`Integrity mismatch for ${e.path}`)
integrityMismatches++
}
recomputedLines.push(e.path)
recomputedLines.push(integ)
}
// recompute bundle hash
const joined = new TextEncoder().encode(recomputedLines.join('\n'))
const bundle = `sha256-${sha256Base64(joined)}`
const bundleHashMismatch = bundle !== parsed.bundleHash
if (bundleHashMismatch) {
errors.push('BundleHash mismatch')
}
return {
ok: errors.length === 0,
errors,
summary: {
total: parsed.entries.length,
missing,
integrityMismatches,
sizeMismatches,
bundleHashMismatch,
},
}
}
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest'
import { buildZip } from '@/lib/exporter/zip'
function u8(s: string): Uint8Array {
return new TextEncoder().encode(s)
}
describe('buildZip path guard', () => {
it('rejects dangerous asset paths with .. segments', async () => {
await expect(
buildZip({ html: '', css: '', js: '', assets: { '../evil.txt': u8('x') } })
).rejects.toThrow(/invalid asset path/i)
})
it('rejects dangerous extras with absolute path and backslashes', async () => {
await expect(
buildZip({ html: '', css: '', js: '', extras: { '/abs.txt': u8('x') } })
).rejects.toThrow(/invalid extra path/i)
await expect(
buildZip({ html: '', css: '', js: '', extras: { 'assets\\x.bin': u8('x') } })
).rejects.toThrow(/invalid extra path/i)
})
it('accepts safe relative paths under assets/', async () => {
const zip = await buildZip({ html: '', css: '', js: '', assets: { 'assets/a.bin': u8('ok') } })
expect(zip.byteLength).toBeGreaterThan(0)
})
})
+12
View File
@@ -14,8 +14,19 @@ export async function buildZip(input: BuildZipInput): Promise<Uint8Array> {
zip.file('index.html', input.html)
zip.file('styles.css', input.css)
zip.file('app.js', input.js)
// guard: basic path sanitizer to avoid directory traversal or absolute paths
const isSafePath = (p: string) => {
if (!p || typeof p !== 'string') return false
if (p.startsWith('/')) return false
if (p.includes('..')) return false
if (p.includes('\\')) return false
return true
}
if (input.assets) {
for (const [path, bytes] of Object.entries(input.assets)) {
if (!isSafePath(path)) throw new Error(`Invalid asset path: ${path}`)
// In Node/Vitest, use Buffer for robust binary handling
const buf = Buffer.from(bytes)
zip.file(path, buf as unknown as Buffer)
@@ -33,6 +44,7 @@ export async function buildZip(input: BuildZipInput): Promise<Uint8Array> {
}
}
for (const [path, bytes] of Object.entries(input.extras)) {
if (!isSafePath(path)) throw new Error(`Invalid extra path: ${path}`)
const buf = Buffer.from(bytes)
zip.file(path, buf as unknown as Buffer)
}
+42
View File
@@ -0,0 +1,42 @@
# 메인플랜
## 목표
- Export ZIP 무결성 강화(Option2): 자산 무결성 지표와 번들 검증 체계 구축
- 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 머지 조건: 테스트/빌드 통과 + 무결성 검증 통과 + 최소 라벨 셋 충족
## 커밋/푸쉬 원칙
- 기능 단위 커밋은 한국어 메시지
- 대범위 브랜치 완료 전에 푸쉬 금지(현 단계는 완료되어 푸쉬 수행)