@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/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