@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,48 @@
1
+ import { ResponseOverrides } from "./overrides.js";
2
+ import { readCookieValue } from "./storage.js";
3
+ import type { TestModeState } from "../types.js";
4
+
5
+ // Leave room for the cookie name and attributes under common 4 KiB limits.
6
+ export const SSR_COOKIE_LIMIT = 3500;
7
+ export const ssrCookieKey = (cookieKey: string) => `${cookieKey}.ssr`;
8
+
9
+ const normalize = (input: unknown): TestModeState => {
10
+ if (!input || typeof input !== "object") throw new TypeError("Invalid SSR state.");
11
+ const state = input as Record<string, unknown>;
12
+ if (state.v !== 1 || !Array.isArray(state.entries) || !Array.isArray(state.overrides) ||
13
+ state.entries.some(item => typeof item !== "string"))
14
+ throw new TypeError("Invalid SSR state.");
15
+ const overrides = new ResponseOverrides();
16
+ for (const item of state.overrides) {
17
+ if (!item || typeof item !== "object" || (item.mode !== "mock" && item.mode !== "patch"))
18
+ throw new TypeError("Invalid SSR override.");
19
+ overrides.set(item.path, item.data, item.mode, item);
20
+ }
21
+ return { entries: [...state.entries], overrides: overrides.list() };
22
+ };
23
+
24
+ export const encodeSSRState = (state: TestModeState): string => {
25
+ const value = encodeURIComponent(JSON.stringify({ v: 1, ...state }));
26
+ if (value.length > SSR_COOKIE_LIMIT)
27
+ throw new RangeError(`SSR response values exceed ${SSR_COOKIE_LIMIT} encoded bytes. Use smaller values or a registered scenario.`);
28
+ return value;
29
+ };
30
+
31
+ /** Malformed or oversized client state never activates a partial server scenario. */
32
+ export const readSSRState = (cookie: string, key: string): TestModeState | null => {
33
+ try {
34
+ const value = readCookieValue(cookie, key);
35
+ if (!value || encodeURIComponent(value).length > SSR_COOKIE_LIMIT) return null;
36
+ return normalize(JSON.parse(value));
37
+ } catch { return null; }
38
+ };
39
+
40
+ export const writeSSRState = (key: string, state: TestModeState): void => {
41
+ if (!/^[!#$%&'*+\-.^_`|~0-9a-z]+$/i.test(key) || key.length > 128)
42
+ throw new TypeError("Use a short, valid cookie key for SSR test mode.");
43
+ const value = encodeSSRState(state);
44
+ const secure = location.protocol === "https:" ? "; Secure" : "";
45
+ document.cookie = `${key}=${value}; Path=/; SameSite=Lax${secure}`;
46
+ if (readCookieValue(document.cookie, key) !== decodeURIComponent(value))
47
+ throw new Error("SSR test mode could not save its cookie. Enable cookies or use browser-only mode.");
48
+ };
@@ -0,0 +1,75 @@
1
+ const DEFAULT_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
2
+
3
+ export const parseStoredPaths = (value: string | null | undefined) => {
4
+ if (!value) {
5
+ return [];
6
+ }
7
+
8
+ try {
9
+ const parsed = JSON.parse(value);
10
+
11
+ return Array.isArray(parsed)
12
+ ? parsed.filter((item): item is string => typeof item === "string")
13
+ : [];
14
+ } catch {
15
+ return [];
16
+ }
17
+ };
18
+
19
+ export const readCookieValue = (cookieHeader: string, name: string) => {
20
+ const rawValue =
21
+ cookieHeader
22
+ .split(";")
23
+ .map((cookie) => cookie.trim())
24
+ .find((cookie) => cookie.startsWith(`${name}=`))
25
+ ?.slice(name.length + 1) ?? "";
26
+
27
+ try {
28
+ return decodeURIComponent(rawValue);
29
+ } catch {
30
+ return rawValue;
31
+ }
32
+ };
33
+
34
+ export const writeCookie = (
35
+ name: string,
36
+ paths: readonly string[],
37
+ maxAgeSeconds = DEFAULT_COOKIE_MAX_AGE_SECONDS,
38
+ ) => {
39
+ if (typeof document === "undefined") {
40
+ return;
41
+ }
42
+
43
+ try {
44
+ document.cookie = [
45
+ `${name}=${encodeURIComponent(JSON.stringify(paths))}`,
46
+ "path=/",
47
+ `max-age=${maxAgeSeconds}`,
48
+ "samesite=lax",
49
+ ].join("; ");
50
+ } catch {
51
+ // Sandboxed browsers can disable cookies; in-memory controls still work.
52
+ }
53
+ };
54
+
55
+ export const readBrowserStorage = (key: string): string | null | undefined => {
56
+ try {
57
+ return typeof window === "undefined"
58
+ ? undefined
59
+ : window.localStorage.getItem(key);
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ };
64
+
65
+ export const writeBrowserStorage = (key: string, value: string | null) => {
66
+ try {
67
+ if (typeof window === "undefined") return false;
68
+ if (value === null) window.localStorage.removeItem(key);
69
+ else window.localStorage.setItem(key, value);
70
+ return true;
71
+ } catch {
72
+ // Storage is best effort (e.g. blocked access or an exhausted quota).
73
+ return false;
74
+ }
75
+ };
@@ -0,0 +1,2 @@
1
+ export const MOCK_RESULT = Symbol("TEST_MODE_MOCK_RESULT");
2
+ export const MOCK_PASS_THROUGH = Symbol("TEST_MODE_PASS_THROUGH");
package/src/next.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { cookies, draftMode } from "next/headers";
2
+ import { installServerTestMode } from "./node.js";
3
+ import type { InstallServerTestModeOptions } from "./node.js";
4
+ import { withoutTestMode } from "./internal/server-context.js";
5
+ import { requestFromDraft } from "./internal/next-request.js";
6
+ import { createDraftControl } from "./internal/draft-handler.js";
7
+ import type { DraftHandlerOptions } from "./internal/draft-handler.js";
8
+
9
+ export type { DraftHandlerOptions } from "./internal/draft-handler.js";
10
+
11
+ /** Export this as POST from app/api/next-test-mode/route.ts. */
12
+ export const createDraftModeHandler = (options: DraftHandlerOptions = {}) => {
13
+ const handler = createDraftControl(
14
+ async () => ({ draft: await draftMode(), cookies: await cookies() }),
15
+ options,
16
+ );
17
+ return (request: Request) => withoutTestMode(() => handler(request));
18
+ };
19
+
20
+ export type NextTestModeOptions = Omit<
21
+ InstallServerTestModeOptions,
22
+ "getRequest"
23
+ >;
24
+
25
+ /** Call once from Next.js instrumentation.register in the Node runtime. */
26
+ export const setupNextTestMode = (options: NextTestModeOptions = {}) =>
27
+ installServerTestMode({
28
+ ...options,
29
+ getRequest: async () => {
30
+ try {
31
+ const draft = await draftMode();
32
+ if (!draft.isEnabled) return null;
33
+ return requestFromDraft(
34
+ draft,
35
+ options.cookieKey ?? options.storageKey ?? "test-mode.entries",
36
+ );
37
+ } catch (error) {
38
+ // Startup jobs have no request. Dynamic-rendering/control-flow errors
39
+ // must still reach Next.js; do not silently turn them into cached data.
40
+ if (
41
+ error instanceof Error &&
42
+ (/outside a request scope/.test(error.message) ||
43
+ /draftMode.*inside `generateStaticParams`/.test(error.message))
44
+ )
45
+ return null;
46
+ throw error;
47
+ }
48
+ },
49
+ });
package/src/node.ts ADDED
@@ -0,0 +1,213 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { isTestModeBypassed } from "./internal/server-context.js";
3
+ import type { IncomingMessage, ServerResponse } from "node:http";
4
+ import { createServerTestMode } from "./server.js";
5
+ import { createMockFetch } from "./fetch.js";
6
+ import type { TestModeOptions } from "./types.js";
7
+
8
+ type Handler = (request: IncomingMessage, response: ServerResponse) => unknown;
9
+ type Scope = { owner: object; active: boolean; fetch: typeof fetch };
10
+ const requests = new AsyncLocalStorage<Scope | undefined>();
11
+ const installations = new WeakMap<
12
+ typeof fetch,
13
+ { previous: typeof fetch; active: boolean }
14
+ >();
15
+
16
+ export type ServerRequestContext = Readonly<{
17
+ key: object;
18
+ cookieHeader: string | null;
19
+ }>;
20
+ export type InstallServerTestModeOptions = Omit<
21
+ WithTestModeOptions,
22
+ "enabled"
23
+ > &
24
+ Readonly<{
25
+ /** Framework-owned request identity and incoming cookie; null outside a request. */
26
+ getRequest: () =>
27
+ | ServerRequestContext
28
+ | null
29
+ | Promise<ServerRequestContext | null>;
30
+ enabled?: boolean | (() => boolean);
31
+ }>;
32
+
33
+ /** Install once for a framework that exposes its current request context. */
34
+ export const installServerTestMode = ({
35
+ getRequest,
36
+ enabled = () => ["development", "test"].includes(process.env.NODE_ENV ?? ""),
37
+ ssr = true,
38
+ allowedPaths,
39
+ ...options
40
+ }: InstallServerTestModeOptions) => {
41
+ if (enabled === false) return () => {};
42
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "fetch");
43
+ if (!descriptor?.configurable || !("value" in descriptor))
44
+ throw new TypeError(
45
+ "Automatic server test mode requires a configurable fetch value. Install it once before other fetch accessors.",
46
+ );
47
+ const bypass = new AsyncLocalStorage<boolean>();
48
+ const scopes = new WeakMap<
49
+ object,
50
+ ReturnType<typeof createServerTestMode>["runtime"]
51
+ >();
52
+ const proxies = new WeakMap<typeof fetch, typeof fetch>();
53
+ let active = true;
54
+ let transport = globalThis.fetch;
55
+ const wrap = (original: typeof fetch): typeof fetch => {
56
+ const existing = proxies.get(original);
57
+ if (existing) return existing;
58
+ const proxy = new Proxy(original, {
59
+ apply(target, receiver, args: Parameters<typeof fetch>) {
60
+ const forward = () =>
61
+ Reflect.apply(target, receiver, args) as ReturnType<typeof fetch>;
62
+ if (
63
+ !active ||
64
+ isTestModeBypassed() ||
65
+ bypass.getStore() ||
66
+ !(typeof enabled === "function" ? enabled() : enabled)
67
+ )
68
+ return forward();
69
+ return bypass.run(true, async () => {
70
+ const request = await getRequest();
71
+ if (!request) return forward();
72
+ const [input, init] = args;
73
+ if (
74
+ allowedPaths &&
75
+ !allowedPaths.includes(
76
+ new URL(input instanceof Request ? input.url : String(input))
77
+ .pathname,
78
+ )
79
+ )
80
+ return forward();
81
+ let runtime = scopes.get(request.key);
82
+ if (!runtime) {
83
+ runtime = createServerTestMode({
84
+ ...options,
85
+ enabled: true,
86
+ ssr,
87
+ cookieHeader: request.cookieHeader,
88
+ originalFetch: target.bind(receiver),
89
+ }).runtime;
90
+ scopes.set(request.key, runtime);
91
+ }
92
+ // The framework fetch may be replaced during startup/HMR. Wrap the
93
+ // current target, keeping our response changes outside its data cache.
94
+ return createMockFetch(runtime, {
95
+ cookieHeader: false,
96
+ originalFetch: target.bind(receiver),
97
+ })(input, init);
98
+ });
99
+ },
100
+ });
101
+ proxies.set(original, proxy);
102
+ proxies.set(proxy, proxy);
103
+ return proxy;
104
+ };
105
+ const get = () => wrap(transport);
106
+ const set = (next: typeof fetch) => {
107
+ if (typeof next !== "function")
108
+ throw new TypeError("fetch must be a function.");
109
+ transport = next;
110
+ };
111
+ Object.defineProperty(globalThis, "fetch", {
112
+ configurable: true,
113
+ enumerable: descriptor.enumerable ?? false,
114
+ get,
115
+ set,
116
+ });
117
+ return () => {
118
+ active = false;
119
+ if (Object.getOwnPropertyDescriptor(globalThis, "fetch")?.get === get)
120
+ Object.defineProperty(globalThis, "fetch", {
121
+ ...descriptor,
122
+ value: transport,
123
+ });
124
+ };
125
+ };
126
+
127
+ export type WithTestModeOptions = Omit<TestModeOptions, "enabled"> &
128
+ Readonly<{
129
+ enabled?: boolean | ((request: IncomingMessage) => boolean);
130
+ /** Accept browser JSON synchronization. Defaults to true for this request wrapper. */
131
+ ssr?: boolean;
132
+ /** Optional exact pathname allowlist, useful for public demos. */
133
+ allowedPaths?: readonly string[];
134
+ }>;
135
+
136
+ /** Wrap the server handler once. All ordinary global fetch calls in that request share its isolated state. */
137
+ export const withTestMode = <T extends Handler>(
138
+ handler: T,
139
+ {
140
+ enabled = () =>
141
+ ["development", "test"].includes(process.env.NODE_ENV ?? ""),
142
+ ssr = true,
143
+ allowedPaths,
144
+ ...options
145
+ }: WithTestModeOptions = {},
146
+ ): T & { dispose: () => void } => {
147
+ const owner = {};
148
+ const previous = globalThis.fetch;
149
+ const installation = { previous, active: true };
150
+ const replacement: typeof fetch = (input, init) => {
151
+ const scope = requests.getStore();
152
+ if (
153
+ !installation.active ||
154
+ isTestModeBypassed() ||
155
+ !scope?.active ||
156
+ scope.owner !== owner
157
+ )
158
+ return previous.call(globalThis, input, init);
159
+ if (allowedPaths) {
160
+ const url = input instanceof Request ? input.url : String(input);
161
+ if (!allowedPaths.includes(new URL(url).pathname))
162
+ return previous.call(globalThis, input, init);
163
+ }
164
+ // Handler-authored fetches and transport hooks must not re-enter the same mock.
165
+ return requests.run(undefined, () => scope.fetch(input, init));
166
+ };
167
+ if (enabled !== false) {
168
+ installations.set(replacement, installation);
169
+ globalThis.fetch = replacement;
170
+ }
171
+ const dispose = () => {
172
+ installation.active = false;
173
+ if (globalThis.fetch === replacement) {
174
+ let restore = previous;
175
+ let state = installations.get(restore);
176
+ while (state && !state.active) {
177
+ restore = state.previous;
178
+ state = installations.get(restore);
179
+ }
180
+ globalThis.fetch = restore;
181
+ }
182
+ };
183
+ const wrapped = function (
184
+ this: unknown,
185
+ request: IncomingMessage,
186
+ response: ServerResponse,
187
+ ) {
188
+ if (
189
+ !installation.active ||
190
+ !(typeof enabled === "function" ? enabled(request) : enabled)
191
+ )
192
+ return requests.run(undefined, () =>
193
+ handler.call(this, request, response),
194
+ );
195
+ const { runtime, fetch } = createServerTestMode({
196
+ ...options,
197
+ enabled: true,
198
+ ssr,
199
+ cookieHeader: request.headers.cookie ?? null,
200
+ originalFetch: previous.bind(globalThis),
201
+ });
202
+ const scope: Scope = { owner, active: true, fetch };
203
+ const end = () => {
204
+ scope.active = false;
205
+ };
206
+ response.once("finish", end);
207
+ response.once("close", end);
208
+ if (runtime.active().length || runtime.overrides().length)
209
+ response.setHeader("Cache-Control", "private, no-store");
210
+ return requests.run(scope, () => handler.call(this, request, response));
211
+ };
212
+ return Object.assign(wrapped, { dispose }) as T & { dispose: () => void };
213
+ };
package/src/server.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { createTestMode } from "./core.js";
2
+ import { createMockFetch } from "./fetch.js";
3
+ import type { TestModeOptions } from "./types.js";
4
+ import { readSSRState, ssrCookieKey } from "./internal/ssr-state.js";
5
+
6
+ export type ServerTestModeOptions = TestModeOptions &
7
+ Readonly<{
8
+ /** The incoming page/request cookie header. Pass null when absent. */
9
+ cookieHeader: string | null;
10
+ /** The server/framework fetch to wrap; its request arguments are preserved. */
11
+ originalFetch?: typeof fetch;
12
+ /** Accept JSON synchronized by setupTestMode({ ssr: true }). Disabled by default. */
13
+ ssr?: boolean;
14
+ }>;
15
+
16
+ /**
17
+ * Create once per incoming SSR/loader request, never at module scope.
18
+ * Only registered feature selections cross from the browser cookie. Counters,
19
+ * selections and server-side overrides belong to this new runtime instance.
20
+ * Does not install a global fetch or forward incoming cookies to an upstream API.
21
+ */
22
+ export const createServerTestMode = ({
23
+ cookieHeader,
24
+ originalFetch = globalThis.fetch.bind(globalThis),
25
+ ssr = false,
26
+ ...options
27
+ }: ServerTestModeOptions) => {
28
+ if (typeof window !== "undefined") {
29
+ throw new TypeError(
30
+ "createServerTestMode must run on the server, once per incoming request. Use createTestMode in the browser.",
31
+ );
32
+ }
33
+ const runtime = createTestMode(options);
34
+ // An absent incoming cookie must not fall back to any other selection source.
35
+ runtime.set(runtime.active(cookieHeader ?? ""));
36
+ if (ssr && runtime.isAvailable()) {
37
+ const state = readSSRState(cookieHeader ?? "", ssrCookieKey(runtime.cookieKey));
38
+ if (state) {
39
+ runtime.set(state.entries);
40
+ for (const item of state.overrides) {
41
+ if (item.mode === "mock") runtime.setMock(item.path, item.data, item);
42
+ else runtime.setPatch(item.path, item.data as Record<string, unknown>, item);
43
+ }
44
+ }
45
+ }
46
+ return {
47
+ runtime,
48
+ // Selection is already captured above. An upstream authentication Cookie
49
+ // header must neither change that selection nor suppress local overrides.
50
+ fetch: createMockFetch(runtime, { originalFetch, cookieHeader: false }),
51
+ };
52
+ };
package/src/setup.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { createTestMode } from "./core.js";
2
+ import { installMockFetch } from "./fetch.js";
3
+ import { installTestModeOverlay } from "./browser.js";
4
+ import { readSSRState, ssrCookieKey, writeSSRState } from "./internal/ssr-state.js";
5
+ import { createCleanup } from "./internal/lifecycle.js";
6
+ import type { TestModeOptions, TestModeOverlayOptions } from "./types.js";
7
+
8
+ export type SetupTestModeOptions = TestModeOptions & Readonly<{
9
+ /** Opt in to sharing JSON with the server and restoring it after navigation. */
10
+ ssr?: boolean;
11
+ /** SSR defaults to reloading the page after a change. Override for router refresh/refetch. */
12
+ refresh?: () => void;
13
+ overlay?: TestModeOverlayOptions;
14
+ }>;
15
+
16
+ /** Install once in the browser entry. Existing fetch calls and Console commands stay the same. */
17
+ export const setupTestMode = ({
18
+ ssr = false,
19
+ refresh,
20
+ overlay,
21
+ beforeChange,
22
+ ...options
23
+ }: SetupTestModeOptions = {}) => {
24
+ let syncing = false;
25
+ let stopped = false;
26
+ let cookieKey = "";
27
+ const runtime = createTestMode({
28
+ ...options,
29
+ beforeChange: state => {
30
+ beforeChange?.(state);
31
+ if (syncing) writeSSRState(cookieKey, state);
32
+ },
33
+ });
34
+ const cleanups: (() => void)[] = [];
35
+ let timer: ReturnType<typeof setTimeout> | undefined;
36
+ const stop = () => {
37
+ if (stopped) return;
38
+ stopped = true;
39
+ syncing = false;
40
+ clearTimeout(timer);
41
+ createCleanup(cleanups)();
42
+ };
43
+ if (!runtime.isAvailable()) return { runtime, stop };
44
+ if (typeof window === "undefined") throw new TypeError("setupTestMode runs in the browser. Use withTestMode on the server.");
45
+ cookieKey = ssrCookieKey(runtime.cookieKey);
46
+ if (ssr) {
47
+ const state = readSSRState(document.cookie, cookieKey);
48
+ if (state) {
49
+ runtime.set(state.entries);
50
+ for (const item of state.overrides) {
51
+ if (item.mode === "mock") runtime.setMock(item.path, item.data, item);
52
+ else runtime.setPatch(item.path, item.data as Record<string, unknown>, item);
53
+ }
54
+ }
55
+ // Test cookie availability during setup, before installing globals.
56
+ writeSSRState(cookieKey, { entries: runtime.active(), overrides: runtime.overrides() });
57
+ syncing = true;
58
+ }
59
+ try {
60
+ cleanups.push(installMockFetch(runtime));
61
+ cleanups.push(installTestModeOverlay(runtime, { datasetName: false, ...overlay }));
62
+ const update = refresh ?? (ssr ? () => location.reload() : undefined);
63
+ if (update) cleanups.push(runtime.subscribe(() => {
64
+ clearTimeout(timer);
65
+ timer = setTimeout(() => { if (!stopped) update(); }, 50);
66
+ }));
67
+ } catch (error) { stop(); throw error; }
68
+ return { runtime, stop };
69
+ };