@frontmcp/testing 1.10.15 → 1.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,26 @@ test('tool execution works', async ({ mcp }) => {
36
36
  npx frontmcp test
37
37
  ```
38
38
 
39
- `frontmcp test` (from the [`frontmcp`](https://www.npmjs.com/package/frontmcp) CLI) runs `src/**/*.spec.ts`, `__tests__/**/*.spec.ts` and `e2e/**/*.e2e.spec.ts` with a Jest configuration it generates. With a `jest.config.*` of your own, use `preset: '@frontmcp/testing'` for the same settings. The server starts when the first test that needs it runs, and tests with the same `test.use()` options share it.
39
+ `frontmcp test` (from the [`frontmcp`](https://www.npmjs.com/package/frontmcp) CLI) runs `src/**/*.spec.ts`, `__tests__/**/*.spec.ts` and `e2e/**/*.e2e.spec.ts` with a Jest configuration it generates. With a `jest.config.*` of your own, start from one of the [Jest presets](#jest-presets). The server starts when the first test that needs it runs, and tests with the same `test.use()` options share it.
40
+
41
+ ## Jest presets
42
+
43
+ | Preset | Use it for |
44
+ | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | `preset: '@frontmcp/testing'` | The configuration `frontmcp test` generates: unit and e2e specs, a 60-second timeout, and the matchers registered through `@frontmcp/testing/setup` |
46
+ | `preset: '@frontmcp/testing/jest-preset-unit'` | Unit tests, in a CommonJS project too: Jest's default 5-second timeout, no setup file, and every `*.spec.ts(x)` except `*.e2e.spec`, `*.perf.spec` and `*.pw.spec` files. Add `@frontmcp/testing/setup` to `setupFilesAfterEnv` to use the matchers |
47
+
48
+ Both compile TypeScript and TSX with `@swc/jest`, and both compile `jose`, `@noble/hashes` and `@noble/ciphers`, ESM-only packages the SDK loads, which Jest's CommonJS runtime otherwise fails on with `SyntaxError: Unexpected token 'export'`. To compile your TypeScript with `ts-jest`, set a transform for `.ts` only, so the preset still compiles those packages:
49
+
50
+ ```js
51
+ // jest.config.js
52
+ module.exports = {
53
+ preset: '@frontmcp/testing/jest-preset-unit',
54
+ transform: { '^.+\\.tsx?$': 'ts-jest' },
55
+ };
56
+ ```
57
+
58
+ `testMatch` and `transformIgnorePatterns` of your own replace the preset's lists, so copy its entries into yours.
40
59
 
41
60
  ## Fixtures
42
61
 
@@ -50,7 +69,7 @@ npx frontmcp test
50
69
 
51
70
  ## Matchers
52
71
 
53
- **Tools**: `toContainTool`, `toBeSuccessful`, `toBeError`, `toHaveTextContent`, `toHaveImageContent`, `toHaveResourceContent`
72
+ **Tools**: `toContainTool`, `toBeSuccessful`, `toBeError`, `toHaveTextContent`, `toHaveImageContent`, `toHaveResourceContent`, `toPassOutputSchemaWhole`
54
73
 
55
74
  **Resources**: `toContainResource`, `toContainResourceTemplate`, `toHaveMimeType`
56
75
 
@@ -60,7 +79,7 @@ npx frontmcp test
60
79
 
61
80
  **Tool UI**: `toHaveRenderedHtml`, `toContainHtmlElement`, `toContainBoundValue`, `toBeXssSafe`, `toHaveWidgetMetadata`, `toHaveCssClass`, `toNotContainRawContent`, `toHaveProperHtmlStructure`
62
81
 
63
- Use them through the `expect` this package exports, which is Jest's `expect` with these matchers typed. `frontmcp test` and the preset also register them on Jest's global `expect`, through `@frontmcp/testing/setup`, which you can add to `setupFilesAfterEnv` yourself.
82
+ Use them through the `expect` this package exports, which is Jest's `expect` with these matchers typed. `frontmcp test` and the `@frontmcp/testing` preset register them, through `@frontmcp/testing/setup`, which you can add to `setupFilesAfterEnv` yourself.
64
83
 
65
84
  ## Configuration
66
85
 
package/esm/index.mjs CHANGED
@@ -109,15 +109,15 @@ Server entry: ${config.server}
109
109
  Project: ${config.project??"default"}
110
110
  Command: ${serverCommand}
111
111
 
112
- Error: ${errMsg}`,{cause:error})}}else{throw new Error('test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option')}const sharedSecret=config.env?.["JWT_SECRET"];const binding=sharedSecret?gatewayTokenBinding(config.baseUrl??server.info.baseUrl,config.entryPath):void 0;const tokenFactory2=new TestTokenFactory(sharedSecret?{hmacSecret:sharedSecret,...binding}:{});return{server,startedByUs,tokenFactory:tokenFactory2,owner}}function acquireServer(chain){const config=resolveConfig(chain);const key=serverKey(config);let entry=serverEntries.get(key);if(!entry){entry=startServerEntry(config,ownerScopeOf(chain));serverEntries.set(key,entry);entry.catch(()=>serverEntries.delete(key))}return entry}async function stopServers(owner){for(const[key,pending]of Array.from(serverEntries)){let entry;try{entry=await pending}catch{serverEntries.delete(key);continue}if(owner&&entry.owner!==owner)continue;serverEntries.delete(key);if(entry.startedByUs){await entry.server.stop()}}}var fixtureContexts=new WeakMap;async function buildFixtures(chain){const config=resolveConfig(chain);const entry=await acquireServer(chain);const{server,tokenFactory:tokenFactory2}=entry;const publicMode=config.publicMode??config.auth?.mode==="public";const clientConfig={...config,publicMode};const clientInstance=McpTestClient.create({baseUrl:resolveClientBaseUrl(server,clientConfig),entryPath:clientConfig.entryPath,transport:clientConfig.transport??"streamable-http",publicMode}).build();try{await clientInstance.connect()}catch(err){const message=err instanceof Error?err.message:String(err);if(/\b401\b|unauthor/i.test(message)){console.warn(`[TestFixture] MCP client could not connect anonymously \u2014 the server requires authentication (${message}). Tests using only the 'server'/'auth' fixtures are unaffected; tests using the 'mcp' fixture must supply a token.`)}else{throw err}}const context={extraClients:[]};const fixtures={mcp:clientInstance,auth:createAuthFixture(tokenFactory2),server:createServerFixture(server,clientConfig,clientInstance,context)};fixtureContexts.set(fixtures,context);return fixtures}async function cleanupTestFixtures(fixtures,testFailed=false){if(testFailed){const logs=fixtures.server.getLogs();if(logs.length>0){console.error("\n[TestFixture] === Server Logs (test failed) ===");const recentLogs=logs.slice(-50);if(logs.length>50){console.error(`[TestFixture] (showing last 50 of ${logs.length} log entries)`)}console.error(recentLogs.join("\n"));console.error("[TestFixture] === End Server Logs ===\n")}}const extras=fixtureContexts.get(fixtures)?.extraClients??[];for(const client of extras){if(client.isConnected()){await client.disconnect().catch(()=>void 0)}}if(fixtures.mcp.isConnected()){await fixtures.mcp.disconnect()}}function resolveClientBaseUrl(server,config){return config.baseUrl??server.info.baseUrl}function createAuthFixture(factory){const users={admin:{sub:"admin-001",scopes:["admin:*","read","write","delete"],email:"admin@test.local",name:"Test Admin"},user:{sub:"user-001",scopes:["read","write"],email:"user@test.local",name:"Test User"},readOnly:{sub:"readonly-001",scopes:["read"],email:"readonly@test.local",name:"Read Only User"}};return{createToken:opts=>factory.createTestToken({sub:opts.sub,scopes:opts.scopes,claims:{email:opts.email,name:opts.name,...opts.claims},exp:opts.expiresIn}),createExpiredToken:opts=>factory.createExpiredToken(opts),createInvalidToken:opts=>factory.createTokenWithInvalidSignature(opts),users:{admin:users["admin"],user:users["user"],readOnly:users["readOnly"]},getJwks:()=>factory.getPublicJwks(),getIssuer:()=>factory.getIssuer(),getAudience:()=>factory.getAudience()}}function createServerFixture(server,config,mcp,context){return{get info(){return server.info},createClient:async opts=>{const client=await McpTestClient.create({baseUrl:resolveClientBaseUrl(server,config),entryPath:opts?.entryPath??config.entryPath,transport:opts?.transport??"streamable-http",auth:opts?.token?{token:opts.token}:void 0,clientInfo:opts?.clientInfo,publicMode:config.publicMode}).buildAndConnect();context.extraClients.push(client);return client},createClientBuilder:()=>{const builder=new McpTestClientBuilder({baseUrl:resolveClientBaseUrl(server,config),entryPath:config.entryPath,publicMode:config.publicMode});return builder},restart:async()=>{const reconnect=[mcp,...context.extraClients].filter(client=>client.isConnected());await server.restart();for(const client of reconnect){await client.reconnect()}},getLogs:()=>server.getLogs(),clearLogs:()=>server.clearLogs()}}function resolveServerCommand(server){if(server.includes(" ")){return server}return`npx tsx ${server}`}function runWithFixtures(fn,chain){return async(...extra)=>{const fixtures=await buildFixtures(chain);let failure;try{for(const scope of chain){for(const hook of scope.beforeEachHooks)await hook(fixtures)}await fn(fixtures,...extra)}catch(error){failure={error}}try{await runAfterEachHooks(chain,fixtures)}catch(error){failure??={error}}await cleanupTestFixtures(fixtures,failure!==void 0);if(failure)throw failure.error}}async function runAfterEachHooks(chain,fixtures){let firstError;let failed=false;for(let i=chain.length-1;i>=0;i--){for(const hook of chain[i].afterEachHooks){try{await hook(fixtures)}catch(error){if(!failed)firstError=error;failed=true}}}if(failed)throw firstError}function skipTitle(name,scope){return scope.reason?`${name} (skipped: ${scope.reason})`:name}function testWithFixtures(name,fn){const chain=scopes.slice();const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,chain));return}jestGlobals().it(name,runWithFixtures(fn,chain))}function use(config){const scope=currentScope();const{env,...rest}=config;scope.config={...scope.config,...rest};if(env)scope.envs.push(env);scope.configured=true;if(!scope.cleanupRegistered){scope.cleanupRegistered=true;jestGlobals().afterAll(async()=>{await stopServers(scope===scopes[0]?void 0:scope)})}}function skip(nameOrCondition,fnOrReason){if(typeof nameOrCondition==="boolean"){if(nameOrCondition){const scope=currentScope();scope.skipped=true;scope.reason=typeof fnOrReason==="string"?fnOrReason:void 0}return}if(typeof fnOrReason!=="function"){throw new TypeError(`test.skip expects either (name: string, fn) or (condition: boolean, reason?: string); received (${typeof nameOrCondition}, ${typeof fnOrReason}).`)}jestGlobals().it.skip(nameOrCondition,runWithFixtures(fnOrReason,scopes.slice()))}function only(name,fn){const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,scopes.slice()));return}jestGlobals().it.only(name,runWithFixtures(fn,scopes.slice()))}function todo(name){jestGlobals().it.todo(name)}function each(table,...tagged){const chain=scopes.slice();const register=jestGlobals().it.each(table,...tagged);return(name,fn)=>{const scope=currentScope();if(scope.skipped){const skipRegister=jestGlobals().it.skip.each(table,...tagged);skipRegister(skipTitle(name,scope),runWithFixtures(fn,chain));return}register(name,runWithFixtures(fn,chain))}}function withScope(fn){return(...args)=>{scopes.push(newScope(currentScope()));try{fn(...args)}finally{scopes.pop()}}}function scopedRegister(pick){return(name,fn,timeout)=>{pick()(name,withScope(fn),timeout)}}function scopedEach(pick){return(...eachArgs)=>(name,fn,timeout)=>{const register=pick()(...eachArgs);register(name,withScope(fn),timeout)}}var describeWithScope=Object.assign(scopedRegister(()=>jestGlobals().describe),{only:Object.assign(scopedRegister(()=>jestGlobals().describe.only),{each:scopedEach(()=>jestGlobals().describe.only.each)}),skip:Object.assign(scopedRegister(()=>jestGlobals().describe.skip),{each:scopedEach(()=>jestGlobals().describe.skip.each)}),each:scopedEach(()=>jestGlobals().describe.each)});function eachHook(kind){return(fn,timeout)=>{if(typeof fn==="function"&&fn.length>0){const scope=currentScope();(kind==="beforeEach"?scope.beforeEachHooks:scope.afterEachHooks).push(fn);return}jestGlobals()[kind](fn,timeout)}}var test=testWithFixtures;test.use=use;test.describe=describeWithScope;test.beforeAll=((...args)=>jestGlobals().beforeAll(...args));test.beforeEach=eachHook("beforeEach");test.afterEach=eachHook("afterEach");test.afterAll=((...args)=>jestGlobals().afterAll(...args));test.skip=skip;test.only=only;test.todo=todo;test.each=each;var resolvedExpect;function resolveJestExpect(){if(resolvedExpect)return resolvedExpect;try{resolvedExpect=__require("@jest/globals").expect;return resolvedExpect}catch(error){throw new Error(`expect() from @frontmcp/testing can only be used inside a Jest test file: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}var expect=new Proxy(function frontmcpExpect(){},{apply:(_target,thisArg,args)=>Reflect.apply(resolveJestExpect(),thisArg,args),get:(_target,prop)=>Reflect.get(resolveJestExpect(),prop),has:(_target,prop)=>Reflect.has(resolveJestExpect(),prop)});function getPlatformMetaNamespace(platform){return"ui"}function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function isOpenAIPlatform(platform){return platform==="openai"}function isExtAppsPlatform(platform){return platform==="ext-apps"}function isUiPlatform(platform){return true}function getToolsListMetaPrefixes(platform){return["ui/"]}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};var toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};var toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};var toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};var toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType2=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType2||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};var toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};var toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};var toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};var toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};var toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};var toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};var toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};var toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};var toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};var toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};var uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml};var toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};var toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};var toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};var toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};var toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};var toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};var toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};var toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};var toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};var toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};var toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};var toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};var toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};var toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};var toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};var mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers};var originalFetch=null;var mockingEnabled=false;var activeInterceptors=[];var HttpInterceptorImpl=class{mocks=[];_allowPassthrough=false;_isActive=true;mock(definition){const entry={definition,callCount:0,calls:[],remainingUses:definition.times??Infinity};this.mocks.push(entry);return{remove:()=>{const index=this.mocks.indexOf(entry);if(index!==-1){this.mocks.splice(index,1)}},callCount:()=>entry.callCount,calls:()=>[...entry.calls],waitForCalls:async(count,timeoutMs=5e3)=>{const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(entry.callCount>=count){return entry.calls.slice(0,count)}await sleep3(50)}throw new Error(`Timeout waiting for ${count} calls, got ${entry.callCount}`)}}}get(url,response,options){return this.mock({match:{url,method:"GET",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}post(url,response,options){return this.mock({match:{url,method:"POST",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}put(url,response,options){return this.mock({match:{url,method:"PUT",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}delete(url,response,options){return this.mock({match:{url,method:"DELETE",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}any(url,response,options){return this.mock({match:{url,...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}clear(){this.mocks=[]}pending(){return this.mocks.filter(m=>m.remainingUses>0).map(m=>m.definition)}isDone(){return this.mocks.every(m=>m.remainingUses<=0||m.definition.times===void 0)}assertDone(){const pending=this.pending().filter(m=>m.times!==void 0);if(pending.length>0){const descriptions=pending.map(m=>{const url=m.match.url instanceof RegExp?m.match.url.toString():m.match.url;return` - ${m.match.method??"ANY"} ${url}`});throw new Error(`Unused HTTP mocks:
112
+ Error: ${errMsg}`,{cause:error})}}else{throw new Error('test.use() requires either "server" (entry file path) or "baseUrl" (for external server) option')}const sharedSecret=config.env?.["JWT_SECRET"];const binding=sharedSecret?gatewayTokenBinding(config.baseUrl??server.info.baseUrl,config.entryPath):void 0;const tokenFactory2=new TestTokenFactory(sharedSecret?{hmacSecret:sharedSecret,...binding}:{});return{server,startedByUs,tokenFactory:tokenFactory2,owner}}function acquireServer(chain){const config=resolveConfig(chain);const key=serverKey(config);let entry=serverEntries.get(key);if(!entry){entry=startServerEntry(config,ownerScopeOf(chain));serverEntries.set(key,entry);entry.catch(()=>serverEntries.delete(key))}return entry}async function stopServers(owner){for(const[key,pending]of Array.from(serverEntries)){let entry;try{entry=await pending}catch{serverEntries.delete(key);continue}if(owner&&entry.owner!==owner)continue;serverEntries.delete(key);if(entry.startedByUs){await entry.server.stop()}}}var fixtureContexts=new WeakMap;async function buildFixtures(chain){const config=resolveConfig(chain);const entry=await acquireServer(chain);const{server,tokenFactory:tokenFactory2}=entry;const publicMode=config.publicMode??config.auth?.mode==="public";const clientConfig={...config,publicMode};const clientInstance=McpTestClient.create({baseUrl:resolveClientBaseUrl(server,clientConfig),entryPath:clientConfig.entryPath,transport:clientConfig.transport??"streamable-http",publicMode}).build();try{await clientInstance.connect()}catch(err){const message=err instanceof Error?err.message:String(err);if(/\b401\b|unauthor/i.test(message)){console.warn(`[TestFixture] MCP client could not connect anonymously \u2014 the server requires authentication (${message}). Tests using only the 'server'/'auth' fixtures are unaffected; tests using the 'mcp' fixture must supply a token.`)}else{throw err}}const context={extraClients:[]};const fixtures={mcp:clientInstance,auth:createAuthFixture(tokenFactory2),server:createServerFixture(server,clientConfig,clientInstance,context)};fixtureContexts.set(fixtures,context);return fixtures}async function cleanupTestFixtures(fixtures,testFailed=false){if(testFailed){const logs=fixtures.server.getLogs();if(logs.length>0){console.error("\n[TestFixture] === Server Logs (test failed) ===");const recentLogs=logs.slice(-50);if(logs.length>50){console.error(`[TestFixture] (showing last 50 of ${logs.length} log entries)`)}console.error(recentLogs.join("\n"));console.error("[TestFixture] === End Server Logs ===\n")}}const extras=fixtureContexts.get(fixtures)?.extraClients??[];for(const client of extras){if(client.isConnected()){await client.disconnect().catch(()=>void 0)}}if(fixtures.mcp.isConnected()){await fixtures.mcp.disconnect()}}function resolveClientBaseUrl(server,config){return config.baseUrl??server.info.baseUrl}function createAuthFixture(factory){const users={admin:{sub:"admin-001",scopes:["admin:*","read","write","delete"],email:"admin@test.local",name:"Test Admin"},user:{sub:"user-001",scopes:["read","write"],email:"user@test.local",name:"Test User"},readOnly:{sub:"readonly-001",scopes:["read"],email:"readonly@test.local",name:"Read Only User"}};return{createToken:opts=>factory.createTestToken({sub:opts.sub,scopes:opts.scopes,claims:{email:opts.email,name:opts.name,...opts.claims},exp:opts.expiresIn}),createExpiredToken:opts=>factory.createExpiredToken(opts),createInvalidToken:opts=>factory.createTokenWithInvalidSignature(opts),users:{admin:users["admin"],user:users["user"],readOnly:users["readOnly"]},getJwks:()=>factory.getPublicJwks(),getIssuer:()=>factory.getIssuer(),getAudience:()=>factory.getAudience()}}function createServerFixture(server,config,mcp,context){return{get info(){return server.info},createClient:async opts=>{const client=await McpTestClient.create({baseUrl:resolveClientBaseUrl(server,config),entryPath:opts?.entryPath??config.entryPath,transport:opts?.transport??"streamable-http",auth:opts?.token?{token:opts.token}:void 0,clientInfo:opts?.clientInfo,publicMode:config.publicMode}).buildAndConnect();context.extraClients.push(client);return client},createClientBuilder:()=>{const builder=new McpTestClientBuilder({baseUrl:resolveClientBaseUrl(server,config),entryPath:config.entryPath,publicMode:config.publicMode});return builder},restart:async()=>{const reconnect=[mcp,...context.extraClients].filter(client=>client.isConnected());await server.restart();for(const client of reconnect){await client.reconnect()}},getLogs:()=>server.getLogs(),clearLogs:()=>server.clearLogs()}}function resolveServerCommand(server){if(server.includes(" ")){return server}return`npx tsx ${server}`}function runWithFixtures(fn,chain){return async(...extra)=>{const fixtures=await buildFixtures(chain);let failure;try{for(const scope of chain){for(const hook of scope.beforeEachHooks)await hook(fixtures)}await fn(fixtures,...extra)}catch(error){failure={error}}try{await runAfterEachHooks(chain,fixtures)}catch(error){failure??={error}}await cleanupTestFixtures(fixtures,failure!==void 0);if(failure)throw failure.error}}async function runAfterEachHooks(chain,fixtures){let firstError;let failed=false;for(let i=chain.length-1;i>=0;i--){for(const hook of chain[i].afterEachHooks){try{await hook(fixtures)}catch(error){if(!failed)firstError=error;failed=true}}}if(failed)throw firstError}function skipTitle(name,scope){return scope.reason?`${name} (skipped: ${scope.reason})`:name}function testWithFixtures(name,fn){const chain=scopes.slice();const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,chain));return}jestGlobals().it(name,runWithFixtures(fn,chain))}function use(config){const scope=currentScope();const{env,...rest}=config;scope.config={...scope.config,...rest};if(env)scope.envs.push(env);scope.configured=true;if(!scope.cleanupRegistered){scope.cleanupRegistered=true;jestGlobals().afterAll(async()=>{await stopServers(scope===scopes[0]?void 0:scope)})}}function skip(nameOrCondition,fnOrReason){if(typeof nameOrCondition==="boolean"){if(nameOrCondition){const scope=currentScope();scope.skipped=true;scope.reason=typeof fnOrReason==="string"?fnOrReason:void 0}return}if(typeof fnOrReason!=="function"){throw new TypeError(`test.skip expects either (name: string, fn) or (condition: boolean, reason?: string); received (${typeof nameOrCondition}, ${typeof fnOrReason}).`)}jestGlobals().it.skip(nameOrCondition,runWithFixtures(fnOrReason,scopes.slice()))}function only(name,fn){const scope=currentScope();if(scope.skipped){jestGlobals().it.skip(skipTitle(name,scope),runWithFixtures(fn,scopes.slice()));return}jestGlobals().it.only(name,runWithFixtures(fn,scopes.slice()))}function todo(name){jestGlobals().it.todo(name)}function each(table,...tagged){const chain=scopes.slice();const register=jestGlobals().it.each(table,...tagged);return(name,fn)=>{const scope=currentScope();if(scope.skipped){const skipRegister=jestGlobals().it.skip.each(table,...tagged);skipRegister(skipTitle(name,scope),runWithFixtures(fn,chain));return}register(name,runWithFixtures(fn,chain))}}function withScope(fn){return(...args)=>{scopes.push(newScope(currentScope()));try{fn(...args)}finally{scopes.pop()}}}function scopedRegister(pick){return(name,fn,timeout)=>{pick()(name,withScope(fn),timeout)}}function scopedEach(pick){return(...eachArgs)=>(name,fn,timeout)=>{const register=pick()(...eachArgs);register(name,withScope(fn),timeout)}}var describeWithScope=Object.assign(scopedRegister(()=>jestGlobals().describe),{only:Object.assign(scopedRegister(()=>jestGlobals().describe.only),{each:scopedEach(()=>jestGlobals().describe.only.each)}),skip:Object.assign(scopedRegister(()=>jestGlobals().describe.skip),{each:scopedEach(()=>jestGlobals().describe.skip.each)}),each:scopedEach(()=>jestGlobals().describe.each)});function eachHook(kind){return(fn,timeout)=>{if(typeof fn==="function"&&fn.length>0){const scope=currentScope();(kind==="beforeEach"?scope.beforeEachHooks:scope.afterEachHooks).push(fn);return}jestGlobals()[kind](fn,timeout)}}var test=testWithFixtures;test.use=use;test.describe=describeWithScope;test.beforeAll=((...args)=>jestGlobals().beforeAll(...args));test.beforeEach=eachHook("beforeEach");test.afterEach=eachHook("afterEach");test.afterAll=((...args)=>jestGlobals().afterAll(...args));test.skip=skip;test.only=only;test.todo=todo;test.each=each;var resolvedExpect;function resolveJestExpect(){if(resolvedExpect)return resolvedExpect;try{resolvedExpect=__require("@jest/globals").expect;return resolvedExpect}catch(error){throw new Error(`expect() from @frontmcp/testing can only be used inside a Jest test file: ${error instanceof Error?error.message:String(error)}`,{cause:error})}}var expect=new Proxy(function frontmcpExpect(){},{apply:(_target,thisArg,args)=>Reflect.apply(resolveJestExpect(),thisArg,args),get:(_target,prop)=>Reflect.get(resolveJestExpect(),prop),has:(_target,prop)=>Reflect.has(resolveJestExpect(),prop)});import{hasTransform,z}from"@frontmcp/lazy-zod";import{findDroppedKeys}from"@frontmcp/utils";function getPlatformMetaNamespace(platform){return"ui"}function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function isOpenAIPlatform(platform){return platform==="openai"}function isExtAppsPlatform(platform){return platform==="ext-apps"}function isUiPlatform(platform){return true}function getToolsListMetaPrefixes(platform){return["ui/"]}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};var toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};var toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};var toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};var toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType2=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType2||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};var toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};var toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};var toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};var toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};var toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};var toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};var toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};var toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};var toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};var toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};var uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml};var toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};var toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};var toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};var toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};var toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};var toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};var toPassOutputSchemaWhole=function(received,outputSchema){const schema=outputSchema instanceof z.ZodType?outputSchema:z.object(outputSchema);if(hasTransform(schema)){return{pass:false,message:()=>"toPassOutputSchemaWhole cannot compare keys through a transform (.transform(), z.preprocess(), .pipe()): assert on the parsed answer instead"}}const parsed=schema.safeParse(received);if(!parsed.success){const[firstIssue]=parsed.error.issues;const location=firstIssue?.path.length?` at ${firstIssue.path.join(".")}`:"";return{pass:false,message:()=>`Expected the answer to pass its output schema whole, but it does not match its output schema${location}: ${firstIssue?.message}`}}const droppedKeys=findDroppedKeys(received,parsed.data);const pass=droppedKeys.length===0;return{pass,message:()=>pass?"Expected the answer not to pass its output schema whole":`Expected the answer to pass its output schema whole, but parsing drops keys it does not declare: ${droppedKeys.join(", ")}`}};var toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};var toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};var toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};var toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};var toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};var toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};var toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};var toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};var toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};var mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toPassOutputSchemaWhole,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers};var originalFetch=null;var mockingEnabled=false;var activeInterceptors=[];var HttpInterceptorImpl=class{mocks=[];_allowPassthrough=false;_isActive=true;mock(definition){const entry={definition,callCount:0,calls:[],remainingUses:definition.times??Infinity};this.mocks.push(entry);return{remove:()=>{const index=this.mocks.indexOf(entry);if(index!==-1){this.mocks.splice(index,1)}},callCount:()=>entry.callCount,calls:()=>[...entry.calls],waitForCalls:async(count,timeoutMs=5e3)=>{const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(entry.callCount>=count){return entry.calls.slice(0,count)}await sleep3(50)}throw new Error(`Timeout waiting for ${count} calls, got ${entry.callCount}`)}}}get(url,response,options){return this.mock({match:{url,method:"GET",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}post(url,response,options){return this.mock({match:{url,method:"POST",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}put(url,response,options){return this.mock({match:{url,method:"PUT",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}delete(url,response,options){return this.mock({match:{url,method:"DELETE",...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}any(url,response,options){return this.mock({match:{url,...options?.match},response:normalizeResponse(response),...options?.times!==void 0&&{times:options.times},...options?.name!==void 0&&{name:options.name}})}clear(){this.mocks=[]}pending(){return this.mocks.filter(m=>m.remainingUses>0).map(m=>m.definition)}isDone(){return this.mocks.every(m=>m.remainingUses<=0||m.definition.times===void 0)}assertDone(){const pending=this.pending().filter(m=>m.times!==void 0);if(pending.length>0){const descriptions=pending.map(m=>{const url=m.match.url instanceof RegExp?m.match.url.toString():m.match.url;return` - ${m.match.method??"ANY"} ${url}`});throw new Error(`Unused HTTP mocks:
113
113
  ${descriptions.join("\n")}`)}}allowPassthrough(allow){this._allowPassthrough=allow}restore(){this._isActive=false;const index=activeInterceptors.indexOf(this);if(index!==-1){activeInterceptors.splice(index,1)}if(activeInterceptors.length===0){httpMock.disable()}}isActive(){return this._isActive}canPassthrough(){return this._allowPassthrough}async matchRequest(info){if(!this._isActive)return null;for(const entry of this.mocks){if(entry.remainingUses<=0)continue;if(this.requestMatches(info,entry.definition.match)){entry.callCount++;entry.calls.push(info);entry.remainingUses--;let mockResponse2;if(typeof entry.definition.response==="function"){mockResponse2=await entry.definition.response(info)}else{mockResponse2=entry.definition.response}if(mockResponse2.delay&&mockResponse2.delay>0){await sleep3(mockResponse2.delay)}return createMockResponse(mockResponse2)}}return null}requestMatches(info,matcher){if(!this.urlMatches(info.url,matcher.url)){return false}if(matcher.method){const methods=Array.isArray(matcher.method)?matcher.method:[matcher.method];if(!methods.includes(info.method)){return false}}if(matcher.headers){for(const[key,expected]of Object.entries(matcher.headers)){const actual=info.headers[key.toLowerCase()];if(!actual)return false;if(expected instanceof RegExp){if(!expected.test(actual))return false}else if(actual!==expected){return false}}}if(matcher.body!==void 0){if(!this.bodyMatches(info.body,matcher.body)){return false}}return true}urlMatches(url,matcher){if(typeof matcher==="string"){return url===matcher||url.includes(matcher)}else if(matcher instanceof RegExp){return matcher.test(url)}else{return matcher(url)}}bodyMatches(actual,expected){if(typeof expected==="function"){return expected(actual)}if(typeof expected==="string"){const actualStr=typeof actual==="string"?actual:JSON.stringify(actual);return actualStr===expected||actualStr.includes(expected)}if(expected instanceof RegExp){const actualStr=typeof actual==="string"?actual:JSON.stringify(actual);return expected.test(actualStr)}if(typeof actual!=="object"||actual===null){return false}for(const[key,value]of Object.entries(expected)){const actualValue=actual[key];if(typeof value==="object"&&value!==null){if(!this.bodyMatches(actualValue,value)){return false}}else if(actualValue!==value){return false}}return true}};async function interceptedFetch(input,init){const request=typeof Request!=="undefined"&&input instanceof Request?input:void 0;const url=typeof input==="string"?input:input instanceof URL?input.toString():request?.url??String(input);const method=(init?.method??request?.method??"GET").toUpperCase();const headers={};const collectHeaders=source=>{if(!source)return;if(source instanceof Headers){source.forEach((value,key)=>{headers[key.toLowerCase()]=value})}else if(Array.isArray(source)){for(const[key,value]of source){headers[key.toLowerCase()]=value}}else{for(const[key,value]of Object.entries(source)){headers[key.toLowerCase()]=value}}};collectHeaders(init?.headers??request?.headers);let body;let rawBody;let bodySource=init?.body;if((bodySource===void 0||bodySource===null)&&request&&request.body!==null){bodySource=await request.clone().text()}if(bodySource){if(typeof bodySource==="string"){rawBody=bodySource}else if(bodySource instanceof ArrayBuffer||ArrayBuffer.isView(bodySource)){rawBody=new TextDecoder().decode(bodySource)}else if(bodySource instanceof URLSearchParams){rawBody=bodySource.toString()}if(rawBody!==void 0){try{body=JSON.parse(rawBody)}catch{body=rawBody}}else{body=bodySource}}const requestInfo={url,method,headers,body,rawBody};for(let i=activeInterceptors.length-1;i>=0;i--){const interceptor=activeInterceptors[i];if(!interceptor.isActive())continue;const mockResponse2=await interceptor.matchRequest(requestInfo);if(mockResponse2){return mockResponse2}}for(const interceptor of activeInterceptors){if(interceptor.isActive()&&interceptor.canPassthrough()){if(originalFetch){return originalFetch(input,init)}}}throw new Error(`No HTTP mock found for ${method} ${url}
114
- Add a mock using httpMock.interceptor().${method.toLowerCase()}('${url}', { body: ... })`)}var RESPONSE_KEYS=new Set(["status","statusText","headers","body","delay"]);function isResponseDescriptor(value){const keys=Object.keys(value);if(keys.length===0||!keys.every(key=>RESPONSE_KEYS.has(key)))return false;if("status"in value){const status=value["status"];if(typeof status!=="number"||!Number.isInteger(status)||status<200||status>599)return false}return true}function normalizeResponse(response){const isNetworkError=!Array.isArray(response)&&response["_throwError"]===true;if(isNetworkError)return response;if(Array.isArray(response)||!isResponseDescriptor(response)){return{body:response}}return response}function createMockResponse(mock){const mockAny=mock;if(mockAny._throwError){const body2=mock.body;const message=body2&&typeof body2==="object"&&"message"in body2?String(body2["message"]):"Network error";throw new TypeError(`fetch failed: ${message}`)}const status=mock.status??200;const statusText=mock.statusText??"OK";const headers=new Headers(mock.headers??{});let body=null;if(mock.body!==void 0){if(typeof mock.body==="string"){body=mock.body;if(!headers.has("content-type")){headers.set("content-type","text/plain")}}else if(mock.body instanceof ArrayBuffer){body=mock.body}else if(Buffer.isBuffer(mock.body)){body=new Uint8Array(mock.body).buffer}else{body=JSON.stringify(mock.body);if(!headers.has("content-type")){headers.set("content-type","application/json")}}}return new Response(body,{status,statusText,headers})}function sleep3(ms){return new Promise(resolve=>setTimeout(resolve,ms))}var HttpMockManagerImpl=class{interceptor(){if(!mockingEnabled){this.enable()}const interceptor=new HttpInterceptorImpl;activeInterceptors.push(interceptor);return interceptor}enable(){if(mockingEnabled)return;if(typeof globalThis.fetch==="function"){originalFetch=globalThis.fetch;globalThis.fetch=interceptedFetch}mockingEnabled=true}disable(){if(!mockingEnabled)return;if(originalFetch){globalThis.fetch=originalFetch;originalFetch=null}activeInterceptors.length=0;mockingEnabled=false}isEnabled(){return mockingEnabled}clearAll(){for(const interceptor of activeInterceptors){interceptor.clear()}activeInterceptors.length=0}};var httpMock=new HttpMockManagerImpl;var httpResponse={json(data,status=200){return{status,headers:{"content-type":"application/json"},body:data}},text(data,status=200){return{status,headers:{"content-type":"text/plain"},body:data}},html(data,status=200){return{status,headers:{"content-type":"text/html"},body:data}},error(status,message){return{status,statusText:message??getStatusText(status),body:message?{error:message}:void 0}},notFound(message="Not Found"){return httpResponse.error(404,message)},serverError(message="Internal Server Error"){return httpResponse.error(500,message)},unauthorized(message="Unauthorized"){return httpResponse.error(401,message)},forbidden(message="Forbidden"){return httpResponse.error(403,message)},networkError(message="Network error"){return{status:0,body:{_networkError:true,message},_throwError:true}},delayed(data,delayMs,status=200){return{status,body:data,delay:delayMs}}};function getStatusText(status){const texts={200:"OK",201:"Created",204:"No Content",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"};return texts[status]??"Unknown"}function escapeRegex2(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var UIAssertions={assertRenderedUI(result){const meta=result.raw._meta;if(!meta){throw new Error("Expected tool result to have _meta, but _meta is undefined")}const html=meta["ui/html"];if(!html){throw new Error("Expected tool result to have ui/html in _meta, but it is missing")}if(typeof html!=="string"){throw new Error(`Expected ui/html to be a string, but got ${typeof html}`)}if(html.includes("mdx-fallback")){throw new Error("Got mdx-fallback instead of rendered HTML - MDX/React rendering failed. Check that @mdx-js/mdx is installed and the template syntax is valid.")}return html},assertDataBinding(html,output,keys){const missingKeys=[];for(const key of keys){const value=output[key];if(value===void 0||value===null){continue}const stringValue=String(value);if(!html.includes(stringValue)){missingKeys.push(`${key}="${stringValue}"`)}}if(missingKeys.length>0){throw new Error(`Expected HTML to contain bound values for: ${missingKeys.join(", ")}. Data binding may have failed.`)}},assertXssSafe(html){const vulnerabilities=[];if(/<script[\s>]/i.test(html)){vulnerabilities.push("<script> tag detected")}if(/\son\w+\s*=/i.test(html)){vulnerabilities.push("inline event handler detected (onclick, onerror, etc.)")}if(/javascript:/i.test(html)){vulnerabilities.push("javascript: URI detected")}if(vulnerabilities.length>0){throw new Error(`Potential XSS vulnerabilities found: ${vulnerabilities.join("; ")}`)}},assertProperHtmlStructure(html){if(html.includes("&lt;")&&html.includes("&gt;")){throw new Error("HTML contains escaped HTML entities (&lt;, &gt;) - content was likely not rendered. Check that the template is being processed correctly.")}if(!/<[a-z]/i.test(html)){throw new Error("HTML contains no HTML tags - content may be plain text or rendering failed.")}},assertContainsElement(html,tag){const regex=new RegExp(`<${escapeRegex2(tag)}[\\s>]`,"i");if(!regex.test(html)){throw new Error(`Expected HTML to contain <${tag}> element`)}},assertHasCssClass(html,className){const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex2(className)}\\b[^"']*["']`,"i");if(!classRegex.test(html)){throw new Error(`Expected HTML to have CSS class "${className}"`)}},assertNotContainsRaw(html,content){if(html.includes(content)){throw new Error(`HTML contains raw content "${content}" - this component may not have been rendered. Check that all custom components are properly passed to the renderer.`)}},assertWidgetMetadata(result){const meta=result.raw._meta;if(!meta){throw new Error("Expected tool result to have _meta with widget metadata")}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType2=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");if(!hasUiHtml&&!hasMimeType2&&!hasUiObject){throw new Error("Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)")}},assertValidUI(result,boundKeys){const html=UIAssertions.assertRenderedUI(result);UIAssertions.assertProperHtmlStructure(html);UIAssertions.assertXssSafe(html);if(boundKeys&&boundKeys.length>0){try{const output=JSON.parse(result.text()||"{}");UIAssertions.assertDataBinding(html,output,boundKeys)}catch{}}return html},assertOpenAIMeta(result){UIAssertions.assertPlatformMeta(result,"openai")},assertExtAppsMeta(result){UIAssertions.assertPlatformMeta(result,"ext-apps")},assertUiMeta(result){UIAssertions.assertPlatformMeta(result,"claude")},assertPlatformMeta(result,platform){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with platform meta for "${platform}"`)}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));if(!hasExpectedPrefix){throw new Error(`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`)}const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));if(forbiddenKeys.length>0){throw new Error(`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`)}},assertNoMixedNamespaces(result,expectedNamespace){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with namespace "${expectedNamespace}"`)}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(expectedNamespace));if(wrongKeys.length>0){throw new Error(`Expected _meta to ONLY have keys with namespace "${expectedNamespace}", but found: [${wrongKeys.join(", ")}]`)}},assertPlatformMimeType(result,platform){const meta=result.raw._meta;const expectedMimeType=getPlatformMimeType(platform);if(!meta){throw new Error(`Expected tool result to have _meta with MIME type for platform "${platform}"`)}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];if(actualMimeType!==expectedMimeType){throw new Error(`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`)}},assertPlatformHtml(result,platform){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with platform HTML for "${platform}"`)}const htmlKey="ui/html";const html=meta[htmlKey];if(typeof html!=="string"||html.length===0){throw new Error(`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`)}return html},assertValidPlatformMeta(result,platform){UIAssertions.assertPlatformMeta(result,platform);UIAssertions.assertPlatformMimeType(result,platform);return UIAssertions.assertPlatformHtml(result,platform)}};import{z}from"@frontmcp/lazy-zod";var basicUIToolInputSchema=z.object({name:z.string().optional().default("World")});var basicUIToolOutputSchema=z.object({message:z.string(),timestamp:z.number()});var BASIC_UI_TOOL_CONFIG={name:"platform-test-basic",description:"Basic UI tool for platform testing",inputSchema:basicUIToolInputSchema,outputSchema:basicUIToolOutputSchema,ui:{template:`
114
+ Add a mock using httpMock.interceptor().${method.toLowerCase()}('${url}', { body: ... })`)}var RESPONSE_KEYS=new Set(["status","statusText","headers","body","delay"]);function isResponseDescriptor(value){const keys=Object.keys(value);if(keys.length===0||!keys.every(key=>RESPONSE_KEYS.has(key)))return false;if("status"in value){const status=value["status"];if(typeof status!=="number"||!Number.isInteger(status)||status<200||status>599)return false}return true}function normalizeResponse(response){const isNetworkError=!Array.isArray(response)&&response["_throwError"]===true;if(isNetworkError)return response;if(Array.isArray(response)||!isResponseDescriptor(response)){return{body:response}}return response}function createMockResponse(mock){const mockAny=mock;if(mockAny._throwError){const body2=mock.body;const message=body2&&typeof body2==="object"&&"message"in body2?String(body2["message"]):"Network error";throw new TypeError(`fetch failed: ${message}`)}const status=mock.status??200;const statusText=mock.statusText??"OK";const headers=new Headers(mock.headers??{});let body=null;if(mock.body!==void 0){if(typeof mock.body==="string"){body=mock.body;if(!headers.has("content-type")){headers.set("content-type","text/plain")}}else if(mock.body instanceof ArrayBuffer){body=mock.body}else if(Buffer.isBuffer(mock.body)){body=new Uint8Array(mock.body).buffer}else{body=JSON.stringify(mock.body);if(!headers.has("content-type")){headers.set("content-type","application/json")}}}return new Response(body,{status,statusText,headers})}function sleep3(ms){return new Promise(resolve=>setTimeout(resolve,ms))}var HttpMockManagerImpl=class{interceptor(){if(!mockingEnabled){this.enable()}const interceptor=new HttpInterceptorImpl;activeInterceptors.push(interceptor);return interceptor}enable(){if(mockingEnabled)return;if(typeof globalThis.fetch==="function"){originalFetch=globalThis.fetch;globalThis.fetch=interceptedFetch}mockingEnabled=true}disable(){if(!mockingEnabled)return;if(originalFetch){globalThis.fetch=originalFetch;originalFetch=null}activeInterceptors.length=0;mockingEnabled=false}isEnabled(){return mockingEnabled}clearAll(){for(const interceptor of activeInterceptors){interceptor.clear()}activeInterceptors.length=0}};var httpMock=new HttpMockManagerImpl;var httpResponse={json(data,status=200){return{status,headers:{"content-type":"application/json"},body:data}},text(data,status=200){return{status,headers:{"content-type":"text/plain"},body:data}},html(data,status=200){return{status,headers:{"content-type":"text/html"},body:data}},error(status,message){return{status,statusText:message??getStatusText(status),body:message?{error:message}:void 0}},notFound(message="Not Found"){return httpResponse.error(404,message)},serverError(message="Internal Server Error"){return httpResponse.error(500,message)},unauthorized(message="Unauthorized"){return httpResponse.error(401,message)},forbidden(message="Forbidden"){return httpResponse.error(403,message)},networkError(message="Network error"){return{status:0,body:{_networkError:true,message},_throwError:true}},delayed(data,delayMs,status=200){return{status,body:data,delay:delayMs}}};function getStatusText(status){const texts={200:"OK",201:"Created",204:"No Content",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"};return texts[status]??"Unknown"}function escapeRegex2(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var UIAssertions={assertRenderedUI(result){const meta=result.raw._meta;if(!meta){throw new Error("Expected tool result to have _meta, but _meta is undefined")}const html=meta["ui/html"];if(!html){throw new Error("Expected tool result to have ui/html in _meta, but it is missing")}if(typeof html!=="string"){throw new Error(`Expected ui/html to be a string, but got ${typeof html}`)}if(html.includes("mdx-fallback")){throw new Error("Got mdx-fallback instead of rendered HTML - MDX/React rendering failed. Check that @mdx-js/mdx is installed and the template syntax is valid.")}return html},assertDataBinding(html,output,keys){const missingKeys=[];for(const key of keys){const value=output[key];if(value===void 0||value===null){continue}const stringValue=String(value);if(!html.includes(stringValue)){missingKeys.push(`${key}="${stringValue}"`)}}if(missingKeys.length>0){throw new Error(`Expected HTML to contain bound values for: ${missingKeys.join(", ")}. Data binding may have failed.`)}},assertXssSafe(html){const vulnerabilities=[];if(/<script[\s>]/i.test(html)){vulnerabilities.push("<script> tag detected")}if(/\son\w+\s*=/i.test(html)){vulnerabilities.push("inline event handler detected (onclick, onerror, etc.)")}if(/javascript:/i.test(html)){vulnerabilities.push("javascript: URI detected")}if(vulnerabilities.length>0){throw new Error(`Potential XSS vulnerabilities found: ${vulnerabilities.join("; ")}`)}},assertProperHtmlStructure(html){if(html.includes("&lt;")&&html.includes("&gt;")){throw new Error("HTML contains escaped HTML entities (&lt;, &gt;) - content was likely not rendered. Check that the template is being processed correctly.")}if(!/<[a-z]/i.test(html)){throw new Error("HTML contains no HTML tags - content may be plain text or rendering failed.")}},assertContainsElement(html,tag){const regex=new RegExp(`<${escapeRegex2(tag)}[\\s>]`,"i");if(!regex.test(html)){throw new Error(`Expected HTML to contain <${tag}> element`)}},assertHasCssClass(html,className){const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex2(className)}\\b[^"']*["']`,"i");if(!classRegex.test(html)){throw new Error(`Expected HTML to have CSS class "${className}"`)}},assertNotContainsRaw(html,content){if(html.includes(content)){throw new Error(`HTML contains raw content "${content}" - this component may not have been rendered. Check that all custom components are properly passed to the renderer.`)}},assertWidgetMetadata(result){const meta=result.raw._meta;if(!meta){throw new Error("Expected tool result to have _meta with widget metadata")}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType2=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");if(!hasUiHtml&&!hasMimeType2&&!hasUiObject){throw new Error("Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)")}},assertValidUI(result,boundKeys){const html=UIAssertions.assertRenderedUI(result);UIAssertions.assertProperHtmlStructure(html);UIAssertions.assertXssSafe(html);if(boundKeys&&boundKeys.length>0){try{const output=JSON.parse(result.text()||"{}");UIAssertions.assertDataBinding(html,output,boundKeys)}catch{}}return html},assertOpenAIMeta(result){UIAssertions.assertPlatformMeta(result,"openai")},assertExtAppsMeta(result){UIAssertions.assertPlatformMeta(result,"ext-apps")},assertUiMeta(result){UIAssertions.assertPlatformMeta(result,"claude")},assertPlatformMeta(result,platform){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with platform meta for "${platform}"`)}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));if(!hasExpectedPrefix){throw new Error(`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`)}const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));if(forbiddenKeys.length>0){throw new Error(`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`)}},assertNoMixedNamespaces(result,expectedNamespace){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with namespace "${expectedNamespace}"`)}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(expectedNamespace));if(wrongKeys.length>0){throw new Error(`Expected _meta to ONLY have keys with namespace "${expectedNamespace}", but found: [${wrongKeys.join(", ")}]`)}},assertPlatformMimeType(result,platform){const meta=result.raw._meta;const expectedMimeType=getPlatformMimeType(platform);if(!meta){throw new Error(`Expected tool result to have _meta with MIME type for platform "${platform}"`)}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];if(actualMimeType!==expectedMimeType){throw new Error(`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`)}},assertPlatformHtml(result,platform){const meta=result.raw._meta;if(!meta){throw new Error(`Expected tool result to have _meta with platform HTML for "${platform}"`)}const htmlKey="ui/html";const html=meta[htmlKey];if(typeof html!=="string"||html.length===0){throw new Error(`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`)}return html},assertValidPlatformMeta(result,platform){UIAssertions.assertPlatformMeta(result,platform);UIAssertions.assertPlatformMimeType(result,platform);return UIAssertions.assertPlatformHtml(result,platform)}};import{z as z2}from"@frontmcp/lazy-zod";var basicUIToolInputSchema=z2.object({name:z2.string().optional().default("World")});var basicUIToolOutputSchema=z2.object({message:z2.string(),timestamp:z2.number()});var BASIC_UI_TOOL_CONFIG={name:"platform-test-basic",description:"Basic UI tool for platform testing",inputSchema:basicUIToolInputSchema,outputSchema:basicUIToolOutputSchema,ui:{template:`
115
115
  <div class="platform-test-basic">
