From 9c611597fc2b50f4fbd5cb5c2b8c9e2b3b886dca Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 15:32:05 +0000 Subject: [PATCH 1/3] fix: use the example of a content type header matcher The V2 DSL passed a Content-Type header matcher's JSON to the FFI as the body content type. Use the matcher's example value, and the first value of a header given as an array. Fixes #1071 Co-Authored-By: Claude Opus 5.5 --- src/httpPact/ffi.spec.ts | 29 +++++++++++++++++++++++++++++ src/httpPact/ffi.ts | 14 +++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/httpPact/ffi.spec.ts b/src/httpPact/ffi.spec.ts index 42e031e49..f00814f20 100644 --- a/src/httpPact/ffi.spec.ts +++ b/src/httpPact/ffi.spec.ts @@ -1,5 +1,6 @@ import type { ConsumerInteraction } from '@pact-foundation/pact-core'; import { vi } from 'vitest'; +import { term } from '../dsl/matchers'; import { contentTypeFromHeaders, setQuery } from './ffi'; describe('Pact FFI', () => { @@ -15,6 +16,34 @@ describe('Pact FFI', () => { }); }); + describe('when the header is a matcher', () => { + it('uses the example value', () => { + const headers = { + 'Content-Type': term({ + generate: 'application/json', + matcher: 'application/json.*', + }), + }; + expect(contentTypeFromHeaders(headers, 'text/plain')).toBe( + 'application/json', + ); + }); + }); + + describe('when the header has more than one value', () => { + it('uses the first value', () => { + const headers = { + 'Content-Type': [ + term({ generate: 'application/xml', matcher: 'application/.*xml' }), + 'text/plain', + ], + }; + expect(contentTypeFromHeaders(headers, 'application/json')).toBe( + 'application/xml', + ); + }); + }); + describe(`when the no content-type header is set`, () => { it('uses a default', () => { expect(contentTypeFromHeaders({}, 'application/json')).toBe( diff --git a/src/httpPact/ffi.ts b/src/httpPact/ffi.ts index feb183e81..66085f3ee 100644 --- a/src/httpPact/ffi.ts +++ b/src/httpPact/ffi.ts @@ -8,7 +8,12 @@ import type { RequestOptions, ResponseOptions, } from '../dsl/interaction'; -import { type MatcherV2, matcherValueOrString } from '../dsl/matchers'; +import { + extractPayload, + isMatcher, + type MatcherV2, + matcherValueOrString, +} from '../dsl/matchers'; enum InteractionPart { REQUEST = 1, @@ -22,10 +27,13 @@ export const contentTypeFromHeaders = ( headers: Headers | undefined, defaultContentType: string, ): string => { - let contentType: string | MatcherV2 = defaultContentType; + let contentType = defaultContentType; forEachObjIndexed((v, k) => { if (`${k}`.toLowerCase() === CONTENT_TYPE_HEADER) { - contentType = matcherValueOrString(v); + const headerValue = Array.isArray(v) ? v[0] : v; + contentType = isMatcher(headerValue) + ? `${extractPayload(headerValue)}` + : headerValue; } }, headers || {}); From 7d7f12d2746f891446f354c521d3dfa7481a6f6c Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 15:32:05 +0000 Subject: [PATCH 2/3] fix: send a matcher on a text body as matching rules pact_ffi only reads matchers embedded in a JSON body, so a matcher on a text body was sent as its JSON and compared as a literal string. Send the example as the body and the matcher as a body rule. Generators can't be given this way, so a warning is logged when one is dropped. Fixes #1107 Co-Authored-By: Claude Opus 5.5 --- src/v3/ffi.spec.ts | 41 +++++++++++++++++++++++++++++++++++++++-- src/v3/ffi.ts | 40 +++++++++++++++++++++++++++++++++++++++- src/v3/pact.ts | 24 +++++++++++++++--------- 3 files changed, 93 insertions(+), 12 deletions(-) diff --git a/src/v3/ffi.spec.ts b/src/v3/ffi.spec.ts index 8fbbaafef..b9a83f405 100644 --- a/src/v3/ffi.spec.ts +++ b/src/v3/ffi.spec.ts @@ -1,5 +1,5 @@ -import { contentTypeFromHeaders } from './ffi'; -import { regex } from './matchers'; +import { bodyAndMatchingRules, contentTypeFromHeaders } from './ffi'; +import { like, regex, string } from './matchers'; describe('V3 Pact FFI', () => { describe('#contentTypeFromHeaders', () => { @@ -16,4 +16,41 @@ describe('V3 Pact FFI', () => { ); }); }); + + describe('#bodyAndMatchingRules', () => { + it('sends a matcher on a text body as its example and a rule on the body', () => { + expect(bodyAndMatchingRules(string('07/14/2023'), 'text/plain')).toEqual({ + body: '07/14/2023', + rules: JSON.stringify({ + body: { + $: { combine: 'AND', matchers: [{ match: 'type' }] }, + }, + }), + }); + }); + + it('keeps the regex of a regex matcher', () => { + const { body, rules } = bodyAndMatchingRules( + regex('\\d+', '123'), + 'text/plain; charset=utf-8', + ); + expect(body).toBe('123'); + expect(JSON.parse(rules as string).body.$.matchers).toEqual([ + { regex: '\\d+', match: 'regex' }, + ]); + }); + + it('sends a matcher on a JSON body as matcher JSON', () => { + const matcher = like({ a: 1 }); + expect(bodyAndMatchingRules(matcher, 'application/hal+json')).toEqual({ + body: JSON.stringify(matcher), + }); + }); + + it('sends a plain text body as it is', () => { + expect(bodyAndMatchingRules('hello', 'text/plain')).toEqual({ + body: 'hello', + }); + }); + }); }); diff --git a/src/v3/ffi.ts b/src/v3/ffi.ts index 46e2de567..10b77315c 100644 --- a/src/v3/ffi.ts +++ b/src/v3/ffi.ts @@ -1,8 +1,9 @@ import type { ConsumerInteraction } from '@pact-foundation/pact-core'; import { forEachObjIndexed } from 'ramda'; +import logger from '../common/logger'; +import { convertStatusMatcherToFFI } from '../common/matchingRules'; import * as MatchersV3 from './matchers'; import type { Matcher, TemplateHeaders, V3Request, V3Response } from './types'; -import { convertStatusMatcherToFFI } from '../common/matchingRules'; type TemplateHeaderArrayValue = string[] | Matcher[]; @@ -82,3 +83,40 @@ export const contentTypeFromHeaders = ( return contentType; }; + +const isJsonContentType = (contentType: string): boolean => + /json/i.test(contentType); + +/** + * pact_ffi only reads matchers embedded in a JSON body. When the whole body is a single matcher and the content + * type is not JSON (for example `text/plain`), send the example as the body and the matcher as a rule on `$`, so + * the body is not written as the matcher's JSON (pact-js#1107). + */ +export const bodyAndMatchingRules = ( + body: unknown, + contentType: string, +): { body: string; rules?: string } => { + if ( + !MatchersV3.isMatcher(body) || + isJsonContentType(contentType) || + typeof body.value === 'object' + ) { + return { body: MatchersV3.matcherValueOrString(body) }; + } + + const { + 'pact:matcher:type': match, + 'pact:generator:type': generator, + value, + ...attributes + } = body as Matcher & Record; + if (generator) { + logger.warn( + `the ${generator} generator is not supported for a ${contentType} body, only the matcher will be used`, + ); + } + const rules = { + body: { $: { combine: 'AND', matchers: [{ ...attributes, match }] } }, + }; + return { body: `${value}`, rules: JSON.stringify(rules) }; +}; diff --git a/src/v3/pact.ts b/src/v3/pact.ts index 3871247fd..e11d78fc0 100644 --- a/src/v3/pact.ts +++ b/src/v3/pact.ts @@ -13,11 +13,11 @@ import logger from '../common/logger'; import { convertRulesToFFI, validateRules } from '../common/matchingRules'; import { filterMissingFeatureFlag, generateMockServerError } from './display'; import { + bodyAndMatchingRules, contentTypeFromHeaders, setRequestDetails, setResponseDetails, } from './ffi'; -import { matcherValueOrString } from './matchers'; import { type PactV3Options, type Rules, @@ -115,11 +115,14 @@ export class PactV3 { public withRequest(req: V3Request): PactV3 { if (req.body) { - this.interaction.withRequestBody( - matcherValueOrString(req.body), + const contentType = req.contentType || - contentTypeFromHeaders(req.headers, 'application/json'), - ); + contentTypeFromHeaders(req.headers, 'application/json'); + const { body, rules } = bodyAndMatchingRules(req.body, contentType); + this.interaction.withRequestBody(body, contentType); + if (rules) { + this.interaction.withRequestMatchingRules(rules); + } } setRequestDetails(this.interaction, req); @@ -203,11 +206,14 @@ export class PactV3 { public willRespondWith(res: V3Response): PactV3 { setResponseDetails(this.interaction, res); if (res.body) { - this.interaction.withResponseBody( - matcherValueOrString(res.body), + const contentType = res.contentType || - contentTypeFromHeaders(res.headers, 'application/json'), - ); + contentTypeFromHeaders(res.headers, 'application/json'); + const { body, rules } = bodyAndMatchingRules(res.body, contentType); + this.interaction.withResponseBody(body, contentType); + if (rules) { + this.interaction.withResponseMatchingRules(rules); + } } this.states = []; return this; From 61277b61da67ab21558afe980ceb6a6a1be58184 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 2 Nov 2026 15:32:06 +0000 Subject: [PATCH 3/3] fix: send text messages with the content type from their metadata The message provider proxy always sent the message as JSON, so a text message was verified as a JSON string. When the metadata gives a content type that is not JSON and the message is a string or Buffer, send it as it is with that content type. Fixes #1112 Co-Authored-By: Claude Opus 5.5 --- src/messageProviderPact.spec.ts | 49 +++++++++++++++++++++++++++++++++ src/messageProviderPact.ts | 33 ++++++++++++++++++++-- 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/src/messageProviderPact.spec.ts b/src/messageProviderPact.spec.ts index 331a98f2e..38e0c81ee 100644 --- a/src/messageProviderPact.spec.ts +++ b/src/messageProviderPact.spec.ts @@ -3,6 +3,7 @@ import express from 'express'; import type { Message } from './dsl/message'; import { MessageProviderPact, + providerWithMetadata, setupProxyServer, waitForServerReady, } from './messageProviderPact'; @@ -187,5 +188,53 @@ describe('MessageProvider', () => { (provider as any).setupProxyApplication.bind(provider); expect(setupProxyApplication().listen).toBeTypeOf('function'); }); + + describe('when a message has a content type in its metadata', () => { + const messageFor = async (description: string) => { + const app = new MessageProviderPact({ + logLevel: 'error', + messageProviders: { + text: providerWithMetadata(() => '07/14/2023', { + contentType: 'text/plain', + }), + json: providerWithMetadata(() => 'yay', { + 'Content-Type': 'application/json', + }), + }, + provider: 'myprovider', + // biome-ignore lint/suspicious/noExplicitAny: accessing private method for test coverage + }) as any; + const server = setupProxyServer(app.setupProxyApplication()); + await waitForServerReady(server); + try { + const { port } = server.address() as { port: number }; + const res = await fetch(`http://localhost:${port}/`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ description }), + }); + return { + contentType: res.headers.get('content-type'), + body: await res.text(), + }; + } finally { + server.close(); + } + }; + + it('sends a text message as it is, with that content type', async () => { + expect(await messageFor('text')).toEqual({ + contentType: 'text/plain; charset=utf-8', + body: '07/14/2023', + }); + }); + + it('still sends a JSON message as JSON', async () => { + expect(await messageFor('json')).toEqual({ + contentType: 'application/json; charset=utf-8', + body: '"yay"', + }); + }); + }); }); }); diff --git a/src/messageProviderPact.ts b/src/messageProviderPact.ts index d03d3dc89..fc05ef025 100644 --- a/src/messageProviderPact.ts +++ b/src/messageProviderPact.ts @@ -37,6 +37,32 @@ const hasMetadata = ( ): o is MessageFromProviderWithMetadata => Boolean((o as MessageFromProviderWithMetadata).__pactMessageMetadata); +const metadataContentType = ( + metadata: Record, +): string | undefined => { + const key = Object.keys(metadata).find((k) => + ['contenttype', 'content-type'].includes(k.toLowerCase()), + ); + return key ? `${metadata[key]}` : undefined; +}; + +// A text or binary message is sent as it is, with the content type from its +// metadata, so the verifier doesn't compare it as a JSON string (pact-js#1112) +const sendMessage = ( + res: express.Response, + message: unknown, + contentType?: string, +) => { + if ( + contentType && + !/json/i.test(contentType) && + (typeof message === 'string' || Buffer.isBuffer(message)) + ) { + return res.type(contentType).send(message); + } + return res.json(message); +}; + export const providerWithMetadata = ( provider: MessageProvider, @@ -134,7 +160,11 @@ export class MessageProviderPact { res.header('Pact-Message-Metadata', metadata); res.header('PACT_MESSAGE_METADATA', metadata); - return res.json(messageFromHandler.message); + return sendMessage( + res, + messageFromHandler.message, + metadataContentType(messageFromHandler.__pactMessageMetadata), + ); } return res.json(messageFromHandler); }) @@ -149,7 +179,6 @@ export class MessageProviderPact { app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use((_req, res, next) => { - // TODO: this seems to override the metadata for content-type res.header('Content-Type', 'application/json; charset=utf-8'); next(); });