Socket
Socket
Sign inDemoInstall

@mswjs/interceptors

Package Overview
Dependencies
Maintainers
0
Versions
144
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mswjs/interceptors - npm Package Compare versions

Comparing version 0.34.1 to 0.34.2

lib/browser/chunk-73X2CAEH.mjs

6

lib/browser/interceptors/fetch/index.js
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk6MBJUL74js = require('../../chunk-6MBJUL74.js');
require('../../chunk-VRKVKT62.js');
var _chunkTPZUQHHYjs = require('../../chunk-TPZUQHHY.js');
require('../../chunk-EJYZ4HR3.js');
require('../../chunk-FXSPMSSQ.js');

@@ -9,3 +9,3 @@ require('../../chunk-TIPR373R.js');

exports.FetchInterceptor = _chunk6MBJUL74js.FetchInterceptor;
exports.FetchInterceptor = _chunkTPZUQHHYjs.FetchInterceptor;
//# sourceMappingURL=index.js.map
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkLERABB57js = require('../../chunk-LERABB57.js');
var _chunkYP3NI6UPjs = require('../../chunk-YP3NI6UP.js');
require('../../chunk-LK6DILFK.js');
require('../../chunk-VRKVKT62.js');
require('../../chunk-EJYZ4HR3.js');
require('../../chunk-FXSPMSSQ.js');

@@ -10,3 +10,3 @@ require('../../chunk-TIPR373R.js');

exports.XMLHttpRequestInterceptor = _chunkLERABB57js.XMLHttpRequestInterceptor;
exports.XMLHttpRequestInterceptor = _chunkYP3NI6UPjs.XMLHttpRequestInterceptor;
//# sourceMappingURL=index.js.map
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkLERABB57js = require('../chunk-LERABB57.js');
var _chunkYP3NI6UPjs = require('../chunk-YP3NI6UP.js');
require('../chunk-LK6DILFK.js');
var _chunk6MBJUL74js = require('../chunk-6MBJUL74.js');
require('../chunk-VRKVKT62.js');
var _chunkTPZUQHHYjs = require('../chunk-TPZUQHHY.js');
require('../chunk-EJYZ4HR3.js');
require('../chunk-FXSPMSSQ.js');

@@ -14,4 +14,4 @@ require('../chunk-TIPR373R.js');

var browser_default = [
new (0, _chunk6MBJUL74js.FetchInterceptor)(),
new (0, _chunkLERABB57js.XMLHttpRequestInterceptor)()
new (0, _chunkTPZUQHHYjs.FetchInterceptor)(),
new (0, _chunkYP3NI6UPjs.XMLHttpRequestInterceptor)()
];

@@ -18,0 +18,0 @@

"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkI57YSVAVjs = require('../../chunk-I57YSVAV.js');
require('../../chunk-5WWNCLB3.js');
var _chunkCQAXV6QMjs = require('../../chunk-CQAXV6QM.js');
require('../../chunk-TQD7SQGP.js');
require('../../chunk-YGM3BCJU.js');
exports.ClientRequestInterceptor = _chunkI57YSVAVjs.ClientRequestInterceptor;
exports.ClientRequestInterceptor = _chunkCQAXV6QMjs.ClientRequestInterceptor;
//# sourceMappingURL=index.js.map
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkUN335ZTDjs = require('../../chunk-UN335ZTD.js');
var _chunkW4AQXISMjs = require('../../chunk-W4AQXISM.js');
require('../../chunk-IDEEMJ3F.js');
require('../../chunk-5WWNCLB3.js');
require('../../chunk-TQD7SQGP.js');
require('../../chunk-YGM3BCJU.js');
exports.FetchInterceptor = _chunkUN335ZTDjs.FetchInterceptor;
exports.FetchInterceptor = _chunkW4AQXISMjs.FetchInterceptor;
//# sourceMappingURL=index.js.map
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkT34TGCMRjs = require('../../chunk-T34TGCMR.js');
var _chunkMFGG7XIPjs = require('../../chunk-MFGG7XIP.js');
require('../../chunk-LK6DILFK.js');
require('../../chunk-IDEEMJ3F.js');
require('../../chunk-5WWNCLB3.js');
require('../../chunk-TQD7SQGP.js');
require('../../chunk-YGM3BCJU.js');
exports.XMLHttpRequestInterceptor = _chunkT34TGCMRjs.XMLHttpRequestInterceptor;
exports.XMLHttpRequestInterceptor = _chunkMFGG7XIPjs.XMLHttpRequestInterceptor;
//# sourceMappingURL=index.js.map
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkI57YSVAVjs = require('../chunk-I57YSVAV.js');
var _chunkCQAXV6QMjs = require('../chunk-CQAXV6QM.js');
var _chunkT34TGCMRjs = require('../chunk-T34TGCMR.js');
var _chunkMFGG7XIPjs = require('../chunk-MFGG7XIP.js');
require('../chunk-LK6DILFK.js');
var _chunkUN335ZTDjs = require('../chunk-UN335ZTD.js');
var _chunkW4AQXISMjs = require('../chunk-W4AQXISM.js');
require('../chunk-IDEEMJ3F.js');
require('../chunk-5WWNCLB3.js');
require('../chunk-TQD7SQGP.js');
require('../chunk-YGM3BCJU.js');

