@uiwwsw/next-test-mode 0.6.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.
Files changed (112) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -0
  4. package/bin/test-mode.mjs +164 -0
  5. package/dist/browser.d.ts +7 -0
  6. package/dist/browser.d.ts.map +1 -0
  7. package/dist/browser.js +455 -0
  8. package/dist/browser.js.map +1 -0
  9. package/dist/client.d.ts +14 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +92 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/core.d.ts +160 -0
  14. package/dist/core.d.ts.map +1 -0
  15. package/dist/core.js +741 -0
  16. package/dist/core.js.map +1 -0
  17. package/dist/fetch.d.ts +16 -0
  18. package/dist/fetch.d.ts.map +1 -0
  19. package/dist/fetch.js +212 -0
  20. package/dist/fetch.js.map +1 -0
  21. package/dist/index.d.ts +6 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +6 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/internal/draft-handler.d.ts +30 -0
  26. package/dist/internal/draft-handler.d.ts.map +1 -0
  27. package/dist/internal/draft-handler.js +80 -0
  28. package/dist/internal/draft-handler.js.map +1 -0
  29. package/dist/internal/lifecycle.d.ts +7 -0
  30. package/dist/internal/lifecycle.d.ts.map +1 -0
  31. package/dist/internal/lifecycle.js +65 -0
  32. package/dist/internal/lifecycle.js.map +1 -0
  33. package/dist/internal/next-request.d.ts +11 -0
  34. package/dist/internal/next-request.d.ts.map +1 -0
  35. package/dist/internal/next-request.js +22 -0
  36. package/dist/internal/next-request.js.map +1 -0
  37. package/dist/internal/overrides.d.ts +25 -0
  38. package/dist/internal/overrides.d.ts.map +1 -0
  39. package/dist/internal/overrides.js +111 -0
  40. package/dist/internal/overrides.js.map +1 -0
  41. package/dist/internal/paths.d.ts +3 -0
  42. package/dist/internal/paths.d.ts.map +1 -0
  43. package/dist/internal/paths.js +22 -0
  44. package/dist/internal/paths.js.map +1 -0
  45. package/dist/internal/server-context.d.ts +4 -0
  46. package/dist/internal/server-context.d.ts.map +1 -0
  47. package/dist/internal/server-context.js +6 -0
  48. package/dist/internal/server-context.js.map +1 -0
  49. package/dist/internal/ssr-state.d.ts +8 -0
  50. package/dist/internal/ssr-state.d.ts.map +1 -0
  51. package/dist/internal/ssr-state.js +48 -0
  52. package/dist/internal/ssr-state.js.map +1 -0
  53. package/dist/internal/storage.d.ts +6 -0
  54. package/dist/internal/storage.d.ts.map +1 -0
  55. package/dist/internal/storage.js +70 -0
  56. package/dist/internal/storage.js.map +1 -0
  57. package/dist/internal/symbols.d.ts +3 -0
  58. package/dist/internal/symbols.d.ts.map +1 -0
  59. package/dist/internal/symbols.js +3 -0
  60. package/dist/internal/symbols.js.map +1 -0
  61. package/dist/next.d.ts +9 -0
  62. package/dist/next.d.ts.map +1 -0
  63. package/dist/next.js +32 -0
  64. package/dist/next.js.map +1 -0
  65. package/dist/node.d.ts +27 -0
  66. package/dist/node.d.ts.map +1 -0
  67. package/dist/node.js +144 -0
  68. package/dist/node.js.map +1 -0
  69. package/dist/server.d.ts +20 -0
  70. package/dist/server.d.ts.map +1 -0
  71. package/dist/server.js +36 -0
  72. package/dist/server.js.map +1 -0
  73. package/dist/setup.d.ts +14 -0
  74. package/dist/setup.d.ts.map +1 -0
  75. package/dist/setup.js +66 -0
  76. package/dist/setup.js.map +1 -0
  77. package/dist/types.d.ts +179 -0
  78. package/dist/types.d.ts.map +1 -0
  79. package/dist/types.js +2 -0
  80. package/dist/types.js.map +1 -0
  81. package/docs/architecture.md +116 -0
  82. package/docs/guide.md +171 -0
  83. package/docs/migration.md +26 -0
  84. package/docs/releasing.md +41 -0
  85. package/docs/server-rendering.md +136 -0
  86. package/docs/story-test-design.md +252 -0
  87. package/package.json +136 -0
  88. package/src/browser.ts +593 -0
  89. package/src/client.ts +114 -0
  90. package/src/core.ts +1161 -0
  91. package/src/fetch.ts +271 -0
  92. package/src/index.ts +5 -0
  93. package/src/internal/draft-handler.ts +113 -0
  94. package/src/internal/lifecycle.ts +81 -0
  95. package/src/internal/next-request.ts +31 -0
  96. package/src/internal/overrides.ts +141 -0
  97. package/src/internal/paths.ts +27 -0
  98. package/src/internal/server-context.ts +6 -0
  99. package/src/internal/ssr-state.ts +48 -0
  100. package/src/internal/storage.ts +75 -0
  101. package/src/internal/symbols.ts +2 -0
  102. package/src/next.ts +49 -0
  103. package/src/node.ts +213 -0
  104. package/src/server.ts +52 -0
  105. package/src/setup.ts +69 -0
  106. package/src/types.ts +240 -0
  107. package/templates/test-mode/README.md +30 -0
  108. package/templates/test-mode/config.ts +25 -0
  109. package/templates/test-mode/features/auth.ts +23 -0
  110. package/templates/test-mode/index.ts +11 -0
  111. package/templates/test-mode/install.ts +13 -0
  112. package/templates/test-mode/stories/auth.stories.ts +10 -0
