Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@pactflow/pact-msw-adapter

Package Overview
Dependencies
Maintainers
6
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pactflow/pact-msw-adapter - npm Package Compare versions

Comparing version 1.2.1 to 1.3.0

.whitesource

7

CHANGELOG.md

@@ -5,2 +5,9 @@ # Changelog

## [1.3.0](https://github.com/pactflow/pact-msw-adapter/compare/v1.2.1...v1.3.0) (2022-10-06)
### Features
* Add client name/version into pact file ([1c8aa9a](https://github.com/pactflow/pact-msw-adapter/commit/1c8aa9a35898be4280c99859d795b29a219b3bc6))
### [1.2.1](https://github.com/pactflow/pact-msw-adapter/compare/v1.2.0...v1.2.1) (2022-07-15)

@@ -7,0 +14,0 @@

19

dist/convertMswMatchToPact.js

@@ -5,2 +5,3 @@ "use strict";

const lodash_1 = require("lodash");
const pjson = require("../package.json");
const convertMswMatchToPact = ({ consumer, provider, matches, headers, }) => {

@@ -10,7 +11,7 @@ const pactFile = {

provider: { name: provider },
interactions: matches.map(match => {
interactions: matches.map((match) => {
var _a;
return ({
description: match.request.id,
providerState: '',
providerState: "",
request: {

@@ -23,3 +24,5 @@ method: match.request.method,

body: match.request.body || undefined,
query: match.request.url.search ? match.request.url.search.split('?')[1] : undefined
query: match.request.url.search
? match.request.url.search.split("?")[1]
: undefined,
},

@@ -32,7 +35,7 @@ response: {

body: match.body
? ((_a = match.response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('json'))
? ((_a = match.response.headers.get("content-type")) === null || _a === void 0 ? void 0 : _a.includes("json"))
? JSON.parse(match.body)
: match.body
: undefined
}
: undefined,
},
});

@@ -44,2 +47,6 @@ }),

},
client: {
name: "pact-msw-adapter",
version: pjson.version,
},
},

@@ -46,0 +53,0 @@ };

/// <reference types="node" />
import { DefaultRequestBody, MockedRequest, SetupWorkerApi } from 'msw';
import { convertMswMatchToPact } from './convertMswMatchToPact';
import { EventEmitter } from 'events';
import { SetupServerApi } from 'msw/lib/types/node/glossary';
import { IsomorphicResponse } from '@mswjs/interceptors';
import { DefaultRequestBody, MockedRequest, SetupWorkerApi } from "msw";
import { convertMswMatchToPact } from "./convertMswMatchToPact";
import { EventEmitter } from "events";
import { SetupServerApi } from "msw/lib/types/node/glossary";
import { IsomorphicResponse } from "@mswjs/interceptors";
export interface PactMswAdapterOptions {

@@ -38,3 +38,3 @@ timeout?: number;

}
export declare const setupPactMswAdapter: ({ options: externalOptions, worker, server }: {
export declare const setupPactMswAdapter: ({ options: externalOptions, worker, server, }: {
options: PactMswAdapterOptions;

@@ -70,4 +70,4 @@ worker?: SetupWorkerApi | undefined;

export interface PactFile {
consumer: PactParticipants['consumer'];
provider: PactParticipants['provider'];
consumer: PactParticipants["consumer"];
provider: PactParticipants["provider"];
interactions: PactInteraction[];

@@ -80,2 +80,6 @@ metadata: PactFileMetaData;

};
client: {
name: string;
version: string;
};
}

@@ -82,0 +86,0 @@ export interface MswMatch {

@@ -8,5 +8,5 @@ "use strict";

const events_1 = require("events");
const setupPactMswAdapter = ({ options: externalOptions, worker, server }) => {
const setupPactMswAdapter = ({ options: externalOptions, worker, server, }) => {
if (!worker && !server) {
throw new Error('Either a worker or server must be provided');
throw new Error("Either a worker or server must be provided");
}

@@ -16,3 +16,3 @@ const isWorker = worker ? !!worker : false;

if (!mswMocker) {
throw new Error('Could not setup either the worker or server');
throw new Error("Could not setup either the worker or server");
}

@@ -24,7 +24,7 @@ const emitter = new events_1.EventEmitter();

debug: externalOptions.debug || false,
pactOutDir: externalOptions.pactOutDir || './msw_generated_pacts/'
pactOutDir: externalOptions.pactOutDir || "./msw_generated_pacts/",
};
(0, utils_1.logGroup)(`Adapter enabled${options.debug ? ' on debug mode' : ''}`);
(0, utils_1.logGroup)(`Adapter enabled${options.debug ? " on debug mode" : ""}`);
if (options.debug) {
(0, utils_1.logGroup)(['options:', options], { endGroup: true });
(0, utils_1.logGroup)(["options:", options], { endGroup: true });
}

@@ -42,3 +42,3 @@ else {

const matches = []; // Completed request-response pairs
mswMocker.events.on('request:match', (req) => {
mswMocker.events.on("request:match", (req) => {
const url = req.url.toString();

@@ -48,3 +48,3 @@ if (!(0, utils_1.checkUrlFilters)(url, options))

if (options.debug) {
(0, utils_1.logGroup)(['Matching request', req], { endGroup: true });
(0, utils_1.logGroup)(["Matching request", req], { endGroup: true });
}

@@ -56,3 +56,3 @@ const startTime = Date.now();

const activeIdx = activeRequestIds.indexOf(req.id);
emitter.emit('pact-msw-adapter:expired', req);
emitter.emit("pact-msw-adapter:expired", req);
if (activeIdx >= 0) {

@@ -63,3 +63,3 @@ // Could be removed if completed or the test ended

reqId: req.id,
startTime
startTime,
});

@@ -69,3 +69,3 @@ }

});
mswMocker.events.on('response:mocked', async (response, reqId) => {
mswMocker.events.on("response:mocked", async (response, reqId) => {
// https://mswjs.io/docs/extensions/life-cycle-events#responsemocked

@@ -91,4 +91,4 @@ // Note that the res instance differs between the browser and Node.js.

(0, utils_1.log)(`Orphan response: ${request.url}`, {
mode: 'warning',
group: expiredReq !== undefined
mode: "warning",
group: expiredReq !== undefined,
});

@@ -99,10 +99,10 @@ }

(0, utils_1.log)(`Expired request to ${request.url.pathname}`, {
mode: 'warning',
group: true
mode: "warning",
group: true,
});
}
expiredReq.duration = endTime - expiredReq.startTime;
console.log('url:', request.url);
console.log('timeout:', options.timeout);
console.log('duration:', expiredReq.duration);
console.log("url:", request.url);
console.log("timeout:", options.timeout);
console.log("duration:", expiredReq.duration);
console.groupEnd();

@@ -113,3 +113,3 @@ }

if (options.debug) {
(0, utils_1.logGroup)(['Mocked response', response], { endGroup: true });
(0, utils_1.logGroup)(["Mocked response", response], { endGroup: true });
}

@@ -120,8 +120,8 @@ activeRequestIds.splice(activeReqIdx, 1);

response,
body: responseBody
body: responseBody,
};
emitter.emit('pact-msw-adapter:match', match);
emitter.emit("pact-msw-adapter:match", match);
matches.push(match);
});
mswMocker.events.on('request:unhandled', (req) => {
mswMocker.events.on("request:unhandled", (req) => {
const url = req.url.toString();

@@ -138,8 +138,8 @@ if (!(0, utils_1.checkUrlFilters)(url, options))

activeRequestIds.length = 0;
emitter.emit('pact-msw-adapter:new-test');
emitter.emit("pact-msw-adapter:new-test");
},
verifyTest: () => {
let errors = '';
let errors = "";
if (unhandledRequests.length) {
errors += `Requests with missing msw handlers:\n ${unhandledRequests.join('\n')}\n`;
errors += `Requests with missing msw handlers:\n ${unhandledRequests.join("\n")}\n`;
unhandledRequests.length = 0;

@@ -151,11 +151,11 @@ }

expired,
req: pendingRequests.find((req) => req.id === expired.reqId)
req: pendingRequests.find((req) => req.id === expired.reqId),
}))
.filter(({ expired, req }) => expired && req)
.map(({ expired, req }) => `${req.url.pathname}${expired.duration ? `took ${expired.duration}ms and` : ''} timed out after ${options.timeout}ms`)
.join('\n')}\n`;
.map(({ expired, req }) => `${req.url.pathname}${expired.duration ? `took ${expired.duration}ms and` : ""} timed out after ${options.timeout}ms`)
.join("\n")}\n`;
expiredRequests.length = 0;
}
if (orphanResponses.length) {
errors += `Orphan responses:\n${orphanResponses.join('\n')}\n`;
errors += `Orphan responses:\n${orphanResponses.join("\n")}\n`;
orphanResponses.length = 0;

@@ -171,4 +171,4 @@ }

(0, utils_1.logGroup)([
'Found the following number of matches to write to a file:- ' +
matches.length
"Found the following number of matches to write to a file:- " +
matches.length,
], { endGroup: true });

@@ -181,9 +181,9 @@ (0, utils_1.logGroup)(JSON.stringify(matches), { endGroup: true });

catch (error) {
(0, utils_1.logGroup)(['An error occurred parsing the JSON file', error]);
throw new Error('error generating pact files');
(0, utils_1.logGroup)(["An error occurred parsing the JSON file", error]);
throw new Error("error generating pact files");
}
if (!pactFiles) {
(0, utils_1.logGroup)([
'writeToFile() was called but no pact files were generated, did you forget to await the writeToFile() method?',
matches.length
"writeToFile() was called but no pact files were generated, did you forget to await the writeToFile() method?",
matches.length,
], { endGroup: true });

@@ -193,9 +193,9 @@ }

const filePath = options.pactOutDir +
'/' +
"/" +
[
pactFile.consumer.name,
pactFile.provider.name,
Date.now().toString()
].join('-') +
'.json';
Date.now().toString(),
].join("-") +
".json";
writer(filePath, pactFile);

@@ -212,5 +212,5 @@ });

matches.length = 0;
emitter.emit('pact-msw-adapter:clear');
emitter.emit("pact-msw-adapter:clear");
return;
}
},
};

