@capybara-devtools/core 0.4.0 → 0.5.1

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 (102) hide show
  1. package/dist/client.d.ts.map +1 -1
  2. package/dist/client.js +20 -2
  3. package/dist/client.js.map +1 -1
  4. package/dist/index.d.ts +8 -2
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +4 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/init.d.ts +40 -0
  9. package/dist/init.d.ts.map +1 -0
  10. package/dist/init.js +35 -0
  11. package/dist/init.js.map +1 -0
  12. package/dist/plugins/console.d.ts.map +1 -1
  13. package/dist/plugins/console.js +105 -9
  14. package/dist/plugins/console.js.map +1 -1
  15. package/dist/plugins/network/body.d.ts +9 -0
  16. package/dist/plugins/network/body.d.ts.map +1 -0
  17. package/dist/plugins/network/body.js +114 -0
  18. package/dist/plugins/network/body.js.map +1 -0
  19. package/dist/plugins/network/failure.d.ts +16 -0
  20. package/dist/plugins/network/failure.d.ts.map +1 -0
  21. package/dist/plugins/network/failure.js +73 -0
  22. package/dist/plugins/network/failure.js.map +1 -0
  23. package/dist/plugins/network/fetch.d.ts +12 -0
  24. package/dist/plugins/network/fetch.d.ts.map +1 -0
  25. package/dist/plugins/network/fetch.js +159 -0
  26. package/dist/plugins/network/fetch.js.map +1 -0
  27. package/dist/plugins/network/settings.d.ts +24 -0
  28. package/dist/plugins/network/settings.d.ts.map +1 -0
  29. package/dist/plugins/network/settings.js +26 -0
  30. package/dist/plugins/network/settings.js.map +1 -0
  31. package/dist/plugins/network/xhr.d.ts +4 -0
  32. package/dist/plugins/network/xhr.d.ts.map +1 -0
  33. package/dist/plugins/network/xhr.js +214 -0
  34. package/dist/plugins/network/xhr.js.map +1 -0
  35. package/dist/plugins/network.d.ts +2 -15
  36. package/dist/plugins/network.d.ts.map +1 -1
  37. package/dist/plugins/network.js +8 -497
  38. package/dist/plugins/network.js.map +1 -1
  39. package/dist/plugins/state/context-names.d.ts +13 -0
  40. package/dist/plugins/state/context-names.d.ts.map +1 -0
  41. package/dist/plugins/state/context-names.js +280 -0
  42. package/dist/plugins/state/context-names.js.map +1 -0
  43. package/dist/plugins/state/context.d.ts +0 -89
  44. package/dist/plugins/state/context.d.ts.map +1 -1
  45. package/dist/plugins/state/context.js +3 -474
  46. package/dist/plugins/state/context.js.map +1 -1
  47. package/dist/plugins/state/engine.d.ts +5 -0
  48. package/dist/plugins/state/engine.d.ts.map +1 -1
  49. package/dist/plugins/state/engine.js +12 -2
  50. package/dist/plugins/state/engine.js.map +1 -1
  51. package/dist/plugins/state/fibers.d.ts +75 -0
  52. package/dist/plugins/state/fibers.d.ts.map +1 -0
  53. package/dist/plugins/state/fibers.js +92 -0
  54. package/dist/plugins/state/fibers.js.map +1 -0
  55. package/dist/plugins/state/index.d.ts +5 -0
  56. package/dist/plugins/state/index.d.ts.map +1 -1
  57. package/dist/plugins/state/index.js.map +1 -1
  58. package/dist/plugins/state/mobx.d.ts +22 -0
  59. package/dist/plugins/state/mobx.d.ts.map +1 -0
  60. package/dist/plugins/state/mobx.js +69 -0
  61. package/dist/plugins/state/mobx.js.map +1 -0
  62. package/dist/plugins/state/react-hook.d.ts +19 -0
  63. package/dist/plugins/state/react-hook.d.ts.map +1 -0
  64. package/dist/plugins/state/react-hook.js +100 -0
  65. package/dist/plugins/state/react-hook.js.map +1 -0
  66. package/dist/plugins/state/redux.d.ts +2 -0
  67. package/dist/plugins/state/redux.d.ts.map +1 -1
  68. package/dist/plugins/state/redux.js +2 -2
  69. package/dist/plugins/state/redux.js.map +1 -1
  70. package/dist/plugins/state/xstate.d.ts +26 -0
  71. package/dist/plugins/state/xstate.d.ts.map +1 -0
  72. package/dist/plugins/state/xstate.js +85 -0
  73. package/dist/plugins/state/xstate.js.map +1 -0
  74. package/dist/plugins/storage.d.ts +1 -1
  75. package/dist/plugins/storage.d.ts.map +1 -1
  76. package/dist/plugins/storage.js +5 -7
  77. package/dist/plugins/storage.js.map +1 -1
  78. package/dist/serialize.d.ts.map +1 -1
  79. package/dist/serialize.js +1 -0
  80. package/dist/serialize.js.map +1 -1
  81. package/package.json +7 -5
  82. package/src/client.ts +19 -2
  83. package/src/index.ts +8 -2
  84. package/src/init.ts +66 -0
  85. package/src/plugins/console.ts +103 -10
  86. package/src/plugins/network/body.ts +114 -0
  87. package/src/plugins/network/failure.ts +79 -0
  88. package/src/plugins/network/fetch.ts +169 -0
  89. package/src/plugins/network/settings.ts +48 -0
  90. package/src/plugins/network/xhr.ts +223 -0
  91. package/src/plugins/network.ts +11 -545
  92. package/src/plugins/state/context-names.ts +265 -0
  93. package/src/plugins/state/context.ts +3 -532
  94. package/src/plugins/state/engine.ts +12 -2
  95. package/src/plugins/state/fibers.ts +160 -0
  96. package/src/plugins/state/index.ts +2 -0
  97. package/src/plugins/state/mobx.ts +80 -0
  98. package/src/plugins/state/react-hook.ts +98 -0
  99. package/src/plugins/state/redux.ts +2 -2
  100. package/src/plugins/state/xstate.ts +94 -0
  101. package/src/plugins/storage.ts +13 -8
  102. package/src/serialize.ts +2 -1