@@ -0,0 +1,26 @@
1
+ # @uiwwsw/test-mode → @uiwwsw/next-test-mode
2
+
3
+ 0.6.0부터 제품 이름은 **Next Test Mode**, npm 패키지는 **`@uiwwsw/next-test-mode`**, 저장소는 **uiwwsw/next-test-mode**입니다. 기존 0.5.0 패키지는 계속 설치할 수 있지만 새 개발은 새 이름으로 진행합니다. 공개 데모 주소는 https://test-mode-tau.vercel.app/ 그대로입니다.
4
+
5
+ ## Next App Router
6
+
7
+ ```bash
8
+ npm uninstall @uiwwsw/test-mode
9
+ npm install @uiwwsw/next-test-mode
10
+ npx @uiwwsw/next-test-mode init --migrate
11
+ npm run dev
12
+ ```
13
+
14
+ 이 명령은 **수정하지 않은 0.5.0 자동 생성 instrumentation 파일**만 새 설정으로 바꾸며, Draft Mode POST 경로를 추가합니다. 기존 파일에 사용자 코드가 있으면 어떤 파일도 변경하지 않고 합칠 코드를 출력합니다. [생성 코드](./server-rendering.md#최초-설정)를 기존 hook 안에 합치세요. 페이지의 fetch 호출은 그대로 둡니다.
15
+
16
+ 앱 소유의 시나리오 파일에 남은 import도 `@uiwwsw/test-mode`에서 `@uiwwsw/next-test-mode`로 바꾸세요. 새 브라우저 연결은 `/client`의 `setupNextTestModeClient`입니다. 기존 `setupTestMode({ ssr: true })`와 중복 설치하지 마세요. 서버는 `/next`의 `setupNextTestMode`를 사용합니다.
17
+
18
+ Next.js 16.3.5 이상 17 미만의 App Router와 Node.js 20.9 이상이 필요합니다. 검증된 Next 버전은 16.3.5입니다. QA 배포는 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 빌드와 실행 환경에 설정하고 재배포하세요. Pages Router와 Edge, 순수 정적 export는 자동 이전 대상이 아닙니다.
19
+
20
+ ## 유지되는 API
21
+
22
+ `test.mock`, `test.patch`, `test.reset`, `test.clear`, feature/story 정의와 범용 core/fetch/browser/server/node/setup export는 유지합니다. 브라우저의 기본 storage/cookie 키도 유지하므로 기존 선택을 읽을 수 있습니다. 두 패키지를 동시에 설치·초기화하지 마세요.
23
+
24
+ 새 Next 연결은 Console 변경 후 Draft Mode를 확인하고 페이지를 새로고침합니다. SSR뿐 아니라 SSG·ISR도 세션별 미리보기가 됩니다. `test.clear()`는 이 도구가 연 Draft Mode를 종료하고 원래 캐시 경로로 돌아갑니다. JSON 상태는 세션 쿠키에 유지되며 새로고침만으로 지워지지 않습니다.
25
+
26
+ 범용 브라우저/Node 앱은 import 이름만 바꾸면 기존 API를 계속 사용할 수 있습니다. 범용 `setupTestMode()`의 기본 직접 JSON은 메모리에만 남습니다. Next peer는 선택적입니다.
@@ -0,0 +1,41 @@
1
+ # 개발 및 배포
2
+
3
+ ```bash
4
+ npm ci
5
+ npx playwright install chromium
6
+ npm run ci
7
+ npm run test:browser
8
+ npm run test:next
9
+ npm run test:demo
10
+ npm pack
11
+ ```
12
+
13
+ PR/main CI는 Node.js 20.9 / 22 / 24, Chromium, 실제 Next.js 16.3.5를 검증합니다. tarball을 독립 앱에 설치해 ESM·타입·스타터·CLI를 확인합니다. Next fixture는 dev, production의 SSR·SSG·ISR·force-static·생성 경로·unstable_cache, Cache Components/use cache, 비활성 production을 각각 검사합니다. 공개 데모도 네 렌더 모드와 모바일 JSON 입력을 검사합니다.
14
+
15
+ ## npm
16
+
17
+ GitHub Release 발행 또는 Publish workflow에서 기존 tag를 지정하면 배포합니다. `NPM_TOKEN`에는 `@uiwwsw/next-test-mode` 발행 권한과 기존 `@uiwwsw/test-mode`의 이전 안내 설정 권한이 필요합니다. 토큰은 publish/deprecate 단계에만 전달합니다.
18
+
19
+ 1. package.json과 package-lock.json 버전을 함께 갱신합니다.
20
+ 2. 검증된 변경을 main에 반영하고 그 커밋에 `vX.Y.Z` 태그를 만듭니다.
21
+ 3. 같은 태그로 GitHub Release를 발행합니다.
22
+ 4. 전체 CI, 태그·버전 일치, main 포함 여부를 통과하면 npm provenance와 함께 발행합니다.
23
+ 5. 레지스트리에서 버전·커밋·무결성·provenance를 확인한 다음, 기존 패키지에 새 이름과 이전 가이드를 안내합니다. 기존 버전은 삭제하지 않습니다.
24
+
25
+ 정식 버전은 `latest`, 사전 버전은 `next` 채널로 배포합니다. 동일 커밋으로 이미 발행했다면 건너뛰며, 다른 커밋의 동일 버전은 거부합니다. 레지스트리 반영은 최대 36회 재시도합니다. 성공 후 일반 `npm view`와 새 소비자 설치로도 확인하세요.
26
+
27
+ npm [Trusted publishing](https://docs.npmjs.com/trusted-publishers/)을 설정한다면 GitHub user `uiwwsw`, repository **`next-test-mode`**, workflow `publish.yml`, environment `npm`을 사용합니다. 워크플로의 OIDC 권한은 준비되어 있습니다.
28
+
29
+ ## Vercel
30
+
31
+ 공개 데모: [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).
32
+
33
+ 저장소를 Import하고 Root Directory를 `./`로 둡니다. `vercel.json`은 **Next.js**, `npm run build:demo`, `.next` 출력을 지정합니다. 기존 프로젝트의 UI에 별도 빌드/출력 override가 있다면 이 값과 맞추세요. GitHub 저장소 이름은 `next-test-mode`이며 데모 도메인은 그대로입니다.
34
+
35
+ 데모는 루트 `app/`의 실제 Next 앱입니다. `instrumentation.js`와 `instrumentation-client.js`가 로컬 패키지 빌드를 연결하고, 공개 샘플 `/api/cart.json`만 서버 테스트 대상으로 허용합니다. 샘플 데모에는 환경 변수가 필요하지 않습니다. 사용자 앱에 생성하는 설정은 기본 development 전용입니다.
36
+
37
+ 루트와 `/ssg`는 정적 생성, `/isr`은 60초 재검증, `/ssr`은 매 요청 렌더, `/csr`은 브라우저 fetch입니다. 빌드 시 공개 데모의 샘플 JSON을 가져오므로 최초 도메인 이전 때는 `demo-components/load-cart.js`의 샘플 주소도 확인하세요. 구 `/api/ssr` 주소는 `/ssr`로 안내합니다.
38
+
39
+ ## 문서 이미지
40
+
41
+ `npm run docs:assets`는 Next production 데모를 Chromium으로 촬영하고 README의 PNG/GIF를 만듭니다. Python 3과 Pillow가 필요합니다. 이미지는 GitHub 릴리스 태그의 절대 URL로 제공하며 npm tarball에는 넣지 않습니다. README 이미지 URL의 태그도 새 릴리스에 맞추세요.
@@ -0,0 +1,136 @@
1
+ # Next Draft Mode와 서버 렌더링
2
+
3
+ Next Test Mode는 브라우저 Console의 값을 다음 서버 요청에 전달하고, Next의 Draft Mode로 해당 세션의 캐시를 우회합니다. 호출부의 `fetch()`는 그대로 둡니다.
4
+
5
+ ## 최초 설정
6
+
7
+ ```bash
8
+ npm install @uiwwsw/next-test-mode
9
+ npx @uiwwsw/next-test-mode init
10
+ ```
11
+
12
+ App Router의 루트 또는 `src/` 구조를 감지합니다. TS 프로젝트는 `.ts`, JS 프로젝트는 `.js` 파일을 생성합니다. 기존 설정은 덮어쓰지 않습니다. 변경하지 않은 구 버전 생성 파일은 `--migrate`로 이전할 수 있습니다.
13
+
14
+ 생성하는 서버 시작 코드:
15
+
16
+ ```ts
17
+ // instrumentation.ts (또는 src/instrumentation.ts)
18
+ export async function register() {
19
+ if (process.env.NEXT_RUNTIME === 'nodejs' &&
20
+ (process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1')) {
21
+ const { setupNextTestMode } = await import('@uiwwsw/next-test-mode/next');
22
+ setupNextTestMode({ enabled: true });
23
+ }
24
+ }
25
+ ```
26
+
27
+ 브라우저 시작 코드:
28
+
29
+ ```ts
30
+ // instrumentation-client.ts
31
+ import { setupNextTestModeClient } from '@uiwwsw/next-test-mode/client';
32
+
33
+ setupNextTestModeClient({
34
+ enabled: process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1',
35
+ });
36
+ ```
37
+
38
+ Draft Mode 경로:
39
+
40
+ ```ts
41
+ // app/api/next-test-mode/route.ts
42
+ import { createDraftModeHandler } from '@uiwwsw/next-test-mode/next';
43
+
44
+ export const POST = createDraftModeHandler({
45
+ enabled: process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1',
46
+ });
47
+ ```
48
+
49
+ Next의 기본 Node 런타임을 사용합니다. Cache Components와 함께 쓰는 앱에는 별도의 `runtime` route 설정을 추가하지 않습니다. QA 배포에서는 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 **빌드와 실행 환경 모두**에 설정하고 재배포하세요. 기본 production 빌드에서는 브라우저 설치와 서버 연결이 꺼지며 제어 경로는 404를 반환합니다.
50
+
51
+ ## 콘솔에서 SSR이 바뀌는 과정
52
+
53
+ 1. `test.patch('/api/cart', { total: 9.99 })`가 선택 상태와 JSON을 검증하고 세션 쿠키에 기록합니다.
54
+ 2. 브라우저 연결이 `/api/next-test-mode`에 같은 출처의 POST 요청을 보냅니다.
55
+ 3. 경로가 Next의 `draftMode().enable()`로 HttpOnly Draft 쿠키를 설정합니다. 이미 켜져 있으면 유지합니다.
56
+ 4. 응답 확인 후 페이지를 새로고침합니다. Next는 Draft 세션에서 페이지·데이터 캐시를 우회해 다시 렌더합니다.
57
+ 5. 서버의 기존 `fetch()`가 해당 요청의 테스트 쿠키를 읽어 mock 또는 patch된 값을 반환합니다. HTML에 이 값이 들어갑니다.
58
+ 6. `test.clear()`가 테스트 상태를 지우고, 이 도구가 연 Draft 세션을 해제한 뒤 새로고침합니다.
59
+
60
+ Worker는 서버의 fetch를 가로챌 수 없으므로 이 연결을 대체하지 않습니다. Next 서버와 브라우저를 각 시작 지점에 한 번 설치하는 이유입니다. Draft 제어 경로는 데이터 API를 대체하지 않고 세션만 전환합니다.
61
+
62
+ ## 렌더 방식별 범위
63
+
64
+ | 방식 | 지원하는 동작 | 유지되는 경계 |
65
+ | --- | --- | --- |
66
+ | CSR | 브라우저 fetch 변경 후 새로고침 | 이전에 받은 앱 상태를 직접 조작하지 않음 |
67
+ | SSR / RSC | 요청별 서버 fetch 변경, 실제 HTML 반영 | 전역 fetch를 거치지 않는 데이터 소스는 별도 연결 |
68
+ | SSG / `force-static` | Draft 세션에서 정적 페이지를 동적으로 미리보기 | 빌드 파일 자체를 수정하지 않음 |
69
+ | ISR | Draft 세션에서 공용 캐시를 우회 | 다른 방문자의 캐시나 재검증 시간을 바꾸지 않음 |
70
+ | `generateStaticParams` | 생성된 경로의 페이지 데이터 미리보기 | 빌드 시 매개변수 목록은 콘솔로 재생성하지 않음 |
71
+ | `unstable_cache` / `use cache` | Draft의 캐시 우회 중 실행하는 fetch 변경 | 사용자 정의 외부 캐시·직접 DB 호출까지 가로채지 않음 |
72
+
73
+ App Router의 **Next.js 16.3.5, Node.js 20.9 이상**을 기준으로 검증했습니다. 패키지의 Next peer 범위는 `>=16.3.5 <17`입니다. 그 범위의 모든 향후 버전을 검증했다는 뜻은 아닙니다. **Pages Router, Edge, `output: 'export'`는 자동 연결 대상이 아닙니다.** 정적 export에는 Draft 쿠키를 만들고 페이지를 다시 렌더할 서버가 없습니다.
74
+
75
+ 이미 CMS가 켜 둔 Draft 세션은 `test.clear()`로 종료하지 않습니다. 도구가 처음 연 세션만 소유 표시 쿠키로 추적합니다. CMS와 같은 브라우저에서 테스트 중 CMS가 세션의 소유권을 바꾸는 복잡한 흐름에는 앱이 별도 세션 정책을 정해야 합니다.
76
+
77
+ ## 호환성 브리지
78
+
79
+ 일반 요청에서 `headers()`를 읽으면 SSG가 동적 페이지로 바뀌고, `use cache` 내부에서 읽으면 오류가 발생합니다. 따라서 서버 연결은 우선 공개 `draftMode()`로 활성 여부를 확인하며, 비활성 요청과 빌드 중 fetch는 원래 경로로 보냅니다.
80
+
81
+ 활성 Draft 요청에서는 `src/internal/next-request.ts`의 작은 브리지가 **Next 내부 Draft provider의 `_mutableCookies`를 읽기 전용으로 사용**합니다. 이것으로 `force-static`과 Cache Components의 캐시 범위에서도 요청별 쿠키와 동일한 요청 식별자를 얻습니다. Next 내부 객체를 수정하지 않으며 테스트 쿠키 두 개만 읽습니다.
82
+
83
+ 이 부분은 공개 API만으로 구현된 호환성 보장이 아닙니다. 내부 구조가 달라지면 명시적인 `Unsupported Next.js` 오류를 내며 잘못된 공유 상태로 진행하지 않습니다. Next 업그레이드 시 `npm run test:next`로 production 회귀 테스트를 통과시켜야 합니다. CI는 설치된 tarball과 CLI로 dev, SSR, SSG, ISR, `force-static`, `generateStaticParams`, `unstable_cache`, Cache Components의 `use cache`, 비활성 production 빌드를 검사합니다. 정적 manifest, 서버 HTML, 독립 방문자와 초기화 후 원래 캐시도 검증합니다.
84
+
85
+ 참고: [Next Draft Mode](https://nextjs.org/docs/app/guides/draft-mode), [draftMode API](https://nextjs.org/docs/app/api-reference/functions/draft-mode), [headers API](https://nextjs.org/docs/app/api-reference/functions/headers).
86
+
87
+ ## 클라이언트 연결 상태
88
+
89
+ ```ts
90
+ const controller = setupNextTestModeClient({
91
+ enabled: true, // 앱의 개발/QA 환경 조건 사용
92
+ // draftEndpoint: '/api/next-test-mode',
93
+ // refresh: () => router.refresh(), // 앱이 선택하는 갱신; 기본값은 전체 새로고침
94
+ onError: error => console.error(error.message),
95
+ });
96
+ await controller.ready; // 초기 Draft 상태 확인. 실패하면 reject
97
+ await controller.sync(); // 현재 상태와 Draft 세션을 다시 맞추기
98
+ // 종료/HMR cleanup: controller.stop()
99
+ ```
100
+
101
+ 기본 오류 처리는 Console 출력과 `next-test-mode:error` CustomEvent입니다. 이벤트 `detail`은 오류 메시지입니다. 실패 시 자동 새로고침하지 않습니다. 로컬 런타임과 JSON 쿠키 기록은 이미 끝났을 수 있으므로, 비동기 Draft 연결 전체가 원자적이라고 가정하지 마세요. 설정을 바로잡은 후 `sync()`하거나 페이지를 다시 여세요.
102
+
103
+ 연결 요청은 설치 전에 캡처한 원래 fetch를 사용하므로 Console mock에 가로채이지 않습니다. 빠른 연속 입력은 직렬화하고 최신 상태 확인 후 갱신합니다. 재배포로 Next Draft 쿠키가 만료되면 다음 클라이언트 초기화에서 다시 연결합니다.
104
+
105
+ `refresh: () => router.refresh()`는 서버 컴포넌트를 갱신하지만, 앱의 React Query/SWR 캐시나 클라이언트 state를 모두 초기화하지 않습니다. 기본 전체 새로고침은 이러한 앱별 연결을 요구하지 않습니다.
106
+
107
+ ## 접근 제어와 상태
108
+
109
+ 제어 경로는 활성 환경, 동일 출처 POST, `Origin`, 커스텀 헤더, JSON 형식과 본문 크기를 검사합니다. 외부에 노출하는 QA 앱은 앱의 기존 로그인 정책을 연결할 수 있습니다.
110
+
111
+ ```ts
112
+ export const POST = createDraftModeHandler({
113
+ enabled: process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1',
114
+ authorize: async request => canUsePreview(request), // 앱의 기존 권한 검사
115
+ });
116
+ ```
117
+
118
+ 제어 경로와 `authorize` 안의 fetch는 테스트 가로채기에서 제외합니다. 기존 Draft 쿠키를 가진 요청의 서버 미리보기도 앱 자체 인증으로 보호해야 합니다. 테스트 쿠키는 인증 수단이 아닙니다.
119
+
120
+ 브라우저·서버·Draft 경로의 `cookieKey`를 동일하게 유지하세요. 기본 선택 쿠키는 `test-mode.entries`, JSON은 `test-mode.entries.ssr`, 소유 표시 쿠키는 `test-mode.entries.draft-owner`입니다. 선택과 JSON은 합쳐서 **3,500 URL 인코딩 바이트**로 제한합니다. 쿠키는 같은 브라우저의 탭이 공유합니다. 민감한 실제 데이터를 테스트 JSON에 담지 말고 앱 소유의 샘플 시나리오를 사용하세요.
121
+
122
+ ## 일반 Node와 수동 어댑터
123
+
124
+ Next 밖의 Node 서버에서는 기존 API를 유지합니다.
125
+
126
+ ```ts
127
+ import { createServer } from 'node:http';
128
+ import { withTestMode } from '@uiwwsw/next-test-mode/node';
129
+ import { app } from './app.js';
130
+
131
+ createServer(withTestMode(app, { enabled: true })).listen(3000);
132
+ ```
133
+
134
+ 브라우저에는 개발 환경에서 `setupTestMode({ enabled: true, ssr: true })`를 연결합니다. `withTestMode`는 AsyncLocalStorage로 요청별 상태를 분리하며, 들어온 인증 쿠키를 외부 fetch에 자동 전달하지 않습니다. 이 일반 Node 연결에는 Next Draft Mode가 없습니다.
135
+
136
+ 서버 코드를 직접 연결하려면 `createServerTestMode({ cookieHeader, ssr: true, ...catalog })`가 반환하는 `fetch`와 `runtime`을 요청 안에서 사용하세요. 가변 런타임을 사용자 간에 공유하지 마세요.
@@ -0,0 +1,252 @@
1
+ # Story-Based Test Mode Design
2
+
3
+ `@uiwwsw/next-test-mode` supports two testing perspectives without mixing their responsibilities.
4
+
5
+ - `test.feat`: feature-level API mock/patch testing for developers.
6
+ - `test.story`: user-facing scenario testing for QA, product, design, and frontend sharing.
7
+
8
+ The package has a feature API around `defineMock`, `definePatch`, `test.feat.list/add/remove/set/toggle()`, `test.active()`, and `test.clear()`. It also has a story layer around `defineStory`, `entry`, `test.story.list/add/remove/set/toggle()`, and `test.story()`.
9
+
10
+ ## Why Split The Concepts
11
+
12
+ API-level mocks are precise, but they are not the best sharing language.
13
+
14
+ ```js
15
+ test.feat.add("/orders/cart/getCartInfo:502");
16
+ ```
17
+
18
+ That is useful for a developer, but a tester usually wants the screen state:
19
+
20
+ ```js
21
+ test.story("cart.load.server-error");
22
+ ```
23
+
24
+ The story API hides path/caseKey details and exposes the state a person wants to verify.
25
+
26
+ ## test.feat
27
+
28
+ `test.feat` is the foundation of the package. It answers: "Can this runtime mock or patch one API behavior correctly?"
29
+
30
+ It covers:
31
+
32
+ - path normalization
33
+ - caseKey serialization and parsing
34
+ - mock handler lookup
35
+ - patch handler lookup
36
+ - active entry storage
37
+ - cookie/server handoff
38
+ - fetch patching
39
+ - overlay state
40
+ - page-aware overlay visibility
41
+ - catalog search
42
+ - pass-through behavior
43
+ - HTTP status result behavior
44
+
45
+ Good feature API examples:
46
+
47
+ ```js
48
+ test.feat.add("/api/session/signin:locked");
49
+ test.feat.remove("/api/session/signin:locked");
50
+ test.active();
51
+ test.feat.list();
52
+ test.clear();
53
+ ```
54
+
55
+ Good package tests:
56
+
57
+ ```ts
58
+ serializeEntry("/api/session/signin", "locked");
59
+ parseEntry("/api/session/signin:locked");
60
+ createTestMode({ definitions });
61
+ installMockFetch(runtime);
62
+ ```
63
+
64
+ This layer remains stable, explicit, and close to the runtime internals.
65
+
66
+ ## test.story
67
+
68
+ `test.story` is a higher-level catalog. It answers: "Which screen state or user flow do I want to reproduce?"
69
+
70
+ Browser API:
71
+
72
+ ```js
73
+ test();
74
+ test.help();
75
+ test.search();
76
+ test.search("cart");
77
+ test.story.list();
78
+ test.story.list("/cart");
79
+ test.story.add("main.event-popup.default");
80
+ test.story.remove("main.event-popup.default");
81
+ test.story.set(["cart.discount-flow"]);
82
+ test.story.toggle("cart.discount-flow");
83
+ test.story("cart.discount-flow");
84
+ test.active();
85
+ test.clear();
86
+ ```
87
+
88
+ Behavior:
89
+
90
+ - `test()` returns command help.
91
+ - `test.help()` returns the same command help object.
92
+ - `test.search()` lists every registered feature and story entry.
93
+ - `test.search(query | options)` searches and filters feature and story catalogs together.
94
+ - `test.story.list(input?)` lists story scenarios.
95
+ - `test.story.add(storyKey)` keeps the current active entries and adds the story entries.
96
+ - `test.story.remove(storyKey)` removes the story entries from the current active entries.
97
+ - `test.story.set(storyKey | storyKeys)` replaces the current active entries with one or more stories.
98
+ - `test.story.toggle(storyKey)` removes the story when all its entries are active; otherwise it adds the story.
99
+ - `test.story(storyKey)` is a shorthand for `test.story.set(storyKey)`.
100
+ - Unknown `storyKey` is ignored and returns the current active entries.
101
+ - If multiple entries target the same path with different caseKeys, the later entry wins through the existing active-entry normalization rules.
102
+
103
+ ## Story Definition
104
+
105
+ The story layer is intentionally small.
106
+
107
+ ```ts
108
+ defineStory({
109
+ key: "cart.load.server-error",
110
+ title: "Cart - server error",
111
+ description: "Reproduces the cart load failure state and retry guidance.",
112
+ entries: [entry("/orders/cart/getCartInfo", "502")],
113
+ });
114
+ ```
115
+
116
+ Required fields:
117
+
118
+ - `key`: stable console identifier
119
+ - `title`: short human-readable name
120
+ - `description`: what state this creates and what should be checked
121
+ - `entries`: mock/patch entries used to build the state
122
+
123
+ Story pages are inherited from referenced feature entries and merged with explicit story pages. Put `pages` on features by default. Use explicit story pages only when the story should appear on extra screens.
124
+
125
+ Do not require `tags` at this stage. `pages`, `key`, `title`, and `description` are enough for discovery. Tags can be reconsidered later if the catalog becomes too large to search comfortably.
126
+
127
+ ## Folder Pattern
128
+
129
+ Applications should separate feature entries from story combinations.
130
+
131
+ The package ships a starter folder at:
132
+
133
+ ```txt
134
+ node_modules/@uiwwsw/next-test-mode/templates/test-mode/
135
+ ```
136
+
137
+ ```txt
138
+ test-mode/
139
+ features/
140
+ auth.ts
141
+ cart.ts
142
+ stories/
143
+ auth.stories.ts
144
+ cart.stories.ts
145
+ index.ts
146
+ ```
147
+
148
+ - `features/*`: defines one API behavior at a time with `defineMock` or `definePatch`; put `pages` here when the API behavior belongs to specific screens.
149
+ - `stories/*`: combines feature entries into user-visible states with `defineStory`.
150
+ - `index.ts`: creates the runtime by passing all features to `definitions`/`patchDefinitions` and all stories to `stories`.
151
+
152
+ ## Naming Rules
153
+
154
+ Use the user-visible state, not the API implementation detail.
155
+
156
+ Good:
157
+
158
+ ```txt
159
+ auth.login.locked
160
+ auth.oauth.session-expired
161
+ cart.discount-flow
162
+ coupon.list.long-text
163
+ withdraw.unused-voucher
164
+ fulfillment.restore.none
165
+ ```
166
+
167
+ Avoid:
168
+
169
+ ```txt
170
+ getCartInfo.502
171
+ oauthUserInfo.AU-204
172
+ membersGetHeader.case1
173
+ ```
174
+
175
+ Recommended shape:
176
+
177
+ ```txt
178
+ domain.screen.state
179
+ domain.flow.result
180
+ domain.feature.variant
181
+ ```
182
+
183
+ ## Catalog Search
184
+
185
+ Initial filtering should stay simple:
186
+
187
+ - by page
188
+ - by active state
189
+ - by text query across `key`, `title`, `description`, `pages`, and `entries`
190
+
191
+ Example:
192
+
193
+ ```js
194
+ test.story.list("/coupon/list");
195
+ test.story.list({ page: "/coupon/list", query: "long" });
196
+ test.story.list({ active: true });
197
+ test.search("coupon");
198
+ test.search({ page: "/coupon/list", query: "long" });
199
+ ```
200
+
201
+ `test.search()` returns both catalogs:
202
+
203
+ ```ts
204
+ {
205
+ features: FeatureCatalogItem[];
206
+ stories: StoryCatalogItem[];
207
+ }
208
+ ```
209
+
210
+ ## Overlay Visibility
211
+
212
+ The `TEST MODE` overlay is page-aware.
213
+
214
+ - If an active feature has `pages`, the overlay appears only when the current page matches those pages.
215
+ - If an active story is applied, the overlay uses the story's explicit pages plus the pages inherited from its feature entries.
216
+ - If a feature has no `pages`, it is treated as global and can show the overlay on every page.
217
+ - SPA navigation through `pushState`, `replaceState`, `popstate`, and `hashchange` re-checks overlay visibility.
218
+
219
+ ## Sharing Guide
220
+
221
+ When sharing this design with a team, lead with the distinction:
222
+
223
+ ```md
224
+ Test mode now has two levels.
225
+
226
+ - Feature tests validate the runtime: API entries, caseKeys, patching, storage, and fetch behavior.
227
+ - Story tests reproduce user-visible screen states with stable story keys.
228
+
229
+ Use `test.search()` for the global feature/story catalog view.
230
+ Use `test.feat.list()` for one-API feature entries when debugging.
231
+ Use `test.story.list()` and `test.story("cart.discount-flow")` when sharing QA scenarios.
232
+ ```
233
+
234
+ ## Runtime Guarantees
235
+
236
+ - `createTestMode({ stories })` validates stories during construction.
237
+ - Story validation runs when the runtime is created or when definitions are registered programmatically.
238
+ - Duplicate story keys throw.
239
+ - Empty `key`, `title`, `description`, or `entries` throw.
240
+ - Missing pages throw only when neither the story nor its referenced features provide pages.
241
+ - Unknown story entries throw.
242
+ - `test.story.set(storyKey | storyKeys)` replaces active entries.
243
+ - `test.story.add(storyKey)` adds entries while preserving compatible active entries.
244
+ - `test.story.remove(storyKey)` removes one story's entries.
245
+ - `test.story.toggle(storyKey)` toggles one story.
246
+ - `test()` shows command help.
247
+ - `test("story.key")` applies a story when the key exists; otherwise it keeps the original toggle behavior.
248
+
249
+ This keeps the runtime useful for developers while giving teams a cleaner language for screen-state verification.
250
+
251
+
252
+
package/package.json ADDED
@@ -0,0 +1,136 @@
1
+ {
2
+ "name": "@uiwwsw/next-test-mode",
3
+ "version": "0.6.0",
4
+ "description": "Console-first Next.js test mode: keep fetch calls unchanged and preview CSR, SSR, ISR and SSG with session-isolated Draft Mode.",
5
+ "type": "module",
6
+ "packageManager": "npm@11.16.0",
7
+ "license": "MIT",
8
+ "author": "uiwwsw",
9
+ "sideEffects": false,
10
+ "files": [
11
+ "dist",
12
+ "bin",
13
+ "src",
14
+ "docs/*.md",
15
+ "templates/test-mode",
16
+ "CHANGELOG.md",
17
+ "LICENSE",
18
+ "README.md"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ },
25
+ "./core": {
26
+ "types": "./dist/core.d.ts",
27
+ "import": "./dist/core.js"
28
+ },
29
+ "./browser": {
30
+ "types": "./dist/browser.d.ts",
31
+ "import": "./dist/browser.js"
32
+ },
33
+ "./fetch": {
34
+ "types": "./dist/fetch.d.ts",
35
+ "import": "./dist/fetch.js"
36
+ },
37
+ "./server": {
38
+ "types": "./dist/server.d.ts",
39
+ "import": "./dist/server.js"
40
+ },
41
+ "./node": {
42
+ "types": "./dist/node.d.ts",
43
+ "import": "./dist/node.js"
44
+ },
45
+ "./setup": {
46
+ "types": "./dist/setup.d.ts",
47
+ "import": "./dist/setup.js"
48
+ },
49
+ "./next": {
50
+ "types": "./dist/next.d.ts",
51
+ "import": "./dist/next.js"
52
+ },
53
+ "./client": {
54
+ "types": "./dist/client.d.ts",
55
+ "import": "./dist/client.js"
56
+ }
57
+ },
58
+ "main": "./dist/index.js",
59
+ "types": "./dist/index.d.ts",
60
+ "scripts": {
61
+ "build": "npm run clean && tsc -p tsconfig.json",
62
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
63
+ "typecheck": "tsc -p tsconfig.json --noEmit",
64
+ "test": "npm run build && node --test tests/*.test.mjs",
65
+ "test:browser": "npm run build:playground && playwright test",
66
+ "test:package": "node scripts/check-package.mjs",
67
+ "ci": "npm run typecheck && npm test && npm run test:package",
68
+ "prepack": "npm run build",
69
+ "prepublishOnly": "npm run ci",
70
+ "pack:dry-run": "npm pack --dry-run",
71
+ "release:check": "node scripts/check-release.mjs",
72
+ "dev:example": "npm run build && node scripts/serve-example.mjs",
73
+ "docs:assets": "npm run build:demo && node scripts/render-doc-assets.mjs",
74
+ "build:demo": "npm run build && node scripts/prepare-next-demo.mjs && next build",
75
+ "dev:ssr": "npm run build && node examples/server/server.mjs",
76
+ "test:next": "npm run build && node scripts/check-next.mjs",
77
+ "build:playground": "npm run build && node scripts/build-demo.mjs",
78
+ "dev:demo": "npm run build && node scripts/prepare-next-demo.mjs && next dev",
79
+ "test:demo": "npm run build:demo && playwright test --config playwright.demo.config.mjs"
80
+ },
81
+ "keywords": [
82
+ "api-mocking",
83
+ "fetch",
84
+ "mock",
85
+ "qa",
86
+ "scenario",
87
+ "typescript",
88
+ "testing",
89
+ "response-patching",
90
+ "test-mode",
91
+ "vanilla",
92
+ "devtools",
93
+ "ui-debugging",
94
+ "ssr",
95
+ "nextjs",
96
+ "next",
97
+ "draft-mode",
98
+ "isr",
99
+ "ssg"
100
+ ],
101
+ "engines": {
102
+ "node": ">=20.9"
103
+ },
104
+ "repository": {
105
+ "type": "git",
106
+ "url": "git+https://github.com/uiwwsw/next-test-mode.git"
107
+ },
108
+ "bugs": {
109
+ "url": "https://github.com/uiwwsw/next-test-mode/issues"
110
+ },
111
+ "homepage": "https://test-mode-tau.vercel.app/",
112
+ "publishConfig": {
113
+ "access": "public"
114
+ },
115
+ "devDependencies": {
116
+ "@playwright/test": "1.63.0",
117
+ "@types/node": "18.19.130",
118
+ "@types/react": "19.3.0",
119
+ "@types/react-dom": "19.3.0",
120
+ "next": "16.3.5",
121
+ "react": "19.3.0",
122
+ "react-dom": "19.3.0",
123
+ "typescript": "5.9.3"
124
+ },
125
+ "peerDependencies": {
126
+ "next": ">=16.3.5 <17"
127
+ },
128
+ "peerDependenciesMeta": {
129
+ "next": {
130
+ "optional": true
131
+ }
132
+ },
133
+ "bin": {
134
+ "next-test-mode": "./bin/test-mode.mjs"
135
+ }
136
+ }