@@ -17,5 +17,5 @@

var node_default = [
new (0, _chunkI57YSVAVjs.ClientRequestInterceptor)(),
new (0, _chunkT34TGCMRjs.XMLHttpRequestInterceptor)(),
new (0, _chunkUN335ZTDjs.FetchInterceptor)()
new (0, _chunkCQAXV6QMjs.ClientRequestInterceptor)(),
new (0, _chunkMFGG7XIPjs.XMLHttpRequestInterceptor)(),
new (0, _chunkW4AQXISMjs.FetchInterceptor)()
];

@@ -22,0 +22,0 @@

@@ -6,6 +6,6 @@ "use strict";Object.defineProperty(exports, "__esModule", {value: true});

var _chunkI57YSVAVjs = require('./chunk-I57YSVAV.js');
var _chunkCQAXV6QMjs = require('./chunk-CQAXV6QM.js');
var _chunkT34TGCMRjs = require('./chunk-T34TGCMR.js');
var _chunkMFGG7XIPjs = require('./chunk-MFGG7XIP.js');
require('./chunk-LK6DILFK.js');

@@ -16,3 +16,3 @@ require('./chunk-IDEEMJ3F.js');

var _chunk5WWNCLB3js = require('./chunk-5WWNCLB3.js');
var _chunkTQD7SQGPjs = require('./chunk-TQD7SQGP.js');

@@ -28,4 +28,4 @@

interceptors: [
new (0, _chunkI57YSVAVjs.ClientRequestInterceptor)(),
new (0, _chunkT34TGCMRjs.XMLHttpRequestInterceptor)()
new (0, _chunkCQAXV6QMjs.ClientRequestInterceptor)(),
new (0, _chunkMFGG7XIPjs.XMLHttpRequestInterceptor)()
]

