Skip to content

[experimental] Pass NetworkFrameResolutionContext to NetworkSource.enable() #2708

@christoph-fricke

Description

@christoph-fricke

This issue has come up while migrating @msw/playwright to the new network source architecture.

I want to bring this idea forward for discussion to improve the new network source API while it is still exported as "experimental".

Problem Statement

I think network sources can benefit from having access to the NetworkFrameResolutionContext that users provide to defineNetwork. Currently this context is only provided to frames.

In the current implementation, both ServiceWorkerSource and FallbackHttpSource accept their own quit option, which results in network definitions looking like this:

const network = defineNetwork({
  sources: [new FallbackHttpSource({ quiet: true })],
  handlers[],
  context: { quit: true },
})

If they where able access NetworkFrameResolutionContext.quit instead, the duplicate configuration can be removed:

const network = defineNetwork({
  sources: [new FallbackHttpSource()],
  handlers[],
  context: { quit: true },
})

In the @msw/playwright rewrite I could benefit from having access to NetworkFrameResolutionContext.baseUrl in the network source to use the value when calling browserContext.route(...). Handlers only match requests that start with prefix if it is provided. Therefore, browserContext.route(...) also only has to intercept requests that start with the baseUrl (instead of all network traffic) to reduce overhead in Playwright.

Proposed Solution

Since the context can be reconfigured with network.configure, we have find the right time for passing along a stable context to the source. I think passing the value when the network, and thus all sources, get enabled is ideal. I can't imagine a source needing access to the context before it gets enabled.

export abstract class NetworkSource<
  Frame extends AnyNetworkFrame = AnyNetworkFrame,
> {
  public abstract enable(context: NetworkFrameResolutionContext): unknown | Promise<unknown>
}

Furthermore, NetworkFrameResolutionContext has to be exported so custom sources are able to type their enable method. With this change, we should consider renaming NetworkFrameResolutionContext as its scope expands beyond just frame resolution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions