@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.
- package/README.md +711 -0
- package/dist/credentials-Cl0G4KpE.d.cts +783 -0
- package/dist/credentials-rqEKODvf.d.ts +783 -0
- package/dist/index-1jRrFc3d.d.cts +215 -0
- package/dist/index-CsRXyS7O.d.ts +215 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +350 -0
- package/dist/index.d.ts +350 -0
- package/dist/index.js +1 -0
- package/dist/protocol-D7sEx8IP.d.ts +62 -0
- package/dist/protocol-Dh-wN2nY.d.cts +62 -0
- package/dist/protocols/graphql/index.cjs +1 -0
- package/dist/protocols/graphql/index.d.cts +95 -0
- package/dist/protocols/graphql/index.d.ts +95 -0
- package/dist/protocols/graphql/index.js +1 -0
- package/dist/protocols/grpc/index.cjs +1 -0
- package/dist/protocols/grpc/index.d.cts +61 -0
- package/dist/protocols/grpc/index.d.ts +61 -0
- package/dist/protocols/grpc/index.js +1 -0
- package/dist/protocols/http/index.cjs +1 -0
- package/dist/protocols/http/index.d.cts +161 -0
- package/dist/protocols/http/index.d.ts +161 -0
- package/dist/protocols/http/index.js +1 -0
- package/dist/protocols/mcp/index.cjs +1 -0
- package/dist/protocols/mcp/index.d.cts +3 -0
- package/dist/protocols/mcp/index.d.ts +3 -0
- package/dist/protocols/mcp/index.js +1 -0
- package/dist/protocols/ws/index.cjs +1 -0
- package/dist/protocols/ws/index.d.cts +35 -0
- package/dist/protocols/ws/index.d.ts +35 -0
- package/dist/protocols/ws/index.js +1 -0
- package/dist/types-C9ifzKqk.d.cts +1226 -0
- package/dist/types-C9ifzKqk.d.ts +1226 -0
- package/package.json +93 -0
package/dist/index.cjs
ADDED
|
@@ -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)),l={};function u(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=u(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=>u(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]=u(o,t);return n}return String(e)}((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(l,{AdapterRegistry:()=>_e,BUILTIN_CAPTURE_TEST:()=>it,DescriptorDecodeError:()=>Co,GraphQLAdapter:()=>$r,GrpcAdapter:()=>Ei,GrpcDependencyBrokenError:()=>En,GrpcDependencyMissingError:()=>$n,GrpcProtocolAdapter:()=>Oi,HttpAdapter:()=>zt,INTROSPECTION_QUERY:()=>lr,LOADER_OPTIONS:()=>hs,MCP_PROTOCOL_VERSION:()=>Pr,McpAdapter:()=>yn,ProtoKitError:()=>h,ReflectionProtocolError:()=>io,ReflectionUnavailableError:()=>oo,SseParser:()=>_t,UnifiedSession:()=>d,WebSocketAdapter:()=>nr,acceptHeaderFor:()=>tt,buildCatalog:()=>xs,buildCredentials:()=>Dn,buildCredentialsAsync:()=>Cn,buildCredentialsChecked:()=>Mn,buildCredentialsCheckedAsync:()=>jn,buildMessageTemplate:()=>Ks,createClient:()=>qi,createDebugger:()=>_i,createEventHub:()=>f,createGrpcManualSession:()=>Ni,createHttpMcpTransport:()=>en,createManualSession:()=>Bi,createMcpManualSession:()=>dn,createMcpStdioSession:()=>pn,createStdioMcpTransport:()=>tn,createWsManualSession:()=>rr,decodeFileDescriptorProto:()=>Ho,decodeFileDescriptorSet:()=>Yo,deriveIncludeDirsDetailed:()=>Gn,discoverAndWriteGraphQLSchema:()=>Sr,discoverAndWriteGrpcOperations:()=>ki,discoverAndWriteMcpCapabilities:()=>Zr,discoverGrpc:()=>gi,discoverMcpCapabilities:()=>Nr,fetchDescriptorSet:()=>xo,fetchFullDescriptorSet:()=>To,generateAllMcpCalls:()=>Yr,generateAllOperations:()=>gr,generateMcpCall:()=>Hr,generateOperation:()=>yr,grpcCall:()=>Fs,grpcDiscover:()=>gi,grpcManualSession:()=>Ni,inferSchema:()=>ye,inferSchemaFromMany:()=>ge,initializeMcpSession:()=>jr,introspectSchema:()=>ur,isGrpcAvailable:()=>On,isSseContentType:()=>Ze,isStreamingContentType:()=>et,isStreamingOperation:()=>Xe,listServices:()=>Eo,listServicesDetailed:()=>$o,loadGrpc:()=>kn,locateOperation:()=>G,mcpManualSession:()=>dn,mergeSchema:()=>oe,probeStreamingResponse:()=>rt,requireCapability:()=>_n,resolveGraphQLConfig:()=>or,resolveMcpConfig:()=>Ar,resolveMethod:()=>Ps,runGraphQL:()=>ar,runMcpManualSession:()=>hn,runWebSocketSession:()=>rr,sampleFromSchema:()=>Ne,scanProtoFiles:()=>zn,serializeDescriptorSet:()=>So,toCloneable:()=>u,toResponseObject:()=>Ee,writeBackResponse:()=>ke,writeGraphQLOperations:()=>wr,writeGrpcOperations:()=>Ti,writeMcpOperations:()=>Xr,wsManualSession:()=>rr}),module.exports=(e=l,a(r({},"__esModule",{value:!0}),e));var d=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:u(e.data),error:u(e.error),meta:u(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)}}}},p=class extends d{async open(){}async close(){}async waitForClose(){}async send(){}};function f(e,t,r,n=1e3){return new p(e,t,r,n)}var m=Symbol.for("@powerduck/openapi-request.ProtoKitError"),h=class e extends Error{code;details;[m]=!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[m]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function y(e,t,r,n){return new h(t,e,r,n)}function g(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 v(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:g(e)}}var b=new Set(["__proto__","constructor","prototype"]);function w(e){return b.has(e)}function S(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return $(e)}function $(e){return E(e,new Set)}function E(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 n=e;if(t.has(n))return null;const o=n.toJSON;if("function"==typeof o){let e;try{e=o.call(n)}catch{return null}return e===n?null:E(e,t)}t.add(n);try{if(Array.isArray(n)){const e=new Array(n.length);for(let r=0;r<n.length;r+=1){const o=E(n[r],t);e[r]=void 0===o?null:o}return e}const e={};for(const r of Object.keys(n)){if(w(r))continue;let o;try{o=n[r]}catch{continue}const s=E(o,t);void 0!==s&&(e[r]=s)}return e}finally{t.delete(n)}}function A(e,t){const r=x(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:x(n)}):r}function x(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 T(e,t){return k(e,t,0)}function k(e,t,r){if(!t||!O(t))return e;if(r>=64)return t;const n={...e};for(const e of Object.keys(t)){if(w(e))continue;const o=t[e];if(void 0===o)continue;const s=n[e];O(s)&&O(o)?n[e]=k(s,o,r+1):n[e]=o}return n}function O(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}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)}}function P(e){if(e)try{clearTimeout(e)}catch{}return null}function M(e,t,r=Number.MAX_SAFE_INTEGER){const n="number"==typeof e?e:Number(e);if(!Number.isFinite(n))return t;const o=Math.floor(n);return o<=0?t:Math.min(o,r)}function D(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}}function C(e){return e instanceof Error?e.message:String(e)}var j=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function I(e){return j.test(e)}function N(e,t){return e>0?new Promise((r,n)=>{const o=()=>{clearTimeout(s),n(new Error("Aborted while waiting."))},s=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);if(s?.unref?.(),t?.aborted)return o();t?.addEventListener("abort",o,{once:!0})}):Promise.resolve()}var B=Symbol("protokit.cycle"),R=new Set(["__proto__","constructor","prototype"]),q=32,L=100,F=2e5;function U(e,t={}){const r=z(t.maxDepth,q),n=z(t.maxNodes,F),o=new Map;function s(e,t){let r=e;try{r=decodeURIComponent(e)}catch{r=e}const n=r.replace(/~1/g,"/").replace(/~0/g,"~");if(R.has(n))throw y("BAD_REF",`Pointer "${t}" traverses a forbidden key "${n}"`);return n}function i(t){if("string"!=typeof t||!t.length)throw y("EXTERNAL_REF","A $ref pointer must be a non-empty string");if("#"===t||"#/"===t)return e;if(!t.startsWith("#/"))throw y("EXTERNAL_REF",`Only local $ref pointers are supported, got: ${t}`);let r=e;for(const e of t.slice(2).split("/")){if(null===r||"object"!=typeof r)throw y("BAD_REF",`Cannot resolve pointer "${t}"`);const n=s(e,t);if(!Object.prototype.hasOwnProperty.call(r,n))throw y("BAD_REF",`Pointer "${t}" resolves to undefined`);r=r[n]}if(void 0===r)throw y("BAD_REF",`Pointer "${t}" resolves to undefined`);return r}function a(e){let t=e;const r=new Set;let n,o=0;for(;null!==t&&"object"==typeof t&&"string"==typeof t.$ref;){const e=t.$ref;if(r.has(e)||++o>L)return l();r.add(e);const s=c(t);s&&(n={...s,...n??{}}),t=i(e)}return n?null===t||"object"!=typeof t||Array.isArray(t)?t:{...t,...n}:t}function c(e){let t;for(const r of Object.keys(e))"$ref"===r||R.has(r)||((t??={})[r]=e[r]);return t}function l(){return{type:"object",[B]:!0}}function u(e,t,o,s){if(null===e||"object"!=typeof e)return e;if(t>r)return{type:"object"};if(++s.nodes>n)return{type:"object"};let i;try{i=a(e)}catch(e){if("EXTERNAL_REF"===e?.code)throw e;return{type:"object"}}if(null===i||"object"!=typeof i)return i;if(i[B])return{type:"object"};if(o.has(i))return{type:"object"};o.add(i);try{if(Array.isArray(i)){const e=new Array(i.length);for(let r=0;r<i.length;r+=1)e[r]=u(i[r],t+1,o,s);return e}const e={};for(const r of Object.keys(i))R.has(r)||(e[r]=u(i[r],t+1,o,s));return e}finally{o.delete(i)}}function d(e){return u(e,0,new Set,{nodes:0})}return{deref:a,deepDeref:function(e){const t=null!==e&&"object"==typeof e?e.$ref:void 0,r="string"==typeof t&&1===Object.keys(e).length;if(r&&o.has(t))return S(o.get(t));const n=d(e);return r?(o.set(t,n),S(n)):n},byPointer:i}}function z(e,t){const r="number"==typeof e?e:Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}var V=["get","put","post","delete","options","head","patch","trace","query"];function G(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw y("BAD_SPEC","spec must be an object");if("string"!=typeof e.openapi||!e.openapi.trim())throw y("BAD_SPEC","spec.openapi version string is required");if(!t||"object"!=typeof t)throw y("BAD_TARGET","target is required");const r=U(e),n=e.paths;if(!n||"object"!=typeof n||Array.isArray(n))throw y("BAD_SPEC","spec.paths is missing or invalid");const o=function(e,t){const r=[];for(const[n,o]of Object.entries(e)){if(n.startsWith("x-"))continue;let e;try{e=t.deref(o)}catch{continue}if(!e||"object"!=typeof e||Array.isArray(e))continue;for(const t of V){const o=e[t];o&&"object"==typeof o&&!Array.isArray(o)&&r.push({path:n,method:t,rawOperation:o,pathItem:e,isCustomMethod:!1})}const s=e.additionalOperations;if(s&&"object"==typeof s&&!Array.isArray(s))for(const[t,o]of Object.entries(s))o&&"object"==typeof o&&!Array.isArray(o)&&r.push({path:n,method:t.toLowerCase(),rawOperation:o,pathItem:e,isCustomMethod:!0,customMethodKey:t})}return r}(n,r);if(!o.length)throw y("EMPTY_SPEC","The document does not declare any operation");const s=t.operationId?function(e,t,r){const n=e.filter(e=>{try{return t.deref(e.rawOperation)?.operationId===r}catch{return!1}});if(!n.length)throw y("OP_NOT_FOUND",`operationId "${r}" was not found`,{available:W(e,t)});if(n.length>1)throw y("AMBIGUOUS_OPERATION_ID",`operationId "${r}" is declared ${n.length} times`,{matches:n.map(e=>`${e.method.toUpperCase()} ${e.path}`)});return n[0]}(o,r,t.operationId):function(e,t){if(!t.path||!t.method)throw y("BAD_TARGET","Provide either operationId, or both path and method");const r=String(t.method).toLowerCase(),n=String(t.path),o=[n,n.startsWith("/")?n.slice(1):`/${n}`];for(const t of o){const n=e.find(e=>e.path===t&&e.method===r);if(n)return n}throw y("OP_NOT_FOUND",`Operation "${String(t.method).toUpperCase()} ${n}" was not found`,{available:e.map(e=>`${e.method.toUpperCase()} ${e.path}`).slice(0,50)})}(o,t),i=r.deepDeref(s.rawOperation)??{},a=s.pathItem??{};return{path:s.path,method:s.method,isCustomMethod:s.isCustomMethod,...s.customMethodKey?{customMethodKey:s.customMethodKey}:{},operation:i,pathItem:a,parameters:J(r,a,i),servers:H(e,a,i),security:Array.isArray(i.security)?i.security:Array.isArray(e.security)?e.security:void 0}}function W(e,t){const r=new Set;for(const n of e)try{const e=t.deref(n.rawOperation)?.operationId;"string"==typeof e&&e&&r.add(e)}catch{}return Array.from(r).slice(0,50)}function J(e,t,r){const n=new Map,o=t=>{if(Array.isArray(t))for(const r of t){let t;try{t=e.deepDeref(r)}catch{continue}t&&"object"==typeof t&&"string"==typeof t.name&&t.name.length>0&&"string"==typeof t.in&&n.set(`${t.in.toLowerCase()}:${t.name}`,t)}};return o(t?.parameters),o(r?.parameters),Array.from(n.values())}function H(e,t,r){const n=e=>{if(!Array.isArray(e))return;const t=e.filter(e=>e&&"object"==typeof e&&"string"==typeof e.url&&e.url.length>0);return t.length?t:void 0};return n(r?.servers)??n(t?.servers)??n(e?.servers)??[{url:"/"}]}var Y=["null","boolean","integer","number","string","array","object"],K=new Set(["$ref","type","format","properties","required","items","prefixItems","additionalProperties","patternProperties","propertyNames","enum","const","examples","example","default","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","oneOf","anyOf","allOf","not","nullable","title","description","deprecated","readOnly","writeOnly"]),Q=new Set(["__proto__","constructor","prototype"]),X=20,Z=50,ee=3,te=e=>null==e?[]:Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[],re=e=>null!==e&&"object"==typeof e&&!Array.isArray(e);function ne(e){if(!re(e))return!1;for(const t of Object.keys(e))if(!Q.has(t))return!1;return!0}function oe(e,t,r=0){if(null==e)return void 0===t?e:t;if(null==t)return e;if(!re(e))return re(t)?t:e;if(!re(t))return e;if(e===t)return e;if(r>X)return e;if(ne(t))return e;if(ne(e))return t;if("string"==typeof e.$ref)return e;if("string"==typeof t.$ref)return t;const n={};let o=Array.from(new Set([...te(e.type),...te(t.type)]));if(o.includes("integer")&&o.includes("number")&&(o=o.filter(e=>"integer"!==e)),o.sort((e,t)=>{const r=Y.indexOf(e),n=Y.indexOf(t);return(r<0?Y.length:r)-(n<0?Y.length:n)}),1===o.length?n.type=o[0]:o.length>1&&(n.type=o),void 0!==e.format&&e.format===t.format||void 0!==e.format&&void 0===t.format?n.format=e.format:void 0!==t.format&&void 0===e.format&&(n.format=t.format),!0!==e.nullable&&!0!==t.nullable||(n.nullable=!0),void 0!==e.properties||void 0!==t.properties){const o={};for(const[t,r]of Object.entries(re(e.properties)?e.properties:{}))Q.has(t)||(o[t]=r);for(const[e,n]of Object.entries(re(t.properties)?t.properties:{}))Q.has(e)||(o[e]=void 0!==o[e]?oe(o[e],n,r+1):n);n.properties=o;const s=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],i=Array.isArray(t.required)?t.required.filter(e=>"string"==typeof e):[];if(re(e.properties)&&re(t.properties)){const e=new Set(i),t=s.filter(t=>e.has(t));t.length&&(n.required=t)}else{const t=re(e.properties)?s:i;t.length&&(n.required=t)}}else if(Array.isArray(e.required)||Array.isArray(t.required)){const r=Array.isArray(e.required)?e.required:[],o=Array.isArray(t.required)?t.required:[];if(r.length)if(o.length){const e=new Set(o),t=r.filter(t=>e.has(t));t.length&&(n.required=t)}else n.required=r.slice();else o.length&&(n.required=o.slice())}if(void 0!==e.additionalProperties||void 0!==t.additionalProperties){const o=e.additionalProperties,s=t.additionalProperties;re(o)&&re(s)?n.additionalProperties=oe(o,s,r+1):n.additionalProperties=!0===o||!0===s||(void 0!==o?o:s)}if(re(e.patternProperties)||re(t.patternProperties)){const o={...re(e.patternProperties)?e.patternProperties:{}};for(const[e,n]of Object.entries(re(t.patternProperties)?t.patternProperties:{}))o[e]=o[e]?oe(o[e],n,r+1):n;n.patternProperties=o}if(void 0===e.propertyNames&&void 0===t.propertyNames||(n.propertyNames=oe(e.propertyNames,t.propertyNames,r+1)),void 0===e.items&&void 0===t.items||(n.items=oe(e.items,t.items,r+1)),Array.isArray(e.prefixItems)||Array.isArray(t.prefixItems)){const o=Array.isArray(e.prefixItems)?e.prefixItems:[],s=Array.isArray(t.prefixItems)?t.prefixItems:[],i=Math.max(o.length,s.length),a=[];for(let e=0;e<i;e+=1)a.push(void 0!==o[e]&&void 0!==s[e]?oe(o[e],s[e],r+1):o[e]??s[e]);n.prefixItems=a}!0===e.uniqueItems&&!0===t.uniqueItems&&(n.uniqueItems=!0),se(n,"minimum",e,t,Math.min),se(n,"exclusiveMinimum",e,t,Math.min),se(n,"minLength",e,t,Math.min),se(n,"minItems",e,t,Math.min),se(n,"minProperties",e,t,Math.min),se(n,"maximum",e,t,Math.max),se(n,"exclusiveMaximum",e,t,Math.max),se(n,"maxLength",e,t,Math.max),se(n,"maxItems",e,t,Math.max),se(n,"maxProperties",e,t,Math.max),"number"==typeof e.multipleOf&&e.multipleOf===t.multipleOf&&(n.multipleOf=e.multipleOf),"string"==typeof e.pattern&&e.pattern===t.pattern||"string"==typeof e.pattern&&void 0===t.pattern?n.pattern=e.pattern:"string"==typeof t.pattern&&void 0===e.pattern&&(n.pattern=t.pattern),Array.isArray(e.enum)&&Array.isArray(t.enum)&&(n.enum=ae([...e.enum,...t.enum]).slice(0,Z)),void 0!==e.const&&void 0!==t.const&&(ie(e.const,t.const)?n.const=e.const:n.enum=ae([e.const,t.const]));const s=ae([...Array.isArray(e.examples)?e.examples:[],...Array.isArray(t.examples)?t.examples:[]]).slice(0,ee);s.length&&(n.examples=s),void 0===e.example&&void 0===t.example||(n.example=void 0!==e.example?e.example:t.example),void 0===e.default&&void 0===t.default||(n.default=void 0!==e.default?e.default:t.default);for(const r of["title","description"])void 0===e[r]&&void 0===t[r]||(n[r]=void 0!==e[r]?e[r]:t[r]);for(const r of["deprecated","readOnly","writeOnly"])!0===e[r]&&!0===t[r]&&(n[r]=!0);for(const r of["oneOf","anyOf","allOf"]){const o=Array.isArray(e[r])?e[r]:void 0,s=Array.isArray(t[r])?t[r]:void 0;(o||s)&&(n[r]=o&&s?ce([...o,...s]):(o??s).slice())}void 0===e.not&&void 0===t.not||void 0!==e.not&&ie(e.not,t.not)&&(n.not=e.not);for(const r of[t,e])for(const e of Object.keys(r))Q.has(e)||K.has(e)||(n[e]=r[e]);return n}function se(e,t,r,n,o){const s=r[t],i=n[t],a="number"==typeof s&&Number.isFinite(s),c="number"==typeof i&&Number.isFinite(i);a&&c?e[t]=o(s,i):"boolean"==typeof s&&s===i&&(e[t]=s)}function ie(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function ae(e){const t=new Set,r=[];for(const n of e){let e;try{const t=JSON.stringify(n);if("string"!=typeof t)continue;e=t}catch{continue}t.has(e)||(t.add(e),r.push(n))}return r}function ce(e){return ae(e.filter(e=>void 0!==e))}var le=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,ue=/^\d{4}-\d{2}-\d{2}$/,de=/^\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})?$/,pe=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,fe=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,me=/^https?:\/\/\S+$/i,he=new Set(["__proto__","constructor","prototype"]);function ye(e,t={},r=0){const n=t.maxDepth??12,o=!1!==t.includeExamples;if(r>n)return{};if(void 0===e)return{};if(null===e)return{type:"null"};const s=typeof e;if("boolean"===s)return o?{type:"boolean",examples:[e]}:{type:"boolean"};if("number"===s){const t=e;if(!Number.isFinite(t))return{type:"number"};const r=Number.isInteger(t)?"integer":"number";return o?{type:r,examples:[t]}:{type:r}}if("bigint"===s)return{type:"string",format:"int64"};if("string"===s){const r=e,n={type:"string"},s=function(e){return e?le.test(e)?"date-time":ue.test(e)?"date":pe.test(e)?"uuid":me.test(e)?"uri":fe.test(e)?"email":de.test(e)?"time":void 0:void 0}(r);if(s&&(n.format=s),o){const e=Math.max(1,t.maxExampleLength??120);n.examples=[r.length>e?`${r.slice(0,e)}...`:r]}return n}if(Array.isArray(e)){if(!e.length)return{type:"array",items:{}};const n=Math.max(1,t.sampleArrayItems??20),o=Math.min(e.length,n);let s=ye(e[0],t,r+1);for(let n=1;n<o;n+=1)s=oe(s,ye(e[n],t,r+1),0);return{type:"array",items:s}}if("object"===s){if(!function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(e))return{};const n=Object.create(null),o=[],s=Math.max(1,t.maxProperties??250);let i=0;for(const[a,c]of Object.entries(e))if(!he.has(a)){if(++i>s)break;n[a]=ye(c,t,r+1),null!=c&&o.push(a)}const a={type:"object",properties:{...n}};return o.length&&(a.required=o),a}return{}}function ge(e,t={}){if(!Array.isArray(e)||!e.length)return{};let r=null;for(const n of e){const e=ye(n,t);r=null===r?e:oe(r,e,0)}return r??{}}var ve=new Set(["date","content-length","connection","keep-alive","transfer-encoding","server","set-cookie","age","via","alt-svc","report-to","nel","x-request-id","x-trace-id","x-correlation-id","x-amzn-requestid","x-amzn-trace-id","x-amz-cf-id","cf-ray","cf-cache-status","x-served-by","x-timer","x-cache","x-cache-hits","x-fastly-request-id","x-envoy-upstream-service-time","x-powered-by","expires","last-modified","etag"]),be=new Set(["[DONE]","DONE","[done]","done"]),we=new Set(["__proto__","constructor","prototype"]);function Se(e){return{type:"string",examples:[$e(e)]}}function $e(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>String(e)).join(", "):null==e?"":String(e)}function Ee(e,t={}){if(!e||"object"!=typeof e||!O(e.response))return{statusCode:"default",response:{description:"Response"}};const{response:r}=e,n="number"==typeof r.status?r.status:0,o=n>0?String(n):"default",s="string"==typeof(i=r.contentType)&&i.trim()&&i.split(";")[0].trim().toLowerCase()||"application/octet-stream";var i;const a=!1!==t.includeExamples,c=Math.max(1,t.maxExampleChars??4e3),l={description:"string"==typeof r.statusText&&r.statusText||Te(n)},u=function(e){if(!e||"object"!=typeof e)return;const t={},r=new Map;for(const[n,o]of Object.entries(e)){if("string"!=typeof n||!n.length)continue;if(we.has(n))continue;const e=n.toLowerCase();if("content-type"===e||ve.has(e))continue;const s=r.get(e);if(s){const e=t[s],r=oe(e.schema,Se(o),0);t[s]={...e,schema:r};continue}r.set(e,n),t[n]={schema:Se(o)}}return Object.keys(t).length?t:void 0}(r.headers);u&&(l.headers=u);if(("sse"===e.protocol||"websocket"===e.protocol)&&Array.isArray(r.events))return{statusCode:o,response:Ae(e,l,s,t)};if(void 0!==r.body&&null!==r.body){const e={schema:ye(r.body)};a&&(e.examples={capturedSample:{summary:"Captured from a live call",value:xe(r.body,c)}}),l.content={[s]:e}}else if("string"==typeof r.text&&r.text.length){const e={schema:{type:"string"}};a&&(e.examples={capturedSample:{summary:"Captured from a live call",value:r.text.slice(0,c)}}),l.content={[s]:e}}else 204!==n&&304!==n&&(r.sizeBytes??0)>0&&(l.content={[s]:{schema:{type:"string",format:"binary"}}});return{statusCode:o,response:l}}function Ae(e,t,r,n){const o=e.response,s=(Array.isArray(o.events)?o.events:[]).filter(e=>e&&"out"!==e.direction).filter(e=>!function(e){const t="string"==typeof e.data?e.data.trim():"";if(be.has(t))return!0;const r=(e.event??"").toLowerCase();return"done"===r||"end"===r||"complete"===r}(e));if(!s.length)return t;const i=Math.max(1,n.maxEventPreviewChars??200);let a=null,c=!1,l=!1;for(const e of s)if(void 0!==e.parsed)c=!0,a=oe(a,ye(e.parsed),0);else{l=!0;const t="string"==typeof e.data?e.data:"";a=oe(a,{type:"string",examples:[t.length>i?`${t.slice(0,i)}...`:t]},0)}const u=Array.from(new Set(s.map(e=>e.event).filter(e=>"string"==typeof e&&!!e))),d=c&&!l?{type:"object"}:{type:"string"},p={type:"object",properties:{id:{type:"string"},event:u.length?{type:"string",enum:u}:{type:"string"},data:a??d,retry:{type:"integer"}},required:["data"]},f="sse"===e.protocol?"text/event-stream":r;return t.content={[f]:{itemSchema:p,"x-protokit-sample-count":s.length,...o.truncated?{"x-protokit-truncated":!0}:{}}},t}function xe(e,t){try{const r=JSON.stringify(e);return"string"==typeof r&&r.length<=t?e:{"x-protokit-truncated":!0,preview:String(r??e).slice(0,t)}}catch{try{return String(e).slice(0,t)}catch{return"[unserializable payload]"}}}function Te(e){return e>=500?"Server error":e>=400?"Client error":e>=300?"Redirection":e>=200?"Successful response":e>=100?"Informational response":"Response"}function ke(e,t,r,n,o={}){if(!e||"object"!=typeof e||Array.isArray(e))throw y("BAD_SPEC","spec must be an object");if("string"!=typeof t||!t.length)throw y("BAD_TARGET","path must be a non-empty string");if("string"!=typeof r||!r.length)throw y("BAD_TARGET","method must be a non-empty string");if(!n||"object"!=typeof n||!O(n.response))throw y("BAD_FRAGMENT","fragment.response must be an object");const s="string"==typeof n.statusCode&&n.statusCode?n.statusCode:"default";if(we.has(s))throw y("BAD_FRAGMENT",`Invalid status code key "${s}"`);const i=S(e);if(!O(i.paths))throw y("BAD_SPEC","spec.paths is missing or invalid");const a=i.paths[t];if(!O(a))throw y("PATH_NOT_FOUND",`Path "${t}" is not present in the document`);const c=function(e,t){const r=t.toLowerCase(),n=e[r];if(O(n))return n;const o=e.additionalOperations;if(!O(o))return;for(const e of Object.keys(o)){if(e.toLowerCase()!==r)continue;const t=o[e];if(O(t))return t}return}(a,r);if(!c)throw y("OP_NOT_FOUND",`Operation "${r.toUpperCase()} ${t}" is not present in the document`);if(Array.isArray(o.allowedStatusCodes)&&o.allowedStatusCodes.length&&!o.allowedStatusCodes.includes(s))return i;O(c.responses)||(c.responses={});const l=S(n.response),u=c.responses[s];return"replace"!==o.strategy&&void 0!==u&&O(u)?("string"==typeof u.$ref||function(e,t,r){const n=!1!==r.protectComponentRefs,o=!1!==r.overwriteExamples,s="string"==typeof e.description&&e.description.length>0;!1!==r.keepExistingDescription&&s||"string"==typeof t.description&&t.description&&(e.description=t.description);O(t.headers)&&(O(e.headers)||(e.headers={}),function(e,t,r){const n=new Map;for(const t of Object.keys(e))n.set(t.toLowerCase(),t);for(const[o,s]of Object.entries(t)){if(we.has(o))continue;if(!O(s))continue;const t=n.get(o.toLowerCase());if(!t){e[o]=s,n.set(o.toLowerCase(),o);continue}const i=e[t];O(i)?r&&"string"==typeof i.$ref||(void 0!==s.schema&&(i.schema=r&&"string"==typeof i.schema?.$ref?i.schema:oe(i.schema,s.schema,0)),"string"==typeof s.description&&"string"!=typeof i.description&&(i.description=s.description)):e[t]=s}}(e.headers,t.headers,n));if(O(t.content)){O(e.content)||(e.content={});for(const[r,s]of Object.entries(t.content)){if(we.has(r))continue;if(!O(s))continue;const t=e.content[r];O(t)?Oe(t,s,n,o):e.content[r]=s}}O(t.links)&&(e.links={...O(e.links)?e.links:{},...t.links});for(const r of Object.keys(t))r.startsWith("x-")&&(we.has(r)||(e[r]=t[r]))}(u,l,o),i):(c.responses[s]=l,i)}function Oe(e,t,r,n){if(void 0!==t.itemSchema&&(e.itemSchema=r&&"string"==typeof e.itemSchema?.$ref?e.itemSchema:oe(e.itemSchema,t.itemSchema,0)),void 0!==t.schema&&(e.schema=r&&"string"==typeof e.schema?.$ref?e.schema:oe(e.schema,t.schema,0)),O(t.examples)){O(e.examples)||(e.examples={});for(const[r,o]of Object.entries(t.examples))we.has(r)||!n&&r in e.examples||(e.examples[r]=o)}void 0!==t.example&&void 0===e.example&&(e.example=t.example),O(t.encoding)&&(e.encoding={...O(e.encoding)?e.encoding:{},...t.encoding});for(const r of Object.keys(t))r.startsWith("x-")&&(we.has(r)||(e[r]=t[r]))}var _e=class{entries=[];nextSeq=0;register(e){if(!e||"object"!=typeof e)throw y("BAD_ADAPTER","Adapter must be an object");if("string"!=typeof e.name||!e.name.trim())throw y("BAD_ADAPTER","Adapter must expose a non-empty `name`");for(const t of["supports","plan","execute"])if("function"!=typeof e[t])throw y("BAD_ADAPTER",`Adapter "${e.name}" must implement ${t}()`);const t=this.entries.findIndex(t=>t.adapter.name===e.name);return t>=0?this.entries[t]={adapter:e,seq:this.entries[t].seq}:this.entries.push({adapter:e,seq:this.nextSeq++}),this}unregister(e){const t=this.entries.findIndex(t=>t.adapter.name===e);return!(t<0)&&(this.entries.splice(t,1),!0)}get(e){return this.entries.find(t=>t.adapter.name===e)?.adapter}list(){return this.entries.map(e=>e.adapter.name)}rank(e){return this.entries.map(t=>({entry:t,score:this.scoreOf(t.adapter,e)})).filter(e=>e.score>0).sort((e,t)=>t.score!==e.score?t.score-e.score:e.entry.seq-t.entry.seq).map(e=>({name:e.entry.adapter.name,score:e.score}))}resolve(e){if(!e||!e.located)throw y("BAD_ADAPTER_CONTEXT","resolve() requires a located operation");let t,r=0;for(const n of this.entries){const o=this.scoreOf(n.adapter,e);o<=0||o>r&&(t=n,r=o)}if(!t){throw y("NO_ADAPTER",`No protocol adapter matched operation "${String(e.located.method??"").toUpperCase()} ${String(e.located.path??"")}"`,{registered:this.list()})}return t.adapter}scoreOf(e,t){let r;try{r=e.supports(t)}catch{return 0}const n="number"==typeof r?r:Number(r);return!Number.isFinite(n)||n<=0?0:n}},Pe=new Set(["__proto__","constructor","prototype"]),Me="2024-01-01T00:00:00.000Z",De=12,Ce=2,je=5,Ie=256;function Ne(e,t=0,r={}){const n=r.maxDepth??De;if(!e||"object"!=typeof e||Array.isArray(e))return null;if(t>n)return null;if("string"==typeof e.$ref)return null;if(void 0!==e.example)return e.example;const o=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!==o)return o;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 n,o;for(const s of e.allOf){const e=Ne(s,t+1,r);null===e||"object"!=typeof e||Array.isArray(e)?null!=e&&(o=e):n={...n??{},...e}}if(e.properties||e.required){const o=Be(e,t,r);o&&"object"==typeof o&&(n={...n??{},...o})}return n||(void 0!==o?o:{})}(e,t,r);for(const n of["oneOf","anyOf"]){const o=e[n];if(Array.isArray(o)&&o.length){return Ne(o.find(e=>e&&"object"==typeof e&&"null"!==e.type)??o[0],t+1,r)}}const s=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(s){case"object":return Be(e,t,r);case"array":return function(e,t,r){const n=[];if(Array.isArray(e.prefixItems))for(const o of e.prefixItems)n.push(Ne(o,t+1,r));const o=Fe(e.minItems)??1,s=Fe(e.maxItems);let i=Math.max(o,n.length,1);i=Math.min(i,je),void 0!==s&&(i=Math.min(i,Math.max(s,0)));const a=e.items&&"object"==typeof e.items?e.items:void 0;if(!a&&Array.isArray(e.prefixItems))return n.slice(0,0===i?0:Math.max(i,n.length));for(;n.length<i;){const o=Ne(a??{},t+1,r);if(!0===e.uniqueItems&&n.length>0)break;n.push(o)}return void 0!==s?n.slice(0,Math.max(s,0)):n}(e,t,r);case"integer":return function(e){const{min:t,max:r}=Re(e,!0);let n=0;void 0!==t&&n<t&&(n=Math.ceil(t));void 0!==r&&n>r&&(n=Math.floor(r));const o=Le(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return Math.trunc(n)}(e);case"number":return function(e){const{min:t,max:r}=Re(e,!1);let n=0;void 0!==t&&n<t&&(n=t);void 0!==r&&n>r&&(n=r);const o=Le(e.multipleOf);if(void 0!==o&&o>0){const e=Math.ceil(n/o)*o;(void 0===r||e<=r)&&(n=e)}return n}(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 Me;case"date":return Me.slice(0,10);case"time":return Me.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?qe(r,e):"string"==typeof e.pattern&&e.pattern.length?"":qe("string",e)}(e)}}function Be(e,t,r){const n={},o=Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[],s=e.properties&&"object"==typeof e.properties?e.properties:{},i=!0===r.includeReadOnly,a=!1!==r.includeWriteOnly;for(const[e,c]of Object.entries(s))Pe.has(e)||!i&&c&&!0===c.readOnly||!a&&c&&!0===c.writeOnly||t>Ce&&o.length&&!o.includes(e)||(n[e]=Ne(c,t+1,r));for(const e of o)Pe.has(e)||e in n||(n[e]=Ne(s[e]??{},t+1,r));!Object.keys(n).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(n.key=Ne(e.additionalProperties,t+1,r));const c=Fe(e.minProperties);if(void 0!==c){const o=e.additionalProperties&&"object"==typeof e.additionalProperties?e.additionalProperties:{};let s=1;for(;Object.keys(n).length<Math.min(c,20);){const e=`additionalProp${s}`;s+=1,e in n||(n[e]=Ne(o,t+1,r))}}return n}function Re(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let n=Le(e.minimum),o=Le(e.maximum);const s=e.exclusiveMinimum,i=e.exclusiveMaximum;if("number"==typeof s&&Number.isFinite(s)){const e=s+r;n=void 0===n?e:Math.max(n,e)}else!0===s&&void 0!==n&&(n+=r);if("number"==typeof i&&Number.isFinite(i)){const e=i-r;o=void 0===o?e:Math.min(o,e)}else!0===i&&void 0!==o&&(o-=r);return{min:n,max:o}}function qe(e,t){const r=Fe(t.minLength),n=Fe(t.maxLength);let o=e;return void 0!==r&&o.length<r&&(o=o.padEnd(Math.min(r,Ie),"x")),void 0!==n&&o.length>n&&(o=o.slice(0,Math.max(n,0))),o}function Le(e){if("number"==typeof e&&Number.isFinite(e))return e}function Fe(e){const t=Le(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}var Ue="\0PK_OPEN\0",ze="\0PK_CLOSE\0",Ve=0;function Ge(e){Ve=(Ve+1)%65535;const t=Date.now().toString(36),r=Math.floor(65535*Math.random()).toString(36);return`${e}-${t}-${Ve.toString(36)}${r}`}function We(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return He(Je(r),"options.serverUrl");const n=Array.isArray(e)?e.filter(O):[],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 y("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return s=function(e,t,r){const n=O(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 y("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 y("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),He(Je(s),"spec.servers")}function Je(e){return e.replace(/\/+$/,"")||e}function He(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(Ue).split("}}").join(ze).replace(/\{[^{}]*\}/g,"").split(Ue).join("{{").split(ze).join("}}")}(e);if(!r)throw y("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw y("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}function Ye(e,t,r={},n={}){const o=!1!==n.maskSecrets,s=!0===n.allowBaseUrlOverride,i=O(r)?r:{},a=[],c=new Set,l=(e,t,r)=>{"string"==typeof e&&e&&(c.has(e)||(c.add(e),a.push({key:e,value:null==t?"":String(t),type:r,enabled:!0})))};s||l("baseUrl",t,"default");for(const[e,t]of Object.entries(i))l(e,t,o&&I(e)?"secret":"default");return s&&l("baseUrl",t,"default"),{id:Ge("protokit-env"),name:"string"==typeof e&&e.trim()?e:"protokit",values:a,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}var Ke=["text/event-stream","application/json-seq","application/x-ndjson","application/ndjson","application/jsonl","application/x-jsonlines"];function Qe(e){return"default"!==e&&(!!/^2\d\d$/.test(e)||/^2xx$/i.test(e))}function Xe(e,t){const r=function(e){if(O(e?.header))for(const[t,r]of Object.entries(e.header))if("accept"===t.toLowerCase())return"string"==typeof r?r:Array.isArray(r)?r.map(e=>String(e)).join(", "):null==r?void 0:String(r)}(t);if(r&&et(r))return!0;if(!O(e))return!1;const n=e["x-protocol"];if("string"==typeof n){const e=n.toLowerCase();if("sse"===e||"eventsource"===e)return!0;if("websocket"===e||"grpc"===e)return!1}if(O(e["x-sse"]))return!0;const o=e.responses;if(!O(o))return!1;for(const[e,t]of Object.entries(o)){if(e.startsWith("x-"))continue;if(!O(t))continue;const r=t.content;if(O(r))for(const[e,t]of Object.entries(r)){const r=e.toLowerCase();if(r.startsWith("text/event-stream"))return!0;if(O(t)&&void 0!==t.itemSchema&&Ke.some(e=>r.startsWith(e)))return!0}}return!1}function Ze(e){return"string"==typeof e&&/(^|[\s,;])text\/event-stream\b/i.test(e)}function et(e){if("string"!=typeof e||!e)return!1;return e.split(",").map(e=>e.split(";")[0].trim().toLowerCase()).filter(Boolean).some(e=>Ke.some(t=>e===t||e.startsWith(t)))}function tt(e){if(!O(e))return;const t=e.responses;if(!O(t))return;const r=new Set,n=new Set;for(const[e,o]of Object.entries(t)){if(e.startsWith("x-"))continue;if(!O(o))continue;const t=o.content;if(!O(t))continue;const s=Qe(e)?r:n;for(const e of Object.keys(t))"string"==typeof e&&e.trim()&&"*/*"!==e&&s.add(e.trim())}const o=r.size?r:n;if(!o.size)return;const s=Array.from(o);return s.sort((e,t)=>{const r=e=>{const t=e.toLowerCase();return t.startsWith("text/event-stream")?0:Ke.some(e=>t.startsWith(e))?1:"application/json"===t?2:t.endsWith("+json")?3:4},n=r(e)-r(t);return 0!==n?n:e.localeCompare(t)}),s.slice(0,8).join(", ")}async function rt(e,t){const r=await fetch(e,t),n=r.headers.get("content-type")??void 0,o=r.headers.get("transfer-encoding")??"";let s="none";return Ze(n)?s="sse":et(n)?s="ndjson":!n&&/chunked/i.test(o)&&(s="chunked"),{ok:r.ok,status:r.status,contentType:n,kind:s,response:r}}function nt(e){if(!e)return[];return(Array.isArray(e)?e:[e]).filter(e=>O(e)&&("string"==typeof e.exec||Array.isArray(e.exec)))}function ot(e,t,r){const n=[],o=new Set;return r.forEach((r,s)=>{const i=function(e){const t=(Array.isArray(e)?e.map(e=>"string"==typeof e?e:String(e??"")):String(e).split(/\r?\n/)).slice(0,2e3);let r=0;const n=[];for(const e of t){if(r+=e.length+1,r>2e5)break;n.push(e)}return n}(r.exec);if(!i.some(e=>e.trim().length>0))return;let a="string"==typeof r.id&&r.id.trim()?r.id.trim():`protokit-${t}-${e}-${s}`;for(;o.has(a);)a=`${a}-b`;o.add(a),n.push({listen:e,script:{id:a,type:"text/javascript",exec:i}})}),n}function st(e,t){const r=e?.["x-postman-scripts"];if(!O(r))return{pre:[],test:[]};const n=e=>{if(null==e)return[];if("string"==typeof e)return[{exec:e}];if(Array.isArray(e))return e.length?e.every(e=>"string"==typeof e)?[{exec:e}]:e.filter(e=>O(e)&&("string"==typeof e.exec||Array.isArray(e.exec))).slice(0,8):[];if(O(e)){const t=e;if("string"==typeof t.exec||Array.isArray(t.exec))return[t]}return[]},o="collection"===t?r.collectionPreRequest??r.preRequest??r.prerequest:r.preRequest??r.prerequest,s="collection"===t?r.collectionTest??r.test??r.tests:r.test??r.tests;return{pre:n(o).slice(0,8),test:n(s).slice(0,8)}}var it={id:"protokit-capture",exec:["try {"," pm.environment.set('__lastStatus', String(pm.response.code));"," var contentType = pm.response.headers.get('content-type') || '';"," if (/json/i.test(contentType)) {"," var text = pm.response.text() || '';"," if (text.length > 20000) { text = text.slice(0, 20000); }"," pm.environment.set('__lastBody', text);"," }","} catch (error) {"," console.warn('protokit capture failed: ' + (error && error.message));","}"]},at=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"]),ct=/^(accept|content-type|authorization)$/i,lt=0;function ut(e){lt=(lt+1)%65535;const t=Date.now().toString(36),r=Math.floor(65535*Math.random()).toString(36);return`${e}-${t}-${lt.toString(36)}${r}`}function dt(e){return"string"==typeof e&&e.length?e:void 0}function pt(e){const t=e.toLowerCase();return"application/json"===t?0:t.includes("json-seq")||t.includes("ndjson")?40:t.endsWith("+json")?10:t.includes("json")?20:t.includes("x-www-form-urlencoded")?30:t.includes("multipart/form-data")?35:50}function ft(e){if(null==e)return"";const t=typeof e;if("string"===t)return e;if("number"===t||"boolean"===t||"bigint"===t)return String(e);if("object"===t)try{const t=JSON.stringify(e);return"string"==typeof t?t:""}catch{return""}return""}var mt={spaceDelimited:" ",pipeDelimited:"|",form:",",simple:","};function ht(e,t){const r=String(e.name),n=dt(e.style)??"form",o="boolean"==typeof e.explode?e.explode:"form"===n||"deepObject"===n;if(Array.isArray(t)){if(!t.length)return[{key:r,value:""}];if(o&&"deepObject"!==n)return t.map(e=>({key:r,value:ft(e)}));if("deepObject"===n)return t.map((e,t)=>({key:`${r}[${t}]`,value:ft(e)}));const e=mt[n]??",";return[{key:r,value:t.map(ft).join(e)}]}if(O(t)){const e=Object.entries(t);return e.length?"deepObject"===n?e.map(([e,t])=>({key:`${r}[${e}]`,value:ft(t)})):o?e.map(([e,t])=>({key:e,value:ft(t)})):[{key:r,value:e.flatMap(([e,t])=>[e,ft(t)]).join(",")}]:[{key:r,value:""}]}return[{key:r,value:ft(t)}]}function yt(e,t){const r=dt(e.style)??"simple",n=!0===e.explode,o=String(e.name),s=(e,t)=>e.map(ft).join(t);if("label"===r){if(Array.isArray(t))return`.${s(t,n?".":",")}`;if(O(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`.${e}=${ft(t)}`).join(""):`.${e.flatMap(([e,t])=>[e,ft(t)]).join(",")}`}return`.${ft(t)}`}if("matrix"===r){if(Array.isArray(t))return n?t.map(e=>`;${o}=${ft(e)}`).join(""):`;${o}=${s(t,",")}`;if(O(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`;${e}=${ft(t)}`).join(""):`;${o}=${e.flatMap(([e,t])=>[e,ft(t)]).join(",")}`}return`;${o}=${ft(t)}`}if(Array.isArray(t))return s(t,",");if(O(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`${e}=${ft(t)}`).join(","):e.flatMap(([e,t])=>[e,ft(t)]).join(",")}return ft(t)}function gt(e,t){const r=!0===e.explode;if(Array.isArray(t))return t.map(ft).join(",");if(O(t)){const e=Object.entries(t);return r?e.map(([e,t])=>`${e}=${ft(t)}`).join(","):e.flatMap(([e,t])=>[e,ft(t)]).join(",")}return ft(t)}function vt(e,t){const r=String(e.name),n=!0===e.explode;if(Array.isArray(t))return n?t.map(e=>[r,ft(e)]):[[r,t.map(ft).join(",")]];if(O(t)){const e=Object.entries(t);return n?e.map(([e,t])=>[e,ft(t)]):[[r,e.flatMap(([e,t])=>[e,ft(t)]).join(",")]]}return[[r,ft(t)]]}function bt(e,t,r){const n=r.values??{},o=[],s=We(e.servers,r),i=Array.isArray(e.parameters)?e.parameters:[],a=e=>i.filter(t=>t&&"object"==typeof t&&t.in===e&&"string"==typeof t.name),{contentType:c,undeclared:l}=function(e,t){const r=e?.requestBody?.content,n=O(r)?Object.keys(r):[],o=dt(t.contentType);if(o){const e=o.split(";")[0].trim().toLowerCase(),t=n.some(t=>t.toLowerCase()===e);return{contentType:o,undeclared:n.length>0&&!t}}return n.length?{contentType:n.slice().sort((e,t)=>pt(e)-pt(t))[0],undeclared:!1}:{contentType:void 0,undeclared:!1}}(e.operation,n);l&&c&&o.push(`Content type "${c}" is not declared by the operation's requestBody.`);const u=[];for(const e of a("path")){const t=n.path?.[e.name],r=null!=t,s=yt(e,r?t:Ne(e.schema??{}));s?r||o.push(`Path parameter "${e.name}" was synthesized from its schema as "${s}".`):o.push(`Path parameter "${e.name}" resolved to an empty value; pass values.path["${e.name}"] to control it.`),u.push({key:e.name,value:s})}const d=String(e.path).replace(/^\//,"").split("/").filter(e=>e.length>0).map(e=>e.replace(/\{([^}]+)\}/g,(e,t)=>`:${t}`)),p=[],f=new Set;for(const e of a("query")){f.add(e.name);const t=O(n.query)&&Object.prototype.hasOwnProperty.call(n.query,e.name),r=t?n.query[e.name]:void 0;if(t&&void 0!==r)p.push(...ht(e,null===r?"":r));else{if(!0===e.required){const t=Ne(e.schema??{});p.push(...ht(e,null===t?"":t));continue}!0!==e.allowEmptyValue?p.push({key:e.name,value:"",disabled:!0}):p.push({key:e.name,value:""})}}if(O(n.query))for(const[e,t]of Object.entries(n.query))if(!f.has(e)&&null!=t)if(Array.isArray(t))for(const r of t)p.push({key:e,value:ft(r)});else p.push({key:e,value:ft(t)});"string"==typeof n.querystring&&n.querystring.length&&p.push(...function(e){const t=[],r=e.replace(/^[?&]+/,"");if(!r)return t;for(const e of r.split("&")){if(!e)continue;const r=e.indexOf("=");r<0?t.push({key:e,value:"",__raw:!0}):t.push({key:e.slice(0,r),value:e.slice(r+1),__raw:!0})}return t}(n.querystring));const m=[],h=new Set,y=(e,t)=>{if(!e)return;const r=e.toLowerCase();h.has(r)||(h.add(r),m.push({key:e,value:t}))};if(O(n.header))for(const[e,t]of Object.entries(n.header))null!=t&&y(e,ft(t));for(const e of a("header")){if(ct.test(e.name))continue;if(!0!==e.required)continue;const t=Ne(e.schema??{});if(null==t)continue;const r=gt(e,t);""!==r&&y(e.name,r)}c&&y("Content-Type",c);const g=tt(e.operation);g&&y("Accept",g);const v=a("cookie"),b=[],w=(e,t)=>{b.push(`${e}=${encodeURIComponent(t)}`)};for(const e of v){const t=n.cookie?.[e.name],r=null!=t?t:!0===e.required?Ne(e.schema??{}):void 0;if(null!=r)for(const[t,n]of vt(e,r))w(t,n)}if(O(n.cookie))for(const[e,t]of Object.entries(n.cookie))v.some(t=>t.name===e)||null!=t&&w(e,ft(t));b.length&&y("Cookie",b.join("; "));const S=function(e,t,r,n){const o=e?.requestBody,s=void 0!==t.body;if(!o&&!s)return;const i=r??(s?"application/json":void 0);if(!i)return void(o&&n.push("The operation declares a requestBody but no media type could be resolved; no body was sent."));!r&&s&&n.push("No request media type was declared; defaulted to application/json for the supplied body.");const a=function(e,t){const r=e?.content;if(!O(r))return;if(O(r[t]))return r[t].schema;const n=t.split(";")[0].trim().toLowerCase();for(const e of Object.keys(r)){if(e.toLowerCase()!==n)continue;const t=r[e];if(O(t))return t.schema}}(o,i),c=s?t.body:Ne(a??{}),l=i.split(";")[0].trim().toLowerCase(),u=l.includes("json-seq")||l.includes("ndjson");if(!u&&("application/json"===l||l.endsWith("+json")||l.includes("json"))){let e;if("string"==typeof c)e=c;else if(void 0===c)e="{}";else try{e=JSON.stringify(c,null,2)??"null"}catch{n.push("The request body could not be serialized as JSON."),e="{}"}return{mode:"raw",raw:e,options:{raw:{language:"json"}}}}if(l.includes("x-www-form-urlencoded"))return{mode:"urlencoded",urlencoded:wt(c).map(([e,t])=>({key:e,value:ft(t),type:"text"}))};if(l.includes("multipart/form-data"))return{mode:"formdata",formdata:wt(c).map(([e,t])=>O(t)&&"__file"in t?{key:e,type:"file",src:String(t.__file)}:{key:e,type:"text",value:ft(t)})};if(l.includes("xml")||l.startsWith("text/")||u)return{mode:"raw",raw:"string"==typeof c?c:ft(c),...l.includes("xml")?{options:{raw:{language:"xml"}}}:{}};return{mode:"raw",raw:"string"==typeof c?c:ft(c)}}(e.operation,n,c,o),$=p.filter(e=>!e.disabled).map(e=>e.__raw?`${e.key}${""===e.value?"":`=${e.value}`}`:`${encodeURIComponent(e.key)}=${encodeURIComponent(e.value)}`).join("&");let E=`{{baseUrl}}/${d.join("/")}`;$&&(E+=`?${$}`);const A={raw:E,host:["{{baseUrl}}"],path:d};p.length&&(A.query=p.map(({__raw:e,...t})=>t)),u.length&&(A.variable=u);const x=String(e.method).toUpperCase(),T={method:x,header:m,url:A},k=dt(e.operation?.description)??dt(e.operation?.summary);k&&(T.description=k),S&&(T.body=S);const _=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:st(e,"item");return[...ot("prerequest","item",[...r.pre,...nt(t?.preRequest)]),...ot("test","item",[...r.test,...nt(t?.test)])]}(e.operation,r.scripts)??[],P=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:st(e,"collection");return[...ot("prerequest","collection",[...r.pre,...nt(t?.collectionPreRequest)]),...ot("test","collection",[...r.test,...nt(t?.collectionTest)])]}(t,r.scripts)??[],M=function(e){if(e&&"object"==typeof e&&"none"!==e.type)switch(e.type){case"bearer":return{type:"bearer",bearer:[{key:"token",value:e.token??"",type:"string"}]};case"basic":return{type:"basic",basic:[{key:"username",value:e.username??"",type:"string"},{key:"password",value:e.password??"",type:"string"}]};case"apikey":return{type:"apikey",apikey:[{key:"key",value:e.key??"X-API-Key",type:"string"},{key:"value",value:e.value??"",type:"string"},{key:"in",value:"query"===e.in?"query":"header",type:"string"}]};default:return}}(r.auth),D=dt(e.operation?.operationId)??`${x} ${e.path}`,C={info:{_postman_id:ut("protokit"),name:(j=t?.info?.title,I="OpenAPI Debug Session","string"==typeof j&&j.trim()?j:I),schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[{name:D,..._.length?{event:_}:{},request:T,response:[]}],variable:[{key:"baseUrl",value:s}]};var j,I;const N=dt(t?.info?.description);return N&&(C.info.description=N),M&&(C.auth=M),P.length&&(C.event=P),{collection:C,baseUrl:s,contentType:c,isCustomMethod:!at.has(x),warnings:o}}function wt(e){return O(e)?Object.entries(e):[]}var St=c(require("http"),1),$t=c(require("https"),1),Et=c(require("postman-runtime"),1),At=c(require("postman-collection"),1),xt=new Set(["[DONE]","DONE","[done]","done"]),Tt=/\r\n\r\n|\n\n|\r\r/,kt=/^\d+$/;function Ot(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var _t=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=Ot(e.maxBufferChars,4194304),this.maxEventChars=Ot(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=Tt.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 n=this.parseBlock(r);n&&e.push(n)}return e}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],n={data:"",receivedAt:Date.now(),direction:"in"};let o=!1,s=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(o=!0,i)break;const e=this.maxEventChars-s;c.length>e?(r.push(c.slice(0,Math.max(0,e))),i=!0,this.overflowed=!0,this.droppedEvents+=1):(r.push(c),s+=c.length+1);break}case"event":n.event=c,o=!0;break;case"id":c.includes("\0")||(n.id=c,this.lastEventId=c),o=!0;break;case"retry":if(kt.test(c)&&c.length<=15){const e=Number(c);Number.isSafeInteger(e)&&(n.retry=e)}o=!0}}if(!o)return null;if(n.data=r.join("\n"),void 0===n.id&&this.inheritEventId&&void 0!==this.lastEventId&&(n.id=this.lastEventId),!i){const e=n.data.trim();if(e&&!xt.has(e)&&function(e){const t=e.charCodeAt(0);return 123===t||91===t||34===t}(e))try{n.parsed=JSON.parse(n.data)}catch{}}return this.sequence+=1,n}};var Pt=c(require("postman-collection"),1),Mt=864e5;function Dt(e){if(null==e)return;const t="number"==typeof e?e:Number(e);return!Number.isFinite(t)||t<0?void 0:Math.min(Math.floor(t),Mt)}function Ct(e,t=[]){const r=[];for(const[t,n]of Object.entries(e??{}))"string"==typeof t&&t&&r.push({key:t,value:null==n?"":String(n)});r.push(...t);const n=new Map;for(const e of r)n.set(e.key,e);return new Pt.default.VariableScope({values:Array.from(n.values())})}function jt(e){if(!O(e))return;if("maxResponseSize"in e){const t=e.maxResponseSize;if(null!=t){const e="number"==typeof t?t:Number(t);if(!Number.isFinite(e)||e<=0)throw y("BAD_RUN_OPTIONS","runner.requester.maxResponseSize must be a positive number of bytes. Omit it to leave the response size unbounded.",{provided:t})}}if("maxRedirects"in e){const t=e.maxRedirects;if(null!=t){const e="number"==typeof t?t:Number(t);if(!Number.isInteger(e)||e<0)throw y("BAD_RUN_OPTIONS","runner.requester.maxRedirects must be a non-negative integer.",{provided:t})}}const t=e.protocolVersion;if(void 0!==t&&"http1"!==t&&"http2"!==t&&"auto"!==t)throw y("BAD_RUN_OPTIONS",'runner.requester.protocolVersion must be "http1", "http2" or "auto".',{provided:t})}function It(e){const t={},r="function"==typeof e?.all?e.all():[];for(const e of r??[]){if(!e||e.disabled)continue;const r=String(e.key??"");r&&(t[r]=t[r]?`${t[r]}, ${String(e.value??"")}`:String(e.value??""))}return t}function Nt(e){if(e)try{const t=e.values??e,r="function"==typeof t.toJSON?t.toJSON():t;if(!Array.isArray(r))return;const n={};for(const e of r){if(!e||!1===e.enabled||null==e.key)continue;const t=String(e.key);"__proto__"!==t&&"constructor"!==t&&(n[t]=null==e.value?"":String(e.value))}return n}catch{return}}function Bt(e){const t=e?.body;if(t)try{if("raw"===t.mode)return t.raw;if("function"==typeof t.toString){return t.toString()||void 0}return $(t)}catch{return}}function Rt(e,t,r){const n=_(),o=Date.now();let s,i,a,c="initialized",l=e.streamingHint,u=!1;const d=M(t.maxEvents,100),p=M(t.maxStreamMs,3e4),f=M(t.runner?.timeout?.request??t.timeout,3e4),m="number"==typeof t.maxResponseSize?t.maxResponseSize:void 0,h=new _t({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId}),g=[],b=[];let w=0,S=!1;const E={prerequest:[],test:[],assertions:[],console:[],passed:!0,skipped:!1},A=[];let x=null,k=null,O=null,C=null,j=null,I=null;const N=function(e){const t=e.runner?.requester;return!(!t?.agents&&!t?.agent)}(t)?null:function(){try{const e=new Set,t=t=>{if(!t||"function"!=typeof t.destroy)return t;e.add(t);const r=()=>e.delete(t);return t.once?.("close",r),t.once?.("error",r),t},r=new St.default.Agent({keepAlive:!1}),n=new $t.default.Agent({keepAlive:!1});return r.createConnection=function(e,r){return t(St.default.Agent.prototype.createConnection.call(this,e,r))},n.createConnection=function(e,r){return t($t.default.Agent.prototype.createConnection.call(this,e,r))},{agents:{http:r,https:n},destroyAll(){let t=0;for(const r of Array.from(e))try{r.destroy(),t+=1}catch{}e.clear();try{r.destroy(),n.destroy()}catch{}return t}}}catch{return null}}(),B=(e,t)=>{E.console.push({level:e,messages:[t],at:Date.now()})},R=e=>(e&&"function"==typeof e.unref&&e.unref(),e),q=(e,t)=>{if("stopping"===c||"finalized"===c)return;c="stopping",i=e,u=!0,B("debug",`[protokit] stopping run: ${t??e}`);try{k?.abort?.()}catch{}const r=N?.destroyAll()??0;r>0&&B("debug",`[protokit] destroyed ${r} open socket(s)`),j=R(setTimeout(()=>{"finalized"!==c&&(B("warn","[protokit] runtime did not report completion after stop"),F())},250))},L=(e,t)=>({target:t,scriptId:e?.script?.id??e?.event?.script?.id,error:e?.error?{name:e.error.name,message:e.error.message}:void 0,environment:Nt(e?.result?.environment),globals:Nt(e?.result?.globals),return:e?.result?.return}),F=()=>{if("finalized"===c)return;if(c="finalized",O=P(O),C=P(C),j=P(j),I?.(),I=null,N?.destroyAll(),l){for(const e of h.flush())g.length<d?(g.push(e),qt(()=>t.onEvent?.(e))):u=!0;h.truncated&&(u=!0)}const e=Date.now();if(x)l&&(x.response.events=g),u&&(x.response.truncated=!0),x.response.timings={...x.response.timings,startedAt:o,endedAt:e,durationMs:e-o,firstByteMs:s?s-o:void 0,...void 0!==a?{networkDurationMs:a}:{}};else{const t=!!i&&g.length>0;x={protocol:l?"sse":"http",request:{method:"",url:"",headers:{}},response:{status:t?200:0,statusText:t?"Stream sampling stopped":"No response received",headers:{},contentType:l?"text/event-stream":void 0,...l?{events:g}:{},timings:{startedAt:o,endedAt:e,durationMs:e-o,firstByteMs:s?s-o:void 0},sizeBytes:w,...u?{truncated:!0}:{}},...t?{}:{error:{message:"aborted"===i?"Run aborted before a response was received":"Runner finished without a response",code:i}}}}i&&(x.response.stopReason=i),h.droppedEvents&&(x.response.droppedEvents=h.droppedEvents),x.scripts=E,n.resolve(x)};if(r?.signal){const e=r.signal;if(e.aborted)return q("aborted","signal already aborted"),F(),n.promise;const t=()=>q("aborted","caller aborted the request");e.addEventListener("abort",t,{once:!0}),I=()=>e.removeEventListener("abort",t)}C=R(setTimeout(()=>{if("finalized"!==c){B("error","[protokit] hard timeout reached, forcing completion"),i??="hardTimeout",u=!0;try{k?.abort?.()}catch{}N?.destroyAll(),F()}},f+p+3e4));const U=(e,t,r)=>(c="finalized",C=P(C),I?.(),N?.destroyAll(),Promise.reject(y(e,t,r)));let z,V,G;try{z=new At.default.Collection($(e.collectionJson))}catch(e){return U("BAD_COLLECTION",`Failed to construct collection: ${v(e).message}`,e)}try{V=function(e,t){if(!e||"object"!=typeof e)throw y("BAD_RUN_OPTIONS","send options are required");jt(e.runner?.requester);const r=Dt(e.runner?.timeout?.request)??Dt(e.timeout)??3e4,n=t.streaming?Dt(e.maxStreamMs)??3e4:0,o=T({iterationCount:1,stopOnError:!1,abortOnError:!1,stopOnFailure:!1,abortOnFailure:!1,timeout:{request:r,script:Dt(e.runner?.timeout?.script)??15e3,global:0===r?0:Math.min(r+n+15e3,Mt)},delay:{item:0,iteration:0},script:{serializeLogs:!1},ignoreProxyEnvironmentVariables:!1,requester:{strictSSL:!0,followRedirects:!0,followOriginalHttpMethod:!1,maxRedirects:10,useWhatWGUrlParser:!0,removeRefererHeaderOnRedirect:!1,insecureHTTPParser:!1,timings:!0,verbose:!0,implicitCacheControl:!0,implicitTraceHeader:!0,disableCookies:!1,protocolVersion:"http1",maxInvokableNestedRequests:5,encoding:null}},e.runner??{});jt(o.requester),o.environment||(o.environment=Ct(e.variables,[{key:"baseUrl",value:t.baseUrl}])),!o.globals&&e.globals&&(o.globals=Ct(e.globals)),!o.localVariables&&e.localVariables&&(o.localVariables=Ct(e.localVariables)),Array.isArray(o.data)&&o.data.length&&void 0===e.runner?.iterationCount&&(o.iterationCount=o.data.length);const s=Number(o.iterationCount);if(!Number.isInteger(s)||s<1)throw y("BAD_RUN_OPTIONS","runner.iterationCount must be an integer of at least 1.",{provided:o.iterationCount});return o}(t,{baseUrl:e.baseUrl,streaming:e.streamingHint}),N&&(V.requester={...V.requester??{},agents:N.agents})}catch(e){return U("BAD_RUN_OPTIONS",`Failed to build runtime options: ${v(e).message}`,e)}try{G=new Et.default.Runner}catch(e){return U("RUNTIME_INIT",`Failed to create runner: ${v(e).message}`,e)}function W(e){let r;try{r=h.push(e)}catch(e){return void B("error",`[protokit] SSE parse failure: ${v(e).message}`)}for(const e of r){if(g.length>=d)return u=!0,void q("maxEvents",`maxEvents (${d}) reached`);if(g.push(e),qt(()=>t.onEvent?.(e)),g.length>=d)return void q("maxEvents",`maxEvents (${d}) reached`)}}return G.run(z,V,(r,d)=>{if(r)return c="finalized",C=P(C),I?.(),N?.destroyAll(),void n.reject(y("RUNTIME_INIT",r.message??"Runner initialization failed",r));if(k=d,"stopping"===c){try{d.abort?.()}catch{}N?.destroyAll()}d.start({console(e,r,...n){const o={level:"string"==typeof r?r:"log",messages:n,at:Date.now()};E.console.push(o),qt(()=>t.onConsole?.(o))},assertion(e,r){for(const e of r??[]){const r={name:e?.name??"assertion",passed:!e?.error&&!e?.skipped,skipped:!!e?.skipped,index:"number"==typeof e?.index?e.index:0,error:e?.error?{name:e.error.name,message:e.error.message??String(e.error),stack:e.error.stack}:void 0};r.passed||r.skipped||(E.passed=!1),E.assertions.push(r),qt(()=>t.onAssertion?.(r))}},prerequest(e,t,r){for(const e of r??[])E.prerequest.push(L(e,"prerequest"))},test(e,t,r){for(const e of r??[])E.test.push(L(e,"test"))},item(e,t,r,n,o){o?.isSkipped&&(E.skipped=!0)},responseStart(r,n,o){"initialized"===c&&(c="headers"),s??=Date.now();const i=Lt(o,"content-type");(Ze(i)||et(i))&&(l=!0),qt(()=>t.onResponseStart?.({status:o?.code??0,headers:It(o?.headers),contentType:i,streaming:l,protocol:l?"sse":"http",url:e.baseUrl})),l&&("headers"===c&&(c="streaming"),O||(O=R(setTimeout(()=>q("maxStreamMs",`maxStreamMs (${p}ms) reached`),p))))},responseData(e,t){if("finalized"===c||null==t)return;let r;try{r=Buffer.isBuffer(t)?t:Buffer.from(t)}catch{return}if(S=!0,w+=r.length,void 0!==m&&w>m&&"stopping"!==c)return l&&W(r),void q("maxResponseSize",`maxResponseSize (${m} bytes) exceeded`);l?W(r):b.push(r)},request(e,t,r,n,d,p){const f=Date.now(),m={method:n?.method??"",url:Ut(n),headers:It(n?.headers),body:Bt(n)};"number"==typeof r?.responseTime&&(a=r.responseTime);if(e&&!("stopping"===c||!!i))return void(x={protocol:l?"sse":"http",request:m,response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:o,endedAt:f,durationMs:f-o,firstByteMs:s?s-o:void 0,...void 0!==a?{networkDurationMs:a}:{}},sizeBytes:w},error:v(e),replays:A});e&&B("debug",`[protokit] transport closed by sampler: ${v(e).message}`);const h=Lt(r,"content-type");let y,$;(Ze(h)||et(h))&&(l=!0);let E=0;if(!l){const e=b.length?Buffer.concat(b):function(e){if(!e)return Buffer.alloc(0);if(Buffer.isBuffer(e))return e;try{return Buffer.from(e)}catch{return Buffer.alloc(0)}}(r?.stream);E=e.length,y=function(e){const t=Math.min(e.length,1024);for(let r=0;r<t;r+=1)if(0===e[r])return!0;return!1}(e)?void 0:e.toString("utf8"),$=D(y,h)}x={protocol:l?"sse":"http",request:m,response:{status:"number"==typeof r?.code?r.code:0,statusText:Ft(r),headers:It(r?.headers),contentType:h,...l?{streaming:!0,events:g,body:Object.assign({},...g.map(e=>e.parsed))}:{body:$,text:y},timings:{startedAt:o,endedAt:f,durationMs:f-o,firstByteMs:s?s-o:void 0,...void 0!==a?{networkDurationMs:a}:{}},sizeBytes:S?w:E,...u?{truncated:!0}:{}},cookies:Array.isArray(p)?p.map(e=>({name:String(e?.name??""),value:String(e?.value??""),domain:e?.domain,path:e?.path})):[],replays:A}},io(e,t,r,n,o){"http"===r?.type&&r.source&&"collection"!==r.source&&A.push({url:Ut(o),method:o?.method??"",status:"number"==typeof n?.code?n.code:0,reason:String(r.source)})},exception(e,t){B("error",`[exception] ${v(t).message}`)},done(e){if(e&&!x&&!(!!i||"stopping"===c))return c="finalized",O=P(O),C=P(C),j=P(j),I?.(),N?.destroyAll(),void n.reject(y("RUNTIME_RUN",e.message??"Run failed",e));F()}})}),n.promise}function qt(e){try{e()}catch{}}function Lt(e,t){try{const r=e?.headers?.get?.(t);return null==r?void 0:String(r)}catch{return}}function Ft(e){try{return String("function"==typeof e?.reason?e.reason()??"":e?.status??"")}catch{return""}}function Ut(e){try{return"function"==typeof e?.url?.toString?e.url.toString():""}catch{return""}}var zt=class{name="http";supports(e){const t=e.located.operation?.["x-protocol"];return"string"==typeof t&&"http"!==t&&"sse"!==t?0:1}plan(e){const t=bt(e.located,e.spec,e.options);return{...t,environment:Ye(`${e.spec?.info?.title??"API"} Environment`,t.baseUrl,e.options.variables),streaming:Xe(e.located.operation,e.options.values)}}execute(e,t,r){return Rt({collectionJson:e.collection,baseUrl:e.baseUrl,streamingHint:e.streaming},t,r)}};var Vt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Gt(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(!Vt.test(t))throw y("BAD_WS_OPTIONS",`Invalid WebSocket subprotocol ${JSON.stringify(t)}: must be an HTTP token`);r.includes(t)||r.push(t)}}return r}function Wt(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(/^\/+/,"")}`}(We(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=A(a,i);const c=a.match(/\{\{([^}]+)\}\}/);if(c)throw y("BAD_WS_URL",`Unresolved variable {{${c[1]}}} in WebSocket URL: ${a}`);let l;try{l=new URL(a)}catch{throw y("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${a}`)}if("ws:"!==l.protocol&&"wss:"!==l.protocol)throw y("BAD_WS_URL",`WebSocket URL must use ws: or wss:, received ${l.protocol}${a}`);for(const[e,t]of Object.entries(r.values?.query??{}))if(null!=t)if(Array.isArray(t)){l.searchParams.delete(e);for(const r of t)null!=r&&l.searchParams.append(e,String(r))}else l.searchParams.set(e,String(t));"apikey"===r.auth?.type&&"query"===r.auth.in&&l.searchParams.set(r.auth.key??"api_key",r.auth.value??""),a=l.toString();const u={},d=e=>{if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(u[t]=A(String(r),i))};d(r.values?.header),d(s.headers),d(n.headers);const p=r.auth;if(p&&"none"!==p.type&&!Object.keys(u).some(e=>"authorization"===e.toLowerCase()))if("bearer"===p.type)u.Authorization=`Bearer ${p.token??""}`;else if("basic"===p.type){const e=`${p.username??""}:${p.password??""}`;u.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===p.type&&"header"===(p.in??"header")&&(u[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(u))t.toLowerCase()===e&&delete u[t];const f=n.send??s.send??[],m=(Array.isArray(f)?f:[f]).map(e=>function(e,t){if(null==e)return null;if("string"==typeof e)return A(e,t);if(e instanceof Uint8Array)return e;if(Buffer.isBuffer(e))return new Uint8Array(e);try{return A(JSON.stringify(e),t)}catch{return null}}(e,i)).filter(e=>null!==e),h=n.keepAlive??s.keepAlive;return{url:a,subprotocols:Gt(n.subprotocols??s.subprotocols),headers:u,send:m,sendDelayMs:Jt(n.sendDelayMs,0,"websocket.sendDelayMs"),idleTimeoutMs:Jt(n.idleTimeoutMs,0,"websocket.idleTimeoutMs"),maxMessages:Ht(n.maxMessages??r.maxEvents,100,"websocket.maxMessages"),maxSessionMs:Ht(n.maxSessionMs??r.maxStreamMs,3e4,"websocket.maxSessionMs"),keepAlive:h?{intervalMs:Ht(h.intervalMs,15e3,"websocket.keepAlive.intervalMs"),payload:String(h.payload??"ping")}:void 0,closeCode:Yt(n.closeCode),closeReason:String(n.closeReason??"Client finished sampling"),closeTimeoutMs:Ht(n.closeTimeoutMs,3e3,"websocket.closeTimeoutMs"),rejectUnauthorized:!1!==n.rejectUnauthorized,maxPayloadBytes:Ht(n.maxPayloadBytes,262144,"websocket.maxPayloadBytes"),clientOptions:n.clientOptions&&"object"==typeof n.clientOptions?{...n.clientOptions}:{}}}function Jt(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<0)throw y("BAD_WS_OPTIONS",`${r} must be a non-negative finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function Ht(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<=0)throw y("BAD_WS_OPTIONS",`${r} must be a positive finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function Yt(e){if(null==e)return 1e3;const t=Number(e);if(1e3===t||Number.isInteger(t)&&t>=3e3&&t<=4999)return t;throw y("BAD_WS_OPTIONS",`websocket.closeCode must be 1000 or within 3000-4999, received ${JSON.stringify(e)}`)}var Kt=c(require("ws"),1),Qt=new Set([1e3,1001,1005]);function Xt(e,t,r){const n=_(),o=Date.now();let s,i,a,c="connecting",l=0,u=0,d=0,p=!1,f=0,m=!1,h=!1;const y=[],g={};let b,w,S=0,$=null,E=null,A=null,x=null;const T=[];let k=null,O=!1;const M=e=>(e&&"function"==typeof e.unref&&e.unref(),e),D=t=>{const r=Date.now(),n=!t&&S>0&&S<400,a={...g};var c,l;return b&&(c=a,l="sec-websocket-protocol",!Object.keys(c).some(e=>e.toLowerCase()===l))&&(a["sec-websocket-protocol"]=b),{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:S||(t?0:101),statusText:t?"WebSocket error":n?"Switching Protocols":"Connection closed",headers:a,contentType:m&&!h?"application/octet-stream":"application/json",events:y,timings:{startedAt:o,endedAt:r,durationMs:r-o,firstByteMs:s?s-o:void 0},sizeBytes:d,...p?{truncated:!0}:{},...i?{stopReason:i}:{},...f?{droppedEvents:f}:{}},...t?{error:t}:{}}},C=e=>{"finalized"!==c&&(c="finalized",(()=>{if($=P($),E=P(E),A=P(A),x){try{clearInterval(x)}catch{}x=null}for(const e of T.splice(0))P(e)})(),k?.(),k=null,n.resolve(D(e??w)))},j=(t,r)=>{if("closing"!==c&&"finalized"!==c){c="closing",i=t,p=!0;try{I&&I.readyState===Kt.default.OPEN?I.close(e.closeCode,Zt(Buffer.from(`${e.closeReason}: ${r}`,"utf8"),123)):I?.terminate?.()}catch{}A=M(setTimeout(()=>{try{I?.terminate?.()}catch{}C()},e.closeTimeoutMs))}};let I;try{I=new Kt.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(D(v(e)))}if(r?.signal??t.signal){const e=r?.signal??t.signal;if(e.aborted)j("aborted","signal already aborted");else{const t=()=>j("aborted","caller aborted the session");e.addEventListener("abort",t,{once:!0}),k=()=>e.removeEventListener("abort",t)}}const N=()=>{e.idleTimeoutMs&&(E=P(E),E=M(setTimeout(()=>j("idleTimeout",`no data frame within ${e.idleTimeoutMs}ms`),e.idleTimeoutMs)))},B=e=>{y.push(e);try{t.onEvent?.(e)}catch{}},R=e=>{for(const[t,r]of Object.entries(e?.headers??{}))g[t]=Array.isArray(r)?r.join(", "):String(r)};return I.on("upgrade",e=>{S=e?.statusCode??101,R(e)}),I.on("unexpected-response",(e,t)=>{S=t?.statusCode??0,R(t),w={message:`Handshake rejected with HTTP ${S}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}try{I.terminate()}catch{}C(w)}),I.on("open",()=>{if("connecting"===c){c="open",s=Date.now(),b=I.protocol||void 0,S||(S=101);try{t.onOpen?.({url:e.url,protocol:b,headers:g})}catch{}if(e.send.forEach((t,r)=>{const n=()=>{"open"===c&&I.readyState===Kt.default.OPEN&&I.send(t,e=>{e?w=w??v(e):(u+=1,B({id:String(u),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?er(t):void 0,receivedAt:Date.now(),direction:"out"}))})},o=e.sendDelayMs*r;o<=0?n():T.push(M(setTimeout(n,o)))}),e.keepAlive){const{intervalMs:t,payload:r}=e.keepAlive;x=M(setInterval(()=>{if("open"===c&&I.readyState===Kt.default.OPEN)if(O)j("idleTimeout",`keep-alive ping unanswered for ${t}ms`);else try{I.ping(r),O=!0}catch{}},t))}N()}}),I.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);d+=n.length,u+=1,l+=1,r?m=!0:h=!0;const o=n.length>e.maxPayloadBytes;o&&(p=!0,f+=1);const s=r?`<binary ${n.length} bytes>`:o?`${Zt(n,e.maxPayloadBytes)}...`:n.toString("utf8");B({id:String(u),event:r?"binary":"text",data:s,parsed:r||o?void 0:er(s),receivedAt:Date.now(),direction:"in"}),N(),l>=e.maxMessages&&j("maxEvents",`maxMessages (${e.maxMessages}) reached`)}),I.on("ping",e=>{"finalized"!==c&&(u+=1,B({id:String(u),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}))}),I.on("pong",()=>{O=!1}),I.on("error",e=>{"closing"!==c&&"finalized"!==c&&(w=w??v(e),I.readyState===Kt.default.CLOSED&&C(w))}),I.on("close",(e,t)=>{a=e;const r=t?.length?t.toString("utf8"):"";w||("closing"===c||!!i)||Qt.has(e)||(w={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),1009===e&&(p=!0,f+=1),C(w)}),$=M(setTimeout(()=>j("maxSessionMs",`maxSessionMs (${e.maxSessionMs}ms) reached`),e.maxSessionMs)),n.promise}function Zt(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 er(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}var tr=c(require("ws"),1);function rr(e){let t="idle";function r(e){t=e,n.setState(e)}const n=f("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 l(e){const{direction:t,receivedAt:r,event:o,data:s,parsed:i,code:a,reason:c,wasClean:l,protocol:u,extensions:d,statusCode:p,statusMessage:f,headers:m,error:h}=e,y={};void 0!==i&&(y.parsed=i),void 0!==a&&(y.code=a),void 0!==c&&(y.reason=c),void 0!==l&&(y.wasClean=l),void 0!==u&&(y.protocol=u),void 0!==d&&(y.extensions=d),void 0!==p&&(y.statusCode=p),void 0!==f&&(y.statusMessage=f),void 0!==m&&(y.headers=m),n.emit({direction:t,kind:o,at:r,state:n.state,data:s,meta:Object.keys(y).length?y:void 0,error:h})}function u(){if(!s||"open"!==t||s.readyState!==tr.default.OPEN)throw new Error("WebSocket session is not open");return s}function d(e){const t=C(e);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");a=c(),r("connecting"),await new Promise((n,a)=>{const c={headers:e.headers};void 0!==e.rejectUnauthorized&&(c.rejectUnauthorized=e.rejectUnauthorized);const u=e.subprotocols?.filter(Boolean)??[],p=u.length>0?new tr.default(e.url,u,c):new tr.default(e.url,c);s=p;let f,m,h=!1,y=!1;const g=()=>{f&&(clearTimeout(f),f=void 0),m?.(),m=void 0},v=e=>{h||(h=!0,g(),a(e))};if(f=setTimeout(()=>{const e=new Error(`WebSocket handshake timed out after ${o}ms`);r("error"),d(e),v(e);try{p.terminate()}catch{}},o),"function"==typeof f?.unref&&f.unref(),e.signal){const t=()=>{const e=new Error("WebSocket open aborted");r("closed"),d(e),v(e);try{p.terminate()}catch{}i()};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)=>{y=!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!==tr.default.CONNECTING&&p.readyState!==tr.default.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}),h||(h=!0,g(),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:D(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}),i(),h||y||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=u();if(void 0!==r.delayMs&&r.delayMs>0&&await N(r.delayMs,e.signal),e.signal?.aborted)throw new Error("WebSocket send aborted");let o,s,i,a;if(u(),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);o=e,s="binary",i=e.toString("base64")}else if("string"==typeof t)o=t,s="text",i=t,a=D(t);else{const e=JSON.stringify(t);if(void 0===e)throw new TypeError("WebSocket payload cannot be serialized");o=e,s="text",i=e,a=t}await new Promise((e,t)=>{n.send(o,{binary:"binary"===s},r=>{if(r)return d(r),void t(r);l({direction:"out",receivedAt:Date.now(),event:s,data:i,parsed:a}),e()})})},async close(e={}){if(!s)return r("closed"),void i();if("closed"!==t){if("closing"!==t)return r("closing"),s.readyState===tr.default.CONNECTING?(s.terminate(),void await a):s.readyState===tr.default.OPEN?(s.close(e.code??1e3,e.reason??"Closed"),void await a):void(s.readyState!==tr.default.CLOSING?(r("closed"),i()):await a);await a}else i()},async waitForClose(){await a}}}var nr=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=Wt(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 Xt(e.config,t,r)}};function or(e,t,r){const n=r.graphql??{},o=e.operation?.["x-graphql"],s=o&&"object"==typeof o?o:{},i={...r.variables??{}};let a;if(a=n.endpoint?n.endpoint:"string"==typeof s.endpoint&&s.endpoint?s.endpoint:We(e.servers,r),a=A(a,i),/\{\{[^}]+\}\}/.test(a))throw y("BAD_GRAPHQL_ENDPOINT",`Unresolved variable in GraphQL endpoint: ${a}`);try{const e=new URL(a);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw y("BAD_GRAPHQL_ENDPOINT",`GraphQL endpoint must be an absolute http(s) URL, received: ${a}`)}const c=n.query??s.query;if("string"!=typeof c||!c.trim())throw y("BAD_GRAPHQL_QUERY","No GraphQL query/mutation document was found. Provide options.graphql.query or declare it on the operation as x-graphql.query (see writeGraphQLOperations).");const l=n.operationName??("string"==typeof(u=s.operationName)&&u.length?u:void 0);var u;const d=O(s.variablesSchema)?Ne(s.variablesSchema):void 0,p=O(s.variables)?s.variables:void 0,f=O(r.values?.body)?r.values.body:void 0,m={...O(d)?d:{},...p??{},...f??{},...n.variables??{}},h={},g=e=>{if(O(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(h[t]=A(String(r),i))};g(r.values?.header),g(s.headers),g(n.headers),sr(h,"content-type")||n.useGet||(h["Content-Type"]="application/json"),sr(h,"accept")||(h.Accept="application/json, text/event-stream");const v=r.auth;if(v&&"none"!==v.type&&!sr(h,"authorization"))if("bearer"===v.type)h.Authorization=`Bearer ${v.token??""}`;else if("basic"===v.type){const e=`${v.username??""}:${v.password??""}`;h.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===v.type&&"header"===(v.in??"header")&&(h[v.key??"X-API-Key"]=v.value??"");return{endpoint:a,query:c,operationName:l,variables:m,headers:h,useGet:!0===n.useGet}}function sr(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}function ir(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}async function ar(e,t,r){const n=Date.now(),o=r?.signal??t.signal,s=e.useGet?function(e){const t=new URL(e.endpoint);return t.searchParams.set("query",e.query),e.operationName&&t.searchParams.set("operationName",e.operationName),Object.keys(e.variables).length&&t.searchParams.set("variables",JSON.stringify(e.variables)),t.toString()}(e):e.endpoint,i=e.useGet?void 0:JSON.stringify({query:e.query,variables:e.variables,...e.operationName?{operationName:e.operationName}:{}}),a="number"==typeof t.timeout&&t.timeout>0?t.timeout:3e4,c=new AbortController,l=()=>c.abort();o?.addEventListener("abort",l,{once:!0});const u=setTimeout(()=>c.abort(),a);let d;u.unref?.();try{d=await fetch(s,{method:e.useGet?"GET":"POST",headers:e.headers,body:i,signal:c.signal})}catch(t){clearTimeout(u),o?.removeEventListener("abort",l);const r=Date.now(),a=!0===o?.aborted;return{protocol:"http",request:{method:e.useGet?"GET":"POST",url:s,headers:e.headers,body:i},response:{status:0,statusText:a?"Aborted":"Request failed",headers:{},timings:{startedAt:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:a?{message:"GraphQL request aborted",code:"ABORTED"}:v(t)}}const p=Date.now(),f=d.headers.get("content-type")??void 0,m=!!f&&/text\/event-stream/i.test(f);let h,y,g,b,w=0;try{if(m&&d.body){const e=new _t({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId});g=[];const r="number"==typeof t.maxEvents&&t.maxEvents>0?t.maxEvents:100,n=d.body.getReader();for(;;){const{done:t,value:o}=await n.read();if(t)break;w+=o?.byteLength??0;for(const t of e.push(o))if(g.push(t),g.length>=r)break;if(g.length>=r){try{await n.cancel()}catch{}break}}for(const t of e.flush())g.length<r&&g.push(t)}else{const e=await d.text();if(w=e.length,y=e,f&&/json/i.test(f)&&e.trim())try{h=JSON.parse(e)}catch{}}}catch(e){b=v(e)}finally{clearTimeout(u),o?.removeEventListener("abort",l)}const S=Date.now();if(!b&&!m&&cr(h)){const e=void 0!==h.data&&null!==h.data,t=Array.isArray(h.errors)?h.errors:void 0;!e&&t?.length&&(b={message:t.map(e=>e?.message).filter(Boolean).join("; ")||"GraphQL request returned errors",code:"GRAPHQL_ERRORS"})}return b||d.ok||cr(h)||(b={message:`GraphQL endpoint responded HTTP ${d.status}`,code:String(d.status)}),{protocol:"http",request:{method:e.useGet?"GET":"POST",url:s,headers:e.headers,body:e.useGet?void 0:{query:e.query,variables:e.variables,operationName:e.operationName}},response:{status:d.status,statusText:d.statusText,headers:ir(d.headers),contentType:f,...m?{events:g}:{body:h,text:y},timings:{startedAt:n,endedAt:S,durationMs:S-n,firstByteMs:p-n},sizeBytes:w},...b?{error:b}:{}}}function cr(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var lr="\nquery IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types { ...FullType }\n }\n}\nfragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args { ...InputValue }\n type { ...TypeRef }\n isDeprecated\n deprecationReason\n }\n inputFields { ...InputValue }\n enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason }\n}\nfragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n}\nfragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType { kind name }\n }\n }\n }\n }\n }\n}\n".trim();async function ur(e,t={}){let r,n;try{r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...t.headers??{}},body:JSON.stringify({operationName:"IntrospectionQuery",query:lr}),signal:t.signal})}catch(e){throw y("GRAPHQL_INTROSPECTION_FAILED",`Could not reach GraphQL endpoint for introspection: ${e?.message??e}`,void 0,{cause:e})}try{n=await r.json()}catch(e){throw y("GRAPHQL_INTROSPECTION_FAILED",`Introspection response was not valid JSON (HTTP ${r.status})`,void 0,{cause:e})}if(!r.ok||!n?.data?.__schema){throw y("GRAPHQL_INTROSPECTION_FAILED",`Introspection failed: ${Array.isArray(n?.errors)&&n.errors.length?n.errors.map(e=>e?.message).filter(Boolean).join("; "):`HTTP ${r.status}`}. The server may have introspection disabled.`)}const o=n.data.__schema,s=new Map;for(const e of o.types??[])e?.name&&"string"==typeof e.name&&(e.name.startsWith("__")||s.set(e.name,e));return{schema:{queryType:o.queryType?.name??void 0,mutationType:o.mutationType?.name??void 0,subscriptionType:o.subscriptionType?.name??void 0,types:s},raw:o}}function dr(e){let t=e,r=!0,n=0,o=!1;for(;t;)if("NON_NULL"!==t.kind){if("LIST"!==t.kind)return 0===n&&(r=!o),{named:t.name??void 0,nullable:r,listDepth:n};n+=1,r=!o,o=!1,t=t.ofType??null}else o=!0,t=t.ofType??null;return{nullable:!0,listDepth:n}}var pr={ID:{type:"string"},String:{type:"string"},Int:{type:"integer"},Float:{type:"number"},Boolean:{type:"boolean"}};function fr(e,t,r){const{named:n,nullable:o,listDepth:s}=dr(e.type);let i;const a=n?t.types.get(n):void 0;if(n&&pr[n])i={...pr[n]};else if("ENUM"===a?.kind)i={type:"string",enum:(a.enumValues??[]).map(e=>e.name)};else if("INPUT_OBJECT"===a?.kind){const e={},n=[];for(const o of a.inputFields??[]){e[o.name]=fr(o,t,r);dr(o.type).nullable||null!=o.defaultValue||n.push(o.name)}i={type:"object",properties:e,...n.length?{required:n}:{}}}else n&&!pr[n]&&r.push(`Argument "${e.name}" has custom scalar type "${n}"; sampled as a string.`),i={type:"string"};for(let e=0;e<s;e+=1)i={type:"array",items:i};return o&&(i.nullable=!0),i}var mr=2;function hr(e,t,r,n){if(!e)return"__typename";const o=t.types.get(e);if(!o||!Array.isArray(o.fields)||!o.fields.length)return"__typename";if(n.has(e)||r<=0)return"__typename";n.add(e);const s=[];for(const e of o.fields){if(e.isDeprecated)continue;if((e.args??[]).some(e=>!dr(e.type).nullable))continue;const{named:o,listDepth:i}=dr(e.type),a=o?t.types.get(o):void 0;if(!a||"SCALAR"===a.kind||"ENUM"===a.kind||!!pr[o??""])s.push(e.name);else if("OBJECT"===a?.kind||"INTERFACE"===a?.kind||"UNION"===a?.kind){if(r<=1)continue;const i=hr(o,t,r-1,new Set(n));s.push(`${e.name} { ${i} }`)}if(s.length>=12)break}return s.length?s.join(" "):"__typename"}function yr(e,t,r){const n=[],o={},s=[],i=[],a=[];for(const e of t.args??[]){const{named:t,nullable:c,listDepth:l}=dr(e.type);let u=t??"String";for(let e=0;e<l;e+=1)u=`[${u}]`;c||(u+="!"),i.push(`$${e.name}: ${u}`),a.push(`${e.name}: $${e.name}`),o[e.name]=fr(e,r,n),c||null!=e.defaultValue||s.push(e.name)}const{named:c,listDepth:l}=dr(t.type),u=c?r.types.get(c):void 0,d=u&&("OBJECT"===u.kind||"INTERFACE"===u.kind||"UNION"===u.kind)?` { ${hr(c,r,mr,new Set)} }`:"",p=`${vr(e)}_${vr(t.name)}`,f=i.length?`(${i.join(", ")})`:"",m=a.length?`(${a.join(", ")})`:"",h=`${e} ${p}${f} {\n ${t.name}${m}${d}\n}`;return{operationType:e,fieldName:t.name,operationName:p,query:h,variablesSchema:{type:"object",properties:o,required:s},notes:n}}function gr(e){const t=[],r=[[e.queryType,"query"],[e.mutationType,"mutation"],[e.subscriptionType,"subscription"]];for(const[n,o]of r){if(!n)continue;const r=e.types.get(n);for(const n of r?.fields??[])t.push(yr(o,n,e))}return t}function vr(e){return e?e[0].toUpperCase()+e.slice(1):e}function br(e){return`/graphql/${e.operationType}/${e.fieldName}`}function wr(e,t,r,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw y("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,s=S(e);O(s.paths)||(s.paths={});for(const e of r){const r=br(e);!o&&O(s.paths[r])||(s.paths[r]={post:{operationId:`graphql_${e.operationType}_${e.fieldName}`,summary:`GraphQL ${e.operationType}: ${e.fieldName}`,"x-protocol":"graphql","x-graphql":{endpoint:t,operationType:e.operationType,operationName:e.operationName,query:e.query,variablesSchema:e.variablesSchema},requestBody:{required:e.variablesSchema.required.length>0,content:{"application/json":{schema:{type:"object",properties:e.variablesSchema.properties,required:e.variablesSchema.required}}}},responses:{200:{description:"GraphQL response envelope (data/errors)."}},...e.notes.length?{"x-graphql-notes":e.notes}:{}}})}return s}async function Sr(e,t,r={}){const{schema:n}=await ur(t,{headers:r.headers,signal:r.signal}),o=gr(n),s=o.flatMap(e=>e.notes.map(t=>`${e.operationType} ${e.fieldName}: ${t}`));o.length||s.push("Introspection succeeded but the schema declares no query, mutation or subscription fields.");return{spec:wr(e,t,o,r),operations:o,warnings:s}}var $r=class{name="graphql";supports(e){const t=e.located.operation??{};return"graphql"===t["x-protocol"]?20:(r=t["x-graphql"])&&"object"==typeof r&&!Array.isArray(r)||e.options.graphql?.query||e.options.graphql?.endpoint?15:"graphql"===e.located.pathItem?.["x-protocol"]?12:0;var r}plan(e){const t=or(e.located,e.spec,e.options),r=[{key:"graphqlEndpoint",value:t.endpoint,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).filter(([e])=>"graphqlEndpoint"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:I(e)?"secret":"default",enabled:!0}))];return{config:t,environment:{id:`protokit-graphql-env-${Date.now().toString(36)}-${(16777215*Math.random()|0).toString(36)}`,name:`${e.spec?.info?.title??"API"} GraphQL Environment`,values:r,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}}execute(e,t,r){return ar(e.config,t,r)}};var Er=new Set(["tools/call","resources/read","prompts/get","tools/list","resources/list","resources/templates/list","prompts/list"]);function Ar(e,t,r){const n=r.mcp??{},o=e.operation?.["x-mcp"],s=o&&"object"==typeof o?o:{},i={...r.variables??{}},a=n.transport??s.transport??"streamable-http";if("streamable-http"!==a&&"stdio"!==a)throw y("BAD_MCP_TRANSPORT",`Unsupported MCP transport: ${JSON.stringify(a)}`);const c=a;let l,u,d,p,f,m,h,g;if("streamable-http"===c){if(l=n.endpoint||("string"==typeof s.endpoint?s.endpoint:We(e.servers,r)),l=A(l,i),/\{\{[^}]+\}\}/.test(l))throw y("BAD_MCP_ENDPOINT",`Unresolved variable in MCP endpoint: ${l}`);try{const e=new URL(l);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw y("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${l}`)}}else{const e=n.command??s.command;if("string"!=typeof e||!e.trim())throw y("BAD_MCP_STDIO_COMMAND","MCP stdio transport requires command.");if(u=A(e.trim(),i),/\{\{[^}]+\}\}/.test(u))throw y("BAD_MCP_STDIO_COMMAND",`Unresolved variable in MCP command: ${u}`);const t=n.args??s.args;if(null!=t){if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw y("BAD_MCP_STDIO_CONFIG","MCP stdio args must be an array of strings.");d=t.map(e=>A(e,i))}const r=n.cwd??s.cwd;if(null!=r){if("string"!=typeof r||!r)throw y("BAD_MCP_STDIO_CONFIG","MCP stdio cwd must be a non-empty string.");p=A(r,i)}const o=n.env??s.env;if(null!=o){if(!O(o))throw y("BAD_MCP_STDIO_CONFIG","MCP stdio env must be an object.");f={};for(const[e,t]of Object.entries(o))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(f[e]=null==t?void 0:A(String(t),i))}for(const[e,t]of[["timeoutMs",n.timeoutMs??s.timeoutMs],["maxBufferBytes",n.maxBufferBytes??s.maxBufferBytes],["maxStderrBytes",n.maxStderrBytes??s.maxStderrBytes]])if(null!=t){if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw y("BAD_MCP_STDIO_CONFIG",`${e} must be a positive finite number.`);"timeoutMs"===e?m=t:"maxBufferBytes"===e?h=t:g=t}}const v=n.method??s.method;if("string"!=typeof v||!Er.has(v))throw y("BAD_MCP_METHOD",`options.mcp.method (or x-mcp.method) must be one of: ${Array.from(Er).join(", ")}. Received: ${JSON.stringify(v)}`);const b=n.name??s.name,w=O(s.arguments)?s.arguments:void 0,S=O(s.argumentsSchema)?s.argumentsSchema:void 0,$=S?Ne(S):void 0,E=O(r.values?.body)?r.values.body:void 0,x={...O($)?$:{},...w??{},...E??{},...n.arguments??{}};let T;if("tools/call"===v){if(!b)throw y("BAD_MCP_TARGET","tools/call requires options.mcp.name (or x-mcp.name).");T={name:b,arguments:x}}else if("prompts/get"===v){if(!b)throw y("BAD_MCP_TARGET","prompts/get requires options.mcp.name (or x-mcp.name).");T={name:b,arguments:x}}else if("resources/read"===v){const e=x.uri??s.uri??n.arguments?.uri;if("string"!=typeof e||!e)throw y("BAD_MCP_TARGET","resources/read requires a `uri` (via options.mcp.arguments.uri or x-mcp.uri).");T={uri:e}}else T=x;const k={"Content-Type":"application/json"},_=e=>{if(O(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(k[t]=A(String(r),i))};_(r.values?.header),_(s.headers),_(n.headers);const P=r.auth;if(P&&"none"!==P.type&&!function(e,t){const r=t.toLowerCase();return Object.keys(e).some(e=>e.toLowerCase()===r)}(k,"Authorization"))if("bearer"===P.type)k.Authorization=`Bearer ${P.token??""}`;else if("basic"===P.type){const e=`${P.username??""}:${P.password??""}`;k.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===P.type&&"header"===(P.in??"header")&&(k[P.key??"X-API-Key"]=P.value??"");return{transport:c,..."streamable-http"===c&&l?{endpoint:l}:{},..."stdio"===c&&u?{command:u,...d?{args:d}:{},...p?{cwd:p}:{},...f?{env:f}:{},...null!=m?{timeoutMs:m}:{},...null!=h?{maxBufferBytes:h}:{},...null!=g?{maxStderrBytes:g}:{}}:{},method:v,params:T,headers:k,sessionId:n.sessionId??xr(s.sessionId),protocolVersion:n.protocolVersion??xr(s.protocolVersion),clientInfo:n.clientInfo??{name:"protokit",version:"0.1.0"}}}function xr(e){return"string"==typeof e&&e.length?e:void 0}var Tr=0;function kr(){return Tr+=1}async function Or(e,t,r){const n=new AbortController;let o,s,i;if(r.signal){const e=()=>n.abort(r.signal?.reason);r.signal.aborted?e():(r.signal.addEventListener("abort",e,{once:!0}),o=()=>r.signal?.removeEventListener("abort",e))}"number"==typeof r.timeoutMs&&r.timeoutMs>0&&(s=setTimeout(()=>{n.abort(new Error(`MCP request timed out after ${r.timeoutMs}ms`))},r.timeoutMs),"function"==typeof s?.unref&&s.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:n.signal})}catch(e){throw y("MCP_TRANSPORT_FAILED",`Could not reach MCP endpoint: ${e?.message??e}`,void 0,{cause:e})}finally{s&&clearTimeout(s),o?.()}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),l=i.headers.get("content-type")??void 0,u=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:l,sessionId:u,sizeBytes:0,firstByteMs:a};if(l&&/text\/event-stream/i.test(l)&&i.body){const e=new _t,n=i.body.getReader();let o=0;const s="number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0?r.maxResponseBytes:0;let d;for(;;){const{done:r,value:i}=await n.read();if(r)break;if(o+=i?.byteLength??0,s>0&&o>s){try{await n.cancel()}catch{}throw y("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${s} 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 n.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:l,sessionId:u,sizeBytes:o,firstByteMs:a}}let d,p;try{if(d=await i.text(),"number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0&&d.length>r.maxResponseBytes)throw y("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:l,sessionId:u,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}return{message:p,status:i.status,statusText:i.statusText,headers:c,contentType:l,sessionId:u,rawText:d,sizeBytes:d?.length??0,firstByteMs:a}}function _r(e){return!!e&&"object"==typeof e&&O(e.error)}var Pr="2025-06-18",Mr=new Set([-32601,-32600]),Dr={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"},Cr=1e3;async function jr(e,t={}){const r=Date.now(),n=await Or(e,{jsonrpc:"2.0",id:kr(),method:"initialize",params:{protocolVersion:Pr,capabilities:t.capabilities??{},clientInfo:t.clientInfo??{name:"protokit",version:"0.1.0"}}},{headers:t.headers,signal:t.signal,startedAt:r});if(_r(n.message))throw y("MCP_INITIALIZE_FAILED",`initialize failed: ${n.message.error.message}`,n.message.error);if(!n.message?.result)throw y("MCP_INITIALIZE_FAILED",`initialize returned no result (HTTP ${n.status}). The endpoint may not speak MCP.`);const o=n.sessionId,s=n.message.result.protocolVersion;return await Or(e,{jsonrpc:"2.0",method:"notifications/initialized"},{headers:{...t.headers??{},...o?{"Mcp-Session-Id":o}:{}},signal:t.signal,startedAt:r,protocolVersion:s}),{sessionId:o,serverInfo:n.message.result.serverInfo,protocolVersion:s}}async function Ir(e,t,r,n){const o=Date.now(),s={...n.headers??{},...r.sessionId?{"Mcp-Session-Id":r.sessionId}:{}},i=Dr[t],a=[],c=new Set;let l,u=0;for(;;){const d=await Or(e,{jsonrpc:"2.0",id:kr(),method:t,params:l?{cursor:l}:{}},{headers:s,signal:n.signal,startedAt:o,protocolVersion:r.protocolVersion});if(_r(d.message)){const{code:e,message:r}=d.message.error;if(Mr.has(e))return;throw y("MCP_LIST_FAILED",`${t} failed (${e}): ${r}`,d.message.error)}const p=d.message?.result;if(!p){if(d.status>=400)throw y("MCP_LIST_FAILED",`${t} returned HTTP ${d.status} ${d.statusText} with no JSON-RPC result.`);return a}u+=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)||u>=Cr)break;c.add(f),l=f}return a}async function Nr(e,t={}){const r=await jr(e,t),n=[],o=[],s=await Ir(e,"tools/list",r,t);if(s)for(const e of s)e?.name&&o.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 n.push("Server does not implement tools/list.");const i=await Ir(e,"resources/list",r,t),a=await Ir(e,"resources/templates/list",r,t);for(const e of[...i??[],...a??[]])e?.name&&o.push({kind:"resource",name:e.name,title:e.title,uri:e.uri,uriTemplate:e.uriTemplate,description:e.description,mimeType:e.mimeType});i||a||n.push("Server does not implement resources/list or resources/templates/list.");const c=await Ir(e,"prompts/list",r,t);if(c)for(const e of c)e?.name&&o.push({kind:"prompt",name:e.name,title:e.title,description:e.description,arguments:e.arguments});else n.push("Server does not implement prompts/list.");return{serverInfo:r.serverInfo,protocolVersion:r.protocolVersion,sessionId:r.sessionId,capabilities:o,warnings:n}}var Br=require("child_process"),Rr=require("events"),qr=3e4,Lr=4194304,Fr=65536,Ur=1500,zr=2e3;function Vr(e){if(!e||"string"!=typeof e.command||!e.command.trim())throw y("BAD_MCP_STDIO_COMMAND","MCP stdio requires a non-empty command.");const t=Gr(e.timeoutMs,qr,"timeoutMs"),r=Gr(e.maxBufferBytes,Lr,"maxBufferBytes"),n=function(e){const t={...process.env};if(!e)return t;for(const[r,n]of Object.entries(e))void 0===n?delete t[r]:t[r]=n;return t}(e.env);let o;try{o=(0,Br.spawn)(e.command,e.args??[],{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(e){throw y("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${C(e)}`,void 0,{cause:e})}let s=!1,i=0,a="",c="";const l=new Map,u=(e,t)=>{l.get(e)===t&&l.delete(e),t.timer&&clearTimeout(t.timer),t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort)},d=e=>{for(const[t,r]of l)u(t,r),r.reject(e)},p=e=>{if(s)return;const t=y("MCP_STDIO_PROTOCOL_ERROR",e);d(t),m()};function f(e){if(s||o.stdin.destroyed||!o.stdin.writable)return Promise.reject(y("MCP_STDIO_CLOSED","MCP stdio process is closed."));let t;try{t=JSON.stringify(e)+"\n"}catch(e){return Promise.reject(y("MCP_STDIO_SERIALIZE_FAILED",`Could not serialize MCP JSON-RPC message: ${C(e)}`,void 0,{cause:e}))}return new Promise((e,r)=>{o.stdin.write(t,"utf8",t=>{t?r(t):e()})})}async function m(){if(s)return;if(s=!0,d(y("MCP_STDIO_CLOSED","MCP stdio process was closed.")),o.stdin.destroyed||o.stdin.end(),null!==o.exitCode||o.killed)return;try{o.kill("SIGTERM")}catch{return}const e=setTimeout(()=>{if(null===o.exitCode&&!o.killed)try{o.kill("SIGKILL")}catch{}},Ur);e.unref?.();try{await Promise.race([(0,Rr.once)(o,"exit").then(()=>{}),N(zr)])}finally{clearTimeout(e)}}return o.stdout.setEncoding("utf8"),o.stdout.on("data",e=>{if(!s)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 n;try{n=JSON.parse(t)}catch{return void p(`MCP stdio emitted invalid JSON-RPC: ${t.slice(0,512)}`)}if(!Wr(n))return void p("MCP stdio emitted an invalid JSON-RPC envelope.");if(void 0===n.id)continue;const o=l.get(n.id);o&&(u(n.id,o),void 0!==n.error?o.reject(y("MCP_RPC_ERROR",`${n.error.code}: ${n.error.message}`,n.error)):Object.prototype.hasOwnProperty.call(n,"result")?o.resolve(n.result):o.reject(y("MCP_STDIO_PROTOCOL_ERROR","MCP stdio response contained neither result nor error.")))}}),o.stderr.setEncoding("utf8"),o.stderr.on("data",e=>{c=(c+e).slice(-Fr)}),o.once("error",e=>{s||(s=!0,d(y("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${C(e)}`,void 0,{cause:e})))}),o.once("exit",(e,t)=>{if(s)return;s=!0;const r=c.trim()?` stderr: ${c.trim().slice(-2048)}`:"";d(y("MCP_STDIO_EXITED",`MCP stdio process exited (code=${e}, signal=${t??"none"}).${r}`))}),{get pid(){return o.pid},request:function(e,r,n){if(n?.aborted)return Promise.reject(y("MCP_ABORTED","MCP request was aborted before send."));if(s)return Promise.reject(y("MCP_STDIO_CLOSED","MCP stdio process is closed."));const o=++i;return new Promise((s,i)=>{const a={resolve:s,reject:i};a.timer=setTimeout(()=>{u(o,a),i(y("MCP_TIMEOUT",`${e} timed out after ${t}ms`))},t),a.timer.unref?.(),n&&(a.signal=n,a.onAbort=()=>{u(o,a),i(y("MCP_ABORTED",`${e} was aborted.`))},n.addEventListener("abort",a.onAbort,{once:!0})),l.set(o,a),f({jsonrpc:"2.0",id:o,method:e,...void 0===r?{}:{params:r}}).catch(e=>{u(o,a),i(e)})})},notify:async function(e,t,r){if(r?.aborted)throw y("MCP_ABORTED","MCP notification was aborted before send.");await f({jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}})},close:m}}function Gr(e,t,r){const n=e??t;if(!Number.isFinite(n)||n<=0)throw y("BAD_MCP_STDIO_CONFIG",`MCP stdio ${r} must be a positive finite number.`);return n}function Wr(e){return!!e&&"object"==typeof e&&"2.0"===e.jsonrpc}async function Jr(e,t,r){return"stdio"===e.transport?async function(e,t,r){const n=Date.now(),o=[],s=r?.signal??t.signal,i={jsonrpc:"2.0",id:kr(),method:e.method,params:e.params},a=Vr({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??Pr,capabilities:{},clientInfo:e.clientInfo},s);if(!t||"object"!=typeof t)throw new Error("MCP initialize returned an invalid result.");o.push({url:`stdio://${e.command}`,method:"initialize",status:200,reason:"mcp-stdio-handshake"}),await a.notify("notifications/initialized",void 0,s);const r=await a.request(e.method,e.params,s),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:n,endedAt:c,durationMs:c-n},sizeBytes:Buffer.byteLength(JSON.stringify(r))},replays:o}}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:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:v(t),replays:o}}finally{await a.close().catch(()=>{})}}(e,t,r):async function(e,t,r){const n=Date.now(),o=r?.signal??t.signal,s=[];let i=e.sessionId,a=e.protocolVersion;if(!i)try{const t=await jr(e.endpoint,{headers:e.headers,signal:o,clientInfo:e.clientInfo});i=t.sessionId,a=t.protocolVersion,s.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:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:v(t),replays:s}}const c={...e.headers,...i?{"Mcp-Session-Id":i}:{}},l={jsonrpc:"2.0",id:kr(),method:e.method,params:e.params};try{const t=await Or(e.endpoint,l,{headers:c,signal:o,startedAt:n,protocolVersion:a}),r=Date.now(),i=_r(t.message)?t.message.error:void 0;return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:l},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:n,endedAt:r,durationMs:r-n,firstByteMs:t.firstByteMs},sizeBytes:t.sizeBytes},...i?{error:{message:i.message,code:String(i.code)}}:{},replays:s}}catch(t){const r=Date.now();return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:c,body:l},response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:v(t),replays:s}}}(e,t,r)}function Hr(e){const t=[];if("tool"===e.kind){const r=e.inputSchema??{type:"object",properties:{}},n=Ne(r);return{capability:e,method:"tools/call",params:{name:e.name,arguments:n&&"object"==typeof n?n:{}},argumentsSchema:r,notes:t}}if("prompt"===e.kind){const r={},n=[];for(const t of e.arguments??[])r[t.name]={type:"string",description:t.description},t.required&&n.push(t.name);const o={type:"object",properties:r,required:n},s=Ne(o);return{capability:e,method:"prompts/get",params:{name:e.name,arguments:s&&"object"==typeof s?s:{}},argumentsSchema:o,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 Yr(e){return e.map(Hr)}function Kr(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Qr(e){return`/mcp/${"tool"===e.kind?"tools":"prompt"===e.kind?"prompts":"resources"}/${Kr(e.name)}`}function Xr(e,t,r,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw y("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,s=S(e);O(s.paths)||(s.paths={});for(const e of r){const{capability:r}=e,n=Qr(r);!o&&O(s.paths[n])||(s.paths[n]={post:{operationId:`mcp_${r.kind}_${Kr(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 s}async function Zr(e,t,r={}){const n=await Nr(t,r);return{spec:Xr(e,t,Yr(n.capabilities),r),capabilities:n.capabilities,warnings:n.warnings}}function en(e){if(!e||!e.endpoint)throw y("BAD_MCP_ENDPOINT","MCP http transport requires an endpoint.");const t=e.endpoint,r={...e.headers??{}};return{transport:"streamable-http",async open(e){const n={headers:r,signal:e.signal,clientInfo:e.clientInfo,capabilities:e.capabilities},o=await jr(t,n);return{sessionId:o.sessionId,serverInfo:o.serverInfo,protocolVersion:o.protocolVersion??e.protocolVersion??Pr}},call:(e,n)=>Or(t,e,{headers:{...n.headers??r},signal:n.signal,startedAt:n.startedAt,protocolVersion:n.protocolVersion}),notify:(e,n)=>Or(t,e,{headers:{...n.headers??r},signal:n.signal,startedAt:n.startedAt,protocolVersion:n.protocolVersion}),async terminate(e){const n=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===n?{outcome:"failed",reason:"terminate request failed"}:n>=200&&n<300?{status:n,outcome:"released"}:405===n?{status:n,outcome:"unsupported"}:404===n?{status:n,outcome:"already-gone"}:{status:n,outcome:"failed"}},async dispose(){}}}function tn(e){const t=Vr(e);let r=!1;return{transport:"stdio",async open(e){const r=await t.request("initialize",{protocolVersion:e.protocolVersion??Pr,capabilities:e.capabilities??{},clientInfo:e.clientInfo??{name:"protokit",version:"0.1.0"}},e.signal);if(!r||"object"!=typeof r)throw y("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??Pr}},async call(e,r){const n=await t.request(e.method,e.params,r.signal),o=JSON.stringify(n);return{message:{jsonrpc:"2.0",id:e.id,result:n},status:200,statusText:"OK",headers:{},sizeBytes:Buffer.byteLength(o??"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 rn=3e4,nn=1e3,on=1e3,sn={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};function an(e,t=0,r=new WeakSet){if(t>8)return"[depth-limit]";if(!O(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=>an(e,t+1,r));const n={};for(const[o,s]of Object.entries(e))n[o]=I(o)&&null!=s?"[redacted]":an(s,t+1,r);return n}function cn(e,...t){const r=t.filter(e=>!!e),n="number"==typeof e&&e>0;if(!r.length&&!n)return{signal:void 0,dispose:()=>{},timedOut:()=>!1};const o=new AbortController;let s=!1;const i=[];for(const e of r){if(e.aborted){o.abort(e.reason);break}const t=()=>o.abort(e.reason);e.addEventListener("abort",t,{once:!0}),i.push(()=>e.removeEventListener("abort",t))}if(n&&!o.signal.aborted){const t=setTimeout(()=>{s=!0,o.abort(new Error(`MCP request timed out after ${e}ms`))},e);t?.unref?.(),i.push(()=>clearTimeout(t))}return{signal:o.signal,dispose:()=>{for(const e of i)e()},timedOut:()=>s}}function ln(e){try{const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("not http(s)");return e}catch{throw y("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${e}`)}}function un(e,t){const r=t.timeoutMs??rn,n=(t.maxEvents,!1!==t.redactSecrets),o=!0===t.serialize,s=f("mcp",t.transport??"http",`mcp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,t.maxEvents??nn);let i="idle";const a=()=>i,c=e=>{i=e,s.setState(e)};let l,u,d,p,m,h;const g=new Promise(e=>{h=e}),b=new Set;function w(e){const t=n?an(e.parsed):e.parsed;s.emit({direction:e.direction,kind:e.event,at:e.at,state:a(),data:e.data,meta:void 0!==t?{parsed:t}:void 0})}function S(e){const t=a();if("open"!==t){if("idle"===t||"connecting"===t)throw y("MCP_NOT_OPEN",`Call open() before ${e}; session is "${t}".`);throw y("MCP_SESSION_CLOSED",`Cannot ${e} on a ${t} session.`)}}async function $(e){const t=e.then(()=>{},()=>{});b.add(t);try{return await e}finally{b.delete(t)}}async function E(n,o,s){const i=o?.timeoutMs??r,a=cn(i,t.signal,o?.signal);try{o?.delayMs&&await(d=o.delayMs,p=a.signal,d>0?new Promise((e,t)=>{const r=()=>{clearTimeout(n),t(y("MCP_ABORTED","Aborted while waiting to send."))},n=setTimeout(()=>{p?.removeEventListener("abort",r),e()},d);if(p?.aborted)return r();p?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),w({direction:"out",at:Date.now(),event:s,parsed:n});const r={signal:a.signal,timeoutMs:i,startedAt:Date.now(),protocolVersion:u,sessionId:l,headers:{...t.headers??{},...l?{"Mcp-Session-Id":l}:{}}},f="notification"===s?await e.notify(n,r):await e.call(n,r);if(f.sessionId&&f.sessionId!==l&&(l=f.sessionId,w({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{sessionIdChanged:l}})),w({direction:"in",at:Date.now(),event:s,parsed:f.message??{status:f.status,statusText:f.statusText,empty:!0}}),404===f.status&&l)throw c("closed"),h(),y("MCP_SESSION_EXPIRED",`Server no longer recognises session ${l} (HTTP 404).`);return f}catch(e){const t=v(e);if(w({direction:"meta",at:Date.now(),event:"error",parsed:t}),a.timedOut())throw y("MCP_TIMEOUT",`${String(n.method)} timed out after ${i}ms`,t);throw e}finally{a.dispose()}var d,p}async function A(e,t,r){if("string"!=typeof e||!e)throw y("BAD_MCP_METHOD","request() requires a non-empty method name.");S(`request("${e}")`);const n={jsonrpc:"2.0",id:kr(),method:e,...void 0===t?{}:{params:t}},o=await $(E(n,r,"jsonrpc"));if(r?.raw)return o;if(_r(o.message))throw y("MCP_RPC_ERROR",`${e} failed (${o.message.error.code}): ${o.message.error.message}`,o.message.error);if(void 0===o.message)throw y("MCP_EMPTY_RESPONSE",`${e} returned no JSON-RPC message (HTTP ${o.status} ${o.statusText}).`);return o.message.result}async function x(e,t){const r=sn[e],n=[],o=new Set;let s,i=0;for(;;){const a=await A(e,s?{cursor:s}:{},t);i+=1,Array.isArray(a?.[r])&&n.push(...a[r]);const c="string"==typeof a?.nextCursor?a.nextCursor:void 0;if(!c)break;if(o.has(c)||i>=on){w({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{warning:`${e} pagination stopped (repeated or excessive cursors)`}});break}o.add(c),s=c}return{items:n,pages:i}}async function T(){if("closed"!==a()){if("closing"===a())return m;if("idle"===a())return c("closed"),h(),void await e.dispose();if("connecting"!==a()||(await(p?.catch(()=>{})),"closed"!==a()))return c("closing"),m=(async()=>{if(await Promise.allSettled([...b]),l){const n=cn(r);try{const r=await e.terminate({sessionId:l,protocolVersion:u,signal:n.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:v(e).message}})}finally{n.dispose()}}await e.dispose(),c("closed"),h(),m=void 0})(),m}}t.signal&&(t.signal.aborted?(c("closed"),h()):t.signal.addEventListener("abort",()=>{T().catch(()=>{})},{once:!0}));const k={get protocol(){return"mcp"},get state(){return a()},get events(){return s.events},onEvent:e=>s.onEvent(e),get sessionId(){return l},get protocolVersion(){return u},get serverInfo(){return d},open:async function(){const n=a();if("open"===n)return;if("connecting"===n)return p;if("closing"===n||"closed"===n)throw y("MCP_SESSION_CLOSED","This session has been closed; create a new one.");c("connecting");const o=cn(r,t.signal);return p=(async()=>{try{const r=await e.open({clientInfo:t.clientInfo,capabilities:t.capabilities,signal:o.signal});l=r.sessionId,u=r.protocolVersion??u??void 0,d=r.serverInfo,c("open"),w({direction:"in",at:Date.now(),event:"session",parsed:{sessionId:l,protocolVersion:u,serverInfo:d}})}catch(e){c("closed"),h();const t=v(e);if(w({direction:"meta",at:Date.now(),event:"error",parsed:t}),o.timedOut())throw y("MCP_TIMEOUT",`initialize timed out after ${r}ms`,t);throw e}finally{o.dispose(),p=void 0}})(),p},request:A,send:async function(e,t){S("send()");const r=O(e)?e:"string"==typeof e?{method:e}:void 0;if(!r||"string"!=typeof r.method||!r.method)throw y("BAD_MCP_MESSAGE","send() expects a method name or an object with a string `method`.");const n=r.method.startsWith("notifications/");return $(E({jsonrpc:"2.0",...r,...void 0!==r.id?{id:r.id}:n?{}:{id:kr()}},t,n?"notification":"jsonrpc"))},notify:async function(e,t,r){if("string"!=typeof e||!e)throw y("BAD_MCP_METHOD","notify() requires a non-empty method name.");S(`notify("${e}")`);const n={jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}};await $(E(n,r,"notification"))},ping:e=>A("ping",{},e).then(()=>{}),listTools:e=>x("tools/list",e),listPrompts:e=>x("prompts/list",e),listResources:e=>x("resources/list",e),listResourceTemplates:e=>x("resources/templates/list",e),async listSources(e){const t=await(async()=>{if(o){const t=[];for(const r of["resources/list","resources/templates/list"])try{t.push({status:"fulfilled",value:await x(r,e)})}catch(e){t.push({status:"rejected",reason:e})}return t}return Promise.allSettled([x("resources/list",e),x("resources/templates/list",e)])})();if(t.every(e=>"rejected"===e.status))throw t[0].reason;const r=[];let n=0;for(const e of t)"fulfilled"===e.status&&(r.push(...e.value.items),n+=e.value.pages);return{items:r,pages:n}},callTool(e,t,r){if(e&&"object"==typeof e){const t=e;if(!t.name)throw y("BAD_MCP_TARGET","callTool() requires a tool name.");return A("tools/call",{name:t.name,arguments:t.arguments??{}},t.opts??r)}const n=e;if(!n)throw y("BAD_MCP_TARGET","callTool() requires a tool name.");return A("tools/call",{name:n,arguments:t??{}},r)},getPrompt(e,t,r){if(!e)throw y("BAD_MCP_TARGET","getPrompt() requires a prompt name.");return A("prompts/get",{name:e,arguments:t??{}},r)},readResource(e,t){if(!e)throw y("BAD_MCP_TARGET","readResource() requires a uri.");return A("resources/read",{uri:e},t)},close:T,waitForClose:()=>g};return k[Symbol.asyncDispose]=()=>T(),k}function dn(e){if(!e||"object"!=typeof e)throw y("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 y("BAD_MCP_STDIO_COMMAND","MCP stdio sessions require a non-empty `command`.");return tn({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes})}if(!e.endpoint)throw y("BAD_MCP_ENDPOINT",'MCP http sessions require an `endpoint` (or set transport: "stdio" with a `command`).');return en({endpoint:ln(e.endpoint),headers:e.headers})}(e);return un(t,e)}function pn(e){return dn({...e,transport:"stdio"})}var fn,mn,hn=dn,yn=class{name="mcp";supports(e){const t=e.located.operation??{};return"mcp"===t["x-protocol"]?20:O(t["x-mcp"])||e.options.mcp?.method||e.options.mcp?.endpoint?15:"mcp"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=Ar(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:I(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 Jr(e.config,t,r)}},gn=require("module"),vn=require("fs"),bn=require("path"),wn={},Sn={grpc:"@grpc/grpc-js",protoLoader:"@grpc/proto-loader"},$n=class extends Error{missing;constructor(e,t){super(`gRPC support requires optional peer dependencies that are not installed: ${e.join(", ")}.\n npm i ${e.join(" ")}`,{cause:t}),this.name="GrpcDependencyMissingError",this.missing=e}},En=class extends Error{packageName;constructor(e,t,r){super(`gRPC dependency "${e}" is installed but unusable: ${t}`,{cause:r}),this.name="GrpcDependencyBrokenError",this.packageName=e}};async function An(e,t){let r;try{r=await(import(e))}catch(t){if(function(e,t){const r=e,n="string"==typeof r?.code?r.code:"";if("ERR_MODULE_NOT_FOUND"!==n&&"MODULE_NOT_FOUND"!==n)return!1;const o="string"==typeof r?.message?r.message:"";return o.includes(`'${t}'`)||o.includes(`"${t}"`)||o.includes(t)}(t,e))throw new $n([e],t);throw new En(e,t instanceof Error?`it threw while loading — ${t.message}`:String(t),t)}return function(e,t,r){const n=[e,e?.default];for(const e of n)if(e&&"object"==typeof e&&t in e)return e;throw new En(r,`its module namespace has no "${t}" export, so the installed version is not the package this library expects.`)}(r,t,e)}function xn(e,t,r){for(const[n,o]of Object.entries(r)){const r=e[n],s=null===r?"null":typeof r;if(s!==o)throw new En(t,`expected "${n}" to be a ${o}, found ${s}. The installed package is not the one this library supports.`)}}function Tn(e){try{const t=(0,gn.createRequire)(wn.url);let r=(0,bn.dirname)(t.resolve(e));for(let t=0;t<8;t++){try{const t=(0,vn.readFileSync)((0,bn.join)(r,"package.json"),"utf8"),n=JSON.parse(t);if(n.name===e&&"string"==typeof n.version)return n.version}catch{}const t=(0,bn.dirname)(r);if(t===r)break;r=t}}catch{}}async function kn(){return mn||(fn||(fn=async function(){const e=await Promise.allSettled([An(Sn.grpc,"Client"),An(Sn.protoLoader,"load")]),t=[];for(const r of e)"rejected"===r.status&&r.reason instanceof $n&&t.push(...r.reason.missing);if(t.length>0){const r=e.find(e=>"rejected"===e.status&&e.reason instanceof $n);throw new $n(t,"rejected"===r?.status?r.reason:void 0)}for(const t of e)if("rejected"===t.status)throw t.reason;const r=e[0].value,n=e[1].value;return xn(r,Sn.grpc,{Client:"function",Metadata:"function",credentials:"object"}),xn(n,Sn.protoLoader,{load:"function"}),{grpc:r,protoLoader:n,capabilities:{descriptorSetFromBuffer:"function"==typeof n.loadFileDescriptorSetFromBuffer,grpcVersion:Tn(Sn.grpc),protoLoaderVersion:Tn(Sn.protoLoader)}}}().then(e=>(mn=e,e),e=>{throw fn=void 0,e})),fn)}async function On(){try{return await kn(),!0}catch{return!1}}function _n(e,t){switch(t){case"descriptorSetFromBuffer":{if(e.capabilities.descriptorSetFromBuffer)return;const t=e.capabilities.protoLoaderVersion?` (found ${e.capabilities.protoLoaderVersion})`:"";throw new En(Sn.protoLoader,`server reflection requires @grpc/proto-loader >= 0.7.0${t}; loadFileDescriptorSetFromBuffer is missing.`)}case"grpcVersion":case"protoLoaderVersion":throw new TypeError(`"${t}" is diagnostic information, not a capability; it cannot be required.`);default:throw new TypeError(`unknown gRPC capability: ${String(t)}`)}}function Pn(e,t){if(null==e)return null;if(Buffer.isBuffer(e))return e;if(e instanceof Uint8Array)return Buffer.from(e);if("string"==typeof e)throw new TypeError(`tls.${t} must be PEM bytes, not a string. A file path is not accepted — read it first, e.g. await readFile(path). Passing a path would fail later during the handshake with an unrelated error.`);throw new TypeError(`tls.${t} must be a Buffer or Uint8Array of PEM bytes; received ${typeof e}.`)}function Mn(e,{grpc:t}){const r=[],n=e.tls;if(void 0===n||!1===n)return{credentials:t.credentials.createInsecure(),mode:"insecure",warnings:r};if(!0===n)return{credentials:t.credentials.createSsl(),mode:"tls-system-roots",warnings:r};const o=Pn(n.rootCerts,"rootCerts"),s=Pn(n.privateKey,"privateKey"),i=Pn(n.certChain,"certChain");if(null===s!=(null===i))throw new Error(`mutual TLS requires both tls.privateKey and tls.certChain; only ${s?"privateKey":"certChain"} was provided.`);const a=null!==s?"mtls":null!==o?"tls-custom-roots":"tls-system-roots";return n.skipHostnameVerification?(r.push("skipHostnameVerification is on: the server certificate chain is still verified, but its hostname is not checked against the address. This permits connecting to an impostor holding any trusted certificate. Use it for local debugging only."),{credentials:t.credentials.createSsl(o,s,i,{checkServerIdentity:()=>{}}),mode:a,warnings:r}):{credentials:t.credentials.createSsl(o,s,i),mode:a,warnings:r}}function Dn(e,t){return Mn(e,t).credentials}async function Cn(e){return Dn(e,await kn())}async function jn(e){return Mn(e,await kn())}var In=require("fs/promises"),Nn=require("path"),Bn=["node_modules",".git","dist","build","out",".venv"],Rn=5e3,qn=40;function Ln(e){return e.toLowerCase().endsWith(".proto")}function Fn(e,t){const r=t?.code;switch(r){case"ENOENT":return`proto path does not exist: ${e}`;case"EACCES":case"EPERM":return`proto path is not readable (permission denied): ${e}`;case"ENOTDIR":return`a component of the proto path is not a directory: ${e}`;case"ELOOP":return`proto path contains a symlink loop: ${e}`;case"ENAMETOOLONG":return`proto path is too long: ${e}`;default:return`proto path could not be read: ${e}`+(r?` (${r})`:"")+(t instanceof Error?` — ${t.message}`:"")}}async function Un(e){try{const t=await(0,In.stat)(e);return t.isDirectory()?"dir":t.isFile()?"file":"other"}catch{return"error"}}async function zn(e){!function(e){if(!e||"object"!=typeof e)throw new TypeError("scanProtoFiles requires an options object.");if(!Array.isArray(e.paths))throw new TypeError(`protoPaths must be an array of strings; received ${typeof e.paths}. A single path must still be wrapped in an array, or it is iterated one character at a time.`);if(e.paths.forEach((e,t)=>{if("string"!=typeof e||0===e.length)throw new TypeError(`protoPaths[${t}] must be a non-empty string; received ${void 0===e?"undefined":typeof e}.`)}),0===e.paths.length)throw new Error("protoPaths is empty; nothing to load.");if(void 0!==e.ignoreDirs){if(!Array.isArray(e.ignoreDirs))throw new TypeError(`ignoreDirs must be an array of directory names; received ${typeof e.ignoreDirs}.`);e.ignoreDirs.forEach((e,t)=>{if("string"!=typeof e)throw new TypeError(`ignoreDirs[${t}] must be a string; received ${typeof e}.`);if(e.includes("/")||e.includes("\\"))throw new TypeError(`ignoreDirs[${t}] ("${e}") looks like a path, but ignoreDirs matches single directory names only; a path never matches and would be silently ignored.`)})}if(void 0!==e.maxFiles&&(!Number.isInteger(e.maxFiles)||e.maxFiles<1))throw new TypeError(`maxFiles must be a positive integer; received ${String(e.maxFiles)}. A cap of 0 would collect nothing and report it as an empty proto tree.`);if(void 0!==e.followSymlinks&&"boolean"!=typeof e.followSymlinks)throw new TypeError(`followSymlinks must be a boolean; received ${typeof e.followSymlinks}.`)}(e);const t=new Set(e.ignoreDirs??Bn),r=e.maxFiles??Rn,n=new Set,o=[],s=[],i=[],a=new Set,c=new Map;let l=!1,u=0;const d=e=>{i.length>=qn?u++:i.push(e)},p=async(t,o)=>{if(!n.has(t))if(n.size>=r)l||(l=!0,d(`stopped after ${r} .proto files; pass maxFiles or a narrower protoPaths if the tree really is this large. The file set is truncated, so symbols may be missing.`));else{if(o||e.followSymlinks){let e;try{e=await(0,In.realpath)(t)}catch(e){return void d(Fn(t,e))}const r=c.get(e);if(void 0!==r)return void(r!==t&&d(`skipped ${t}: it is the same file as ${r} (both resolve to ${e}). Loading it twice would be reported as a duplicate symbol definition.`));c.set(e,t)}n.add(t)}},f=async(r,n)=>{let o,s;try{o=await(0,In.realpath)(r)}catch(e){return void d(Fn(r,e))}if(a.has(o))n&&d(`skipped ${r}: it resolves to ${o}, which was already scanned.`);else{a.add(o);try{s=await(0,In.readdir)(r,{withFileTypes:!0})}catch(e){return void d(Fn(r,e))}for(const o of s){if(l)return;const s=(0,Nn.join)(r,o.name);if(o.isSymbolicLink()){if(!e.followSymlinks){d(`skipped symlink ${s} (followSymlinks is off). If your proto tree links to shared definitions, enable followSymlinks or add the target to protoPaths.`);continue}let r;try{r=await(0,In.stat)(s)}catch(e){d(Fn(s,e));continue}r.isDirectory()?t.has(o.name)||await f(s,!0):r.isFile()&&Ln(o.name)&&await p((0,Nn.resolve)(s),!0);continue}if(o.isDirectory()){t.has(o.name)||await f(s,n);continue}if(o.isFile()){Ln(o.name)&&await p((0,Nn.resolve)(s),n);continue}if(o.isFIFO()||o.isSocket()||o.isBlockDevice()||o.isCharacterDevice())continue;const i=await Un(s);"dir"===i?t.has(o.name)||await f(s,n):"file"===i?Ln(o.name)&&await p((0,Nn.resolve)(s),n):"error"===i&&Ln(o.name)&&d(`could not determine the type of ${s}; it was skipped even though its name suggests a proto file.`)}}};for(const t of e.paths){const e=(0,Nn.resolve)(t);let r;try{r=await(0,In.stat)(e)}catch(e){throw new Error(Fn(t,e),{cause:e})}if(r.isFile()){if(!Ln(e))throw new Error(`not a .proto file: ${t}. protoPaths accepts .proto files and directories containing them.`);await p(e,!1),s.includes(e)||s.push(e)}else{if(!r.isDirectory())throw new Error(`proto path is neither a file nor a directory: ${t}`);o.includes(e)||o.push(e),await f(e,!1)}}if(u>0&&i.push(`${u} further scan note(s) were suppressed; the ones above are representative.`),0===n.size){const r=i.length?` Some entries were skipped: ${i[0]}`:` Checked for *.proto, skipping ${[...t].join(", ")}.`;throw new Error(`no .proto files found under: ${e.paths.join(", ")}.${r}`)}return{files:[...n].sort(),rootDirs:o,fileRoots:s,notes:i}}function Vn(e,t){const r=t.endsWith(Nn.sep)?t:t+Nn.sep;return e===t||e.startsWith(r)}function Gn(e){const t=[],r=new Set;for(const t of e.rootDirs)r.add(t);for(const t of e.fileRoots)r.add((0,Nn.dirname)(t));const n=[...r],o=[];for(const t of e.files){const e=(0,Nn.dirname)(t);n.some(t=>Vn(e,t))||(r.has(e)||(r.add(e),o.push(e)))}return o.length>0&&t.push(`${o.length} directory(ies) outside the given protoPaths were added as include roots so their imports resolve: ${o.slice(0,3).join(", ")}${o.length>3?", …":""}. Imports are therefore resolved more loosely than protoc would; pass includeDirs explicitly for exact behaviour.`),{includeDirs:[...r].sort(),notes:t}}var Wn=0,Jn=2,Hn=[1,128,16384,2097152,268435456,34359738368,4398046511104,562949953421312,72057594037927940,0x8000000000000000],Yn=class{constructor(e,t=0){this.buf=e,this.pos=t}buf;pos;get eof(){return this.pos>=this.buf.length}varint(){let e,t=0,r=0;do{if(this.pos>=this.buf.length)throw new Error(`truncated varint at offset ${this.pos}`);if(r>=Hn.length)throw new Error("varint longer than 10 bytes");e=this.buf[this.pos++],t+=(127&e)*Hn[r++]}while(128&e);if(!Number.isSafeInteger(t))throw new Error("varint exceeds Number.MAX_SAFE_INTEGER");return t}bytes(){return Buffer.from(this.view())}view(){const e=this.varint(),t=this.pos+e;if(t>this.buf.length)throw new Error(`length-delimited field runs past end of buffer (need ${e} bytes at ${this.pos}, have ${this.buf.length-this.pos})`);const r=this.buf.subarray(this.pos,t);return this.pos=t,r}string(){return this.view().toString("utf8")}skip(e){switch(e){case Wn:return void this.varint();case 1:return void this.advance(8);case Jn:return void this.view();case 5:return void this.advance(4);default:throw new Error(`unsupported wire type ${e} at offset ${this.pos}`)}}advance(e){const t=this.pos+e;if(t>this.buf.length)throw new Error("fixed-width field runs past end of buffer");this.pos=t}};function Kn(e,t){const r=new Yn(e);for(;!r.eof;){const e=r.varint(),n=Math.floor(e/8),o=7&e;if(0===n)throw new Error("field number 0 is not valid");const s=r.pos;if(t(n,o,r)){if(r.pos===s)throw new Error(`decoder claimed field ${n} (wire ${o}) without consuming it`)}else r.skip(o)}}function Qn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`cannot encode ${e} as an unsigned varint`);const t=[];let r=e;for(;r>127;)t.push(r%128|128),r=Math.floor(r/128);return t.push(r),Buffer.from(t)}function Xn(e,t){return Qn(8*e+t)}function Zn(e,t){return Buffer.concat([Xn(e,Jn),Qn(t.length),t])}function eo(e,t){return Zn(e,Buffer.from(t,"utf8"))}function to(e){return"list"===e?"the service list":e.slice(e.indexOf(":")+1)}function ro(e){let t,r={kind:"other",field:0};return Kn(e,(e,n,o)=>{if(n!==Jn)return!1;switch(e){case 2:return t=function(e){let t;return Kn(e,(e,r,n)=>r===Jn&&(3===e?(t=`file:${n.string()}`,!0):4===e?(t=`sym:${n.string()}`,!0):7===e&&(n.view(),t="list",!0))),t}(o.view()),!0;case 4:{const e=[];return Kn(o.view(),(t,r,n)=>1===t&&r===Jn&&(e.push(n.bytes()),!0)),r={kind:"files",descriptors:e},!0}case 6:{const e=[];return Kn(o.view(),(t,r,n)=>1===t&&r===Jn&&(Kn(n.view(),(t,r,n)=>1===t&&r===Jn&&(e.push(n.string()),!0)),!0)),r={kind:"services",services:e},!0}case 7:{let e=2,t="";return Kn(o.view(),(r,n,o)=>1===r&&n===Wn?(e=o.varint(),!0):2===r&&n===Jn&&(t=o.string(),!0)),r={kind:"error",code:e,message:t},!0}case 5:return o.view(),r={kind:"other",field:5},!0;default:return!1}}),{answers:t,body:r}}function no(e){let t="";const r=[];return Kn(e,(e,n,o)=>n===Jn&&(1===e?(t=o.string(),!0):3===e&&(r.push(o.string()),!0))),{name:t,dependencies:r}}var oo=class extends Error{address;versionsTried;constructor(e,t,r){super(`server at ${e} answered but does not implement the gRPC reflection service (${t.join(" and ")} both reported UNIMPLEMENTED/NOT_FOUND). Register the reflection service on the server, or pass protoPaths instead.`,{cause:r}),this.name="ReflectionUnavailableError",this.address=e,this.versionsTried=t}},so=class extends Error{address;code;constructor(e,t,r){super(`could not complete the reflection handshake with ${e}`+(void 0!==t?` (gRPC status ${t})`:"")+`: ${r}. This is a connectivity or transport failure, not a missing reflection service — nothing was reached that could answer.`),this.name="ReflectionTransportError",this.address=e,this.code=t}},io=class extends Error{detail;constructor(e,t){super(t?`${e} (${t})`:e),this.name="ReflectionProtocolError",this.detail=t}},ao={v1:"/grpc.reflection.v1.ServerReflection/ServerReflectionInfo",v1alpha:"/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo"},co=5e3,lo=2e3,uo=33554432,po=12,fo=5;function mo(e){return"object"==typeof e&&null!==e&&!0===e.versionMissing}function ho(e){const t=e?.code;return"number"==typeof t?t:void 0}function yo(e,t,r){if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<r))throw new RangeError(`${e} must be a finite number >= ${r}; received ${"number"==typeof t?t:typeof t}.`)}function go(e){if("string"!=typeof e.address||""===e.address)throw new TypeError("reflection requires a non-empty address.");if(yo("timeoutMs",e.timeoutMs,1),yo("maxFiles",e.maxFiles,1),yo("maxBytes",e.maxBytes,1),void 0!==e.version&&"v1"!==e.version&&"v1alpha"!==e.version)throw new TypeError(`reflectionVersion must be "v1" or "v1alpha"; received ${String(e.version)}.`)}async function vo(e,t){const r=e.version?[e.version]:["v1","v1alpha"];let n;for(const[o,s]of r.entries())try{const n=await bo(e,t,s);return o>0&&n.notes.unshift(`reflection ${r[0]} was unimplemented; used ${s}.`),n}catch(e){if(!mo(e))throw e;n=e.cause}throw new oo(e.address,r,n)}function bo(e,t,r){const n=e.timeoutMs??co,o=e.maxFiles??lo,s=e.maxBytes??uo,i=e.host??"";return kn().then(({grpc:a})=>{const c=function(e,t){const r=new e.Metadata;for(const[e,n]of Object.entries(t??{})){const t=Array.isArray(n)?n:[n];for(const n of t){if("string"!=typeof n&&!Buffer.isBuffer(n))throw new TypeError(`reflection metadata["${e}"] must be a string, a Buffer, or an array of those; received ${null===n?"null":typeof n}.`);try{r.add(e,n)}catch(t){throw new TypeError(`reflection metadata key "${e}" was rejected by grpc-js: ${C(t)}. Keys must match [0-9a-z_.-]+, and only keys ending in "-bin" may carry Buffers.`)}}}return r}(a,e.metadata);let l,u;try{l=new a.Client(e.address,e.credentials,e.channelOptions)}catch(t){throw new so(e.address,void 0,`the channel could not be created: ${C(t)}. Expected host:port`)}try{u=l.makeBidiStreamRequest(ao[r],e=>e,e=>e,c,{deadline:new Date(Date.now()+n)})}catch(t){try{l.close()}catch{}throw new so(e.address,ho(t),C(t))}return new Promise((a,c)=>{const d=new Map,p=[],f=new Map,m=new Set;let h,y="symbols"!==t.kind,g=0,v=!1,b=!1,w=!1;const S=()=>{if(0===f.size)return;const e=[...f.keys()].slice(0,5).join(", ");return`still awaiting ${f.size} reply(ies): ${e}${f.size>5?", …":""}`},$=setTimeout(()=>{A(new io(`reflection session at ${e.address} did not complete within ${n}ms`,S()))},n+250);$.unref?.();const E=()=>{clearTimeout($);try{u.cancel()}catch{}try{l.close()}catch{}};function A(e){v||(v=!0,E(),c(e))}function x(t){A(w?new io(`the reflection stream at ${e.address} failed after the server had already answered, so ${r} is served here; ${d.size} file(s) were discarded`,C(t)):{versionMissing:!0,cause:t})}function T(){if(!v){v=!0,clearTimeout($);try{u.end()}catch{}try{l.close()}catch{}a({services:"symbols"===t.kind?void 0:h??[],descriptors:d,version:r,notes:p})}}const k=(t,r)=>{if(!v&&!m.has(t))if(m.size>=o)A(new io(`reflection closure exceeded maxFiles=${o}`,`while requesting ${to(t)}`));else{m.add(t),f.set(t,{key:t,primary:r});try{u.write(function(e,t){const r=[];return t&&r.push(eo(1,t)),"list"===e?r.push(eo(7,"*")):e.startsWith("file:")?r.push(eo(3,e.slice(5))):r.push(eo(4,e.slice(4))),Buffer.concat(r)}(t,i))}catch(r){A(new so(e.address,ho(r),`writing the request for ${to(t)} failed: ${C(r)}`))}}};if(u.on("data",e=>{if(v)return;let r;try{r=ro(e)}catch(e){return w=!0,void A(new io("malformed ServerReflectionResponse",C(e)))}w=!0;const n=(e=>{if(void 0!==e&&f.has(e)){const t=f.get(e);return f.delete(e),t}b||(b=!0,p.push(void 0===e?"server omitted original_request; replies were paired by arrival order.":`server echoed an unrequested original_request (${e}); replies were paired by arrival order.`));const t=f.keys().next();if(t.done)return;const r=f.get(t.value);return f.delete(t.value),r})(r.answers);switch(r.body.kind){case"error":{const{code:e,message:t}=r.body,o=`code ${e}: ${t||"(no message)"}`;if(!n||n.primary)return void A(new io(`reflection request for ${n?to(n.key):"(unknown)"} failed`,o));p.push(`server could not supply ${to(n.key)} — ${o}. The descriptor set may be incomplete.`);break}case"files":if(0===r.body.descriptors.length&&n?.primary&&p.push(`server returned an empty file set for ${to(n.key)}.`),(e=>{for(const t of e){if(v)return;if(g+=t.length,g>s)return void A(new io(`reflection payload exceeded maxBytes=${s}`,`after ${d.size} file(s)`));let e;try{e=no(t)}catch(e){return void A(new io("server returned a FileDescriptorProto that could not be parsed",C(e)))}if(e.name){if(!d.has(e.name)){d.set(e.name,t);for(const t of e.dependencies)if(d.has(t)||k(`file:${t}`,!1),v)return}}else p.push("server returned a FileDescriptorProto with no name; it was skipped.")}})(r.body.descriptors),v)return;break;case"services":if(h=r.body.services,y=!1,"list_then_symbols"===t.kind){const e=h.filter(e=>!e.startsWith("grpc.reflection."));for(const t of e)if(k(`sym:${t}`,!0),v)return}break;case"other":p.push(`ignored an unexpected reflection response variant (field ${r.body.field}) for ${n?to(n.key):"(unknown request)"}.`)}0!==f.size||y||T()}),u.on("error",t=>{if(v)return;const r=ho(t);r!==po&&r!==fo?A(new so(e.address,r,C(t))):x(t)}),u.on("status",t=>{if(v)return;const r=t;if(0!==r.code){const t=`${r.code} ${r.details??""}`.trim();return r.code===po||r.code===fo?void x(Object.assign(new Error(`reflection stream ended: ${t}`),{code:r.code,details:r.details})):void A(new so(e.address,r.code,r.details||"the stream ended with a non-OK status"))}f.size>0||y?A(new io("server closed the reflection stream before answering everything",S()??"the service list was requested but never returned")):T()}),u.on("end",()=>{v||0!==f.size||y||T()}),"symbols"===t.kind){for(const e of t.symbols)if(k(`sym:${e}`,!0),v)return}else k("list",!0)})})}function wo(e){const t=new Map;for(const[r,n]of e){let o;try{o=no(n)}catch{t.set(r,[]);continue}t.set(r,o.dependencies.filter(t=>e.has(t)))}const r=[],n=[],o=new Map,s=e=>{const i=o.get(e);if("done"!==i)if("visiting"!==i){o.set(e,"visiting");for(const r of t.get(e)??[])s(r);o.set(e,"done"),r.push(e)}else n.includes(e)||n.push(e)};for(const t of[...e.keys()].sort())s(t);return{ordered:r,cycles:n}}function So(e){const{ordered:t}=wo(e);return Buffer.concat(t.map(t=>Zn(1,e.get(t))))}async function $o(e){go(e);const t=await vo(e,{kind:"list"});return{services:(t.services??[]).filter(e=>!e.startsWith("grpc.reflection.")).sort(),version:t.version,notes:t.notes}}async function Eo(e){return(await $o(e)).services}function Ao(e,t){if(0===e.descriptors.size)throw new io(`reflection returned no file descriptors for ${t}`,e.notes.join(" ")||void 0);const{ordered:r,cycles:n}=wo(e.descriptors),o=[...e.notes];return n.length>0&&o.push(`${n.length} file(s) take part in an import cycle, which protoc cannot produce: ${n.slice(0,5).join(", ")}`+(n.length>5?", …":"")+". They were emitted once each; the descriptor set may not load."),{descriptorSet:Buffer.concat(r.map(t=>Zn(1,e.descriptors.get(t)))),files:r,version:e.version,notes:o}}async function xo(e){if(go(e),!Array.isArray(e.symbols)||0===e.symbols.length)throw new TypeError("fetchDescriptorSet requires a non-empty array of symbol names.");const t=e.symbols.findIndex(e=>"string"!=typeof e||""===e);if(-1!==t)throw new TypeError(`symbols[${t}] is not a non-empty string (got ${typeof e.symbols[t]}).`);return Ao(await vo(e,{kind:"symbols",symbols:e.symbols}),e.symbols.join(", "))}async function To(e){go(e);const t=await vo(e,{kind:"list_then_symbols"}),r=(t.services??[]).filter(e=>!e.startsWith("grpc.reflection.")).sort();return 0===r.length?{services:r,descriptorSet:Buffer.alloc(0),files:[],version:t.version,notes:[...t.notes,`reflection is available at ${e.address} but the server advertises no services other than reflection itself.`]}:{services:r,...Ao(t,r.join(", "))}}var ko=0,Oo=1,_o=2,Po=3,Mo=4,Do=5,Co=class extends Error{constructor(e){super(`descriptor decode failed: ${e}`),this.name="DescriptorDecodeError"}};function jo(e){let t=0n,r=0n;for(;;){if(e.pos>=e.end)throw new Co("truncated varint");const n=e.buf[e.pos++];if(t|=BigInt(127&n)<<r,!(128&n))return t;if(r+=7n,r>70n)throw new Co("varint too long")}}function Io(e,t,r){switch(t){case ko:return void jo(e);case Oo:return void No(e,8);case Do:return void No(e,4);case _o:return void No(e,Number(jo(e)));case Po:if(r>32)throw new Co("group nesting too deep");for(;;){if(e.pos>=e.end)throw new Co("unterminated group");const t=7&Number(jo(e));if(t===Mo)return;Io(e,t,r+1)}default:throw new Co(`unsupported wire type ${t}`)}}function No(e,t){if(t<0||e.pos+t>e.end)throw new Co("length exceeds buffer");e.pos+=t}function Bo(e){const t={buf:e,pos:0,end:e.length},r=new Map;for(;t.pos<t.end;){const n=Number(jo(t)),o=n>>>3,s=7&n;if(0===o)throw new Co("field number 0 is invalid");let i;if(s===ko)i={wireType:s,varint:jo(t)};else if(s===_o){const r=Number(jo(t));if(r<0||t.pos+r>t.end)throw new Co("length-delimited field overruns");i={wireType:s,bytes:e.subarray(t.pos,t.pos+r)},t.pos+=r}else{const r=t.pos;Io(t,s,0),i={wireType:s,bytes:e.subarray(r,t.pos)}}const a=r.get(o);a?a.push(i):r.set(o,[i])}return r}var Ro=new TextDecoder("utf-8",{fatal:!0});function qo(e,t){const r=e.get(t)?.at(-1);if(r?.bytes)try{return Ro.decode(r.bytes)}catch{throw new Co(`field ${t} is not valid UTF-8`)}}function Lo(e,t){const r=e.get(t)?.at(-1);if(void 0===r?.varint)return;const n=r.varint;return Number(n>0x7fffffffn?BigInt.asIntN(32,n):n)}function Fo(e,t){const r=e.get(t)?.at(-1);return void 0!==r?.varint&&0n!==r.varint}function Uo(e,t){const r=e.get(t);return r?r.map(e=>{if(!e.bytes)throw new Co(`field ${t} was expected to be length-delimited`);return e.bytes}):[]}function zo(e,t){if(void 0===e||""===e)throw new Co(`${t} is missing or empty`);return e}function Vo(e){const t=Bo(e),r=Lo(t,4),n=Lo(t,5);if(void 0===r)throw new Co("FieldDescriptorProto.label is missing");if(void 0===n)throw new Co("FieldDescriptorProto.type is missing");return{name:zo(qo(t,1),"FieldDescriptorProto.name"),number:Lo(t,3)??0,label:r,type:n,type_name:qo(t,6),json_name:qo(t,10),oneof_index:Lo(t,9),proto3_optional:Fo(t,17)}}function Go(e){const t=Bo(e);return{name:zo(qo(t,1),"EnumDescriptorProto.name"),value:Uo(t,2).map(e=>{const t=Bo(e);return{name:zo(qo(t,1),"EnumValueDescriptorProto.name"),number:Lo(t,2)??0}})}}function Wo(e,t=0){if(t>64)throw new Co("message nesting too deep");const r=Bo(e),n=Uo(r,7).at(-1);const o=n?Bo(n):void 0;return{name:zo(qo(r,1),"DescriptorProto.name"),field:Uo(r,2).map(Vo),nested_type:Uo(r,3).map(e=>Wo(e,t+1)),enum_type:Uo(r,4).map(Go),oneof_decl:Uo(r,8).map(e=>({name:zo(qo(Bo(e),1),"OneofDescriptorProto.name")})),options:{map_entry:!!o&&Fo(o,7)}}}function Jo(e){const t=Bo(e);return{name:zo(qo(t,1),"ServiceDescriptorProto.name"),method:Uo(t,2).map(e=>{const t=Bo(e);return{name:zo(qo(t,1),"MethodDescriptorProto.name"),input_type:zo(qo(t,2),"MethodDescriptorProto.input_type"),output_type:zo(qo(t,3),"MethodDescriptorProto.output_type"),client_streaming:Fo(t,5),server_streaming:Fo(t,6)}})}}function Ho(e){const t=Bo(e);return{name:qo(t,1),package:qo(t,2),syntax:qo(t,12),dependency:Uo(t,3).map(e=>function(e,t){try{return Ro.decode(e)}catch{throw new Co(`${t} is not valid UTF-8`)}}(e,"FileDescriptorProto.dependency")),message_type:Uo(t,4).map(e=>Wo(e)),enum_type:Uo(t,5).map(Go),service:Uo(t,6).map(Jo)}}function Yo(e){const t=Bo(e),r=Uo(t,1),n=[...t.keys()].filter(e=>1!==e);if(n.length>0)throw new Co(`expected a FileDescriptorSet but the message also carries field(s) ${n.sort((e,t)=>e-t).join(", ")}. These bytes are most likely a bare FileDescriptorProto; decode it with decodeFileDescriptorProto instead.`);return 0===r.length?[]:r.map(Ho)}var Ko=class extends Error{expected;observedKeys;constructor(e,t,r){const n=t&&"object"==typeof t?Object.keys(t).sort():[],o=n.length?n.slice(0,24).join(", "):"(none)";super(`descriptor shape mismatch: expected ${e}, got ${Qo(t)} with keys [${o}]`+(n.length>24?` ...+${n.length-24} more`:"")+(r?`. ${r}`:"")),this.name="DescriptorShapeError",this.expected=e,this.observedKeys=n}};function Qo(e){if(null===e)return"null";if(Array.isArray(e))return`array(${e.length})`;const t=typeof e;return"object"===t?e.constructor?.name??"object":t}function Xo(e,t,r){if(!e||"object"!=typeof e)return;const n=e;return Object.prototype.hasOwnProperty.call(n,t)?n[t]:t!==r&&Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0}function Zo(e,t,r){if(!e||"object"!=typeof e)return!1;const n=e;return Object.prototype.hasOwnProperty.call(n,t)||t!==r&&Object.prototype.hasOwnProperty.call(n,r)}function es(e,t,r,n){if(!Zo(e,t,r))return[];const o=Xo(e,t,r);if(void 0===o)return[];if(null===o||!Array.isArray(o))throw new Ko(`${n}.${r} to be a repeated field`,e,`field "${r}" is ${Qo(o)}.`);return o}function ts(e,t,r,n){const o=Xo(e,t,r);if("string"!=typeof o||0===o.length)throw new Ko(`${n}.${r} to be a non-empty string`,e,`got ${Qo(o)}.`);return o}function rs(e,t,r,n){const o=Xo(e,t,r),s="string"==typeof o&&""!==o.trim()?Number(o):o;if("number"!=typeof s||!Number.isFinite(s))throw new Ko(`${n}.${r} to be a number`,e,`got ${Qo(o)}.`);return s}function ns(e,t,r){const n=Xo(e,t,r);return!0===n||1===n||"true"===n}var os={1:"TYPE_DOUBLE",2:"TYPE_FLOAT",3:"TYPE_INT64",4:"TYPE_UINT64",5:"TYPE_INT32",6:"TYPE_FIXED64",7:"TYPE_FIXED32",8:"TYPE_BOOL",9:"TYPE_STRING",10:"TYPE_GROUP",11:"TYPE_MESSAGE",12:"TYPE_BYTES",13:"TYPE_UINT32",14:"TYPE_ENUM",15:"TYPE_SFIXED32",16:"TYPE_SFIXED64",17:"TYPE_SINT32",18:"TYPE_SINT64"},ss={1:"LABEL_OPTIONAL",2:"LABEL_REQUIRED",3:"LABEL_REPEATED"},is=new Set(Object.values(os)),as=new Set(Object.values(ss));function cs(e,t,r,n,o){if("string"==typeof e){if(r.has(e))return e;throw new Ko(`${n}.${o} to be a known enum name`,e,`"${e}" is not one of [${[...r].join(", ")}].`)}if("number"==typeof e){const r=t[e];if(r)return r;throw new Ko(`${n}.${o} to be a known enum number`,e,`${e} has no mapping; the descriptor may use a newer protobuf revision.`)}throw new Ko(`${n}.${o} to be present`,e,`got ${Qo(e)}.`)}function ls(e){return!(!e||"object"!=typeof e)&&Object.values(e).some(e=>{const t=e;return!!t&&"object"==typeof t&&"string"==typeof t.path&&"function"==typeof t.requestSerialize})}function us(e){ds(e);return es(e,"field","field","DescriptorProto").map((e,t)=>{const r=`FieldDescriptorProto[${t}]`,n=Xo(e,"typeName","type_name"),o=Xo(e,"jsonName","json_name"),s=Xo(e,"oneofIndex","oneof_index"),i=cs(Xo(e,"type","type"),os,is,r,"type");if(("TYPE_MESSAGE"===i||"TYPE_ENUM"===i||"TYPE_GROUP"===i)&&"string"!=typeof n)throw new Ko(`${r}.type_name to be present for ${i}`,e,`a ${i} field cannot be resolved without its type name.`);return{name:ts(e,"name","name",r),number:rs(e,"number","number",r),type:i,label:cs(Xo(e,"label","label"),ss,as,r,"label"),typeName:"string"==typeof n&&n?n:void 0,jsonName:"string"==typeof o&&o?o:void 0,oneofIndex:"number"==typeof s&&Number.isFinite(s)?s:void 0,proto3Optional:ns(e,"proto3Optional","proto3_optional")}})}function ds(e){var t;if(!(t=e)||"object"!=typeof t||!Zo(t,"name","name")||Zo(t,"method","method")||Zo(t,"value","value")||ls(t))throw new Ko("a DescriptorProto (message descriptor)",e,ls(e)?"this looks like a proto-loader runtime object, not a descriptor proto. Descriptor protos come from loadFileDescriptorSetFromBuffer or from reflection.":"the descriptor source did not produce descriptor protos.")}function ps(e){if(!e||"object"!=typeof e)return!1;return ns(Xo(e,"options","options"),"mapEntry","map_entry")}function fs(e){if(!((t=e)&&"object"==typeof t&&Zo(t,"name","name")&&Zo(t,"value","value")))throw new Ko("an EnumDescriptorProto",e,"the descriptor source did not produce enum descriptors.");var t;return es(e,"value","value","EnumDescriptorProto").map((e,t)=>ts(e,"name","name",`EnumValueDescriptorProto[${t}]`))}function ms(e){if(!((t=e)&&"object"==typeof t&&Zo(t,"name","name")&&Zo(t,"method","method")))throw new Ko("a ServiceDescriptorProto",e,ls(e)?"this is a proto-loader runtime service object (entries carry `path` and `requestSerialize`), which contains no method descriptors. Load a FileDescriptorSet or use reflection to obtain them.":"the descriptor source did not produce service descriptors.");var t;return es(e,"method","method","ServiceDescriptorProto").map((e,t)=>{const r=`MethodDescriptorProto[${t}]`;return{name:ts(e,"name","name",r),inputType:ts(e,"inputType","input_type",r),outputType:ts(e,"outputType","output_type",r),clientStreaming:ns(e,"clientStreaming","client_streaming"),serverStreaming:ns(e,"serverStreaming","server_streaming")}})}var hs={keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0};function ys(e,t){return e?`${e}.${t}`:t}function gs(e,t,r){if(""===r)return;const n=t=>e.symbols.has(t)||e.mapEntries.has(t);if(r.startsWith(".")){const e=r.slice(1);return n(e)?e:void 0}let o=t;for(;;){const e=o?`${o}.${r}`:r;if(n(e))return e;if(""===o)return;const t=o.lastIndexOf(".");o=-1===t?"":o.slice(0,t)}}function vs(e,t,r){const n=Xo(e,t,r);return Array.isArray(n)?n:[]}function bs(e,t,r,n,o){e.notes.push(`duplicate definition of ${t} "${r}" (${n} and ${o}); the first one was kept.`)}function ws(e,t,r,n){const o=String(Xo(n,"name","name")??"");if(!o)return void e.notes.push(`${t}: a message with no name was skipped.`);const s=ys(r,o);if(ps(n))e.mapEntries.add(s);else{const r=e.symbols.get(s);r?bs(e,"message",s,r.file,t):e.symbols.set(s,{kind:"message",type:n,file:t})}for(const r of vs(n,"nestedType","nested_type"))ws(e,t,s,r);for(const r of vs(n,"enumType","enum_type"))Ss(e,t,s,r)}function Ss(e,t,r,n){const o=String(Xo(n,"name","name")??"");if(!o)return void e.notes.push(`${t}: an enum with no name was skipped.`);const s=ys(r,o),i=e.symbols.get(s);i?bs(e,"enum",s,i.file,t):e.symbols.set(s,{kind:"enum",type:n,file:t})}function $s(e,t){const r=Xo(t,"name","name"),n="string"==typeof r&&""!==r?r:`(unnamed #${++e.unnamedSeq})`,o=String(Xo(t,"package","package")??"");for(const r of vs(t,"messageType","message_type"))ws(e,n,o,r);for(const r of vs(t,"enumType","enum_type"))Ss(e,n,o,r);for(const r of vs(t,"service","service")){const t=String(Xo(r,"name","name")??"");if(!t){e.notes.push(`${n}: a service with no name was skipped.`);continue}const s=ys(o,t),i=e.symbols.get(s);i?"service"===i.kind?bs(e,"service",s,i.file,n):e.notes.push(`"${s}" is declared both as a service (${n}) and as a ${i.kind} (${i.file}); the ${i.kind} was kept and the service is not callable through this catalog.`):(e.symbols.set(s,{kind:"service",type:r,file:n}),e.serviceDescriptors.set(s,r))}}function Es(e){return null!==e&&"object"==typeof e&&"string"==typeof e.path}function As(e,t,r,n){if(0===t.length)return void n.push(r?"the descriptors attached by @grpc/proto-loader carry no file names, so symbols cannot be attributed to the .proto they were declared in. This affects diagnostics only.":"no descriptor file names were recovered, so symbols cannot be attributed to their .proto files. This affects diagnostics only.");const o=e.filter(e=>!(e=>{const r=e.split("\\").join("/");return t.some(e=>r===e||r.endsWith(`/${e}`))})(e));0!==o.length&&(o.length!==e.length?n.push(`${o.length} of ${e.length} scanned .proto file(s) are not represented in the decoded descriptors, so nothing they declare is in the symbol table: ${o.join(", ")}.`):n.push(`descriptor file names do not correspond to the .proto paths that were scanned (descriptors report ${t.slice(0,3).join(", ")}${t.length>3?", …":""}), so symbols cannot be attributed to the file that declared them. This is how protobufjs-generated descriptors name files and affects diagnostics only — the symbol table itself is unaffected.`))}async function xs(e){!function(e){if(!0===e.reflection)return;const t=e.protoPaths;if(null==t)throw new Error("a gRPC endpoint needs a descriptor source: either set reflection: true, or pass protoPaths: string[] pointing at your .proto files or directories. Neither was provided.");if(!Array.isArray(t))throw new TypeError(`protoPaths must be an array of paths; received ${"string"==typeof t?`the string "${t}" — wrap it: ["${t}"]`:typeof t}.`);if(0===t.length)throw new Error("protoPaths is empty. Pass at least one .proto file or directory, or set reflection: true to obtain descriptors from the server.");const r=t.findIndex(e=>"string"!=typeof e||""===e);if(-1!==r)throw new TypeError(`protoPaths[${r}] is not a non-empty string (got ${typeof t[r]}).`);const n=e.includeDirs;if(null!=n&&!Array.isArray(n))throw new TypeError(`includeDirs must be an array of directories; received ${"string"==typeof n?`the string "${n}" — wrap it: ["${n}"]`:typeof n}.`)}(e);const t=await kn(),{protoLoader:r}=t,n=[];let o,s,i,a;if(!0===e.reflection){_n(t,"descriptorSetFromBuffer");const{credentials:c,mode:l,warnings:u}=Mn(e,t);n.push(...u);const d=await To({address:e.address,credentials:c,metadata:e.metadata,timeoutMs:e.reflectionTimeoutMs??5e3,channelOptions:e.channelOptions,version:e.reflectionVersion,host:e.reflectionHost,maxFiles:e.maxReflectionFiles,maxBytes:e.maxReflectionBytes});if(n.push(...d.notes),0===d.services.length)throw new Error(`reflection is available at ${e.address} (${d.version}) but no services are registered on it. Either the server registered only the reflection service itself, or the services you expect were never added to it.`);o=r.loadFileDescriptorSetFromBuffer(d.descriptorSet,hs);try{s=Yo(d.descriptorSet)}catch(t){if(!(t instanceof Co))throw t;throw new Error(`reflection at ${e.address} returned ${d.descriptorSet.length} byte(s) that could not be decoded as a FileDescriptorSet: ${t.message}. The server may be answering the reflection method with a non-standard payload.`)}if(0===s.length)throw new Error(`reflection at ${e.address} reported ${d.services.length} service(s) but its descriptor set decoded to zero files, so nothing can be described.`);i="reflection",a=d.files,n.push(`reflection (${d.version}, ${l}) returned ${d.services.length} service(s) across ${d.files.length} file(s).`)}else{const t=e.protoPaths,c=await zn({paths:t,ignoreDirs:e.ignoreDirs,followSymlinks:e.followSymlinks,maxFiles:e.maxProtoFiles});let l;if(n.push(...c.notes),a=c.files,Array.isArray(e.includeDirs)&&e.includeDirs.length>0)l=e.includeDirs;else{const e=Gn(c);l=e.includeDirs,n.push(...e.notes)}o=await r.load(c.files,{...hs,includeDirs:l});const u=function(e){const t=new Set,r=[];let n=!1,o=0;const s=e=>{const s=e?.fileDescriptorProtos;if(!Array.isArray(s))return!1;n=!0,o++;for(const e of s){if(!(Buffer.isBuffer(e)||e instanceof Uint8Array))continue;const n=Buffer.isBuffer(e)?e:Buffer.from(e),o=n.toString("base64");t.has(o)||(t.add(o),r.push(n))}return!0};for(const t of Object.values(e))if(t&&"object"==typeof t&&!s(t))for(const e of Object.values(t))e&&"object"==typeof e&&s(e);return{buffers:r,found:n,carriers:o}}(o);if(!u.found)throw new Error(`@grpc/proto-loader did not attach fileDescriptorProtos to any of the ${Object.keys(o).length} entries it produced, so no method or field metadata can be read. Upgrade to @grpc/proto-loader >= 0.6.0.`);if(0===u.buffers.length)throw new Error(`@grpc/proto-loader attached fileDescriptorProtos to ${u.carriers} entry/entries, but none of them contained descriptor bytes. The loader output cannot be interpreted; this is a version incompatibility rather than a problem with your protos.`);s=function(e,t){const r=[],n=[];for(const t of e)try{r.push(Ho(t))}catch(e){n.push(e instanceof Error?e.message:String(e))}if(n.length>0&&0===r.length)throw new Error(`none of the ${e.length} FileDescriptorProto(s) attached by @grpc/proto-loader could be decoded, so no method or field metadata is available. First failure: ${n[0]}`);return n.length>0&&t.push(`${n.length} of ${e.length} FileDescriptorProto(s) could not be decoded and their symbols are unavailable. First failure: ${n[0]}`),r}(u.buffers,n),i="proto",c.files.length>1&&n.push(`merged ${c.files.length} .proto file(s) from ${t.length} path(s).`)}const c={symbols:new Map,serviceDescriptors:new Map,mapEntries:new Set,notes:n,unnamedSeq:0};for(const e of s)$s(c,e);const{symbols:l,serviceDescriptors:u,mapEntries:d}=c,p=s.map(e=>{const t=Xo(e,"name","name");return"string"==typeof t&&""!==t?t:void 0}),f=p.length>0&&p.every(e=>void 0===e),m=[...new Set(p.filter(e=>void 0!==e))].sort();"proto"===i&&a&&As(a,m,f,n),function(e){const t={symbols:e.symbols,mapEntries:e.mapEntries},r=new Map,n=(e,t)=>{const n=r.get(e)??[];n.includes(t)||n.push(t),r.set(e,n)},o=(e,r,s)=>{for(const o of vs(s,"field","field")){const s=Xo(o,"typeName","type_name");"string"==typeof s&&""!==s&&void 0===gs(t,e,s)&&n(s,r)}for(const t of vs(s,"nestedType","nested_type")){const n=String(Xo(t,"name","name")??"");n&&o(`${e}.${n}`,r,t)}};for(const[t,r]of e.symbols)"message"===r.kind&&o(t,t,r.type);for(const[r,o]of e.serviceDescriptors)for(const e of vs(o,"method","method"))for(const[o,s]of[["inputType","input_type"],["outputType","output_type"]]){const i=Xo(e,o,s);"string"==typeof i&&""!==i&&void 0===gs(t,r,i)&&n(i,r)}if(0===r.size)return;const s=[...r.keys()].sort().slice(0,12),i=[...new Set([...r.values()].flat())].sort();e.notes.push(`${r.size} type reference(s) do not resolve against the symbol table: ${s.join(", ")}`+(r.size>s.length?" ...+"+(r.size-s.length):"")+`. Request templates for the messages using them will be incomplete. Referenced from: ${i.slice(0,6).join(", ")}`+(i.length>6?" ...+"+(i.length-6):"")+".")}(c);const h=[...u.keys()].sort(),y=function(e,t){const r=[],n=[];for(const[t,o]of Object.entries(e)){if(!o||"object"!=typeof o)continue;if("fileDescriptorProtos"in o)continue;const e=Object.values(o);0!==e.length?e.every(Es)&&r.push(t):n.push(t)}return n.length>0&&t.push(`${n.length} service(s) declare no methods and cannot be called: ${n.sort().join(", ")}.`),r.sort()}(o,n);return function(e,t,r){const n=new Set(e),o=new Set(t),s=e.filter(e=>!o.has(e)),i=t.filter(e=>!n.has(e));s.length>0&&r.push(`${s.length} service(s) are described but not invocable (no codecs were generated): ${s.join(", ")}.`),i.length>0&&r.push(`${i.length} service(s) are invocable but have no descriptor, so no request template can be generated: ${i.join(", ")}.`)}(h,y,n),0===h.length&&0===y.length&&n.push("proto"===i?`the ${a?.length??0} .proto file(s) loaded declare no services.`:"reflection returned descriptors that declare no services."),{catalog:{source:i,symbols:l,services:h,invocableServices:y,serviceDescriptors:u,notes:n,files:a,descriptorFiles:m,mapEntries:d,descriptorFilesUnnamed:f},packageDefinition:o}}function Ts(e,t){return e&&t?"bidi_streaming":e?"client_streaming":t?"server_streaming":"unary"}function ks(e,t,r,n,o){const s=(i=r).startsWith(".")?i.slice(1):i;var i;let a;try{a=function(e){if("string"==typeof e)return e||void 0;const t=e?.name;return"string"==typeof t&&t?t:void 0}(gs(e,t,r))}catch(e){return o.push(`resolving the ${n} type "${r}" failed: ${e instanceof Error?e.message:String(e)}. The name is reported as written.`),s}return a||(o.push(r.startsWith(".")?`the ${n} type "${s}" is not in the symbol table; the descriptor closure is incomplete. The name is reported as written.`:`the ${n} type "${r}" is a relative reference that could not be resolved in scope "${t||"(root)"}"; it is reported as written and is therefore not fully qualified.`),s)}function Os(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.path&&t.path.length>0&&"boolean"==typeof t.requestStream&&"boolean"==typeof t.responseStream&&"function"==typeof t.requestSerialize&&"function"==typeof t.responseDeserialize}function _s(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Ps(e,t){if(function(e){const t=["address","service","method"];for(const r of t){const t=e[r];if("string"!=typeof t||0===t.length)throw new TypeError(`GrpcTarget.${r} must be a non-empty string; received ${void 0===t?"undefined":typeof t}.`)}}(e),t&&(!t.catalog||!t.packageDefinition))throw new TypeError("ResolveMethodOptions requires both catalog and packageDefinition, from the same buildCatalog call.");const{catalog:r,packageDefinition:n}=t??await xs(e),o=[...r.notes],s=Object.prototype.hasOwnProperty.call(n,e.service)?n[e.service]:void 0;if(!s||"object"!=typeof s){const t=new Set([...r.invocableServices,...r.services]),n=r.services.includes(e.service)?" It exists in the descriptor but no codecs were generated for it, so it cannot be called.":` Available: ${[...t].sort().join(", ")||"(none)"}`;throw new Error(`service "${e.service}" is not invocable (source: ${r.source}).${n}`)}const i=function(e){const t=new Map,r=new Set;for(const n of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const o=e[n];if(!Os(o))continue;const s=_s(o.path);r.has(s)||(t.set(s,o),n===s&&r.add(s))}return t}(s),a=[...i.keys()],c=function(e,t){if(e.includes(t))return{name:t,exact:!0};const r=t.toLowerCase(),n=e.filter(e=>e.toLowerCase()===r);return 1===n.length?{name:n[0],exact:!1}:void 0}(a,e.method);if(!c){const t=a.filter(t=>t.toLowerCase()===e.method.toLowerCase()).length>1;throw new Error(t?`method "${e.method}" is ambiguous on ${e.service}; several methods differ only in case. Use the exact name.`:`method "${e.method}" not found on ${e.service}. Available: ${[...a].sort().join(", ")||"(none)"}`)}c.exact||o.push(`method matched case-insensitively: requested "${e.method}", using "${c.name}".`);const l=i.get(c.name),u=l.requestStream,d=l.responseStream,p=function(e,t,r){const n=e.serviceDescriptors.get(t);if(void 0!==n)try{return ms(n)}catch(e){if(!(e instanceof Ko))throw e;return void r.push(`the descriptor for ${t} is unreadable, so message type names are unavailable and no request template can be generated; the call itself is unaffected: ${e.message}`)}else r.push(`no descriptor for ${t} in the ${e.source} catalog; the call can still be made but request templates and message type names are unavailable.`)}(r,e.service,o);let f;if(p&&(f=p.find(e=>e.name===c.name),f||o.push(`method "${c.name}" is invocable but absent from the ${e.service} descriptor; message type names are unavailable.`)),f&&(f.clientStreaming!==u||f.serverStreaming!==d))throw new Error(`descriptor and runtime disagree on the streaming kind of ${e.service}/${c.name}: descriptor says ${Ts(f.clientStreaming,f.serverStreaming)}, runtime says ${Ts(u,d)}. Refusing to dial, because either choice would misuse the stream. The descriptor source is likely stale or mixed — reload the proto tree, or clear cached reflection data.`);const m=`/${e.service}/${c.name}`;l.path!==m&&o.push(`the method path reported by the loader (${l.path}) differs from the expected ${m}; the loader's path is used.`);const h=function(e){const t=e.lastIndexOf(".");return t>0?e.slice(0,t):""}(e.service),y=f?ks(r,h,f.inputType,"request",o):void 0,g=f?ks(r,h,f.outputType,"response",o):void 0;return{name:c.name,kind:Ts(u,d),path:l.path,requestStream:u,responseStream:d,serialize:e=>l.requestSerialize(e),deserialize:e=>l.responseDeserialize(e),inputType:y,outputType:g,source:r.source,notes:o}}var Ms={0:"OK",1:"CANCELLED",2:"UNKNOWN",3:"INVALID_ARGUMENT",4:"DEADLINE_EXCEEDED",5:"NOT_FOUND",6:"ALREADY_EXISTS",7:"PERMISSION_DENIED",8:"RESOURCE_EXHAUSTED",9:"FAILED_PRECONDITION",10:"ABORTED",11:"OUT_OF_RANGE",12:"UNIMPLEMENTED",13:"INTERNAL",14:"UNAVAILABLE",15:"DATA_LOSS",16:"UNAUTHENTICATED"},Ds=0,Cs=1,js=2,Is=3,Ns=200;function Bs(e,t){return{code:e,codeName:Ms[e]??`CODE_${e}`,details:t}}function Rs(e){const t=e;if("function"!=typeof t?.toJSON)return{};const r={};for(const[e,n]of Object.entries(t.toJSON())){const t=Array.isArray(n)?n:[n];r[e]=t.map(e=>Buffer.isBuffer(e)?e.toString("base64"):String(e))}return r}var qs=new Set(["max_messages","idle_timeout","max_session","aborted"]);function Ls(e,t){if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<0))throw new RangeError(`${e} must be a finite number of milliseconds >= 0; received ${"number"==typeof t?t:typeof t}.`)}async function Fs(e,t={},r){const n=Date.now(),o=function(e){if(void 0===e)return[];if(!Array.isArray(e))throw new TypeError(`options.messages must be an array of request payloads; received ${null===e?"null":typeof e}. A single message still goes in an array.`);return e}(t.messages);if(function(e,t){if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new RangeError(`${e} must be a non-negative integer; received ${"number"==typeof t?t:typeof t}. A fractional limit can never be reached by a message count.`)}("maxMessages",t.maxMessages),Ls("idleTimeoutMs",t.idleTimeoutMs),Ls("maxSessionMs",t.maxSessionMs),Ls("sendIntervalMs",t.sendIntervalMs),Ls("deadlineMs",e.deadlineMs),void 0!==t.signal&&null!==t.signal){const e=t.signal;if("function"!=typeof e.addEventListener||"boolean"!=typeof e.aborted)throw new TypeError("options.signal must be an AbortSignal (pass controller.signal, not the controller).")}if(void 0!==t.onEvent&&"function"!=typeof t.onEvent)throw new TypeError(`options.onEvent must be a function; received ${typeof t.onEvent}.`);const s=await kn(),{grpc:i}=s,a=r??await(async()=>{const t=await xs(e);return{catalog:t.catalog,packageDefinition:t.packageDefinition,includeSourceNotes:!1}})(),c=await Ps(e,{catalog:a.catalog,packageDefinition:a.packageDefinition}),l=new Set(a.catalog.notes),u=a.includeSourceNotes?[...c.notes]:c.notes.filter(e=>!l.has(e)),d=[],p=[];let f,m,h,y,g,v,b=0,w=!1;if(!c.requestStream&&o.length>1&&u.push(`${c.kind} accepts a single request message; ${o.length-1} extra message(s) were ignored.`),c.requestStream||0!==o.length||u.push(`${c.kind} requires a request message and none was given; an empty message was sent, which on the wire means "all defaults".`),t.keepWriteOpen&&"bidi_streaming"!==c.kind&&u.push(`keepWriteOpen only applies to bidi_streaming; ignored for ${c.kind}.`),void 0===t.sendIntervalMs||c.requestStream||u.push(`sendIntervalMs paces the outbound stream and has no effect on ${c.kind}, which sends exactly one message.`),t.keepWriteOpen&&"bidi_streaming"===c.kind){const r=void 0!==t.maxSessionMs||void 0!==t.idleTimeoutMs||void 0!==t.maxMessages||Boolean(t.signal);r||void 0!==e.deadlineMs?r||u.push(`keepWriteOpen is bounded only by deadlineMs (${e.deadlineMs}ms); since the write side is never half-closed, the call will end in DEADLINE_EXCEEDED unless the server closes the stream first. Set maxMessages, idleTimeoutMs, or maxSessionMs for a clean stop.`):u.push("keepWriteOpen is set with no limit and no deadline; the call can only end when the server closes the stream.")}const S=Mn(e,s);u.push(...S.warnings);const $=function(e,t){const r=new e.Metadata;for(const[e,n]of Object.entries(t??{})){const t=Array.isArray(n)?n:[n];for(const n of t){if("string"!=typeof n&&!Buffer.isBuffer(n))throw new TypeError(`metadata["${e}"] must be a string, a Buffer, or an array of those; received ${null===n?"null":typeof n}. Binary values require a key ending in "-bin".`);try{r.add(e,n)}catch(t){throw new TypeError(`metadata key "${e}" was rejected by grpc-js: ${t instanceof Error?t.message:String(t)}. Keys must match [0-9a-z_.-]+, and only keys ending in "-bin" may carry Buffers.`)}}}return r}(i,e.metadata);let E;try{E=new i.Client(e.address,S.credentials,e.channelOptions)}catch(t){throw new Error(`could not create a channel to "${e.address}": ${t instanceof Error?t.message:String(t)}. Expected host:port.`)}const A={};return void 0!==e.deadlineMs&&(A.deadline=new Date(Date.now()+e.deadlineMs)),await new Promise(e=>{let r,n,s,i,a,l,S=!1,x=!1,T=!1,k=!1;const O=e=>{if(S)return;const r={...e,seq:b++,at:Date.now()};if(d.push(r),t.onEvent)try{t.onEvent(r)}catch{}},_=(e,t)=>{x||(x=!0,h=e,y=t)},P=e=>{T||w||(T=!0,m=e)},M=o=>{if(!S){o&&(w=!0,f=o,qs.has(o)&&_(Bs(Cs,`call stopped by the client (${o}); the server never reported a status`),"synthesized")),k&&!x&&(_(Bs(Ds),"synthesized"),u.push(`the response was received but the server's status did not arrive within ${Ns}ms; OK was inferred from the successful response and no trailing metadata is available.`)),k=!1,S=!0,clearTimeout(r),clearTimeout(n),clearTimeout(s),clearTimeout(i),l&&t.signal&&t.signal.removeEventListener("abort",l);try{a?.cancel()}catch{}try{E.close()}catch{}e()}},D=()=>{S||void 0!==t.idleTimeoutMs&&(clearTimeout(r),r=setTimeout(()=>M("idle_timeout"),t.idleTimeoutMs))},C=e=>{S||(p.push(e),O({direction:"inbound",payload:e}),D(),void 0!==t.maxMessages&&p.length>=t.maxMessages&&M("max_messages"))},j=()=>{S||x?M():(k=!0,clearTimeout(r),i=setTimeout(()=>M(),Ns))},I=e=>{const t=e,r=Bs(t.code??js,t.details??t.message),n=void 0===t.code?"client":"server";_(r,n),P(t.message??String(e)),O({direction:"status",status:r,statusOrigin:n}),M()},N=(e,t,r)=>{const n=Bs(e,t);_(n,"client"),P(r instanceof Error?r.message:String(r)),O({direction:"status",status:n,statusOrigin:"client"}),M()};if(0===t.maxMessages)return u.push("maxMessages is 0, so the call is stopped before any response is read."),void M("max_messages");if(void 0!==t.maxSessionMs&&(n=setTimeout(()=>M("max_session"),t.maxSessionMs)),t.signal){if(t.signal.aborted)return void M("aborted");l=()=>M("aborted"),t.signal.addEventListener("abort",l,{once:!0})}const B=e=>c.serialize(e),R=e=>c.deserialize(e),q=(e,t)=>{try{return c.serialize(e),!0}catch(e){return N(Is,`request message #${t} does not match ${c.inputType??"the request type"}`,e),!1}},L=e=>{e.on("metadata",e=>{g=Rs(e),O({direction:"meta",metadata:g})}),e.on("status",e=>{const t=e;v=Rs(t.metadata);const r=Bs(t.code,t.details);_(r,"server"),O({direction:"status",status:r,statusOrigin:"server",metadata:v}),(c.responseStream||k)&&M()})},F=e=>{let r=0;const n=()=>{if(S)return;if(r>=o.length){if(!(!0===t.keepWriteOpen&&"bidi_streaming"===c.kind))try{e.end?.()}catch{}return}const i=r,a=o[r++];if(q(a,i)){try{e.write?.(a),O({direction:"outbound",payload:a}),D()}catch(e){return void N(js,`write of message #${i} failed`,e)}t.sendIntervalMs?s=setTimeout(n,t.sendIntervalMs):n()}};n()};try{if("unary"===c.kind||"server_streaming"===c.kind){const e=o[0]??{};if(!q(e,0))return;O({direction:"outbound",payload:e}),"unary"===c.kind?(a=E.makeUnaryRequest(c.path,B,R,e,$,A,(e,t)=>{e?I(e):(C(t),j())}),L(a),a.on("error",I)):(a=E.makeServerStreamRequest(c.path,B,R,e,$,A),L(a),a.on("data",e=>C(e)),a.on("error",I),a.on("end",()=>{_(Bs(Ds),"synthesized"),M()}))}else"client_streaming"===c.kind?(a=E.makeClientStreamRequest(c.path,B,R,$,A,(e,t)=>{e?I(e):(C(t),j())}),L(a),a.on("error",I),F(a)):(a=E.makeBidiStreamRequest(c.path,B,R,$,A),L(a),a.on("data",e=>C(e)),a.on("error",I),a.on("end",()=>{_(Bs(Ds),"synthesized"),M()}),F(a))}catch(e){return void N(js,"call setup failed",e)}D()}),{protocol:"grpc",kind:c.kind,target:e,events:d,messages:p,initialMetadata:g,status:h,statusOrigin:y,trailers:v,truncated:w,truncatedReason:f,error:m,warnings:u,durationMs:Date.now()-n}}var Us=Symbol("omit"),zs={TYPE_DOUBLE:0,TYPE_FLOAT:0,TYPE_INT32:0,TYPE_UINT32:0,TYPE_SINT32:0,TYPE_FIXED32:0,TYPE_SFIXED32:0,TYPE_BOOL:!1,TYPE_STRING:"",TYPE_BYTES:"",TYPE_INT64:"0",TYPE_UINT64:"0",TYPE_SINT64:"0",TYPE_FIXED64:"0",TYPE_SFIXED64:"0"},Vs={"google.protobuf.Timestamp":"1970-01-01T00:00:00Z","google.protobuf.Duration":"0s","google.protobuf.Empty":{},"google.protobuf.StringValue":"","google.protobuf.BoolValue":!1,"google.protobuf.Int32Value":0,"google.protobuf.Int64Value":"0","google.protobuf.UInt32Value":0,"google.protobuf.UInt64Value":"0","google.protobuf.DoubleValue":0,"google.protobuf.FloatValue":0,"google.protobuf.BytesValue":"","google.protobuf.FieldMask":"","google.protobuf.Struct":{},"google.protobuf.ListValue":[]},Gs=new Set(["google.protobuf.Value","google.protobuf.Any"]);function Ws(e){return e.startsWith(".")?e.slice(1):e}function Js(e,t){return e?`${e}.${t}`:t}var Hs=!0===hs.keepCase?"declared":"json";function Ys(e){return"declared"===Hs?e.name:e.jsonName??e.name.replace(/_([a-z0-9])/g,(e,t)=>t.toUpperCase())}function Ks(e,t,r={}){const n={catalog:e,maxDepth:r.maxDepth??4,seedCollections:!1!==r.seedCollections,fillExplicitOptional:!0===r.fillExplicitOptional,fillMessageFields:!1!==r.fillMessageFields,keyOf:Ys,oneofs:[],enums:[],collections:[],presence:[],warnings:[],stack:[],hintDepth:0},o=Ws(t),s=ei(n,"",t)??o;let i={};try{i=si(n,s,"",0)??{}}catch(e){if(!(e instanceof Ko))throw e;n.warnings.push(`template generation stopped: ${e.message}. The request must be composed by hand.`)}return{message:s,example:i,keyStyle:Hs,oneofs:n.oneofs,enums:n.enums,collections:n.collections,presence:n.presence,warnings:n.warnings}}function Qs(e){return 0===e.hintDepth}function Xs(e,t){Qs(e)&&e.warnings.push(t)}function Zs(e,t){e.hintDepth++;try{return t()}finally{e.hintDepth--}}function ei(e,t,r){const n=gs(e.catalog,t,r);if(void 0!==n)return"message"===e.catalog.symbols.get(n)?.kind?n:void 0}function ti(e,t){const r=e.catalog.symbols.get(t);return"message"===r?.kind?r.type:void 0}function ri(e,t,r){return r.typeName?gs(e.catalog,t,r.typeName)??Ws(r.typeName):r.type}function ni(e,t,r){const n=ti(e,t);if(!n)return;const o=Ws(r),s=o.slice(o.lastIndexOf(".")+1);try{for(const e of(ds(i=n),es(i,"nestedType","nested_type","DescriptorProto"))){if(String(Xo(e,"name","name")??"")!==s)continue;if(!ps(e))continue;const t=us(e),r=t.find(e=>"key"===e.name),n=t.find(e=>"value"===e.name);if(r&&n)return{keyType:r.type,valueField:n}}}catch(e){if(!(e instanceof Ko))throw e;return}var i}function oi(e,t){return 1===t.length&&("LABEL_REPEATED"!==t[0].label&&(void 0===e||e===`_${t[0].name}`))}function si(e,t,r,n){if(n>e.maxDepth)return Xs(e,`recursion depth ${e.maxDepth} reached at "${r||"(root)"}" (${t}); the value is an empty message, which on the wire means "set with all defaults" — remove the key to leave it unset.`),{};if(e.stack.includes(t))return Xs(e,`cyclic reference to ${t} at "${r}"; the value is an empty message, which on the wire means "set with all defaults".`),{};const o=ti(e,t);if(!o)return Xs(e,`message "${t}" is not in the symbol table (referenced at "${r||"(root)"}"); left as an empty object. The descriptor closure is incomplete — the catalog notes say which references failed.`),{};e.stack.push(t);try{const i=us(o),a=(ds(s=o),es(s,"oneofDecl","oneof_decl","DescriptorProto").map((e,t)=>ts(e,"name","name",`OneofDescriptorProto[${t}]`))),c={},l=new Map;for(const e of i){if(void 0===e.oneofIndex)continue;const t=l.get(e.oneofIndex)??[];t.push(e),l.set(e.oneofIndex,t)}const u=new Map,d=new Set;for(const[r,n]of l){if(n.every(e=>e.proto3Optional)||oi(a[r],n))for(const e of n)d.add(e.name);else{const o=n.filter(e=>e.proto3Optional);if(o.length>0){Xs(e,`oneof "${a[r]??r}" in ${t} mixes ${o.length} explicit-presence member(s) with ${n.length-o.length} plain one(s), which protoc does not produce. All of them are treated as optional fields and left unset; set at most one by hand.`);for(const e of n)d.add(e.name)}else u.set(r,n)}}const p=new Set;for(const o of i){const s=e.keyOf(o),i=Js(r,o.name);if(void 0!==o.oneofIndex&&u.has(o.oneofIndex)){if(p.has(o.oneofIndex))continue;p.add(o.oneofIndex);const s=u.get(o.oneofIndex),i=s[0],l=ii(e,t,i,Js(r,i.name),n),d={};l!==Us&&(d[e.keyOf(i)]=l),Zs(e,()=>{for(const o of s.slice(1)){const s=ii(e,t,o,Js(r,o.name),n);s!==Us&&(d[e.keyOf(o)]=s)}}),Qs(e)&&e.oneofs.push({at:r,oneof:a[o.oneofIndex]??`oneof_${o.oneofIndex}`,branches:s.map(e=>e.name),chosen:i.name,branchValues:d}),l!==Us&&(c[e.keyOf(i)]=l);continue}if(o.proto3Optional||d.has(o.name)){const r=Zs(e,()=>ii(e,t,o,i,n));Qs(e)&&e.presence.push({at:i,reason:"proto3_optional",presentInExample:e.fillExplicitOptional,valueIfSet:r===Us?void 0:r}),e.fillExplicitOptional&&r!==Us&&(c[s]=r);continue}const l=ii(e,t,o,i,n);l!==Us&&(c[s]=l)}return c}finally{e.stack.pop()}var s}function ii(e,t,r,n,o){const s="LABEL_REPEATED"===r.label;if(s&&"TYPE_MESSAGE"===r.type&&r.typeName){const s=ni(e,t,r.typeName);if(s){if(Qs(e)&&e.collections.push({at:n,kind:"map",of:ri(e,t,s.valueField),keyOf:s.keyType}),!e.seedCollections)return{};const r="TYPE_STRING"===s.keyType?"key":"0",i=ai(e,t,s.valueField,`${n}.${r}`,o);return i===Us?{}:{[r]:i}}Xs(e,`"${n}" is a repeated ${Ws(r.typeName)} that could not be read as a map entry; treating it as a repeated message field.`)}if(s){if(Qs(e)&&e.collections.push({at:n,kind:"repeated",of:ri(e,t,r)}),!e.seedCollections)return[];const s=ai(e,t,r,`${n}[0]`,o);return s===Us?[]:[s]}return ai(e,t,r,n,o)}function ai(e,t,r,n,o){if("TYPE_ENUM"===r.type){const o=r.typeName,s=function(e,t,r){const n=gs(e.catalog,t,r);if(void 0!==n)return"enum"===e.catalog.symbols.get(n)?.kind?n:void 0}(e,t,o),i=s??Ws(o);let a=[];if(void 0!==s){const t=function(e,t){const r=e.catalog.symbols.get(t);return"enum"===r?.kind?r.type:void 0}(e,s);try{a=fs(t)}catch(t){if(!(t instanceof Ko))throw t;Xs(e,`enum "${i}" at "${n}" is unreadable: ${t.message}`)}}return 0===a.length?(Xs(e,void 0===s?`enum "${i}" at "${n}" does not resolve from scope "${t}"; the example uses an empty string, which the server will reject. The catalog notes list the failed references.`:`enum "${i}" at "${n}" declares no values; the example uses an empty string, which the server will reject.`),""):(Qs(e)&&e.enums.push({at:n,enum:i,values:a}),a[0])}if("TYPE_MESSAGE"===r.type||"TYPE_GROUP"===r.type){const s=r.typeName,i=Ws(s),a=ei(e,t,s),c=a??i;if("google.protobuf.Any"===c||"google.protobuf.Any"===i)return Xs(e,`"${n}" is google.protobuf.Any; its payload is passed through unmodified and is not validated against the descriptor. Editing support is not available in this version.`),{"@type":"",value:{}};if(Gs.has(c)||Gs.has(i))return Xs(e,`"${n}" is ${c}, whose JSON form is any JSON value; no example can be generated without guessing. Supply it by hand.`),{};if(c in Vs)return Vs[c];if(i in Vs)return Vs[i];if(void 0===a)return Xs(e,`message "${i}" at "${n}" does not resolve from scope "${t}"; left as an empty object, which on the wire means "set with all defaults". The catalog notes list the failed references.`),Qs(e)&&e.presence.push({at:n,reason:"message",presentInExample:e.fillMessageFields,valueIfSet:{}}),e.fillMessageFields?{}:Us;const l=si(e,a,n,o+1)??{};return Qs(e)&&e.presence.push({at:n,reason:"message",presentInExample:e.fillMessageFields,valueIfSet:l}),e.fillMessageFields?l:Us}return r.type in zs?zs[r.type]:(Xs(e,`unhandled field type ${r.type} at "${n}"; the example uses null, which will not serialise.`),null)}var ci=(e,t)=>e.name<t.name?-1:e.name>t.name?1:0;function li(e,t){return e&&t?"bidi_streaming":e?"client_streaming":t?"server_streaming":"unary"}function ui(e){return e.startsWith(".")?e.slice(1):e}function di(e){const t=e.lastIndexOf(".");return-1===t?"":e.slice(0,t)}function pi(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function fi(e,t){const r=new Map,n=e[t];if(!n||"object"!=typeof n)return r;for(const[e,t]of Object.entries(n)){const n=t;if(!n||"object"!=typeof n||"string"!=typeof n.path)continue;const o={key:e,path:n.path,requestStream:!0===n.requestStream,responseStream:!0===n.responseStream,hasCodecs:"function"==typeof n.requestSerialize&&"function"==typeof n.responseDeserialize},s=pi(o.path),i=r.get(s);i&&i.key===s||r.set(s,o)}return r}function mi(e,t,r){const n=e.serviceDescriptors.get(t);if(void 0!==n)try{return ms(n)}catch(e){return void r.push(`descriptor for ${t} is unreadable, so request templates and type names are unavailable for it: ${e instanceof Error?e.message:String(e)}`)}}function hi(e,t,r,n,o={}){if(!(e.serviceDescriptors.has(r)||e.invocableServices.includes(r))){const t=[...new Set([...e.services,...e.invocableServices])].sort();throw new Error(`service "${r}" not found (source: ${e.source}). Available: ${t.join(", ")||"(none)"}`)}const s=[...e.notes],i=mi(e,r,s),a=fi(t,r);let c=i?.find(e=>e.name===n);if(!c&&i){const e=i.filter(e=>e.name.toLowerCase()===n.toLowerCase());if(1===e.length)s.push(`method matched case-insensitively: requested "${n}", using "${e[0].name}".`),c=e[0];else if(e.length>1)throw new Error(`method "${n}" is ambiguous on ${r}: ${e.map(e=>e.name).sort().join(", ")}. Use the exact declared name.`)}if(!c)throw function(e,t,r,n,o){const s=(n??[]).map(e=>e.name).sort(),i=[...o.keys()].sort();if(void 0===n)return new Error(`cannot describe "${e}/${t}": no readable descriptor for ${e} (source: ${r}), so no method metadata is available. The method may still be callable — the runtime view lists ${i.join(", ")||"(none)"}.`);const a=i.filter(e=>!s.includes(e));return o.has(t)?new Error(`method "${t}" is callable on ${e} but missing from its descriptor (source: ${r}), so no request template can be built. Described: ${s.join(", ")||"(none)"}.`+(a.length?` Also undescribed: ${a.filter(e=>e!==t).join(", ")||"(none)"}.`:"")):new Error(`method "${t}" not found on ${e} (source: ${r}). Described: ${s.join(", ")||"(none)"}`+(a.length?`; callable but undescribed: ${a.join(", ")}`:"")+".")}(r,n,e.source,i,a);const l=a.get(c.name),u={name:c.name,path:l?.path??`/${r}/${c.name}`,kind:li(c.clientStreaming,c.serverStreaming),inputType:ui(c.inputType),outputType:ui(c.outputType),requestStream:c.clientStreaming,responseStream:c.serverStreaming,invocable:!0===l?.hasCodecs};u.invocable||s.push(`${r}/${c.name} can be described but not called: the loaded definition has no codecs for it.`);const d={maxDepth:o.maxDepth,seedCollections:o.seedCollections,fillExplicitOptional:o.fillExplicitOptional,fillMessageFields:o.fillMessageFields};let p,f;if(void 0===u.inputType)s.push(`the request type of ${r}/${u.name} is unknown, so no template can be built.`);else try{p=Ks(e,u.inputType,d)}catch(e){if(!(e instanceof Ko))throw e;s.push(`request template unavailable: ${e.message}`)}if(o.includeResponse)if(void 0===u.outputType)s.push(`the response type of ${r}/${u.name} is unknown, so its shape is unavailable.`);else try{f=Ks(e,u.outputType,d)}catch(e){if(!(e instanceof Ko))throw e;s.push(`response shape unavailable: ${e.message}`)}return{...u,service:r,request:p,response:f,notes:s}}function yi(e,t,r){const n=[...t.notes],o=[...new Set([...t.services,...t.invocableServices])].sort().map(e=>function(e,t,r,n){const o=[],s=new Set;for(const i of t??[]){s.add(i.name);const t=r.get(i.name);if(t){const r=li(i.clientStreaming,i.serverStreaming),o=li(t.requestStream,t.responseStream);r!==o&&n.push(`streaming flags disagree for ${e}/${i.name}: descriptor says ${r}, runtime says ${o}. Calls to this method will be refused.`)}o.push({name:i.name,path:t?.path??`/${e}/${i.name}`,kind:li(i.clientStreaming,i.serverStreaming),inputType:ui(i.inputType),outputType:ui(i.outputType),requestStream:i.clientStreaming,responseStream:i.serverStreaming,invocable:!0===t?.hasCodecs})}const i=[];for(const[e,t]of r)s.has(e)||(i.push(e),o.push({name:e,path:t.path,kind:li(t.requestStream,t.responseStream),inputType:void 0,outputType:void 0,requestStream:t.requestStream,responseStream:t.responseStream,invocable:t.hasCodecs}));i.length&&n.push(`${e}: ${i.sort().join(", ")} ${1===i.length?"is":"are"} callable but absent from the descriptor; no request template can be generated for ${1===i.length?"it":"them"}.`);const a=o.filter(e=>!e.invocable).map(e=>e.name);return a.length&&t&&n.push(`${e}: ${a.sort().join(", ")} ${1===a.length?"is":"are"} declared but not invocable; the loaded definition has no codecs for ${1===a.length?"it":"them"}.`),o.sort(ci),{name:e,package:di(e),methods:o,views:t&&r.size>0?"both":t?"descriptor_only":"runtime_only"}}(e,mi(t,e,n),fi(r,e),n));return{address:e.address,source:t.source,services:o,files:t.files,notes:n}}async function gi(e){const{catalog:t,packageDefinition:r}=await xs(e);return yi(e,t,r)}function vi(e){return void 0!==e&&!1!==e&&(!0===e?"system":{roots:e.rootCerts?.length??0,key:e.privateKey?.length??0,chain:e.certChain?.length??0,skipHostname:!0===e.skipHostnameVerification})}function bi(e){return Array.isArray(e)?[...e].filter(e=>"string"==typeof e).sort():[]}function wi(e){return!0===e.reflection?JSON.stringify({kind:"reflection",address:e.address,version:e.reflectionVersion??null,host:e.reflectionHost??null,tls:vi(e.tls)}):JSON.stringify({kind:"proto",address:e.address,protoPaths:bi(e.protoPaths),includeDirs:bi(e.includeDirs),ignoreDirs:bi(e.ignoreDirs),followSymlinks:!0===e.followSymlinks,tls:vi(e.tls)})}function Si(e){return"string"==typeof e&&e.length>0}function $i(e){if(!e||"object"!=typeof e)return!1;const t=e;return!!Si(t.address)&&(!0===t.reflection||Array.isArray(t.protoPaths)&&t.protoPaths.length>0&&t.protoPaths.every(Si))}var Ei=class{protocol="grpc";catalogTtlMs;maxCachedCatalogs;catalogs=new Map;building=new Map;constructor(e={}){const t=e.catalogTtlMs??3e4;if(!Number.isFinite(t)||t<0)throw new RangeError(`catalogTtlMs must be a finite number >= 0; received ${t}.`);const r=e.maxCachedCatalogs??32;if(!Number.isInteger(r)||r<1)throw new RangeError(`maxCachedCatalogs must be an integer >= 1; received ${r}.`);this.catalogTtlMs=t,this.maxCachedCatalogs=r}supports(e){if(!$i(e))return!1;const t=e;return Si(t.service)&&Si(t.method)}assertSupported(e){if(!this.supports(e))throw new Error("not a usable gRPC target: address, service and method are required, plus either protoPaths (a non-empty array of files or directories) or reflection: true.");return e}assertEndpoint(e){if(!$i(e))throw new Error("not a usable gRPC endpoint: address is required, plus either protoPaths (a non-empty array of files or directories) or reflection: true.");return e}async catalogFor(e){const t=wi(e);if(this.catalogTtlMs>0){const e=this.catalogs.get(t);if(e&&Date.now()-e.at<=this.catalogTtlMs)return this.catalogs.delete(t),this.catalogs.set(t,e),e;e&&this.catalogs.delete(t)}const r=this.building.get(t);if(r)return r;const n=xs(e).then(({catalog:e,packageDefinition:r})=>{const n={catalog:e,packageDefinition:r,at:Date.now()};return this.catalogTtlMs>0&&(this.catalogs.set(t,n),this.evict()),n}).finally(()=>{this.building.delete(t)});return this.building.set(t,n),n}evict(){for(;this.catalogs.size>this.maxCachedCatalogs;){const e=this.catalogs.keys().next();if(e.done)return;this.catalogs.delete(e.value)}}invalidate(e){if(!e)return this.catalogs.clear(),void this.building.clear();const t=wi(e);this.catalogs.delete(t),this.building.delete(t)}async sourceNotes(e){const t=this.assertEndpoint(e),{catalog:r}=await this.catalogFor(t);return[...r.notes]}async plan(e){const t=this.assertSupported(e),{catalog:r,packageDefinition:n}=await this.catalogFor(t),o=await Ps(t,{catalog:r,packageDefinition:n}),s=(new Set(r.notes),[...o.notes,'the exported collection is not a valid Postman v2.1.0 document: gRPC has no standard representation there, so method is written as "GRPC" and the invocation details live under protocolProfileBehavior. Import support depends on the client.',"only address, service, method and metadata survive the export. Message payloads, stream pacing, deadlines and truncation limits do not.","gRPC results cannot be written back into an OpenAPI document; writeBack is ignored for protocol=grpc.",...Ai(t)]);return{streaming:o.requestStream||o.responseStream,warnings:s,environment:{baseUrl:t.address},collection:xi(t,o)}}async run(e,t){const r=this.assertSupported(e),{catalog:n,packageDefinition:o}=await this.catalogFor(r);return Fs(r,t??{},{catalog:n,packageDefinition:o,includeSourceNotes:!1})}async discover(e){const t=this.assertEndpoint(e),{catalog:r,packageDefinition:n}=await this.catalogFor(t);return yi(t,r,n)}async describeMethod(e,t,r,n={}){const o=this.assertEndpoint(e);if(!Si(t)||!Si(r))throw new TypeError("describeMethod needs a non-empty service and method name.");const{catalog:s,packageDefinition:i}=await this.catalogFor(o);return hi(s,i,t,r,{includeResponse:!0,...n})}};function Ai(e){const t=e.tls;if(void 0===t||!1===t||!0===t)return[];const r=[];return(t.privateKey||t.certChain)&&r.push("the client certificate"),t.rootCerts&&r.push("the custom CA bundle"),t.skipHostnameVerification&&r.push("skipHostnameVerification, which the importing client will not honour"),0===r.length?[]:[`the export records only that TLS is enabled; ${r.join(" and ")} will be absent, so the imported request will not connect as configured.`]}function xi(e,t){const r=`${e.service}/${t.name}`;return{info:{name:r,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[{name:r,request:{method:"GRPC",url:{raw:`grpc://${e.address}${t.path}`},description:`kind=${t.kind} source=${t.source}`,header:Object.entries(e.metadata??{}).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>({key:e,value:Buffer.isBuffer(t)?t.toString("base64"):String(t)})))},protocolProfileBehavior:{grpc:{service:e.service,methodName:t.name,methodType:t.kind,url:e.address,tls:void 0!==e.tls&&!1!==e.tls}}}]}}function Ti(e,t,r,n={}){const o=structuredClone(e??{});o.openapi??="3.2.0",o.paths??={};const s=(n.pathPrefix??"/grpc").replace(/\/+$/,"");for(const e of t.services)for(const t of e.methods){const n=`${s}/${e.name.replace(/\./g,"/")}/${t.name}`;o.paths[n]??={},o.paths[n].post={operationId:`grpc_${e.name.replace(/\./g,"_")}_${t.name}`.replace(/[^A-Za-z0-9_]/g,"_"),summary:`${e.name}/${t.name}`,tags:["grpc"],"x-protocol":"grpc","x-grpc":{address:r.address,service:e.name,method:t.name,kind:t.kind,reflection:!0===r.reflection||void 0,protoPaths:r.protoPaths,includeDirs:r.includeDirs,ignoreDirs:r.ignoreDirs},requestBody:{required:!1,content:{"application/json":{schema:{type:"object",properties:{messages:{type:"array",items:{type:"object"}}}}}}},responses:{200:{description:"gRPC result envelope"},default:{description:"gRPC error"}}}}return o}async function ki(e,t,r={}){const n=await gi(t);return{spec:Ti(e,n,t,r),discovery:n}}var Oi=class{name="grpc";adapter=new Ei;supports(e){const t=e.located.operation??{};return"grpc"===t["x-protocol"]?20:t["x-grpc"]?18:e.options.grpc?.address?15:0}plan(e){const t=function(e,t){const r={...e.operation?.["x-grpc"]??{},...t.grpc??{}};if(!r.address||!r.service||!r.method)throw y("BAD_GRPC_TARGET","x-grpc or options.grpc must define address, service and method");if(!0!==r.reflection&&(!Array.isArray(r.protoPaths)||0===r.protoPaths.length))throw y("BAD_GRPC_TARGET","gRPC target needs reflection:true or non-empty protoPaths");return r}(e.located,e.options);return{target:t,environment:{name:`${e.spec?.info?.title??"API"} gRPC Environment`,values:[{key:"grpcAddress",value:t.address,type:"default",enabled:!0}]},collection:{info:{name:`${t.service}/${t.method}`},item:[{name:`${t.service}/${t.method}`,request:{method:"GRPC",url:`grpc://${t.address}/${t.service}/${t.method}`}}]},streaming:!0,warnings:[`linked into OpenAPI as operationId grpc_${t.service.replace(/\./g,"_")}_${t.method}`]}}async execute(e,t,r){const n=t.values?.body,o=t.grpc?.sendOptions??{},s={...o,...n,messages:n?.messages??o.messages??t.grpc?.messages??t.messages};return function(e){const t=0===e.status?.code?200:500,r=(e.events??[]).map(e=>{const t="status"===e.direction?e.status:"meta"===e.direction?e.metadata:e.payload;return{id:String(e.seq),event:e.direction,data:JSON.stringify(t),parsed:t,receivedAt:e.at,direction:"outbound"===e.direction?"out":"in"}}),n=(e.events??[]).filter(e=>"outbound"===e.direction);return{protocol:"grpc",request:{method:"GRPC",url:`grpc://${e.target.address}/${e.target.service}/${e.target.method}`,headers:e.target.metadata??{},body:"unary"===e.kind||"server_streaming"===e.kind?n[0]?.payload:n.map(e=>e.payload)},response:{status:t,statusText:e.status?.codeName??"UNKNOWN",headers:e.initialMetadata??{},body:{kind:e.kind,messages:e.messages,status:e.status,trailers:e.trailers,events:e.events,truncated:e.truncated,truncatedReason:e.truncatedReason,warnings:e.warnings},contentType:"application/json",events:r,timings:{startedAt:Date.now()-e.durationMs,endedAt:Date.now(),durationMs:e.durationMs},sizeBytes:JSON.stringify(e.messages??[]).length,...e.truncated?{truncated:!0,stopReason:"maxEvents"}:{}},...e.error?{error:{message:e.error,code:e.status?.codeName}}:{}}}(await Fs(e.target,s))}};function _i(e={}){const t=new _e,r=e.adapters??[new zt,new nr,new $r,new yn,new Oi];for(const n of[...r,...e.extraAdapters??[]])t.register(n);const n=e=>{if(!e||"object"!=typeof e)throw y("BAD_OPTIONS","send() requires an options object");if(!e.spec||"object"!=typeof e.spec)throw y("BAD_OPTIONS","send() requires options.spec");const r=G(e.spec,e.target),n={spec:e.spec,options:e,located:r},o=t.resolve(n),s=o.plan(n);return{located:r,adapter:o,plan:s}};async function o(t){const{located:r,adapter:o,plan:s}=n(t),i=await(async(e,t,r)=>{const n=r.signal?{signal:r.signal}:void 0;try{return await e.execute(t,r,n)}catch(t){if(h.isProtoKitError(t))throw t;throw y("EXECUTION_FAILED",`Adapter "${e.name}" failed: ${v(t).message}`,t)}})(o,s,t),a=s,c=Array.isArray(a?.warnings)?[...a.warnings]:[];let l,u,d,p;try{l=Ee(i,e.response)}catch(e){u=`response fragment error: ${v(e).message}`,l={response:{description:"Fragment generation failed"},statusCode:String(i.response.status||"default")},c.push(u)}if(u)p=u;else if(!1===t.writeBack)p="disabled by options.writeBack";else if(i.response.status<=0)p="no response was received";else if(i.scripts?.skipped)p="request was skipped by a script";else if(!1!==e.writeBack?.requirePassingTests&&!1===i.scripts?.passed)p="one or more assertions failed";else if(i.response.truncated&&!1===e.writeBackTruncated)p=`stream was truncated (${i.response.stopReason??"unknown limit"})`;else{i.response.truncated&&c.push(`Schema inferred from a truncated stream (${i.response.stopReason??"unknown limit"}); fields appearing later were not observed.`),i.response.droppedEvents&&c.push(`${i.response.droppedEvents} event(s) exceeded the size caps and were not fully retained.`);try{d=ke(t.spec,r.path,r.method,l,e.writeBack)}catch(e){p=`write-back error: ${v(e).message}`}}return{...i,collection:a?.collection,environment:a?.environment,responseFragment:l.response,responseStatusCode:l.statusCode,patchedSpec:d,writeBackSkippedReason:p,...c.length?{writeBackWarnings:c}:{}}}return{registry:t,toCollection:function(e,t,r={}){const o={...r,spec:e,target:t},{located:s,adapter:i,plan:a}=n(o),c=a;return{protocol:i.name,located:s,collection:c?.collection,environment:c?.environment,streaming:c?.streaming,warnings:Array.isArray(c?.warnings)?c.warnings:void 0,plan:a}},send:o,sendMany:async function(e,t,r={}){if(!Array.isArray(t))throw y("BAD_OPTIONS","sendMany() requires an array of targets");let n=e;const s=[];for(const e of t){const t=e.signal??r.signal;if(t?.aborted)s.push({target:e.target,error:"aborted"});else try{const t=await o({...r,...e,spec:n});t.patchedSpec&&(n=t.patchedSpec),s.push(t)}catch(t){s.push({target:e.target,error:v(t).message})}}return{spec:n,results:s}}}}var Pi=c(require("@grpc/grpc-js"),1),Mi=c(require("@grpc/proto-loader"),1);function Di(e,t){if("string"!=typeof t||!t.trim())return;const r=t.split(".").reduce((e,t)=>e&&"object"==typeof e?e[t]:void 0,e);if("function"!=typeof r)return;const n=r;return n.service&&"object"==typeof n.service?r:void 0}function Ci(e,t,r){const n=function(e,t){if("string"!=typeof t||!t.trim())throw new Error("Invalid gRPC method name");const r=e.service??{};if(r[t])return t;const n=t.toLowerCase();for(const[e,t]of Object.entries(r)){const r="string"==typeof t?.path?t.path:void 0;if(e.toLowerCase()===n||r?.split("/").pop()?.toLowerCase()===n)return e}const o=Object.keys(r).sort();throw new Error(o.length?`Unable to resolve gRPC method "${t}". Available: ${o.join(", ")}`:`Unable to resolve gRPC method "${t}"`)}(e,t.method),o=e.service[n];if(!o)throw new Error(`Unable to resolve gRPC method "${t.service}/${t.method}"`);var s;return{client:new e(t.address,t.tls?Pi.credentials.createSsl():Pi.credentials.createInsecure(),t.channelOptions??{}),methodName:n,kind:(s=o,s.requestStream&&s.responseStream?"bidi_streaming":s.requestStream&&!s.responseStream?"client_streaming":!s.requestStream&&s.responseStream?"server_streaming":"unary"),source:r}}async function ji(e){const t={address:e.address,reflection:!0,metadata:e.metadata,channelOptions:e.channelOptions,tls:e.tls,reflectionTimeoutMs:e.reflectionTimeoutMs,reflectionVersion:e.reflectionVersion,reflectionHost:e.reflectionHost,loaderOptions:e.loaderOptions},{catalog:r,packageDefinition:n}=await xs(t),o=Di(Pi.loadPackageDefinition(function(e){if(!e||"object"!=typeof e)throw new Error("The gRPC descriptor source did not return a usable package definition.");for(const[t,r]of Object.entries(e))if(!r||"object"!=typeof r)throw new Error(`gRPC package definition entry "${t}" is not an object; the descriptor source returned an unexpected shape.`);return e}(n)),e.service);if(!o){const t=[...new Set([...r?.services??[],...r?.invocableServices??[]])].filter(e=>"string"==typeof e).sort();throw new Error(t.length?`Unable to resolve gRPC service "${e.service}" via reflection. Available: ${t.join(", ")}`:`Unable to resolve gRPC service "${e.service}" via reflection; the server exposed no services.`)}return Ci(o,e,"reflection")}async function Ii(e){const t=function(e){return Array.isArray(e.protoPaths)&&e.protoPaths.some(e=>"string"==typeof e&&e.trim())}(e),r=!0===e.reflection;if(!t&&!r)throw new Error("a gRPC endpoint needs a descriptor source: either set reflection: true, or pass protoPaths: string[] pointing at your .proto files or directories. Neither was provided.");return t?async function(e){const t=function(e){return(e.protoPaths??[]).filter(e=>"string"==typeof e&&e.trim().length>0)}(e);if(!t.length)throw new Error("protoPaths is required when loading a gRPC service from proto files.");const r=await zn({paths:t});if(!r.files.length)throw new Error("No .proto files were found under the given protoPaths.");const n=Gn(r),o=await Mi.load(r.files,{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:n.includeDirs,...e.loaderOptions??{}}),s=Di(Pi.loadPackageDefinition(o),e.service);if(!s)throw new Error(`Unable to resolve gRPC service "${e.service}" from the provided proto files. Make sure the name is fully qualified, e.g. "package.ServiceName".`);return Ci(s,e,"proto")}(e):ji(e)}function Ni(e){const t=f("grpc","grpc",`grpc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,1e3),r=[];let n,o,s,i,a,c,l="idle",u=0,d=()=>{};const p=new Promise(e=>{d=e});let m=null;function h(e){const r="outbound"===e.direction?"out":"inbound"===e.direction?"in":"meta",n={};void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.code&&(n.code=e.code),void 0!==e.details&&(n.details=e.details),void 0!==e.statusName&&(n.statusName=e.statusName);const o="data"===e.event;t.emit({direction:r,kind:e.event??"event",at:e.at,state:t.state,data:o?e.payload:void 0,meta:Object.keys(n).length?n:void 0,error:e.error})}function y(e){l=e,t.setState(e)}function g(){"closed"!==l&&(y("closed"),d())}function v(){if(!s)throw new Error("gRPC session is not open");return s}function b(e){e.on("metadata",e=>{h({direction:"meta",event:"metadata",metadata:e.getMap(),at:Date.now()})}),e.on("status",e=>{0===e.code?g():(y("error"),d()),m=null,h({direction:"status",event:"status",code:e.code,statusName:Pi.status[e.code],details:e.details,metadata:e.metadata?.getMap?.()??void 0,at:Date.now()})}),e.on("error",e=>{y("error"),h({direction:"status",event:"error",code:e?.code,statusName:"number"==typeof e?.code?Pi.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),d(),m=null}),e.on("end",()=>{"server_streaming"!==n&&"bidi_streaming"!==n||g(),h({direction:"meta",event:"end",at:Date.now()})})}function w(){if(m)return m;const e=v(),t={};return a&&(t.deadline=a),"client_streaming"===e.kind?(m=e.client[e.methodName](i,t,(e,t)=>{if(e)return y("error"),h({direction:"status",event:"error",code:e?.code,statusName:"number"==typeof e?.code?Pi.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),d(),void(m=null);h({direction:"inbound",event:"data",payload:t,at:Date.now()}),g(),m=null}),b(m),m):"bidi_streaming"===e.kind?(m=e.client[e.methodName](i,t),b(m),m.on("data",e=>{"closing"!==l&&"closed"!==l&&h({direction:"inbound",event:"data",payload:e,at:Date.now()})}),m):null}return{get protocol(){return"grpc"},get state(){return l},get kind(){return n},get source(){return o},get events(){return t.events},onEvent:e=>t.onEvent(e),get warnings(){return r},async open(){if(c)return c;if("idle"!==l&&"closed"!==l&&"error"!==l)throw new Error(`gRPC session cannot open from state "${l}"`);return y("connecting"),c=(async()=>{try{const t=await Ii(e);s=t,n=t.kind,o=t.source,i=function(e){const t=new Pi.Metadata;for(const[r,n]of Object.entries(e??{}))t.set(r,n);return t}(e.metadata),a=function(e){if(e&&!(e<=0))return new Date(Date.now()+e)}(e.deadlineMs),"client_streaming"!==n&&"bidi_streaming"!==n||w(),y("open"),h({direction:"meta",event:"open",payload:{address:e.address,service:e.service,method:t.methodName,requestedMethod:e.method,kind:n,descriptorSource:o},at:Date.now()})}catch(e){throw y("error"),d(),h({direction:"status",event:"error",error:e instanceof Error?e.message:String(e),at:Date.now()}),e}finally{c=void 0}})(),c},async send(e){if("open"!==l)throw new Error("gRPC session is not open");h({direction:"outbound",event:"data",payload:e,at:Date.now()});const t=v(),r={};if(a&&(r.deadline=a),"unary"===t.kind){if(u>0)throw new Error("Unary gRPC call only supports one send()");return u+=1,void await new Promise((n,o)=>{const s=t.client[t.methodName](e,i,r,(e,t)=>{if(e)return y("error"),h({direction:"status",event:"error",code:e?.code,statusName:"number"==typeof e?.code?Pi.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),d(),m=null,void o(e);h({direction:"inbound",event:"data",payload:t,at:Date.now()}),g(),m=null,n()});m=s,b(s)})}if("server_streaming"===t.kind){if(u>0)throw new Error("Server-streaming gRPC call only supports one send()");u+=1;const n=t.client[t.methodName](e,i,r);m=n,b(n),n.on("data",e=>{h({direction:"inbound",event:"data",payload:e,at:Date.now()})});try{await new Promise((e,t)=>{n.on("status",()=>e()),n.on("error",e=>t(e))})}finally{m=null}return}if("client_streaming"===t.kind||"bidi_streaming"===t.kind){const t=w();if(!t)throw new Error("Streaming gRPC call was not initialized");return void await new Promise((r,n)=>{t.write(e,e=>{e?n(e):(u+=1,r())})})}throw new Error(`Unsupported gRPC method kind: ${t.kind}`)},async close(){"closed"!==l&&("open"===l||"error"===l||"closing"===l?(y("closing"),h({direction:"meta",event:"close",at:Date.now()}),"client_streaming"===n||"bidi_streaming"===n?m&&"function"==typeof m.end?m.end():g():m&&"function"==typeof m.cancel?m.cancel():g(),await p):g())},async waitForClose(){await p}}}function Bi(e){if(!e||"object"!=typeof e)throw new Error("createManualSession requires an options object");switch(e.kind){case"websocket":return rr(e);case"mcp":return dn(e);case"grpc":return Ni(e);default:throw new Error(`Unknown manual session kind: ${String(e.kind)}`)}}function Ri(e,t){return"websocket"===e||"mcp"===e||"grpc-client-stream"===t||"grpc-bidi"===t?"duplex-session":"grpc-server-stream"===t?"event-list":"grpc-unary"===t?"response":"none"!==t?"event-list":"response"}function qi(e={}){const t=_i(e);return{prepare:function(e){if(!e||!e.spec)throw new Error("prepare() requires an options object with spec");const t=G(e.spec,e.target).operation,r=function(e){const t=String(e?.["x-protocol"]??"http").toLowerCase();return"ws"===t?"websocket":t}(t),n=function(e,t){const r=String(t?.["x-transport"]??"").toLowerCase();return r||("mcp"===e?String(t?.["x-mcp"]?.transport??"http").toLowerCase():"websocket"===e?"websocket":"grpc"===e?"grpc":"http")}(r,t),o=function(e,t,r){if("websocket"===e)return"websocket";if("graphql"===e)return r?.["x-response-stream"]?"graphql-stream":"none";if("mcp"===e)return"stdio"===t?"mcp-stdio":"mcp-http-stream";if("grpc"===e){const e=String(r?.["x-grpc"]?.kind??r?.["x-grpc-mode"]??"unary").toLowerCase();return"server_streaming"===e||"server-streaming"===e?"grpc-server-stream":"client_streaming"===e||"client-streaming"===e?"grpc-client-stream":"bidi_streaming"===e||"bidi-streaming"===e||"bidi"===e?"grpc-bidi":"grpc-unary"}return Xe(r)?"sse":"none"}(r,n,t);return{protocol:r,transport:n,target:e.target,operation:t,display:{mode:Ri(r,o)},stream:{kind:o,expected:"none"!==o},openapi:{extensions:{"x-protocol":r,"x-transport":n,"x-session":"websocket"===r||"mcp"===r||"grpc"===r,"x-discovery":"mcp"===r||"grpc"===r||"graphql"===r,"x-message-schema":t?.["x-message-schema"]??null,"x-response-stream":"none"!==o?{kind:o}:null,"x-writeback":{protocol:r,transport:n}}},warnings:[]}},send:function(e){return t.send(e)},sendMany:function(e,r,n={}){return t.sendMany(e,r,n)},connect:function(e){return Bi(e)},discover:async function(e){const t=String(e?.protocol??"").toLowerCase();if("mcp"===t)return Nr(e);if("grpc"===t)return gi(e);throw new Error(`Unsupported discover protocol: ${t}`)},writeback:function(t,r,n,o){if(!r.target)throw new Error("writeback() requires a PreparedRequest with target");const s=G(t,r.target),i=Ee(n,e.response);return ke(t,s.path,s.method,i,{...e.writeBack,...o})},dispose:function(){},probeStreamingResponse:rt}}
|