@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.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +170 -0
- package/bin/test-mode.mjs +164 -0
- package/dist/browser.d.ts +7 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +455 -0
- package/dist/browser.js.map +1 -0
- package/dist/client.d.ts +14 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +92 -0
- package/dist/client.js.map +1 -0
- package/dist/core.d.ts +160 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +741 -0
- package/dist/core.js.map +1 -0
- package/dist/fetch.d.ts +16 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +212 -0
- package/dist/fetch.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/draft-handler.d.ts +30 -0
- package/dist/internal/draft-handler.d.ts.map +1 -0
- package/dist/internal/draft-handler.js +80 -0
- package/dist/internal/draft-handler.js.map +1 -0
- package/dist/internal/lifecycle.d.ts +7 -0
- package/dist/internal/lifecycle.d.ts.map +1 -0
- package/dist/internal/lifecycle.js +65 -0
- package/dist/internal/lifecycle.js.map +1 -0
- package/dist/internal/next-request.d.ts +11 -0
- package/dist/internal/next-request.d.ts.map +1 -0
- package/dist/internal/next-request.js +22 -0
- package/dist/internal/next-request.js.map +1 -0
- package/dist/internal/overrides.d.ts +25 -0
- package/dist/internal/overrides.d.ts.map +1 -0
- package/dist/internal/overrides.js +111 -0
- package/dist/internal/overrides.js.map +1 -0
- package/dist/internal/paths.d.ts +3 -0
- package/dist/internal/paths.d.ts.map +1 -0
- package/dist/internal/paths.js +22 -0
- package/dist/internal/paths.js.map +1 -0
- package/dist/internal/server-context.d.ts +4 -0
- package/dist/internal/server-context.d.ts.map +1 -0
- package/dist/internal/server-context.js +6 -0
- package/dist/internal/server-context.js.map +1 -0
- package/dist/internal/ssr-state.d.ts +8 -0
- package/dist/internal/ssr-state.d.ts.map +1 -0
- package/dist/internal/ssr-state.js +48 -0
- package/dist/internal/ssr-state.js.map +1 -0
- package/dist/internal/storage.d.ts +6 -0
- package/dist/internal/storage.d.ts.map +1 -0
- package/dist/internal/storage.js +70 -0
- package/dist/internal/storage.js.map +1 -0
- package/dist/internal/symbols.d.ts +3 -0
- package/dist/internal/symbols.d.ts.map +1 -0
- package/dist/internal/symbols.js +3 -0
- package/dist/internal/symbols.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +32 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +27 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +144 -0
- package/dist/node.js.map +1 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +36 -0
- package/dist/server.js.map +1 -0
- package/dist/setup.d.ts +14 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +66 -0
- package/dist/setup.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/architecture.md +116 -0
- package/docs/guide.md +171 -0
- package/docs/migration.md +26 -0
- package/docs/releasing.md +41 -0
- package/docs/server-rendering.md +136 -0
- package/docs/story-test-design.md +252 -0
- package/package.json +136 -0
- package/src/browser.ts +593 -0
- package/src/client.ts +114 -0
- package/src/core.ts +1161 -0
- package/src/fetch.ts +271 -0
- package/src/index.ts +5 -0
- package/src/internal/draft-handler.ts +113 -0
- package/src/internal/lifecycle.ts +81 -0
- package/src/internal/next-request.ts +31 -0
- package/src/internal/overrides.ts +141 -0
- package/src/internal/paths.ts +27 -0
- package/src/internal/server-context.ts +6 -0
- package/src/internal/ssr-state.ts +48 -0
- package/src/internal/storage.ts +75 -0
- package/src/internal/symbols.ts +2 -0
- package/src/next.ts +49 -0
- package/src/node.ts +213 -0
- package/src/server.ts +52 -0
- package/src/setup.ts +69 -0
- package/src/types.ts +240 -0
- package/templates/test-mode/README.md +30 -0
- package/templates/test-mode/config.ts +25 -0
- package/templates/test-mode/features/auth.ts +23 -0
- package/templates/test-mode/index.ts +11 -0
- package/templates/test-mode/install.ts +13 -0
- package/templates/test-mode/stories/auth.stories.ts +10 -0
package/src/browser.ts
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { createCleanup, installProperty } from "./internal/lifecycle.js";
|
|
2
|
+
import type {
|
|
3
|
+
StoryListInput,
|
|
4
|
+
TestModeSearchInput,
|
|
5
|
+
TestModeExtension,
|
|
6
|
+
ToggleExtensionOptions,
|
|
7
|
+
TestModeOverlayOptions,
|
|
8
|
+
TestModeConsoleOptions,
|
|
9
|
+
TestModeConsoleHelp,
|
|
10
|
+
} from "./types.js";
|
|
11
|
+
import type { TestMode } from "./core.js";
|
|
12
|
+
import { normalizePath, parseInputList } from "./internal/paths.js";
|
|
13
|
+
import { readBrowserStorage, writeBrowserStorage } from "./internal/storage.js";
|
|
14
|
+
|
|
15
|
+
export type {
|
|
16
|
+
TestModeConsoleOptions,
|
|
17
|
+
TestModeOverlayOptions,
|
|
18
|
+
TestModeExtension,
|
|
19
|
+
TestModeExtensionContext,
|
|
20
|
+
ToggleExtensionOptions,
|
|
21
|
+
} from "./types.js";
|
|
22
|
+
|
|
23
|
+
export const createToggleExtension = ({
|
|
24
|
+
aliases = [],
|
|
25
|
+
key,
|
|
26
|
+
label,
|
|
27
|
+
onDisable,
|
|
28
|
+
onEnable,
|
|
29
|
+
setup,
|
|
30
|
+
storageKey = `test-mode.extension.${key}`,
|
|
31
|
+
}: ToggleExtensionOptions): TestModeExtension => {
|
|
32
|
+
let activeInMemory = false;
|
|
33
|
+
let memoryOnly = false;
|
|
34
|
+
let sideEffectApplied = false;
|
|
35
|
+
const listeners = new Set<() => void>();
|
|
36
|
+
const isActive = () => {
|
|
37
|
+
const stored = readBrowserStorage(storageKey);
|
|
38
|
+
return memoryOnly || stored === undefined
|
|
39
|
+
? activeInMemory
|
|
40
|
+
: stored === "true";
|
|
41
|
+
};
|
|
42
|
+
const notify = () => {
|
|
43
|
+
for (const listener of listeners) {
|
|
44
|
+
listener();
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const applySideEffect = () => {
|
|
48
|
+
if (sideEffectApplied) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
onEnable?.();
|
|
53
|
+
sideEffectApplied = true;
|
|
54
|
+
};
|
|
55
|
+
const releaseSideEffect = () => {
|
|
56
|
+
if (!sideEffectApplied) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
onDisable?.();
|
|
61
|
+
sideEffectApplied = false;
|
|
62
|
+
};
|
|
63
|
+
const enable = () => {
|
|
64
|
+
activeInMemory = true;
|
|
65
|
+
memoryOnly = !writeBrowserStorage(storageKey, "true");
|
|
66
|
+
applySideEffect();
|
|
67
|
+
notify();
|
|
68
|
+
};
|
|
69
|
+
const disable = () => {
|
|
70
|
+
activeInMemory = false;
|
|
71
|
+
memoryOnly = !writeBrowserStorage(storageKey, null);
|
|
72
|
+
releaseSideEffect();
|
|
73
|
+
notify();
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
aliases,
|
|
78
|
+
disable,
|
|
79
|
+
enable,
|
|
80
|
+
install: (context) => {
|
|
81
|
+
const teardown = setup?.(context);
|
|
82
|
+
|
|
83
|
+
if (isActive()) {
|
|
84
|
+
applySideEffect();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return () => {
|
|
88
|
+
releaseSideEffect();
|
|
89
|
+
teardown?.();
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
isActive,
|
|
93
|
+
key,
|
|
94
|
+
label,
|
|
95
|
+
subscribe: (listener) => {
|
|
96
|
+
listeners.add(listener);
|
|
97
|
+
|
|
98
|
+
return () => {
|
|
99
|
+
listeners.delete(listener);
|
|
100
|
+
};
|
|
101
|
+
},
|
|
102
|
+
toggle: () => {
|
|
103
|
+
if (isActive()) {
|
|
104
|
+
disable();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
enable();
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const extensionMatches = (extension: TestModeExtension, input: string) => {
|
|
114
|
+
const trimmed = input.trim();
|
|
115
|
+
|
|
116
|
+
return (
|
|
117
|
+
trimmed === extension.key ||
|
|
118
|
+
trimmed === extension.label ||
|
|
119
|
+
(extension.aliases ?? []).includes(trimmed)
|
|
120
|
+
);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const findExtension = (
|
|
124
|
+
extensions: readonly TestModeExtension[],
|
|
125
|
+
input: string,
|
|
126
|
+
) => extensions.find((extension) => extensionMatches(extension, input)) ?? null;
|
|
127
|
+
|
|
128
|
+
const activeExtensionLabels = (extensions: readonly TestModeExtension[]) =>
|
|
129
|
+
extensions
|
|
130
|
+
.filter((extension) => extension.isActive())
|
|
131
|
+
.map((extension) => extension.label);
|
|
132
|
+
|
|
133
|
+
const installExtensions = (
|
|
134
|
+
testMode: TestMode,
|
|
135
|
+
extensions: readonly TestModeExtension[],
|
|
136
|
+
refresh: () => void,
|
|
137
|
+
) => {
|
|
138
|
+
const cleanups: (() => void)[] = [];
|
|
139
|
+
const cleanup = createCleanup(cleanups);
|
|
140
|
+
try {
|
|
141
|
+
for (const extension of extensions) {
|
|
142
|
+
cleanups.push(extension.subscribe?.(refresh) ?? (() => {}));
|
|
143
|
+
cleanups.push(extension.install?.({ refresh, testMode }) ?? (() => {}));
|
|
144
|
+
}
|
|
145
|
+
} catch (error) {
|
|
146
|
+
try {
|
|
147
|
+
cleanup();
|
|
148
|
+
} catch (cleanupError) {
|
|
149
|
+
throw new AggregateError(
|
|
150
|
+
[error, cleanupError],
|
|
151
|
+
"Extension installation failed",
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
return cleanup;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
export const installConsole = (
|
|
160
|
+
testMode: TestMode,
|
|
161
|
+
{
|
|
162
|
+
extensions = [],
|
|
163
|
+
globalName = "test",
|
|
164
|
+
installExtensions: shouldInstallExtensions = true,
|
|
165
|
+
namespace = "__testMode",
|
|
166
|
+
}: TestModeConsoleOptions = {},
|
|
167
|
+
) => {
|
|
168
|
+
if (typeof window === "undefined" || !testMode.isAvailable()) {
|
|
169
|
+
return () => {};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const target = window as unknown as Record<string, unknown>;
|
|
173
|
+
const active = () => [
|
|
174
|
+
...testMode.active(),
|
|
175
|
+
...testMode
|
|
176
|
+
.overrides()
|
|
177
|
+
.map((item) => `${item.mode.toUpperCase()} ${item.method} ${item.path}`),
|
|
178
|
+
...activeExtensionLabels(extensions),
|
|
179
|
+
];
|
|
180
|
+
const add = (path: string) => {
|
|
181
|
+
const extension = findExtension(extensions, path);
|
|
182
|
+
|
|
183
|
+
if (extension) {
|
|
184
|
+
extension.enable();
|
|
185
|
+
return active();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return testMode.add(path);
|
|
189
|
+
};
|
|
190
|
+
const remove = (path: string) => {
|
|
191
|
+
const extension = findExtension(extensions, path);
|
|
192
|
+
|
|
193
|
+
if (extension) {
|
|
194
|
+
extension.disable();
|
|
195
|
+
return active();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return testMode.remove(path);
|
|
199
|
+
};
|
|
200
|
+
const toggle = (path: string) => {
|
|
201
|
+
const extension = findExtension(extensions, path);
|
|
202
|
+
|
|
203
|
+
if (extension) {
|
|
204
|
+
extension.toggle?.();
|
|
205
|
+
|
|
206
|
+
if (!extension.toggle) {
|
|
207
|
+
if (extension.isActive()) {
|
|
208
|
+
extension.disable();
|
|
209
|
+
} else {
|
|
210
|
+
extension.enable();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return active();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return testMode.toggle(path);
|
|
218
|
+
};
|
|
219
|
+
const set = (paths: readonly string[] | string) => {
|
|
220
|
+
const inputs = parseInputList(paths);
|
|
221
|
+
const mockInputs = inputs.filter(
|
|
222
|
+
(input) => !findExtension(extensions, input),
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
for (const extension of extensions) {
|
|
226
|
+
if (inputs.some((input) => extensionMatches(extension, input))) {
|
|
227
|
+
extension.enable();
|
|
228
|
+
} else {
|
|
229
|
+
extension.disable();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
testMode.set(mockInputs);
|
|
234
|
+
|
|
235
|
+
return active();
|
|
236
|
+
};
|
|
237
|
+
const clear = () => {
|
|
238
|
+
for (const extension of extensions) {
|
|
239
|
+
extension.disable();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return testMode.clear();
|
|
243
|
+
};
|
|
244
|
+
const list = () => {
|
|
245
|
+
return testMode.list();
|
|
246
|
+
};
|
|
247
|
+
const feat = {
|
|
248
|
+
add,
|
|
249
|
+
list,
|
|
250
|
+
remove,
|
|
251
|
+
set,
|
|
252
|
+
toggle,
|
|
253
|
+
};
|
|
254
|
+
const findStoryCatalogItem = (storyKey: string) =>
|
|
255
|
+
testMode.stories({ storyKey })[0] ?? null;
|
|
256
|
+
const setStories = (storyKeys: readonly string[] | string) => {
|
|
257
|
+
const keys = parseInputList(storyKeys);
|
|
258
|
+
const entries = keys.flatMap(
|
|
259
|
+
(key) => findStoryCatalogItem(key)?.entries ?? [],
|
|
260
|
+
);
|
|
261
|
+
return keys.length > 0 && entries.length === 0
|
|
262
|
+
? testMode.active()
|
|
263
|
+
: testMode.set(entries);
|
|
264
|
+
};
|
|
265
|
+
const removeStory = (storyKey: string) => {
|
|
266
|
+
const story = findStoryCatalogItem(storyKey);
|
|
267
|
+
|
|
268
|
+
if (!story) {
|
|
269
|
+
return testMode.active();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const storyEntries = new Set(story.entries);
|
|
273
|
+
|
|
274
|
+
return testMode.set(
|
|
275
|
+
testMode.active().filter((item) => !storyEntries.has(item)),
|
|
276
|
+
);
|
|
277
|
+
};
|
|
278
|
+
const toggleStory = (storyKey: string) => {
|
|
279
|
+
const story = findStoryCatalogItem(storyKey);
|
|
280
|
+
|
|
281
|
+
if (!story) {
|
|
282
|
+
return testMode.active();
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return story.active ? removeStory(storyKey) : testMode.addStory(storyKey);
|
|
286
|
+
};
|
|
287
|
+
const apply = (input: string) =>
|
|
288
|
+
testMode.hasStory(input) ? setStories(input) : toggle(input);
|
|
289
|
+
const storyCommand = Object.assign(
|
|
290
|
+
(storyKey: string) => setStories(storyKey),
|
|
291
|
+
{
|
|
292
|
+
add: (storyKey: string) => testMode.addStory(storyKey),
|
|
293
|
+
list: (input?: StoryListInput) => testMode.stories(input),
|
|
294
|
+
remove: removeStory,
|
|
295
|
+
set: setStories,
|
|
296
|
+
toggle: toggleStory,
|
|
297
|
+
},
|
|
298
|
+
);
|
|
299
|
+
const help = (): TestModeConsoleHelp => ({
|
|
300
|
+
commands: {
|
|
301
|
+
"test()": "Show this help.",
|
|
302
|
+
"test('story.key')":
|
|
303
|
+
"Apply a story when the key exists; otherwise toggle a feature entry.",
|
|
304
|
+
"test.clear()":
|
|
305
|
+
"Clear response overrides, active entries and extensions.",
|
|
306
|
+
"test.mock('/api/cart', { items: [], total: 0 })":
|
|
307
|
+
"Immediately replace the GET response with your JSON value.",
|
|
308
|
+
"test.patch('/api/cart', { total: 9.99 })":
|
|
309
|
+
"Shallow-merge fields into the real GET response.",
|
|
310
|
+
"test.overrides()":
|
|
311
|
+
"Inspect response overrides (memory by default; shared when SSR sync is enabled).",
|
|
312
|
+
"test.reset('/api/cart')":
|
|
313
|
+
"Remove this path's overrides and restore the selected scenario or real API.",
|
|
314
|
+
"test.feat.add('path:caseKey')": "Enable one feature entry.",
|
|
315
|
+
"test.feat.list()": "List feature mock/patch API entries.",
|
|
316
|
+
"test.feat.remove('path:caseKey')": "Disable one feature entry.",
|
|
317
|
+
"test.feat.set(['path:caseKey'])":
|
|
318
|
+
"Replace active feature entries and extensions.",
|
|
319
|
+
"test.feat.toggle('path:caseKey')": "Toggle one feature entry.",
|
|
320
|
+
"test.search('query')": "Search feature and story catalogs together.",
|
|
321
|
+
"test.story('story.key')":
|
|
322
|
+
"Replace active entries with one story. Alias of test.story.set('story.key').",
|
|
323
|
+
"test.story.add('story.key')":
|
|
324
|
+
"Add a story without clearing currently active entries.",
|
|
325
|
+
"test.story.list()": "List story scenarios.",
|
|
326
|
+
"test.story.list('/page')": "List story scenarios available for a page.",
|
|
327
|
+
"test.story.remove('story.key')":
|
|
328
|
+
"Remove one story's entries from the active entries.",
|
|
329
|
+
"test.story.set(['story.key'])":
|
|
330
|
+
"Replace active entries with one or more stories.",
|
|
331
|
+
"test.story.toggle('story.key')": "Toggle one story.",
|
|
332
|
+
},
|
|
333
|
+
examples: [
|
|
334
|
+
"test()",
|
|
335
|
+
"test.patch('/api/cart', { total: 9.99 })",
|
|
336
|
+
"test.mock('/api/cart', { message: 'Try again' }, { status: 503 })",
|
|
337
|
+
"test.story.list('/cart')",
|
|
338
|
+
"test.search('cart')",
|
|
339
|
+
"test.story('cart.discount-flow')",
|
|
340
|
+
"test.story.add('main.event-popup')",
|
|
341
|
+
"test.feat.add('/api/session/signin:locked')",
|
|
342
|
+
"test.active()",
|
|
343
|
+
"test.clear()",
|
|
344
|
+
],
|
|
345
|
+
summary:
|
|
346
|
+
"Override API responses with mock/patch, or select registered scenarios with story. Browser setup with ssr: true shares values with a connected server and refreshes the page. Default values stay in memory. Use clear to reset.",
|
|
347
|
+
});
|
|
348
|
+
const run = (input?: string) =>
|
|
349
|
+
typeof input === "string" && input.trim() ? apply(input) : help();
|
|
350
|
+
const api = Object.assign(run, {
|
|
351
|
+
active,
|
|
352
|
+
clear,
|
|
353
|
+
feat,
|
|
354
|
+
help,
|
|
355
|
+
mock: testMode.setMock,
|
|
356
|
+
patch: testMode.setPatch,
|
|
357
|
+
overrides: testMode.overrides,
|
|
358
|
+
reset: testMode.resetOverrides,
|
|
359
|
+
isEnabled: () => active().length > 0,
|
|
360
|
+
search: (input?: TestModeSearchInput) => testMode.search(input),
|
|
361
|
+
story: storyCommand,
|
|
362
|
+
});
|
|
363
|
+
const cleanups: (() => void)[] = [];
|
|
364
|
+
const cleanup = createCleanup(cleanups);
|
|
365
|
+
try {
|
|
366
|
+
cleanups.push(
|
|
367
|
+
installProperty(target, namespace, {
|
|
368
|
+
configurable: true,
|
|
369
|
+
enumerable: true,
|
|
370
|
+
writable: true,
|
|
371
|
+
value: api,
|
|
372
|
+
}),
|
|
373
|
+
);
|
|
374
|
+
cleanups.push(
|
|
375
|
+
installProperty(target, globalName, {
|
|
376
|
+
configurable: true,
|
|
377
|
+
get: () => api,
|
|
378
|
+
set: (value: unknown) => {
|
|
379
|
+
if (typeof value === "string") {
|
|
380
|
+
if (testMode.hasStory(value)) setStories(value);
|
|
381
|
+
else testMode.set(value);
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
}),
|
|
385
|
+
);
|
|
386
|
+
if (shouldInstallExtensions)
|
|
387
|
+
cleanups.push(installExtensions(testMode, extensions, () => undefined));
|
|
388
|
+
} catch (error) {
|
|
389
|
+
try {
|
|
390
|
+
cleanup();
|
|
391
|
+
} catch (cleanupError) {
|
|
392
|
+
throw new AggregateError(
|
|
393
|
+
[error, cleanupError],
|
|
394
|
+
"Console installation failed",
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
return cleanup;
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
const setStyles = (element: HTMLElement, styles: Record<string, string>) => {
|
|
403
|
+
for (const [key, value] of Object.entries(styles)) {
|
|
404
|
+
element.style.setProperty(key, value);
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const createOverlay = (
|
|
409
|
+
documentRef: Document,
|
|
410
|
+
watermarkText: string,
|
|
411
|
+
zIndex: number,
|
|
412
|
+
) => {
|
|
413
|
+
const container = documentRef.createElement("div");
|
|
414
|
+
const viewport = documentRef.createElement("div");
|
|
415
|
+
const rail = documentRef.createElement("div");
|
|
416
|
+
|
|
417
|
+
container.setAttribute("aria-hidden", "true");
|
|
418
|
+
setStyles(container, {
|
|
419
|
+
inset: "0",
|
|
420
|
+
"pointer-events": "none",
|
|
421
|
+
position: "fixed",
|
|
422
|
+
"user-select": "none",
|
|
423
|
+
"z-index": String(zIndex),
|
|
424
|
+
});
|
|
425
|
+
setStyles(viewport, {
|
|
426
|
+
inset: "0",
|
|
427
|
+
opacity: "0.08",
|
|
428
|
+
overflow: "hidden",
|
|
429
|
+
position: "absolute",
|
|
430
|
+
});
|
|
431
|
+
setStyles(rail, {
|
|
432
|
+
color: "#dc2626",
|
|
433
|
+
display: "flex",
|
|
434
|
+
"flex-wrap": "wrap",
|
|
435
|
+
gap: "32px 48px",
|
|
436
|
+
"justify-content": "center",
|
|
437
|
+
left: "-64px",
|
|
438
|
+
position: "absolute",
|
|
439
|
+
top: "50%",
|
|
440
|
+
transform: "translateY(-50%) rotate(-24deg)",
|
|
441
|
+
width: "140vw",
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
for (let index = 0; index < 24; index += 1) {
|
|
445
|
+
const item = documentRef.createElement("span");
|
|
446
|
+
|
|
447
|
+
item.textContent = watermarkText;
|
|
448
|
+
setStyles(item, {
|
|
449
|
+
"font-size": "28px",
|
|
450
|
+
"font-weight": "900",
|
|
451
|
+
"letter-spacing": "0",
|
|
452
|
+
"line-height": "1",
|
|
453
|
+
"white-space": "nowrap",
|
|
454
|
+
});
|
|
455
|
+
rail.appendChild(item);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
viewport.appendChild(rail);
|
|
459
|
+
container.appendChild(viewport);
|
|
460
|
+
|
|
461
|
+
return container;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
export const installTestModeOverlay = (
|
|
465
|
+
testMode: TestMode,
|
|
466
|
+
{
|
|
467
|
+
datasetName = "testMode",
|
|
468
|
+
document: documentRef = typeof document === "undefined"
|
|
469
|
+
? undefined
|
|
470
|
+
: document,
|
|
471
|
+
extensions = [],
|
|
472
|
+
globalName = "test",
|
|
473
|
+
installConsole: shouldInstallConsole = true,
|
|
474
|
+
namespace = "__testMode",
|
|
475
|
+
watermarkText = "TEST MODE",
|
|
476
|
+
zIndex = 2147483647,
|
|
477
|
+
}: TestModeOverlayOptions = {},
|
|
478
|
+
) => {
|
|
479
|
+
if (!documentRef || !testMode.isAvailable()) {
|
|
480
|
+
return () => {};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const overlay = createOverlay(documentRef, watermarkText, zIndex);
|
|
484
|
+
const windowRef = documentRef.defaultView;
|
|
485
|
+
let installed = true;
|
|
486
|
+
let timer: number | undefined;
|
|
487
|
+
const markers = new Map<HTMLElement, () => void>();
|
|
488
|
+
const clearMarkers = () => {
|
|
489
|
+
const cleanup = createCleanup([...markers.values()]);
|
|
490
|
+
markers.clear();
|
|
491
|
+
cleanup();
|
|
492
|
+
};
|
|
493
|
+
const cleanups: (() => void)[] = [
|
|
494
|
+
() => {
|
|
495
|
+
if (timer !== undefined) windowRef?.clearTimeout(timer);
|
|
496
|
+
overlay.remove();
|
|
497
|
+
clearMarkers();
|
|
498
|
+
},
|
|
499
|
+
];
|
|
500
|
+
const cleanup = createCleanup(cleanups);
|
|
501
|
+
const getCurrentPage = () =>
|
|
502
|
+
normalizePath(
|
|
503
|
+
documentRef.location?.pathname ??
|
|
504
|
+
(typeof window === "undefined" ? "/" : window.location.pathname),
|
|
505
|
+
);
|
|
506
|
+
const sync = () => {
|
|
507
|
+
if (!installed) return;
|
|
508
|
+
const visible =
|
|
509
|
+
testMode.isAvailable() &&
|
|
510
|
+
(testMode.isActiveForPage(getCurrentPage()) ||
|
|
511
|
+
extensions.some((extension) => extension.isActive()));
|
|
512
|
+
if (visible) {
|
|
513
|
+
for (const element of [documentRef.documentElement, documentRef.body]) {
|
|
514
|
+
if (datasetName !== false && element && !markers.has(element)) {
|
|
515
|
+
markers.set(
|
|
516
|
+
element,
|
|
517
|
+
installProperty(element.dataset, datasetName, {
|
|
518
|
+
configurable: true,
|
|
519
|
+
enumerable: true,
|
|
520
|
+
writable: true,
|
|
521
|
+
value: "true",
|
|
522
|
+
}),
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (!overlay.parentElement)
|
|
527
|
+
(documentRef.body ?? documentRef.documentElement).appendChild(overlay);
|
|
528
|
+
} else {
|
|
529
|
+
overlay.remove();
|
|
530
|
+
clearMarkers();
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
const scheduleSync = () => {
|
|
534
|
+
if (!installed) return;
|
|
535
|
+
if (timer !== undefined) windowRef?.clearTimeout(timer);
|
|
536
|
+
timer = windowRef?.setTimeout(sync, 0);
|
|
537
|
+
};
|
|
538
|
+
try {
|
|
539
|
+
if (shouldInstallConsole)
|
|
540
|
+
cleanups.push(
|
|
541
|
+
installConsole(testMode, {
|
|
542
|
+
extensions,
|
|
543
|
+
globalName,
|
|
544
|
+
installExtensions: false,
|
|
545
|
+
namespace,
|
|
546
|
+
}),
|
|
547
|
+
);
|
|
548
|
+
cleanups.push(installExtensions(testMode, extensions, sync));
|
|
549
|
+
cleanups.push(testMode.subscribe(sync));
|
|
550
|
+
if (windowRef) {
|
|
551
|
+
for (const eventName of ["hashchange", "popstate"]) {
|
|
552
|
+
windowRef.addEventListener(eventName, scheduleSync);
|
|
553
|
+
cleanups.push(() =>
|
|
554
|
+
windowRef.removeEventListener(eventName, scheduleSync),
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
for (const method of ["pushState", "replaceState"] as const) {
|
|
558
|
+
const original = windowRef.history[method];
|
|
559
|
+
cleanups.push(
|
|
560
|
+
installProperty(windowRef.history, method, {
|
|
561
|
+
configurable: true,
|
|
562
|
+
enumerable: true,
|
|
563
|
+
writable: true,
|
|
564
|
+
value: function (
|
|
565
|
+
this: History,
|
|
566
|
+
...args: Parameters<History[typeof method]>
|
|
567
|
+
) {
|
|
568
|
+
const result = original.apply(this, args);
|
|
569
|
+
scheduleSync();
|
|
570
|
+
return result;
|
|
571
|
+
},
|
|
572
|
+
}),
|
|
573
|
+
);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
sync();
|
|
577
|
+
} catch (error) {
|
|
578
|
+
installed = false;
|
|
579
|
+
try {
|
|
580
|
+
cleanup();
|
|
581
|
+
} catch (cleanupError) {
|
|
582
|
+
throw new AggregateError(
|
|
583
|
+
[error, cleanupError],
|
|
584
|
+
"Overlay installation failed",
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
589
|
+
return () => {
|
|
590
|
+
installed = false;
|
|
591
|
+
cleanup();
|
|
592
|
+
};
|
|
593
|
+
};
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { setupTestMode } from "./setup.js";
|
|
2
|
+
import type { SetupTestModeOptions } from "./setup.js";
|
|
3
|
+
|
|
4
|
+
export type NextTestModeClientOptions = Omit<
|
|
5
|
+
SetupTestModeOptions,
|
|
6
|
+
"ssr" | "refresh"
|
|
7
|
+
> &
|
|
8
|
+
Readonly<{
|
|
9
|
+
draftEndpoint?: string;
|
|
10
|
+
refresh?: () => void | Promise<void>;
|
|
11
|
+
onError?: (error: Error) => void;
|
|
12
|
+
}>;
|
|
13
|
+
|
|
14
|
+
/** One browser entry connects Console, fetch, JSON handoff and Next Draft Mode. */
|
|
15
|
+
export const setupNextTestModeClient = ({
|
|
16
|
+
draftEndpoint = "/api/next-test-mode",
|
|
17
|
+
refresh = () => location.reload(),
|
|
18
|
+
onError = (error) => {
|
|
19
|
+
console.error("[next-test-mode]", error.message);
|
|
20
|
+
window.dispatchEvent(
|
|
21
|
+
new CustomEvent("next-test-mode:error", { detail: error.message }),
|
|
22
|
+
);
|
|
23
|
+
},
|
|
24
|
+
...options
|
|
25
|
+
}: NextTestModeClientOptions = {}) => {
|
|
26
|
+
let stopped = false;
|
|
27
|
+
let pending: Promise<void> | undefined;
|
|
28
|
+
let dirty = false;
|
|
29
|
+
let lastSynced: string | undefined;
|
|
30
|
+
const abort = new AbortController();
|
|
31
|
+
const transport = globalThis.fetch.bind(globalThis);
|
|
32
|
+
const installation = setupTestMode({
|
|
33
|
+
...options,
|
|
34
|
+
ssr: true,
|
|
35
|
+
refresh: () => {
|
|
36
|
+
if (snapshot() !== lastSynced) {
|
|
37
|
+
dirty = true;
|
|
38
|
+
void sync().catch(report);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
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 () => {
|
|
56
|
+
const endpoint = new URL(draftEndpoint, location.href);
|
|
57
|
+
if (endpoint.origin !== location.origin)
|
|
58
|
+
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
|
+
};
|
|
104
|
+
const ready = sync();
|
|
105
|
+
void ready.catch(report);
|
|
106
|
+
const stop = () => {
|
|
107
|
+
if (!stopped) {
|
|
108
|
+
stopped = true;
|
|
109
|
+
abort.abort();
|
|
110
|
+
installation.stop();
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
return { runtime, ready, sync, stop };
|
|
114
|
+
};
|