@capybara-devtools/core 0.5.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.
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +20 -2
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +40 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/init.js +35 -0
- package/dist/init.js.map +1 -0
- package/dist/plugins/console.d.ts.map +1 -1
- package/dist/plugins/console.js +105 -9
- package/dist/plugins/console.js.map +1 -1
- package/dist/plugins/network/body.d.ts +9 -0
- package/dist/plugins/network/body.d.ts.map +1 -0
- package/dist/plugins/network/body.js +114 -0
- package/dist/plugins/network/body.js.map +1 -0
- package/dist/plugins/network/failure.d.ts +16 -0
- package/dist/plugins/network/failure.d.ts.map +1 -0
- package/dist/plugins/network/failure.js +73 -0
- package/dist/plugins/network/failure.js.map +1 -0
- package/dist/plugins/network/fetch.d.ts +12 -0
- package/dist/plugins/network/fetch.d.ts.map +1 -0
- package/dist/plugins/network/fetch.js +159 -0
- package/dist/plugins/network/fetch.js.map +1 -0
- package/dist/plugins/network/settings.d.ts +24 -0
- package/dist/plugins/network/settings.d.ts.map +1 -0
- package/dist/plugins/network/settings.js +26 -0
- package/dist/plugins/network/settings.js.map +1 -0
- package/dist/plugins/network/xhr.d.ts +4 -0
- package/dist/plugins/network/xhr.d.ts.map +1 -0
- package/dist/plugins/network/xhr.js +214 -0
- package/dist/plugins/network/xhr.js.map +1 -0
- package/dist/plugins/network.d.ts +2 -15
- package/dist/plugins/network.d.ts.map +1 -1
- package/dist/plugins/network.js +5 -518
- package/dist/plugins/network.js.map +1 -1
- package/dist/plugins/state/context-names.d.ts +13 -0
- package/dist/plugins/state/context-names.d.ts.map +1 -0
- package/dist/plugins/state/context-names.js +280 -0
- package/dist/plugins/state/context-names.js.map +1 -0
- package/dist/plugins/state/context.d.ts +0 -89
- package/dist/plugins/state/context.d.ts.map +1 -1
- package/dist/plugins/state/context.js +3 -474
- package/dist/plugins/state/context.js.map +1 -1
- package/dist/plugins/state/engine.d.ts +5 -0
- package/dist/plugins/state/engine.d.ts.map +1 -1
- package/dist/plugins/state/engine.js +12 -2
- package/dist/plugins/state/engine.js.map +1 -1
- package/dist/plugins/state/fibers.d.ts +75 -0
- package/dist/plugins/state/fibers.d.ts.map +1 -0
- package/dist/plugins/state/fibers.js +92 -0
- package/dist/plugins/state/fibers.js.map +1 -0
- package/dist/plugins/state/index.d.ts +5 -0
- package/dist/plugins/state/index.d.ts.map +1 -1
- package/dist/plugins/state/index.js.map +1 -1
- package/dist/plugins/state/mobx.d.ts +22 -0
- package/dist/plugins/state/mobx.d.ts.map +1 -0
- package/dist/plugins/state/mobx.js +69 -0
- package/dist/plugins/state/mobx.js.map +1 -0
- package/dist/plugins/state/react-hook.d.ts +19 -0
- package/dist/plugins/state/react-hook.d.ts.map +1 -0
- package/dist/plugins/state/react-hook.js +100 -0
- package/dist/plugins/state/react-hook.js.map +1 -0
- package/dist/plugins/state/redux.d.ts +2 -0
- package/dist/plugins/state/redux.d.ts.map +1 -1
- package/dist/plugins/state/redux.js +2 -2
- package/dist/plugins/state/redux.js.map +1 -1
- package/dist/plugins/state/xstate.d.ts +26 -0
- package/dist/plugins/state/xstate.d.ts.map +1 -0
- package/dist/plugins/state/xstate.js +85 -0
- package/dist/plugins/state/xstate.js.map +1 -0
- package/dist/plugins/storage.d.ts +1 -1
- package/dist/plugins/storage.d.ts.map +1 -1
- package/dist/plugins/storage.js +5 -7
- package/dist/plugins/storage.js.map +1 -1
- package/dist/serialize.d.ts.map +1 -1
- package/dist/serialize.js +1 -0
- package/dist/serialize.js.map +1 -1
- package/package.json +7 -5
- package/src/client.ts +19 -2
- package/src/index.ts +8 -2
- package/src/init.ts +66 -0
- package/src/plugins/console.ts +103 -10
- package/src/plugins/network/body.ts +114 -0
- package/src/plugins/network/failure.ts +79 -0
- package/src/plugins/network/fetch.ts +169 -0
- package/src/plugins/network/settings.ts +48 -0
- package/src/plugins/network/xhr.ts +223 -0
- package/src/plugins/network.ts +8 -572
- package/src/plugins/state/context-names.ts +265 -0
- package/src/plugins/state/context.ts +3 -532
- package/src/plugins/state/engine.ts +12 -2
- package/src/plugins/state/fibers.ts +160 -0
- package/src/plugins/state/index.ts +2 -0
- package/src/plugins/state/mobx.ts +80 -0
- package/src/plugins/state/react-hook.ts +98 -0
- package/src/plugins/state/redux.ts +2 -2
- package/src/plugins/state/xstate.ts +94 -0
- package/src/plugins/storage.ts +13 -8
- package/src/serialize.ts +2 -1
package/src/plugins/network.ts
CHANGED
|
@@ -1,42 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
import type { Plugin
|
|
3
|
-
import {
|
|
1
|
+
import { MAX_SOCKET_MESSAGE_SIZE } from '@capybara-devtools/protocol';
|
|
2
|
+
import type { Plugin } from '../client.js';
|
|
3
|
+
import { isXhrFetch, patchFetch } from './network/fetch.js';
|
|
4
|
+
import { resolveSettings, type NetworkPluginOptions } from './network/settings.js';
|
|
5
|
+
import { patchXhr } from './network/xhr.js';
|
|
4
6
|
import { hookWebSockets } from './websocket.js';
|
|
5
7
|
|
|
8
|
+
export type { NetworkPluginOptions } from './network/settings.js';
|
|
9
|
+
|
|
6
10
|
/** Vite's dev server channel. */
|
|
7
11
|
const DEV_TOOL_PROTOCOLS = ['vite-hmr', 'vite-ping'];
|
|
8
12
|
|
|
9
|
-
export interface NetworkPluginOptions {
|
|
10
|
-
/** Patch `fetch`. Where fetch runs on XHR (whatwg-fetch), its requests are recorded once, by the XHR patch, as fetch. */
|
|
11
|
-
fetch?: boolean;
|
|
12
|
-
xhr?: boolean;
|
|
13
|
-
/** Record WebSocket connections and their messages. Default true. */
|
|
14
|
-
websocket?: boolean;
|
|
15
|
-
/** Requests and WebSockets whose URL contains one of these strings or matches one of these patterns are not recorded. */
|
|
16
|
-
ignoreUrls?: Array<string | RegExp>;
|
|
17
|
-
/** Request and response bodies are cut after this many characters. Default 128 KiB. */
|
|
18
|
-
maxBodySize?: number;
|
|
19
|
-
/** WebSocket messages are cut after this many characters. Default 16 KiB. */
|
|
20
|
-
maxMessageSize?: number;
|
|
21
|
-
/** Header names (case-insensitive) whose values are replaced with "[redacted]". */
|
|
22
|
-
redactHeaders?: string[];
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
interface Settings {
|
|
26
|
-
maxBody: number;
|
|
27
|
-
isIgnored(url: string): boolean;
|
|
28
|
-
redact(headers: Record<string, string>): Record<string, string>;
|
|
29
|
-
failures: FailureExplainer;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
type Explanation = Pick<NetworkErrorPayload, 'cause' | 'credentials'> & { message?: string };
|
|
33
|
-
|
|
34
|
-
interface FailureExplainer {
|
|
35
|
-
/** Runs `report` once the cause can be told, which in a browser may be a moment after the failure. */
|
|
36
|
-
explain(url: string, credentials: boolean, report: (explanation: Explanation) => void): void;
|
|
37
|
-
stop(): void;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
13
|
export function networkPlugin(options: NetworkPluginOptions = {}): Plugin {
|
|
41
14
|
return {
|
|
42
15
|
name: 'network',
|
|
@@ -53,7 +26,7 @@ export function networkPlugin(options: NetworkPluginOptions = {}): Plugin {
|
|
|
53
26
|
typeof pattern === 'string' ? pattern : { source: pattern.source, flags: pattern.flags },
|
|
54
27
|
),
|
|
55
28
|
ignoreProtocols: DEV_TOOL_PROTOCOLS,
|
|
56
|
-
maxMessage: options.maxMessageSize ??
|
|
29
|
+
maxMessage: options.maxMessageSize ?? MAX_SOCKET_MESSAGE_SIZE,
|
|
57
30
|
}),
|
|
58
31
|
);
|
|
59
32
|
}
|
|
@@ -63,540 +36,3 @@ export function networkPlugin(options: NetworkPluginOptions = {}): Plugin {
|
|
|
63
36
|
},
|
|
64
37
|
};
|
|
65
38
|
}
|
|
66
|
-
|
|
67
|
-
function resolveSettings(options: NetworkPluginOptions): Settings {
|
|
68
|
-
const patterns = options.ignoreUrls ?? [];
|
|
69
|
-
const redacted = new Set((options.redactHeaders ?? []).map((name) => name.toLowerCase()));
|
|
70
|
-
return {
|
|
71
|
-
maxBody: options.maxBodySize ?? 128 * 1024,
|
|
72
|
-
isIgnored: (url) =>
|
|
73
|
-
patterns.some((pattern) => {
|
|
74
|
-
if (typeof pattern === 'string') return url.includes(pattern);
|
|
75
|
-
pattern.lastIndex = 0;
|
|
76
|
-
return pattern.test(url);
|
|
77
|
-
}),
|
|
78
|
-
redact: (headers) => {
|
|
79
|
-
if (redacted.size === 0) return headers;
|
|
80
|
-
const out: Record<string, string> = {};
|
|
81
|
-
for (const [name, value] of Object.entries(headers)) {
|
|
82
|
-
out[name] = redacted.has(name.toLowerCase()) ? '[redacted]' : value;
|
|
83
|
-
}
|
|
84
|
-
return out;
|
|
85
|
-
},
|
|
86
|
-
failures: failureExplainer(),
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Browsers never tell a page why a request failed. What a page can know: whether it is offline,
|
|
92
|
-
* whether the URL is mixed content, and CSP blocks, which arrive as `securitypolicyviolation`
|
|
93
|
-
* events. Anything else cross-origin is reported as such for the Capybara server to diagnose.
|
|
94
|
-
*/
|
|
95
|
-
function failureExplainer(): FailureExplainer {
|
|
96
|
-
const g = globalThis as {
|
|
97
|
-
location?: { href?: string; origin?: string; protocol?: string };
|
|
98
|
-
navigator?: { onLine?: boolean; product?: string; userAgent?: string };
|
|
99
|
-
document?: Pick<Document, 'addEventListener' | 'removeEventListener'>;
|
|
100
|
-
};
|
|
101
|
-
const page = g.location;
|
|
102
|
-
if (!page?.href || !page.origin || page.origin === 'null' || g.navigator?.product === 'ReactNative') {
|
|
103
|
-
return { explain: (_url, _credentials, report) => report({}), stop() {} };
|
|
104
|
-
}
|
|
105
|
-
const blocked: Array<{ origin: string; directive: string; at: number }> = [];
|
|
106
|
-
const onViolation = (event: Event) => {
|
|
107
|
-
const violation = event as SecurityPolicyViolationEvent;
|
|
108
|
-
const directive = violation.effectiveDirective || violation.violatedDirective || '';
|
|
109
|
-
if (!/^(connect-src|default-src)/.test(directive)) return;
|
|
110
|
-
try {
|
|
111
|
-
blocked.push({ origin: new URL(violation.blockedURI, page.href).origin, directive, at: now() });
|
|
112
|
-
if (blocked.length > 20) blocked.shift();
|
|
113
|
-
} catch {
|
|
114
|
-
// `inline` or `eval` violations carry no URL
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
g.document?.addEventListener('securitypolicyviolation', onViolation);
|
|
118
|
-
// Chromium lets https pages call local-network devices over http and gates them with its Local
|
|
119
|
-
// Network Access permission instead; other browsers block them as mixed content.
|
|
120
|
-
const chromium = /Chrom(e|ium)\//.test(g.navigator?.userAgent ?? '');
|
|
121
|
-
const classify = (url: string, credentials: boolean): Explanation => {
|
|
122
|
-
let target: URL;
|
|
123
|
-
try {
|
|
124
|
-
target = new URL(url, page.href);
|
|
125
|
-
} catch {
|
|
126
|
-
return {};
|
|
127
|
-
}
|
|
128
|
-
if (g.navigator?.onLine === false) return { cause: 'offline', message: 'The browser is offline' };
|
|
129
|
-
const csp = blocked.find((entry) => entry.origin === target.origin && now() - entry.at < 10_000);
|
|
130
|
-
if (csp) return { cause: 'csp', message: `Blocked by the page's Content-Security-Policy (${csp.directive})` };
|
|
131
|
-
const exempt = isTrustworthyHost(target.hostname) || (chromium && isLocalNetworkHost(target.hostname));
|
|
132
|
-
if (page.protocol === 'https:' && target.protocol === 'http:' && !exempt) {
|
|
133
|
-
return { cause: 'mixed-content', message: `Blocked as mixed content: an https page cannot call ${target.origin}` };
|
|
134
|
-
}
|
|
135
|
-
if (target.origin !== page.origin) return { cause: 'cross-origin', credentials: credentials || undefined };
|
|
136
|
-
return {};
|
|
137
|
-
};
|
|
138
|
-
return {
|
|
139
|
-
// The violation event can arrive after the request has already failed.
|
|
140
|
-
explain: (url, credentials, report) => void setTimeout(() => report(classify(url, credentials)), 30),
|
|
141
|
-
stop: () => g.document?.removeEventListener('securitypolicyviolation', onViolation),
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** Browsers let https pages call these over plain http. */
|
|
146
|
-
function isTrustworthyHost(hostname: string): boolean {
|
|
147
|
-
return hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '127.0.0.1' || hostname === '[::1]';
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** Private IP literals and .local names; a hostname that resolves to a private IP does not count. */
|
|
151
|
-
function isLocalNetworkHost(hostname: string): boolean {
|
|
152
|
-
if (hostname.endsWith('.local')) return true;
|
|
153
|
-
const ipv4 = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(hostname);
|
|
154
|
-
if (!ipv4) return /^\[(f[cd]|fe[89ab])/i.test(hostname);
|
|
155
|
-
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
|
156
|
-
return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// ---------------------------------------------------------------------------
|
|
160
|
-
// fetch
|
|
161
|
-
// ---------------------------------------------------------------------------
|
|
162
|
-
|
|
163
|
-
type FetchFunction = ((...args: unknown[]) => unknown) & { polyfill?: unknown };
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* whatwg-fetch marks itself `polyfill`. Bare React Native ships it as fetch, so every fetch is also an
|
|
167
|
-
* XHR there, and patching both would record each request twice. Expo swaps in a native fetch.
|
|
168
|
-
*/
|
|
169
|
-
function isXhrFetch(): boolean {
|
|
170
|
-
return (globalThis as { fetch?: FetchFunction }).fetch?.polyfill === true;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function patchFetch(ctx: PluginContext, settings: Settings): () => void {
|
|
174
|
-
const g = globalThis as { fetch?: typeof fetch };
|
|
175
|
-
const original = g.fetch;
|
|
176
|
-
if (typeof original !== 'function') return () => {};
|
|
177
|
-
|
|
178
|
-
const patched = function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
179
|
-
let request: ReturnType<typeof describeFetch>;
|
|
180
|
-
try {
|
|
181
|
-
request = describeFetch(input, init, settings.maxBody);
|
|
182
|
-
} catch {
|
|
183
|
-
return original.call(globalThis, input, init);
|
|
184
|
-
}
|
|
185
|
-
if (settings.isIgnored(request.url)) return original.call(globalThis, input, init);
|
|
186
|
-
|
|
187
|
-
const id = randomId();
|
|
188
|
-
const start = now();
|
|
189
|
-
ctx.emit('network.request', {
|
|
190
|
-
id,
|
|
191
|
-
initiator: 'fetch',
|
|
192
|
-
method: request.method,
|
|
193
|
-
url: request.url,
|
|
194
|
-
headers: settings.redact(request.headers),
|
|
195
|
-
body: request.body,
|
|
196
|
-
});
|
|
197
|
-
|
|
198
|
-
let promise: Promise<Response>;
|
|
199
|
-
try {
|
|
200
|
-
promise = original.call(globalThis, input, init);
|
|
201
|
-
} catch (error) {
|
|
202
|
-
ctx.emit('network.error', { id, message: errorMessage(error), duration: now() - start });
|
|
203
|
-
throw error;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Registered before the caller gets the promise, so the response is cloned before app code can read it.
|
|
207
|
-
promise.then(
|
|
208
|
-
(response) => {
|
|
209
|
-
try {
|
|
210
|
-
const duration = now() - start;
|
|
211
|
-
const headers = settings.redact(headersToRecord(response.headers));
|
|
212
|
-
const done = (body?: BodyPreview) =>
|
|
213
|
-
ctx.emit('network.response', {
|
|
214
|
-
id,
|
|
215
|
-
status: response.status,
|
|
216
|
-
statusText: response.statusText || undefined,
|
|
217
|
-
headers,
|
|
218
|
-
body,
|
|
219
|
-
duration,
|
|
220
|
-
});
|
|
221
|
-
readFetchBody(response, settings.maxBody).then(done, () => done());
|
|
222
|
-
} catch {
|
|
223
|
-
// never surface SDK failures to the app
|
|
224
|
-
}
|
|
225
|
-
},
|
|
226
|
-
(error: unknown) => {
|
|
227
|
-
const duration = now() - start;
|
|
228
|
-
const aborted = (error as { name?: string } | null)?.name === 'AbortError';
|
|
229
|
-
const fail = (explanation: Explanation) =>
|
|
230
|
-
ctx.emit('network.error', { id, duration, aborted, ...explanation, message: explanation.message ?? errorMessage(error) });
|
|
231
|
-
if (aborted) fail({});
|
|
232
|
-
else settings.failures.explain(request.url, request.credentials, fail);
|
|
233
|
-
},
|
|
234
|
-
);
|
|
235
|
-
return promise;
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
g.fetch = patched as typeof fetch;
|
|
239
|
-
return () => {
|
|
240
|
-
if (g.fetch === patched) g.fetch = original;
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
function describeFetch(input: RequestInfo | URL, init: RequestInit | undefined, maxBody: number) {
|
|
245
|
-
const RequestCtor = (globalThis as { Request?: typeof Request }).Request;
|
|
246
|
-
const request = RequestCtor && input instanceof RequestCtor ? input : undefined;
|
|
247
|
-
const url = request ? request.url : String((input as { href?: string }).href ?? input);
|
|
248
|
-
const method = String(init?.method ?? request?.method ?? 'GET').toUpperCase();
|
|
249
|
-
const headers = { ...(request ? headersToRecord(request.headers) : {}), ...headersToRecord(init?.headers) };
|
|
250
|
-
let body: BodyPreview | undefined;
|
|
251
|
-
if (init?.body !== undefined && init.body !== null) {
|
|
252
|
-
body = previewRequestBody(init.body, maxBody, findHeader(headers, 'content-type'));
|
|
253
|
-
} else if (request?.body) {
|
|
254
|
-
body = { kind: 'stream', summary: 'Request body (not captured)' };
|
|
255
|
-
}
|
|
256
|
-
const credentials = (init?.credentials ?? request?.credentials) === 'include';
|
|
257
|
-
return { url: absoluteUrl(url), method, headers, body, credentials };
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
async function readFetchBody(response: Response, maxBody: number): Promise<BodyPreview | undefined> {
|
|
261
|
-
const contentType = response.headers.get('content-type') ?? undefined;
|
|
262
|
-
const declared = Number(response.headers.get('content-length') ?? Number.NaN);
|
|
263
|
-
const size = Number.isFinite(declared) ? declared : undefined;
|
|
264
|
-
if (!response.body) return undefined;
|
|
265
|
-
if (contentType && /^text\/event-stream/i.test(contentType)) {
|
|
266
|
-
return { kind: 'stream', contentType, summary: 'Event stream' };
|
|
267
|
-
}
|
|
268
|
-
if (!isTextual(contentType)) return { kind: 'binary', contentType, size, summary: contentType ?? 'Binary' };
|
|
269
|
-
if (typeof TextDecoder === 'undefined') return textPreview(await response.clone().text(), maxBody, contentType);
|
|
270
|
-
|
|
271
|
-
// Read only up to the limit, then cancel our branch; the app's branch of the tee is unaffected.
|
|
272
|
-
const reader = response.clone().body!.getReader();
|
|
273
|
-
const decoder = new TextDecoder();
|
|
274
|
-
let text = '';
|
|
275
|
-
let bytes = 0;
|
|
276
|
-
let truncated = false;
|
|
277
|
-
try {
|
|
278
|
-
for (;;) {
|
|
279
|
-
const { done, value } = await reader.read();
|
|
280
|
-
if (done) break;
|
|
281
|
-
bytes += value.byteLength;
|
|
282
|
-
text += decoder.decode(value, { stream: true });
|
|
283
|
-
if (text.length > maxBody) {
|
|
284
|
-
truncated = true;
|
|
285
|
-
break;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if (!truncated) text += decoder.decode();
|
|
289
|
-
} finally {
|
|
290
|
-
if (truncated) reader.cancel().catch(() => {});
|
|
291
|
-
}
|
|
292
|
-
return {
|
|
293
|
-
kind: 'text',
|
|
294
|
-
text: truncated ? text.slice(0, maxBody) : text,
|
|
295
|
-
size: truncated ? size : bytes,
|
|
296
|
-
truncated,
|
|
297
|
-
contentType,
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// ---------------------------------------------------------------------------
|
|
302
|
-
// XMLHttpRequest
|
|
303
|
-
// ---------------------------------------------------------------------------
|
|
304
|
-
|
|
305
|
-
interface XhrInfo {
|
|
306
|
-
method: string;
|
|
307
|
-
url: string;
|
|
308
|
-
headers: Record<string, string>;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function patchXhr(ctx: PluginContext, settings: Settings, fetchOverXhr: boolean): () => void {
|
|
312
|
-
const XHR = (globalThis as { XMLHttpRequest?: { prototype: XMLHttpRequest } }).XMLHttpRequest;
|
|
313
|
-
if (!XHR?.prototype) return () => {};
|
|
314
|
-
const proto = XHR.prototype;
|
|
315
|
-
const g = globalThis as { fetch?: FetchFunction };
|
|
316
|
-
// whatwg-fetch opens and sends its XHR inside the fetch call, so XHRs sent meanwhile are the fetch.
|
|
317
|
-
let fetching = 0;
|
|
318
|
-
const originalFetch = fetchOverXhr ? g.fetch : undefined;
|
|
319
|
-
const taggedFetch: FetchFunction | undefined = originalFetch
|
|
320
|
-
? Object.assign(
|
|
321
|
-
function fetch(this: unknown) {
|
|
322
|
-
fetching++;
|
|
323
|
-
try {
|
|
324
|
-
return originalFetch.apply(this, arguments as unknown as unknown[]);
|
|
325
|
-
} finally {
|
|
326
|
-
fetching--;
|
|
327
|
-
}
|
|
328
|
-
},
|
|
329
|
-
{ polyfill: originalFetch.polyfill },
|
|
330
|
-
)
|
|
331
|
-
: undefined;
|
|
332
|
-
if (taggedFetch) g.fetch = taggedFetch;
|
|
333
|
-
const originalOpen = proto.open;
|
|
334
|
-
const originalSend = proto.send;
|
|
335
|
-
const originalSetRequestHeader = proto.setRequestHeader;
|
|
336
|
-
const requests = new WeakMap<XMLHttpRequest, XhrInfo>();
|
|
337
|
-
// React Native hands the native reason for a failure (e.g. "Unable to resolve host …") to this
|
|
338
|
-
// internal method. It reaches responseText only for text responses, and whatwg-fetch asks for blobs.
|
|
339
|
-
const nativeErrors = new WeakMap<XMLHttpRequest, string>();
|
|
340
|
-
const internals = proto as unknown as Record<string, unknown>;
|
|
341
|
-
const originalComplete = internals.__didCompleteResponse;
|
|
342
|
-
if (typeof originalComplete === 'function') {
|
|
343
|
-
internals.__didCompleteResponse = function (this: XMLHttpRequest, _requestId: unknown, error: unknown) {
|
|
344
|
-
if (typeof error === 'string' && error) nativeErrors.set(this, error);
|
|
345
|
-
return (originalComplete as (...args: unknown[]) => unknown).apply(this, arguments as unknown as unknown[]);
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
const track = (xhr: XMLHttpRequest, info: XhrInfo, body: unknown) => {
|
|
350
|
-
const id = randomId();
|
|
351
|
-
const start = now();
|
|
352
|
-
ctx.emit('network.request', {
|
|
353
|
-
id,
|
|
354
|
-
initiator: fetching > 0 ? 'fetch' : 'xhr',
|
|
355
|
-
method: info.method,
|
|
356
|
-
url: absoluteUrl(info.url),
|
|
357
|
-
headers: settings.redact(info.headers),
|
|
358
|
-
body: previewRequestBody(body, settings.maxBody, findHeader(info.headers, 'content-type')),
|
|
359
|
-
});
|
|
360
|
-
|
|
361
|
-
let failure: 'error' | 'timeout' | 'abort' | undefined;
|
|
362
|
-
xhr.addEventListener('error', () => (failure = 'error'));
|
|
363
|
-
xhr.addEventListener('timeout', () => (failure = 'timeout'));
|
|
364
|
-
xhr.addEventListener('abort', () => (failure = 'abort'));
|
|
365
|
-
xhr.addEventListener('loadend', () => {
|
|
366
|
-
const duration = now() - start;
|
|
367
|
-
try {
|
|
368
|
-
if (failure || xhr.status === 0) {
|
|
369
|
-
const base = { id, duration, aborted: failure === 'abort', timeout: failure === 'timeout' };
|
|
370
|
-
if (failure === 'timeout' || failure === 'abort') {
|
|
371
|
-
ctx.emit('network.error', { ...base, message: failure === 'timeout' ? 'Request timed out' : 'Request aborted' });
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
const native = nativeErrors.get(xhr);
|
|
375
|
-
if (native) {
|
|
376
|
-
ctx.emit('network.error', { ...base, message: native });
|
|
377
|
-
return;
|
|
378
|
-
}
|
|
379
|
-
settings.failures.explain(absoluteUrl(info.url), xhr.withCredentials === true, (explanation) =>
|
|
380
|
-
ctx.emit('network.error', { ...base, ...explanation, message: explanation.message ?? 'Network request failed' }),
|
|
381
|
-
);
|
|
382
|
-
return;
|
|
383
|
-
}
|
|
384
|
-
const headers = parseRawHeaders(xhr.getAllResponseHeaders());
|
|
385
|
-
const done = (responseBody?: BodyPreview) =>
|
|
386
|
-
ctx.emit('network.response', {
|
|
387
|
-
id,
|
|
388
|
-
status: xhr.status,
|
|
389
|
-
statusText: xhr.statusText || undefined,
|
|
390
|
-
headers: settings.redact(headers),
|
|
391
|
-
body: responseBody,
|
|
392
|
-
duration,
|
|
393
|
-
});
|
|
394
|
-
const result = readXhrBody(xhr, findHeader(headers, 'content-type'), settings.maxBody);
|
|
395
|
-
if (result && typeof (result as Promise<unknown>).then === 'function') {
|
|
396
|
-
(result as Promise<BodyPreview | undefined>).then(done, () => done());
|
|
397
|
-
} else {
|
|
398
|
-
done(result as BodyPreview | undefined);
|
|
399
|
-
}
|
|
400
|
-
} catch {
|
|
401
|
-
// never surface SDK failures to the app
|
|
402
|
-
}
|
|
403
|
-
});
|
|
404
|
-
};
|
|
405
|
-
|
|
406
|
-
proto.open = function open(this: XMLHttpRequest, method: string, url: string | URL) {
|
|
407
|
-
requests.set(this, { method: String(method).toUpperCase(), url: String(url), headers: {} });
|
|
408
|
-
nativeErrors.delete(this);
|
|
409
|
-
// `arguments` keeps the caller's exact arity; some engines treat an explicit `undefined` async flag as false.
|
|
410
|
-
return (originalOpen as (...args: unknown[]) => void).apply(this, arguments as unknown as unknown[]);
|
|
411
|
-
} as XMLHttpRequest['open'];
|
|
412
|
-
|
|
413
|
-
proto.setRequestHeader = function setRequestHeader(this: XMLHttpRequest, name: string, value: string) {
|
|
414
|
-
const info = requests.get(this);
|
|
415
|
-
if (info) info.headers[name] = name in info.headers ? `${info.headers[name]}, ${value}` : String(value);
|
|
416
|
-
return originalSetRequestHeader.call(this, name, value);
|
|
417
|
-
};
|
|
418
|
-
|
|
419
|
-
proto.send = function send(this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null) {
|
|
420
|
-
const info = requests.get(this);
|
|
421
|
-
if (info && !settings.isIgnored(info.url)) {
|
|
422
|
-
try {
|
|
423
|
-
track(this, info, body);
|
|
424
|
-
} catch {
|
|
425
|
-
// never surface SDK failures to the app
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
return originalSend.call(this, body);
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
return () => {
|
|
432
|
-
proto.open = originalOpen;
|
|
433
|
-
proto.send = originalSend;
|
|
434
|
-
proto.setRequestHeader = originalSetRequestHeader;
|
|
435
|
-
if (typeof originalComplete === 'function') internals.__didCompleteResponse = originalComplete;
|
|
436
|
-
if (taggedFetch && g.fetch === taggedFetch) g.fetch = originalFetch;
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
function readXhrBody(
|
|
441
|
-
xhr: XMLHttpRequest,
|
|
442
|
-
contentType: string | undefined,
|
|
443
|
-
maxBody: number,
|
|
444
|
-
): BodyPreview | undefined | Promise<BodyPreview | undefined> {
|
|
445
|
-
const type = xhr.responseType;
|
|
446
|
-
if (type === '' || type === 'text') {
|
|
447
|
-
const text = xhr.responseText;
|
|
448
|
-
return text ? textPreview(text, maxBody, contentType) : undefined;
|
|
449
|
-
}
|
|
450
|
-
const response: unknown = xhr.response;
|
|
451
|
-
if (response === null || response === undefined) return undefined;
|
|
452
|
-
if (type === 'json') {
|
|
453
|
-
try {
|
|
454
|
-
return textPreview(JSON.stringify(response), maxBody, contentType);
|
|
455
|
-
} catch {
|
|
456
|
-
return { kind: 'unknown', contentType, summary: 'JSON' };
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
if (type === 'blob') {
|
|
460
|
-
// React Native's fetch polyfill always asks XHR for a blob.
|
|
461
|
-
const blob = response as Blob;
|
|
462
|
-
if (!isTextual(contentType)) return { kind: 'binary', size: blob.size, contentType, summary: contentType ?? 'Blob' };
|
|
463
|
-
const truncated = blob.size > maxBody;
|
|
464
|
-
return readBlobText(truncated ? blob.slice(0, maxBody) : blob).then(
|
|
465
|
-
(text): BodyPreview => ({ kind: 'text', text, size: blob.size, truncated, contentType }),
|
|
466
|
-
);
|
|
467
|
-
}
|
|
468
|
-
if (type === 'arraybuffer') {
|
|
469
|
-
const buffer = response as ArrayBuffer;
|
|
470
|
-
if (isTextual(contentType) && typeof TextDecoder !== 'undefined') {
|
|
471
|
-
const truncated = buffer.byteLength > maxBody;
|
|
472
|
-
const text = new TextDecoder().decode(truncated ? buffer.slice(0, maxBody) : buffer);
|
|
473
|
-
return { kind: 'text', text, size: buffer.byteLength, truncated, contentType };
|
|
474
|
-
}
|
|
475
|
-
return { kind: 'binary', size: buffer.byteLength, contentType, summary: contentType ?? 'ArrayBuffer' };
|
|
476
|
-
}
|
|
477
|
-
return { kind: 'unknown', contentType, summary: `responseType "${type}"` };
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
function readBlobText(blob: Blob): Promise<string> {
|
|
481
|
-
if (typeof blob.text === 'function') return blob.text();
|
|
482
|
-
return new Promise((resolve, reject) => {
|
|
483
|
-
const reader = new FileReader();
|
|
484
|
-
reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
|
|
485
|
-
reader.onerror = () => reject(reader.error ?? new Error('Failed to read blob'));
|
|
486
|
-
reader.readAsText(blob);
|
|
487
|
-
});
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
// ---------------------------------------------------------------------------
|
|
491
|
-
// Helpers
|
|
492
|
-
// ---------------------------------------------------------------------------
|
|
493
|
-
|
|
494
|
-
const TEXTUAL =
|
|
495
|
-
/^(text\/|application\/([\w.+-]*\+)?(json|xml|javascript|ecmascript|x-www-form-urlencoded|graphql|x-ndjson)\b)/i;
|
|
496
|
-
|
|
497
|
-
function isTextual(contentType: string | undefined): boolean {
|
|
498
|
-
return !contentType || TEXTUAL.test(contentType.trim());
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
function textPreview(text: string, maxBody: number, contentType?: string, kind: 'text' | 'form' = 'text'): BodyPreview {
|
|
502
|
-
const truncated = text.length > maxBody;
|
|
503
|
-
return { kind, text: truncated ? text.slice(0, maxBody) : text, size: utf8Length(text), truncated, contentType };
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
function previewRequestBody(body: unknown, maxBody: number, contentType?: string): BodyPreview | undefined {
|
|
507
|
-
if (body === undefined || body === null) return undefined;
|
|
508
|
-
if (typeof body === 'string') return textPreview(body, maxBody, contentType);
|
|
509
|
-
const g = globalThis as Record<string, any>;
|
|
510
|
-
if (g.URLSearchParams && body instanceof g.URLSearchParams) {
|
|
511
|
-
return textPreview(String(body), maxBody, contentType ?? 'application/x-www-form-urlencoded');
|
|
512
|
-
}
|
|
513
|
-
if (g.FormData && body instanceof g.FormData) return formPreview(body, maxBody);
|
|
514
|
-
if (g.Blob && body instanceof g.Blob) {
|
|
515
|
-
const blob = body as Blob;
|
|
516
|
-
return { kind: 'binary', size: blob.size, contentType: blob.type || contentType, summary: blob.type ? `Blob (${blob.type})` : 'Blob' };
|
|
517
|
-
}
|
|
518
|
-
if (body instanceof ArrayBuffer) return { kind: 'binary', size: body.byteLength, contentType, summary: 'ArrayBuffer' };
|
|
519
|
-
if (ArrayBuffer.isView(body)) {
|
|
520
|
-
return { kind: 'binary', size: body.byteLength, contentType, summary: body.constructor?.name ?? 'TypedArray' };
|
|
521
|
-
}
|
|
522
|
-
if (g.ReadableStream && body instanceof g.ReadableStream) return { kind: 'stream', contentType, summary: 'ReadableStream' };
|
|
523
|
-
return { kind: 'unknown', contentType, summary: Object.prototype.toString.call(body) };
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
interface ReactNativeFormPart {
|
|
527
|
-
fieldName: string;
|
|
528
|
-
string?: string;
|
|
529
|
-
uri?: string;
|
|
530
|
-
name?: string;
|
|
531
|
-
type?: string;
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
function formPreview(form: unknown, maxBody: number): BodyPreview {
|
|
535
|
-
const lines: string[] = [];
|
|
536
|
-
const browserForm = form as { entries?: () => Iterable<[string, unknown]> };
|
|
537
|
-
const nativeForm = form as { getParts?: () => ReactNativeFormPart[] };
|
|
538
|
-
if (typeof browserForm.entries === 'function') {
|
|
539
|
-
for (const [name, value] of browserForm.entries()) lines.push(`${name}=${describeFormValue(value)}`);
|
|
540
|
-
} else if (typeof nativeForm.getParts === 'function') {
|
|
541
|
-
// React Native's FormData has no entries().
|
|
542
|
-
for (const part of nativeForm.getParts()) {
|
|
543
|
-
const value =
|
|
544
|
-
part.string !== undefined ? part.string : `[file ${part.name ?? part.uri ?? ''}${part.type ? `, ${part.type}` : ''}]`;
|
|
545
|
-
lines.push(`${part.fieldName}=${value}`);
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
return textPreview(lines.join('\n'), maxBody, 'multipart/form-data', 'form');
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
function describeFormValue(value: unknown): string {
|
|
552
|
-
if (typeof value === 'string') return value;
|
|
553
|
-
const file = value as { name?: string; size?: number; type?: string };
|
|
554
|
-
return `[file ${file.name ?? 'blob'}${file.type ? `, ${file.type}` : ''}${file.size !== undefined ? `, ${file.size} B` : ''}]`;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
function headersToRecord(headers: unknown): Record<string, string> {
|
|
558
|
-
const out: Record<string, string> = {};
|
|
559
|
-
if (!headers) return out;
|
|
560
|
-
const add = (name: string, value: string) => {
|
|
561
|
-
out[name] = name in out ? `${out[name]}, ${value}` : value;
|
|
562
|
-
};
|
|
563
|
-
if (Array.isArray(headers)) {
|
|
564
|
-
for (const pair of headers) if (Array.isArray(pair) && pair.length >= 2) add(String(pair[0]), String(pair[1]));
|
|
565
|
-
} else if (typeof (headers as Headers).forEach === 'function') {
|
|
566
|
-
(headers as Headers).forEach((value, name) => add(name, value));
|
|
567
|
-
} else if (typeof headers === 'object') {
|
|
568
|
-
for (const [name, value] of Object.entries(headers as Record<string, unknown>)) {
|
|
569
|
-
if (value !== undefined) add(name, String(value));
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
return out;
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
function parseRawHeaders(raw: string | null | undefined): Record<string, string> {
|
|
576
|
-
const out: Record<string, string> = {};
|
|
577
|
-
if (!raw) return out;
|
|
578
|
-
for (const line of raw.split(/\r?\n/)) {
|
|
579
|
-
const index = line.indexOf(':');
|
|
580
|
-
if (index <= 0) continue;
|
|
581
|
-
const name = line.slice(0, index).trim().toLowerCase();
|
|
582
|
-
const value = line.slice(index + 1).trim();
|
|
583
|
-
out[name] = name in out ? `${out[name]}, ${value}` : value;
|
|
584
|
-
}
|
|
585
|
-
return out;
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
function findHeader(headers: Record<string, string>, name: string): string | undefined {
|
|
589
|
-
const target = name.toLowerCase();
|
|
590
|
-
for (const key of Object.keys(headers)) if (key.toLowerCase() === target) return headers[key];
|
|
591
|
-
return undefined;
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
function absoluteUrl(url: string): string {
|
|
595
|
-
const base = (globalThis as { location?: { href?: string } }).location?.href;
|
|
596
|
-
if (!base || /^[a-z][a-z\d+.-]*:/i.test(url)) return url;
|
|
597
|
-
try {
|
|
598
|
-
return new URL(url, base).href;
|
|
599
|
-
} catch {
|
|
600
|
-
return url;
|
|
601
|
-
}
|
|
602
|
-
}
|