116
116
  <h1>Platform Test - Basic</h1>
117
117
  <p>Message: {output.message}</p>
118
118
  <p>Timestamp: {output.timestamp}</p>
119
119
  </div>
120
- `.trim()}};var fullUIToolInputSchema=z.object({name:z.string().optional().default("World"),count:z.number().optional().default(1)});var fullUIToolOutputSchema=z.object({message:z.string(),count:z.number(),items:z.array(z.string()),timestamp:z.number()});var FULL_UI_TOOL_CONFIG={name:"platform-test-full",description:"Full UI tool with all options for comprehensive platform testing",inputSchema:fullUIToolInputSchema,outputSchema:fullUIToolOutputSchema,ui:{template:`
120
+ `.trim()}};var fullUIToolInputSchema=z2.object({name:z2.string().optional().default("World"),count:z2.number().optional().default(1)});var fullUIToolOutputSchema=z2.object({message:z2.string(),count:z2.number(),items:z2.array(z2.string()),timestamp:z2.number()});var FULL_UI_TOOL_CONFIG={name:"platform-test-full",description:"Full UI tool with all options for comprehensive platform testing",inputSchema:fullUIToolInputSchema,outputSchema:fullUIToolOutputSchema,ui:{template:`
121
121
  <div class="platform-test-full">