@@ -1,33 +1,111 @@
1
- import type { LogLevel } from '@capybara-devtools/protocol';
1
+ import { isUnhandledRejection, type LogLevel, type LogPayload, type SerializedValue } from '@capybara-devtools/protocol';
2
2
  import type { Plugin } from '../client.js';
3
3
 
4
4
  const LEVELS: LogLevel[] = ['debug', 'log', 'info', 'warn', 'error'];
5
+ const METHODS = ['table', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeLog', 'timeEnd', 'count', 'countReset', 'assert', 'trace'];
5
6
 
6
7
  export interface ConsolePluginOptions {
7
8
  /** Calls whose first argument is a string matching one of these are not recorded; they still print. */
8
9
  ignore?: RegExp[];
9
10
  }
10
11
 
12
+ type ConsoleMethod = (...args: unknown[]) => unknown;
13
+
11
14
  export function consolePlugin(options: ConsolePluginOptions = {}): Plugin {
12
15
  const ignore = options.ignore ?? [];
13
16
  const ignored = (args: unknown[]) => typeof args[0] === 'string' && ignore.some((pattern) => pattern.test(args[0] as string));
14
17
  return {
15
18
  name: 'console',
16
19
  setup(ctx) {
17
- const target = console as unknown as Record<LogLevel, (...args: unknown[]) => void>;
18
- const originals = new Map<LogLevel, (...args: unknown[]) => void>();
20
+ const target = console as unknown as Record<string, ConsoleMethod | undefined>;
21
+ const patches = new Map<string, { original: ConsoleMethod; patched: ConsoleMethod }>();
19
22
  // A getter or toJSON hit during serialization may log; recording that would recurse.
20
23
  let capturing = false;
24
+ let active = true;
25
+ // What browsers keep per page between calls: open groups, timers and counters.
26
+ let depth = 0;
27
+ const timers = new Map<string, number>();
28
+ const counts = new Map<string, number>();
29
+
30
+ const serialize = (args: unknown[]) => args.map((arg) => ctx.serialize(arg));
31
+ const emit = (level: LogLevel, args: SerializedValue[], method?: LogPayload['method']) => {
32
+ const source = level === 'error' && isUnhandledRejection(args) ? 'unhandledrejection' : 'console';
33
+ ctx.emit('log', { level, source, args, ...(depth > 0 && { depth }), ...(method && { method }) });
34
+ };
35
+ const now = () => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now());
36
+ const labelOf = (label: unknown) => (label === undefined ? 'default' : String(label));
37
+ const elapsed = (label: string, data: unknown[], end: boolean) => {
38
+ const start = timers.get(label);
39
+ if (start === undefined) {
40
+ emit('warn', [`Timer '${label}' does not exist`]);
41
+ return;
42
+ }
43
+ if (end) timers.delete(label);
44
+ emit('log', [`${label}: ${(now() - start).toFixed(3)} ms`, ...serialize(data)]);
45
+ };
46
+
47
+ /** Records a call of `name`; `caller` was created in the patch, so its stack starts at the app's call. */
48
+ const record = (name: string, args: unknown[], caller: Error | undefined) => {
49
+ switch (name) {
50
+ case 'table':
51
+ emit('log', serialize(args.slice(0, 2)), 'table');
52
+ return;
53
+ case 'group':
54
+ case 'groupCollapsed':
55
+ emit('log', args.length > 0 ? serialize(args) : [`console.${name}`], name);
56
+ depth++;
57
+ return;
58
+ case 'groupEnd':
59
+ depth = Math.max(0, depth - 1);
60
+ return;
61
+ case 'time': {
62
+ const label = labelOf(args[0]);
63
+ if (timers.has(label)) emit('warn', [`Timer '${label}' already exists`]);
64
+ else timers.set(label, now());
65
+ return;
66
+ }
67
+ case 'timeLog':
68
+ elapsed(labelOf(args[0]), args.slice(1), false);
69
+ return;
70
+ case 'timeEnd':
71
+ elapsed(labelOf(args[0]), [], true);
72
+ return;
73
+ case 'count': {
74
+ const label = labelOf(args[0]);
75
+ const n = (counts.get(label) ?? 0) + 1;
76
+ counts.set(label, n);
77
+ emit('log', [`${label}: ${n}`]);
78
+ return;
79
+ }
80
+ case 'countReset': {
81
+ const label = labelOf(args[0]);
82
+ if (counts.has(label)) counts.set(label, 0);
83
+ else emit('warn', [`Count for '${label}' does not exist`]);
84
+ return;
85
+ }
86
+ case 'assert': {
87
+ if (args[0]) return;
88
+ const data = serialize(args.slice(1));
89
+ const [first] = data;
90
+ emit('error', typeof first === 'string' ? [`Assertion failed: ${first}`, ...data.slice(1)] : ['Assertion failed', ...data]);
91
+ return;
92
+ }
93
+ case 'trace':
94
+ emit('log', [...(args.length > 0 ? serialize(args) : ['console.trace']), ctx.serialize(traceOf(caller))], 'trace');
95
+ return;
96
+ default:
97
+ emit(name as LogLevel, serialize(args));
98
+ }
99
+ };
21
100
 
22
- for (const level of LEVELS) {
23
- const original = target[level];
101
+ for (const name of [...LEVELS, ...METHODS]) {
102
+ const original = target[name];
24
103
  if (typeof original !== 'function') continue;
25
- originals.set(level, original);
26
- target[level] = function (this: unknown, ...args: unknown[]) {
27
- if (!capturing && !ignored(args)) {
104
+ const patched = function (this: unknown, ...args: unknown[]) {
105
+ if (active && !capturing && !ignored(args)) {
28
106
  capturing = true;
29
107
  try {
30
- ctx.emit('log', { level, source: 'console', args: args.map((arg) => ctx.serialize(arg)) });
108
+ record(name, args, name === 'trace' ? new Error() : undefined);
31
109
  } catch {
32
110
  // logging must keep working even if capture fails
33
111
  } finally {
@@ -36,11 +114,26 @@ export function consolePlugin(options: ConsolePluginOptions = {}): Plugin {
36
114
  }
37
115
  return original.apply(this, args);
38
116
  };
117
+ target[name] = patched;
118
+ patches.set(name, { original, patched });
39
119
  }
40
120
 
41
121
  return () => {
42
- for (const [level, original] of originals) target[level] = original;
122
+ // A wrapper installed after ours (LogBox, Sentry) stays; ours, still under it, then only passes calls on.
123
+ active = false;
124
+ for (const [name, { original, patched }] of patches) if (target[name] === patched) target[name] = original;
43
125
  };
44
126
  },
45
127
  };
46
128
  }
129
+
130
+ /** An error named Trace whose stack starts at the caller of the console patch that created `caller`. */
131
+ function traceOf(caller: Error | undefined): Error {
132
+ const trace = new Error();
133
+ trace.name = 'Trace';
134
+ const lines = (caller?.stack ?? '').split('\n').filter((line) => line.trim() !== '');
135
+ // V8 and Hermes start with an "Error" line; Safari and Firefox list frames only. The first frame is the patch.
136
+ const frames = lines[0] !== undefined && !lines[0].includes('@') && !/^\s*at /.test(lines[0]) ? lines.slice(2) : lines.slice(1);
137
+ trace.stack = ['Trace', ...frames].join('\n');
138
+ return trace;
139
+ }
@@ -0,0 +1,114 @@
1
+ import type { BodyPreview } from '@capybara-devtools/protocol';
2
+ import { utf8Length } from '../../utils.js';
3
+
4
+ const TEXTUAL =
5
+ /^(text\/|application\/([\w.+-]*\+)?(json|xml|javascript|ecmascript|x-www-form-urlencoded|graphql|x-ndjson)\b)/i;
6
+
7
+ export function isTextual(contentType: string | undefined): boolean {
8
+ return !contentType || TEXTUAL.test(contentType.trim());
9
+ }
10
+
11
+ export function textPreview(text: string, maxBody: number, contentType?: string, kind: 'text' | 'form' = 'text'): BodyPreview {
12
+ const truncated = text.length > maxBody;
13
+ return { kind, text: truncated ? text.slice(0, maxBody) : text, size: utf8Length(text), truncated, contentType };
14
+ }
15
+
16
+ export function previewRequestBody(body: unknown, maxBody: number, contentType?: string): BodyPreview | undefined {
17
+ if (body === undefined || body === null) return undefined;
18
+ if (typeof body === 'string') return textPreview(body, maxBody, contentType);
19
+ const g = globalThis as Record<string, any>;
20
+ if (g.URLSearchParams && body instanceof g.URLSearchParams) {
21
+ return textPreview(String(body), maxBody, contentType ?? 'application/x-www-form-urlencoded');
22
+ }
23
+ if (g.FormData && body instanceof g.FormData) return formPreview(body, maxBody);
24
+ if (g.Blob && body instanceof g.Blob) {
25
+ const blob = body as Blob;
26
+ return { kind: 'binary', size: blob.size, contentType: blob.type || contentType, summary: blob.type ? `Blob (${blob.type})` : 'Blob' };
27
+ }
28
+ if (body instanceof ArrayBuffer) return { kind: 'binary', size: body.byteLength, contentType, summary: 'ArrayBuffer' };
29
+ if (ArrayBuffer.isView(body)) {
30
+ return { kind: 'binary', size: body.byteLength, contentType, summary: body.constructor?.name ?? 'TypedArray' };
31
+ }
32
+ if (g.ReadableStream && body instanceof g.ReadableStream) return { kind: 'stream', contentType, summary: 'ReadableStream' };
33
+ return { kind: 'unknown', contentType, summary: Object.prototype.toString.call(body) };
34
+ }
35
+
36
+ interface ReactNativeFormPart {
37
+ fieldName: string;
38
+ string?: string;
39
+ uri?: string;
40
+ name?: string;
41
+ type?: string;
42
+ }
43
+
44
+ function formPreview(form: unknown, maxBody: number): BodyPreview {
45
+ const lines: string[] = [];
46
+ const browserForm = form as { entries?: () => Iterable<[string, unknown]> };
47
+ const nativeForm = form as { getParts?: () => ReactNativeFormPart[] };
48
+ if (typeof browserForm.entries === 'function') {
49
+ for (const [name, value] of browserForm.entries()) lines.push(`${name}=${describeFormValue(value)}`);
50
+ } else if (typeof nativeForm.getParts === 'function') {
51
+ // React Native's FormData has no entries().
52
+ for (const part of nativeForm.getParts()) {
53
+ const value =
54
+ part.string !== undefined ? part.string : `[file ${part.name ?? part.uri ?? ''}${part.type ? `, ${part.type}` : ''}]`;
55
+ lines.push(`${part.fieldName}=${value}`);
56
+ }
57
+ }
58
+ return textPreview(lines.join('\n'), maxBody, 'multipart/form-data', 'form');
59
+ }
60
+
61
+ function describeFormValue(value: unknown): string {
62
+ if (typeof value === 'string') return value;
63
+ const file = value as { name?: string; size?: number; type?: string };
64
+ return `[file ${file.name ?? 'blob'}${file.type ? `, ${file.type}` : ''}${file.size !== undefined ? `, ${file.size} B` : ''}]`;
65
+ }
66
+
67
+ export function headersToRecord(headers: unknown): Record<string, string> {
68
+ const out: Record<string, string> = {};
69
+ if (!headers) return out;
70
+ const add = (name: string, value: string) => {
71
+ out[name] = name in out ? `${out[name]}, ${value}` : value;
72
+ };
73
+ if (Array.isArray(headers)) {
74
+ for (const pair of headers) if (Array.isArray(pair) && pair.length >= 2) add(String(pair[0]), String(pair[1]));
75
+ } else if (typeof (headers as Headers).forEach === 'function') {
76
+ (headers as Headers).forEach((value, name) => {
77
+ add(name, value);
78
+ });
79
+ } else if (typeof headers === 'object') {
80
+ for (const [name, value] of Object.entries(headers as Record<string, unknown>)) {
81
+ if (value !== undefined) add(name, String(value));
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+
87
+ export function parseRawHeaders(raw: string | null | undefined): Record<string, string> {
88
+ const out: Record<string, string> = {};
89
+ if (!raw) return out;
90
+ for (const line of raw.split(/\r?\n/)) {
91
+ const index = line.indexOf(':');
92
+ if (index <= 0) continue;
93
+ const name = line.slice(0, index).trim().toLowerCase();
94
+ const value = line.slice(index + 1).trim();
95
+ out[name] = name in out ? `${out[name]}, ${value}` : value;
96
+ }
97
+ return out;
98
+ }
99
+
100
+ export function findHeader(headers: Record<string, string>, name: string): string | undefined {
101
+ const target = name.toLowerCase();
102
+ for (const key of Object.keys(headers)) if (key.toLowerCase() === target) return headers[key];
103
+ return undefined;
104
+ }
105
+
106
+ export function absoluteUrl(url: string): string {
107
+ const base = (globalThis as { location?: { href?: string } }).location?.href;
108
+ if (!base || /^[a-z][a-z\d+.-]*:/i.test(url)) return url;
109
+ try {
110
+ return new URL(url, base).href;
111
+ } catch {
112
+ return url;
113
+ }
114
+ }
@@ -0,0 +1,79 @@
1
+ import type { NetworkErrorPayload } from '@capybara-devtools/protocol';
2
+ import { now } from '../../utils.js';
3
+
4
+ export type Explanation = Pick<NetworkErrorPayload, 'cause' | 'credentials'> & { message?: string };
5
+
6
+ export interface FailureExplainer {
7
+ /** Runs `report` once the cause can be told, which in a browser may be a moment after the failure. */
8
+ explain(url: string, credentials: boolean, report: (explanation: Explanation) => void): void;
9
+ stop(): void;
10
+ }
11
+
12
+ /**
13
+ * Browsers never tell a page why a request failed. What a page can know: whether it is offline,
14
+ * whether the URL is mixed content, and CSP blocks, which arrive as `securitypolicyviolation`
15
+ * events. Anything else cross-origin is reported as such for the Capybara server to diagnose.
16
+ */
17
+ export function failureExplainer(): FailureExplainer {
18
+ const g = globalThis as {
19
+ location?: { href?: string; origin?: string; protocol?: string };
20
+ navigator?: { onLine?: boolean; product?: string; userAgent?: string };
21
+ document?: Pick<Document, 'addEventListener' | 'removeEventListener'>;
22
+ };
23
+ const page = g.location;
24
+ if (!page?.href || !page.origin || page.origin === 'null' || g.navigator?.product === 'ReactNative') {
25
+ return { explain: (_url, _credentials, report) => report({}), stop() {} };
26
+ }
27
+ const blocked: Array<{ origin: string; directive: string; at: number }> = [];
28
+ const onViolation = (event: Event) => {
29
+ const violation = event as SecurityPolicyViolationEvent;
30
+ const directive = violation.effectiveDirective || violation.violatedDirective || '';
31
+ if (!/^(connect-src|default-src)/.test(directive)) return;
32
+ try {
33
+ blocked.push({ origin: new URL(violation.blockedURI, page.href).origin, directive, at: now() });
34
+ if (blocked.length > 20) blocked.shift();
35
+ } catch {
36
+ // `inline` or `eval` violations carry no URL
37
+ }
38
+ };
39
+ g.document?.addEventListener('securitypolicyviolation', onViolation);
40
+ // Chromium lets https pages call local-network devices over http and gates them with its Local
41
+ // Network Access permission instead; other browsers block them as mixed content.
42
+ const chromium = /Chrom(e|ium)\//.test(g.navigator?.userAgent ?? '');
43
+ const classify = (url: string, credentials: boolean): Explanation => {
44
+ let target: URL;
45
+ try {
46
+ target = new URL(url, page.href);
47
+ } catch {
48
+ return {};
49
+ }
50
+ if (g.navigator?.onLine === false) return { cause: 'offline', message: 'The browser is offline' };
51
+ const csp = blocked.find((entry) => entry.origin === target.origin && now() - entry.at < 10_000);
52
+ if (csp) return { cause: 'csp', message: `Blocked by the page's Content-Security-Policy (${csp.directive})` };
53
+ const exempt = isTrustworthyHost(target.hostname) || (chromium && isLocalNetworkHost(target.hostname));
54
+ if (page.protocol === 'https:' && target.protocol === 'http:' && !exempt) {
55
+ return { cause: 'mixed-content', message: `Blocked as mixed content: an https page cannot call ${target.origin}` };
56
+ }
57
+ if (target.origin !== page.origin) return { cause: 'cross-origin', credentials: credentials || undefined };
58
+ return {};
59
+ };
60
+ return {
61
+ // The violation event can arrive after the request has already failed.
62
+ explain: (url, credentials, report) => void setTimeout(() => report(classify(url, credentials)), 30),
63
+ stop: () => g.document?.removeEventListener('securitypolicyviolation', onViolation),
64
+ };
65
+ }
66
+
67
+ /** Browsers let https pages call these over plain http. */
68
+ function isTrustworthyHost(hostname: string): boolean {
69
+ return hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '127.0.0.1' || hostname === '[::1]';
70
+ }
71
+
72
+ /** Private IP literals and .local names; a hostname that resolves to a private IP does not count. */
73
+ function isLocalNetworkHost(hostname: string): boolean {
74
+ if (hostname.endsWith('.local')) return true;
75
+ const ipv4 = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(hostname);
76
+ if (!ipv4) return /^\[(f[cd]|fe[89ab])/i.test(hostname);
77
+ const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
78
+ return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
79
+ }
@@ -0,0 +1,169 @@
1
+ import type { BodyPreview } from '@capybara-devtools/protocol';
2
+ import type { PluginContext } from '../../client.js';
3
+ import { errorMessage, now, randomId } from '../../utils.js';
4
+ import { absoluteUrl, findHeader, headersToRecord, isTextual, previewRequestBody, textPreview } from './body.js';
5
+ import type { Explanation } from './failure.js';
6
+ import type { Settings } from './settings.js';
7
+
8
+ export type FetchFunction = ((...args: unknown[]) => unknown) & { polyfill?: unknown };
9
+
10
+ /** A body still arriving after this long, e.g. a streamed AI answer or a long poll, is reported as it comes. */
11
+ const STREAM_AFTER_MS = 500;
12
+ const STREAM_EVERY_MS = 1_000;
13
+
14
+ /**
15
+ * whatwg-fetch marks itself `polyfill`. Bare React Native ships it as fetch, so every fetch is also an
16
+ * XHR there, and patching both would record each request twice. Expo swaps in a native fetch.
17
+ */
18
+ export function isXhrFetch(): boolean {
19
+ return (globalThis as { fetch?: FetchFunction }).fetch?.polyfill === true;
20
+ }
21
+
22
+ export function patchFetch(ctx: PluginContext, settings: Settings): () => void {
23
+ const g = globalThis as { fetch?: typeof fetch };
24
+ const original = g.fetch;
25
+ if (typeof original !== 'function') return () => {};
26
+ let active = true;
27
+
28
+ const patched = function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
29
+ if (!active) return original.call(globalThis, input, init);
30
+ let request: ReturnType<typeof describeFetch>;
31
+ try {
32
+ request = describeFetch(input, init, settings.maxBody);
33
+ } catch {
34
+ return original.call(globalThis, input, init);
35
+ }
36
+ if (settings.isIgnored(request.url)) return original.call(globalThis, input, init);
37
+
38
+ const id = randomId();
39
+ const start = now();
40
+ ctx.emit('network.request', {
41
+ id,
42
+ initiator: 'fetch',
43
+ method: request.method,
44
+ url: request.url,
45
+ headers: settings.redact(request.headers),
46
+ body: request.body,
47
+ });
48
+
49
+ let promise: Promise<Response>;
50
+ try {
51
+ promise = original.call(globalThis, input, init);
52
+ } catch (error) {
53
+ ctx.emit('network.error', { id, message: errorMessage(error), duration: now() - start });
54
+ throw error;
55
+ }
56
+
57
+ // Registered before the caller gets the promise, so the response is cloned before app code can read it.
58
+ promise.then(
59
+ (response) => {
60
+ try {
61
+ const duration = now() - start;
62
+ const headers = settings.redact(headersToRecord(response.headers));
63
+ const respond = (body: BodyPreview | undefined, streaming = false) =>
64
+ ctx.emit('network.response', {
65
+ id,
66
+ status: response.status,
67
+ statusText: response.statusText || undefined,
68
+ headers,
69
+ body,
70
+ duration,
71
+ ...(streaming && { streaming: true as const }),
72
+ });
73
+ readFetchBody(response, settings.maxBody, (partial) => respond(partial, true)).then(
74
+ (body) => respond(body),
75
+ () => respond(undefined),
76
+ );
77
+ } catch {
78
+ // never surface SDK failures to the app
79
+ }
80
+ },
81
+ (error: unknown) => {
82
+ const duration = now() - start;
83
+ const aborted = (error as { name?: string } | null)?.name === 'AbortError';
84
+ const fail = (explanation: Explanation) =>
85
+ ctx.emit('network.error', { id, duration, aborted, ...explanation, message: explanation.message ?? errorMessage(error) });
86
+ if (aborted) fail({});
87
+ else settings.failures.explain(request.url, request.credentials, fail);
88
+ },
89
+ );
90
+ return promise;
91
+ };
92
+
93
+ g.fetch = patched as typeof fetch;
94
+ return () => {
95
+ // A wrapper installed after ours stays; ours, still under it, then only passes calls on.
96
+ active = false;
97
+ if (g.fetch === patched) g.fetch = original;
98
+ };
99
+ }
100
+
101
+ function describeFetch(input: RequestInfo | URL, init: RequestInit | undefined, maxBody: number) {
102
+ const RequestCtor = (globalThis as { Request?: typeof Request }).Request;
103
+ const request = RequestCtor && input instanceof RequestCtor ? input : undefined;
104
+ const url = request ? request.url : String((input as { href?: string }).href ?? input);
105
+ const method = String(init?.method ?? request?.method ?? 'GET').toUpperCase();
106
+ const headers = { ...(request ? headersToRecord(request.headers) : {}), ...headersToRecord(init?.headers) };
107
+ let body: BodyPreview | undefined;
108
+ if (init?.body !== undefined && init.body !== null) {
109
+ body = previewRequestBody(init.body, maxBody, findHeader(headers, 'content-type'));
110
+ } else if (request?.body) {
111
+ body = { kind: 'stream', summary: 'Request body (not captured)' };
112
+ }
113
+ const credentials = (init?.credentials ?? request?.credentials) === 'include';
114
+ return { url: absoluteUrl(url), method, headers, body, credentials };
115
+ }
116
+
117
+ /** `onProgress` gets what came so far of a body that takes a while, then again every second while more comes. */
118
+ async function readFetchBody(
119
+ response: Response,
120
+ maxBody: number,
121
+ onProgress: (partial: BodyPreview | undefined) => void,
122
+ ): Promise<BodyPreview | undefined> {
123
+ const contentType = response.headers.get('content-type') ?? undefined;
124
+ const declared = Number(response.headers.get('content-length') ?? Number.NaN);
125
+ const size = Number.isFinite(declared) ? declared : undefined;
126
+ if (!response.body) return undefined;
127
+ if (contentType && /^text\/event-stream/i.test(contentType)) {
128
+ return { kind: 'stream', contentType, summary: 'Event stream' };
129
+ }
130
+ if (!isTextual(contentType)) return { kind: 'binary', contentType, size, summary: contentType ?? 'Binary' };
131
+ if (typeof TextDecoder === 'undefined') return textPreview(await response.clone().text(), maxBody, contentType);
132
+
133
+ // Read only up to the limit, then cancel our branch; the app's branch of the tee is unaffected.
134
+ const reader = response.clone().body!.getReader();
135
+ const decoder = new TextDecoder();
136
+ let text = '';
137
+ let bytes = 0;
138
+ let truncated = false;
139
+ let reported = 0;
140
+ const report = () => {
141
+ reported = now();
142
+ onProgress(text === '' ? undefined : { kind: 'text', text, size: bytes, contentType });
143
+ };
144
+ const timer = setTimeout(report, STREAM_AFTER_MS);
145
+ try {
146
+ for (;;) {
147
+ const { done, value } = await reader.read();
148
+ if (done) break;
149
+ bytes += value.byteLength;
150
+ text += decoder.decode(value, { stream: true });
151
+ if (text.length > maxBody) {
152
+ truncated = true;
153
+ break;
154
+ }
155
+ if (reported > 0 && now() - reported >= STREAM_EVERY_MS) report();
156
+ }
157
+ if (!truncated) text += decoder.decode();
158
+ } finally {
159
+ clearTimeout(timer);
160
+ if (truncated) reader.cancel().catch(() => {});
161
+ }
162
+ return {
163
+ kind: 'text',
164
+ text: truncated ? text.slice(0, maxBody) : text,
165
+ size: truncated ? size : bytes,
166
+ truncated,
167
+ contentType,
168
+ };
169
+ }
@@ -0,0 +1,48 @@
1
+ import { MAX_BODY_SIZE } from '@capybara-devtools/protocol';
2
+ import { failureExplainer, type FailureExplainer } from './failure.js';
3
+
4
+ export interface NetworkPluginOptions {
5
+ /** Patch `fetch`. Where fetch runs on XHR (whatwg-fetch), its requests are recorded once, by the XHR patch, as fetch. */
6
+ fetch?: boolean;
7
+ xhr?: boolean;
8
+ /** Record WebSocket connections and their messages. Default true. */
9
+ websocket?: boolean;
10
+ /** Requests and WebSockets whose URL contains one of these strings or matches one of these patterns are not recorded. */
11
+ ignoreUrls?: Array<string | RegExp>;
12
+ /** Request and response bodies are cut after this many characters. Default 128 KiB. */
13
+ maxBodySize?: number;
14
+ /** WebSocket messages are cut after this many characters. Default 16 KiB. */
15
+ maxMessageSize?: number;
16
+ /** Header names (case-insensitive) whose values are replaced with "[redacted]". */
17
+ redactHeaders?: string[];
18
+ }
19
+
20
+ export interface Settings {
21
+ maxBody: number;
22
+ isIgnored(url: string): boolean;
23
+ redact(headers: Record<string, string>): Record<string, string>;
24
+ failures: FailureExplainer;
25
+ }
26
+
27
+ export function resolveSettings(options: NetworkPluginOptions): Settings {
28
+ const patterns = options.ignoreUrls ?? [];
29
+ const redacted = new Set((options.redactHeaders ?? []).map((name) => name.toLowerCase()));
30
+ return {
31
+ maxBody: options.maxBodySize ?? MAX_BODY_SIZE,
32
+ isIgnored: (url) =>
33
+ patterns.some((pattern) => {
34
+ if (typeof pattern === 'string') return url.includes(pattern);
35
+ pattern.lastIndex = 0;
36
+ return pattern.test(url);
37
+ }),
38
+ redact: (headers) => {
39
+ if (redacted.size === 0) return headers;
40
+ const out: Record<string, string> = {};
41
+ for (const [name, value] of Object.entries(headers)) {
42
+ out[name] = redacted.has(name.toLowerCase()) ? '[redacted]' : value;
43
+ }
44
+ return out;
45
+ },
46
+ failures: failureExplainer(),
47
+ };
48
+ }