@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
package/dist/core.js ADDED
@@ -0,0 +1,741 @@
1
+ import { MOCK_RESULT, MOCK_PASS_THROUGH } from "./internal/symbols.js";
2
+ import { normalizePath, parseInputList } from "./internal/paths.js";
3
+ import { parseStoredPaths, readCookieValue, writeCookie, readBrowserStorage, writeBrowserStorage, } from "./internal/storage.js";
4
+ import { ResponseOverrides } from "./internal/overrides.js";
5
+ export { normalizePath } from "./internal/paths.js";
6
+ const DEFAULT_STORAGE_KEY = "test-mode.entries";
7
+ const DEFAULT_CHANGE_EVENT = "test-mode:change";
8
+ const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
9
+ const readNodeEnv = () => globalThis
10
+ .process?.env?.NODE_ENV;
11
+ const defaultEnabled = () => ["development", "test"].includes(readNodeEnv() ?? "");
12
+ const createPathCandidates = (path) => {
13
+ const normalizedPath = normalizePath(path);
14
+ if (!normalizedPath) {
15
+ return [];
16
+ }
17
+ const withoutApiPrefix = normalizedPath.replace(/^\/api(?=\/)/, "");
18
+ return Array.from(new Set([normalizedPath, withoutApiPrefix, `/api${withoutApiPrefix}`]));
19
+ };
20
+ const serializeEntry = (path, caseKey) => {
21
+ const normalizedPath = normalizePath(path);
22
+ return caseKey
23
+ ? `${normalizedPath}:${encodeURIComponent(caseKey)}`
24
+ : normalizedPath;
25
+ };
26
+ export const entry = serializeEntry;
27
+ const parseEntry = (value) => {
28
+ const normalizedValue = normalizePath(value);
29
+ if (!normalizedValue) {
30
+ return null;
31
+ }
32
+ const separatorIndex = normalizedValue.lastIndexOf(":");
33
+ if (separatorIndex <= 0) {
34
+ return {
35
+ path: normalizedValue,
36
+ serialized: normalizedValue,
37
+ };
38
+ }
39
+ const path = normalizedValue.slice(0, separatorIndex);
40
+ let caseKey;
41
+ try {
42
+ caseKey = decodeURIComponent(normalizedValue.slice(separatorIndex + 1).trim());
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if (!path || !caseKey) {
48
+ return {
49
+ path: normalizedValue,
50
+ serialized: normalizedValue,
51
+ };
52
+ }
53
+ return {
54
+ caseKey,
55
+ path,
56
+ serialized: serializeEntry(path, caseKey),
57
+ };
58
+ };
59
+ const isSamePath = (left, right) => {
60
+ const leftCandidates = createPathCandidates(left);
61
+ const rightCandidates = createPathCandidates(right);
62
+ return leftCandidates.some((candidate) => rightCandidates.includes(candidate));
63
+ };
64
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
65
+ const routePatternToRegExp = (pattern) => new RegExp(`^${normalizePath(pattern)
66
+ .split("/")
67
+ .map((segment) => {
68
+ if (segment === "*") {
69
+ return ".*";
70
+ }
71
+ if (segment.startsWith(":")) {
72
+ return "[^/]+";
73
+ }
74
+ return escapeRegExp(segment).replace(/\\\*/g, ".*");
75
+ })
76
+ .join("/")}$`);
77
+ const doesPathMatch = (pattern, path) => {
78
+ if (!pattern.includes(":") && !pattern.includes("*")) {
79
+ return isSamePath(pattern, path);
80
+ }
81
+ const matcher = routePatternToRegExp(pattern);
82
+ return createPathCandidates(path).some((candidate) => matcher.test(candidate));
83
+ };
84
+ const normalizeMethods = (method) => {
85
+ if (!method) {
86
+ return undefined;
87
+ }
88
+ const methods = (Array.isArray(method) ? method : [method])
89
+ .map((item) => item.trim().toUpperCase())
90
+ .filter(Boolean);
91
+ return methods.length > 0 ? methods : undefined;
92
+ };
93
+ const methodsOverlap = (left, right) => {
94
+ if (!left || !right) {
95
+ return true;
96
+ }
97
+ return left.some((method) => right.includes(method));
98
+ };
99
+ const isMockHttpResult = (value) => typeof value === "object" &&
100
+ value !== null &&
101
+ value[MOCK_RESULT] === true;
102
+ const isMockPassThrough = (value) => typeof value === "object" &&
103
+ value !== null &&
104
+ value[MOCK_PASS_THROUGH] === true;
105
+ export const httpResult = (result) => ({
106
+ ...result,
107
+ [MOCK_RESULT]: true,
108
+ });
109
+ export const passThrough = () => ({
110
+ [MOCK_PASS_THROUGH]: true,
111
+ });
112
+ export const defineMock = (path, handler, options = {}) => ({
113
+ ...options,
114
+ handler,
115
+ path: normalizePath(path),
116
+ });
117
+ export const definePatch = (path, handler, options = {}) => ({
118
+ ...options,
119
+ handler,
120
+ path: normalizePath(path),
121
+ });
122
+ export const defineStory = (story) => ({
123
+ description: story.description,
124
+ entries: story.entries
125
+ .map((item) => parseEntry(item)?.serialized ?? "")
126
+ .filter(Boolean),
127
+ key: story.key,
128
+ pages: story.pages?.map(normalizePath).filter(Boolean) ?? [],
129
+ title: story.title,
130
+ });
131
+ const normalizeDefinition = (definition, mode) => {
132
+ const method = normalizeMethods(definition.method);
133
+ const normalized = {
134
+ handler: definition.handler,
135
+ key: serializeEntry(definition.path, definition.caseKey),
136
+ mode,
137
+ pages: definition.pages?.map(normalizePath).filter(Boolean) ?? [],
138
+ path: normalizePath(definition.path),
139
+ };
140
+ if (definition.caseKey) {
141
+ normalized.caseKey = definition.caseKey;
142
+ }
143
+ if (definition.description) {
144
+ normalized.description = definition.description;
145
+ }
146
+ if (definition.match) {
147
+ normalized.match = definition.match;
148
+ }
149
+ if (method) {
150
+ normalized.method = method;
151
+ }
152
+ return normalized;
153
+ };
154
+ const normalizeStoryQuery = (query) => query?.trim().toLocaleLowerCase() ?? "";
155
+ const normalizeStoryListOptions = (input) => typeof input === "string" ? { page: input } : input;
156
+ const doesPageMatch = (page, pages) => {
157
+ const normalizedPage = normalizePath(page ?? "");
158
+ if (!normalizedPage) {
159
+ return true;
160
+ }
161
+ return pages.some((candidate) => {
162
+ const normalizedCandidate = normalizePath(candidate);
163
+ return (normalizedCandidate === normalizedPage ||
164
+ (normalizedCandidate !== "/" &&
165
+ normalizedPage.startsWith(`${normalizedCandidate}/`)));
166
+ });
167
+ };
168
+ const doesStoryQueryMatch = (query, story) => {
169
+ if (!query) {
170
+ return true;
171
+ }
172
+ return [
173
+ story.description,
174
+ story.key,
175
+ story.title,
176
+ ...story.entries,
177
+ ...story.pages,
178
+ ].some((value) => value.toLocaleLowerCase().includes(query));
179
+ };
180
+ const normalizeSearchOptions = (input) => typeof input === "string" ? { query: input } : input;
181
+ const doesFeatureQueryMatch = (query, feature) => {
182
+ if (!query) {
183
+ return true;
184
+ }
185
+ return [
186
+ feature.caseKey,
187
+ feature.description,
188
+ feature.key,
189
+ feature.mode,
190
+ feature.path,
191
+ ...feature.pages,
192
+ ]
193
+ .filter((value) => typeof value === "string")
194
+ .some((value) => value.toLocaleLowerCase().includes(query));
195
+ };
196
+ export class TestMode {
197
+ cookieKey;
198
+ eventName;
199
+ storageKey;
200
+ enabled;
201
+ beforeChange;
202
+ logger;
203
+ definitions;
204
+ storiesCatalog;
205
+ memoryPaths = [];
206
+ responseOverrides = new ResponseOverrides();
207
+ listeners = new Set();
208
+ requestCounts = new Map();
209
+ dispatchingChange = false;
210
+ memoryOnly = false;
211
+ constructor({ beforeChange, cookieKey, definitions = [], enabled = defaultEnabled, eventName = DEFAULT_CHANGE_EVENT, logger, patchDefinitions = [], stories = [], storageKey = DEFAULT_STORAGE_KEY, } = {}) {
212
+ this.cookieKey = cookieKey ?? storageKey;
213
+ this.beforeChange = beforeChange;
214
+ this.enabled = enabled;
215
+ this.eventName = eventName;
216
+ this.logger = logger;
217
+ this.storageKey = storageKey;
218
+ this.definitions = [
219
+ ...definitions.map((definition) => normalizeDefinition(definition, "mock")),
220
+ ...patchDefinitions.map((definition) => normalizeDefinition(definition, "patch")),
221
+ ];
222
+ this.storiesCatalog = stories.map(defineStory);
223
+ this.assertStoriesAreValid();
224
+ this.canonicalizeStories();
225
+ }
226
+ isAvailable = () => typeof this.enabled === "function" ? this.enabled() : this.enabled;
227
+ register = (definitions = [], patchDefinitions = [], stories = []) => {
228
+ const previousDefinitions = this.definitions;
229
+ const previousStories = this.storiesCatalog;
230
+ this.definitions = [
231
+ ...this.definitions,
232
+ ...definitions.map((definition) => normalizeDefinition(definition, "mock")),
233
+ ...patchDefinitions.map((definition) => normalizeDefinition(definition, "patch")),
234
+ ];
235
+ this.storiesCatalog = [...this.storiesCatalog, ...stories.map(defineStory)];
236
+ try {
237
+ this.assertStoriesAreValid();
238
+ this.canonicalizeStories();
239
+ }
240
+ catch (error) {
241
+ this.definitions = previousDefinitions;
242
+ this.storiesCatalog = previousStories;
243
+ throw error;
244
+ }
245
+ this.notify();
246
+ };
247
+ /** Replace one response immediately, without registering a feature or story. */
248
+ setMock = (path, data, options = {}) => {
249
+ if (!this.isAvailable())
250
+ return [];
251
+ const next = this.responseOverrides.clone();
252
+ const result = next.set(path, data, "mock", options);
253
+ this.validateChange(this.read(), next);
254
+ this.responseOverrides = next;
255
+ this.notify();
256
+ return result;
257
+ };
258
+ /** Shallow-merge JSON fields into the real response. Nested values are replaced. */
259
+ setPatch = (path, fields, options = {}) => {
260
+ if (!this.isAvailable())
261
+ return [];
262
+ const next = this.responseOverrides.clone();
263
+ const result = next.set(path, fields, "patch", options);
264
+ this.validateChange(this.read(), next);
265
+ this.responseOverrides = next;
266
+ this.notify();
267
+ return result;
268
+ };
269
+ overrides = () => (this.isAvailable() ? this.responseOverrides.list() : []);
270
+ resetOverrides = (path, options = {}) => {
271
+ const next = this.responseOverrides.clone();
272
+ const result = next.clear(path, options.method);
273
+ this.validateChange(this.read(), next);
274
+ this.responseOverrides = next;
275
+ this.notify();
276
+ return result;
277
+ };
278
+ active = (cookieHeader) => this.read(cookieHeader);
279
+ isActiveForPage = (page, cookieHeader) => {
280
+ if (typeof cookieHeader !== "string" && this.overrides().length > 0)
281
+ return true;
282
+ const activeKeys = new Set(this.read(cookieHeader));
283
+ const activeDefinitions = this.definitions.filter((definition) => activeKeys.has(definition.key));
284
+ return (activeDefinitions.some((definition) => this.definitionMatchesPage(definition, page)) ||
285
+ this.storiesCatalog.some((story) => {
286
+ const entries = story.entries.filter((item) => Boolean(this.findDefinitionByInput(item)));
287
+ return (entries.length > 0 &&
288
+ entries.every((item) => activeKeys.has(item)) &&
289
+ doesPageMatch(page, this.getStoryPages(story)));
290
+ }));
291
+ };
292
+ list = () => {
293
+ const active = this.read();
294
+ const items = this.definitions
295
+ .map((definition) => ({
296
+ active: active.includes(definition.key),
297
+ description: definition.description ?? "No description",
298
+ key: definition.key,
299
+ mode: definition.mode,
300
+ pages: definition.pages,
301
+ path: definition.path,
302
+ ...(definition.caseKey ? { caseKey: definition.caseKey } : {}),
303
+ }))
304
+ .sort((left, right) => left.key.localeCompare(right.key));
305
+ return {
306
+ active: items.filter((item) => item.active),
307
+ inactive: items.filter((item) => !item.active),
308
+ };
309
+ };
310
+ features = this.list;
311
+ stories = (input = {}) => {
312
+ if (!this.isAvailable()) {
313
+ return [];
314
+ }
315
+ const options = normalizeStoryListOptions(input);
316
+ const active = this.read();
317
+ const query = normalizeStoryQuery(options.query);
318
+ return this.storiesCatalog
319
+ .map((story) => {
320
+ const entries = story.entries.filter((item) => Boolean(this.findDefinitionByInput(item)));
321
+ const pages = this.getStoryPages(story);
322
+ return {
323
+ active: entries.length > 0 &&
324
+ entries.every((item) => active.includes(item)),
325
+ activeEntries: entries.filter((item) => active.includes(item)),
326
+ description: story.description,
327
+ entries,
328
+ key: story.key,
329
+ pages,
330
+ title: story.title,
331
+ unavailableEntries: story.entries.filter((item) => !this.findDefinitionByInput(item)),
332
+ };
333
+ })
334
+ .filter((story) => !options.storyKey || story.key === options.storyKey)
335
+ .filter((story) => doesPageMatch(options.page, story.pages))
336
+ .filter((story) => doesStoryQueryMatch(query, story))
337
+ .filter((story) => typeof options.active !== "boolean" ||
338
+ story.active === options.active)
339
+ .sort((left, right) => left.title.localeCompare(right.title));
340
+ };
341
+ search = (input = {}) => {
342
+ const options = normalizeSearchOptions(input);
343
+ const query = normalizeStoryQuery(options.query);
344
+ const featureItems = [...this.list().active, ...this.list().inactive]
345
+ .filter((feature) => doesPageMatch(options.page, feature.pages))
346
+ .filter((feature) => doesFeatureQueryMatch(query, feature))
347
+ .filter((feature) => typeof options.active !== "boolean" ||
348
+ feature.active === options.active);
349
+ return {
350
+ features: featureItems,
351
+ stories: this.stories(options),
352
+ };
353
+ };
354
+ hasStory = (storyKey) => this.storiesCatalog.some((story) => story.key === storyKey);
355
+ story = (storyKey) => {
356
+ const story = this.findStory(storyKey);
357
+ return story ? this.set(story.entries) : this.read();
358
+ };
359
+ addStory = (storyKey) => {
360
+ const story = this.findStory(storyKey);
361
+ return story ? this.set([...this.read(), ...story.entries]) : this.read();
362
+ };
363
+ set = (paths) => {
364
+ const nextPaths = [];
365
+ for (const input of parseInputList(paths)) {
366
+ const key = this.normalizeActiveInput(input);
367
+ if (!key) {
368
+ continue;
369
+ }
370
+ const compatible = nextPaths.filter((path) => !this.conflicts(path, key));
371
+ nextPaths.splice(0, nextPaths.length, ...compatible, key);
372
+ }
373
+ return this.write(nextPaths.sort());
374
+ };
375
+ add = (path) => {
376
+ const key = this.normalizeActiveInput(path);
377
+ if (!key) {
378
+ return this.read();
379
+ }
380
+ return this.set([
381
+ ...this.read().filter((item) => !this.conflicts(item, key)),
382
+ key,
383
+ ]);
384
+ };
385
+ remove = (path) => {
386
+ const key = this.normalizeActiveInput(path);
387
+ if (!key) {
388
+ return this.read();
389
+ }
390
+ return this.set(this.read().filter((item) => item !== key));
391
+ };
392
+ toggle = (path) => {
393
+ const key = this.normalizeActiveInput(path);
394
+ if (!key) {
395
+ return this.read();
396
+ }
397
+ return this.read().includes(key) ? this.remove(key) : this.add(key);
398
+ };
399
+ clear = () => this.write([], new ResponseOverrides());
400
+ subscribe = (listener) => {
401
+ this.listeners.add(listener);
402
+ if (typeof window !== "undefined") {
403
+ const handleStorage = (event) => {
404
+ if (event.key === this.storageKey || event.key === null) {
405
+ try {
406
+ if (event.storageArea && event.storageArea !== window.localStorage)
407
+ return;
408
+ }
409
+ catch {
410
+ return;
411
+ }
412
+ this.memoryPaths = this.normalizeActivePaths(parseStoredPaths(event.newValue));
413
+ this.memoryOnly = false;
414
+ writeCookie(this.cookieKey, this.memoryPaths);
415
+ listener(this.read());
416
+ }
417
+ };
418
+ const handleCustomEvent = () => {
419
+ if (!this.dispatchingChange)
420
+ listener(this.read());
421
+ };
422
+ window.addEventListener("storage", handleStorage);
423
+ window.addEventListener(this.eventName, handleCustomEvent);
424
+ return () => {
425
+ this.listeners.delete(listener);
426
+ window.removeEventListener("storage", handleStorage);
427
+ window.removeEventListener(this.eventName, handleCustomEvent);
428
+ };
429
+ }
430
+ return () => {
431
+ this.listeners.delete(listener);
432
+ };
433
+ };
434
+ resolve = async ({ body, cookieHeader, headers = {}, method, params, path, url, }) => {
435
+ const definition = this.findActiveDefinition("mock", {
436
+ cookieHeader,
437
+ headers,
438
+ method,
439
+ params,
440
+ path,
441
+ url,
442
+ });
443
+ if (!definition) {
444
+ return null;
445
+ }
446
+ const normalizedMethod = method.toUpperCase();
447
+ const normalizedPath = normalizePath(path);
448
+ const request = BODYLESS_METHODS.has(normalizedMethod) ? params : body;
449
+ const result = await definition.handler({
450
+ activeKey: definition.key,
451
+ body: request,
452
+ headers,
453
+ method: normalizedMethod,
454
+ params,
455
+ path: normalizedPath,
456
+ request,
457
+ requestCount: this.nextRequestCount(definition.key),
458
+ url: url ?? normalizedPath,
459
+ });
460
+ if (isMockPassThrough(result)) {
461
+ this.log("info", "Mock pass-through", { method: normalizedMethod, path });
462
+ return null;
463
+ }
464
+ if (isMockHttpResult(result)) {
465
+ return result;
466
+ }
467
+ return {
468
+ data: result,
469
+ status: 200,
470
+ statusText: "OK",
471
+ };
472
+ };
473
+ hasMock = (request) => this.findActiveDefinition("mock", request) !== null;
474
+ hasPatch = (request) => this.findActiveDefinition("patch", request) !== null;
475
+ /** Unlike patch(), this distinguishes a JSON null payload from no match. */
476
+ applyPatch = async ({ body, cookieHeader, data, headers = {}, method, params, path, url, }) => {
477
+ const definition = this.findActiveDefinition("patch", {
478
+ cookieHeader,
479
+ headers,
480
+ method,
481
+ params,
482
+ path,
483
+ url,
484
+ });
485
+ if (!definition) {
486
+ return null;
487
+ }
488
+ const normalizedMethod = method.toUpperCase();
489
+ const normalizedPath = normalizePath(path);
490
+ const request = BODYLESS_METHODS.has(normalizedMethod) ? params : body;
491
+ const patched = await definition.handler(data, {
492
+ activeKey: definition.key,
493
+ body: request,
494
+ headers,
495
+ method: normalizedMethod,
496
+ params,
497
+ path: normalizedPath,
498
+ request,
499
+ requestCount: this.nextRequestCount(definition.key),
500
+ url: url ?? normalizedPath,
501
+ });
502
+ return { data: patched };
503
+ };
504
+ /** Compatibility helper. Use applyPatch() when a handler can return null. */
505
+ patch = async (request) => {
506
+ const result = await this.applyPatch(request);
507
+ return result === null ? null : result.data;
508
+ };
509
+ read = (cookieHeader) => {
510
+ if (!this.isAvailable()) {
511
+ return [];
512
+ }
513
+ if (typeof cookieHeader === "string") {
514
+ return this.normalizeActivePaths(parseStoredPaths(readCookieValue(cookieHeader, this.cookieKey)));
515
+ }
516
+ if (typeof window === "undefined" || this.memoryOnly) {
517
+ return [...this.memoryPaths];
518
+ }
519
+ const stored = readBrowserStorage(this.storageKey);
520
+ if (typeof stored === "string") {
521
+ return this.normalizeActivePaths(parseStoredPaths(stored));
522
+ }
523
+ try {
524
+ const cookie = typeof document === "undefined"
525
+ ? ""
526
+ : readCookieValue(document.cookie, this.cookieKey);
527
+ if (cookie)
528
+ return this.normalizeActivePaths(parseStoredPaths(cookie));
529
+ }
530
+ catch {
531
+ // Fall back to the instance state when browser persistence is unavailable.
532
+ }
533
+ return [...this.memoryPaths];
534
+ };
535
+ validateChange = (paths, overrides) => this.beforeChange?.({ entries: [...paths], overrides: overrides.list() });
536
+ write = (paths, overrides = this.responseOverrides) => {
537
+ if (!this.isAvailable()) {
538
+ this.responseOverrides = overrides;
539
+ return [];
540
+ }
541
+ const normalizedPaths = this.normalizeActivePaths(paths);
542
+ this.validateChange(normalizedPaths, overrides);
543
+ this.responseOverrides = overrides;
544
+ this.memoryPaths = normalizedPaths;
545
+ if (typeof window !== "undefined") {
546
+ this.memoryOnly = !writeBrowserStorage(this.storageKey, JSON.stringify(normalizedPaths));
547
+ writeCookie(this.cookieKey, normalizedPaths);
548
+ }
549
+ this.notify(normalizedPaths);
550
+ return [...normalizedPaths];
551
+ };
552
+ notify = (paths = this.read()) => {
553
+ if (typeof window !== "undefined") {
554
+ this.dispatchingChange = true;
555
+ try {
556
+ window.dispatchEvent(new CustomEvent(this.eventName, { detail: [...paths] }));
557
+ }
558
+ finally {
559
+ this.dispatchingChange = false;
560
+ }
561
+ }
562
+ for (const listener of this.listeners)
563
+ listener([...paths]);
564
+ };
565
+ normalizeActivePaths = (paths) => Array.from(new Set(paths
566
+ .map((path) => this.normalizeActiveInput(path))
567
+ .filter((path) => path.length > 0))).sort();
568
+ normalizeActiveInput = (input) => {
569
+ const trimmed = input.trim();
570
+ if (!trimmed) {
571
+ return "";
572
+ }
573
+ const exact = this.definitions.find((definition) => definition.key === trimmed);
574
+ if (exact) {
575
+ return exact.key;
576
+ }
577
+ const entry = parseEntry(trimmed);
578
+ if (!entry) {
579
+ return "";
580
+ }
581
+ const definition = this.findDefinitionByEntry(entry);
582
+ return definition?.key ?? "";
583
+ };
584
+ findDefinitionByInput = (input) => {
585
+ const exact = this.definitions.find((definition) => definition.key === input);
586
+ if (exact) {
587
+ return exact;
588
+ }
589
+ const entry = parseEntry(input);
590
+ return entry ? this.findDefinitionByEntry(entry) : null;
591
+ };
592
+ findDefinitionByEntry = (entry) => this.definitions.find((item) => item.caseKey === entry.caseKey && isSamePath(item.path, entry.path));
593
+ conflicts = (leftKey, rightKey) => {
594
+ const left = this.definitions.filter((definition) => definition.key === leftKey);
595
+ const right = this.definitions.filter((definition) => definition.key === rightKey);
596
+ if (left.length === 0 || right.length === 0) {
597
+ return leftKey === rightKey;
598
+ }
599
+ return left.some((a) => right.some((b) => isSamePath(a.path, b.path) && methodsOverlap(a.method, b.method)));
600
+ };
601
+ findActiveDefinition = (mode, request) => {
602
+ if (!this.isAvailable()) {
603
+ return null;
604
+ }
605
+ const normalizedMethod = request.method.toUpperCase();
606
+ const normalizedPath = normalizePath(request.path);
607
+ // Explicit cookie input is server/request-scoped; never apply a local experiment to it.
608
+ const override = typeof request.cookieHeader === "string"
609
+ ? undefined
610
+ : this.responseOverrides.find(normalizedPath, normalizedMethod);
611
+ if (override) {
612
+ if (override.mode !== mode)
613
+ return null;
614
+ const handler = mode === "mock"
615
+ ? () => httpResult({
616
+ data: override.data,
617
+ bodyFormat: "json",
618
+ status: override.status,
619
+ statusText: override.statusText,
620
+ })
621
+ : (data) => {
622
+ if (data === null ||
623
+ typeof data !== "object" ||
624
+ Array.isArray(data))
625
+ throw new TypeError("Cannot apply an object patch to a non-object response. Use a mock to replace it.");
626
+ return { ...data, ...override.data };
627
+ };
628
+ return {
629
+ key: `override:${normalizedMethod}:${normalizedPath}`,
630
+ path: normalizedPath,
631
+ mode,
632
+ pages: [],
633
+ handler,
634
+ };
635
+ }
636
+ for (const key of this.read(request.cookieHeader)) {
637
+ const definition = this.definitions.find((item) => item.mode === mode &&
638
+ item.key === key &&
639
+ this.methodMatches(item, normalizedMethod) &&
640
+ this.routeMatches(item, {
641
+ headers: request.headers ?? {},
642
+ method: normalizedMethod,
643
+ params: request.params,
644
+ path: normalizedPath,
645
+ url: request.url ?? normalizedPath,
646
+ }));
647
+ if (definition) {
648
+ return definition;
649
+ }
650
+ }
651
+ return null;
652
+ };
653
+ methodMatches = (definition, method) => !definition.method || definition.method.includes(method);
654
+ routeMatches = (definition, context) => {
655
+ const matcher = definition.match ?? definition.path;
656
+ if (typeof matcher === "function") {
657
+ return matcher(context);
658
+ }
659
+ if (matcher instanceof RegExp) {
660
+ matcher.lastIndex = 0;
661
+ return matcher.test(context.path);
662
+ }
663
+ return doesPathMatch(matcher, context.path);
664
+ };
665
+ nextRequestCount = (key) => {
666
+ const nextCount = (this.requestCounts.get(key) ?? 0) + 1;
667
+ this.requestCounts.set(key, nextCount);
668
+ return nextCount;
669
+ };
670
+ log = (level, message, data) => {
671
+ if (this.logger === false) {
672
+ return;
673
+ }
674
+ this.logger?.[level]?.(message, data);
675
+ };
676
+ findStory = (storyKey) => this.storiesCatalog.find((story) => story.key === storyKey) ?? null;
677
+ definitionMatchesPage = (definition, page) => definition.pages.length === 0 || doesPageMatch(page, definition.pages);
678
+ getStoryPages = (story) => Array.from(new Set([
679
+ ...story.pages,
680
+ ...story.entries.flatMap((item) => this.findDefinitionByInput(item)?.pages ?? []),
681
+ ])).sort();
682
+ assertStoriesAreValid = () => {
683
+ const seenStoryKeys = new Set();
684
+ const errors = [];
685
+ for (const [index, definition] of this.definitions.entries()) {
686
+ if (!definition.path)
687
+ errors.push("Feature path is required.");
688
+ if (this.definitions
689
+ .slice(0, index)
690
+ .some((other) => isSamePath(other.path, definition.path) &&
691
+ other.caseKey === definition.caseKey &&
692
+ methodsOverlap(other.method, definition.method)))
693
+ errors.push(`Ambiguous feature entry: ${definition.key}`);
694
+ }
695
+ for (const story of this.storiesCatalog) {
696
+ if (!story.key.trim()) {
697
+ errors.push("Story key is required.");
698
+ }
699
+ else if (seenStoryKeys.has(story.key)) {
700
+ errors.push(`Duplicate story key: ${story.key}`);
701
+ }
702
+ seenStoryKeys.add(story.key);
703
+ if (!story.title.trim()) {
704
+ errors.push(`Story title is required: ${story.key || "(missing key)"}`);
705
+ }
706
+ if (!story.description.trim()) {
707
+ errors.push(`Story description is required: ${story.key || "(missing key)"}`);
708
+ }
709
+ if (this.getStoryPages(story).length === 0) {
710
+ errors.push(`Story pages are required: ${story.key || "(missing key)"}`);
711
+ }
712
+ if (story.entries.length === 0) {
713
+ errors.push(`Story entries are required: ${story.key || "(missing key)"}`);
714
+ }
715
+ for (const item of story.entries) {
716
+ if (!this.findDefinitionByInput(item)) {
717
+ errors.push(`Story references unknown entry: ${story.key}: ${item}`);
718
+ }
719
+ }
720
+ const canonicalEntries = story.entries
721
+ .map(this.normalizeActiveInput)
722
+ .filter(Boolean);
723
+ if (canonicalEntries.some((item, index) => canonicalEntries
724
+ .slice(0, index)
725
+ .some((other) => other !== item && this.conflicts(item, other)))) {
726
+ errors.push(`Story contains conflicting entries: ${story.key}`);
727
+ }
728
+ }
729
+ if (errors.length > 0) {
730
+ throw new Error(`Invalid test-mode stories:\n${errors.join("\n")}`);
731
+ }
732
+ };
733
+ canonicalizeStories = () => {
734
+ this.storiesCatalog = this.storiesCatalog.map((story) => ({
735
+ ...story,
736
+ entries: [...new Set(story.entries.map(this.normalizeActiveInput))],
737
+ }));
738
+ };
739
+ }
740
+ export const createTestMode = (options) => new TestMode(options);
741
+ //# sourceMappingURL=core.js.map