@uiwwsw/next-test-mode 0.6.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.0 — 2026-10-19
4
+
5
+ - First stable release of the console-first Next.js development and QA workflow.
6
+ - Reframe the README and demo around testing fetch data and page states from the console, with server and static rendering examples demonstrating the same workflow.
7
+ - Add English and Korean landing pages and READMEs, localized search/social metadata, canonical and language alternate links, robots.txt and sitemap.xml.
8
+ - Upgrade the demo, fixture and minimum Next peer to 16.4.2, including upstream Draft Mode cache isolation fixes.
9
+ - Explain session-scoped Draft Mode previews and supported data boundaries. Existing 0.7 APIs remain compatible.
10
+
11
+ ## 0.7.0 — Separate tests, inspect the server preview
12
+
13
+ - Generate an app-owned test folder with one shared catalog, browser/server adapters and thin environment-gated hooks; migrate unchanged 0.5/0.6 setup without overwriting custom code.
14
+ - Add Console cache status, manual Draft bypass without mocks, forced refresh and complete restoration. Keep shared production caches intact.
15
+ - Extract a framework-independent preview coordinator and bounded Draft transport. Preserve edits made during async refresh, recover from failures and cancel work on cleanup.
16
+ - Add extensible Console namespaces with built-in collision protection.
17
+ - Verify catalog exclusion from browser/server production bundles, first-CSR-request interception, folder scenarios, cache-only previews and the public demo.
18
+
3
19
  ## 0.6.0 — Next Test Mode
4
20
 
5
21
  - Rename the npm package to `@uiwwsw/next-test-mode` and repository to `uiwwsw/next-test-mode`; retain the old package for existing installs and document migration.