122
122
  <h1>Platform Test - Full</h1>
123
123
  <div class="message-box">
@@ -1 +1 @@
1
- function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};var toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};var toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};var toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};var toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};var toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};var toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};var toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};var toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};var toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};var toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};var toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};var toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};var toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};var toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};var uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml};var toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};var toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};var toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};var toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};var toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};var toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};var toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};var toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};var toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};var toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};var toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};var toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};var toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};var toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};var toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};var mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers};export{mcpMatchers};
1
+ import{hasTransform,z}from"@frontmcp/lazy-zod";import{findDroppedKeys}from"@frontmcp/utils";function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};var toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};var toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};var toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};var toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};var toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};var toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};var toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};var toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};var toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};var toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};var toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};var toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};var toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};var toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};var uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml};var toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};var toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};var toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};var toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};var toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};var toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};var toPassOutputSchemaWhole=function(received,outputSchema){const schema=outputSchema instanceof z.ZodType?outputSchema:z.object(outputSchema);if(hasTransform(schema)){return{pass:false,message:()=>"toPassOutputSchemaWhole cannot compare keys through a transform (.transform(), z.preprocess(), .pipe()): assert on the parsed answer instead"}}const parsed=schema.safeParse(received);if(!parsed.success){const[firstIssue]=parsed.error.issues;const location=firstIssue?.path.length?` at ${firstIssue.path.join(".")}`:"";return{pass:false,message:()=>`Expected the answer to pass its output schema whole, but it does not match its output schema${location}: ${firstIssue?.message}`}}const droppedKeys=findDroppedKeys(received,parsed.data);const pass=droppedKeys.length===0;return{pass,message:()=>pass?"Expected the answer not to pass its output schema whole":`Expected the answer to pass its output schema whole, but parsing drops keys it does not declare: ${droppedKeys.join(", ")}`}};var toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};var toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};var toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};var toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};var toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};var toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};var toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};var toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};var toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};var mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toPassOutputSchemaWhole,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers};export{mcpMatchers};
package/esm/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/testing",
3
- "version": "1.10.15",
3
+ "version": "1.10.16",
4
4
  "description": "End-to-end testing for FrontMCP servers: Jest fixtures with a connected MCP client, MCP matchers, JWT and OAuth mocks, and HTTP mocking",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://frontmcp.dev/reference/testing",
