Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -726,11 +726,13 @@ in the DevTools Elements panel (if any).

### `mock_network`

**Description:** Inspect or update network mocks for a page. With no actions, list mocks matching the supplied filters, or all mocks when no filters are given. Providing body or upstream updates the exact route/resourceType pair. An omitted route matches any URL. Other mocks are preserved. The most recently updated matching mock wins and persists across navigations. Configure before navigating or reloading; inspection shows hit counts and replacement errors. Upstream responses use server-side GET/HEAD fetches. Changes are rejected during a performance trace. Mocks disable the page HTTP cache and intercept every request, affecting measurements. Service workers can bypass mocks. Use [`remove_network_mock`](#remove_network_mock) to remove mocks. (requires flag: --categoryNetworkMocks=true)
**Description:** Inspect or update network mocks for a page. With no actions, list mocks matching the supplied filters, or all mocks when no filters are given. Providing abort (including false), allowOrigin, body, or upstream updates the exact route/resourceType pair; omitted actions keep existing settings. Remove and recreate a mock to clear its source or allowOrigin. An omitted route matches any URL. Other mocks are preserved. abort=true suppresses its response and allowOrigin header. The most recently updated matching mock wins and persists across navigations. Configure before navigating or reloading; inspection shows hit counts and replacement errors. allowOrigin requires a body or upstream source. Upstream responses use server-side GET/HEAD fetches. Changes are rejected during a performance trace. Mocks disable the page HTTP cache and intercept every request, affecting measurements. Service workers can bypass mocks. Use [`remove_network_mock`](#remove_network_mock) to remove mocks. (requires flag: --categoryNetworkMocks=true)

**Parameters:**

- **pageId** (number) **(required)**: Targets a specific page by ID.
- **abort** (boolean) _(optional)_: Abort matching requests when true. When false, use the stored body or upstream source, or send the request to the network if neither is set. A mock without a source still wins over older matching mocks. Abortion takes precedence over body, upstream, and allowOrigin.
- **allowOrigin** (string) _(optional)_: Set the Access-Control-Allow-Origin response header to `*`, `null`, or a serialized origin such as https://example.com. Requires body or upstream, either supplied now or already set on the mock. This does not configure preflight or credential headers.
- **body** (string) _(optional)_: Local response body file, revalidated and reread for every request. Content-Type follows its extension. Mutually exclusive with upstream.
- **resourceType** (enum: "document", "stylesheet", "image", "media", "font", "script", "texttrack", "xhr", "fetch", "prefetch", "eventsource", "manifest", "signedexchange", "ping", "cspviolationreport", "preflight", "fedcm", "other") _(optional)_: Restrict requests and stored mock filters to this resource type. Omit to inspect/remove all types or configure a mock for any type.
- **route** (string) _(optional)_: Absolute URLPattern, e.g. https://example.com/app.js or `*://*:*/app.js`. Use `*` for wildcards; omitted query strings match any query. Regex and `:name` groups are rejected. Inspection and removal compare the stored pattern exactly. Omit to inspect/remove all routes or match any URL.
Expand Down
87 changes: 70 additions & 17 deletions src/NetworkOverrideManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,20 @@ import {logger, redactUrlForLogging} from './utils/logger.js';
interface BaseNetworkOverride {
urlPattern: string;
resourceType?: ResourceType;
abort?: boolean;
allowOrigin?: string;
}

export interface NetworkMockFilter {
urlPattern?: string;
resourceType?: ResourceType;
}

interface NetworkMockActions {
abort?: boolean;
allowOrigin?: string;
}

export interface UpstreamNetworkOverrideInput extends NetworkMockFilter {
kind: 'upstream';
upstreamUrl: string;
Expand All @@ -44,8 +51,12 @@ export interface FileNetworkOverrideInput extends NetworkMockFilter {
loadResponseFile: () => Promise<Uint8Array<ArrayBufferLike>>;
}

export type NetworkMockInput =
UpstreamNetworkOverrideInput | FileNetworkOverrideInput;
export type NetworkMockInput = NetworkMockActions &
(
| UpstreamNetworkOverrideInput
| FileNetworkOverrideInput
| (NetworkMockFilter & {kind?: undefined})
);

interface NetworkOverrideBase extends BaseNetworkOverride {
id: number;
Expand All @@ -68,7 +79,12 @@ export interface FileNetworkOverride extends NetworkOverrideBase {
contentType: string;
}

export type NetworkOverride = UpstreamNetworkOverride | FileNetworkOverride;
export interface PassthroughNetworkOverride extends NetworkOverrideBase {
kind: 'passthrough';
}

export type NetworkOverride =
UpstreamNetworkOverride | FileNetworkOverride | PassthroughNetworkOverride;

interface StoredNetworkOverrideBase extends NetworkOverrideBase {
matcher: URLPattern;
Expand All @@ -87,7 +103,9 @@ interface StoredFileNetworkOverride extends StoredNetworkOverrideBase {
}

type StoredNetworkOverride =
StoredUpstreamNetworkOverride | StoredFileNetworkOverride;
| StoredUpstreamNetworkOverride
| StoredFileNetworkOverride
| (StoredNetworkOverrideBase & {kind: 'passthrough'});

const DEFAULT_URL_PATTERN = '*://*:*/*';

Expand Down Expand Up @@ -122,6 +140,8 @@ function toNetworkOverride(override: StoredNetworkOverride): NetworkOverride {
id: override.id,
urlPattern: override.urlPattern,
resourceType: override.resourceType,
abort: override.abort,
allowOrigin: override.allowOrigin,
diagnostics: {...override.diagnostics},
};
if (override.kind === 'upstream') {
Expand All @@ -131,6 +151,9 @@ function toNetworkOverride(override: StoredNetworkOverride): NetworkOverride {
upstreamUrl: override.upstreamUrl,
};
}
if (override.kind === 'passthrough') {
return {...base, kind: override.kind};
}
return {
...base,
kind: override.kind,
Expand Down Expand Up @@ -212,6 +235,8 @@ export class NetworkOverrideManager {
id: existing?.id ?? this.#nextId,
urlPattern,
resourceType: input.resourceType,
abort: input.abort ?? existing?.abort ?? false,
allowOrigin: input.allowOrigin ?? existing?.allowOrigin,
matcher: new URLPattern(urlPattern),
diagnostics: {hits: 0, errors: 0, navigations: 0},
};
Expand All @@ -223,16 +248,26 @@ export class NetworkOverrideManager {
upstreamUrl: input.upstreamUrl,
};
}

await input.loadResponseFile();
return {
...base,
kind: input.kind,
responseFilePath: input.responseFilePath,
contentType:
input.contentType ?? inferContentType(input.responseFilePath),
loadResponseFile: input.loadResponseFile,
};
if (input.kind === 'file') {
await input.loadResponseFile();
return {
...base,
kind: input.kind,
responseFilePath: input.responseFilePath,
contentType:
input.contentType ?? inferContentType(input.responseFilePath),
loadResponseFile: input.loadResponseFile,
};
}
if (
base.allowOrigin !== undefined &&
(!existing || existing.kind === 'passthrough')
) {
throw new Error(
'allowOrigin requires a body or upstream source on the mock.',
);
}
return existing ? {...existing, ...base} : {...base, kind: 'passthrough'};
}

list(filter: NetworkMockFilter = {}): NetworkOverride[] {
Expand Down Expand Up @@ -390,18 +425,32 @@ export class NetworkOverrideManager {
}

override.diagnostics.hits++;
if (override.abort) {
await this.#abortRequest(request);
return;
}
if (override.kind === 'passthrough') {
await this.#continueRequest(request);
return;
}
try {
if (override.kind === 'upstream') {
await this.#fulfillUpstream(request, override.upstreamUrl);
await this.#fulfillUpstream(
request,
override.upstreamUrl,
override.allowOrigin,
);
return;
}

const body = await override.loadResponseFile();
await request.respond({
status: 200,
contentType: override.contentType,
headers: {
'Cache-Control': 'no-store',
...(override.allowOrigin !== undefined
? {'Access-Control-Allow-Origin': override.allowOrigin}
: {}),
},
body,
});
Expand Down Expand Up @@ -434,6 +483,7 @@ export class NetworkOverrideManager {
async #fulfillUpstream(
request: HTTPRequest,
upstreamUrl: string,
allowOrigin?: string,
): Promise<void> {
const method = request.method();
if (method !== 'GET' && method !== 'HEAD') {
Expand Down Expand Up @@ -463,6 +513,9 @@ export class NetworkOverrideManager {
if (cookies.length > 0) {
responseHeaders['set-cookie'] = cookies;
}
if (allowOrigin !== undefined) {
responseHeaders['access-control-allow-origin'] = allowOrigin;
}
await request.respond({
status: response.status,
headers: responseHeaders,
Expand All @@ -488,7 +541,7 @@ export class NetworkOverrideManager {
try {
await request.abort('failed');
} catch (error) {
logger?.('Failed to abort a request after a network mock error', error);
logger?.('Failed to abort an intercepted network request', error);
}
}
}
18 changes: 17 additions & 1 deletion src/config/cli-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1479,7 +1479,7 @@ export const commands: Commands = {
},
mock_network: {
description:
'Inspect or update network mocks for a page. With no actions, list mocks matching the supplied filters, or all mocks when no filters are given. Providing body or upstream updates the exact route/resourceType pair. An omitted route matches any URL. Other mocks are preserved. The most recently updated matching mock wins and persists across navigations. Configure before navigating or reloading; inspection shows hit counts and replacement errors. Upstream responses use server-side GET/HEAD fetches. Changes are rejected during a performance trace. Mocks disable the page HTTP cache and intercept every request, affecting measurements. Service workers can bypass mocks. Use remove_network_mock to remove mocks. (requires flag: --categoryNetworkMocks=true)',
'Inspect or update network mocks for a page. With no actions, list mocks matching the supplied filters, or all mocks when no filters are given. Providing abort (including false), allowOrigin, body, or upstream updates the exact route/resourceType pair; omitted actions keep existing settings. Remove and recreate a mock to clear its source or allowOrigin. An omitted route matches any URL. Other mocks are preserved. abort=true suppresses its response and allowOrigin header. The most recently updated matching mock wins and persists across navigations. Configure before navigating or reloading; inspection shows hit counts and replacement errors. allowOrigin requires a body or upstream source. Upstream responses use server-side GET/HEAD fetches. Changes are rejected during a performance trace. Mocks disable the page HTTP cache and intercept every request, affecting measurements. Service workers can bypass mocks. Use remove_network_mock to remove mocks. (requires flag: --categoryNetworkMocks=true)',
category: 'Network mocks',
args: {
pageId: {
Expand Down Expand Up @@ -1525,6 +1525,22 @@ export const commands: Commands = {
'other',
],
},
abort: {
name: 'abort',
type: 'boolean',
description:
'Abort matching requests when true. When false, use the stored body or upstream source, or send the request to the network if neither is set. A mock without a source still wins over older matching mocks. Abortion takes precedence over body, upstream, and allowOrigin.',
required: false,
positional: false,
},
allowOrigin: {
name: 'allowOrigin',
type: 'string',
description:
'Set the Access-Control-Allow-Origin response header to `*`, `null`, or a serialized origin such as https://example.com. Requires body or upstream, either supplied now or already set on the mock. This does not configure preflight or credential headers.',
required: false,
positional: false,
},
body: {
name: 'body',
type: 'string',
Expand Down
10 changes: 9 additions & 1 deletion src/formatters/NetworkOverridesFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,19 @@ export class NetworkOverridesFormatter {
const source =
override.kind === 'file'
? override.responseFilePath + ' (' + override.contentType + ')'
: override.upstreamUrl;
: override.kind === 'upstream'
? override.upstreamUrl
: 'original response';
const resourceType = override.resourceType
? ' [' + override.resourceType + ']'
: '';
lines.push(override.urlPattern + resourceType + ' -> ' + source);
if (override.abort) {
lines.push(' Requests are aborted; the response source is ignored.');
}
if (override.allowOrigin !== undefined) {
lines.push(' Access-Control-Allow-Origin: ' + override.allowOrigin);
}
const {hits, errors, navigations, lastError} = override.diagnostics;
lines.push(
' Since configured: ' + hits + ' hits, ' + errors + ' errors.',
Expand Down
8 changes: 8 additions & 0 deletions src/telemetry/tool_call_metrics.json
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,14 @@
{
"name": "upstream_length",
"argType": "number"
},
{
"name": "abort",
"argType": "boolean"
},
{
"name": "allow_origin_length",
"argType": "number"
}
]
},
Expand Down
81 changes: 60 additions & 21 deletions src/tools/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@ const mockNetworkSchema = zod
// eslint-disable-next-line @local/enforce-zod-schema -- Flat parameters.
.object({
...mockFilterSchema,
abort: zod
.boolean()
.optional()
.describe(
'Abort matching requests when true. When false, use the stored ' +
'body or upstream source, or send the request to the network if ' +
'neither is set. A mock without a source still wins over older ' +
'matching mocks. Abortion takes precedence over body, upstream, ' +
'and allowOrigin.',
),
allowOrigin: zod
.string()
.refine(value => {
if (value === '*' || value === 'null') {
return true;
}
try {
return new URL(value).origin === value;
} catch {
return false;
}
}, 'allowOrigin must be *, null, or a serialized origin such as https://example.com.')
.optional()
.describe(
'Set the Access-Control-Allow-Origin response header to `*`, `null`, or a serialized origin such as https://example.com. Requires body or upstream, either supplied now or already set on the mock. This does not configure preflight or credential headers.',
),
body: zod
.string()
.trim()
Expand Down Expand Up @@ -226,13 +252,17 @@ export const mockNetwork: PageToolFactory = definePageTool(() => ({
description:
'Inspect or update network mocks for a page. With no actions, list mocks ' +
'matching the supplied filters, or all mocks when no filters are given. ' +
'Providing body or upstream updates the exact route/resourceType pair. ' +
'Providing abort (including false), allowOrigin, body, or upstream updates ' +
'the exact route/resourceType pair; omitted actions keep existing settings. ' +
'Remove and recreate a mock to clear its source or allowOrigin. ' +
'An omitted route matches any URL. Other mocks are preserved. ' +
'abort=true suppresses its response and allowOrigin header. ' +
'The most recently updated matching mock wins and persists across ' +
'navigations. Configure before navigating or reloading; inspection shows ' +
'hit counts and replacement errors. Upstream responses use server-side ' +
'GET/HEAD fetches. Changes are rejected during ' +
'a performance trace. Mocks disable the page HTTP cache and intercept ' +
'hit counts and replacement errors. allowOrigin requires a body or ' +
'upstream source. Upstream responses use server-side GET/HEAD fetches. ' +
'Changes are rejected during a performance trace. ' +
'Mocks disable the page HTTP cache and intercept ' +
'every request, affecting measurements. Service workers can bypass mocks. ' +
'Use remove_network_mock to remove mocks.',
annotations: {
Expand All @@ -249,29 +279,38 @@ export const mockNetwork: PageToolFactory = definePageTool(() => ({
urlPattern: params.route,
resourceType: params.resourceType,
};
let input: NetworkMockInput | undefined;
if (params.upstream !== undefined) {
input = {...filter, kind: 'upstream', upstreamUrl: params.upstream};
} else if (params.body !== undefined) {
const responseFilePath = params.body;
input = {
let overrides;
if (
params.abort === undefined &&
params.allowOrigin === undefined &&
params.body === undefined &&
params.upstream === undefined
) {
overrides = request.page.listNetworkMocks(filter);
} else {
let input: NetworkMockInput = {
...filter,
kind: 'file',
responseFilePath,
loadResponseFile: async () => {
const validatedPath = await context.validatePath(responseFilePath);
return await fs.readFile(validatedPath);
},
abort: params.abort,
allowOrigin: params.allowOrigin,
};
}
let overrides;
if (input) {
if (params.upstream !== undefined) {
input = {...input, kind: 'upstream', upstreamUrl: params.upstream};
} else if (params.body !== undefined) {
const responseFilePath = params.body;
input = {
...input,
kind: 'file',
responseFilePath,
loadResponseFile: async () => {
const validatedPath = await context.validatePath(responseFilePath);
return await fs.readFile(validatedPath);
},
};
}
overrides = [await request.page.mockNetwork(input)];
response.appendResponseLine(
'Network mock configured. Reload or navigate the page to apply it.',
);
} else {
overrides = request.page.listNetworkMocks(filter);
}

if (overrides.length === 0) {
Expand Down
Loading
Loading