package/README.ko.md ADDED
@@ -0,0 +1,209 @@
1
+ [English](./README.md) · **한국어**
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v1.0.0/docs/assets/hero.png" width="100%" alt="Next Test Mode — 콘솔 한 줄로 서버 데이터까지 테스트." />
5
+ </p>
6
+ <p align="center">
7
+ <strong>콘솔 한 줄로. 서버 데이터까지 테스트.</strong><br />
8
+ One console command. Test server data, too.
9
+ </p>
10
+ <p align="center">
11
+ <a href="https://www.npmjs.com/package/@uiwwsw/next-test-mode"><img src="https://img.shields.io/npm/v/@uiwwsw/next-test-mode?style=flat-square&amp;color=173c36" alt="npm version" /></a>
12
+ <a href="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml"><img src="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
13
+ <img src="https://img.shields.io/badge/Next.js-App_Router-173c36?style=flat-square" alt="Next.js App Router" />
14
+ <a href="https://github.com/uiwwsw/next-test-mode/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-62796f?style=flat-square" alt="MIT license" /></a>
15
+ </p>
16
+ <p align="center">
17
+ <a href="https://test-mode-tau.vercel.app/">Live demo ↗</a> ·
18
+ <a href="#quick-start">Quick start</a> ·
19
+ <a href="#rendering-support">지원 범위</a> ·
20
+ <a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md">API 가이드</a> ·
21
+ <a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md">기존 패키지에서 이전</a>
22
+ </p>
23
+
24
+ **개발 중 필요한 데이터와 화면 상태를 콘솔 한 줄로 테스트하세요.** Next Test Mode는 Next.js 앱의 fetch 응답을 바꿔 빈 목록, 다른 가격, 서버 오류까지 실제 화면에서 재현하는 개발·QA 도구입니다. 기존 API 호출 코드는 그대로 사용합니다.
25
+
26
+ 브라우저 콘솔만으로는 서버가 이미 만든 HTML이나 빌드 시점에 고정된 데이터를 바꾸기 어렵습니다. **이 도구는 콘솔의 테스트 값을 서버까지 전달하고, 개발·QA 세션의 렌더 경로를 열어 같은 데이터로 화면을 다시 그립니다.** 평소 데브 모드에서 여러 화면 상태를 흉내 내며 개발하듯, 렌더 방식에 관계없이 같은 명령으로 확인하는 것이 핵심입니다.
27
+
28
+ CSR·SSR·ISR·SSG 예제는 이 범위를 직접 확인하기 위한 것입니다. 원래 렌더 방식을 서로 변환하거나 production의 정적 파일을 다시 만드는 기능은 아닙니다. 지원하는 fetch 기반 데이터는 콘솔에서 mock·patch할 수 있으며, DB 직접 조회 등은 별도 연결이 필요합니다.
29
+
30
+ > `@uiwwsw/test-mode`의 새 이름은 **`@uiwwsw/next-test-mode`**입니다. [이전 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md).
31
+
32
+ ## Why Next Test Mode
33
+
34
+ | 호출 코드는 그대로 | 테스트 데이터는 따로 | 확인은 콘솔에서 |
35
+ | :--- | :--- | :--- |
36
+ | 최초 설정 후 기존 `fetch()`를 계속 사용합니다. 각 API 호출부에 테스트 함수나 조건 분기를 추가할 필요가 없습니다. | 한 번 확인할 값은 콘솔에서 끝내고, 반복할 시나리오는 `src/test-mode/` 같은 전용 폴더에서 수정하고 공유합니다. | `test.patch()` 한 줄로 가격을 바꾸고 `test.mock()`으로 빈 목록·오류를 넣습니다. `test.clear()`로 원래 응답에 돌아갑니다. |
37
+
38
+ ```ts
39
+ // 앱의 API 호출: 테스트를 켜도 이 코드는 그대로입니다.
40
+ const response = await fetch('https://api.example.com/api/cart');
41
+ const cart = await response.json();
42
+ ```
43
+
44
+ ```js
45
+ // DevTools → Console: 자신의 API pathname을 사용하세요.
46
+ test.patch('/api/cart', { total: 9.99 });
47
+ // Draft Mode 연결 → 자동 새로고침 → 바뀐 데이터로 화면 확인
48
+ test.clear();
49
+ ```
50
+
51
+ ## Quick start
52
+
53
+ Next.js **16 App Router / Node.js 20.9+** 프로젝트 루트에서:
54
+
55
+ ```bash
56
+ npm install @uiwwsw/next-test-mode
57
+ npx @uiwwsw/next-test-mode init
58
+ npm run dev
59
+ ```
60
+
61
+ 설치 명령이 `app/` 또는 `src/app/`, JavaScript/TypeScript를 감지해 **얇은 연결 파일 세 개와 테스트 전용 폴더**를 생성합니다.
62
+
63
+ | 파일 | 하는 일 |
64
+ | :--- | :--- |
65
+ | `instrumentation.ts` 또는 `.js` | 서버의 기존 fetch에 요청별 테스트 데이터 연결 |
66
+ | `instrumentation-client.ts` 또는 `.js` | Console·브라우저 fetch·Draft Mode·자동 새로고침 연결 |
67
+ | `app/api/next-test-mode/route.ts` 또는 `.js` | Next.js의 Draft Mode 쿠키를 켜고 끄는 POST 경로 |
68
+
69
+ ```text
70
+ src/ # src 없는 앱은 프로젝트 루트
71
+ app/ # 실제 페이지와 API: 테스트 폴더를 import하지 않음
72
+ test-mode/
73
+ catalog.ts # mock · patch · story: 이곳만 편집
74
+ client.ts # Console와 브라우저 연결
75
+ server.ts # 서버 fetch와 Draft 연결
76
+ ```
77
+
78
+ 테스트 정의는 `catalog.ts` 한 곳에 두고 브라우저와 서버가 함께 사용합니다. 일반 production 빌드에서는 조건부 연결이 제거됩니다. CI는 **테스트 카탈로그가 브라우저·서버 번들에서 빠지는지** 실제 빌드 산출물로 확인합니다. QA 빌드에는 의도적으로 포함됩니다.
79
+
80
+ 페이지, API 함수, Next 설정 파일은 수정하지 않습니다. 기존 사용자 파일이 있으면 변경 없이 합칠 코드를 출력합니다. 워커나 별도 서버는 필요하지 않습니다.
81
+
82
+ 기본 설정은 개발 환경에서만 켜집니다. **QA 배포에서도 사용하려면 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 빌드와 실행 환경에 설정**하세요. [생성 코드와 접근 제어](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
83
+
84
+ ## See it in action
85
+
86
+ **[CSR](https://test-mode-tau.vercel.app/csr) · [SSR](https://test-mode-tau.vercel.app/ssr) · [ISR](https://test-mode-tau.vercel.app/isr) · [SSG](https://test-mode-tau.vercel.app/ssg)** — 먼저 콘솔에서 장바구니 값을 바꾸고, 페이지를 이동해 서버·정적 화면에도 같은 값이 반영되는지 확인하세요.
87
+
88
+ <p align="center">
89
+ <img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v1.0.0/docs/assets/scenarios.gif" width="960" alt="실제 Next.js 데모: SSG 원래 가격, 콘솔 patch, SSR에서도 같은 값, HTTP 503, 원래 캐시 응답 복귀." />
90
+ </p>
91
+
92
+ 데모의 DevTools Console에 입력하거나, 화면의 JSON 편집기에서 원하는 값을 적용하세요.
93
+
94
+ ```js
95
+ test.patch('/api/cart.json', { total: 9.99 });
96
+ test.mock('/api/cart.json', { items: [], total: 0 });
97
+ test.mock('/api/cart.json', { message: 'Try again' }, { status: 503 });
98
+ test.overrides(); // 직접 입력한 값 확인
99
+ test.reset('/api/cart.json'); // 이 경로의 직접 입력만 제거
100
+ test.clear(); // 모든 입력과 시나리오 해제
101
+ ```
102
+
103
+ SSR·ISR·SSG 탭에서는 **서버가 보낸 HTML 자체에 변경된 값이 들어갑니다.** 다른 브라우저 세션의 원래 응답은 유지됩니다. JSON 상태는 같은 브라우저의 탭이 공유하며 새로고침 후에도 유지됩니다. 테스트가 끝나면 `test.clear()`를 사용하세요.
104
+
105
+ ## Rendering support
106
+
107
+ 개발·QA에서 다양한 렌더 환경의 화면 상태를 재현합니다. CSR은 브라우저 fetch를 가로채고, 서버 페이지는 테스트 쿠키로 값을 전달받습니다. Next Draft Mode가 해당 세션의 정적·재검증 캐시를 우회하므로, 원래 SSG·ISR 페이지에서도 변경된 데이터로 새 HTML을 확인할 수 있습니다.
108
+
109
+ | 렌더 방식 | Console 변경 후 동작 |
110
+ | :--- | :--- |
111
+ | **CSR** | 브라우저 fetch 응답 교체 또는 patch, 페이지 자동 새로고침 |
112
+ | **SSR / Server Components** | 해당 요청의 서버 fetch에 값 적용 → 새 HTML |
113
+ | **SSG / `force-static`** | Draft Mode에서 정적 결과를 우회해 세션별 동적 미리보기 |
114
+ | **ISR** | Draft Mode에서 기존 페이지·데이터 캐시를 우회해 미리보기. 공용 ISR 결과는 변경하지 않음 |
115
+ | **`unstable_cache` / `use cache`** | Draft Mode의 캐시 우회 경로에서 실행되는 fetch에 적용 |
116
+ | **`generateStaticParams`** | 빌드에서 생성한 경로의 페이지 미리보기 지원. 콘솔로 빌드 시 경로 목록을 다시 만들지는 않음 |
117
+
118
+ `test.clear()`는 이 도구가 연 Draft Mode를 해제해 원래 캐시 경로로 복귀합니다. **SSG 파일을 다시 쓰거나 모든 방문자의 ISR 캐시를 갱신하는 기능은 아닙니다.** 이미 켜진 CMS Draft 세션은 해제하지 않습니다.
119
+
120
+ 실제 production 빌드로 검증한 기준은 **Next.js 16.4.2 / App Router / Node 런타임**입니다. Pages Router, Edge, `output: 'export'`는 자동 연결 대상이 아닙니다. 직접 DB 조회, XHR·WebSocket, fetch를 거치지 않는 외부 캐시에도 별도 어댑터가 필요합니다. 캐시 내부의 요청 쿠키를 읽는 작은 Next 내부 브리지가 있어, Next 버전 업그레이드 시 production 회귀 테스트가 필요합니다. [동작 원리와 호환성](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
121
+
122
+ ## Console controls the server preview
123
+
124
+ 콘솔에서 바꾼 값이 서버에서 렌더한 HTML까지 바뀌는 것이 핵심입니다. **데이터를 조작하지 않고 캐시만 우회해서 실제 응답을 다시 확인할 수도 있습니다.**
125
+
126
+ ```js
127
+ test.cache.bypass(); // 내 Next Draft 세션에서 새 서버 렌더. mock 없어도 사용 가능
128
+ test.cache.status(); // 연결 상태, Draft 활성 여부, 미반영 변경, 오류 확인
129
+ test.cache.refresh(); // 같은 값으로 다시 렌더
130
+ test.cache.restore(); // 테스트 입력·시나리오·수동 우회 해제, 기본 캐시 경로 복귀
131
+ ```
132
+
133
+ `bypass()`는 기존 mock/patch를 유지합니다. `refresh()`는 Draft가 켜져 있을 때 새 서버 렌더를 요청하며, 꺼져 있으면 기존 캐시 정책을 따릅니다.
134
+
135
+ 일반 mock/patch는 캐시 우회를 자동으로 연결하므로 이 명령들을 따로 호출할 필요가 없습니다. `test.clear()`도 전체 테스트를 해제합니다. 초기화 시 기존 CMS Draft 세션은 유지합니다.
136
+
137
+ **제어 범위는 내 브라우저 세션의 Next 렌더링·데이터 캐시 경로입니다.** 공용 캐시를 삭제하지 않으며, 브라우저 HTTP 캐시·SWR/React Query·Redis·외부 CDN을 일괄 무효화하지 않습니다. [캐시별 동작과 설계](https://github.com/uiwwsw/next-test-mode/blob/main/docs/concept.md).
138
+
139
+ ## Try once, or keep it in a folder
140
+
141
+ **잠깐 확인할 테스트는 콘솔에서 끝내세요.** `test.mock()` / `test.patch()` → 화면 확인 → `test.clear()`. 임시 실험 때문에 파일이나 API 호출 코드를 고칠 필요가 없습니다.
142
+
143
+ **반복할 테스트는 `init`이 생성한 `test-mode/catalog.ts`에서 관리하세요.**
144
+
145
+ ```text
146
+ src/
147
+ api/cart.ts # 기존 API 호출
148
+ test-mode/
149
+ catalog.ts # 브라우저·서버에서 공유할 등록 목록
150
+ features/cart.ts # API별 mock / patch와 데이터
151
+ stories/cart.stories.ts # 여러 API를 묶은 화면 시나리오
152
+ ```
153
+
154
+ ```ts
155
+ // src/test-mode/catalog.ts
156
+ import { defineMock } from '@uiwwsw/next-test-mode/core';
157
+
158
+ export const catalog = {
159
+ cookieKey: 'test-mode.entries',
160
+ definitions: [
161
+ defineMock('/api/cart', () => ({ items: [], total: 0 }), {
162
+ caseKey: 'empty',
163
+ pages: ['/cart'],
164
+ }),
165
+ ],
166
+ };
167
+ ```
168
+
169
+ 생성된 두 설치 파일이 같은 catalog를 자동으로 읽습니다. Console에서 `test.feat.add('/api/cart:empty')`로 선택하세요. 여러 API를 묶은 story도 `test.story('cart.empty')`로 활성화합니다. 서버에서도 쓸 정의에는 브라우저 전용 코드를 넣지 마세요.
170
+
171
+ `init`을 다시 실행해도 편집한 테스트 폴더를 덮어쓰지 않습니다. 0.5/0.6의 변경하지 않은 자동 생성 설정은 `init --migrate`로 옮길 수 있습니다. 사용자 코드가 섞인 연결 파일은 변경 없이 합칠 내용을 안내합니다.
172
+
173
+ ## Details that matter
174
+
175
+ - 직접 입력은 **GET + 정확한 pathname**에 매칭합니다. 다른 메서드는 `{ method: 'POST' }` 옵션으로 지정합니다. 여러 호스트의 같은 pathname은 함께 매칭됩니다.
176
+ - `patch`는 실제 응답의 최상위 필드를 덮어씁니다. 중첩 객체와 배열은 통째로 교체되며, 실제 네트워크 요청은 실행됩니다. `mock`은 매칭된 요청의 응답을 직접 만듭니다.
177
+ - 쿠키로 전달하는 전체 선택·JSON 상태는 URL 인코딩 후 **3,500바이트**까지입니다. 큰 응답은 작은 patch 또는 파일에 정의한 시나리오로 관리하세요. 브라우저 세션 복원 설정에 따라 쿠키도 복원될 수 있습니다.
178
+ - Draft 연결 실패는 Console 오류와 `next-test-mode:error` 이벤트로 알리며 자동 새로고침하지 않습니다. `ready` / `sync()`로 성공 여부를 기다릴 수 있습니다. [클라이언트 API](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md#클라이언트-연결-상태).
179
+ - 테스트 쿠키는 로그인 자격이 아닙니다. QA 환경의 접근 권한은 앱이 관리합니다. 들어온 인증 쿠키를 외부 API에 자동 전달하지 않습니다.
180
+ - 이 패키지는 **화면 상태를 재현하는 도구**입니다. 자동 assertion·합격 판정은 Playwright나 Vitest가 담당합니다.
181
+
182
+ ## Framework-independent APIs
183
+
184
+ 기존 범용 core·browser·Node API도 새 이름 아래 유지합니다. Next.js는 선택적 peer이며, 범용 API는 Next 없이 설치할 수 있습니다. 외부 런타임 의존성은 없습니다.
185
+
186
+ ```ts
187
+ import { setupTestMode } from '@uiwwsw/next-test-mode';
188
+ import { createTestMode, defineMock } from '@uiwwsw/next-test-mode/core';
189
+ import { createMockFetch } from '@uiwwsw/next-test-mode/fetch';
190
+ import { withTestMode } from '@uiwwsw/next-test-mode/node';
191
+ import { createServerTestMode } from '@uiwwsw/next-test-mode/server';
192
+ ```
193
+
194
+ 일반 브라우저 앱은 `setupTestMode({ enabled: true, refresh: () => refetch() })`를 시작 시 한 번 연결합니다. 이 범용 설정의 직접 JSON은 기본적으로 메모리에만 남습니다. Next에서는 Draft Mode를 연결하는 `init` 설정을 사용하세요. [전체 API 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md).
195
+
196
+ ## Develop & release
197
+
198
+ ```bash
199
+ npm ci
200
+ npx playwright install chromium
201
+ npm run ci # 타입, 런타임, tarball 설치와 소비자 타입 검사
202
+ npm run test:browser # 브라우저 Console·fetch·Draft 연결
203
+ npm run test:next # 실제 Next dev/production/Cache Components/비활성 배포
204
+ npm run test:demo # 네 렌더 모드와 모바일 JSON 편집기
205
+ npm run dev:demo # 실제 Next.js 데모
206
+ npm run build:demo # Vercel 배포용 Next 빌드
207
+ ```
208
+
209
+ 검증된 main의 릴리스 태그를 GitHub Release로 발행하면, CI를 다시 통과한 패키지가 `NPM_TOKEN`을 사용하는 Actions에서 npm provenance와 함께 배포됩니다. [배포 절차](https://github.com/uiwwsw/next-test-mode/blob/main/docs/releasing.md) · [설계](https://github.com/uiwwsw/next-test-mode/blob/main/docs/architecture.md) · [Changelog](https://github.com/uiwwsw/next-test-mode/blob/main/CHANGELOG.md).
package/README.md CHANGED
@@ -1,50 +1,47 @@
1
+ **English** · [한국어](./README.ko.md)
2
+
1
3
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v0.6.0/docs/assets/hero.png" width="100%" alt="Next Test Mode — Same API calls. Your test data. CSR, SSR, ISR and SSG from one Console." />
3
- </p>
4
- <p align="center">
5
- <strong>호출 코드는 그대로. 테스트 데이터는 따로. 확인은 콘솔에서.</strong><br />
6
- Keep your fetch calls. Keep scenarios separate. Preview from DevTools.
4
+ <img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v1.0.0/docs/assets/hero.png" width="100%" alt="Next Test Mode — One console. Server data, too." />
7
5
  </p>
6
+ <p align="center"><strong>Test Next.js API data and page states from the console.</strong><br />Keep your fetch calls. Try the data you need. Check the real page.</p>
8
7
  <p align="center">
9
8
  <a href="https://www.npmjs.com/package/@uiwwsw/next-test-mode"><img src="https://img.shields.io/npm/v/@uiwwsw/next-test-mode?style=flat-square&amp;color=173c36" alt="npm version" /></a>
10
9
  <a href="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml"><img src="https://github.com/uiwwsw/next-test-mode/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
11
10
  <img src="https://img.shields.io/badge/Next.js-App_Router-173c36?style=flat-square" alt="Next.js App Router" />
12
- <a href="https://github.com/uiwwsw/next-test-mode/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-62796f?style=flat-square" alt="MIT license" /></a>
13
- </p>
14
- <p align="center">
15
- <a href="https://test-mode-tau.vercel.app/">Live demo ↗</a> ·
16
- <a href="#quick-start">Quick start</a> ·
17
- <a href="#rendering-support">지원 범위</a> ·
18
- <a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md">API 가이드</a> ·
19
- <a href="https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md">기존 패키지에서 이전</a>
11
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-62796f?style=flat-square" alt="MIT license" /></a>
20
12
  </p>
13
+ <p align="center"><a href="https://test-mode-tau.vercel.app/en">Live demo ↗</a> · <a href="#quick-start">Quick start</a> · <a href="#rendering-support">Compatibility</a> · <a href="./docs/guide.md">API guide</a></p>
14
+
15
+ **Reproduce the data and page states you need during development with one console command.** Next Test Mode is a development and QA tool for mocking and patching Next.js fetch responses: empty lists, different prices, server errors, and reusable scenarios, without editing individual API calls.
16
+
17
+ The browser console alone cannot easily change HTML already rendered on the server or data fixed at build time. **Next Test Mode carries your console values to the server and opens a session-scoped preview path.** Just as you reproduce different page states in dev mode, you can use the same commands across browser, server, and static page examples.
21
18
 
22
- **Next Test Mode는 Next.js 앱의 API 응답을 콘솔에서 바꿔 화면 상태를 재현하는 개발·QA 도구입니다.** 빈 목록, 다른 가격, 서버 오류를 실제 화면에서 확인하세요. CSR은 브라우저 응답을 바꾸고, SSR·ISR·SSG는 **Next Draft Mode를 자동으로 연결해 해당 브라우저 세션에서 새로 렌더**합니다.
19
+ CSR, SSR, ISR and SSG demonstrate the reach of this workflow. Server previews use Next Draft Mode to bypass static and revalidation caches for your test session. They do not regenerate public static files or change other visitors' pages. Supported fetch-based data can be mocked or patched; direct database calls and other transports need separate integration.
23
20
 
24
- > `@uiwwsw/test-mode`의 새 이름은 **`@uiwwsw/next-test-mode`**입니다. [이전 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/migration.md).
21
+ > `@uiwwsw/test-mode` is now **`@uiwwsw/next-test-mode`**. See the [migration guide](./docs/migration.md).
25
22
 
26
23
  ## Why Next Test Mode
27
24
 
28
- | 호출 코드는 그대로 | 테스트 데이터는 따로 | 확인은 콘솔에서 |
25
+ | Keep your calls | Test from the console | Save reusable scenarios |
29
26
  | :--- | :--- | :--- |
30
- | 최초 설정 후 기존 `fetch()`를 계속 사용합니다. 각 API 호출부에 테스트 함수나 조건 분기를 추가할 필요가 없습니다. | 한 번 확인할 값은 콘솔에서 끝내고, 반복할 시나리오는 `src/test-mode/` 같은 전용 폴더에서 수정하고 공유합니다. | `test.patch()` 한 줄로 가격을 바꾸고 `test.mock()`으로 빈 목록·오류를 넣습니다. `test.clear()`로 원래 응답에 돌아갑니다. |
27
+ | Connect once and keep existing `fetch()` calls. No per-call test branches. | Change values, reload automatically, and check the actual page, including server HTML. | Keep repeated tests in a dedicated folder shared by the browser and server. |
31
28
 
32
29
  ```ts
33
- // 앱의 API 호출: 테스트를 켜도 이 코드는 그대로입니다.
30
+ // Your application code stays the same.
34
31
  const response = await fetch('https://api.example.com/api/cart');
35
32
  const cart = await response.json();
36
33
  ```
37
34
 
38
35
  ```js
39
- // DevTools → Console: 자신의 API pathname을 사용하세요.
36
+ // DevTools → Console: use your own API pathname.
40
37
  test.patch('/api/cart', { total: 9.99 });
41
- // Draft Mode 연결 → 자동 새로고침 → 바뀐 데이터로 화면 확인
38
+ // Draft Mode connects automatically and the page refreshes.
42
39
  test.clear();
43
40
  ```
44
41
 
45
42
  ## Quick start
46
43
 
47
- Next.js **16 App Router / Node.js 20.9+** 프로젝트 루트에서:
44
+ From a **Next.js 16 App Router / Node.js 20.9+** project:
48
45
 
49
46
  ```bash
50
47
  npm install @uiwwsw/next-test-mode
@@ -52,74 +49,91 @@ npx @uiwwsw/next-test-mode init
52
49
  npm run dev
53
50
  ```
54
51
 
55
- 설치 명령이 `app/` 또는 `src/app/`, JavaScript/TypeScript를 감지해 **세 파일**을 생성합니다.
52
+ The installer detects `app/` or `src/app/` and JavaScript or TypeScript. It generates three thin integration files and a dedicated test folder:
56
53
 
57
- | 파일 | 하는 일 |
54
+ | File | Purpose |
58
55
  | :--- | :--- |
59
- | `instrumentation.ts` 또는 `.js` | 서버의 기존 fetch에 요청별 테스트 데이터 연결 |
60
- | `instrumentation-client.ts` 또는 `.js` | Console·브라우저 fetch·Draft Mode·자동 새로고침 연결 |
61
- | `app/api/next-test-mode/route.ts` 또는 `.js` | Next.js의 Draft Mode 쿠키를 켜고 끄는 POST 경로 |
56
+ | `instrumentation.ts` or `.js` | Connect request-scoped test data to existing server fetch calls |
57
+ | `instrumentation-client.ts` or `.js` | Connect the console, browser fetch, Draft Mode and automatic refresh |
58
+ | `app/api/next-test-mode/route.ts` or `.js` | POST route to enable or disable the Next.js Draft Mode cookie |
62
59
 
63
- 페이지, API 함수, Next 설정 파일은 수정하지 않습니다. 기존 사용자 파일이 있으면 변경 없이 합칠 코드를 출력합니다. 워커나 별도 서버는 필요하지 않습니다.
60
+ ```text
61
+ src/ # Project root when there is no src/
62
+ app/ # Real pages and APIs do not import the test folder
63
+ test-mode/
64
+ catalog.ts # Edit mock, patch and story definitions here
65
+ client.ts # Console and browser integration
66
+ server.ts # Server fetch and Draft integration
67
+ ```
68
+
69
+ Browser and server share one catalog. The generated conditional integration excludes the test catalog from ordinary production builds; CI checks the actual client and server bundles. QA builds intentionally include it.
64
70
 
65
- 기본 설정은 개발 환경에서만 켜집니다. **QA 배포에서도 사용하려면 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 빌드와 실행 환경에 설정**하세요. [생성 코드와 접근 제어](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
71
+ The installer leaves pages, API functions and Next configuration untouched. If an integration file already exists, it prints the code to merge without overwriting the file. No worker or separate server is required.
72
+
73
+ Development is enabled by default. To use an intentional QA deployment, set **`NEXT_PUBLIC_NEXT_TEST_MODE=1` at build time and runtime**. Your application owns access control. See [generated setup and authorization](./docs/server-rendering.md).
66
74
 
67
75
  ## See it in action
68
76
 
69
- **[CSR](https://test-mode-tau.vercel.app/csr) · [SSR](https://test-mode-tau.vercel.app/ssr) · [ISR](https://test-mode-tau.vercel.app/isr) · [SSG](https://test-mode-tau.vercel.app/ssg)** — 같은 장바구니를 네 가지 렌더 방식으로 직접 비교하세요.
77
+ Open the [English demo](https://test-mode-tau.vercel.app/en) or [한국어 데모](https://test-mode-tau.vercel.app/). Change a cart value first, then visit the server and static examples to see the same value in their rendered HTML.
70
78
 
71
- <p align="center">
72
- <img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v0.6.0/docs/assets/scenarios.gif" width="960" alt="실제 Next.js 데모: SSG 원래 가격, 콘솔 patch, SSR에서도 같은 값, HTTP 503, 원래 캐시 응답 복귀." />
73
- </p>
79
+ [CSR](https://test-mode-tau.vercel.app/en/csr) · [SSR](https://test-mode-tau.vercel.app/en/ssr) · [ISR](https://test-mode-tau.vercel.app/en/isr) · [SSG](https://test-mode-tau.vercel.app/en/ssg)
74
80
 
75
- 데모의 DevTools Console에 입력하거나, 화면의 JSON 편집기에서 원하는 값을 적용하세요.
81
+ <p align="center"><img src="https://raw.githubusercontent.com/uiwwsw/next-test-mode/v1.0.0/docs/assets/scenarios.gif" width="960" alt="Console patch changes a static cart preview and server HTML; mock an HTTP error, then restore the original response." /></p>
82
+
83
+ Use DevTools Console or the demo's JSON editor:
76
84
 
77
85
  ```js
78
86
  test.patch('/api/cart.json', { total: 9.99 });
79
87
  test.mock('/api/cart.json', { items: [], total: 0 });
80
88
  test.mock('/api/cart.json', { message: 'Try again' }, { status: 503 });
81
- test.overrides(); // 직접 입력한 값 확인
82
- test.reset('/api/cart.json'); // 이 경로의 직접 입력만 제거
83
- test.clear(); // 모든 입력과 시나리오 해제
89
+ test.overrides(); // Inspect console overrides
90
+ test.reset('/api/cart.json'); // Remove direct overrides for this path
91
+ test.clear(); // Clear all overrides and scenarios
84
92
  ```
85
93
 
86
- SSR·ISR·SSG 탭에서는 **서버가 보낸 HTML 자체에 변경된 값이 들어갑니다.** 다른 브라우저 세션의 원래 응답은 유지됩니다. JSON 상태는 같은 브라우저의 탭이 공유하며 새로고침 후에도 유지됩니다. 테스트가 끝나면 `test.clear()`를 사용하세요.
94
+ Server previews put the changed data in the **HTML returned by the server**. Other browser sessions keep their original responses. Values survive reloads and are shared by tabs in the same browser. Finish with `test.clear()`.
87
95
 
88
96
  ## Rendering support
89
97
 
90
- | 렌더 방식 | Console 변경 후 동작 |
91
- | :--- | :--- |
92
- | **CSR** | 브라우저 fetch 응답 교체 또는 patch, 페이지 자동 새로고침 |
93
- | **SSR / Server Components** | 해당 요청의 서버 fetch에 값 적용 → 새 HTML |
94
- | **SSG / `force-static`** | Draft Mode에서 정적 결과를 우회해 세션별 동적 미리보기 |
95
- | **ISR** | Draft Mode에서 기존 페이지·데이터 캐시를 우회해 미리보기. 공용 ISR 결과는 변경하지 않음 |
96
- | **`unstable_cache` / `use cache`** | Draft Mode의 캐시 우회 경로에서 실행되는 fetch에 적용 |
97
- | **`generateStaticParams`** | 빌드에서 생성한 경로의 페이지 미리보기 지원. 콘솔로 빌드 시 경로 목록을 다시 만들지는 않음 |
98
+ In development and QA, browser fetch interception handles CSR. Server requests read test values from cookies. Next Draft Mode bypasses static and revalidation caches for that session, allowing a fresh HTML preview even for an SSG or ISR page.
98
99
 
99
- `test.clear()`는 이 도구가 연 Draft Mode를 해제해 원래 캐시 경로로 복귀합니다. **SSG 파일을 다시 쓰거나 모든 방문자의 ISR 캐시를 갱신하는 기능은 아닙니다.** 이미 켜진 CMS Draft 세션은 해제하지 않습니다.
100
+ | Rendering path | After a console change |
101
+ | :--- | :--- |
102
+ | **CSR** | Intercept or patch browser fetch responses, then refresh |
103
+ | **SSR / Server Components** | Apply values to request-scoped server fetch calls and render new HTML |
104
+ | **SSG / `force-static`** | Bypass the static result through a session-scoped Draft Mode preview |
105
+ | **ISR** | Bypass the page and data cache for the preview; retain the shared ISR result |
106
+ | **`unstable_cache` / `use cache`** | Apply to fetch calls executed through the Draft Mode cache-bypass path |
107
+ | **`generateStaticParams`** | Preview existing generated routes; console commands do not regenerate the build-time route list |
100
108
 
101
- 실제 production 빌드로 검증한 기준은 **Next.js 16.3.5 / App Router / Node 런타임**입니다. Pages Router, Edge, `output: 'export'`는 자동 연결 대상이 아닙니다. 직접 DB 조회, XHR·WebSocket, fetch를 거치지 않는 외부 캐시에도 별도 어댑터가 필요합니다. 캐시 내부의 요청 쿠키를 읽는 작은 Next 내부 브리지가 있어, Next 버전 업그레이드 시 production 회귀 테스트가 필요합니다. [동작 원리와 호환성](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md).
109
+ `test.clear()` releases Draft Mode owned by this tool and returns to the default cache path. Existing CMS Draft sessions are preserved.
102
110
 
103
- ## Try once, or keep it in a folder
111
+ Validated against **Next.js 16.4.2 / App Router / Node runtime** with real production builds. Pages Router, Edge and `output: 'export'` are outside automatic integration. Direct database reads, XHR, WebSocket and external caches that do not use fetch need adapters. A small bridge reads request cookies inside cached Next scopes; rerun production regression tests when upgrading Next. [How it works and compatibility](./docs/server-rendering.md).
104
112
 
105
- **잠깐 확인할 테스트는 콘솔에서 끝내세요.** `test.mock()` / `test.patch()` → 화면 확인 → `test.clear()`. 임시 실험 때문에 파일이나 API 호출 코드를 고칠 필요가 없습니다.
113
+ ## Console controls the server preview
106
114
 
107
- **반복할 테스트는 별도 폴더에서 관리하세요.**
115
+ Mock and patch commands connect the preview automatically. You can also bypass caches to inspect fresh real data without changing it:
108
116
 
109
- ```text
110
- src/
111
- api/cart.ts # 기존 API 호출
112
- test-mode/
113
- catalog.ts # 브라우저·서버에서 공유할 등록 목록
114
- features/cart.ts # API별 mock / patch와 데이터
115
- stories/cart.stories.ts # 여러 API를 묶은 화면 시나리오
117
+ ```js
118
+ test.cache.bypass(); // Keep existing overrides and open a server preview
119
+ test.cache.status(); // Inspect Draft status, pending changes and errors
120
+ test.cache.refresh(); // Render again with the same values
121
+ test.cache.restore(); // Clear tests and return to the default cache path
116
122
  ```
117
123
 
124
+ `refresh()` requests a fresh server render while Draft Mode is active; otherwise the existing cache policy applies. `test.clear()` also ends all tests. These controls cover your session's Next rendering and data cache path, not shared cache deletion, browser HTTP caches, SWR/React Query, Redis or external CDNs. [Cache behavior and design](./docs/concept.md).
125
+
126
+ ## Try once, or keep it in a folder
127
+
128
+ For a one-off check, use `test.mock()` or `test.patch()`, inspect the page, then `test.clear()`. No temporary file or API call edits are needed.
129
+
130
+ Keep repeated tests in the generated `test-mode/catalog.ts` and split larger catalogs into feature and story files:
131
+
118
132
  ```ts
119
- // src/test-mode/catalog.ts
120
133
  import { defineMock } from '@uiwwsw/next-test-mode/core';
121
134
 
122
135
  export const catalog = {
136
+ cookieKey: 'test-mode.entries',
123
137
  definitions: [
124
138
  defineMock('/api/cart', () => ({ items: [], total: 0 }), {
125
139
  caseKey: 'empty',
@@ -129,20 +143,22 @@ export const catalog = {
129
143
  };
130
144
  ```
131
145
 
132
- 이 목록을 생성된 두 instrumentation의 `setupNextTestMode({ ...catalog, enabled: true })`와 `setupNextTestModeClient({ ...catalog, enabled: ... })`에 전달하면 Console에서 `test.feat.add('/api/cart:empty')`로 선택할 수 있습니다. 여러 API를 묶은 story도 `test.story('cart.empty')`로 활성화합니다. 서버에서도 쓸 정의에는 브라우저 전용 코드를 넣지 마세요. [스타터와 연결 예시](https://github.com/uiwwsw/next-test-mode/tree/main/templates/test-mode).
146
+ Select this case with `test.feat.add('/api/cart:empty')`. Activate a story spanning multiple APIs with `test.story('cart.empty')`. Definitions used by the server must avoid browser-only code.
147
+
148
+ Running `init` again preserves the edited test folder. `init --migrate` migrates unchanged generated 0.5/0.6 setup; customized integration files receive manual merge instructions. [Migration guide](./docs/migration.md).
133
149
 
134
150
  ## Details that matter
135
151
 
136
- - 직접 입력은 **GET + 정확한 pathname**에 매칭합니다. 다른 메서드는 `{ method: 'POST' }` 옵션으로 지정합니다. 여러 호스트의 같은 pathname은 함께 매칭됩니다.
137
- - `patch`는 실제 응답의 최상위 필드를 덮어씁니다. 중첩 객체와 배열은 통째로 교체되며, 실제 네트워크 요청은 실행됩니다. `mock`은 매칭된 요청의 응답을 직접 만듭니다.
138
- - 쿠키로 전달하는 전체 선택·JSON 상태는 URL 인코딩 후 **3,500바이트**까지입니다. 큰 응답은 작은 patch 또는 파일에 정의한 시나리오로 관리하세요. 브라우저 세션 복원 설정에 따라 쿠키도 복원될 수 있습니다.
139
- - Draft 연결 실패는 Console 오류와 `next-test-mode:error` 이벤트로 알리며 자동 새로고침하지 않습니다. `ready` / `sync()`로 성공 여부를 기다릴 수 있습니다. [클라이언트 API](https://github.com/uiwwsw/next-test-mode/blob/main/docs/server-rendering.md#클라이언트-연결-상태).
140
- - 테스트 쿠키는 로그인 자격이 아닙니다. QA 환경의 접근 권한은 앱이 관리합니다. 들어온 인증 쿠키를 외부 API에 자동 전달하지 않습니다.
141
- - 이 패키지는 **화면 상태를 재현하는 도구**입니다. 자동 assertion·합격 판정은 Playwright나 Vitest가 담당합니다.
152
+ - Direct overrides match **GET plus exact pathname** by default. Specify other methods with `{ method: 'POST' }`. Identical pathnames on different hosts match together.
153
+ - `patch` overwrites top-level fields of the real response. Nested objects and arrays are replaced as a whole; the network request still runs. `mock` supplies the matching response directly.
154
+ - The total URL-encoded cookie state is limited to **3,500 bytes**. Use a small patch or a file-defined scenario for larger responses. Browser session restoration may restore cookies too.
155
+ - Draft connection failures emit a console error and `next-test-mode:error`; they do not trigger a reload. Await `ready` or `sync()` to verify success. [Client API](./docs/server-rendering.md#클라이언트-연결-상태).
156
+ - Test cookies are not authentication. The application controls QA access. Incoming authentication cookies are not automatically forwarded to external APIs.
157
+ - This tool reproduces page states. Use Playwright or Vitest for automated assertions and pass/fail results.
142
158
 
143
159
  ## Framework-independent APIs
144
160
 
145
- 기존 범용 core·browser·Node API도 새 이름 아래 유지합니다. Next.js는 선택적 peer이며, 범용 API는 Next 없이 설치할 수 있습니다. 외부 런타임 의존성은 없습니다.
161
+ The core, browser and Node APIs remain available under the new package name. Next.js is an optional peer; generic APIs work without it. There are no external runtime dependencies.
146
162
 
147
163
  ```ts
148
164
  import { setupTestMode } from '@uiwwsw/next-test-mode';
@@ -152,19 +168,19 @@ import { withTestMode } from '@uiwwsw/next-test-mode/node';
152
168
  import { createServerTestMode } from '@uiwwsw/next-test-mode/server';
153
169
  ```
154
170
 
155
- 일반 브라우저 앱은 `setupTestMode({ enabled: true, refresh: () => refetch() })`를 시작 시 한 번 연결합니다. 이 범용 설정의 직접 JSON은 기본적으로 메모리에만 남습니다. Next에서는 Draft Mode를 연결하는 `init` 설정을 사용하세요. [전체 API 가이드](https://github.com/uiwwsw/next-test-mode/blob/main/docs/guide.md).
171
+ For a generic browser application, connect `setupTestMode({ enabled: true, refresh: () => refetch() })` once at startup. Direct JSON overrides stay in memory by default. Use the generated `init` integration for Next Draft Mode. [Full API guide](./docs/guide.md) (Korean).
156
172
 
157
173
  ## Develop & release
158
174
 
159
175
  ```bash
160
176
  npm ci
161
177
  npx playwright install chromium
162
- npm run ci # 타입, 런타임, tarball 설치와 소비자 타입 검사
163
- npm run test:browser # 브라우저 Console·fetch·Draft 연결
164
- npm run test:next # 실제 Next dev/production/Cache Components/비활성 배포
165
- npm run test:demo # 네 렌더 모드와 모바일 JSON 편집기
166
- npm run dev:demo # 실제 Next.js 데모
167
- npm run build:demo # Vercel 배포용 Next 빌드
178
+ npm run ci # Types, runtime tests, tarball installation and consumer types
179
+ npm run test:browser # Browser console, fetch and Draft integration
180
+ npm run test:next # Next dev, production, Cache Components and disabled builds
181
+ npm run test:demo # Rendering examples, localized SEO and mobile editor
182
+ npm run dev:demo # Next.js demo
183
+ npm run build:demo # Vercel production build
168
184
  ```
169
185
 
170
- 검증된 main의 릴리스 태그를 GitHub Release로 발행하면, CI를 다시 통과한 패키지가 `NPM_TOKEN`을 사용하는 Actions에서 npm provenance와 함께 배포됩니다. [배포 절차](https://github.com/uiwwsw/next-test-mode/blob/main/docs/releasing.md) · [설계](https://github.com/uiwwsw/next-test-mode/blob/main/docs/architecture.md) · [Changelog](https://github.com/uiwwsw/next-test-mode/blob/main/CHANGELOG.md).
186
+ A GitHub Release from a verified main tag triggers CI and npm publishing with provenance. Stable releases use `latest`. Version 1.0.0 retains the 0.7 public APIs. [Release process](./docs/releasing.md) · [Architecture](./docs/architecture.md) · [Changelog](./CHANGELOG.md).
@@ -0,0 +1,82 @@
1
+ export const environment =
2
+ "process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1'";
3
+ const header = "// Generated by @uiwwsw/next-test-mode";
4
+ export const templates = (extension) => ({
5
+ instrumentation: `${header}
6
+ export async function register() {
7
+ if (process.env.NEXT_RUNTIME === 'nodejs' && (${environment})) {
8
+ const { registerTestMode } = await import('./test-mode/server');
9
+ registerTestMode();
10
+ }
11
+ }
12
+ `,
13
+ "instrumentation-client": `${header}
14
+ if (${environment}) {
15
+ // Initialize before the application's first browser fetch.
16
+ require('./test-mode/client');
17
+ }
18
+ `,
19
+ "app/api/next-test-mode/route": `${header}
20
+ export async function POST(request${extension === "ts" ? ": Request" : ""}) {
21
+ if (${environment}) {
22
+ const { handleDraft } = await import('../../../test-mode/server');
23
+ return handleDraft(request);
24
+ }
25
+ return new Response(null, { status: 404 });
26
+ }
27
+ `,
28
+ "test-mode/catalog": `${header}
29
+ // Your test definitions live here. Application fetch calls never import this folder.
30
+ ${extension === "ts" ? "import type { TestModeOptions } from '@uiwwsw/next-test-mode/core';\n" : ""}
31
+ export const catalog = {
32
+ cookieKey: 'test-mode.entries',
33
+ definitions: [],
34
+ patchDefinitions: [],
35
+ stories: [],
36
+ }${extension === "ts" ? ' satisfies Omit<TestModeOptions, "enabled" | "beforeChange">' : ""};
37
+ `,
38
+ "test-mode/client": `${header}
39
+ import { setupNextTestModeClient } from '@uiwwsw/next-test-mode/client';
40
+ import { catalog } from './catalog';
41
+
42
+ export const controller = setupNextTestModeClient({ ...catalog, enabled: true });
43
+ `,
44
+ "test-mode/server": `${header}
45
+ import { setupNextTestMode, createDraftModeHandler } from '@uiwwsw/next-test-mode/next';
46
+ import { catalog } from './catalog';
47
+
48
+ export const registerTestMode = () => setupNextTestMode({ ...catalog, enabled: true });
49
+ export const handleDraft = createDraftModeHandler({ cookieKey: catalog.cookieKey, enabled: true });
50
+ `,
51
+ });
52
+
53
+ export const legacyTemplates = {
54
+ instrumentation: [
55
+ `export async function register() {
56
+ if (process.env.NODE_ENV === 'development' && process.env.NEXT_RUNTIME === 'nodejs') {
57
+ const { setupNextTestMode } = await import('@uiwwsw/test-mode/next');
58
+ setupNextTestMode();
59
+ }
60
+ }`,
61
+ `${header}
62
+ export async function register() {
63
+ if (process.env.NEXT_RUNTIME === 'nodejs' && (${environment})) {
64
+ const { setupNextTestMode } = await import('@uiwwsw/next-test-mode/next');
65
+ setupNextTestMode({ enabled: true });
66
+ }
67
+ }`,
68
+ ],
69
+ "instrumentation-client": [
70
+ "import { setupTestMode } from '@uiwwsw/test-mode';\n\nsetupTestMode({ enabled: process.env.NODE_ENV === 'development', ssr: true });",
71
+ `${header}
72
+ import { setupNextTestModeClient } from '@uiwwsw/next-test-mode/client';
73
+
74
+ setupNextTestModeClient({ enabled: ${environment} });`,
75
+ ],
76
+ "app/api/next-test-mode/route": [
77
+ `${header}
78
+ import { createDraftModeHandler } from '@uiwwsw/next-test-mode/next';
79
+
80
+ export const POST = createDraftModeHandler({ enabled: ${environment} });`,
81
+ ],
82
+ };