@uiwwsw/next-test-mode 0.6.0 → 0.7.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.
@@ -11,15 +11,17 @@ npx @uiwwsw/next-test-mode init
11
11
 
12
12
  App Router의 루트 또는 `src/` 구조를 감지합니다. TS 프로젝트는 `.ts`, JS 프로젝트는 `.js` 파일을 생성합니다. 기존 설정은 덮어쓰지 않습니다. 변경하지 않은 구 버전 생성 파일은 `--migrate`로 이전할 수 있습니다.
13
13
 
14
- 생성하는 서버 시작 코드:
14
+ 테스트 구현은 `test-mode/catalog.ts`, `test-mode/client.ts`, `test-mode/server.ts`에 모읍니다. 브라우저와 서버가 같은 catalog를 읽으며, 실제 페이지와 API는 이 폴더를 import하지 않습니다. 연결 파일은 활성 환경 여부를 검사한 뒤 이 폴더만 연결합니다.
15
+
16
+ 생성하는 서버 연결 코드:
15
17
 
16
18
  ```ts
17
19
  // instrumentation.ts (또는 src/instrumentation.ts)
18
20
  export async function register() {
19
21
  if (process.env.NEXT_RUNTIME === 'nodejs' &&
20
22
  (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
+ const { registerTestMode } = await import('./test-mode/server');
24
+ registerTestMode();
23
25
  }
24
26
  }
25
27
  ```