@@ -228,6 +228,6 @@ };

const events = [
'pact-msw-adapter:expired ',
'pact-msw-adapter:match',
'pact-msw-adapter:new-test',
'pact-msw-adapter:clear'
"pact-msw-adapter:expired ",
"pact-msw-adapter:match",
"pact-msw-adapter:new-test",
"pact-msw-adapter:clear",
];

@@ -242,3 +242,3 @@ const listener = () => {

});
await (0, utils_1.addTimeout)(requestsCompleted, 'requests completed listener', options.timeout * 2);
await (0, utils_1.addTimeout)(requestsCompleted, "requests completed listener", options.timeout * 2);
const pactFiles = [];

@@ -250,3 +250,3 @@ const providers = Object.entries(options.providers);

const url = match.request.url.toString();
const provider = ((_a = providers.find(([_, paths]) => paths.some((path) => url.includes(path)))) === null || _a === void 0 ? void 0 : _a[0]) || 'unknown';
const provider = ((_a = providers.find(([_, paths]) => paths.some((path) => url.includes(path)))) === null || _a === void 0 ? void 0 : _a[0]) || "unknown";
if (!matchesByProvider[provider])

@@ -261,3 +261,3 @@ matchesByProvider[provider] = [];

matches: providerMatches,
headers: { excludeHeaders: options.excludeHeaders }
headers: { excludeHeaders: options.excludeHeaders },
});

@@ -274,5 +274,5 @@ if (pactFile) {

}
if (err && typeof err === 'string')
if (err && typeof err === "string")
err = new Error(err);
console.groupCollapsed('%c[pact-msw-adapter] Unexpected error.', 'color:coral;font-weight:bold;');
console.groupCollapsed("%c[pact-msw-adapter] Unexpected error.", "color:coral;font-weight:bold;");
console.log(err);

@@ -279,0 +279,0 @@ console.groupEnd();

{
"name": "@pactflow/pact-msw-adapter",
"version": "1.2.1",
"version": "1.3.0",
"main": "./dist/pactMswAdapter.js",

@@ -5,0 +5,0 @@ "keywords": [

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