@@ -54,6 +54,12 @@
54
54
  "./jest-preset": {
55
55
  "default": "../jest-preset.js"
56
56
  },
57
+ "./jest-preset-unit": {
58
+ "default": "../jest-preset-unit.js"
59
+ },
60
+ "./jest-preset-unit/jest-preset": {
61
+ "default": "../jest-preset-unit.js"
62
+ },
57
63
  "./fixtures": {
58
64
  "require": {
59
65
  "types": "../fixtures/index.d.ts",
@@ -87,9 +93,9 @@
87
93
  "./esm": null
88
94
  },
89
95
  "peerDependencies": {
90
- "@frontmcp/lazy-zod": "1.10.15",
91
- "@frontmcp/sdk": "1.10.15",
92
- "@frontmcp/ui": "1.10.15",
96
+ "@frontmcp/lazy-zod": "1.10.16",
97
+ "@frontmcp/sdk": "1.10.16",
98
+ "@frontmcp/ui": "1.10.16",
93
99
  "@jest/globals": "^29.0.0 || ^30.0.0",
94
100
  "@playwright/test": "^1.40.0",
95
101
  "jest": "^29.0.0 || ^30.0.0"
@@ -112,8 +118,8 @@
112
118
  "node": ">=24.0.0"
113
119
  },
114
120
  "dependencies": {
115
- "@frontmcp/protocol": "1.10.15",
116
- "@frontmcp/utils": "1.10.15",
121
+ "@frontmcp/protocol": "1.10.16",
122
+ "@frontmcp/utils": "1.10.16",
117
123
  "@swc/core": "~1.15.41",
118
124
  "@swc/jest": "~0.2.38",
119
125
  "jose": "^6.0.11",
package/esm/setup.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  var __frontmcpModule = typeof process !== "undefined" && typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("module") : undefined;
2
2
  const require = __frontmcpModule ? __frontmcpModule.createRequire(import.meta.url || 'file:///') : undefined;
3
3
  // __frontmcpCreateRequire
4
- var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res,err)=>function __init(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function __require(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}var init_platform_types=__esm({"libs/testing/src/platform/platform-types.ts"(){"use strict"}});function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml,uiMatchers;var init_ui_matchers=__esm({"libs/testing/src/ui/ui-matchers.ts"(){"use strict";init_platform_types();toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml}}});var toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,mcpMatchers;var init_mcp_matchers=__esm({"libs/testing/src/matchers/mcp-matchers.ts"(){"use strict";init_ui_matchers();toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers}}});import{expect}from"@jest/globals";var require_setup=__commonJS({"libs/testing/src/setup.ts"(){init_mcp_matchers();expect.extend(mcpMatchers)}});export default require_setup();
4
+ var __getOwnPropNames=Object.getOwnPropertyNames;var __esm=(fn,res,err)=>function __init(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function __require(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};function getPlatformMimeType(platform){return"text/html;profile=mcp-app"}function getToolCallMetaPrefixes(platform){return["ui/"]}function getForbiddenMetaPrefixes(platform){return["openai/","frontmcp/"]}var init_platform_types=__esm({"libs/testing/src/platform/platform-types.ts"(){"use strict"}});function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function extractUiHtml(received){if(typeof received==="string"){return received}const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){const uiHtml=meta["ui/html"];if(typeof uiHtml==="string"){return uiHtml}}return void 0}function extractMeta(received){const wrapper=received;const meta=wrapper?.raw?._meta||wrapper?._meta;if(meta&&typeof meta==="object"){return meta}return void 0}var toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml,uiMatchers;var init_ui_matchers=__esm({"libs/testing/src/ui/ui-matchers.ts"(){"use strict";init_platform_types();toHaveRenderedHtml=function(received){const html=extractUiHtml(received);const hasHtml=html!==void 0&&html.length>0;const isFallback=hasHtml&&html.includes("mdx-fallback");const pass=hasHtml&&!isFallback;return{pass,message:()=>{if(isFallback){return"Expected rendered HTML but got mdx-fallback (raw escaped content). MDX rendering may have failed."}if(!hasHtml){return"Expected _meta to have ui/html property with rendered HTML"}return"Expected result not to have rendered HTML"}}};toContainHtmlElement=function(received,tag){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected to find <${tag}> element, but no HTML content found`}}const regex=new RegExp(`<${escapeRegex(tag)}[\\s>]`,"i");const pass=regex.test(html);return{pass,message:()=>pass?`Expected HTML not to contain <${tag}> element`:`Expected HTML to contain <${tag}> element`}};toContainBoundValue=function(received,value){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to contain bound value "${value}", but no HTML content found`}}const stringValue=String(value);const pass=html.includes(stringValue);return{pass,message:()=>pass?`Expected HTML not to contain bound value "${stringValue}"`:`Expected HTML to contain bound value "${stringValue}"`}};toBeXssSafe=function(received){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>"Expected HTML to be XSS unsafe (no HTML found)"}}const hasScript=/<script[\s>]/i.test(html);const hasOnHandler=/\son\w+\s*=/i.test(html);const hasJavascriptUri=/javascript:/i.test(html);const issues=[];if(hasScript)issues.push("<script> tag");if(hasOnHandler)issues.push("inline event handler (onclick, etc.)");if(hasJavascriptUri)issues.push("javascript: URI");const pass=!hasScript&&!hasOnHandler&&!hasJavascriptUri;return{pass,message:()=>pass?"Expected HTML not to be XSS safe":`Expected HTML to be XSS safe, but found: ${issues.join(", ")}`}};toHaveWidgetMetadata=function(received){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>"Expected _meta to have widget metadata, but no _meta found"}}const hasUiHtml=Boolean(meta["ui/html"]);const hasMimeType=Boolean(meta["ui/mimeType"]);const hasUiObject=Boolean(meta["ui"]&&typeof meta["ui"]==="object");const pass=hasUiHtml||hasMimeType||hasUiObject;return{pass,message:()=>pass?"Expected result not to have widget metadata":"Expected _meta to have widget metadata (ui/html, ui/mimeType, or ui object)"}};toHaveCssClass=function(received,className){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>`Expected HTML to have CSS class "${className}", but no HTML content found`}}const classRegex=new RegExp(`class(?:Name)?\\s*=\\s*["'][^"']*\\b${escapeRegex(className)}\\b[^"']*["']`,"i");const pass=classRegex.test(html);return{pass,message:()=>pass?`Expected HTML not to have CSS class "${className}"`:`Expected HTML to have CSS class "${className}"`}};toNotContainRawContent=function(received,content){const html=extractUiHtml(received);if(!html){return{pass:true,message:()=>`Expected HTML to contain raw content "${content}", but no HTML found`}}const pass=!html.includes(content);return{pass,message:()=>pass?`Expected HTML to contain raw content "${content}"`:`Expected HTML not to contain raw content "${content}" (may indicate rendering failure)`}};toHaveProperHtmlStructure=function(received){const html=extractUiHtml(received);if(!html){return{pass:false,message:()=>"Expected proper HTML structure, but no HTML content found"}}const hasEscapedTags=html.includes("&lt;")&&html.includes("&gt;");const hasHtmlTags=/<[a-z]/i.test(html);const pass=hasHtmlTags&&!hasEscapedTags;return{pass,message:()=>{if(hasEscapedTags){return"Expected proper HTML structure, but found escaped HTML entities - content may not have been rendered"}if(!hasHtmlTags){return"Expected proper HTML structure, but found no HTML tags"}return"Expected result not to have proper HTML structure"}}};toHavePlatformMeta=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform meta for "${platform}", but no _meta found`}}const expectedPrefixes=getToolCallMetaPrefixes(platform);const forbiddenPrefixes=getForbiddenMetaPrefixes(platform);const metaKeys=Object.keys(meta);const hasExpectedPrefix=metaKeys.some(key=>expectedPrefixes.some(prefix=>key.startsWith(prefix)));const forbiddenKeys=metaKeys.filter(key=>forbiddenPrefixes.some(prefix=>key.startsWith(prefix)));const pass=hasExpectedPrefix&&forbiddenKeys.length===0;return{pass,message:()=>{if(!hasExpectedPrefix){return`Expected _meta to have keys with prefixes [${expectedPrefixes.join(", ")}] for platform "${platform}", but found: [${metaKeys.join(", ")}]`}if(forbiddenKeys.length>0){return`Expected _meta NOT to have keys [${forbiddenKeys.join(", ")}] for platform "${platform}" (forbidden prefixes: [${forbiddenPrefixes.join(", ")}])`}return`Expected result not to have platform meta for "${platform}"`}}};toHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=key in meta;return{pass,message:()=>pass?`Expected _meta not to have key "${key}"`:`Expected _meta to have key "${key}"`}};toHaveMetaValue=function(received,key,value){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but no _meta found`}}const actualValue=meta[key];const pass=JSON.stringify(actualValue)===JSON.stringify(value);return{pass,message:()=>pass?`Expected _meta["${key}"] not to equal ${JSON.stringify(value)}`:`Expected _meta["${key}"] to equal ${JSON.stringify(value)}, but got ${JSON.stringify(actualValue)}`}};toNotHaveMetaKey=function(received,key){const meta=extractMeta(received);if(!meta){return{pass:true,message:()=>`Expected _meta to have key "${key}", but no _meta found`}}const pass=!(key in meta);return{pass,message:()=>pass?`Expected _meta to have key "${key}"`:`Expected _meta not to have key "${key}"`}};toHaveOnlyNamespacedMeta=function(received,namespace){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have keys with namespace "${namespace}", but no _meta found`}}const metaKeys=Object.keys(meta);const wrongKeys=metaKeys.filter(key=>!key.startsWith(namespace));const pass=wrongKeys.length===0&&metaKeys.length>0;return{pass,message:()=>{if(metaKeys.length===0){return`Expected _meta to have keys with namespace "${namespace}", but _meta is empty`}if(wrongKeys.length>0){return`Expected _meta to ONLY have keys with namespace "${namespace}", but found: [${wrongKeys.join(", ")}]`}return`Expected _meta not to have only keys with namespace "${namespace}"`}}};toHavePlatformMimeType=function(received,platform){const meta=extractMeta(received);const expectedMimeType=getPlatformMimeType(platform);if(!meta){return{pass:false,message:()=>`Expected _meta to have MIME type "${expectedMimeType}" for platform "${platform}", but no _meta found`}}const mimeTypeKey="ui/mimeType";const actualMimeType=meta[mimeTypeKey];const pass=actualMimeType===expectedMimeType;return{pass,message:()=>pass?`Expected _meta["${mimeTypeKey}"] not to be "${expectedMimeType}"`:`Expected _meta["${mimeTypeKey}"] to be "${expectedMimeType}" for platform "${platform}", but got "${actualMimeType}"`}};toHavePlatformHtml=function(received,platform){const meta=extractMeta(received);if(!meta){return{pass:false,message:()=>`Expected _meta to have platform HTML for "${platform}", but no _meta found`}}const htmlKey="ui/html";const html=meta[htmlKey];const pass=typeof html==="string"&&html.length>0;return{pass,message:()=>pass?`Expected _meta not to have platform HTML in "${htmlKey}"`:`Expected _meta["${htmlKey}"] to contain HTML for platform "${platform}", but ${html===void 0?"key not found":`got ${typeof html}`}`}};uiMatchers={toHaveRenderedHtml,toContainHtmlElement,toContainBoundValue,toBeXssSafe,toHaveWidgetMetadata,toHaveCssClass,toNotContainRawContent,toHaveProperHtmlStructure,toHavePlatformMeta,toHaveMetaKey,toHaveMetaValue,toNotHaveMetaKey,toHaveOnlyNamespacedMeta,toHavePlatformMimeType,toHavePlatformHtml}}});import{hasTransform,z}from"@frontmcp/lazy-zod";import{findDroppedKeys}from"@frontmcp/utils";var toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toPassOutputSchemaWhole,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,mcpMatchers;var init_mcp_matchers=__esm({"libs/testing/src/matchers/mcp-matchers.ts"(){"use strict";init_ui_matchers();toContainTool=function(received,toolName){const tools=received;if(!Array.isArray(tools)){return{pass:false,message:()=>`Expected an array of tools, but received ${typeof received}`}}const pass=tools.some(t=>t.name===toolName);const availableTools=tools.map(t=>t.name).join(", ");return{pass,message:()=>pass?`Expected tools not to contain "${toolName}"`:`Expected tools to contain "${toolName}", but got: [${availableTools}]`}};toBeSuccessful=function(received){const result=received;if(typeof result!=="object"||result===null||!("isSuccess"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isSuccess property`}}const pass=result.isSuccess;return{pass,message:()=>pass?"Expected result not to be successful":`Expected result to be successful, but got error: ${result.error?.message??"unknown error"}`}};toBeError=function(received,expectedCode){const result=received;if(typeof result!=="object"||result===null||!("isError"in result)){return{pass:false,message:()=>`Expected a result wrapper object with isError property`}}const receivedCode=typeof expectedCode==="string"?result.raw?._meta?.["code"]:result.error?.code;const codeMatches=expectedCode===void 0||receivedCode===expectedCode;const pass=result.isError&&codeMatches;return{pass,message:()=>{if(!result.isError){return"Expected result to be an error, but it was successful"}if(!codeMatches){return`Expected error code ${expectedCode}, but got ${String(receivedCode)}`}return"Expected result not to be an error"}}};toHaveTextContent=function(received,expectedText){const result=received;if(typeof result!=="object"||result===null||!("text"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper or ResourceContentWrapper object with text method`}}const text=result.text();const hasText="hasTextContent"in result?result.hasTextContent():text!==void 0;let pass=hasText;if(pass&&expectedText!==void 0){pass=text?.includes(expectedText)??false}return{pass,message:()=>{if(!hasText){return"Expected result to have text content"}if(expectedText!==void 0&&!text?.includes(expectedText)){return`Expected text to contain "${expectedText}", but got: "${text}"`}return"Expected result not to have text content"}}};toHaveImageContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasImageContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasImageContent method`}}const pass=result.hasImageContent();return{pass,message:()=>pass?"Expected result not to have image content":"Expected result to have image content"}};toHaveResourceContent=function(received){const result=received;if(typeof result!=="object"||result===null||!("hasResourceContent"in result)){return{pass:false,message:()=>`Expected a ToolResultWrapper object with hasResourceContent method`}}const pass=result.hasResourceContent();return{pass,message:()=>pass?"Expected result not to have resource content":"Expected result to have resource content"}};toPassOutputSchemaWhole=function(received,outputSchema){const schema=outputSchema instanceof z.ZodType?outputSchema:z.object(outputSchema);if(hasTransform(schema)){return{pass:false,message:()=>"toPassOutputSchemaWhole cannot compare keys through a transform (.transform(), z.preprocess(), .pipe()): assert on the parsed answer instead"}}const parsed=schema.safeParse(received);if(!parsed.success){const[firstIssue]=parsed.error.issues;const location=firstIssue?.path.length?` at ${firstIssue.path.join(".")}`:"";return{pass:false,message:()=>`Expected the answer to pass its output schema whole, but it does not match its output schema${location}: ${firstIssue?.message}`}}const droppedKeys=findDroppedKeys(received,parsed.data);const pass=droppedKeys.length===0;return{pass,message:()=>pass?"Expected the answer not to pass its output schema whole":`Expected the answer to pass its output schema whole, but parsing drops keys it does not declare: ${droppedKeys.join(", ")}`}};toContainResource=function(received,uri){const resources=received;if(!Array.isArray(resources)){return{pass:false,message:()=>`Expected an array of resources, but received ${typeof received}`}}const pass=resources.some(r=>r.uri===uri);const availableUris=resources.map(r=>r.uri).join(", ");return{pass,message:()=>pass?`Expected resources not to contain "${uri}"`:`Expected resources to contain "${uri}", but got: [${availableUris}]`}};toContainResourceTemplate=function(received,uriTemplate){const templates=received;if(!Array.isArray(templates)){return{pass:false,message:()=>`Expected an array of resource templates, but received ${typeof received}`}}const pass=templates.some(t=>t.uriTemplate===uriTemplate);const availableTemplates=templates.map(t=>t.uriTemplate).join(", ");return{pass,message:()=>pass?`Expected templates not to contain "${uriTemplate}"`:`Expected templates to contain "${uriTemplate}", but got: [${availableTemplates}]`}};toHaveMimeType=function(received,mimeType){const result=received;if(typeof result!=="object"||result===null||!("hasMimeType"in result)){return{pass:false,message:()=>`Expected a ResourceContentWrapper object with hasMimeType method`}}const pass=result.hasMimeType(mimeType);const actualMimeType=result.mimeType();return{pass,message:()=>pass?`Expected content not to have MIME type "${mimeType}"`:`Expected MIME type "${mimeType}", but got "${actualMimeType}"`}};toContainPrompt=function(received,name){const prompts=received;if(!Array.isArray(prompts)){return{pass:false,message:()=>`Expected an array of prompts, but received ${typeof received}`}}const pass=prompts.some(p=>p.name===name);const availablePrompts=prompts.map(p=>p.name).join(", ");return{pass,message:()=>pass?`Expected prompts not to contain "${name}"`:`Expected prompts to contain "${name}", but got: [${availablePrompts}]`}};toHaveMessages=function(received,count){const result=received;if(typeof result!=="object"||result===null||!("messages"in result)){return{pass:false,message:()=>`Expected a PromptResultWrapper object with messages property`}}const actualCount=result.messages?.length??0;const pass=actualCount===count;return{pass,message:()=>pass?`Expected prompt not to have ${count} messages`:`Expected prompt to have ${count} messages, but got ${actualCount}`}};toBeValidJsonRpc=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const hasJsonRpc=response["jsonrpc"]==="2.0";const hasId="id"in response;const hasResult="result"in response;const hasError="error"in response;const hasExactlyOneResultOrError=(hasResult||hasError)&&!(hasResult&&hasError);const pass=hasJsonRpc&&hasId&&hasExactlyOneResultOrError;return{pass,message:()=>{if(pass){return"Expected response not to be valid JSON-RPC"}const issues=[];if(!hasJsonRpc)issues.push('missing or invalid "jsonrpc": "2.0"');if(!hasId)issues.push('missing "id" field');if(!hasExactlyOneResultOrError){if(!hasResult&&!hasError)issues.push('missing "result" or "error"');else issues.push('cannot have both "result" and "error"')}return`Expected valid JSON-RPC 2.0 response: ${issues.join(", ")}`}}};toHaveResult=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="result"in response;return{pass,message:()=>pass?"Expected response not to have result":"Expected response to have result"}};toHaveError=function(received){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const pass="error"in response;return{pass,message:()=>pass?"Expected response not to have error":"Expected response to have error"}};toHaveErrorCode=function(received,code){const response=received;if(typeof response!=="object"||response===null){return{pass:false,message:()=>`Expected an object, but received ${typeof received}`}}const actualCode=response.error?.code;const pass=actualCode===code;return{pass,message:()=>pass?`Expected response not to have error code ${code}`:`Expected error code ${code}, but got ${actualCode??"no error"}`}};mcpMatchers={toContainTool,toBeSuccessful,toBeError,toHaveTextContent,toHaveImageContent,toHaveResourceContent,toPassOutputSchemaWhole,toContainResource,toContainResourceTemplate,toHaveMimeType,toContainPrompt,toHaveMessages,toBeValidJsonRpc,toHaveResult,toHaveError,toHaveErrorCode,...uiMatchers}}});import{expect}from"@jest/globals";var require_setup=__commonJS({"libs/testing/src/setup.ts"(){init_mcp_matchers();expect.extend(mcpMatchers)}});export default require_setup();