@@ -125,4 +125,4 @@ });

});
const controller = new (0, _chunk5WWNCLB3js.RequestController)(request);
await _chunk5WWNCLB3js.handleRequest.call(void 0, {
const controller = new (0, _chunkTQD7SQGPjs.RequestController)(request);
await _chunkTQD7SQGPjs.handleRequest.call(void 0, {
request,

@@ -129,0 +129,0 @@ requestId: requestJson.id,

{
"name": "@mswjs/interceptors",
"description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.",
"version": "0.34.1",
"version": "0.34.2",
"main": "./lib/node/index.js",

@@ -120,2 +120,3 @@ "module": "./lib/node/index.mjs",

"@types/express": "^4.17.13",
"@types/express-fileupload": "^1.5.0",
"@types/express-rate-limit": "^6.0.0",

@@ -136,2 +137,3 @@ "@types/follow-redirects": "^1.14.1",

"express": "^4.17.3",
"express-fileupload": "^1.5.1",
"express-rate-limit": "^6.3.0",

@@ -138,0 +140,0 @@ "follow-redirects": "^1.15.1",

export class EventPolyfill implements Event {
readonly AT_TARGET: number = 0
readonly BUBBLING_PHASE: number = 0
readonly CAPTURING_PHASE: number = 0
readonly NONE: number = 0
readonly NONE = 0
readonly CAPTURING_PHASE = 1
readonly AT_TARGET = 2
readonly BUBBLING_PHASE = 3

@@ -7,0 +7,0 @@ public type: string = ''

@@ -7,3 +7,3 @@ import { EventPolyfill } from '../polyfills/EventPolyfill'

export function createEvent(
target: XMLHttpRequest,
target: XMLHttpRequest | XMLHttpRequestUpload,
type: string,

@@ -10,0 +10,0 @@ init?: ProgressEventInit

@@ -51,5 +51,10 @@ import { invariant } from 'outvariant'

private events: Map<keyof XMLHttpRequestEventTargetEventMap, Array<Function>>
private uploadEvents: Map<
keyof XMLHttpRequestEventTargetEventMap,
Array<Function>
>
constructor(readonly initialRequest: XMLHttpRequest, public logger: Logger) {
this.events = new Map()
this.uploadEvents = new Map()
this.requestId = createRequestId()

@@ -204,2 +209,45 @@ this.requestHeaders = new Headers()

})
/**
* Proxy the `.upload` property to gather the event listeners/callbacks.
*/
define(
this.request,
'upload',
createProxy(this.request.upload, {
setProperty: ([propertyName, nextValue], invoke) => {
switch (propertyName) {
case 'onloadstart':
case 'onprogress':
case 'onaboart':
case 'onerror':
case 'onload':
case 'ontimeout':
case 'onloadend': {
const eventName = propertyName.slice(
2
) as keyof XMLHttpRequestEventTargetEventMap
this.registerUploadEvent(eventName, nextValue as Function)
}
}
return invoke()
},
methodCall: ([methodName, args], invoke) => {
switch (methodName) {
case 'addEventListener': {
const [eventName, listener] = args as [
keyof XMLHttpRequestEventTargetEventMap,
Function
]
this.registerUploadEvent(eventName, listener)
this.logger.info('upload.addEventListener', eventName, listener)
return invoke()
}
}
},
})
)
}

@@ -218,2 +266,13 @@

private registerUploadEvent(
eventName: keyof XMLHttpRequestEventTargetEventMap,
listener: Function
): void {
const prevEvents = this.uploadEvents.get(eventName) || []
const nextEvents = prevEvents.concat(listener)
this.uploadEvents.set(eventName, nextEvents)
this.logger.info('registered upload event "%s"', eventName, listener)
}
/**

@@ -223,3 +282,33 @@ * Responds to the current request with the given

*/
public respondWith(response: Response): void {
public async respondWith(response: Response): Promise<void> {
/**
* Dispatch request upload events for requests with a body.
* @see https://github.com/mswjs/interceptors/issues/573
*/
if (this.requestBody != null) {
const totalRequestBodyLength = this.requestHeaders.has('content-length')
? Number(this.requestHeaders.get('content-length'))
: await getXMLHttpRequestBodyInitLength(
this.requestBody,
this.requestHeaders
)
this.trigger('loadstart', this.request.upload, {
loaded: 0,
total: totalRequestBodyLength,
})
this.trigger('progress', this.request.upload, {
loaded: totalRequestBodyLength,
total: totalRequestBodyLength,
})
this.trigger('load', this.request.upload, {
loaded: totalRequestBodyLength,
total: totalRequestBodyLength,
})
this.trigger('loadend', this.request.upload, {
loaded: totalRequestBodyLength,
total: totalRequestBodyLength,
})
}
this.logger.info(

@@ -310,3 +399,3 @@ 'responding with a mocked response: %d %s',

const totalResponseBodyLength = response.headers.has('Content-Length')
const totalResponseBodyLength = response.headers.has('content-length')
? Number(response.headers.get('Content-Length'))

@@ -320,3 +409,3 @@ : /**

this.trigger('loadstart', {
this.trigger('loadstart', this.request, {
loaded: 0,

@@ -334,3 +423,3 @@ total: totalResponseBodyLength,

this.trigger('load', {
this.trigger('load', this.request, {
loaded: this.responseBuffer.byteLength,

@@ -340,3 +429,3 @@ total: totalResponseBodyLength,

this.trigger('loadend', {
this.trigger('loadend', this.request, {
loaded: this.responseBuffer.byteLength,

@@ -365,3 +454,3 @@ total: totalResponseBodyLength,

this.trigger('progress', {
this.trigger('progress', this.request, {
loaded: this.responseBuffer.byteLength,

@@ -497,4 +586,4 @@ total: totalResponseBodyLength,

this.setReadyState(this.request.DONE)
this.trigger('error')
this.trigger('loadend')
this.trigger('error', this.request)
this.trigger('loadend', this.request)
}

@@ -524,3 +613,3 @@

this.trigger('readystatechange')
this.trigger('readystatechange', this.request)
}

@@ -536,5 +625,9 @@ }

})
>(eventName: EventName, options?: ProgressEventInit): void {
const callback = this.request[`on${eventName}`]
const event = createEvent(this.request, eventName, options)
>(
eventName: EventName,
target: XMLHttpRequest | XMLHttpRequestUpload,
options?: ProgressEventInit
): void {
const callback = (target as XMLHttpRequest)[`on${eventName}`]
const event = createEvent(target, eventName, options)

@@ -546,7 +639,10 @@ this.logger.info('trigger "%s"', eventName, options || '')

this.logger.info('found a direct "%s" callback, calling...', eventName)
callback.call(this.request, event)
callback.call(target as XMLHttpRequest, event)
}
// Invoke event listeners.
for (const [registeredEventName, listeners] of this.events) {
const events =
target instanceof XMLHttpRequestUpload ? this.uploadEvents : this.events
for (const [registeredEventName, listeners] of events) {
if (registeredEventName === eventName) {

@@ -559,3 +655,3 @@ this.logger.info(

listeners.forEach((listener) => listener.call(this.request, event))
listeners.forEach((listener) => listener.call(target, event))
}

@@ -568,3 +664,3 @@ }

*/
public toFetchApiRequest(): Request {
private toFetchApiRequest(): Request {
this.logger.info('converting request to a Fetch API Request...')

@@ -644,1 +740,48 @@

}
async function getXMLHttpRequestBodyInitLength(
body: XMLHttpRequestBodyInit | Document,
headers: Headers
): Promise<number> {
if (typeof body === 'object' && 'byteLength' in body) {
return body.byteLength
}
if (body instanceof Blob) {
return body.size
}
if (body instanceof FormData) {
const lines: Array<string> = []
const contentType =
headers.get('content-type') || 'application/octet-stream'
for (const [name, entry] of body) {
lines.push(`------WebKitFormBoundary1234567890123456`)
lines.push(`content-type: ${contentType}`)
if (typeof entry === 'string') {
lines.push(`content-disposition: form-data; name="${name}"`)
lines.push(``)
lines.push(entry)
} else {
lines.push(
`content-disposition: form-data; name="${name}"; filename="${entry.name}"`
)
lines.push(``)
lines.push(await entry.text())
}
}
lines.push('------WebKitFormBoundary1234567890123456--')
lines.push(``)
return lines.join('\r\n').length
}
if (body instanceof Document) {
return body.documentElement.innerHTML.length
}
return body.toString().length
}

@@ -69,4 +69,4 @@ import type { Logger } from '@open-draft/logger'

emitter,
onResponse: (response) => {
this.respondWith(response)
onResponse: async (response) => {
await this.respondWith(response)
},

@@ -73,0 +73,0 @@ onRequestError: () => {

@@ -25,3 +25,3 @@ import type { Emitter } from 'strict-event-emitter'

*/
onResponse: (response: Response) => void
onResponse: (response: Response) => void | Promise<void>

@@ -47,3 +47,3 @@ /**

): Promise<boolean> {
const handleResponse = (response: Response | Error): true => {
const handleResponse = async (response: Response | Error) => {
if (response instanceof Error) {

@@ -57,3 +57,3 @@ options.onError(response)

} else {
options.onResponse(response)
await options.onResponse(response)
}

@@ -64,3 +64,3 @@

const handleResponseError = (error: unknown): boolean => {
const handleResponseError = async (error: unknown): Promise<boolean> => {
// Forward the special interceptor error instances

@@ -80,3 +80,3 @@ // to the developer. These must not be handled in any way.

if (error instanceof Response) {
return handleResponse(error)
return await handleResponse(error)
}

@@ -148,3 +148,3 @@

// These can be thrown responses or request errors.
if (handleResponseError(result.error)) {
if (await handleResponseError(result.error)) {
return true

@@ -151,0 +151,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc