@powerduck/openapi-request 0.2.2

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.
@@ -0,0 +1 @@
1
+ "use strict";var e,t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,r)=>{for(var s in r)t(e,s,{get:r[s],enumerable:!0})})(o,{MCP_PROTOCOL_VERSION:()=>Z,McpAdapter:()=>$e,createHttpMcpTransport:()=>Ce,createMcpManualSession:()=>Be,createMcpSessionCore:()=>De,createMcpStdioConnection:()=>le,createMcpStdioSession:()=>je,createStdioMcpTransport:()=>Se,discoverAndWriteMcpCapabilities:()=>be,discoverMcpCapabilities:()=>re,generateAllMcpCalls:()=>he,generateMcpCall:()=>me,initializeSession:()=>ee,mcpManualSession:()=>Be,resolveMcpConfig:()=>L,runMcp:()=>fe,runMcpManualSession:()=>Be,writeMcpOperations:()=>ve}),module.exports=(e=o,((e,o,i,a)=>{if(o&&"object"==typeof o||"function"==typeof o)for(let c of s(o))n.call(e,c)||c===i||t(e,c,{get:()=>o[c],enumerable:!(a=r(o,c))||a.enumerable});return e})(t({},"__esModule",{value:!0}),e));var i=new Set(["__proto__","constructor","prototype"]);function a(e){return i.has(e)}function c(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return function(e){return u(e,new Set)}(e)}function u(e,t){if(null===e)return null;const r=typeof e;if("string"===r||"boolean"===r)return e;if("number"===r)return Number.isFinite(e)?e:null;if("bigint"===r)return e.toString();if("object"!==r)return;const s=e;if(t.has(s))return null;const n=s.toJSON;if("function"==typeof n){let e;try{e=n.call(s)}catch{return null}return e===s?null:u(e,t)}t.add(s);try{if(Array.isArray(s)){const e=new Array(s.length);for(let r=0;r<s.length;r+=1){const n=u(s[r],t);e[r]=void 0===n?null:n}return e}const e={};for(const r of Object.keys(s)){if(a(r))continue;let n;try{n=s[r]}catch{continue}const o=u(n,t);void 0!==o&&(e[r]=o)}return e}finally{t.delete(s)}}function l(e,t){const r=d(e);return r&&-1!==r.indexOf("{{")&&t?r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;const s=t[r];return null==s?e:d(s)}):r}function d(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function p(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function f(e){return e instanceof Error?e.message:String(e)}var m=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function h(e){return m.test(e)}var y=Symbol.for("@powerduck/openapi-request.ProtoKitError"),g=class e extends Error{code;details;[y]=!0;constructor(t,r,s,n){if(super(t),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=s,n&&"cause"in n)try{Object.defineProperty(this,"cause",{value:n.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,e.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isProtoKitError(e){return"object"==typeof e&&null!==e&&!0===e[y]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function v(e,t,r,s){return new g(t,e,r,s)}function b(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function w(e){if(g.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:b(e)}}var M="\0PK_OPEN\0",P="\0PK_CLOSE\0";function C(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return _(S(r),"options.serverUrl");const s=Array.isArray(e)?e.filter(p):[],n=s[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??s[0];let o=n&&"string"==typeof n.url&&n.url.trim()?n.url.trim():"";if(!o)throw v("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return o=function(e,t,r){const s=p(t)?t:{};let n=e;for(const[e,t]of Object.entries(s)){const s=r?.[e];let o;if(null!=s){if(o=s,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(s)))throw v("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:s,allowed:t.enum})}else if(void 0!==t?.default)o=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw v("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);o=t.enum[0]}n=n.split(`{${e}}`).join(String(o??""))}for(const[e,t]of Object.entries(r??{}))Object.prototype.hasOwnProperty.call(s,e)||null!=t&&(n=n.split(`{${e}}`).join(String(t)));return n}(o,n?.variables,t.serverVariables),_(S(o),"spec.servers")}function S(e){return e.replace(/\/+$/,"")||e}function _(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(M).split("}}").join(P).replace(/\{[^{}]*\}/g,"").split(M).join("{{").split(P).join("}}")}(e);if(!r)throw v("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw v("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}var O=new Set(["__proto__","constructor","prototype"]),A="2024-01-01T00:00:00.000Z",I=12,T=2,E=5,x=256;function D(e,t=0,r={}){const s=r.maxDepth??I;if(!e||"object"!=typeof e||Array.isArray(e))return null;if(t>s)return null;if("string"==typeof e.$ref)return null;if(void 0!==e.example)return e.example;const n=function(e){if(null==e)return;if(Array.isArray(e))return e.length?e[0]:void 0;if("object"==typeof e)for(const t of Object.values(e))if(void 0!==t){if(t&&"object"==typeof t){if("value"in t)return t.value;if("externalValue"in t)continue}return t}return}(e.examples);if(void 0!==n)return n;if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length){const t=e.enum.find(e=>null!==e);return void 0!==t?t:e.enum[0]}if(Array.isArray(e.allOf)&&e.allOf.length)return function(e,t,r){let s,n;for(const o of e.allOf){const e=D(o,t+1,r);null===e||"object"!=typeof e||Array.isArray(e)?null!=e&&(n=e):s={...s??{},...e}}if(e.properties||e.required){const n=B(e,t,r);n&&"object"==typeof n&&(s={...s??{},...n})}return s||(void 0!==n?n:{})}(e,t,r);for(const s of["oneOf","anyOf"]){const n=e[s];if(Array.isArray(n)&&n.length){return D(n.find(e=>e&&"object"==typeof e&&"null"!==e.type)??n[0],t+1,r)}}const o=function(e){const t=Array.isArray(e.type)?e.type.find(e=>"string"==typeof e&&"null"!==e)??(e.type.includes("null")?"null":void 0):"string"==typeof e.type?e.type:void 0;if(t)return t;if(e.properties||e.additionalProperties||e.required)return"object";if(e.items||e.prefixItems)return"array";if(void 0!==e.minimum||void 0!==e.maximum||void 0!==e.multipleOf)return"number";return"string"}(e);switch(o){case"object":return B(e,t,r);case"array":return function(e,t,r){const s=[];if(Array.isArray(e.prefixItems))for(const n of e.prefixItems)s.push(D(n,t+1,r));const n=N(e.minItems)??1,o=N(e.maxItems);let i=Math.max(n,s.length,1);i=Math.min(i,E),void 0!==o&&(i=Math.min(i,Math.max(o,0)));const a=e.items&&"object"==typeof e.items?e.items:void 0;if(!a&&Array.isArray(e.prefixItems))return s.slice(0,0===i?0:Math.max(i,s.length));for(;s.length<i;){const n=D(a??{},t+1,r);if(!0===e.uniqueItems&&s.length>0)break;s.push(n)}return void 0!==o?s.slice(0,Math.max(o,0)):s}(e,t,r);case"integer":return function(e){const{min:t,max:r}=j(e,!0);let s=0;void 0!==t&&s<t&&(s=Math.ceil(t));void 0!==r&&s>r&&(s=Math.floor(r));const n=R(e.multipleOf);if(void 0!==n&&n>0){const e=Math.ceil(s/n)*n;(void 0===r||e<=r)&&(s=e)}return Math.trunc(s)}(e);case"number":return function(e){const{min:t,max:r}=j(e,!1);let s=0;void 0!==t&&s<t&&(s=t);void 0!==r&&s>r&&(s=r);const n=R(e.multipleOf);if(void 0!==n&&n>0){const e=Math.ceil(s/n)*n;(void 0===r||e<=r)&&(s=e)}return s}(e);case"boolean":return!1;case"null":return null;default:return function(e){const t="string"==typeof e.format?e.format:void 0,r=t?function(e){switch(e){case"date-time":return A;case"date":return A.slice(0,10);case"time":return A.slice(11,19);case"duration":return"PT1S";case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":case"idn-email":return"user@example.com";case"hostname":case"idn-hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"iri":return"https://example.com";case"uri-reference":case"iri-reference":case"json-pointer":return"/example";case"uri-template":return"https://example.com/{id}";case"relative-json-pointer":return"0/example";case"regex":return"^example$";case"byte":return"ZXhhbXBsZQ==";case"binary":return"";case"password":return"password";default:return}}(t):void 0;return void 0!==r?$(r,e):"string"==typeof e.pattern&&e.pattern.length?"":$("string",e)}(e)}}function B(e,t,r){const s={},n=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],o=e.properties&&"object"==typeof e.properties?e.properties:{},i=!0===r.includeReadOnly,a=!1!==r.includeWriteOnly;for(const[e,c]of Object.entries(o))O.has(e)||!i&&c&&!0===c.readOnly||!a&&c&&!0===c.writeOnly||t>T&&n.length&&!n.includes(e)||(s[e]=D(c,t+1,r));for(const e of n)O.has(e)||e in s||(s[e]=D(o[e]??{},t+1,r));!Object.keys(s).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(s.key=D(e.additionalProperties,t+1,r));const c=N(e.minProperties);if(void 0!==c){const n=e.additionalProperties&&"object"==typeof e.additionalProperties?e.additionalProperties:{};let o=1;for(;Object.keys(s).length<Math.min(c,20);){const e=`additionalProp${o}`;o+=1,e in s||(s[e]=D(n,t+1,r))}}return s}function j(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let s=R(e.minimum),n=R(e.maximum);const o=e.exclusiveMinimum,i=e.exclusiveMaximum;if("number"==typeof o&&Number.isFinite(o)){const e=o+r;s=void 0===s?e:Math.max(s,e)}else!0===o&&void 0!==s&&(s+=r);if("number"==typeof i&&Number.isFinite(i)){const e=i-r;n=void 0===n?e:Math.min(n,e)}else!0===i&&void 0!==n&&(n-=r);return{min:s,max:n}}function $(e,t){const r=N(t.minLength),s=N(t.maxLength);let n=e;return void 0!==r&&n.length<r&&(n=n.padEnd(Math.min(r,x),"x")),void 0!==s&&n.length>s&&(n=n.slice(0,Math.max(s,0))),n}function R(e){if("number"==typeof e&&Number.isFinite(e))return e}function N(e){const t=R(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}var k=new Set(["tools/call","resources/read","prompts/get","tools/list","resources/list","resources/templates/list","prompts/list"]);function L(e,t,r){const s=r.mcp??{},n=e.operation?.["x-mcp"],o=n&&"object"==typeof n?n:{},i={...r.variables??{}},a=s.transport??o.transport??"streamable-http";if("streamable-http"!==a&&"stdio"!==a)throw v("BAD_MCP_TRANSPORT",`Unsupported MCP transport: ${JSON.stringify(a)}`);const c=a;let u,d,f,m,h,y,g,b;if("streamable-http"===c){if(u=s.endpoint||("string"==typeof o.endpoint?o.endpoint:C(e.servers,r)),u=l(u,i),/\{\{[^}]+\}\}/.test(u))throw v("BAD_MCP_ENDPOINT",`Unresolved variable in MCP endpoint: ${u}`);try{const e=new URL(u);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw v("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${u}`)}}else{const e=s.command??o.command;if("string"!=typeof e||!e.trim())throw v("BAD_MCP_STDIO_COMMAND","MCP stdio transport requires command.");if(d=l(e.trim(),i),/\{\{[^}]+\}\}/.test(d))throw v("BAD_MCP_STDIO_COMMAND",`Unresolved variable in MCP command: ${d}`);const t=s.args??o.args;if(null!=t){if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw v("BAD_MCP_STDIO_CONFIG","MCP stdio args must be an array of strings.");f=t.map(e=>l(e,i))}const r=s.cwd??o.cwd;if(null!=r){if("string"!=typeof r||!r)throw v("BAD_MCP_STDIO_CONFIG","MCP stdio cwd must be a non-empty string.");m=l(r,i)}const n=s.env??o.env;if(null!=n){if(!p(n))throw v("BAD_MCP_STDIO_CONFIG","MCP stdio env must be an object.");h={};for(const[e,t]of Object.entries(n))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(h[e]=null==t?void 0:l(String(t),i))}for(const[e,t]of[["timeoutMs",s.timeoutMs??o.timeoutMs],["maxBufferBytes",s.maxBufferBytes??o.maxBufferBytes],["maxStderrBytes",s.maxStderrBytes??o.maxStderrBytes]])if(null!=t){if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw v("BAD_MCP_STDIO_CONFIG",`${e} must be a positive finite number.`);"timeoutMs"===e?y=t:"maxBufferBytes"===e?g=t:b=t}}const w=s.method??o.method;if("string"!=typeof w||!k.has(w))throw v("BAD_MCP_METHOD",`options.mcp.method (or x-mcp.method) must be one of: ${Array.from(k).join(", ")}. Received: ${JSON.stringify(w)}`);const M=s.name??o.name,P=p(o.arguments)?o.arguments:void 0,S=p(o.argumentsSchema)?o.argumentsSchema:void 0,_=S?D(S):void 0,O=p(r.values?.body)?r.values.body:void 0,A={...p(_)?_:{},...P??{},...O??{},...s.arguments??{}};let I;if("tools/call"===w){if(!M)throw v("BAD_MCP_TARGET","tools/call requires options.mcp.name (or x-mcp.name).");I={name:M,arguments:A}}else if("prompts/get"===w){if(!M)throw v("BAD_MCP_TARGET","prompts/get requires options.mcp.name (or x-mcp.name).");I={name:M,arguments:A}}else if("resources/read"===w){const e=A.uri??o.uri??s.arguments?.uri;if("string"!=typeof e||!e)throw v("BAD_MCP_TARGET","resources/read requires a `uri` (via options.mcp.arguments.uri or x-mcp.uri).");I={uri:e}}else I=A;const T={"Content-Type":"application/json"},E=e=>{if(p(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(T[t]=l(String(r),i))};E(r.values?.header),E(o.headers),E(s.headers);const x=r.auth;if(x&&"none"!==x.type&&!function(e,t){const r=t.toLowerCase();return Object.keys(e).some(e=>e.toLowerCase()===r)}(T,"Authorization"))if("bearer"===x.type)T.Authorization=`Bearer ${x.token??""}`;else if("basic"===x.type){const e=`${x.username??""}:${x.password??""}`;T.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===x.type&&"header"===(x.in??"header")&&(T[x.key??"X-API-Key"]=x.value??"");return{transport:c,..."streamable-http"===c&&u?{endpoint:u}:{},..."stdio"===c&&d?{command:d,...f?{args:f}:{},...m?{cwd:m}:{},...h?{env:h}:{},...null!=y?{timeoutMs:y}:{},...null!=g?{maxBufferBytes:g}:{},...null!=b?{maxStderrBytes:b}:{}}:{},method:w,params:I,headers:T,sessionId:s.sessionId??V(o.sessionId),protocolVersion:s.protocolVersion??V(o.protocolVersion),clientInfo:s.clientInfo??{name:"protokit",version:"0.1.0"}}}function V(e){return"string"==typeof e&&e.length?e:void 0}var q=new Set(["[DONE]","DONE","[done]","done"]),z=/\r\n\r\n|\n\n|\r\r/,U=/^\d+$/;function F(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var J=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=F(e.maxBufferChars,4194304),this.maxEventChars=F(e.maxEventChars,1048576),this.inheritEventId=!1!==e.inheritEventId}get truncated(){return this.overflowed}get count(){return this.sequence}push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{let t;if(e instanceof Uint8Array)t=e;else try{t=new Uint8Array(e)}catch{return[]}try{this.buffer+=this.decoder.decode(t,{stream:!0})}catch{return[]}}!this.bomChecked&&this.buffer.length&&(this.bomChecked=!0,65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1)));const t=this.drain();return this.buffer.length>this.maxBufferChars&&(this.overflowed=!0,this.droppedEvents+=1,this.buffer=this.buffer.slice(-8)),t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.drain(),t=this.buffer;if(this.buffer="",t.trim()){const r=this.parseBlock(t);r&&e.push(r)}return e}reset(){this.buffer="",this.lastEventId=void 0,this.bomChecked=!1,this.overflowed=!1,this.sequence=0,this.droppedEvents=0;try{this.decoder.decode()}catch{}}drain(){const e=[];for(;;){const t=z.exec(this.buffer);if(!t)break;const r=this.buffer.slice(0,t.index);this.buffer=this.buffer.slice(t.index+t[0].length);const s=this.parseBlock(r);s&&e.push(s)}return e}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],s={data:"",receivedAt:Date.now(),direction:"in"};let n=!1,o=0,i=!1;for(const e of t){if(""===e)continue;if(58===e.charCodeAt(0))continue;const t=e.indexOf(":"),a=-1===t?e:e.slice(0,t);let c=-1===t?"":e.slice(t+1);switch(32===c.charCodeAt(0)&&(c=c.slice(1)),a){case"data":{if(n=!0,i)break;const e=this.maxEventChars-o;c.length>e?(r.push(c.slice(0,Math.max(0,e))),i=!0,this.overflowed=!0,this.droppedEvents+=1):(r.push(c),o+=c.length+1);break}case"event":s.event=c,n=!0;break;case"id":c.includes("\0")||(s.id=c,this.lastEventId=c),n=!0;break;case"retry":if(U.test(c)&&c.length<=15){const e=Number(c);Number.isSafeInteger(e)&&(s.retry=e)}n=!0}}if(!n)return null;if(s.data=r.join("\n"),void 0===s.id&&this.inheritEventId&&void 0!==this.lastEventId&&(s.id=this.lastEventId),!i){const e=s.data.trim();if(e&&!q.has(e)&&function(e){const t=e.charCodeAt(0);return 123===t||91===t||34===t}(e))try{s.parsed=JSON.parse(s.data)}catch{}}return this.sequence+=1,s}};var G=0;function K(){return G+=1}async function H(e,t,r){const s=new AbortController;let n,o,i;if(r.signal){const e=()=>s.abort(r.signal?.reason);r.signal.aborted?e():(r.signal.addEventListener("abort",e,{once:!0}),n=()=>r.signal?.removeEventListener("abort",e))}"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{s.abort(new Error(`MCP request timed out after ${r.timeoutMs}ms`))},r.timeoutMs),"function"==typeof o?.unref&&o.unref());try{i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...r.protocolVersion?{"MCP-Protocol-Version":r.protocolVersion}:{},...r.headers??{}},body:JSON.stringify(t),signal:s.signal})}catch(e){throw v("MCP_TRANSPORT_FAILED",`Could not reach MCP endpoint: ${e?.message??e}`,void 0,{cause:e})}finally{o&&clearTimeout(o),n?.()}const a=Date.now()-r.startedAt,c=function(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}(i.headers),u=i.headers.get("content-type")??void 0,l=i.headers.get("mcp-session-id")??void 0;if(202===i.status||204===i.status)return{message:void 0,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,sizeBytes:0,firstByteMs:a};if(u&&/text\/event-stream/i.test(u)&&i.body){const e=new J,s=i.body.getReader();let n=0;const o="number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0?r.maxResponseBytes:0;let d;for(;;){const{done:r,value:i}=await s.read();if(r)break;if(n+=i?.byteLength??0,o>0&&n>o){try{await s.cancel()}catch{}throw v("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${o} bytes while reading event stream.`)}for(const r of e.push(i))if(r.parsed&&"object"==typeof r.parsed){const e=r.parsed;void 0!==t.id&&e.id!==t.id||(d=e)}if(void 0!==d){try{await s.cancel()}catch{}break}}if(void 0===d)for(const t of e.flush())t.parsed&&"object"==typeof t.parsed&&(d=t.parsed);return{message:d,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,sizeBytes:n,firstByteMs:a}}let d,p;try{if(d=await i.text(),"number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0&&d.length>r.maxResponseBytes)throw v("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${r.maxResponseBytes} bytes.`);d.trim()&&(p=JSON.parse(d))}catch(e){return{message:void 0,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}return{message:p,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}function W(e){return!!e&&"object"==typeof e&&p(e.error)}var Z="2025-06-18",X=new Set([-32601,-32600]),Q={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"},Y=1e3;async function ee(e,t={}){const r=Date.now(),s=await H(e,{jsonrpc:"2.0",id:K(),method:"initialize",params:{protocolVersion:Z,capabilities:t.capabilities??{},clientInfo:t.clientInfo??{name:"protokit",version:"0.1.0"}}},{headers:t.headers,signal:t.signal,startedAt:r});if(W(s.message))throw v("MCP_INITIALIZE_FAILED",`initialize failed: ${s.message.error.message}`,s.message.error);if(!s.message?.result)throw v("MCP_INITIALIZE_FAILED",`initialize returned no result (HTTP ${s.status}). The endpoint may not speak MCP.`);const n=s.sessionId,o=s.message.result.protocolVersion;return await H(e,{jsonrpc:"2.0",method:"notifications/initialized"},{headers:{...t.headers??{},...n?{"Mcp-Session-Id":n}:{}},signal:t.signal,startedAt:r,protocolVersion:o}),{sessionId:n,serverInfo:s.message.result.serverInfo,protocolVersion:o}}async function te(e,t,r,s){const n=Date.now(),o={...s.headers??{},...r.sessionId?{"Mcp-Session-Id":r.sessionId}:{}},i=Q[t],a=[],c=new Set;let u,l=0;for(;;){const d=await H(e,{jsonrpc:"2.0",id:K(),method:t,params:u?{cursor:u}:{}},{headers:o,signal:s.signal,startedAt:n,protocolVersion:r.protocolVersion});if(W(d.message)){const{code:e,message:r}=d.message.error;if(X.has(e))return;throw v("MCP_LIST_FAILED",`${t} failed (${e}): ${r}`,d.message.error)}const p=d.message?.result;if(!p){if(d.status>=400)throw v("MCP_LIST_FAILED",`${t} returned HTTP ${d.status} ${d.statusText} with no JSON-RPC result.`);return a}l+=1,Array.isArray(p[i])&&a.push(...p[i]);const f="string"==typeof p.nextCursor?p.nextCursor:void 0;if(!f)break;if(c.has(f)||l>=Y)break;c.add(f),u=f}return a}async function re(e,t={}){const r=await ee(e,t),s=[],n=[],o=await te(e,"tools/list",r,t);if(o)for(const e of o)e?.name&&n.push({kind:"tool",name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema??{},...e.execution&&"object"==typeof e.execution?{execution:e.execution}:{}});else s.push("Server does not implement tools/list.");const i=await te(e,"resources/list",r,t),a=await te(e,"resources/templates/list",r,t);for(const e of[...i??[],...a??[]])e?.name&&n.push({kind:"resource",name:e.name,title:e.title,uri:e.uri,uriTemplate:e.uriTemplate,description:e.description,mimeType:e.mimeType});i||a||s.push("Server does not implement resources/list or resources/templates/list.");const c=await te(e,"prompts/list",r,t);if(c)for(const e of c)e?.name&&n.push({kind:"prompt",name:e.name,title:e.title,description:e.description,arguments:e.arguments});else s.push("Server does not implement prompts/list.");return{serverInfo:r.serverInfo,protocolVersion:r.protocolVersion,sessionId:r.sessionId,capabilities:n,warnings:s}}var se=require("child_process"),ne=require("events"),oe=3e4,ie=4194304,ae=65536,ce=1500,ue=2e3;function le(e){if(!e||"string"!=typeof e.command||!e.command.trim())throw v("BAD_MCP_STDIO_COMMAND","MCP stdio requires a non-empty command.");const t=de(e.timeoutMs,oe,"timeoutMs"),r=de(e.maxBufferBytes,ie,"maxBufferBytes"),s=function(e){const t={...process.env};if(!e)return t;for(const[r,s]of Object.entries(e))void 0===s?delete t[r]:t[r]=s;return t}(e.env);let n;try{n=(0,se.spawn)(e.command,e.args??[],{cwd:e.cwd,env:s,stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(e){throw v("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${f(e)}`,void 0,{cause:e})}let o=!1,i=0,a="",c="";const u=new Map,l=(e,t)=>{u.get(e)===t&&u.delete(e),t.timer&&clearTimeout(t.timer),t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort)},d=e=>{for(const[t,r]of u)l(t,r),r.reject(e)},p=e=>{if(o)return;const t=v("MCP_STDIO_PROTOCOL_ERROR",e);d(t),h()};function m(e){if(o||n.stdin.destroyed||!n.stdin.writable)return Promise.reject(v("MCP_STDIO_CLOSED","MCP stdio process is closed."));let t;try{t=JSON.stringify(e)+"\n"}catch(e){return Promise.reject(v("MCP_STDIO_SERIALIZE_FAILED",`Could not serialize MCP JSON-RPC message: ${f(e)}`,void 0,{cause:e}))}return new Promise((e,r)=>{n.stdin.write(t,"utf8",t=>{t?r(t):e()})})}async function h(){if(o)return;if(o=!0,d(v("MCP_STDIO_CLOSED","MCP stdio process was closed.")),n.stdin.destroyed||n.stdin.end(),null!==n.exitCode||n.killed)return;try{n.kill("SIGTERM")}catch{return}const e=setTimeout(()=>{if(null===n.exitCode&&!n.killed)try{n.kill("SIGKILL")}catch{}},ce);e.unref?.();try{await Promise.race([(0,ne.once)(n,"exit").then(()=>{}),(t=ue,t>0?new Promise((e,s)=>{const n=()=>{clearTimeout(o),s(new Error("Aborted while waiting."))},o=setTimeout(()=>{r?.removeEventListener("abort",n),e()},t);if(o?.unref?.(),r?.aborted)return n();r?.addEventListener("abort",n,{once:!0})}):Promise.resolve())])}finally{clearTimeout(e)}var t,r}return n.stdout.setEncoding("utf8"),n.stdout.on("data",e=>{if(!o)if(a+=e,Buffer.byteLength(a,"utf8")>r)p(`MCP stdio stdout buffer exceeded ${r} bytes without a complete JSON-RPC line.`);else for(;;){const e=a.indexOf("\n");if(e<0)break;const t=a.slice(0,e).replace(/\r$/,"");if(a=a.slice(e+1),!t.trim())continue;if(Buffer.byteLength(t,"utf8")>r)return void p(`MCP stdio JSON-RPC message exceeded ${r} bytes.`);let s;try{s=JSON.parse(t)}catch{return void p(`MCP stdio emitted invalid JSON-RPC: ${t.slice(0,512)}`)}if(!pe(s))return void p("MCP stdio emitted an invalid JSON-RPC envelope.");if(void 0===s.id)continue;const n=u.get(s.id);n&&(l(s.id,n),void 0!==s.error?n.reject(v("MCP_RPC_ERROR",`${s.error.code}: ${s.error.message}`,s.error)):Object.prototype.hasOwnProperty.call(s,"result")?n.resolve(s.result):n.reject(v("MCP_STDIO_PROTOCOL_ERROR","MCP stdio response contained neither result nor error.")))}}),n.stderr.setEncoding("utf8"),n.stderr.on("data",e=>{c=(c+e).slice(-ae)}),n.once("error",e=>{o||(o=!0,d(v("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${f(e)}`,void 0,{cause:e})))}),n.once("exit",(e,t)=>{if(o)return;o=!0;const r=c.trim()?` stderr: ${c.trim().slice(-2048)}`:"";d(v("MCP_STDIO_EXITED",`MCP stdio process exited (code=${e}, signal=${t??"none"}).${r}`))}),{get pid(){return n.pid},request:function(e,r,s){if(s?.aborted)return Promise.reject(v("MCP_ABORTED","MCP request was aborted before send."));if(o)return Promise.reject(v("MCP_STDIO_CLOSED","MCP stdio process is closed."));const n=++i;return new Promise((o,i)=>{const a={resolve:o,reject:i};a.timer=setTimeout(()=>{l(n,a),i(v("MCP_TIMEOUT",`${e} timed out after ${t}ms`))},t),a.timer.unref?.(),s&&(a.signal=s,a.onAbort=()=>{l(n,a),i(v("MCP_ABORTED",`${e} was aborted.`))},s.addEventListener("abort",a.onAbort,{once:!0})),u.set(n,a),m({jsonrpc:"2.0",id:n,method:e,...void 0===r?{}:{params:r}}).catch(e=>{l(n,a),i(e)})})},notify:async function(e,t,r){if(r?.aborted)throw v("MCP_ABORTED","MCP notification was aborted before send.");await m({jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}})},close:h}}function de(e,t,r){const s=e??t;if(!Number.isFinite(s)||s<=0)throw v("BAD_MCP_STDIO_CONFIG",`MCP stdio ${r} must be a positive finite number.`);return s}function pe(e){return!!e&&"object"==typeof e&&"2.0"===e.jsonrpc}async function fe(e,t,r){return"stdio"===e.transport?async function(e,t,r){const s=Date.now(),n=[],o=r?.signal??t.signal,i={jsonrpc:"2.0",id:K(),method:e.method,params:e.params},a=le({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes});try{const t=await a.request("initialize",{protocolVersion:e.protocolVersion??Z,capabilities:{},clientInfo:e.clientInfo},o);if(!t||"object"!=typeof t)throw new Error("MCP initialize returned an invalid result.");n.push({url:`stdio://${e.command}`,method:"initialize",status:200,reason:"mcp-stdio-handshake"}),await a.notify("notifications/initialized",void 0,o);const r=await a.request(e.method,e.params,o),c=Date.now();return{protocol:"mcp",request:{method:"STDIO",url:`stdio://${e.command}`,headers:{},body:i},response:{status:200,statusText:"OK",headers:{},body:r,text:JSON.stringify(r),timings:{startedAt:s,endedAt:c,durationMs:c-s},sizeBytes:Buffer.byteLength(JSON.stringify(r))},replays:n}}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"STDIO",url:`stdio://${e.command}`,headers:{},body:i},response:{status:0,statusText:"MCP stdio failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:w(t),replays:n}}finally{await a.close().catch(()=>{})}}(e,t,r):async function(e,t,r){const s=Date.now(),n=r?.signal??t.signal,o=[];let i=e.sessionId,a=e.protocolVersion;if(!i)try{const t=await ee(e.endpoint,{headers:e.headers,signal:n,clientInfo:e.clientInfo});i=t.sessionId,a=t.protocolVersion,o.push({url:e.endpoint,method:"initialize",status:200,reason:"mcp-handshake"})}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:e.headers,body:{method:"initialize"}},response:{status:0,statusText:"Handshake failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:w(t),replays:o}}const c={...e.headers,...i?{"Mcp-Session-Id":i}:{}},u={jsonrpc:"2.0",id:K(),method:e.method,params:e.params};try{const t=await H(e.endpoint,u,{headers:c,signal:n,startedAt:s,protocolVersion:a}),r=Date.now(),i=W(t.message)?t.message.error:void 0;return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:u},response:{status:t.status,statusText:t.statusText,headers:t.headers,contentType:t.contentType,body:i?t.message:t.message?.result,text:t.rawText,timings:{startedAt:s,endedAt:r,durationMs:r-s,firstByteMs:t.firstByteMs},sizeBytes:t.sizeBytes},...i?{error:{message:i.message,code:String(i.code)}}:{},replays:o}}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:u},response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:w(t),replays:o}}}(e,t,r)}function me(e){const t=[];if("tool"===e.kind){const r=e.inputSchema??{type:"object",properties:{}},s=D(r);return{capability:e,method:"tools/call",params:{name:e.name,arguments:s&&"object"==typeof s?s:{}},argumentsSchema:r,notes:t}}if("prompt"===e.kind){const r={},s=[];for(const t of e.arguments??[])r[t.name]={type:"string",description:t.description},t.required&&s.push(t.name);const n={type:"object",properties:r,required:s},o=D(n);return{capability:e,method:"prompts/get",params:{name:e.name,arguments:o&&"object"==typeof o?o:{}},argumentsSchema:n,notes:t}}return!e.uri&&e.uriTemplate&&t.push(`Resource "${e.name}" is a template (${e.uriTemplate}); fill in its placeholders before calling.`),{capability:e,method:"resources/read",params:{uri:e.uri??e.uriTemplate??""},argumentsSchema:{type:"object",properties:{uri:{type:"string"}},required:["uri"]},notes:t}}function he(e){return e.map(me)}function ye(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ge(e){return`/mcp/${"tool"===e.kind?"tools":"prompt"===e.kind?"prompts":"resources"}/${ye(e.name)}`}function ve(e,t,r,s={}){if(!e||"object"!=typeof e||Array.isArray(e))throw v("BAD_SPEC","spec must be an object");const n=!1!==s.overwrite,o=c(e);p(o.paths)||(o.paths={});for(const e of r){const{capability:r}=e,s=ge(r);!n&&p(o.paths[s])||(o.paths[s]={post:{operationId:`mcp_${r.kind}_${ye(r.name)}`,summary:`MCP ${r.kind}: ${r.name}`,description:r.description,"x-protocol":"mcp","x-mcp":{endpoint:t,method:e.method,name:"resource"===r.kind?void 0:r.name,uri:"resource"===r.kind?r.uri??r.uriTemplate:void 0,argumentsSchema:e.argumentsSchema,arguments:e.params.arguments},requestBody:{content:{"application/json":{schema:e.argumentsSchema}}},responses:{200:{description:"MCP JSON-RPC result."}},...e.notes.length?{"x-mcp-notes":e.notes}:{}}})}return o}async function be(e,t,r={}){const s=await re(t,r);return{spec:ve(e,t,he(s.capabilities),r),capabilities:s.capabilities,warnings:s.warnings}}function we(e,t=new WeakMap){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(void 0===e)return null;if("bigint"==typeof e)return e.toString();if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return String(e);if(e instanceof Date)return e.toISOString();if(e instanceof URL)return e.toString();if(e instanceof Error){const r={name:e.name,message:e.message,stack:e.stack},s=e.cause;return void 0!==s&&(r.cause=we(s,t)),r}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return{type:"Buffer",data:Array.from(e.values())};if(e instanceof Uint8Array)return{type:e.constructor.name,data:Array.from(e.values())};if(Array.isArray(e))return e.map(e=>we(e,t));if("object"==typeof e){const r=e;if(t.has(r))return t.get(r);const s={};t.set(r,s);for(const[e,n]of Object.entries(r))s[e]=we(n,t);return s}return String(e)}var Me=class{constructor(e,t,r,s=1e3){this.protocol=e,this.transport=t,this.sessionId=r,this.maxEvents=s}protocol;transport;sessionId;maxEvents;state="idle";events=[];listeners=new Set;setState(e){this.state=e}emit(e){const t={protocol:this.protocol,transport:this.transport,sessionId:this.sessionId,at:e.at??Date.now(),direction:e.direction,kind:e.kind,state:e.state,data:we(e.data),error:we(e.error),meta:we(e.meta)};this.events.push(t),this.maxEvents>0&&this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);for(const e of this.listeners)try{e(t)}catch{}}onEvent(e){return this.listeners.add(e),{unsubscribe:()=>{this.listeners.delete(e)}}}},Pe=class extends Me{async open(){}async close(){}async waitForClose(){}async send(){}};function Ce(e){if(!e||!e.endpoint)throw v("BAD_MCP_ENDPOINT","MCP http transport requires an endpoint.");const t=e.endpoint,r={...e.headers??{}};return{transport:"streamable-http",async open(e){const s={headers:r,signal:e.signal,clientInfo:e.clientInfo,capabilities:e.capabilities},n=await ee(t,s);return{sessionId:n.sessionId,serverInfo:n.serverInfo,protocolVersion:n.protocolVersion??e.protocolVersion??Z}},call:(e,s)=>H(t,e,{headers:{...s.headers??r},signal:s.signal,startedAt:s.startedAt,protocolVersion:s.protocolVersion}),notify:(e,s)=>H(t,e,{headers:{...s.headers??r},signal:s.signal,startedAt:s.startedAt,protocolVersion:s.protocolVersion}),async terminate(e){const s=await fetch(t,{method:"DELETE",headers:{...r,...e.sessionId?{"Mcp-Session-Id":e.sessionId}:{},...e.protocolVersion?{"MCP-Protocol-Version":e.protocolVersion}:{}},signal:e.signal}).then(e=>e.status,()=>{});return void 0===s?{outcome:"failed",reason:"terminate request failed"}:s>=200&&s<300?{status:s,outcome:"released"}:405===s?{status:s,outcome:"unsupported"}:404===s?{status:s,outcome:"already-gone"}:{status:s,outcome:"failed"}},async dispose(){}}}function Se(e){const t=le(e);let r=!1;return{transport:"stdio",async open(e){const r=await t.request("initialize",{protocolVersion:e.protocolVersion??Z,capabilities:e.capabilities??{},clientInfo:e.clientInfo??{name:"protokit",version:"0.1.0"}},e.signal);if(!r||"object"!=typeof r)throw v("MCP_INITIALIZE_FAILED","MCP stdio initialize returned an invalid result.");return await t.notify("notifications/initialized",void 0,e.signal),{sessionId:void 0,serverInfo:r.serverInfo,protocolVersion:r.protocolVersion??e.protocolVersion??Z}},async call(e,r){const s=await t.request(e.method,e.params,r.signal),n=JSON.stringify(s);return{message:{jsonrpc:"2.0",id:e.id,result:s},status:200,statusText:"OK",headers:{},sizeBytes:Buffer.byteLength(n??"null","utf8"),firstByteMs:0}},notify:async(e,r)=>(await t.notify(e.method,e.params,r.signal),{message:void 0,status:200,statusText:"OK",headers:{},sizeBytes:0,firstByteMs:0}),terminate:async()=>({outcome:"unsupported"}),async dispose(){r||(r=!0,await t.close().catch(()=>{}))}}}var _e=3e4,Oe=1e3,Ae=1e3,Ie={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};function Te(e,t=0,r=new WeakSet){if(t>8)return"[depth-limit]";if(!p(e)&&!Array.isArray(e))return e;if("object"==typeof e&&null!==e){if(r.has(e))return"[circular]";r.add(e)}if(Array.isArray(e))return e.map(e=>Te(e,t+1,r));const s={};for(const[n,o]of Object.entries(e))s[n]=h(n)&&null!=o?"[redacted]":Te(o,t+1,r);return s}function Ee(e,...t){const r=t.filter(e=>!!e),s="number"==typeof e&&e>0;if(!r.length&&!s)return{signal:void 0,dispose:()=>{},timedOut:()=>!1};const n=new AbortController;let o=!1;const i=[];for(const e of r){if(e.aborted){n.abort(e.reason);break}const t=()=>n.abort(e.reason);e.addEventListener("abort",t,{once:!0}),i.push(()=>e.removeEventListener("abort",t))}if(s&&!n.signal.aborted){const t=setTimeout(()=>{o=!0,n.abort(new Error(`MCP request timed out after ${e}ms`))},e);t?.unref?.(),i.push(()=>clearTimeout(t))}return{signal:n.signal,dispose:()=>{for(const e of i)e()},timedOut:()=>o}}function xe(e){try{const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("not http(s)");return e}catch{throw v("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${e}`)}}function De(e,t){const r=t.timeoutMs??_e,s=(t.maxEvents,!1!==t.redactSecrets),n=!0===t.serialize,o=function(e,t,r,s=1e3){return new Pe(e,t,r,s)}("mcp",t.transport??"http",`mcp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,t.maxEvents??Oe);let i="idle";const a=()=>i,c=e=>{i=e,o.setState(e)};let u,l,d,f,m,h;const y=new Promise(e=>{h=e}),g=new Set;function b(e){const t=s?Te(e.parsed):e.parsed;o.emit({direction:e.direction,kind:e.event,at:e.at,state:a(),data:e.data,meta:void 0!==t?{parsed:t}:void 0})}function M(e){const t=a();if("open"!==t){if("idle"===t||"connecting"===t)throw v("MCP_NOT_OPEN",`Call open() before ${e}; session is "${t}".`);throw v("MCP_SESSION_CLOSED",`Cannot ${e} on a ${t} session.`)}}async function P(e){const t=e.then(()=>{},()=>{});g.add(t);try{return await e}finally{g.delete(t)}}async function C(s,n,o){const i=n?.timeoutMs??r,a=Ee(i,t.signal,n?.signal);try{n?.delayMs&&await(d=n.delayMs,p=a.signal,d>0?new Promise((e,t)=>{const r=()=>{clearTimeout(s),t(v("MCP_ABORTED","Aborted while waiting to send."))},s=setTimeout(()=>{p?.removeEventListener("abort",r),e()},d);if(p?.aborted)return r();p?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),b({direction:"out",at:Date.now(),event:o,parsed:s});const r={signal:a.signal,timeoutMs:i,startedAt:Date.now(),protocolVersion:l,sessionId:u,headers:{...t.headers??{},...u?{"Mcp-Session-Id":u}:{}}},f="notification"===o?await e.notify(s,r):await e.call(s,r);if(f.sessionId&&f.sessionId!==u&&(u=f.sessionId,b({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{sessionIdChanged:u}})),b({direction:"in",at:Date.now(),event:o,parsed:f.message??{status:f.status,statusText:f.statusText,empty:!0}}),404===f.status&&u)throw c("closed"),h(),v("MCP_SESSION_EXPIRED",`Server no longer recognises session ${u} (HTTP 404).`);return f}catch(e){const t=w(e);if(b({direction:"meta",at:Date.now(),event:"error",parsed:t}),a.timedOut())throw v("MCP_TIMEOUT",`${String(s.method)} timed out after ${i}ms`,t);throw e}finally{a.dispose()}var d,p}async function S(e,t,r){if("string"!=typeof e||!e)throw v("BAD_MCP_METHOD","request() requires a non-empty method name.");M(`request("${e}")`);const s={jsonrpc:"2.0",id:K(),method:e,...void 0===t?{}:{params:t}},n=await P(C(s,r,"jsonrpc"));if(r?.raw)return n;if(W(n.message))throw v("MCP_RPC_ERROR",`${e} failed (${n.message.error.code}): ${n.message.error.message}`,n.message.error);if(void 0===n.message)throw v("MCP_EMPTY_RESPONSE",`${e} returned no JSON-RPC message (HTTP ${n.status} ${n.statusText}).`);return n.message.result}async function _(e,t){const r=Ie[e],s=[],n=new Set;let o,i=0;for(;;){const a=await S(e,o?{cursor:o}:{},t);i+=1,Array.isArray(a?.[r])&&s.push(...a[r]);const c="string"==typeof a?.nextCursor?a.nextCursor:void 0;if(!c)break;if(n.has(c)||i>=Ae){b({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{warning:`${e} pagination stopped (repeated or excessive cursors)`}});break}n.add(c),o=c}return{items:s,pages:i}}async function O(){if("closed"!==a()){if("closing"===a())return m;if("idle"===a())return c("closed"),h(),void await e.dispose();if("connecting"!==a()||(await(f?.catch(()=>{})),"closed"!==a()))return c("closing"),m=(async()=>{if(await Promise.allSettled([...g]),u){const s=Ee(r);try{const r=await e.terminate({sessionId:u,protocolVersion:l,signal:s.signal,headers:t.headers});b({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{terminate:r.status,outcome:r.outcome,...r.reason?{reason:r.reason}:{}}})}catch(e){b({direction:"meta",at:Date.now(),event:"error",parsed:{terminate:"failed",reason:w(e).message}})}finally{s.dispose()}}await e.dispose(),c("closed"),h(),m=void 0})(),m}}t.signal&&(t.signal.aborted?(c("closed"),h()):t.signal.addEventListener("abort",()=>{O().catch(()=>{})},{once:!0}));const A={get protocol(){return"mcp"},get state(){return a()},get events(){return o.events},onEvent:e=>o.onEvent(e),get sessionId(){return u},get protocolVersion(){return l},get serverInfo(){return d},open:async function(){const s=a();if("open"===s)return;if("connecting"===s)return f;if("closing"===s||"closed"===s)throw v("MCP_SESSION_CLOSED","This session has been closed; create a new one.");c("connecting");const n=Ee(r,t.signal);return f=(async()=>{try{const r=await e.open({clientInfo:t.clientInfo,capabilities:t.capabilities,signal:n.signal});u=r.sessionId,l=r.protocolVersion??l??void 0,d=r.serverInfo,c("open"),b({direction:"in",at:Date.now(),event:"session",parsed:{sessionId:u,protocolVersion:l,serverInfo:d}})}catch(e){c("closed"),h();const t=w(e);if(b({direction:"meta",at:Date.now(),event:"error",parsed:t}),n.timedOut())throw v("MCP_TIMEOUT",`initialize timed out after ${r}ms`,t);throw e}finally{n.dispose(),f=void 0}})(),f},request:S,send:async function(e,t){M("send()");const r=p(e)?e:"string"==typeof e?{method:e}:void 0;if(!r||"string"!=typeof r.method||!r.method)throw v("BAD_MCP_MESSAGE","send() expects a method name or an object with a string `method`.");const s=r.method.startsWith("notifications/");return P(C({jsonrpc:"2.0",...r,...void 0!==r.id?{id:r.id}:s?{}:{id:K()}},t,s?"notification":"jsonrpc"))},notify:async function(e,t,r){if("string"!=typeof e||!e)throw v("BAD_MCP_METHOD","notify() requires a non-empty method name.");M(`notify("${e}")`);const s={jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}};await P(C(s,r,"notification"))},ping:e=>S("ping",{},e).then(()=>{}),listTools:e=>_("tools/list",e),listPrompts:e=>_("prompts/list",e),listResources:e=>_("resources/list",e),listResourceTemplates:e=>_("resources/templates/list",e),async listSources(e){const t=await(async()=>{if(n){const t=[];for(const r of["resources/list","resources/templates/list"])try{t.push({status:"fulfilled",value:await _(r,e)})}catch(e){t.push({status:"rejected",reason:e})}return t}return Promise.allSettled([_("resources/list",e),_("resources/templates/list",e)])})();if(t.every(e=>"rejected"===e.status))throw t[0].reason;const r=[];let s=0;for(const e of t)"fulfilled"===e.status&&(r.push(...e.value.items),s+=e.value.pages);return{items:r,pages:s}},callTool(e,t,r){if(e&&"object"==typeof e){const t=e;if(!t.name)throw v("BAD_MCP_TARGET","callTool() requires a tool name.");return S("tools/call",{name:t.name,arguments:t.arguments??{}},t.opts??r)}const s=e;if(!s)throw v("BAD_MCP_TARGET","callTool() requires a tool name.");return S("tools/call",{name:s,arguments:t??{}},r)},getPrompt(e,t,r){if(!e)throw v("BAD_MCP_TARGET","getPrompt() requires a prompt name.");return S("prompts/get",{name:e,arguments:t??{}},r)},readResource(e,t){if(!e)throw v("BAD_MCP_TARGET","readResource() requires a uri.");return S("resources/read",{uri:e},t)},close:O,waitForClose:()=>y};return A[Symbol.asyncDispose]=()=>O(),A}function Be(e){if(!e||"object"!=typeof e)throw v("BAD_MCP_ENDPOINT","MCP session options are required.");const t=function(e){if("stdio"===(e.transport??"streamable-http")){if(!e.command||!String(e.command).trim())throw v("BAD_MCP_STDIO_COMMAND","MCP stdio sessions require a non-empty `command`.");return Se({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes})}if(!e.endpoint)throw v("BAD_MCP_ENDPOINT",'MCP http sessions require an `endpoint` (or set transport: "stdio" with a `command`).');return Ce({endpoint:xe(e.endpoint),headers:e.headers})}(e);return De(t,e)}function je(e){return Be({...e,transport:"stdio"})}var $e=class{name="mcp";supports(e){const t=e.located.operation??{};return"mcp"===t["x-protocol"]?20:p(t["x-mcp"])||e.options.mcp?.method||e.options.mcp?.endpoint?15:"mcp"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=L(e.located,e.spec,e.options),r=[{key:"mcpEndpoint",value:t.endpoint,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"mcpEndpoint"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:h(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-mcp-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} MCP Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return fe(e.config,t,r)}};
@@ -0,0 +1,3 @@
1
+ import '../../protocol-Dh-wN2nY.cjs';
2
+ export { a1 as McpCapability, a2 as McpDiscoveryResult, a3 as McpListing, a4 as McpManualSession, a5 as McpManualSessionOptions, a7 as McpPrompt, a8 as McpRequestOptions, a9 as McpResource, aa as McpSessionEvent, ab as McpSessionState, ac as McpStdioSessionOptions, ad as McpTerminateOutcome, ae as McpTool } from '../../types-C9ifzKqk.cjs';
3
+ export { D as DiscoverAndWriteMcpResult, G as GeneratedMcpCall, M as MCP_PROTOCOL_VERSION, a as McpAdapter, l as McpPlan, m as McpStdioConnection, n as McpStdioOptions, o as McpTransport, W as WriteMcpOptions, c as createHttpMcpTransport, b as createMcpManualSession, p as createMcpSessionCore, q as createMcpStdioConnection, d as createMcpStdioSession, e as createStdioMcpTransport, f as discoverAndWriteMcpCapabilities, g as discoverMcpCapabilities, h as generateAllMcpCalls, i as generateMcpCall, j as initializeSession, b as mcpManualSession, r as resolveMcpConfig, s as runMcp, b as runMcpManualSession, w as writeMcpOperations } from '../../index-1jRrFc3d.cjs';
@@ -0,0 +1,3 @@
1
+ import '../../protocol-D7sEx8IP.js';
2
+ export { a1 as McpCapability, a2 as McpDiscoveryResult, a3 as McpListing, a4 as McpManualSession, a5 as McpManualSessionOptions, a7 as McpPrompt, a8 as McpRequestOptions, a9 as McpResource, aa as McpSessionEvent, ab as McpSessionState, ac as McpStdioSessionOptions, ad as McpTerminateOutcome, ae as McpTool } from '../../types-C9ifzKqk.js';
3
+ export { D as DiscoverAndWriteMcpResult, G as GeneratedMcpCall, M as MCP_PROTOCOL_VERSION, a as McpAdapter, l as McpPlan, m as McpStdioConnection, n as McpStdioOptions, o as McpTransport, W as WriteMcpOptions, c as createHttpMcpTransport, b as createMcpManualSession, p as createMcpSessionCore, q as createMcpStdioConnection, d as createMcpStdioSession, e as createStdioMcpTransport, f as discoverAndWriteMcpCapabilities, g as discoverMcpCapabilities, h as generateAllMcpCalls, i as generateMcpCall, j as initializeSession, b as mcpManualSession, r as resolveMcpConfig, s as runMcp, b as runMcpManualSession, w as writeMcpOperations } from '../../index-CsRXyS7O.js';
@@ -0,0 +1 @@
1
+ var e=new Set(["__proto__","constructor","prototype"]);function t(t){return e.has(t)}function r(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return function(e){return s(e,new Set)}(e)}function s(e,r){if(null===e)return null;const n=typeof e;if("string"===n||"boolean"===n)return e;if("number"===n)return Number.isFinite(e)?e:null;if("bigint"===n)return e.toString();if("object"!==n)return;const o=e;if(r.has(o))return null;const i=o.toJSON;if("function"==typeof i){let e;try{e=i.call(o)}catch{return null}return e===o?null:s(e,r)}r.add(o);try{if(Array.isArray(o)){const e=new Array(o.length);for(let t=0;t<o.length;t+=1){const n=s(o[t],r);e[t]=void 0===n?null:n}return e}const e={};for(const n of Object.keys(o)){if(t(n))continue;let i;try{i=o[n]}catch{continue}const a=s(i,r);void 0!==a&&(e[n]=a)}return e}finally{r.delete(o)}}function n(e,t){const r=o(e);return r&&-1!==r.indexOf("{{")&&t?r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;const s=t[r];return null==s?e:o(s)}):r}function o(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function i(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function a(e){return e instanceof Error?e.message:String(e)}var c=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function u(e){return c.test(e)}var l=Symbol.for("@powerduck/openapi-request.ProtoKitError"),d=class e extends Error{code;details;[l]=!0;constructor(t,r,s,n){if(super(t),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=s,n&&"cause"in n)try{Object.defineProperty(this,"cause",{value:n.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,e.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isProtoKitError(e){return"object"==typeof e&&null!==e&&!0===e[l]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function f(e,t,r,s){return new d(t,e,r,s)}function p(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function m(e){if(d.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:p(e)}}var h="\0PK_OPEN\0",y="\0PK_CLOSE\0";function g(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return b(v(r),"options.serverUrl");const s=Array.isArray(e)?e.filter(i):[],n=s[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??s[0];let o=n&&"string"==typeof n.url&&n.url.trim()?n.url.trim():"";if(!o)throw f("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return o=function(e,t,r){const s=i(t)?t:{};let n=e;for(const[e,t]of Object.entries(s)){const s=r?.[e];let o;if(null!=s){if(o=s,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(s)))throw f("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:s,allowed:t.enum})}else if(void 0!==t?.default)o=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw f("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);o=t.enum[0]}n=n.split(`{${e}}`).join(String(o??""))}for(const[e,t]of Object.entries(r??{}))Object.prototype.hasOwnProperty.call(s,e)||null!=t&&(n=n.split(`{${e}}`).join(String(t)));return n}(o,n?.variables,t.serverVariables),b(v(o),"spec.servers")}function v(e){return e.replace(/\/+$/,"")||e}function b(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(h).split("}}").join(y).replace(/\{[^{}]*\}/g,"").split(h).join("{{").split(y).join("}}")}(e);if(!r)throw f("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw f("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}var w=new Set(["__proto__","constructor","prototype"]),M="2024-01-01T00:00:00.000Z";function P(e,t=0,r={}){const s=r.maxDepth??12;if(!e||"object"!=typeof e||Array.isArray(e))return null;if(t>s)return null;if("string"==typeof e.$ref)return null;if(void 0!==e.example)return e.example;const n=function(e){if(null==e)return;if(Array.isArray(e))return e.length?e[0]:void 0;if("object"==typeof e)for(const t of Object.values(e))if(void 0!==t){if(t&&"object"==typeof t){if("value"in t)return t.value;if("externalValue"in t)continue}return t}return}(e.examples);if(void 0!==n)return n;if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length){const t=e.enum.find(e=>null!==e);return void 0!==t?t:e.enum[0]}if(Array.isArray(e.allOf)&&e.allOf.length)return function(e,t,r){let s,n;for(const o of e.allOf){const e=P(o,t+1,r);null===e||"object"!=typeof e||Array.isArray(e)?null!=e&&(n=e):s={...s??{},...e}}if(e.properties||e.required){const n=C(e,t,r);n&&"object"==typeof n&&(s={...s??{},...n})}return s||(void 0!==n?n:{})}(e,t,r);for(const s of["oneOf","anyOf"]){const n=e[s];if(Array.isArray(n)&&n.length){return P(n.find(e=>e&&"object"==typeof e&&"null"!==e.type)??n[0],t+1,r)}}const o=function(e){const t=Array.isArray(e.type)?e.type.find(e=>"string"==typeof e&&"null"!==e)??(e.type.includes("null")?"null":void 0):"string"==typeof e.type?e.type:void 0;if(t)return t;if(e.properties||e.additionalProperties||e.required)return"object";if(e.items||e.prefixItems)return"array";if(void 0!==e.minimum||void 0!==e.maximum||void 0!==e.multipleOf)return"number";return"string"}(e);switch(o){case"object":return C(e,t,r);case"array":return function(e,t,r){const s=[];if(Array.isArray(e.prefixItems))for(const n of e.prefixItems)s.push(P(n,t+1,r));const n=I(e.minItems)??1,o=I(e.maxItems);let i=Math.max(n,s.length,1);i=Math.min(i,5),void 0!==o&&(i=Math.min(i,Math.max(o,0)));const a=e.items&&"object"==typeof e.items?e.items:void 0;if(!a&&Array.isArray(e.prefixItems))return s.slice(0,0===i?0:Math.max(i,s.length));for(;s.length<i;){const n=P(a??{},t+1,r);if(!0===e.uniqueItems&&s.length>0)break;s.push(n)}return void 0!==o?s.slice(0,Math.max(o,0)):s}(e,t,r);case"integer":return function(e){const{min:t,max:r}=S(e,!0);let s=0;void 0!==t&&s<t&&(s=Math.ceil(t));void 0!==r&&s>r&&(s=Math.floor(r));const n=A(e.multipleOf);if(void 0!==n&&n>0){const e=Math.ceil(s/n)*n;(void 0===r||e<=r)&&(s=e)}return Math.trunc(s)}(e);case"number":return function(e){const{min:t,max:r}=S(e,!1);let s=0;void 0!==t&&s<t&&(s=t);void 0!==r&&s>r&&(s=r);const n=A(e.multipleOf);if(void 0!==n&&n>0){const e=Math.ceil(s/n)*n;(void 0===r||e<=r)&&(s=e)}return s}(e);case"boolean":return!1;case"null":return null;default:return function(e){const t="string"==typeof e.format?e.format:void 0,r=t?function(e){switch(e){case"date-time":return M;case"date":return M.slice(0,10);case"time":return M.slice(11,19);case"duration":return"PT1S";case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":case"idn-email":return"user@example.com";case"hostname":case"idn-hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"iri":return"https://example.com";case"uri-reference":case"iri-reference":case"json-pointer":return"/example";case"uri-template":return"https://example.com/{id}";case"relative-json-pointer":return"0/example";case"regex":return"^example$";case"byte":return"ZXhhbXBsZQ==";case"binary":return"";case"password":return"password";default:return}}(t):void 0;return void 0!==r?_(r,e):"string"==typeof e.pattern&&e.pattern.length?"":_("string",e)}(e)}}function C(e,t,r){const s={},n=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],o=e.properties&&"object"==typeof e.properties?e.properties:{},i=!0===r.includeReadOnly,a=!1!==r.includeWriteOnly;for(const[e,c]of Object.entries(o))w.has(e)||!i&&c&&!0===c.readOnly||!a&&c&&!0===c.writeOnly||t>2&&n.length&&!n.includes(e)||(s[e]=P(c,t+1,r));for(const e of n)w.has(e)||e in s||(s[e]=P(o[e]??{},t+1,r));!Object.keys(s).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(s.key=P(e.additionalProperties,t+1,r));const c=I(e.minProperties);if(void 0!==c){const n=e.additionalProperties&&"object"==typeof e.additionalProperties?e.additionalProperties:{};let o=1;for(;Object.keys(s).length<Math.min(c,20);){const e=`additionalProp${o}`;o+=1,e in s||(s[e]=P(n,t+1,r))}}return s}function S(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let s=A(e.minimum),n=A(e.maximum);const o=e.exclusiveMinimum,i=e.exclusiveMaximum;if("number"==typeof o&&Number.isFinite(o)){const e=o+r;s=void 0===s?e:Math.max(s,e)}else!0===o&&void 0!==s&&(s+=r);if("number"==typeof i&&Number.isFinite(i)){const e=i-r;n=void 0===n?e:Math.min(n,e)}else!0===i&&void 0!==n&&(n-=r);return{min:s,max:n}}function _(e,t){const r=I(t.minLength),s=I(t.maxLength);let n=e;return void 0!==r&&n.length<r&&(n=n.padEnd(Math.min(r,256),"x")),void 0!==s&&n.length>s&&(n=n.slice(0,Math.max(s,0))),n}function A(e){if("number"==typeof e&&Number.isFinite(e))return e}function I(e){const t=A(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}var O=new Set(["tools/call","resources/read","prompts/get","tools/list","resources/list","resources/templates/list","prompts/list"]);function E(e,t,r){const s=r.mcp??{},o=e.operation?.["x-mcp"],a=o&&"object"==typeof o?o:{},c={...r.variables??{}},u=s.transport??a.transport??"streamable-http";if("streamable-http"!==u&&"stdio"!==u)throw f("BAD_MCP_TRANSPORT",`Unsupported MCP transport: ${JSON.stringify(u)}`);const l=u;let d,p,m,h,y,v,b,w;if("streamable-http"===l){if(d=s.endpoint||("string"==typeof a.endpoint?a.endpoint:g(e.servers,r)),d=n(d,c),/\{\{[^}]+\}\}/.test(d))throw f("BAD_MCP_ENDPOINT",`Unresolved variable in MCP endpoint: ${d}`);try{const e=new URL(d);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw f("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${d}`)}}else{const e=s.command??a.command;if("string"!=typeof e||!e.trim())throw f("BAD_MCP_STDIO_COMMAND","MCP stdio transport requires command.");if(p=n(e.trim(),c),/\{\{[^}]+\}\}/.test(p))throw f("BAD_MCP_STDIO_COMMAND",`Unresolved variable in MCP command: ${p}`);const t=s.args??a.args;if(null!=t){if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw f("BAD_MCP_STDIO_CONFIG","MCP stdio args must be an array of strings.");m=t.map(e=>n(e,c))}const r=s.cwd??a.cwd;if(null!=r){if("string"!=typeof r||!r)throw f("BAD_MCP_STDIO_CONFIG","MCP stdio cwd must be a non-empty string.");h=n(r,c)}const o=s.env??a.env;if(null!=o){if(!i(o))throw f("BAD_MCP_STDIO_CONFIG","MCP stdio env must be an object.");y={};for(const[e,t]of Object.entries(o))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(y[e]=null==t?void 0:n(String(t),c))}for(const[e,t]of[["timeoutMs",s.timeoutMs??a.timeoutMs],["maxBufferBytes",s.maxBufferBytes??a.maxBufferBytes],["maxStderrBytes",s.maxStderrBytes??a.maxStderrBytes]])if(null!=t){if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw f("BAD_MCP_STDIO_CONFIG",`${e} must be a positive finite number.`);"timeoutMs"===e?v=t:"maxBufferBytes"===e?b=t:w=t}}const M=s.method??a.method;if("string"!=typeof M||!O.has(M))throw f("BAD_MCP_METHOD",`options.mcp.method (or x-mcp.method) must be one of: ${Array.from(O).join(", ")}. Received: ${JSON.stringify(M)}`);const C=s.name??a.name,S=i(a.arguments)?a.arguments:void 0,_=i(a.argumentsSchema)?a.argumentsSchema:void 0,A=_?P(_):void 0,I=i(r.values?.body)?r.values.body:void 0,E={...i(A)?A:{},...S??{},...I??{},...s.arguments??{}};let x;if("tools/call"===M){if(!C)throw f("BAD_MCP_TARGET","tools/call requires options.mcp.name (or x-mcp.name).");x={name:C,arguments:E}}else if("prompts/get"===M){if(!C)throw f("BAD_MCP_TARGET","prompts/get requires options.mcp.name (or x-mcp.name).");x={name:C,arguments:E}}else if("resources/read"===M){const e=E.uri??a.uri??s.arguments?.uri;if("string"!=typeof e||!e)throw f("BAD_MCP_TARGET","resources/read requires a `uri` (via options.mcp.arguments.uri or x-mcp.uri).");x={uri:e}}else x=E;const D={"Content-Type":"application/json"},B=e=>{if(i(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(D[t]=n(String(r),c))};B(r.values?.header),B(a.headers),B(s.headers);const j=r.auth;if(j&&"none"!==j.type&&!function(e,t){const r=t.toLowerCase();return Object.keys(e).some(e=>e.toLowerCase()===r)}(D,"Authorization"))if("bearer"===j.type)D.Authorization=`Bearer ${j.token??""}`;else if("basic"===j.type){const e=`${j.username??""}:${j.password??""}`;D.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===j.type&&"header"===(j.in??"header")&&(D[j.key??"X-API-Key"]=j.value??"");return{transport:l,..."streamable-http"===l&&d?{endpoint:d}:{},..."stdio"===l&&p?{command:p,...m?{args:m}:{},...h?{cwd:h}:{},...y?{env:y}:{},...null!=v?{timeoutMs:v}:{},...null!=b?{maxBufferBytes:b}:{},...null!=w?{maxStderrBytes:w}:{}}:{},method:M,params:x,headers:D,sessionId:s.sessionId??T(a.sessionId),protocolVersion:s.protocolVersion??T(a.protocolVersion),clientInfo:s.clientInfo??{name:"protokit",version:"0.1.0"}}}function T(e){return"string"==typeof e&&e.length?e:void 0}var x=new Set(["[DONE]","DONE","[done]","done"]),D=/\r\n\r\n|\n\n|\r\r/,B=/^\d+$/;function j(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var $=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=j(e.maxBufferChars,4194304),this.maxEventChars=j(e.maxEventChars,1048576),this.inheritEventId=!1!==e.inheritEventId}get truncated(){return this.overflowed}get count(){return this.sequence}push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{let t;if(e instanceof Uint8Array)t=e;else try{t=new Uint8Array(e)}catch{return[]}try{this.buffer+=this.decoder.decode(t,{stream:!0})}catch{return[]}}!this.bomChecked&&this.buffer.length&&(this.bomChecked=!0,65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1)));const t=this.drain();return this.buffer.length>this.maxBufferChars&&(this.overflowed=!0,this.droppedEvents+=1,this.buffer=this.buffer.slice(-8)),t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.drain(),t=this.buffer;if(this.buffer="",t.trim()){const r=this.parseBlock(t);r&&e.push(r)}return e}reset(){this.buffer="",this.lastEventId=void 0,this.bomChecked=!1,this.overflowed=!1,this.sequence=0,this.droppedEvents=0;try{this.decoder.decode()}catch{}}drain(){const e=[];for(;;){const t=D.exec(this.buffer);if(!t)break;const r=this.buffer.slice(0,t.index);this.buffer=this.buffer.slice(t.index+t[0].length);const s=this.parseBlock(r);s&&e.push(s)}return e}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],s={data:"",receivedAt:Date.now(),direction:"in"};let n=!1,o=0,i=!1;for(const e of t){if(""===e)continue;if(58===e.charCodeAt(0))continue;const t=e.indexOf(":"),a=-1===t?e:e.slice(0,t);let c=-1===t?"":e.slice(t+1);switch(32===c.charCodeAt(0)&&(c=c.slice(1)),a){case"data":{if(n=!0,i)break;const e=this.maxEventChars-o;c.length>e?(r.push(c.slice(0,Math.max(0,e))),i=!0,this.overflowed=!0,this.droppedEvents+=1):(r.push(c),o+=c.length+1);break}case"event":s.event=c,n=!0;break;case"id":c.includes("\0")||(s.id=c,this.lastEventId=c),n=!0;break;case"retry":if(B.test(c)&&c.length<=15){const e=Number(c);Number.isSafeInteger(e)&&(s.retry=e)}n=!0}}if(!n)return null;if(s.data=r.join("\n"),void 0===s.id&&this.inheritEventId&&void 0!==this.lastEventId&&(s.id=this.lastEventId),!i){const e=s.data.trim();if(e&&!x.has(e)&&function(e){const t=e.charCodeAt(0);return 123===t||91===t||34===t}(e))try{s.parsed=JSON.parse(s.data)}catch{}}return this.sequence+=1,s}};var R=0;function N(){return R+=1}async function k(e,t,r){const s=new AbortController;let n,o,i;if(r.signal){const e=()=>s.abort(r.signal?.reason);r.signal.aborted?e():(r.signal.addEventListener("abort",e,{once:!0}),n=()=>r.signal?.removeEventListener("abort",e))}"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(o=setTimeout(()=>{s.abort(new Error(`MCP request timed out after ${r.timeoutMs}ms`))},r.timeoutMs),"function"==typeof o?.unref&&o.unref());try{i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...r.protocolVersion?{"MCP-Protocol-Version":r.protocolVersion}:{},...r.headers??{}},body:JSON.stringify(t),signal:s.signal})}catch(e){throw f("MCP_TRANSPORT_FAILED",`Could not reach MCP endpoint: ${e?.message??e}`,void 0,{cause:e})}finally{o&&clearTimeout(o),n?.()}const a=Date.now()-r.startedAt,c=function(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}(i.headers),u=i.headers.get("content-type")??void 0,l=i.headers.get("mcp-session-id")??void 0;if(202===i.status||204===i.status)return{message:void 0,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,sizeBytes:0,firstByteMs:a};if(u&&/text\/event-stream/i.test(u)&&i.body){const e=new $,s=i.body.getReader();let n=0;const o="number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0?r.maxResponseBytes:0;let d;for(;;){const{done:r,value:i}=await s.read();if(r)break;if(n+=i?.byteLength??0,o>0&&n>o){try{await s.cancel()}catch{}throw f("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${o} bytes while reading event stream.`)}for(const r of e.push(i))if(r.parsed&&"object"==typeof r.parsed){const e=r.parsed;void 0!==t.id&&e.id!==t.id||(d=e)}if(void 0!==d){try{await s.cancel()}catch{}break}}if(void 0===d)for(const t of e.flush())t.parsed&&"object"==typeof t.parsed&&(d=t.parsed);return{message:d,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,sizeBytes:n,firstByteMs:a}}let d,p;try{if(d=await i.text(),"number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0&&d.length>r.maxResponseBytes)throw f("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${r.maxResponseBytes} bytes.`);d.trim()&&(p=JSON.parse(d))}catch(e){return{message:void 0,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}return{message:p,status:i.status,statusText:i.statusText,headers:c,contentType:u,sessionId:l,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}function L(e){return!!e&&"object"==typeof e&&i(e.error)}var V="2025-06-18",q=new Set([-32601,-32600]),z={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};async function U(e,t={}){const r=Date.now(),s=await k(e,{jsonrpc:"2.0",id:N(),method:"initialize",params:{protocolVersion:V,capabilities:t.capabilities??{},clientInfo:t.clientInfo??{name:"protokit",version:"0.1.0"}}},{headers:t.headers,signal:t.signal,startedAt:r});if(L(s.message))throw f("MCP_INITIALIZE_FAILED",`initialize failed: ${s.message.error.message}`,s.message.error);if(!s.message?.result)throw f("MCP_INITIALIZE_FAILED",`initialize returned no result (HTTP ${s.status}). The endpoint may not speak MCP.`);const n=s.sessionId,o=s.message.result.protocolVersion;return await k(e,{jsonrpc:"2.0",method:"notifications/initialized"},{headers:{...t.headers??{},...n?{"Mcp-Session-Id":n}:{}},signal:t.signal,startedAt:r,protocolVersion:o}),{sessionId:n,serverInfo:s.message.result.serverInfo,protocolVersion:o}}async function F(e,t,r,s){const n=Date.now(),o={...s.headers??{},...r.sessionId?{"Mcp-Session-Id":r.sessionId}:{}},i=z[t],a=[],c=new Set;let u,l=0;for(;;){const d=await k(e,{jsonrpc:"2.0",id:N(),method:t,params:u?{cursor:u}:{}},{headers:o,signal:s.signal,startedAt:n,protocolVersion:r.protocolVersion});if(L(d.message)){const{code:e,message:r}=d.message.error;if(q.has(e))return;throw f("MCP_LIST_FAILED",`${t} failed (${e}): ${r}`,d.message.error)}const p=d.message?.result;if(!p){if(d.status>=400)throw f("MCP_LIST_FAILED",`${t} returned HTTP ${d.status} ${d.statusText} with no JSON-RPC result.`);return a}l+=1,Array.isArray(p[i])&&a.push(...p[i]);const m="string"==typeof p.nextCursor?p.nextCursor:void 0;if(!m)break;if(c.has(m)||l>=1e3)break;c.add(m),u=m}return a}async function J(e,t={}){const r=await U(e,t),s=[],n=[],o=await F(e,"tools/list",r,t);if(o)for(const e of o)e?.name&&n.push({kind:"tool",name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema??{},...e.execution&&"object"==typeof e.execution?{execution:e.execution}:{}});else s.push("Server does not implement tools/list.");const i=await F(e,"resources/list",r,t),a=await F(e,"resources/templates/list",r,t);for(const e of[...i??[],...a??[]])e?.name&&n.push({kind:"resource",name:e.name,title:e.title,uri:e.uri,uriTemplate:e.uriTemplate,description:e.description,mimeType:e.mimeType});i||a||s.push("Server does not implement resources/list or resources/templates/list.");const c=await F(e,"prompts/list",r,t);if(c)for(const e of c)e?.name&&n.push({kind:"prompt",name:e.name,title:e.title,description:e.description,arguments:e.arguments});else s.push("Server does not implement prompts/list.");return{serverInfo:r.serverInfo,protocolVersion:r.protocolVersion,sessionId:r.sessionId,capabilities:n,warnings:s}}import{spawn as G}from"child_process";import{once as K}from"events";function H(e){if(!e||"string"!=typeof e.command||!e.command.trim())throw f("BAD_MCP_STDIO_COMMAND","MCP stdio requires a non-empty command.");const t=Z(e.timeoutMs,3e4,"timeoutMs"),r=Z(e.maxBufferBytes,4194304,"maxBufferBytes"),s=function(e){const t={...process.env};if(!e)return t;for(const[r,s]of Object.entries(e))void 0===s?delete t[r]:t[r]=s;return t}(e.env);let n;try{n=G(e.command,e.args??[],{cwd:e.cwd,env:s,stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(e){throw f("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${a(e)}`,void 0,{cause:e})}let o=!1,i=0,c="",u="";const l=new Map,d=(e,t)=>{l.get(e)===t&&l.delete(e),t.timer&&clearTimeout(t.timer),t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort)},p=e=>{for(const[t,r]of l)d(t,r),r.reject(e)},m=e=>{if(o)return;const t=f("MCP_STDIO_PROTOCOL_ERROR",e);p(t),y()};function h(e){if(o||n.stdin.destroyed||!n.stdin.writable)return Promise.reject(f("MCP_STDIO_CLOSED","MCP stdio process is closed."));let t;try{t=JSON.stringify(e)+"\n"}catch(e){return Promise.reject(f("MCP_STDIO_SERIALIZE_FAILED",`Could not serialize MCP JSON-RPC message: ${a(e)}`,void 0,{cause:e}))}return new Promise((e,r)=>{n.stdin.write(t,"utf8",t=>{t?r(t):e()})})}async function y(){if(o)return;if(o=!0,p(f("MCP_STDIO_CLOSED","MCP stdio process was closed.")),n.stdin.destroyed||n.stdin.end(),null!==n.exitCode||n.killed)return;try{n.kill("SIGTERM")}catch{return}const e=setTimeout(()=>{if(null===n.exitCode&&!n.killed)try{n.kill("SIGKILL")}catch{}},1500);e.unref?.();try{await Promise.race([K(n,"exit").then(()=>{}),(t=2e3,t>0?new Promise((e,s)=>{const n=()=>{clearTimeout(o),s(new Error("Aborted while waiting."))},o=setTimeout(()=>{r?.removeEventListener("abort",n),e()},t);if(o?.unref?.(),r?.aborted)return n();r?.addEventListener("abort",n,{once:!0})}):Promise.resolve())])}finally{clearTimeout(e)}var t,r}return n.stdout.setEncoding("utf8"),n.stdout.on("data",e=>{if(!o)if(c+=e,Buffer.byteLength(c,"utf8")>r)m(`MCP stdio stdout buffer exceeded ${r} bytes without a complete JSON-RPC line.`);else for(;;){const e=c.indexOf("\n");if(e<0)break;const t=c.slice(0,e).replace(/\r$/,"");if(c=c.slice(e+1),!t.trim())continue;if(Buffer.byteLength(t,"utf8")>r)return void m(`MCP stdio JSON-RPC message exceeded ${r} bytes.`);let s;try{s=JSON.parse(t)}catch{return void m(`MCP stdio emitted invalid JSON-RPC: ${t.slice(0,512)}`)}if(!W(s))return void m("MCP stdio emitted an invalid JSON-RPC envelope.");if(void 0===s.id)continue;const n=l.get(s.id);n&&(d(s.id,n),void 0!==s.error?n.reject(f("MCP_RPC_ERROR",`${s.error.code}: ${s.error.message}`,s.error)):Object.prototype.hasOwnProperty.call(s,"result")?n.resolve(s.result):n.reject(f("MCP_STDIO_PROTOCOL_ERROR","MCP stdio response contained neither result nor error.")))}}),n.stderr.setEncoding("utf8"),n.stderr.on("data",e=>{u=(u+e).slice(-65536)}),n.once("error",e=>{o||(o=!0,p(f("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${a(e)}`,void 0,{cause:e})))}),n.once("exit",(e,t)=>{if(o)return;o=!0;const r=u.trim()?` stderr: ${u.trim().slice(-2048)}`:"";p(f("MCP_STDIO_EXITED",`MCP stdio process exited (code=${e}, signal=${t??"none"}).${r}`))}),{get pid(){return n.pid},request:function(e,r,s){if(s?.aborted)return Promise.reject(f("MCP_ABORTED","MCP request was aborted before send."));if(o)return Promise.reject(f("MCP_STDIO_CLOSED","MCP stdio process is closed."));const n=++i;return new Promise((o,i)=>{const a={resolve:o,reject:i};a.timer=setTimeout(()=>{d(n,a),i(f("MCP_TIMEOUT",`${e} timed out after ${t}ms`))},t),a.timer.unref?.(),s&&(a.signal=s,a.onAbort=()=>{d(n,a),i(f("MCP_ABORTED",`${e} was aborted.`))},s.addEventListener("abort",a.onAbort,{once:!0})),l.set(n,a),h({jsonrpc:"2.0",id:n,method:e,...void 0===r?{}:{params:r}}).catch(e=>{d(n,a),i(e)})})},notify:async function(e,t,r){if(r?.aborted)throw f("MCP_ABORTED","MCP notification was aborted before send.");await h({jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}})},close:y}}function Z(e,t,r){const s=e??t;if(!Number.isFinite(s)||s<=0)throw f("BAD_MCP_STDIO_CONFIG",`MCP stdio ${r} must be a positive finite number.`);return s}function W(e){return!!e&&"object"==typeof e&&"2.0"===e.jsonrpc}async function X(e,t,r){return"stdio"===e.transport?async function(e,t,r){const s=Date.now(),n=[],o=r?.signal??t.signal,i={jsonrpc:"2.0",id:N(),method:e.method,params:e.params},a=H({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes});try{const t=await a.request("initialize",{protocolVersion:e.protocolVersion??V,capabilities:{},clientInfo:e.clientInfo},o);if(!t||"object"!=typeof t)throw new Error("MCP initialize returned an invalid result.");n.push({url:`stdio://${e.command}`,method:"initialize",status:200,reason:"mcp-stdio-handshake"}),await a.notify("notifications/initialized",void 0,o);const r=await a.request(e.method,e.params,o),c=Date.now();return{protocol:"mcp",request:{method:"STDIO",url:`stdio://${e.command}`,headers:{},body:i},response:{status:200,statusText:"OK",headers:{},body:r,text:JSON.stringify(r),timings:{startedAt:s,endedAt:c,durationMs:c-s},sizeBytes:Buffer.byteLength(JSON.stringify(r))},replays:n}}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"STDIO",url:`stdio://${e.command}`,headers:{},body:i},response:{status:0,statusText:"MCP stdio failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:m(t),replays:n}}finally{await a.close().catch(()=>{})}}(e,t,r):async function(e,t,r){const s=Date.now(),n=r?.signal??t.signal,o=[];let i=e.sessionId,a=e.protocolVersion;if(!i)try{const t=await U(e.endpoint,{headers:e.headers,signal:n,clientInfo:e.clientInfo});i=t.sessionId,a=t.protocolVersion,o.push({url:e.endpoint,method:"initialize",status:200,reason:"mcp-handshake"})}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:e.headers,body:{method:"initialize"}},response:{status:0,statusText:"Handshake failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:m(t),replays:o}}const c={...e.headers,...i?{"Mcp-Session-Id":i}:{}},u={jsonrpc:"2.0",id:N(),method:e.method,params:e.params};try{const t=await k(e.endpoint,u,{headers:c,signal:n,startedAt:s,protocolVersion:a}),r=Date.now(),i=L(t.message)?t.message.error:void 0;return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:u},response:{status:t.status,statusText:t.statusText,headers:t.headers,contentType:t.contentType,body:i?t.message:t.message?.result,text:t.rawText,timings:{startedAt:s,endedAt:r,durationMs:r-s,firstByteMs:t.firstByteMs},sizeBytes:t.sizeBytes},...i?{error:{message:i.message,code:String(i.code)}}:{},replays:o}}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:u},response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:s,endedAt:r,durationMs:r-s},sizeBytes:0},error:m(t),replays:o}}}(e,t,r)}function Q(e){const t=[];if("tool"===e.kind){const r=e.inputSchema??{type:"object",properties:{}},s=P(r);return{capability:e,method:"tools/call",params:{name:e.name,arguments:s&&"object"==typeof s?s:{}},argumentsSchema:r,notes:t}}if("prompt"===e.kind){const r={},s=[];for(const t of e.arguments??[])r[t.name]={type:"string",description:t.description},t.required&&s.push(t.name);const n={type:"object",properties:r,required:s},o=P(n);return{capability:e,method:"prompts/get",params:{name:e.name,arguments:o&&"object"==typeof o?o:{}},argumentsSchema:n,notes:t}}return!e.uri&&e.uriTemplate&&t.push(`Resource "${e.name}" is a template (${e.uriTemplate}); fill in its placeholders before calling.`),{capability:e,method:"resources/read",params:{uri:e.uri??e.uriTemplate??""},argumentsSchema:{type:"object",properties:{uri:{type:"string"}},required:["uri"]},notes:t}}function Y(e){return e.map(Q)}function ee(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function te(e){return`/mcp/${"tool"===e.kind?"tools":"prompt"===e.kind?"prompts":"resources"}/${ee(e.name)}`}function re(e,t,s,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw f("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,a=r(e);i(a.paths)||(a.paths={});for(const e of s){const{capability:r}=e,s=te(r);!o&&i(a.paths[s])||(a.paths[s]={post:{operationId:`mcp_${r.kind}_${ee(r.name)}`,summary:`MCP ${r.kind}: ${r.name}`,description:r.description,"x-protocol":"mcp","x-mcp":{endpoint:t,method:e.method,name:"resource"===r.kind?void 0:r.name,uri:"resource"===r.kind?r.uri??r.uriTemplate:void 0,argumentsSchema:e.argumentsSchema,arguments:e.params.arguments},requestBody:{content:{"application/json":{schema:e.argumentsSchema}}},responses:{200:{description:"MCP JSON-RPC result."}},...e.notes.length?{"x-mcp-notes":e.notes}:{}}})}return a}async function se(e,t,r={}){const s=await J(t,r);return{spec:re(e,t,Y(s.capabilities),r),capabilities:s.capabilities,warnings:s.warnings}}function ne(e,t=new WeakMap){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(void 0===e)return null;if("bigint"==typeof e)return e.toString();if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return String(e);if(e instanceof Date)return e.toISOString();if(e instanceof URL)return e.toString();if(e instanceof Error){const r={name:e.name,message:e.message,stack:e.stack},s=e.cause;return void 0!==s&&(r.cause=ne(s,t)),r}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return{type:"Buffer",data:Array.from(e.values())};if(e instanceof Uint8Array)return{type:e.constructor.name,data:Array.from(e.values())};if(Array.isArray(e))return e.map(e=>ne(e,t));if("object"==typeof e){const r=e;if(t.has(r))return t.get(r);const s={};t.set(r,s);for(const[e,n]of Object.entries(r))s[e]=ne(n,t);return s}return String(e)}var oe=class{constructor(e,t,r,s=1e3){this.protocol=e,this.transport=t,this.sessionId=r,this.maxEvents=s}protocol;transport;sessionId;maxEvents;state="idle";events=[];listeners=new Set;setState(e){this.state=e}emit(e){const t={protocol:this.protocol,transport:this.transport,sessionId:this.sessionId,at:e.at??Date.now(),direction:e.direction,kind:e.kind,state:e.state,data:ne(e.data),error:ne(e.error),meta:ne(e.meta)};this.events.push(t),this.maxEvents>0&&this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);for(const e of this.listeners)try{e(t)}catch{}}onEvent(e){return this.listeners.add(e),{unsubscribe:()=>{this.listeners.delete(e)}}}},ie=class extends oe{async open(){}async close(){}async waitForClose(){}async send(){}};function ae(e){if(!e||!e.endpoint)throw f("BAD_MCP_ENDPOINT","MCP http transport requires an endpoint.");const t=e.endpoint,r={...e.headers??{}};return{transport:"streamable-http",async open(e){const s={headers:r,signal:e.signal,clientInfo:e.clientInfo,capabilities:e.capabilities},n=await U(t,s);return{sessionId:n.sessionId,serverInfo:n.serverInfo,protocolVersion:n.protocolVersion??e.protocolVersion??V}},call:(e,s)=>k(t,e,{headers:{...s.headers??r},signal:s.signal,startedAt:s.startedAt,protocolVersion:s.protocolVersion}),notify:(e,s)=>k(t,e,{headers:{...s.headers??r},signal:s.signal,startedAt:s.startedAt,protocolVersion:s.protocolVersion}),async terminate(e){const s=await fetch(t,{method:"DELETE",headers:{...r,...e.sessionId?{"Mcp-Session-Id":e.sessionId}:{},...e.protocolVersion?{"MCP-Protocol-Version":e.protocolVersion}:{}},signal:e.signal}).then(e=>e.status,()=>{});return void 0===s?{outcome:"failed",reason:"terminate request failed"}:s>=200&&s<300?{status:s,outcome:"released"}:405===s?{status:s,outcome:"unsupported"}:404===s?{status:s,outcome:"already-gone"}:{status:s,outcome:"failed"}},async dispose(){}}}function ce(e){const t=H(e);let r=!1;return{transport:"stdio",async open(e){const r=await t.request("initialize",{protocolVersion:e.protocolVersion??V,capabilities:e.capabilities??{},clientInfo:e.clientInfo??{name:"protokit",version:"0.1.0"}},e.signal);if(!r||"object"!=typeof r)throw f("MCP_INITIALIZE_FAILED","MCP stdio initialize returned an invalid result.");return await t.notify("notifications/initialized",void 0,e.signal),{sessionId:void 0,serverInfo:r.serverInfo,protocolVersion:r.protocolVersion??e.protocolVersion??V}},async call(e,r){const s=await t.request(e.method,e.params,r.signal),n=JSON.stringify(s);return{message:{jsonrpc:"2.0",id:e.id,result:s},status:200,statusText:"OK",headers:{},sizeBytes:Buffer.byteLength(n??"null","utf8"),firstByteMs:0}},notify:async(e,r)=>(await t.notify(e.method,e.params,r.signal),{message:void 0,status:200,statusText:"OK",headers:{},sizeBytes:0,firstByteMs:0}),terminate:async()=>({outcome:"unsupported"}),async dispose(){r||(r=!0,await t.close().catch(()=>{}))}}}var ue={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};function le(e,t=0,r=new WeakSet){if(t>8)return"[depth-limit]";if(!i(e)&&!Array.isArray(e))return e;if("object"==typeof e&&null!==e){if(r.has(e))return"[circular]";r.add(e)}if(Array.isArray(e))return e.map(e=>le(e,t+1,r));const s={};for(const[n,o]of Object.entries(e))s[n]=u(n)&&null!=o?"[redacted]":le(o,t+1,r);return s}function de(e,...t){const r=t.filter(e=>!!e),s="number"==typeof e&&e>0;if(!r.length&&!s)return{signal:void 0,dispose:()=>{},timedOut:()=>!1};const n=new AbortController;let o=!1;const i=[];for(const e of r){if(e.aborted){n.abort(e.reason);break}const t=()=>n.abort(e.reason);e.addEventListener("abort",t,{once:!0}),i.push(()=>e.removeEventListener("abort",t))}if(s&&!n.signal.aborted){const t=setTimeout(()=>{o=!0,n.abort(new Error(`MCP request timed out after ${e}ms`))},e);t?.unref?.(),i.push(()=>clearTimeout(t))}return{signal:n.signal,dispose:()=>{for(const e of i)e()},timedOut:()=>o}}function fe(e){try{const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("not http(s)");return e}catch{throw f("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${e}`)}}function pe(e,t){const r=t.timeoutMs??3e4,s=(t.maxEvents,!1!==t.redactSecrets),n=!0===t.serialize,o=function(e,t,r,s=1e3){return new ie(e,t,r,s)}("mcp",t.transport??"http",`mcp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,t.maxEvents??1e3);let a="idle";const c=()=>a,u=e=>{a=e,o.setState(e)};let l,d,p,h,y,g;const v=new Promise(e=>{g=e}),b=new Set;function w(e){const t=s?le(e.parsed):e.parsed;o.emit({direction:e.direction,kind:e.event,at:e.at,state:c(),data:e.data,meta:void 0!==t?{parsed:t}:void 0})}function M(e){const t=c();if("open"!==t){if("idle"===t||"connecting"===t)throw f("MCP_NOT_OPEN",`Call open() before ${e}; session is "${t}".`);throw f("MCP_SESSION_CLOSED",`Cannot ${e} on a ${t} session.`)}}async function P(e){const t=e.then(()=>{},()=>{});b.add(t);try{return await e}finally{b.delete(t)}}async function C(s,n,o){const i=n?.timeoutMs??r,a=de(i,t.signal,n?.signal);try{n?.delayMs&&await(c=n.delayMs,p=a.signal,c>0?new Promise((e,t)=>{const r=()=>{clearTimeout(s),t(f("MCP_ABORTED","Aborted while waiting to send."))},s=setTimeout(()=>{p?.removeEventListener("abort",r),e()},c);if(p?.aborted)return r();p?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),w({direction:"out",at:Date.now(),event:o,parsed:s});const r={signal:a.signal,timeoutMs:i,startedAt:Date.now(),protocolVersion:d,sessionId:l,headers:{...t.headers??{},...l?{"Mcp-Session-Id":l}:{}}},m="notification"===o?await e.notify(s,r):await e.call(s,r);if(m.sessionId&&m.sessionId!==l&&(l=m.sessionId,w({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{sessionIdChanged:l}})),w({direction:"in",at:Date.now(),event:o,parsed:m.message??{status:m.status,statusText:m.statusText,empty:!0}}),404===m.status&&l)throw u("closed"),g(),f("MCP_SESSION_EXPIRED",`Server no longer recognises session ${l} (HTTP 404).`);return m}catch(e){const t=m(e);if(w({direction:"meta",at:Date.now(),event:"error",parsed:t}),a.timedOut())throw f("MCP_TIMEOUT",`${String(s.method)} timed out after ${i}ms`,t);throw e}finally{a.dispose()}var c,p}async function S(e,t,r){if("string"!=typeof e||!e)throw f("BAD_MCP_METHOD","request() requires a non-empty method name.");M(`request("${e}")`);const s={jsonrpc:"2.0",id:N(),method:e,...void 0===t?{}:{params:t}},n=await P(C(s,r,"jsonrpc"));if(r?.raw)return n;if(L(n.message))throw f("MCP_RPC_ERROR",`${e} failed (${n.message.error.code}): ${n.message.error.message}`,n.message.error);if(void 0===n.message)throw f("MCP_EMPTY_RESPONSE",`${e} returned no JSON-RPC message (HTTP ${n.status} ${n.statusText}).`);return n.message.result}async function _(e,t){const r=ue[e],s=[],n=new Set;let o,i=0;for(;;){const a=await S(e,o?{cursor:o}:{},t);i+=1,Array.isArray(a?.[r])&&s.push(...a[r]);const c="string"==typeof a?.nextCursor?a.nextCursor:void 0;if(!c)break;if(n.has(c)||i>=1e3){w({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{warning:`${e} pagination stopped (repeated or excessive cursors)`}});break}n.add(c),o=c}return{items:s,pages:i}}async function A(){if("closed"!==c()){if("closing"===c())return y;if("idle"===c())return u("closed"),g(),void await e.dispose();if("connecting"!==c()||(await(h?.catch(()=>{})),"closed"!==c()))return u("closing"),y=(async()=>{if(await Promise.allSettled([...b]),l){const s=de(r);try{const r=await e.terminate({sessionId:l,protocolVersion:d,signal:s.signal,headers:t.headers});w({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{terminate:r.status,outcome:r.outcome,...r.reason?{reason:r.reason}:{}}})}catch(e){w({direction:"meta",at:Date.now(),event:"error",parsed:{terminate:"failed",reason:m(e).message}})}finally{s.dispose()}}await e.dispose(),u("closed"),g(),y=void 0})(),y}}t.signal&&(t.signal.aborted?(u("closed"),g()):t.signal.addEventListener("abort",()=>{A().catch(()=>{})},{once:!0}));const I={get protocol(){return"mcp"},get state(){return c()},get events(){return o.events},onEvent:e=>o.onEvent(e),get sessionId(){return l},get protocolVersion(){return d},get serverInfo(){return p},open:async function(){const s=c();if("open"===s)return;if("connecting"===s)return h;if("closing"===s||"closed"===s)throw f("MCP_SESSION_CLOSED","This session has been closed; create a new one.");u("connecting");const n=de(r,t.signal);return h=(async()=>{try{const r=await e.open({clientInfo:t.clientInfo,capabilities:t.capabilities,signal:n.signal});l=r.sessionId,d=r.protocolVersion??d??void 0,p=r.serverInfo,u("open"),w({direction:"in",at:Date.now(),event:"session",parsed:{sessionId:l,protocolVersion:d,serverInfo:p}})}catch(e){u("closed"),g();const t=m(e);if(w({direction:"meta",at:Date.now(),event:"error",parsed:t}),n.timedOut())throw f("MCP_TIMEOUT",`initialize timed out after ${r}ms`,t);throw e}finally{n.dispose(),h=void 0}})(),h},request:S,send:async function(e,t){M("send()");const r=i(e)?e:"string"==typeof e?{method:e}:void 0;if(!r||"string"!=typeof r.method||!r.method)throw f("BAD_MCP_MESSAGE","send() expects a method name or an object with a string `method`.");const s=r.method.startsWith("notifications/");return P(C({jsonrpc:"2.0",...r,...void 0!==r.id?{id:r.id}:s?{}:{id:N()}},t,s?"notification":"jsonrpc"))},notify:async function(e,t,r){if("string"!=typeof e||!e)throw f("BAD_MCP_METHOD","notify() requires a non-empty method name.");M(`notify("${e}")`);const s={jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}};await P(C(s,r,"notification"))},ping:e=>S("ping",{},e).then(()=>{}),listTools:e=>_("tools/list",e),listPrompts:e=>_("prompts/list",e),listResources:e=>_("resources/list",e),listResourceTemplates:e=>_("resources/templates/list",e),async listSources(e){const t=await(async()=>{if(n){const t=[];for(const r of["resources/list","resources/templates/list"])try{t.push({status:"fulfilled",value:await _(r,e)})}catch(e){t.push({status:"rejected",reason:e})}return t}return Promise.allSettled([_("resources/list",e),_("resources/templates/list",e)])})();if(t.every(e=>"rejected"===e.status))throw t[0].reason;const r=[];let s=0;for(const e of t)"fulfilled"===e.status&&(r.push(...e.value.items),s+=e.value.pages);return{items:r,pages:s}},callTool(e,t,r){if(e&&"object"==typeof e){const t=e;if(!t.name)throw f("BAD_MCP_TARGET","callTool() requires a tool name.");return S("tools/call",{name:t.name,arguments:t.arguments??{}},t.opts??r)}const s=e;if(!s)throw f("BAD_MCP_TARGET","callTool() requires a tool name.");return S("tools/call",{name:s,arguments:t??{}},r)},getPrompt(e,t,r){if(!e)throw f("BAD_MCP_TARGET","getPrompt() requires a prompt name.");return S("prompts/get",{name:e,arguments:t??{}},r)},readResource(e,t){if(!e)throw f("BAD_MCP_TARGET","readResource() requires a uri.");return S("resources/read",{uri:e},t)},close:A,waitForClose:()=>v};return I[Symbol.asyncDispose]=()=>A(),I}function me(e){if(!e||"object"!=typeof e)throw f("BAD_MCP_ENDPOINT","MCP session options are required.");const t=function(e){if("stdio"===(e.transport??"streamable-http")){if(!e.command||!String(e.command).trim())throw f("BAD_MCP_STDIO_COMMAND","MCP stdio sessions require a non-empty `command`.");return ce({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes})}if(!e.endpoint)throw f("BAD_MCP_ENDPOINT",'MCP http sessions require an `endpoint` (or set transport: "stdio" with a `command`).');return ae({endpoint:fe(e.endpoint),headers:e.headers})}(e);return pe(t,e)}function he(e){return me({...e,transport:"stdio"})}var ye=class{name="mcp";supports(e){const t=e.located.operation??{};return"mcp"===t["x-protocol"]?20:i(t["x-mcp"])||e.options.mcp?.method||e.options.mcp?.endpoint?15:"mcp"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=E(e.located,e.spec,e.options),r=[{key:"mcpEndpoint",value:t.endpoint,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"mcpEndpoint"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:u(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-mcp-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} MCP Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return X(e.config,t,r)}};export{V as MCP_PROTOCOL_VERSION,ye as McpAdapter,ae as createHttpMcpTransport,me as createMcpManualSession,pe as createMcpSessionCore,H as createMcpStdioConnection,he as createMcpStdioSession,ce as createStdioMcpTransport,se as discoverAndWriteMcpCapabilities,J as discoverMcpCapabilities,Y as generateAllMcpCalls,Q as generateMcpCall,U as initializeSession,me as mcpManualSession,E as resolveMcpConfig,X as runMcp,me as runMcpManualSession,re as writeMcpOperations};
@@ -0,0 +1 @@
1
+ "use strict";var e,t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,i=Object.prototype.hasOwnProperty,a=(e,t,s,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))i.call(e,c)||c===s||r(e,c,{get:()=>t[c],enumerable:!(a=n(t,c))||a.enumerable});return e},c=(e,n,o)=>(o=null!=e?t(s(e)):{},a(!n&&e&&e.__esModule?o:r(o,"default",{value:e,enumerable:!0}),e)),u={};function l(e,t){const r=f(e);return r&&-1!==r.indexOf("{{")&&t?r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>{if(!Object.prototype.hasOwnProperty.call(t,r))return e;const n=t[r];return null==n?e:f(n)}):r}function f(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function d(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function p(e){if(e)try{clearTimeout(e)}catch{}return null}function y(e,t){if(!e)return;if(t&&!/json/i.test(t))return;const r=e.trim();if(r&&/^[[{"\-\d]|^(true|false|null)$/.test(r))try{return JSON.parse(r)}catch{return}}((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(u,{WebSocketAdapter:()=>J,createWsManualSession:()=>z,resolveWsConfig:()=>B,runWebSocket:()=>N,runWebSocketSession:()=>z,wsManualSession:()=>z}),module.exports=(e=u,a(r({},"__esModule",{value:!0}),e));var m=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function g(e){return m.test(e)}var b=Symbol.for("@powerduck/openapi-request.ProtoKitError"),h=class e extends Error{code;details;[b]=!0;constructor(t,r,n,o){if(super(t),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=n,o&&"cause"in o)try{Object.defineProperty(this,"cause",{value:o.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,e.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isProtoKitError(e){return"object"==typeof e&&null!==e&&!0===e[b]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function v(e,t,r,n){return new h(t,e,r,n)}function w(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function S(e){if(h.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:w(e)}}var k="\0PK_OPEN\0",A="\0PK_CLOSE\0";function E(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return x(O(r),"options.serverUrl");const n=Array.isArray(e)?e.filter(d):[],o=n[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??n[0];let s=o&&"string"==typeof o.url&&o.url.trim()?o.url.trim():"";if(!s)throw v("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return s=function(e,t,r){const n=d(t)?t:{};let o=e;for(const[e,t]of Object.entries(n)){const n=r?.[e];let s;if(null!=n){if(s=n,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(n)))throw v("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:n,allowed:t.enum})}else if(void 0!==t?.default)s=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw v("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);s=t.enum[0]}o=o.split(`{${e}}`).join(String(s??""))}for(const[e,t]of Object.entries(r??{}))Object.prototype.hasOwnProperty.call(n,e)||null!=t&&(o=o.split(`{${e}}`).join(String(t)));return o}(s,o?.variables,t.serverVariables),x(O(s),"spec.servers")}function O(e){return e.replace(/\/+$/,"")||e}function x(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(k).split("}}").join(A).replace(/\{[^{}]*\}/g,"").split(k).join("{{").split(A).join("}}")}(e);if(!r)throw v("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw v("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}var M=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function $(e){const t=Array.isArray(e)?e:null==e?[]:[e],r=[];for(const e of t){if(null==e)continue;const t=String(e).trim();if(t){if(!M.test(t))throw v("BAD_WS_OPTIONS",`Invalid WebSocket subprotocol ${JSON.stringify(t)}: must be an HTTP token`);r.includes(t)||r.push(t)}}return r}function B(e,t,r){const n=r.websocket??{},o=e.operation?.["x-websocket"],s=o&&"object"==typeof o?o:{},i={...r.variables??{}};let a;if(n.url)a=String(n.url);else if("string"==typeof s.url&&s.url)a=s.url;else{const t=function(e){return/^wss?:\/\//i.test(e)?e:/^https:\/\//i.test(e)?e.replace(/^https:/i,"wss:"):/^http:\/\//i.test(e)?e.replace(/^http:/i,"ws:"):`wss://${e.replace(/^\/+/,"")}`}(E(e.servers,r)),n=e.path.replace(/\{([^}]+)\}/g,(e,t)=>{const n=r.values?.path?.[t];return null==n?e:encodeURIComponent(String(n))});a=`${t.replace(/\/+$/,"")}/${n.replace(/^\//,"")}`}a=l(a,i);const c=a.match(/\{\{([^}]+)\}\}/);if(c)throw v("BAD_WS_URL",`Unresolved variable {{${c[1]}}} in WebSocket URL: ${a}`);let u;try{u=new URL(a)}catch{throw v("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${a}`)}if("ws:"!==u.protocol&&"wss:"!==u.protocol)throw v("BAD_WS_URL",`WebSocket URL must use ws: or wss:, received ${u.protocol}${a}`);for(const[e,t]of Object.entries(r.values?.query??{}))if(null!=t)if(Array.isArray(t)){u.searchParams.delete(e);for(const r of t)null!=r&&u.searchParams.append(e,String(r))}else u.searchParams.set(e,String(t));"apikey"===r.auth?.type&&"query"===r.auth.in&&u.searchParams.set(r.auth.key??"api_key",r.auth.value??""),a=u.toString();const f={},d=e=>{if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(f[t]=l(String(r),i))};d(r.values?.header),d(s.headers),d(n.headers);const p=r.auth;if(p&&"none"!==p.type&&!Object.keys(f).some(e=>"authorization"===e.toLowerCase()))if("bearer"===p.type)f.Authorization=`Bearer ${p.token??""}`;else if("basic"===p.type){const e=`${p.username??""}:${p.password??""}`;f.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===p.type&&"header"===(p.in??"header")&&(f[p.key??"X-API-Key"]=p.value??"");for(const e of["sec-websocket-key","sec-websocket-version","sec-websocket-extensions","sec-websocket-protocol","upgrade","connection"])for(const t of Object.keys(f))t.toLowerCase()===e&&delete f[t];const y=n.send??s.send??[],m=(Array.isArray(y)?y:[y]).map(e=>function(e,t){if(null==e)return null;if("string"==typeof e)return l(e,t);if(e instanceof Uint8Array)return e;if(Buffer.isBuffer(e))return new Uint8Array(e);try{return l(JSON.stringify(e),t)}catch{return null}}(e,i)).filter(e=>null!==e),g=n.keepAlive??s.keepAlive;return{url:a,subprotocols:$(n.subprotocols??s.subprotocols),headers:f,send:m,sendDelayMs:P(n.sendDelayMs,0,"websocket.sendDelayMs"),idleTimeoutMs:P(n.idleTimeoutMs,0,"websocket.idleTimeoutMs"),maxMessages:j(n.maxMessages??r.maxEvents,100,"websocket.maxMessages"),maxSessionMs:j(n.maxSessionMs??r.maxStreamMs,3e4,"websocket.maxSessionMs"),keepAlive:g?{intervalMs:j(g.intervalMs,15e3,"websocket.keepAlive.intervalMs"),payload:String(g.payload??"ping")}:void 0,closeCode:_(n.closeCode),closeReason:String(n.closeReason??"Client finished sampling"),closeTimeoutMs:j(n.closeTimeoutMs,3e3,"websocket.closeTimeoutMs"),rejectUnauthorized:!1!==n.rejectUnauthorized,maxPayloadBytes:j(n.maxPayloadBytes,262144,"websocket.maxPayloadBytes"),clientOptions:n.clientOptions&&"object"==typeof n.clientOptions?{...n.clientOptions}:{}}}function P(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<0)throw v("BAD_WS_OPTIONS",`${r} must be a non-negative finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function j(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<=0)throw v("BAD_WS_OPTIONS",`${r} must be a positive finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function _(e){if(null==e)return 1e3;const t=Number(e);if(1e3===t||Number.isInteger(t)&&t>=3e3&&t<=4999)return t;throw v("BAD_WS_OPTIONS",`websocket.closeCode must be 1000 or within 3000-4999, received ${JSON.stringify(e)}`)}var T=c(require("ws"),1),U=new Set([1e3,1001,1005]);function N(e,t,r){const n=function(){let e,t,r=!1;const n=new Promise((r,n)=>{e=r,t=n});return n.catch(()=>{}),{promise:n,get settled(){return r},resolve:t=>!r&&(r=!0,e(t),!0),reject:e=>!r&&(r=!0,t(e),!0)}}(),o=Date.now();let s,i,a,c="connecting",u=0,l=0,f=0,d=!1,y=0,m=!1,g=!1;const b=[],h={};let v,w,k=0,A=null,E=null,O=null,x=null;const M=[];let $=null,B=!1;const P=e=>(e&&"function"==typeof e.unref&&e.unref(),e),j=t=>{const r=Date.now(),n=!t&&k>0&&k<400,a={...h};var c,u;return v&&(c=a,u="sec-websocket-protocol",!Object.keys(c).some(e=>e.toLowerCase()===u))&&(a["sec-websocket-protocol"]=v),{protocol:"websocket",request:{method:"GET",url:e.url,headers:{...e.headers,Upgrade:"websocket",Connection:"Upgrade",...e.subprotocols.length?{"Sec-WebSocket-Protocol":e.subprotocols.join(", ")}:{}},body:e.send.length?e.send.map(e=>"string"==typeof e?e:`<binary ${e.byteLength} bytes>`):void 0},response:{status:k||(t?0:101),statusText:t?"WebSocket error":n?"Switching Protocols":"Connection closed",headers:a,contentType:m&&!g?"application/octet-stream":"application/json",events:b,timings:{startedAt:o,endedAt:r,durationMs:r-o,firstByteMs:s?s-o:void 0},sizeBytes:f,...d?{truncated:!0}:{},...i?{stopReason:i}:{},...y?{droppedEvents:y}:{}},...t?{error:t}:{}}},_=e=>{"finalized"!==c&&(c="finalized",(()=>{if(A=p(A),E=p(E),O=p(O),x){try{clearInterval(x)}catch{}x=null}for(const e of M.splice(0))p(e)})(),$?.(),$=null,n.resolve(j(e??w)))},N=(t,r)=>{if("closing"!==c&&"finalized"!==c){c="closing",i=t,d=!0;try{R&&R.readyState===T.default.OPEN?R.close(e.closeCode,D(Buffer.from(`${e.closeReason}: ${r}`,"utf8"),123)):R?.terminate?.()}catch{}O=P(setTimeout(()=>{try{R?.terminate?.()}catch{}_()},e.closeTimeoutMs))}};let R;try{R=new T.default(e.url,e.subprotocols,{headers:e.headers,handshakeTimeout:Math.max(1e3,Math.min(e.maxSessionMs,3e4)),rejectUnauthorized:e.rejectUnauthorized,maxPayload:Math.max(1048576,4*e.maxPayloadBytes),...e.clientOptions})}catch(e){return c="finalized",Promise.resolve(j(S(e)))}if(r?.signal??t.signal){const e=r?.signal??t.signal;if(e.aborted)N("aborted","signal already aborted");else{const t=()=>N("aborted","caller aborted the session");e.addEventListener("abort",t,{once:!0}),$=()=>e.removeEventListener("abort",t)}}const W=()=>{e.idleTimeoutMs&&(E=p(E),E=P(setTimeout(()=>N("idleTimeout",`no data frame within ${e.idleTimeoutMs}ms`),e.idleTimeoutMs)))},L=e=>{b.push(e);try{t.onEvent?.(e)}catch{}},I=e=>{for(const[t,r]of Object.entries(e?.headers??{}))h[t]=Array.isArray(r)?r.join(", "):String(r)};return R.on("upgrade",e=>{k=e?.statusCode??101,I(e)}),R.on("unexpected-response",(e,t)=>{k=t?.statusCode??0,I(t),w={message:`Handshake rejected with HTTP ${k}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}try{R.terminate()}catch{}_(w)}),R.on("open",()=>{if("connecting"===c){c="open",s=Date.now(),v=R.protocol||void 0,k||(k=101);try{t.onOpen?.({url:e.url,protocol:v,headers:h})}catch{}if(e.send.forEach((t,r)=>{const n=()=>{"open"===c&&R.readyState===T.default.OPEN&&R.send(t,e=>{e?w=w??S(e):(l+=1,L({id:String(l),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?C(t):void 0,receivedAt:Date.now(),direction:"out"}))})},o=e.sendDelayMs*r;o<=0?n():M.push(P(setTimeout(n,o)))}),e.keepAlive){const{intervalMs:t,payload:r}=e.keepAlive;x=P(setInterval(()=>{if("open"===c&&R.readyState===T.default.OPEN)if(B)N("idleTimeout",`keep-alive ping unanswered for ${t}ms`);else try{R.ping(r),B=!0}catch{}},t))}W()}}),R.on("message",(t,r)=>{if("open"!==c)return;const n=function(e){if(Buffer.isBuffer(e))return e;if(Array.isArray(e))return Buffer.concat(e);try{return Buffer.from(e)}catch{return Buffer.alloc(0)}}(t);f+=n.length,l+=1,u+=1,r?m=!0:g=!0;const o=n.length>e.maxPayloadBytes;o&&(d=!0,y+=1);const s=r?`<binary ${n.length} bytes>`:o?`${D(n,e.maxPayloadBytes)}...`:n.toString("utf8");L({id:String(l),event:r?"binary":"text",data:s,parsed:r||o?void 0:C(s),receivedAt:Date.now(),direction:"in"}),W(),u>=e.maxMessages&&N("maxEvents",`maxMessages (${e.maxMessages}) reached`)}),R.on("ping",e=>{"finalized"!==c&&(l+=1,L({id:String(l),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}))}),R.on("pong",()=>{B=!1}),R.on("error",e=>{"closing"!==c&&"finalized"!==c&&(w=w??S(e),R.readyState===T.default.CLOSED&&_(w))}),R.on("close",(e,t)=>{a=e;const r=t?.length?t.toString("utf8"):"";w||("closing"===c||!!i)||U.has(e)||(w={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),1009===e&&(d=!0,y+=1),_(w)}),A=P(setTimeout(()=>N("maxSessionMs",`maxSessionMs (${e.maxSessionMs}ms) reached`),e.maxSessionMs)),n.promise}function D(e,t){if(e.length<=t)return e.toString("utf8");let r=t;for(;r>0&&128==(192&e[r]);)r-=1;return 0===r&&(r=t),e.subarray(0,r).toString("utf8")}function C(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}var R=c(require("ws"),1);function W(e,t=new WeakMap){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(void 0===e)return null;if("bigint"==typeof e)return e.toString();if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return String(e);if(e instanceof Date)return e.toISOString();if(e instanceof URL)return e.toString();if(e instanceof Error){const r={name:e.name,message:e.message,stack:e.stack},n=e.cause;return void 0!==n&&(r.cause=W(n,t)),r}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return{type:"Buffer",data:Array.from(e.values())};if(e instanceof Uint8Array)return{type:e.constructor.name,data:Array.from(e.values())};if(Array.isArray(e))return e.map(e=>W(e,t));if("object"==typeof e){const r=e;if(t.has(r))return t.get(r);const n={};t.set(r,n);for(const[e,o]of Object.entries(r))n[e]=W(o,t);return n}return String(e)}var L=class{constructor(e,t,r,n=1e3){this.protocol=e,this.transport=t,this.sessionId=r,this.maxEvents=n}protocol;transport;sessionId;maxEvents;state="idle";events=[];listeners=new Set;setState(e){this.state=e}emit(e){const t={protocol:this.protocol,transport:this.transport,sessionId:this.sessionId,at:e.at??Date.now(),direction:e.direction,kind:e.kind,state:e.state,data:W(e.data),error:W(e.error),meta:W(e.meta)};this.events.push(t),this.maxEvents>0&&this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);for(const e of this.listeners)try{e(t)}catch{}}onEvent(e){return this.listeners.add(e),{unsubscribe:()=>{this.listeners.delete(e)}}}},I=class extends L{async open(){}async close(){}async waitForClose(){}async send(){}};function z(e){let t="idle";function r(e){t=e,n.setState(e)}const n=function(e,t,r,n=1e3){return new I(e,t,r,n)}("websocket","websocket",`ws_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,"number"==typeof e.maxEvents&&e.maxEvents>=0?Math.floor(e.maxEvents):1e3),o="number"==typeof e.openTimeoutMs&&e.openTimeoutMs>0?Math.floor(e.openTimeoutMs):15e3;let s=null,i=()=>{},a=c();function c(){return new Promise(e=>{i=e})}function u(e){const{direction:t,receivedAt:r,event:o,data:s,parsed:i,code:a,reason:c,wasClean:u,protocol:l,extensions:f,statusCode:d,statusMessage:p,headers:y,error:m}=e,g={};void 0!==i&&(g.parsed=i),void 0!==a&&(g.code=a),void 0!==c&&(g.reason=c),void 0!==u&&(g.wasClean=u),void 0!==l&&(g.protocol=l),void 0!==f&&(g.extensions=f),void 0!==d&&(g.statusCode=d),void 0!==p&&(g.statusMessage=p),void 0!==y&&(g.headers=y),n.emit({direction:t,kind:o,at:r,state:n.state,data:s,meta:Object.keys(g).length?g:void 0,error:m})}function l(){if(!s||"open"!==t||s.readyState!==R.default.OPEN)throw new Error("WebSocket session is not open");return s}function f(e){const t=(r=e)instanceof Error?r.message:String(r);var r;u({direction:"meta",receivedAt:Date.now(),event:"error",data:t,error:t})}return{get protocol(){return"websocket"},get state(){return t},get events(){return n.events},onEvent:e=>n.onEvent(e),async open(){if("idle"!==t&&"closed"!==t&&"error"!==t)throw new Error(`WebSocket session cannot open from state "${t}"`);if(e.signal?.aborted)throw r("closed"),new Error("WebSocket open aborted");if(!e.url?.trim())throw new Error("WebSocket URL is required");a=c(),r("connecting"),await new Promise((n,a)=>{const c={headers:e.headers};void 0!==e.rejectUnauthorized&&(c.rejectUnauthorized=e.rejectUnauthorized);const l=e.subprotocols?.filter(Boolean)??[],d=l.length>0?new R.default(e.url,l,c):new R.default(e.url,c);s=d;let p,m,g=!1,b=!1;const h=()=>{p&&(clearTimeout(p),p=void 0),m?.(),m=void 0},v=e=>{g||(g=!0,h(),a(e))};if(p=setTimeout(()=>{const e=new Error(`WebSocket handshake timed out after ${o}ms`);r("error"),f(e),v(e);try{d.terminate()}catch{}},o),"function"==typeof p?.unref&&p.unref(),e.signal){const t=()=>{const e=new Error("WebSocket open aborted");r("closed"),f(e),v(e);try{d.terminate()}catch{}i()};if(e.signal.aborted)return void t();e.signal.addEventListener("abort",t,{once:!0}),m=()=>e.signal?.removeEventListener("abort",t)}d.once("upgrade",e=>{u({direction:"meta",receivedAt:Date.now(),event:"upgrade",statusCode:e.statusCode,statusMessage:e.statusMessage,headers:e.headers})}),d.once("unexpected-response",(e,t)=>{b=!0,u({direction:"meta",receivedAt:Date.now(),event:"unexpected-response",statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers}),t.resume();const n=[t.statusCode,t.statusMessage].filter(e=>void 0!==e&&""!==e).join(" "),o=new Error("WebSocket handshake failed"+(n?`: ${n}`:""));r("error"),f(o),v(o),d.readyState!==R.default.CONNECTING&&d.readyState!==R.default.OPEN||d.terminate()}),d.once("open",()=>{r("open"),u({direction:"meta",receivedAt:Date.now(),event:"open",statusCode:101,statusMessage:"Switching Protocols",protocol:d.protocol||void 0,extensions:d.extensions||void 0}),g||(g=!0,h(),n())}),d.on("message",(e,t)=>{if(t){const t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):(ArrayBuffer,Buffer.from(e));return void u({direction:"in",receivedAt:Date.now(),event:"binary",data:t.toString("base64")})}const r=Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):(ArrayBuffer,Buffer.from(e).toString("utf8"));u({direction:"in",receivedAt:Date.now(),event:"text",data:r,parsed:y(r)})}),d.on("error",e=>{r("error"),f(e),v(e)}),d.once("close",(e,n)=>{const o=n.toString("utf8"),s=1e3===e;"error"!==t&&r("closed"),u({direction:"meta",receivedAt:Date.now(),event:"close",code:e,reason:o,wasClean:s}),i(),g||b||v(new Error(`WebSocket closed before opening: ${e}${o?` ${o}`:""}`))})})},async send(t,r={}){if(e.signal?.aborted)throw new Error("WebSocket send aborted");const n=l();var o,s;if(void 0!==r.delayMs&&r.delayMs>0&&await(o=r.delayMs,s=e.signal,o>0?new Promise((e,t)=>{const r=()=>{clearTimeout(n),t(new Error("Aborted while waiting."))},n=setTimeout(()=>{s?.removeEventListener("abort",r),e()},o);if(n?.unref?.(),s?.aborted)return r();s?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),e.signal?.aborted)throw new Error("WebSocket send aborted");let i,a,c,d;if(l(),r.binary||Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer){const e=function(e){if(Buffer.isBuffer(e))return e;if(e instanceof Uint8Array)return Buffer.from(e);if(e instanceof ArrayBuffer)return Buffer.from(e);if("string"==typeof e)return Buffer.from(e,"base64");throw new TypeError("Binary WebSocket data must be a Buffer, Uint8Array, ArrayBuffer, or base64 string")}(t);i=e,a="binary",c=e.toString("base64")}else if("string"==typeof t)i=t,a="text",c=t,d=y(t);else{const e=JSON.stringify(t);if(void 0===e)throw new TypeError("WebSocket payload cannot be serialized");i=e,a="text",c=e,d=t}await new Promise((e,t)=>{n.send(i,{binary:"binary"===a},r=>{if(r)return f(r),void t(r);u({direction:"out",receivedAt:Date.now(),event:a,data:c,parsed:d}),e()})})},async close(e={}){if(!s)return r("closed"),void i();if("closed"!==t){if("closing"!==t)return r("closing"),s.readyState===R.default.CONNECTING?(s.terminate(),void await a):s.readyState===R.default.OPEN?(s.close(e.code??1e3,e.reason??"Closed"),void await a):void(s.readyState!==R.default.CLOSING?(r("closed"),i()):await a);await a}else i()},async waitForClose(){await a}}}var J=class{name="websocket";supports(e){const t=e.located.operation??{};return"websocket"===t["x-protocol"]||"ws"===t["x-protocol"]?20:t["x-websocket"]&&"object"==typeof t["x-websocket"]||e.options.websocket?.url?15:"websocket"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=B(e.located,e.spec,e.options),r=[{key:"wsUrl",value:t.url,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"wsUrl"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:g(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-ws-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} WebSocket Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return N(e.config,t,r)}};
@@ -0,0 +1,35 @@
1
+ import { L as LocatedOperation, E as ExecuteContext, P as ProtocolAdapter, A as AdapterContext } from '../../protocol-Dh-wN2nY.cjs';
2
+ import { a as SendOptions, al as ResolvedWsConfig, E as ExecResult, k as CreateWsManualSessionOptions, aC as WsManualSession } from '../../types-C9ifzKqk.cjs';
3
+ export { az as WebSocketSessionEvent, aA as WebSocketSessionState, aD as WsSendOptions } from '../../types-C9ifzKqk.cjs';
4
+
5
+ /**
6
+ * Resolve the effective WebSocket configuration.
7
+ *
8
+ * Precedence: options.websocket.url > operation['x-websocket'].url > server URL + path.
9
+ */
10
+ declare function resolveWsConfig(located: LocatedOperation, spec: any, options: SendOptions): ResolvedWsConfig;
11
+
12
+ /**
13
+ * Open a WebSocket session, send the configured messages, and collect inbound
14
+ * frames until a sampling limit or a close event is reached.
15
+ *
16
+ * Lifecycle: connecting -> open -> closing -> finalized. Every exit path runs
17
+ * through `finalize()`, which is idempotent, so a close frame racing the close
18
+ * watchdog cannot produce two results.
19
+ */
20
+ declare function runWebSocket(config: ResolvedWsConfig, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
21
+
22
+ declare function createWsManualSession(options: CreateWsManualSessionOptions): WsManualSession;
23
+
24
+ interface WsPlan {
25
+ config: ResolvedWsConfig;
26
+ environment: Record<string, any>;
27
+ }
28
+ declare class WebSocketAdapter implements ProtocolAdapter<WsPlan> {
29
+ readonly name = "websocket";
30
+ supports(ctx: AdapterContext): number;
31
+ plan(ctx: AdapterContext): WsPlan;
32
+ execute(plan: WsPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
33
+ }
34
+
35
+ export { CreateWsManualSessionOptions, ResolvedWsConfig, WebSocketAdapter, WsManualSession, type WsPlan, createWsManualSession, resolveWsConfig, runWebSocket, createWsManualSession as runWebSocketSession, createWsManualSession as wsManualSession };
@@ -0,0 +1,35 @@
1
+ import { L as LocatedOperation, E as ExecuteContext, P as ProtocolAdapter, A as AdapterContext } from '../../protocol-D7sEx8IP.js';
2
+ import { a as SendOptions, al as ResolvedWsConfig, E as ExecResult, k as CreateWsManualSessionOptions, aC as WsManualSession } from '../../types-C9ifzKqk.js';
3
+ export { az as WebSocketSessionEvent, aA as WebSocketSessionState, aD as WsSendOptions } from '../../types-C9ifzKqk.js';
4
+
5
+ /**
6
+ * Resolve the effective WebSocket configuration.
7
+ *
8
+ * Precedence: options.websocket.url > operation['x-websocket'].url > server URL + path.
9
+ */
10
+ declare function resolveWsConfig(located: LocatedOperation, spec: any, options: SendOptions): ResolvedWsConfig;
11
+
12
+ /**
13
+ * Open a WebSocket session, send the configured messages, and collect inbound
14
+ * frames until a sampling limit or a close event is reached.
15
+ *
16
+ * Lifecycle: connecting -> open -> closing -> finalized. Every exit path runs
17
+ * through `finalize()`, which is idempotent, so a close frame racing the close
18
+ * watchdog cannot produce two results.
19
+ */
20
+ declare function runWebSocket(config: ResolvedWsConfig, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
21
+
22
+ declare function createWsManualSession(options: CreateWsManualSessionOptions): WsManualSession;
23
+
24
+ interface WsPlan {
25
+ config: ResolvedWsConfig;
26
+ environment: Record<string, any>;
27
+ }
28
+ declare class WebSocketAdapter implements ProtocolAdapter<WsPlan> {
29
+ readonly name = "websocket";
30
+ supports(ctx: AdapterContext): number;
31
+ plan(ctx: AdapterContext): WsPlan;
32
+ execute(plan: WsPlan, options: SendOptions, ctx?: ExecuteContext): Promise<ExecResult>;
33
+ }
34
+
35
+ export { CreateWsManualSessionOptions, ResolvedWsConfig, WebSocketAdapter, WsManualSession, type WsPlan, createWsManualSession, resolveWsConfig, runWebSocket, createWsManualSession as runWebSocketSession, createWsManualSession as wsManualSession };
@@ -0,0 +1 @@
1
+ function e(e,r){const n=t(e);return n&&-1!==n.indexOf("{{")&&r?n.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,n)=>{if(!Object.prototype.hasOwnProperty.call(r,n))return e;const o=r[n];return null==o?e:t(o)}):n}function t(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{try{return String(e)}catch{return""}}}function r(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function n(e){if(e)try{clearTimeout(e)}catch{}return null}function o(e,t){if(!e)return;if(t&&!/json/i.test(t))return;const r=e.trim();if(r&&/^[[{"\-\d]|^(true|false|null)$/.test(r))try{return JSON.parse(r)}catch{return}}var s=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function i(e){return s.test(e)}var a=Symbol.for("@powerduck/openapi-request.ProtoKitError"),c=class e extends Error{code;details;[a]=!0;constructor(t,r,n,o){if(super(t),this.name="ProtoKitError",this.code="string"==typeof r&&r?r:"UNKNOWN",this.details=n,o&&"cause"in o)try{Object.defineProperty(this,"cause",{value:o.cause,configurable:!0,writable:!0,enumerable:!1})}catch{}Object.setPrototypeOf(this,e.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,e)}static isProtoKitError(e){return"object"==typeof e&&null!==e&&!0===e[a]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function u(e,t,r,n){return new c(t,e,r,n)}function l(e){const t=typeof e;if(null===e)return"null";if("undefined"===t)return"undefined";if("function"===t){const t=e.name;return t?`[Function: ${t}]`:"[Function (anonymous)]"}if("symbol"===t)return String(e);if("bigint"===t)return`${String(e)}n`;try{const t=JSON.stringify(e);if("string"==typeof t)return t}catch{}try{return String(e)}catch{return"[unserializable value]"}}function f(e){if(c.isProtoKitError(e))return{message:e.message||"Unknown ProtoKitError",code:e.code,name:e.name};if(e instanceof Error){const t=e.code,r="string"==typeof t||"number"==typeof t?String(t):void 0;return{message:e.message||e.name||"Unknown error",...r?{code:r}:{},name:e.name||"Error"}}if("object"==typeof e&&null!==e&&"string"==typeof e.message){const t=e,r="string"==typeof t.code||"number"==typeof t.code?String(t.code):void 0;return{message:t.message||"Unknown error",...r?{code:r}:{},..."string"==typeof t.name?{name:t.name}:{}}}return"string"==typeof e?{message:e||"Unknown error"}:{message:l(e)}}var d="\0PK_OPEN\0",p="\0PK_CLOSE\0";function y(e,t){const n="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(n)return g(m(n),"options.serverUrl");const o=Array.isArray(e)?e.filter(r):[],s=o[Number.isInteger(t.serverIndex)?Math.max(0,t.serverIndex):0]??o[0];let i=s&&"string"==typeof s.url&&s.url.trim()?s.url.trim():"";if(!i)throw u("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return i=function(e,t,n){const o=r(t)?t:{};let s=e;for(const[e,t]of Object.entries(o)){const r=n?.[e];let o;if(null!=r){if(o=r,Array.isArray(t?.enum)&&t.enum.length&&!t.enum.some(e=>String(e)===String(r)))throw u("BAD_SERVER_VARIABLE",`Server variable "${e}" must be one of: ${t.enum.join(", ")}`,{provided:r,allowed:t.enum})}else if(void 0!==t?.default)o=t.default;else{if(!Array.isArray(t?.enum)||!t.enum.length)throw u("BAD_SERVER_VARIABLE",`Server variable "${e}" has no default; pass serverVariables["${e}"].`);o=t.enum[0]}s=s.split(`{${e}}`).join(String(o??""))}for(const[e,t]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(o,e)||null!=t&&(s=s.split(`{${e}}`).join(String(t)));return s}(i,s?.variables,t.serverVariables),g(m(i),"spec.servers")}function m(e){return e.replace(/\/+$/,"")||e}function g(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(d).split("}}").join(p).replace(/\{[^{}]*\}/g,"").split(d).join("{{").split(p).join("}}")}(e);if(!r)throw u("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw u("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}var h=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function b(e){const t=Array.isArray(e)?e:null==e?[]:[e],r=[];for(const e of t){if(null==e)continue;const t=String(e).trim();if(t){if(!h.test(t))throw u("BAD_WS_OPTIONS",`Invalid WebSocket subprotocol ${JSON.stringify(t)}: must be an HTTP token`);r.includes(t)||r.push(t)}}return r}function v(t,r,n){const o=n.websocket??{},s=t.operation?.["x-websocket"],i=s&&"object"==typeof s?s:{},a={...n.variables??{}};let c;if(o.url)c=String(o.url);else if("string"==typeof i.url&&i.url)c=i.url;else{const e=function(e){return/^wss?:\/\//i.test(e)?e:/^https:\/\//i.test(e)?e.replace(/^https:/i,"wss:"):/^http:\/\//i.test(e)?e.replace(/^http:/i,"ws:"):`wss://${e.replace(/^\/+/,"")}`}(y(t.servers,n)),r=t.path.replace(/\{([^}]+)\}/g,(e,t)=>{const r=n.values?.path?.[t];return null==r?e:encodeURIComponent(String(r))});c=`${e.replace(/\/+$/,"")}/${r.replace(/^\//,"")}`}c=e(c,a);const l=c.match(/\{\{([^}]+)\}\}/);if(l)throw u("BAD_WS_URL",`Unresolved variable {{${l[1]}}} in WebSocket URL: ${c}`);let f;try{f=new URL(c)}catch{throw u("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${c}`)}if("ws:"!==f.protocol&&"wss:"!==f.protocol)throw u("BAD_WS_URL",`WebSocket URL must use ws: or wss:, received ${f.protocol}${c}`);for(const[e,t]of Object.entries(n.values?.query??{}))if(null!=t)if(Array.isArray(t)){f.searchParams.delete(e);for(const r of t)null!=r&&f.searchParams.append(e,String(r))}else f.searchParams.set(e,String(t));"apikey"===n.auth?.type&&"query"===n.auth.in&&f.searchParams.set(n.auth.key??"api_key",n.auth.value??""),c=f.toString();const d={},p=t=>{if(t&&"object"==typeof t)for(const[r,n]of Object.entries(t))null!=n&&"__proto__"!==r&&"constructor"!==r&&(d[r]=e(String(n),a))};p(n.values?.header),p(i.headers),p(o.headers);const m=n.auth;if(m&&"none"!==m.type&&!Object.keys(d).some(e=>"authorization"===e.toLowerCase()))if("bearer"===m.type)d.Authorization=`Bearer ${m.token??""}`;else if("basic"===m.type){const e=`${m.username??""}:${m.password??""}`;d.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===m.type&&"header"===(m.in??"header")&&(d[m.key??"X-API-Key"]=m.value??"");for(const e of["sec-websocket-key","sec-websocket-version","sec-websocket-extensions","sec-websocket-protocol","upgrade","connection"])for(const t of Object.keys(d))t.toLowerCase()===e&&delete d[t];const g=o.send??i.send??[],h=(Array.isArray(g)?g:[g]).map(t=>function(t,r){if(null==t)return null;if("string"==typeof t)return e(t,r);if(t instanceof Uint8Array)return t;if(Buffer.isBuffer(t))return new Uint8Array(t);try{return e(JSON.stringify(t),r)}catch{return null}}(t,a)).filter(e=>null!==e),v=o.keepAlive??i.keepAlive;return{url:c,subprotocols:b(o.subprotocols??i.subprotocols),headers:d,send:h,sendDelayMs:w(o.sendDelayMs,0,"websocket.sendDelayMs"),idleTimeoutMs:w(o.idleTimeoutMs,0,"websocket.idleTimeoutMs"),maxMessages:S(o.maxMessages??n.maxEvents,100,"websocket.maxMessages"),maxSessionMs:S(o.maxSessionMs??n.maxStreamMs,3e4,"websocket.maxSessionMs"),keepAlive:v?{intervalMs:S(v.intervalMs,15e3,"websocket.keepAlive.intervalMs"),payload:String(v.payload??"ping")}:void 0,closeCode:k(o.closeCode),closeReason:String(o.closeReason??"Client finished sampling"),closeTimeoutMs:S(o.closeTimeoutMs,3e3,"websocket.closeTimeoutMs"),rejectUnauthorized:!1!==o.rejectUnauthorized,maxPayloadBytes:S(o.maxPayloadBytes,262144,"websocket.maxPayloadBytes"),clientOptions:o.clientOptions&&"object"==typeof o.clientOptions?{...o.clientOptions}:{}}}function w(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<0)throw u("BAD_WS_OPTIONS",`${r} must be a non-negative finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function S(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<=0)throw u("BAD_WS_OPTIONS",`${r} must be a positive finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function k(e){if(null==e)return 1e3;const t=Number(e);if(1e3===t||Number.isInteger(t)&&t>=3e3&&t<=4999)return t;throw u("BAD_WS_OPTIONS",`websocket.closeCode must be 1000 or within 3000-4999, received ${JSON.stringify(e)}`)}import A from"ws";var E=new Set([1e3,1001,1005]);function x(e,t,r){const o=function(){let e,t,r=!1;const n=new Promise((r,n)=>{e=r,t=n});return n.catch(()=>{}),{promise:n,get settled(){return r},resolve:t=>!r&&(r=!0,e(t),!0),reject:e=>!r&&(r=!0,t(e),!0)}}(),s=Date.now();let i,a,c,u="connecting",l=0,d=0,p=0,y=!1,m=0,g=!1,h=!1;const b=[],v={};let w,S,k=0,x=null,$=null,B=null,P=null;const j=[];let T=null,U=!1;const _=e=>(e&&"function"==typeof e.unref&&e.unref(),e),N=t=>{const r=Date.now(),n=!t&&k>0&&k<400,o={...v};var c,u;return w&&(c=o,u="sec-websocket-protocol",!Object.keys(c).some(e=>e.toLowerCase()===u))&&(o["sec-websocket-protocol"]=w),{protocol:"websocket",request:{method:"GET",url:e.url,headers:{...e.headers,Upgrade:"websocket",Connection:"Upgrade",...e.subprotocols.length?{"Sec-WebSocket-Protocol":e.subprotocols.join(", ")}:{}},body:e.send.length?e.send.map(e=>"string"==typeof e?e:`<binary ${e.byteLength} bytes>`):void 0},response:{status:k||(t?0:101),statusText:t?"WebSocket error":n?"Switching Protocols":"Connection closed",headers:o,contentType:g&&!h?"application/octet-stream":"application/json",events:b,timings:{startedAt:s,endedAt:r,durationMs:r-s,firstByteMs:i?i-s:void 0},sizeBytes:p,...y?{truncated:!0}:{},...a?{stopReason:a}:{},...m?{droppedEvents:m}:{}},...t?{error:t}:{}}},D=e=>{"finalized"!==u&&(u="finalized",(()=>{if(x=n(x),$=n($),B=n(B),P){try{clearInterval(P)}catch{}P=null}for(const e of j.splice(0))n(e)})(),T?.(),T=null,o.resolve(N(e??S)))},C=(t,r)=>{if("closing"!==u&&"finalized"!==u){u="closing",a=t,y=!0;try{R&&R.readyState===A.OPEN?R.close(e.closeCode,O(Buffer.from(`${e.closeReason}: ${r}`,"utf8"),123)):R?.terminate?.()}catch{}B=_(setTimeout(()=>{try{R?.terminate?.()}catch{}D()},e.closeTimeoutMs))}};let R;try{R=new A(e.url,e.subprotocols,{headers:e.headers,handshakeTimeout:Math.max(1e3,Math.min(e.maxSessionMs,3e4)),rejectUnauthorized:e.rejectUnauthorized,maxPayload:Math.max(1048576,4*e.maxPayloadBytes),...e.clientOptions})}catch(e){return u="finalized",Promise.resolve(N(f(e)))}if(r?.signal??t.signal){const e=r?.signal??t.signal;if(e.aborted)C("aborted","signal already aborted");else{const t=()=>C("aborted","caller aborted the session");e.addEventListener("abort",t,{once:!0}),T=()=>e.removeEventListener("abort",t)}}const L=()=>{e.idleTimeoutMs&&($=n($),$=_(setTimeout(()=>C("idleTimeout",`no data frame within ${e.idleTimeoutMs}ms`),e.idleTimeoutMs)))},W=e=>{b.push(e);try{t.onEvent?.(e)}catch{}},I=e=>{for(const[t,r]of Object.entries(e?.headers??{}))v[t]=Array.isArray(r)?r.join(", "):String(r)};return R.on("upgrade",e=>{k=e?.statusCode??101,I(e)}),R.on("unexpected-response",(e,t)=>{k=t?.statusCode??0,I(t),S={message:`Handshake rejected with HTTP ${k}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}try{R.terminate()}catch{}D(S)}),R.on("open",()=>{if("connecting"===u){u="open",i=Date.now(),w=R.protocol||void 0,k||(k=101);try{t.onOpen?.({url:e.url,protocol:w,headers:v})}catch{}if(e.send.forEach((t,r)=>{const n=()=>{"open"===u&&R.readyState===A.OPEN&&R.send(t,e=>{e?S=S??f(e):(d+=1,W({id:String(d),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?M(t):void 0,receivedAt:Date.now(),direction:"out"}))})},o=e.sendDelayMs*r;o<=0?n():j.push(_(setTimeout(n,o)))}),e.keepAlive){const{intervalMs:t,payload:r}=e.keepAlive;P=_(setInterval(()=>{if("open"===u&&R.readyState===A.OPEN)if(U)C("idleTimeout",`keep-alive ping unanswered for ${t}ms`);else try{R.ping(r),U=!0}catch{}},t))}L()}}),R.on("message",(t,r)=>{if("open"!==u)return;const n=function(e){if(Buffer.isBuffer(e))return e;if(Array.isArray(e))return Buffer.concat(e);try{return Buffer.from(e)}catch{return Buffer.alloc(0)}}(t);p+=n.length,d+=1,l+=1,r?g=!0:h=!0;const o=n.length>e.maxPayloadBytes;o&&(y=!0,m+=1);const s=r?`<binary ${n.length} bytes>`:o?`${O(n,e.maxPayloadBytes)}...`:n.toString("utf8");W({id:String(d),event:r?"binary":"text",data:s,parsed:r||o?void 0:M(s),receivedAt:Date.now(),direction:"in"}),L(),l>=e.maxMessages&&C("maxEvents",`maxMessages (${e.maxMessages}) reached`)}),R.on("ping",e=>{"finalized"!==u&&(d+=1,W({id:String(d),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}))}),R.on("pong",()=>{U=!1}),R.on("error",e=>{"closing"!==u&&"finalized"!==u&&(S=S??f(e),R.readyState===A.CLOSED&&D(S))}),R.on("close",(e,t)=>{c=e;const r=t?.length?t.toString("utf8"):"";S||("closing"===u||!!a)||E.has(e)||(S={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),1009===e&&(y=!0,m+=1),D(S)}),x=_(setTimeout(()=>C("maxSessionMs",`maxSessionMs (${e.maxSessionMs}ms) reached`),e.maxSessionMs)),o.promise}function O(e,t){if(e.length<=t)return e.toString("utf8");let r=t;for(;r>0&&128==(192&e[r]);)r-=1;return 0===r&&(r=t),e.subarray(0,r).toString("utf8")}function M(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}import $ from"ws";function B(e,t=new WeakMap){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(void 0===e)return null;if("bigint"==typeof e)return e.toString();if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return String(e);if(e instanceof Date)return e.toISOString();if(e instanceof URL)return e.toString();if(e instanceof Error){const r={name:e.name,message:e.message,stack:e.stack},n=e.cause;return void 0!==n&&(r.cause=B(n,t)),r}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return{type:"Buffer",data:Array.from(e.values())};if(e instanceof Uint8Array)return{type:e.constructor.name,data:Array.from(e.values())};if(Array.isArray(e))return e.map(e=>B(e,t));if("object"==typeof e){const r=e;if(t.has(r))return t.get(r);const n={};t.set(r,n);for(const[e,o]of Object.entries(r))n[e]=B(o,t);return n}return String(e)}var P=class{constructor(e,t,r,n=1e3){this.protocol=e,this.transport=t,this.sessionId=r,this.maxEvents=n}protocol;transport;sessionId;maxEvents;state="idle";events=[];listeners=new Set;setState(e){this.state=e}emit(e){const t={protocol:this.protocol,transport:this.transport,sessionId:this.sessionId,at:e.at??Date.now(),direction:e.direction,kind:e.kind,state:e.state,data:B(e.data),error:B(e.error),meta:B(e.meta)};this.events.push(t),this.maxEvents>0&&this.events.length>this.maxEvents&&this.events.splice(0,this.events.length-this.maxEvents);for(const e of this.listeners)try{e(t)}catch{}}onEvent(e){return this.listeners.add(e),{unsubscribe:()=>{this.listeners.delete(e)}}}},j=class extends P{async open(){}async close(){}async waitForClose(){}async send(){}};function T(e){let t="idle";function r(e){t=e,n.setState(e)}const n=function(e,t,r,n=1e3){return new j(e,t,r,n)}("websocket","websocket",`ws_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,"number"==typeof e.maxEvents&&e.maxEvents>=0?Math.floor(e.maxEvents):1e3),s="number"==typeof e.openTimeoutMs&&e.openTimeoutMs>0?Math.floor(e.openTimeoutMs):15e3;let i=null,a=()=>{},c=u();function u(){return new Promise(e=>{a=e})}function l(e){const{direction:t,receivedAt:r,event:o,data:s,parsed:i,code:a,reason:c,wasClean:u,protocol:l,extensions:f,statusCode:d,statusMessage:p,headers:y,error:m}=e,g={};void 0!==i&&(g.parsed=i),void 0!==a&&(g.code=a),void 0!==c&&(g.reason=c),void 0!==u&&(g.wasClean=u),void 0!==l&&(g.protocol=l),void 0!==f&&(g.extensions=f),void 0!==d&&(g.statusCode=d),void 0!==p&&(g.statusMessage=p),void 0!==y&&(g.headers=y),n.emit({direction:t,kind:o,at:r,state:n.state,data:s,meta:Object.keys(g).length?g:void 0,error:m})}function f(){if(!i||"open"!==t||i.readyState!==$.OPEN)throw new Error("WebSocket session is not open");return i}function d(e){const t=(r=e)instanceof Error?r.message:String(r);var r;l({direction:"meta",receivedAt:Date.now(),event:"error",data:t,error:t})}return{get protocol(){return"websocket"},get state(){return t},get events(){return n.events},onEvent:e=>n.onEvent(e),async open(){if("idle"!==t&&"closed"!==t&&"error"!==t)throw new Error(`WebSocket session cannot open from state "${t}"`);if(e.signal?.aborted)throw r("closed"),new Error("WebSocket open aborted");if(!e.url?.trim())throw new Error("WebSocket URL is required");c=u(),r("connecting"),await new Promise((n,c)=>{const u={headers:e.headers};void 0!==e.rejectUnauthorized&&(u.rejectUnauthorized=e.rejectUnauthorized);const f=e.subprotocols?.filter(Boolean)??[],p=f.length>0?new $(e.url,f,u):new $(e.url,u);i=p;let y,m,g=!1,h=!1;const b=()=>{y&&(clearTimeout(y),y=void 0),m?.(),m=void 0},v=e=>{g||(g=!0,b(),c(e))};if(y=setTimeout(()=>{const e=new Error(`WebSocket handshake timed out after ${s}ms`);r("error"),d(e),v(e);try{p.terminate()}catch{}},s),"function"==typeof y?.unref&&y.unref(),e.signal){const t=()=>{const e=new Error("WebSocket open aborted");r("closed"),d(e),v(e);try{p.terminate()}catch{}a()};if(e.signal.aborted)return void t();e.signal.addEventListener("abort",t,{once:!0}),m=()=>e.signal?.removeEventListener("abort",t)}p.once("upgrade",e=>{l({direction:"meta",receivedAt:Date.now(),event:"upgrade",statusCode:e.statusCode,statusMessage:e.statusMessage,headers:e.headers})}),p.once("unexpected-response",(e,t)=>{h=!0,l({direction:"meta",receivedAt:Date.now(),event:"unexpected-response",statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers}),t.resume();const n=[t.statusCode,t.statusMessage].filter(e=>void 0!==e&&""!==e).join(" "),o=new Error("WebSocket handshake failed"+(n?`: ${n}`:""));r("error"),d(o),v(o),p.readyState!==$.CONNECTING&&p.readyState!==$.OPEN||p.terminate()}),p.once("open",()=>{r("open"),l({direction:"meta",receivedAt:Date.now(),event:"open",statusCode:101,statusMessage:"Switching Protocols",protocol:p.protocol||void 0,extensions:p.extensions||void 0}),g||(g=!0,b(),n())}),p.on("message",(e,t)=>{if(t){const t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):(ArrayBuffer,Buffer.from(e));return void l({direction:"in",receivedAt:Date.now(),event:"binary",data:t.toString("base64")})}const r=Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):(ArrayBuffer,Buffer.from(e).toString("utf8"));l({direction:"in",receivedAt:Date.now(),event:"text",data:r,parsed:o(r)})}),p.on("error",e=>{r("error"),d(e),v(e)}),p.once("close",(e,n)=>{const o=n.toString("utf8"),s=1e3===e;"error"!==t&&r("closed"),l({direction:"meta",receivedAt:Date.now(),event:"close",code:e,reason:o,wasClean:s}),a(),g||h||v(new Error(`WebSocket closed before opening: ${e}${o?` ${o}`:""}`))})})},async send(t,r={}){if(e.signal?.aborted)throw new Error("WebSocket send aborted");const n=f();var s,i;if(void 0!==r.delayMs&&r.delayMs>0&&await(s=r.delayMs,i=e.signal,s>0?new Promise((e,t)=>{const r=()=>{clearTimeout(n),t(new Error("Aborted while waiting."))},n=setTimeout(()=>{i?.removeEventListener("abort",r),e()},s);if(n?.unref?.(),i?.aborted)return r();i?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),e.signal?.aborted)throw new Error("WebSocket send aborted");let a,c,u,p;if(f(),r.binary||Buffer.isBuffer(t)||t instanceof Uint8Array||t instanceof ArrayBuffer){const e=function(e){if(Buffer.isBuffer(e))return e;if(e instanceof Uint8Array)return Buffer.from(e);if(e instanceof ArrayBuffer)return Buffer.from(e);if("string"==typeof e)return Buffer.from(e,"base64");throw new TypeError("Binary WebSocket data must be a Buffer, Uint8Array, ArrayBuffer, or base64 string")}(t);a=e,c="binary",u=e.toString("base64")}else if("string"==typeof t)a=t,c="text",u=t,p=o(t);else{const e=JSON.stringify(t);if(void 0===e)throw new TypeError("WebSocket payload cannot be serialized");a=e,c="text",u=e,p=t}await new Promise((e,t)=>{n.send(a,{binary:"binary"===c},r=>{if(r)return d(r),void t(r);l({direction:"out",receivedAt:Date.now(),event:c,data:u,parsed:p}),e()})})},async close(e={}){if(!i)return r("closed"),void a();if("closed"!==t){if("closing"!==t)return r("closing"),i.readyState===$.CONNECTING?(i.terminate(),void await c):i.readyState===$.OPEN?(i.close(e.code??1e3,e.reason??"Closed"),void await c):void(i.readyState!==$.CLOSING?(r("closed"),a()):await c);await c}else a()},async waitForClose(){await c}}}var U=class{name="websocket";supports(e){const t=e.located.operation??{};return"websocket"===t["x-protocol"]||"ws"===t["x-protocol"]?20:t["x-websocket"]&&"object"==typeof t["x-websocket"]||e.options.websocket?.url?15:"websocket"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=v(e.located,e.spec,e.options),r=[{key:"wsUrl",value:t.url,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"wsUrl"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:i(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-ws-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} WebSocket Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return x(e.config,t,r)}};export{U as WebSocketAdapter,T as createWsManualSession,v as resolveWsConfig,x as runWebSocket,T as runWebSocketSession,T as wsManualSession};