req-race 0.2.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/bin/req-race.js CHANGED
@@ -15,8 +15,9 @@ Usage:
15
15
  npx req-race <url> [options]
16
16
 
17
17
  Options:
18
- --mode <mode> reverse-order | jitter | throttle-mutations (default: reverse-order)
18
+ --mode <mode> reverse-order | jitter | throttle-mutations | timeout (default: reverse-order)
19
19
  --delay <ms> Delay ms for reordered requests (default: 1000)
20
+ --timeout <ms> Timeout ms when using --mode timeout (default: 1500)
20
21
  --wait <ms> Wait ms after load to collect requests (default: 1500)
21
22
  --json Output machine-readable JSON
22
23
  -h, --help Show this help message
@@ -32,14 +33,29 @@ const getArgValue = (flag) => {
32
33
  const url = args.find((a) => !a.startsWith("-"));
33
34
  const mode = getArgValue("--mode") || "reverse-order";
34
35
  const delayMs = Number(getArgValue("--delay") ?? 1000);
36
+ const timeoutMs = Number(getArgValue("--timeout") ?? 1500);
35
37
  const waitMs = Number(getArgValue("--wait") ?? 1500);
36
38
  const jsonOutput = args.includes("--json");
37
39
 
40
+ const VALID_MODES = new Set(["reverse-order", "jitter", "throttle-mutations", "timeout"]);
41
+
38
42
  if (!url) {
39
43
  console.error("Error: Please provide a target URL, e.g. npx req-race http://localhost:5173");
40
44
  process.exit(1);
41
45
  }
42
46
 
47
+ if (!/^(https?|file):\/\//i.test(url)) {
48
+ console.error(`Error: Invalid URL "${url}". Expected http://, https://, or file:// URL.`);
49
+ process.exit(1);
50
+ }
51
+
52
+ if (!VALID_MODES.has(mode)) {
53
+ console.error(
54
+ `Error: Invalid --mode "${mode}". Expected one of: ${Array.from(VALID_MODES).join(", ")}.`
55
+ );
56
+ process.exit(1);
57
+ }
58
+
43
59
  let playwright;
44
60
  try {
45
61
  playwright = await import("playwright");
@@ -65,7 +81,7 @@ try {
65
81
  const enable = factory();
66
82
  window.__reqRace = enable(opts);
67
83
  },
68
- { source: coreSource, opts: { mode, delayMs } }
84
+ { source: coreSource, opts: { mode, delayMs, timeoutMs } }
69
85
  );
70
86
 
71
87
  await page.goto(url, { waitUntil: "networkidle" });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "req-race",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "Automated stale-fetch race condition, out-of-order response chaos, and double-submit mutation tester for browsers, Playwright, and CI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/index.d.ts CHANGED
@@ -44,6 +44,8 @@ export interface RaceChaosController {
44
44
  export interface RaceSafeFetchOptions {
45
45
  normalizeKey?: (url: string, method: string) => string;
46
46
  dedupeMutations?: boolean;
47
+ timeoutMs?: number;
48
+ retries?: number;
47
49
  }
48
50
 
49
51
  export function enableFetchRaceChaos(options?: RaceChaosOptions): RaceChaosController;
package/src/index.js CHANGED
@@ -247,13 +247,46 @@ export function createRaceSafeFetch(
247
247
  ? optionsOrNormalizeKey
248
248
  : optionsOrNormalizeKey.normalizeKey || defaultNormalizeKey;
249
249
  const dedupeMutations = isFn ? false : Boolean(optionsOrNormalizeKey.dedupeMutations);
250
+ const timeoutMs = isFn ? 0 : Number(optionsOrNormalizeKey.timeoutMs || 0);
251
+ const retries = isFn ? 0 : Number(optionsOrNormalizeKey.retries || 0);
250
252
 
251
253
  const controllers = new Map();
252
254
  const inFlightMutations = new Map();
253
255
 
256
+ const runWithTimeout = async (input, init, externalSignal) => {
257
+ if (!timeoutMs || timeoutMs <= 0) {
258
+ return fetchImpl(input, init);
259
+ }
260
+ const timeoutController = new AbortController();
261
+ const onExternalAbort = () => timeoutController.abort(externalSignal.reason);
262
+ externalSignal?.addEventListener("abort", onExternalAbort, { once: true });
263
+
264
+ let timedOut = false;
265
+ const timer = setTimeout(() => {
266
+ timedOut = true;
267
+ timeoutController.abort(new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError"));
268
+ }, timeoutMs);
269
+
270
+ try {
271
+ return await fetchImpl(input, { ...init, signal: timeoutController.signal });
272
+ } catch (err) {
273
+ if (timedOut) {
274
+ throw new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError");
275
+ }
276
+ throw err;
277
+ } finally {
278
+ clearTimeout(timer);
279
+ externalSignal?.removeEventListener("abort", onExternalAbort);
280
+ }
281
+ };
282
+
254
283
  return async function raceSafeFetch(input, init = {}) {
255
284
  const url = extractUrl(input);
256
- const method = (init?.method || "GET").toUpperCase();
285
+ const method = (
286
+ init?.method ||
287
+ (typeof input === "object" && input?.method) ||
288
+ "GET"
289
+ ).toUpperCase();
257
290
  const key = normalizeKey(url, method);
258
291
 
259
292
  if (method === "GET" || method === "HEAD") {
@@ -265,15 +298,33 @@ export function createRaceSafeFetch(
265
298
  controllers.set(key, controller);
266
299
 
267
300
  if (init?.signal) {
268
- init.signal.addEventListener(
269
- "abort",
270
- () => controller.abort(init.signal.reason),
271
- { once: true }
272
- );
301
+ if (init.signal.aborted) {
302
+ controller.abort(init.signal.reason);
303
+ } else {
304
+ init.signal.addEventListener(
305
+ "abort",
306
+ () => controller.abort(init.signal.reason),
307
+ { once: true }
308
+ );
309
+ }
273
310
  }
274
311
 
275
312
  try {
276
- return await fetchImpl(input, { ...init, signal: controller.signal });
313
+ let attempt = 0;
314
+ while (true) {
315
+ try {
316
+ return await runWithTimeout(
317
+ input,
318
+ { ...init, signal: controller.signal },
319
+ controller.signal
320
+ );
321
+ } catch (err) {
322
+ const isUserAbort = err?.name === "AbortError" || controller.signal.aborted;
323
+ if (isUserAbort || attempt >= retries) throw err;
324
+ attempt++;
325
+ await sleep(50 * attempt, controller.signal);
326
+ }
327
+ }
277
328
  } finally {
278
329
  if (controllers.get(key) === controller) {
279
330
  controllers.delete(key);
@@ -285,7 +336,7 @@ export function createRaceSafeFetch(
285
336
  const existing = inFlightMutations.get(key);
286
337
  if (existing) return existing;
287
338
 
288
- const promise = Promise.resolve(fetchImpl(input, init)).finally(() => {
339
+ const promise = Promise.resolve(runWithTimeout(input, init, init?.signal)).finally(() => {
289
340
  if (inFlightMutations.get(key) === promise) {
290
341
  inFlightMutations.delete(key);
291
342
  }
@@ -294,7 +345,7 @@ export function createRaceSafeFetch(
294
345
  return promise;
295
346
  }
296
347
 
297
- return fetchImpl(input, init);
348
+ return runWithTimeout(input, init, init?.signal);
298
349
  };
299
350
  }
300
351
 
@@ -15,8 +15,16 @@ export interface DoubleSubmitOptions {
15
15
  windowMs?: number;
16
16
  }
17
17
 
18
+ export interface LoadingHangOptions {
19
+ url: string | RegExp;
20
+ trigger: () => Promise<void>;
21
+ loadingSelector: string;
22
+ timeoutMs?: number;
23
+ }
24
+
18
25
  export function assertNoStaleRace(page: Page, options: StaleRaceOptions): Promise<void>;
19
26
  export function assertNoDoubleSubmit(
20
27
  page: Page,
21
28
  options: DoubleSubmitOptions
22
29
  ): Promise<{ mutationCount: number }>;
30
+ export function assertNoLoadingHang(page: Page, options: LoadingHangOptions): Promise<void>;
package/src/playwright.js CHANGED
@@ -41,6 +41,14 @@ export async function assertNoStaleRace(page, options) {
41
41
  }
42
42
  }
43
43
 
44
+ function globToRegex(pattern) {
45
+ if (pattern instanceof RegExp) return pattern;
46
+ const escaped = String(pattern)
47
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
48
+ .replace(/\*/g, ".*");
49
+ return new RegExp(escaped);
50
+ }
51
+
44
52
  /**
45
53
  * Rapidly double-click a button and assert that at most `maxRequests` mutation
46
54
  * requests are fired.
@@ -49,14 +57,13 @@ export async function assertNoStaleRace(page, options) {
49
57
  */
50
58
  export async function assertNoDoubleSubmit(page, options) {
51
59
  const { button, url, maxRequests = 1, windowMs = 600 } = options;
60
+ const urlRegex = globToRegex(url);
52
61
 
53
62
  let mutationCount = 0;
54
63
  const onRequest = (req) => {
55
64
  const method = req.method().toUpperCase();
56
65
  if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
57
- const reqUrl = req.url();
58
- const matches = typeof url === "string" ? reqUrl.includes(url.replace(/\*/g, "")) : url.test(reqUrl);
59
- if (matches) mutationCount++;
66
+ if (urlRegex.test(req.url())) mutationCount++;
60
67
  }
61
68
  };
62
69
 
@@ -77,3 +84,30 @@ export async function assertNoDoubleSubmit(page, options) {
77
84
  page.off("request", onRequest);
78
85
  }
79
86
  }
87
+
88
+ /**
89
+ * Abort or stall matching requests and assert the UI does not remain stuck
90
+ * in a loading state after `timeoutMs`.
91
+ * @param {import('playwright').Page} page
92
+ * @param {object} options
93
+ */
94
+ export async function assertNoLoadingHang(page, options) {
95
+ const { url, trigger, loadingSelector, timeoutMs = 1500 } = options;
96
+ const handler = async (route) => {
97
+ await route.abort("timedout");
98
+ };
99
+
100
+ await page.route(url, handler);
101
+ try {
102
+ await trigger();
103
+ await page.waitForTimeout(timeoutMs);
104
+ const stillVisible = await page.locator(loadingSelector).first().isVisible().catch(() => false);
105
+ if (stillVisible) {
106
+ throw new Error(
107
+ `Infinite loading hang detected! "${loadingSelector}" is still visible ${timeoutMs}ms after request failure.`
108
+ );
109
+ }
110
+ } finally {
111
+ await page.unroute(url, handler);
112
+ }
113
+ }