@@ -28,24 +30,28 @@ export async function register() {
28
30
 
29
31
  ```ts
30
32
  // 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
- });
33
+ if (process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1') {
34
+ require('./test-mode/client');
35
+ }
36
36
  ```
37
37
 
38
38
  Draft Mode 경로:
39
39
 
40
40
  ```ts
41
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
- });
42
+ export async function POST(request: Request) {
43
+ if (process.env.NODE_ENV === 'development' || process.env.NEXT_PUBLIC_NEXT_TEST_MODE === '1') {
44
+ const { handleDraft } = await import('../../../test-mode/server');
45
+ return handleDraft(request);
46
+ }
47
+ return new Response(null, { status: 404 });
48
+ }
47
49
  ```
48
50
 
51
+ 클라이언트는 조건부 동기 로딩으로 앱의 첫 fetch보다 먼저 설치합니다. 초기화를 기다리지 않는 동적 import는 처음 보낸 요청을 놓칠 수 있습니다. Next 번들러가 이 require를 처리하며, 조건이 꺼진 production 빌드에서는 테스트 카탈로그가 제거되는지 CI가 검증합니다.
52
+
53
+ `test-mode/client.ts`는 `setupNextTestModeClient({ ...catalog, enabled: true })`를 호출합니다. `test-mode/server.ts`는 `setupNextTestMode({ ...catalog, enabled: true })`와 `createDraftModeHandler({ cookieKey: catalog.cookieKey, enabled: true })`를 연결합니다. 사용자 인증 등 테스트 환경 정책도 이 서버 파일에서 설정하세요.
54
+
49
55
  Next의 기본 Node 런타임을 사용합니다. Cache Components와 함께 쓰는 앱에는 별도의 `runtime` route 설정을 추가하지 않습니다. QA 배포에서는 `NEXT_PUBLIC_NEXT_TEST_MODE=1`을 **빌드와 실행 환경 모두**에 설정하고 재배포하세요. 기본 production 빌드에서는 브라우저 설치와 서버 연결이 꺼지며 제어 경로는 404를 반환합니다.
50
56
 
51
57
  ## 콘솔에서 SSR이 바뀌는 과정
@@ -89,18 +95,23 @@ App Router의 **Next.js 16.3.5, Node.js 20.9 이상**을 기준으로 검증했
89
95
  ```ts
90
96
  const controller = setupNextTestModeClient({
91
97
  enabled: true, // 앱의 개발/QA 환경 조건 사용
98
+ timeoutMs: 10000, // 연결과 응답 본문을 포함한 시간 제한
92
99
  // draftEndpoint: '/api/next-test-mode',
93
100
  // refresh: () => router.refresh(), // 앱이 선택하는 갱신; 기본값은 전체 새로고침
94
101
  onError: error => console.error(error.message),
95
102
  });
96
103
  await controller.ready; // 초기 Draft 상태 확인. 실패하면 reject
97
104
  await controller.sync(); // 현재 상태와 Draft 세션을 다시 맞추기
105
+ controller.cache.status(); // 오류/연결/미반영 변경 확인
106
+ await controller.cache.refresh(); // 값이 같아도 새로 렌더
98
107
  // 종료/HMR cleanup: controller.stop()
99
108
  ```
100
109
 
101
110
  기본 오류 처리는 Console 출력과 `next-test-mode:error` CustomEvent입니다. 이벤트 `detail`은 오류 메시지입니다. 실패 시 자동 새로고침하지 않습니다. 로컬 런타임과 JSON 쿠키 기록은 이미 끝났을 수 있으므로, 비동기 Draft 연결 전체가 원자적이라고 가정하지 마세요. 설정을 바로잡은 후 `sync()`하거나 페이지를 다시 여세요.
102
111
 
103
- 연결 요청은 설치 전에 캡처한 원래 fetch를 사용하므로 Console mock에 가로채이지 않습니다. 빠른 연속 입력은 직렬화하고 최신 상태 확인 후 갱신합니다. 재배포로 Next Draft 쿠키가 만료되면 다음 클라이언트 초기화에서 다시 연결합니다.
112
+ Console에서는 `test.cache.bypass()`로 mock 없이 실제 데이터의 Draft 미리보기를 시작하고, `test.cache.restore()` 또는 `test.clear()`로 종료합니다. 수동 우회 선택은 `.preview` 세션 쿠키로 유지됩니다. `test.cache.status()`의 `scope`는 `next-draft-session`이며 공용 캐시 삭제를 뜻하지 않습니다.
113
+
114
+ 연결 요청은 설치 전에 캡처한 원래 fetch를 사용하므로 Console mock에 가로채이지 않습니다. 빠른 연속 입력은 직렬화하고 최신 상태 확인 후 갱신합니다. 비동기 refresh 도중 추가된 입력도 다시 확인해 누락하지 않습니다. 재배포로 Next Draft 쿠키가 만료되면 다음 클라이언트 초기화에서 다시 연결합니다.
104
115
 
105
116
  `refresh: () => router.refresh()`는 서버 컴포넌트를 갱신하지만, 앱의 React Query/SWR 캐시나 클라이언트 state를 모두 초기화하지 않습니다. 기본 전체 새로고침은 이러한 앱별 연결을 요구하지 않습니다.
106
117
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uiwwsw/next-test-mode",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
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
5
  "type": "module",
6
6
  "packageManager": "npm@11.16.0",
package/src/browser.ts CHANGED
@@ -159,6 +159,8 @@ const installExtensions = (
159
159
  export const installConsole = (
160
160
  testMode: TestMode,
161
161
  {
162
+ commands = {},
163
+ commandHelp = {},
162
164
  extensions = [],
163
165
  globalName = "test",
164
166
  installExtensions: shouldInstallExtensions = true,
@@ -298,6 +300,7 @@ export const installConsole = (
298
300
  );
299
301
  const help = (): TestModeConsoleHelp => ({
300
302
  commands: {
303
+ ...commandHelp,
301
304
  "test()": "Show this help.",
302
305
  "test('story.key')":
303
306
  "Apply a story when the key exists; otherwise toggle a feature entry.",
@@ -360,6 +363,11 @@ export const installConsole = (
360
363
  search: (input?: TestModeSearchInput) => testMode.search(input),
361
364
  story: storyCommand,
362
365
  });
366
+ for (const key of Object.keys(commands)) {
367
+ if (key in api)
368
+ throw new TypeError(`Console command already exists: ${key}`);
369
+ Object.defineProperty(api, key, { value: commands[key], enumerable: true });
370
+ }
363
371
  const cleanups: (() => void)[] = [];
364
372
  const cleanup = createCleanup(cleanups);
365
373
  try {
@@ -468,6 +476,8 @@ export const installTestModeOverlay = (
468
476
  document: documentRef = typeof document === "undefined"
469
477
  ? undefined
470
478
  : document,
479
+ commands = {},
480
+ commandHelp = {},
471
481
  extensions = [],
472
482
  globalName = "test",
473
483
  installConsole: shouldInstallConsole = true,
@@ -539,6 +549,8 @@ export const installTestModeOverlay = (
539
549
  if (shouldInstallConsole)
540
550
  cleanups.push(
541
551
  installConsole(testMode, {
552
+ commands,
553
+ commandHelp,
542
554
  extensions,
543
555
  globalName,
544
556
  installExtensions: false,
package/src/client.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import { setupTestMode } from "./setup.js";
2
2
  import type { SetupTestModeOptions } from "./setup.js";
3
+ import type { TestModeExtension } from "./types.js";
4
+ import { createPreviewSession } from "./internal/preview-session.js";
5
+ import type { PreviewStatus } from "./internal/preview-session.js";
6
+ import { createDraftTransport } from "./internal/draft-transport.js";
7
+ import { readCookieValue } from "./internal/storage.js";
8
+
9
+ export type NextCacheStatus = Readonly<
10
+ Omit<PreviewStatus, "phase"> & {
11
+ phase: PreviewStatus["phase"] | "disabled";
12
+ scope: "next-draft-session";
13
+ manualBypass: boolean;
14
+ cache: "unknown" | "bypass" | "default";
15
+ }
16
+ >;
3
17
 
4
18
  export type NextTestModeClientOptions = Omit<
5
19
  SetupTestModeOptions,
@@ -9,106 +23,164 @@ export type NextTestModeClientOptions = Omit<
9
23
  draftEndpoint?: string;
10
24
  refresh?: () => void | Promise<void>;
11
25
  onError?: (error: Error) => void;
26
+ /** Bound the Draft handshake, including its response body. Default 10 seconds. */
27
+ timeoutMs?: number;
12
28
  }>;
13
29
 
14
- /** One browser entry connects Console, fetch, JSON handoff and Next Draft Mode. */
30
+ /** Browser composition only; transport and synchronization have independent lifecycles. */
15
31
  export const setupNextTestModeClient = ({
16
32
  draftEndpoint = "/api/next-test-mode",
17
33
  refresh = () => location.reload(),
34
+ timeoutMs = 10000,
18
35
  onError = (error) => {
19
36
  console.error("[next-test-mode]", error.message);
20
37
  window.dispatchEvent(
21
38
  new CustomEvent("next-test-mode:error", { detail: error.message }),
22
39
  );
23
40
  },
41
+ overlay,
24
42
  ...options
25
43
  }: NextTestModeClientOptions = {}) => {
44
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
45
+ throw new RangeError("timeoutMs must be between 1 and 2147483647.");
46
+ if (overlay?.commands && Object.hasOwn(overlay.commands, "cache"))
47
+ throw new TypeError("The Next Console cache namespace is reserved.");
26
48
  let stopped = false;
27
- let pending: Promise<void> | undefined;
28
- let dirty = false;
29
- let lastSynced: string | undefined;
30
- const abort = new AbortController();
49
+ let session: ReturnType<typeof createPreviewSession> | undefined;
50
+ let timer: ReturnType<typeof setTimeout> | undefined;
31
51
  const transport = globalThis.fetch.bind(globalThis);
52
+ const key = `${options.cookieKey ?? options.storageKey ?? "test-mode.entries"}.preview`;
53
+ const manual = () =>
54
+ typeof document !== "undefined" &&
55
+ readCookieValue(document.cookie, key) === "1";
56
+ const report = (cause: unknown) => {
57
+ if (!stopped)
58
+ onError(cause instanceof Error ? cause : new Error(String(cause)));
59
+ };
60
+ const schedule = () => {
61
+ clearTimeout(timer);
62
+ timer = setTimeout(() => {
63
+ if (!stopped && session?.status().pendingChanges)
64
+ void session.sync().catch(report);
65
+ }, 50);
66
+ };
67
+ const listeners = new Set<() => void>();
68
+ const selectManual = (enabled: boolean) => {
69
+ if (stopped || !installation.runtime.isAvailable())
70
+ throw new Error("Next Test Mode is not available.");
71
+ document.cookie = `${key}=${enabled ? "1" : ""}; Path=/; SameSite=Lax${location.protocol === "https:" ? "; Secure" : ""}${enabled ? "" : "; Max-Age=0"}`;
72
+ if (manual() !== enabled)
73
+ throw new Error(
74
+ "Could not save the cache preview preference. Enable cookies.",
75
+ );
76
+ for (const listener of listeners) listener();
77
+ schedule();
78
+ };
79
+ const bypass: TestModeExtension = {
80
+ key: "next-cache",
81
+ label: "Next cache bypass",
82
+ isActive: manual,
83
+ enable: () => selectManual(true),
84
+ disable: () => {
85
+ if (manual()) selectManual(false);
86
+ },
87
+ subscribe: (listener) => {
88
+ listeners.add(listener);
89
+ return () => {
90
+ listeners.delete(listener);
91
+ };
92
+ },
93
+ };
94
+ const cache = {
95
+ status: (): NextCacheStatus => ({
96
+ ...(session?.status() ?? {
97
+ phase: "disabled" as const,
98
+ draftEnabled: null,
99
+ pendingChanges: false,
100
+ error: null,
101
+ }),
102
+ scope: "next-draft-session" as const,
103
+ manualBypass: manual(),
104
+ cache:
105
+ session?.status().draftEnabled === null || !session
106
+ ? "unknown"
107
+ : session.status().draftEnabled
108
+ ? "bypass"
109
+ : "default",
110
+ }),
111
+ bypass: () => {
112
+ selectManual(true);
113
+ return session!.sync(true);
114
+ },
115
+ refresh: () => {
116
+ if (!session || stopped)
117
+ return Promise.reject(new Error("Next Test Mode is not available."));
118
+ return session.sync(true);
119
+ },
120
+ restore: () => {
121
+ if (!session || stopped)
122
+ return Promise.reject(new Error("Next Test Mode is not available."));
123
+ installation.runtime.clear();
124
+ for (const extension of [bypass, ...(overlay?.extensions ?? [])])
125
+ extension.disable();
126
+ return session.sync();
127
+ },
128
+ };
32
129
  const installation = setupTestMode({
33
130
  ...options,
34
131
  ssr: true,
35
- refresh: () => {
36
- if (snapshot() !== lastSynced) {
37
- dirty = true;
38
- void sync().catch(report);
39
- }
132
+ refresh: schedule,
133
+ overlay: {
134
+ ...overlay,
135
+ extensions: [bypass, ...(overlay?.extensions ?? [])],
136
+ commands: { ...overlay?.commands, cache },
137
+ commandHelp: {
138
+ ...overlay?.commandHelp,
139
+ "test.cache.status()":
140
+ "Inspect Draft connection, cache bypass, pending changes and errors.",
141
+ "test.cache.bypass()":
142
+ "Preview fresh real data in this Next Draft session without mocks.",
143
+ "test.cache.refresh()":
144
+ "Refresh the current preview, even when values have not changed.",
145
+ "test.cache.restore()":
146
+ "Clear all test values and return to the ordinary cache path (preserve pre-existing CMS Draft).",
147
+ },
40
148
  },
41
149
  });
42
150
  const { runtime } = installation;
43
- const report = (error: unknown) => {
44
- if (!stopped)
45
- onError(error instanceof Error ? error : new Error(String(error)));
46
- };
47
- const snapshot = () =>
48
- JSON.stringify({
49
- entries: runtime.active(),
50
- overrides: runtime.overrides(),
51
- });
52
- const sync = (): Promise<void> => {
53
- if (stopped || !runtime.isAvailable()) return Promise.resolve();
54
- if (pending) return pending;
55
- pending = (async () => {
151
+ try {
152
+ if (runtime.isAvailable()) {
56
153
  const endpoint = new URL(draftEndpoint, location.href);
57
154
  if (endpoint.origin !== location.origin)
58
155
  throw new TypeError("Draft endpoint must be on the same origin.");
59
- while (!stopped) {
60
- const state = snapshot();
61
- const enabled =
62
- runtime.active().length > 0 || runtime.overrides().length > 0;
63
- const response = await transport(endpoint, {
64
- method: "POST",
65
- credentials: "same-origin",
66
- cache: "no-store",
67
- signal: abort.signal,
68
- headers: {
69
- "Content-Type": "application/json",
70
- "X-Next-Test-Mode": "1",
71
- },
72
- body: JSON.stringify({ enabled }),
73
- });
74
- if (!response.ok)
75
- throw new Error(
76
- `Draft Mode connection failed (HTTP ${response.status}). Check the generated route and the app's test-mode environment setting.`,
77
- );
78
- const result: unknown = await response.json();
79
- if (
80
- !result ||
81
- typeof result !== "object" ||
82
- typeof (result as { changed?: unknown }).changed !== "boolean" ||
83
- typeof (result as { enabled?: unknown }).enabled !== "boolean"
84
- )
85
- throw new Error("Draft endpoint returned an invalid response.");
86
- if (enabled && !(result as { enabled: boolean }).enabled)
87
- throw new Error("Draft endpoint did not enable the preview session.");
88
- if (state !== snapshot()) {
89
- dirty = true;
90
- continue;
91
- }
92
- lastSynced = state;
93
- if (!stopped && (dirty || (result as { changed: boolean }).changed)) {
94
- dirty = false;
95
- await refresh();
96
- }
97
- return;
98
- }
99
- })().finally(() => {
100
- pending = undefined;
101
- });
102
- return pending;
103
- };
156
+ session = createPreviewSession({
157
+ read: () => {
158
+ const entries = runtime.active();
159
+ const overrides = runtime.overrides();
160
+ const bypass = manual();
161
+ return {
162
+ key: JSON.stringify({ entries, overrides, bypass }),
163
+ enabled: bypass || entries.length > 0 || overrides.length > 0,
164
+ };
165
+ },
166
+ connect: createDraftTransport(transport, endpoint, timeoutMs),
167
+ refresh,
168
+ });
169
+ }
170
+ } catch (error) {
171
+ installation.stop();
172
+ throw error;
173
+ }
174
+ const sync = () => session?.sync() ?? Promise.resolve();
104
175
  const ready = sync();
105
176
  void ready.catch(report);
106
177
  const stop = () => {
107
- if (!stopped) {
108
- stopped = true;
109
- abort.abort();
110
- installation.stop();
111
- }
178
+ if (stopped) return;
179
+ stopped = true;
180
+ clearTimeout(timer);
181
+ session?.stop();
182
+ installation.stop();
183
+ listeners.clear();
112
184
  };
113
- return { runtime, ready, sync, stop };
185
+ return { runtime, ready, sync, cache, stop };
114
186
  };
@@ -0,0 +1,51 @@
1
+ /** Captured transport keeps preview controls outside the app's mockable fetch. */
2
+ export const createDraftTransport =
3
+ (transport: typeof fetch, endpoint: URL, timeoutMs: number) =>
4
+ async (enabled: boolean, parent: AbortSignal) => {
5
+ const abort = new AbortController();
6
+ const stop = () => abort.abort(parent.reason);
7
+ parent.addEventListener("abort", stop, { once: true });
8
+ if (parent.aborted) stop();
9
+ const timer = setTimeout(
10
+ () =>
11
+ abort.abort(
12
+ new Error(`Draft Mode connection timed out after ${timeoutMs}ms.`),
13
+ ),
14
+ timeoutMs,
15
+ );
16
+ try {
17
+ const response = await transport(endpoint, {
18
+ method: "POST",
19
+ credentials: "same-origin",
20
+ cache: "no-store",
21
+ signal: abort.signal,
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ "X-Next-Test-Mode": "1",
25
+ },
26
+ body: JSON.stringify({ enabled }),
27
+ });
28
+ if (!response.ok)
29
+ throw new Error(
30
+ `Draft Mode connection failed (HTTP ${response.status}). Check the generated route and the app's test-mode environment setting.`,
31
+ );
32
+ const result: unknown = await response.json();
33
+ if (
34
+ !result ||
35
+ typeof result !== "object" ||
36
+ typeof (result as { enabled?: unknown }).enabled !== "boolean" ||
37
+ typeof (result as { changed?: unknown }).changed !== "boolean"
38
+ )
39
+ throw new Error("Draft endpoint returned an invalid response.");
40
+ const state = result as { enabled: boolean; changed: boolean };
41
+ if (enabled && !state.enabled)
42
+ throw new Error("Draft endpoint did not enable the preview session.");
43
+ return state;
44
+ } catch (error) {
45
+ if (abort.signal.aborted && !parent.aborted) throw abort.signal.reason;
46
+ throw error;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ parent.removeEventListener("abort", stop);
50
+ }
51
+ };
@@ -0,0 +1,88 @@
1
+ export type PreviewSnapshot = Readonly<{ key: string; enabled: boolean }>;
2
+ export type PreviewStatus = Readonly<{
3
+ phase: "idle" | "syncing" | "refreshing" | "error" | "stopped";
4
+ draftEnabled: boolean | null;
5
+ pendingChanges: boolean;
6
+ error: string | null;
7
+ }>;
8
+
9
+ /** Framework/DOM independent coordinator. Never drops edits made during an async refresh. */
10
+ export const createPreviewSession = ({
11
+ read,
12
+ connect,
13
+ refresh,
14
+ }: {
15
+ read: () => PreviewSnapshot;
16
+ connect: (
17
+ enabled: boolean,
18
+ signal: AbortSignal,
19
+ ) => Promise<{ enabled: boolean; changed: boolean }>;
20
+ refresh: () => void | Promise<void>;
21
+ }) => {
22
+ const abort = new AbortController();
23
+ let phase: PreviewStatus["phase"] = "idle";
24
+ let draftEnabled: boolean | null = null;
25
+ let error: string | null = null;
26
+ let rendered = read().key;
27
+ let requestedRefresh = 0;
28
+ let completedRefresh = 0;
29
+ let pending: Promise<void> | undefined;
30
+ const status = (): PreviewStatus => ({
31
+ phase,
32
+ draftEnabled,
33
+ error,
34
+ pendingChanges:
35
+ read().key !== rendered || requestedRefresh !== completedRefresh,
36
+ });
37
+ const sync = (force = false): Promise<void> => {
38
+ if (phase === "stopped") return Promise.resolve();
39
+ if (force) requestedRefresh++;
40
+ if (pending) return pending;
41
+ pending = (async () => {
42
+ try {
43
+ while (!abort.signal.aborted) {
44
+ const snapshot = read();
45
+ const revision = requestedRefresh;
46
+ phase = "syncing";
47
+ error = null;
48
+ const result = await connect(snapshot.enabled, abort.signal);
49
+ if (abort.signal.aborted) return;
50
+ draftEnabled = result.enabled;
51
+ if (snapshot.key !== read().key) continue;
52
+ if (
53
+ result.changed ||
54
+ snapshot.key !== rendered ||
55
+ revision !== completedRefresh
56
+ ) {
57
+ phase = "refreshing";
58
+ await refresh();
59
+ if (abort.signal.aborted) return;
60
+ rendered = snapshot.key;
61
+ completedRefresh = revision;
62
+ }
63
+ if (snapshot.key !== read().key || revision !== requestedRefresh)
64
+ continue;
65
+ phase = "idle";
66
+ return;
67
+ }
68
+ } catch (cause) {
69
+ if (!abort.signal.aborted) {
70
+ phase = "error";
71
+ error = cause instanceof Error ? cause.message : String(cause);
72
+ }
73
+ throw cause;
74
+ }
75
+ })().finally(() => {
76
+ pending = undefined;
77
+ });
78
+ return pending;
79
+ };
80
+ return {
81
+ sync,
82
+ status,
83
+ stop: () => {
84
+ phase = "stopped";
85
+ abort.abort();
86
+ },
87
+ };
88
+ };
package/src/types.ts CHANGED
@@ -194,6 +194,9 @@ export type TestModeOptions = Readonly<{
194
194
  }>;
195
195
 
196
196
  export type TestModeOverlayOptions = Readonly<{
197
+ /** Extra Console namespaces; existing built-in commands cannot be replaced. */
198
+ commands?: Readonly<Record<string, unknown>>;
199
+ commandHelp?: Readonly<Record<string, string>>;
197
200
  /** Set false when installing before React hydration to avoid changing app-owned attributes. */
198
201
  datasetName?: string | false;
199
202
  document?: Document;
@@ -206,6 +209,9 @@ export type TestModeOverlayOptions = Readonly<{
206
209
  }>;
207
210
 
208
211
  export type TestModeConsoleOptions = Readonly<{
212
+ /** Extra Console namespaces; existing built-in commands cannot be replaced. */
213
+ commands?: Readonly<Record<string, unknown>>;
214
+ commandHelp?: Readonly<Record<string, string>>;
209
215
  extensions?: readonly TestModeExtension[];
210
216
  globalName?: string;
211
217
  installExtensions?: boolean;
@@ -8,7 +8,7 @@ cp -R node_modules/@uiwwsw/next-test-mode/templates/test-mode src/test-mode
8
8
 
9
9
  ## Next App Router
10
10
 
11
- 먼저 패키지의 `init`으로 서버·브라우저·Draft 경로를 생성하세요. 이 폴더에서 브라우저용 runtime을 만들거나 `install.ts`를 중복 실행하지 않고, 서버와 브라우저가 공유할 순수 등록 목록을 만듭니다.
11
+ `npx @uiwwsw/next-test-mode init`이 앱 안에 `test-mode/catalog`, `client`, `server`를 생성합니다. 반복할 시나리오는 그 catalog에 등록하세요. 이 템플릿에서는 `features/`와 `stories/`만 필요에 따라 가져오면 됩니다. `index.ts`와 `install.ts`의 범용 runtime을 중복 설치하지 마세요.
12
12
 
13
13
  ```ts
14
14
  // src/test-mode/catalog.ts
@@ -16,14 +16,15 @@ import { authFeatures } from './features/auth';
16
16
  import { authStories } from './stories/auth.stories';
17
17
 
18
18
  export const catalog = {
19
+ cookieKey: 'test-mode.entries',
19
20
  definitions: [...authFeatures],
20
21
  stories: [...authStories],
21
22
  };
22
23
  ```
23
24
 
24
- 생성된 서버 hook의 `setupNextTestMode({ ...catalog, enabled: true })`, 클라이언트 hook의 `setupNextTestModeClient({ ...catalog, enabled: 기존환경조건 })`에 같은 목록을 전달하세요. `/src` 구조의 hook에서는 `./test-mode/catalog`로 import합니다. 서버에서도 실행하는 정의에는 DOM이나 브라우저 전용 라이브러리를 넣지 마세요. `config.ts`의 범용 환경 감지 대신 생성된 Next 환경 조건을 유지합니다.
25
+ 생성된 두 설치 파일이 같은 catalog를 읽습니다. 실제 앱의 페이지와 API에는 import를 추가하지 않습니다. 서버에서도 실행하는 정의에는 DOM이나 브라우저 전용 라이브러리를 넣지 마세요. 빌드 조건은 생성된 instrumentation 파일에 유지해야 일반 production에서 테스트 코드가 제외됩니다.
25
26
 
26
- 등록 후 Console에서 `test.search()`로 목록을 보고 `test.story('auth.locked')`처럼 선택합니다. 정확한 story key는 `stories/auth.stories.ts`를 확인하세요. 전체 응답은 파일에 두고 선택 key만 쿠키로 보내면 큰 데이터도 JSON 쿠키 제한을 피할 수 있습니다.
27
+ 등록 후 Console의 `test.search()`로 목록을 보고 선택합니다. 큰 응답은 파일에 두고 선택 key만 전달하면 JSON 쿠키 제한을 피할 수 있습니다. `test.cache.bypass()`는 데이터 mock 없이 서버 미리보기만 켭니다.
27
28
 
28
29
  ## 범용 브라우저 앱
29
30