@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.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(t,r=new WeakMap){if(null===t||"string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;if(void 0===t)return null;if("bigint"==typeof t)return t.toString();if("function"==typeof t)return"[Function]";if("symbol"==typeof t)return String(t);if(t instanceof Date)return t.toISOString();if(t instanceof URL)return t.toString();if(t instanceof Error){const n={name:t.name,message:t.message,stack:t.stack},o=t.cause;return void 0!==o&&(n.cause=e(o,r)),n}if("undefined"!=typeof Buffer&&Buffer.isBuffer(t))return{type:"Buffer",data:Array.from(t.values())};if(t instanceof Uint8Array)return{type:t.constructor.name,data:Array.from(t.values())};if(Array.isArray(t))return t.map(t=>e(t,r));if("object"==typeof t){const n=t;if(r.has(n))return r.get(n);const o={};r.set(n,o);for(const[t,s]of Object.entries(n))o[t]=e(s,r);return o}return String(t)}var t=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(t){const r={protocol:this.protocol,transport:this.transport,sessionId:this.sessionId,at:t.at??Date.now(),direction:t.direction,kind:t.kind,state:t.state,data:e(t.data),error:e(t.error),meta:e(t.meta)};this.events.push(r),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(r)}catch{}}onEvent(e){return this.listeners.add(e),{unsubscribe:()=>{this.listeners.delete(e)}}}},r=class extends t{async open(){}async close(){}async waitForClose(){}async send(){}};function n(e,t,n,o=1e3){return new r(e,t,n,o)}var o=Symbol.for("@powerduck/openapi-request.ProtoKitError"),s=class e extends Error{code;details;[o]=!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[o]}toJSON(){return{name:this.name,code:this.code,message:this.message,...void 0===this.details?{}:{details:this.details}}}};function i(e,t,r,n){return new s(t,e,r,n)}function a(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 c(e){if(s.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:a(e)}}var l=new Set(["__proto__","constructor","prototype"]);function u(e){return l.has(e)}function d(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return p(e)}function p(e){return f(e,new Set)}function f(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:f(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=f(n[r],t);e[r]=void 0===o?null:o}return e}const e={};for(const r of Object.keys(n)){if(u(r))continue;let o;try{o=n[r]}catch{continue}const s=f(o,t);void 0!==s&&(e[r]=s)}return e}finally{t.delete(n)}}function m(e,t){const r=h(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:h(n)}):r}function h(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 y(e,t){return g(e,t,0)}function g(e,t,r){if(!t||!v(t))return e;if(r>=64)return t;const n={...e};for(const e of Object.keys(t)){if(u(e))continue;const o=t[e];if(void 0===o)continue;const s=n[e];v(s)&&v(o)?n[e]=g(s,o,r+1):n[e]=o}return n}function v(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function b(){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 w(e){if(e)try{clearTimeout(e)}catch{}return null}function $(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 S(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 E(e){return e instanceof Error?e.message:String(e)}var A=/(token|secret|password|passwd|apikey|api_key|credential|private|authorization)/i;function x(e){return A.test(e)}function T(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 k=Symbol("protokit.cycle"),_=new Set(["__proto__","constructor","prototype"]);function O(e,t={}){const r=P(t.maxDepth,32),n=P(t.maxNodes,2e5),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(_.has(n))throw i("BAD_REF",`Pointer "${t}" traverses a forbidden key "${n}"`);return n}function a(t){if("string"!=typeof t||!t.length)throw i("EXTERNAL_REF","A $ref pointer must be a non-empty string");if("#"===t||"#/"===t)return e;if(!t.startsWith("#/"))throw i("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 i("BAD_REF",`Cannot resolve pointer "${t}"`);const n=s(e,t);if(!Object.prototype.hasOwnProperty.call(r,n))throw i("BAD_REF",`Pointer "${t}" resolves to undefined`);r=r[n]}if(void 0===r)throw i("BAD_REF",`Pointer "${t}" resolves to undefined`);return r}function c(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>100)return u();r.add(e);const s=l(t);s&&(n={...s,...n??{}}),t=a(e)}return n?null===t||"object"!=typeof t||Array.isArray(t)?t:{...t,...n}:t}function l(e){let t;for(const r of Object.keys(e))"$ref"===r||_.has(r)||((t??={})[r]=e[r]);return t}function u(){return{type:"object",[k]:!0}}function p(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=c(e)}catch(e){if("EXTERNAL_REF"===e?.code)throw e;return{type:"object"}}if(null===i||"object"!=typeof i)return i;if(i[k])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]=p(i[r],t+1,o,s);return e}const e={};for(const r of Object.keys(i))_.has(r)||(e[r]=p(i[r],t+1,o,s));return e}finally{o.delete(i)}}function f(e){return p(e,0,new Set,{nodes:0})}return{deref:c,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 d(o.get(t));const n=f(e);return r?(o.set(t,n),d(n)):n},byPointer:a}}function P(e,t){const r="number"==typeof e?e:Number(e);return!Number.isFinite(r)||r<=0?t:Math.floor(r)}var M=["get","put","post","delete","options","head","patch","trace","query"];function D(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw i("BAD_SPEC","spec must be an object");if("string"!=typeof e.openapi||!e.openapi.trim())throw i("BAD_SPEC","spec.openapi version string is required");if(!t||"object"!=typeof t)throw i("BAD_TARGET","target is required");const r=O(e),n=e.paths;if(!n||"object"!=typeof n||Array.isArray(n))throw i("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 M){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 i("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 i("OP_NOT_FOUND",`operationId "${r}" was not found`,{available:C(e,t)});if(n.length>1)throw i("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 i("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 i("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),a=r.deepDeref(s.rawOperation)??{},c=s.pathItem??{};return{path:s.path,method:s.method,isCustomMethod:s.isCustomMethod,...s.customMethodKey?{customMethodKey:s.customMethodKey}:{},operation:a,pathItem:c,parameters:j(r,c,a),servers:I(e,c,a),security:Array.isArray(a.security)?a.security:Array.isArray(e.security)?e.security:void 0}}function C(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 I(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 N=["null","boolean","integer","number","string","array","object"],B=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"]),R=new Set(["__proto__","constructor","prototype"]),q=e=>null==e?[]:Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[],L=e=>null!==e&&"object"==typeof e&&!Array.isArray(e);function F(e){if(!L(e))return!1;for(const t of Object.keys(e))if(!R.has(t))return!1;return!0}function U(e,t,r=0){if(null==e)return void 0===t?e:t;if(null==t)return e;if(!L(e))return L(t)?t:e;if(!L(t))return e;if(e===t)return e;if(r>20)return e;if(F(t))return e;if(F(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([...q(e.type),...q(t.type)]));if(o.includes("integer")&&o.includes("number")&&(o=o.filter(e=>"integer"!==e)),o.sort((e,t)=>{const r=N.indexOf(e),n=N.indexOf(t);return(r<0?N.length:r)-(n<0?N.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(L(e.properties)?e.properties:{}))R.has(t)||(o[t]=r);for(const[e,n]of Object.entries(L(t.properties)?t.properties:{}))R.has(e)||(o[e]=void 0!==o[e]?U(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(L(e.properties)&&L(t.properties)){const e=new Set(i),t=s.filter(t=>e.has(t));t.length&&(n.required=t)}else{const t=L(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;L(o)&&L(s)?n.additionalProperties=U(o,s,r+1):n.additionalProperties=!0===o||!0===s||(void 0!==o?o:s)}if(L(e.patternProperties)||L(t.patternProperties)){const o={...L(e.patternProperties)?e.patternProperties:{}};for(const[e,n]of Object.entries(L(t.patternProperties)?t.patternProperties:{}))o[e]=o[e]?U(o[e],n,r+1):n;n.patternProperties=o}if(void 0===e.propertyNames&&void 0===t.propertyNames||(n.propertyNames=U(e.propertyNames,t.propertyNames,r+1)),void 0===e.items&&void 0===t.items||(n.items=U(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]?U(o[e],s[e],r+1):o[e]??s[e]);n.prefixItems=a}!0===e.uniqueItems&&!0===t.uniqueItems&&(n.uniqueItems=!0),z(n,"minimum",e,t,Math.min),z(n,"exclusiveMinimum",e,t,Math.min),z(n,"minLength",e,t,Math.min),z(n,"minItems",e,t,Math.min),z(n,"minProperties",e,t,Math.min),z(n,"maximum",e,t,Math.max),z(n,"exclusiveMaximum",e,t,Math.max),z(n,"maxLength",e,t,Math.max),z(n,"maxItems",e,t,Math.max),z(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=G([...e.enum,...t.enum]).slice(0,50)),void 0!==e.const&&void 0!==t.const&&(V(e.const,t.const)?n.const=e.const:n.enum=G([e.const,t.const]));const s=G([...Array.isArray(e.examples)?e.examples:[],...Array.isArray(t.examples)?t.examples:[]]).slice(0,3);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?W([...o,...s]):(o??s).slice())}void 0===e.not&&void 0===t.not||void 0!==e.not&&V(e.not,t.not)&&(n.not=e.not);for(const r of[t,e])for(const e of Object.keys(r))R.has(e)||B.has(e)||(n[e]=r[e]);return n}function z(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 V(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function G(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 W(e){return G(e.filter(e=>void 0!==e))}var J=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,Y=/^\d{4}-\d{2}-\d{2}$/,H=/^\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})?$/,K=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,X=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,Q=/^https?:\/\/\S+$/i,Z=new Set(["__proto__","constructor","prototype"]);function ee(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?J.test(e)?"date-time":Y.test(e)?"date":K.test(e)?"uuid":Q.test(e)?"uri":X.test(e)?"email":H.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=ee(e[0],t,r+1);for(let n=1;n<o;n+=1)s=U(s,ee(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(!Z.has(a)){if(++i>s)break;n[a]=ee(c,t,r+1),null!=c&&o.push(a)}const a={type:"object",properties:{...n}};return o.length&&(a.required=o),a}return{}}function te(e,t={}){if(!Array.isArray(e)||!e.length)return{};let r=null;for(const n of e){const e=ee(n,t);r=null===r?e:U(r,e,0)}return r??{}}var re=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"]),ne=new Set(["[DONE]","DONE","[done]","done"]),oe=new Set(["__proto__","constructor","prototype"]);function se(e){return{type:"string",examples:[ie(e)]}}function ie(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>String(e)).join(", "):null==e?"":String(e)}function ae(e,t={}){if(!e||"object"!=typeof e||!v(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||ue(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(oe.has(n))continue;const e=n.toLowerCase();if("content-type"===e||re.has(e))continue;const s=r.get(e);if(s){const e=t[s],r=U(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:ce(e,l,s,t)};if(void 0!==r.body&&null!==r.body){const e={schema:ee(r.body)};a&&(e.examples={capturedSample:{summary:"Captured from a live call",value:le(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 ce(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(ne.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=U(a,ee(e.parsed),0);else{l=!0;const t="string"==typeof e.data?e.data:"";a=U(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 le(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 ue(e){return e>=500?"Server error":e>=400?"Client error":e>=300?"Redirection":e>=200?"Successful response":e>=100?"Informational response":"Response"}function de(e,t,r,n,o={}){if(!e||"object"!=typeof e||Array.isArray(e))throw i("BAD_SPEC","spec must be an object");if("string"!=typeof t||!t.length)throw i("BAD_TARGET","path must be a non-empty string");if("string"!=typeof r||!r.length)throw i("BAD_TARGET","method must be a non-empty string");if(!n||"object"!=typeof n||!v(n.response))throw i("BAD_FRAGMENT","fragment.response must be an object");const s="string"==typeof n.statusCode&&n.statusCode?n.statusCode:"default";if(oe.has(s))throw i("BAD_FRAGMENT",`Invalid status code key "${s}"`);const a=d(e);if(!v(a.paths))throw i("BAD_SPEC","spec.paths is missing or invalid");const c=a.paths[t];if(!v(c))throw i("PATH_NOT_FOUND",`Path "${t}" is not present in the document`);const l=function(e,t){const r=t.toLowerCase(),n=e[r];if(v(n))return n;const o=e.additionalOperations;if(!v(o))return;for(const e of Object.keys(o)){if(e.toLowerCase()!==r)continue;const t=o[e];if(v(t))return t}return}(c,r);if(!l)throw i("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 a;v(l.responses)||(l.responses={});const u=d(n.response),p=l.responses[s];return"replace"!==o.strategy&&void 0!==p&&v(p)?("string"==typeof p.$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);v(t.headers)&&(v(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(oe.has(o))continue;if(!v(s))continue;const t=n.get(o.toLowerCase());if(!t){e[o]=s,n.set(o.toLowerCase(),o);continue}const i=e[t];v(i)?r&&"string"==typeof i.$ref||(void 0!==s.schema&&(i.schema=r&&"string"==typeof i.schema?.$ref?i.schema:U(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(v(t.content)){v(e.content)||(e.content={});for(const[r,s]of Object.entries(t.content)){if(oe.has(r))continue;if(!v(s))continue;const t=e.content[r];v(t)?pe(t,s,n,o):e.content[r]=s}}v(t.links)&&(e.links={...v(e.links)?e.links:{},...t.links});for(const r of Object.keys(t))r.startsWith("x-")&&(oe.has(r)||(e[r]=t[r]))}(p,u,o),a):(l.responses[s]=u,a)}function pe(e,t,r,n){if(void 0!==t.itemSchema&&(e.itemSchema=r&&"string"==typeof e.itemSchema?.$ref?e.itemSchema:U(e.itemSchema,t.itemSchema,0)),void 0!==t.schema&&(e.schema=r&&"string"==typeof e.schema?.$ref?e.schema:U(e.schema,t.schema,0)),v(t.examples)){v(e.examples)||(e.examples={});for(const[r,o]of Object.entries(t.examples))oe.has(r)||!n&&r in e.examples||(e.examples[r]=o)}void 0!==t.example&&void 0===e.example&&(e.example=t.example),v(t.encoding)&&(e.encoding={...v(e.encoding)?e.encoding:{},...t.encoding});for(const r of Object.keys(t))r.startsWith("x-")&&(oe.has(r)||(e[r]=t[r]))}var fe=class{entries=[];nextSeq=0;register(e){if(!e||"object"!=typeof e)throw i("BAD_ADAPTER","Adapter must be an object");if("string"!=typeof e.name||!e.name.trim())throw i("BAD_ADAPTER","Adapter must expose a non-empty `name`");for(const t of["supports","plan","execute"])if("function"!=typeof e[t])throw i("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 i("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 i("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}},me=new Set(["__proto__","constructor","prototype"]),he="2024-01-01T00:00:00.000Z";function ye(e,t=0,r={}){const n=r.maxDepth??12;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=ye(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=ge(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 ye(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 ge(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(ye(o,t+1,r));const o=$e(e.minItems)??1,s=$e(e.maxItems);let i=Math.max(o,n.length,1);i=Math.min(i,5),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=ye(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}=ve(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=we(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}=ve(e,!1);let n=0;void 0!==t&&n<t&&(n=t);void 0!==r&&n>r&&(n=r);const o=we(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 he;case"date":return he.slice(0,10);case"time":return he.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?be(r,e):"string"==typeof e.pattern&&e.pattern.length?"":be("string",e)}(e)}}function ge(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))me.has(e)||!i&&c&&!0===c.readOnly||!a&&c&&!0===c.writeOnly||t>2&&o.length&&!o.includes(e)||(n[e]=ye(c,t+1,r));for(const e of o)me.has(e)||e in n||(n[e]=ye(s[e]??{},t+1,r));!Object.keys(n).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(n.key=ye(e.additionalProperties,t+1,r));const c=$e(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]=ye(o,t+1,r))}}return n}function ve(e,t){const r=t?1:Number.EPSILON>0?1e-6:1;let n=we(e.minimum),o=we(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 be(e,t){const r=$e(t.minLength),n=$e(t.maxLength);let o=e;return void 0!==r&&o.length<r&&(o=o.padEnd(Math.min(r,256),"x")),void 0!==n&&o.length>n&&(o=o.slice(0,Math.max(n,0))),o}function we(e){if("number"==typeof e&&Number.isFinite(e))return e}function $e(e){const t=we(e);if(void 0===t)return;const r=Math.floor(t);return r<0?0:r}var Se="\0PK_OPEN\0",Ee="\0PK_CLOSE\0",Ae=0;function xe(e){Ae=(Ae+1)%65535;const t=Date.now().toString(36),r=Math.floor(65535*Math.random()).toString(36);return`${e}-${t}-${Ae.toString(36)}${r}`}function Te(e,t){const r="string"==typeof t.serverUrl?t.serverUrl.trim():"";if(r)return _e(ke(r),"options.serverUrl");const n=Array.isArray(e)?e.filter(v):[],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 i("NO_SERVER_URL","The document declares no usable server URL. Pass options.serverUrl to specify one.");return s=function(e,t,r){const n=v(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 i("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 i("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),_e(ke(s),"spec.servers")}function ke(e){return e.replace(/\/+$/,"")||e}function _e(e,t){const r=function(e){return-1===e.indexOf("{")?e:e.split("{{").join(Se).split("}}").join(Ee).replace(/\{[^{}]*\}/g,"").split(Se).join("{{").split(Ee).join("}}")}(e);if(!r)throw i("BAD_SERVER_URL",`${t} resolved to an empty URL`);if(r.includes("{{"))return r;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(r))throw i("RELATIVE_SERVER_URL",`${t} resolved to the relative URL "${r}". A request needs an absolute origin; pass options.serverUrl.`,{url:r});return r}function Oe(e,t,r={},n={}){const o=!1!==n.maskSecrets,s=!0===n.allowBaseUrlOverride,i=v(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&&x(e)?"secret":"default");return s&&l("baseUrl",t,"default"),{id:xe("protokit-env"),name:"string"==typeof e&&e.trim()?e:"protokit",values:a,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}var Pe=["text/event-stream","application/json-seq","application/x-ndjson","application/ndjson","application/jsonl","application/x-jsonlines"];function Me(e){return"default"!==e&&(!!/^2\d\d$/.test(e)||/^2xx$/i.test(e))}function De(e,t){const r=function(e){if(v(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&&je(r))return!0;if(!v(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(v(e["x-sse"]))return!0;const o=e.responses;if(!v(o))return!1;for(const[e,t]of Object.entries(o)){if(e.startsWith("x-"))continue;if(!v(t))continue;const r=t.content;if(v(r))for(const[e,t]of Object.entries(r)){const r=e.toLowerCase();if(r.startsWith("text/event-stream"))return!0;if(v(t)&&void 0!==t.itemSchema&&Pe.some(e=>r.startsWith(e)))return!0}}return!1}function Ce(e){return"string"==typeof e&&/(^|[\s,;])text\/event-stream\b/i.test(e)}function je(e){if("string"!=typeof e||!e)return!1;return e.split(",").map(e=>e.split(";")[0].trim().toLowerCase()).filter(Boolean).some(e=>Pe.some(t=>e===t||e.startsWith(t)))}function Ie(e){if(!v(e))return;const t=e.responses;if(!v(t))return;const r=new Set,n=new Set;for(const[e,o]of Object.entries(t)){if(e.startsWith("x-"))continue;if(!v(o))continue;const t=o.content;if(!v(t))continue;const s=Me(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:Pe.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 Ne(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 Ce(n)?s="sse":je(n)?s="ndjson":!n&&/chunked/i.test(o)&&(s="chunked"),{ok:r.ok,status:r.status,contentType:n,kind:s,response:r}}function Be(e){if(!e)return[];return(Array.isArray(e)?e:[e]).filter(e=>v(e)&&("string"==typeof e.exec||Array.isArray(e.exec)))}function Re(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 qe(e,t){const r=e?.["x-postman-scripts"];if(!v(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=>v(e)&&("string"==typeof e.exec||Array.isArray(e.exec))).slice(0,8):[];if(v(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 Le={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));","}"]},Fe=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"]),Ue=/^(accept|content-type|authorization)$/i,ze=0;function Ve(e){ze=(ze+1)%65535;const t=Date.now().toString(36),r=Math.floor(65535*Math.random()).toString(36);return`${e}-${t}-${ze.toString(36)}${r}`}function Ge(e){return"string"==typeof e&&e.length?e:void 0}function We(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 Je(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 Ye={spaceDelimited:" ",pipeDelimited:"|",form:",",simple:","};function He(e,t){const r=String(e.name),n=Ge(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:Je(e)}));if("deepObject"===n)return t.map((e,t)=>({key:`${r}[${t}]`,value:Je(e)}));const e=Ye[n]??",";return[{key:r,value:t.map(Je).join(e)}]}if(v(t)){const e=Object.entries(t);return e.length?"deepObject"===n?e.map(([e,t])=>({key:`${r}[${e}]`,value:Je(t)})):o?e.map(([e,t])=>({key:e,value:Je(t)})):[{key:r,value:e.flatMap(([e,t])=>[e,Je(t)]).join(",")}]:[{key:r,value:""}]}return[{key:r,value:Je(t)}]}function Ke(e,t){const r=Ge(e.style)??"simple",n=!0===e.explode,o=String(e.name),s=(e,t)=>e.map(Je).join(t);if("label"===r){if(Array.isArray(t))return`.${s(t,n?".":",")}`;if(v(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`.${e}=${Je(t)}`).join(""):`.${e.flatMap(([e,t])=>[e,Je(t)]).join(",")}`}return`.${Je(t)}`}if("matrix"===r){if(Array.isArray(t))return n?t.map(e=>`;${o}=${Je(e)}`).join(""):`;${o}=${s(t,",")}`;if(v(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`;${e}=${Je(t)}`).join(""):`;${o}=${e.flatMap(([e,t])=>[e,Je(t)]).join(",")}`}return`;${o}=${Je(t)}`}if(Array.isArray(t))return s(t,",");if(v(t)){const e=Object.entries(t);return n?e.map(([e,t])=>`${e}=${Je(t)}`).join(","):e.flatMap(([e,t])=>[e,Je(t)]).join(",")}return Je(t)}function Xe(e,t){const r=!0===e.explode;if(Array.isArray(t))return t.map(Je).join(",");if(v(t)){const e=Object.entries(t);return r?e.map(([e,t])=>`${e}=${Je(t)}`).join(","):e.flatMap(([e,t])=>[e,Je(t)]).join(",")}return Je(t)}function Qe(e,t){const r=String(e.name),n=!0===e.explode;if(Array.isArray(t))return n?t.map(e=>[r,Je(e)]):[[r,t.map(Je).join(",")]];if(v(t)){const e=Object.entries(t);return n?e.map(([e,t])=>[e,Je(t)]):[[r,e.flatMap(([e,t])=>[e,Je(t)]).join(",")]]}return[[r,Je(t)]]}function Ze(e,t,r){const n=r.values??{},o=[],s=Te(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=v(r)?Object.keys(r):[],o=Ge(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)=>We(e)-We(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=Ke(e,r?t:ye(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=v(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(...He(e,null===r?"":r));else{if(!0===e.required){const t=ye(e.schema??{});p.push(...He(e,null===t?"":t));continue}!0!==e.allowEmptyValue?p.push({key:e.name,value:"",disabled:!0}):p.push({key:e.name,value:""})}}if(v(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:Je(r)});else p.push({key:e,value:Je(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(v(n.header))for(const[e,t]of Object.entries(n.header))null!=t&&y(e,Je(t));for(const e of a("header")){if(Ue.test(e.name))continue;if(!0!==e.required)continue;const t=ye(e.schema??{});if(null==t)continue;const r=Xe(e,t);""!==r&&y(e.name,r)}c&&y("Content-Type",c);const g=Ie(e.operation);g&&y("Accept",g);const b=a("cookie"),w=[],$=(e,t)=>{w.push(`${e}=${encodeURIComponent(t)}`)};for(const e of b){const t=n.cookie?.[e.name],r=null!=t?t:!0===e.required?ye(e.schema??{}):void 0;if(null!=r)for(const[t,n]of Qe(e,r))$(t,n)}if(v(n.cookie))for(const[e,t]of Object.entries(n.cookie))b.some(t=>t.name===e)||null!=t&&$(e,Je(t));w.length&&y("Cookie",w.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(!v(r))return;if(v(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(v(t))return t.schema}}(o,i),c=s?t.body:ye(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:et(c).map(([e,t])=>({key:e,value:Je(t),type:"text"}))};if(l.includes("multipart/form-data"))return{mode:"formdata",formdata:et(c).map(([e,t])=>v(t)&&"__file"in t?{key:e,type:"file",src:String(t.__file)}:{key:e,type:"text",value:Je(t)})};if(l.includes("xml")||l.startsWith("text/")||u)return{mode:"raw",raw:"string"==typeof c?c:Je(c),...l.includes("xml")?{options:{raw:{language:"xml"}}}:{}};return{mode:"raw",raw:"string"==typeof c?c:Je(c)}}(e.operation,n,c,o),E=p.filter(e=>!e.disabled).map(e=>e.__raw?`${e.key}${""===e.value?"":`=${e.value}`}`:`${encodeURIComponent(e.key)}=${encodeURIComponent(e.value)}`).join("&");let A=`{{baseUrl}}/${d.join("/")}`;E&&(A+=`?${E}`);const x={raw:A,host:["{{baseUrl}}"],path:d};p.length&&(x.query=p.map(({__raw:e,...t})=>t)),u.length&&(x.variable=u);const T=String(e.method).toUpperCase(),k={method:T,header:m,url:x},_=Ge(e.operation?.description)??Ge(e.operation?.summary);_&&(k.description=_),S&&(k.body=S);const O=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:qe(e,"item");return[...Re("prerequest","item",[...r.pre,...Be(t?.preRequest)]),...Re("test","item",[...r.test,...Be(t?.test)])]}(e.operation,r.scripts)??[],P=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:qe(e,"collection");return[...Re("prerequest","collection",[...r.pre,...Be(t?.collectionPreRequest)]),...Re("test","collection",[...r.test,...Be(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=Ge(e.operation?.operationId)??`${T} ${e.path}`,C={info:{_postman_id:Ve("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,...O.length?{event:O}:{},request:k,response:[]}],variable:[{key:"baseUrl",value:s}]};var j,I;const N=Ge(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:!Fe.has(T),warnings:o}}function et(e){return v(e)?Object.entries(e):[]}import tt from"http";import rt from"https";import nt from"postman-runtime";import ot from"postman-collection";var st=new Set(["[DONE]","DONE","[done]","done"]),it=/\r\n\r\n|\n\n|\r\r/,at=/^\d+$/;function ct(e,t){const r="number"==typeof e?e:Number(e);return Number.isFinite(r)&&r>0?Math.floor(r):t}var lt=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;bomChecked=!1;overflowed=!1;sequence=0;maxBufferChars;maxEventChars;inheritEventId;droppedEvents=0;constructor(e={}){this.maxBufferChars=ct(e.maxBufferChars,4194304),this.maxEventChars=ct(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=it.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(at.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&&!st.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}};import ut from"postman-collection";var dt=864e5;function pt(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),dt)}function ft(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 ut.VariableScope({values:Array.from(n.values())})}function mt(e){if(!v(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 i("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 i("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 i("BAD_RUN_OPTIONS",'runner.requester.protocolVersion must be "http1", "http2" or "auto".',{provided:t})}function ht(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 yt(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 gt(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 p(t)}catch{return}}function vt(e,t,r){const n=b(),o=Date.now();let s,a,l,u="initialized",d=e.streamingHint,f=!1;const m=$(t.maxEvents,100),h=$(t.maxStreamMs,3e4),g=$(t.runner?.timeout?.request??t.timeout,3e4),v="number"==typeof t.maxResponseSize?t.maxResponseSize:void 0,E=new lt({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId}),A=[],x=[];let T=0,k=!1;const _={prerequest:[],test:[],assertions:[],console:[],passed:!0,skipped:!1},O=[];let P=null,M=null,D=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 tt.Agent({keepAlive:!1}),n=new rt.Agent({keepAlive:!1});return r.createConnection=function(e,r){return t(tt.Agent.prototype.createConnection.call(this,e,r))},n.createConnection=function(e,r){return t(rt.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)=>{_.console.push({level:e,messages:[t],at:Date.now()})},R=e=>(e&&"function"==typeof e.unref&&e.unref(),e),q=(e,t)=>{if("stopping"===u||"finalized"===u)return;u="stopping",a=e,f=!0,B("debug",`[protokit] stopping run: ${t??e}`);try{M?.abort?.()}catch{}const r=N?.destroyAll()??0;r>0&&B("debug",`[protokit] destroyed ${r} open socket(s)`),j=R(setTimeout(()=>{"finalized"!==u&&(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:yt(e?.result?.environment),globals:yt(e?.result?.globals),return:e?.result?.return}),F=()=>{if("finalized"===u)return;if(u="finalized",D=w(D),C=w(C),j=w(j),I?.(),I=null,N?.destroyAll(),d){for(const e of E.flush())A.length<m?(A.push(e),bt(()=>t.onEvent?.(e))):f=!0;E.truncated&&(f=!0)}const e=Date.now();if(P)d&&(P.response.events=A),f&&(P.response.truncated=!0),P.response.timings={...P.response.timings,startedAt:o,endedAt:e,durationMs:e-o,firstByteMs:s?s-o:void 0,...void 0!==l?{networkDurationMs:l}:{}};else{const t=!!a&&A.length>0;P={protocol:d?"sse":"http",request:{method:"",url:"",headers:{}},response:{status:t?200:0,statusText:t?"Stream sampling stopped":"No response received",headers:{},contentType:d?"text/event-stream":void 0,...d?{events:A}:{},timings:{startedAt:o,endedAt:e,durationMs:e-o,firstByteMs:s?s-o:void 0},sizeBytes:T,...f?{truncated:!0}:{}},...t?{}:{error:{message:"aborted"===a?"Run aborted before a response was received":"Runner finished without a response",code:a}}}}a&&(P.response.stopReason=a),E.droppedEvents&&(P.response.droppedEvents=E.droppedEvents),P.scripts=_,n.resolve(P)};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"!==u){B("error","[protokit] hard timeout reached, forcing completion"),a??="hardTimeout",f=!0;try{M?.abort?.()}catch{}N?.destroyAll(),F()}},g+h+3e4));const U=(e,t,r)=>(u="finalized",C=w(C),I?.(),N?.destroyAll(),Promise.reject(i(e,t,r)));let z,V,G;try{z=new ot.Collection(p(e.collectionJson))}catch(e){return U("BAD_COLLECTION",`Failed to construct collection: ${c(e).message}`,e)}try{V=function(e,t){if(!e||"object"!=typeof e)throw i("BAD_RUN_OPTIONS","send options are required");mt(e.runner?.requester);const r=pt(e.runner?.timeout?.request)??pt(e.timeout)??3e4,n=t.streaming?pt(e.maxStreamMs)??3e4:0,o=y({iterationCount:1,stopOnError:!1,abortOnError:!1,stopOnFailure:!1,abortOnFailure:!1,timeout:{request:r,script:pt(e.runner?.timeout?.script)??15e3,global:0===r?0:Math.min(r+n+15e3,dt)},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??{});mt(o.requester),o.environment||(o.environment=ft(e.variables,[{key:"baseUrl",value:t.baseUrl}])),!o.globals&&e.globals&&(o.globals=ft(e.globals)),!o.localVariables&&e.localVariables&&(o.localVariables=ft(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 i("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: ${c(e).message}`,e)}try{G=new nt.Runner}catch(e){return U("RUNTIME_INIT",`Failed to create runner: ${c(e).message}`,e)}function W(e){let r;try{r=E.push(e)}catch(e){return void B("error",`[protokit] SSE parse failure: ${c(e).message}`)}for(const e of r){if(A.length>=m)return f=!0,void q("maxEvents",`maxEvents (${m}) reached`);if(A.push(e),bt(()=>t.onEvent?.(e)),A.length>=m)return void q("maxEvents",`maxEvents (${m}) reached`)}}return G.run(z,V,(r,p)=>{if(r)return u="finalized",C=w(C),I?.(),N?.destroyAll(),void n.reject(i("RUNTIME_INIT",r.message??"Runner initialization failed",r));if(M=p,"stopping"===u){try{p.abort?.()}catch{}N?.destroyAll()}p.start({console(e,r,...n){const o={level:"string"==typeof r?r:"log",messages:n,at:Date.now()};_.console.push(o),bt(()=>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||(_.passed=!1),_.assertions.push(r),bt(()=>t.onAssertion?.(r))}},prerequest(e,t,r){for(const e of r??[])_.prerequest.push(L(e,"prerequest"))},test(e,t,r){for(const e of r??[])_.test.push(L(e,"test"))},item(e,t,r,n,o){o?.isSkipped&&(_.skipped=!0)},responseStart(r,n,o){"initialized"===u&&(u="headers"),s??=Date.now();const i=wt(o,"content-type");(Ce(i)||je(i))&&(d=!0),bt(()=>t.onResponseStart?.({status:o?.code??0,headers:ht(o?.headers),contentType:i,streaming:d,protocol:d?"sse":"http",url:e.baseUrl})),d&&("headers"===u&&(u="streaming"),D||(D=R(setTimeout(()=>q("maxStreamMs",`maxStreamMs (${h}ms) reached`),h))))},responseData(e,t){if("finalized"===u||null==t)return;let r;try{r=Buffer.isBuffer(t)?t:Buffer.from(t)}catch{return}if(k=!0,T+=r.length,void 0!==v&&T>v&&"stopping"!==u)return d&&W(r),void q("maxResponseSize",`maxResponseSize (${v} bytes) exceeded`);d?W(r):x.push(r)},request(e,t,r,n,i,p){const m=Date.now(),h={method:n?.method??"",url:St(n),headers:ht(n?.headers),body:gt(n)};"number"==typeof r?.responseTime&&(l=r.responseTime);if(e&&!("stopping"===u||!!a))return void(P={protocol:d?"sse":"http",request:h,response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:o,endedAt:m,durationMs:m-o,firstByteMs:s?s-o:void 0,...void 0!==l?{networkDurationMs:l}:{}},sizeBytes:T},error:c(e),replays:O});e&&B("debug",`[protokit] transport closed by sampler: ${c(e).message}`);const y=wt(r,"content-type");let g,v;(Ce(y)||je(y))&&(d=!0);let b=0;if(!d){const e=x.length?Buffer.concat(x):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);b=e.length,g=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"),v=S(g,y)}P={protocol:d?"sse":"http",request:h,response:{status:"number"==typeof r?.code?r.code:0,statusText:$t(r),headers:ht(r?.headers),contentType:y,...d?{streaming:!0,events:A,body:Object.assign({},...A.map(e=>e.parsed))}:{body:v,text:g},timings:{startedAt:o,endedAt:m,durationMs:m-o,firstByteMs:s?s-o:void 0,...void 0!==l?{networkDurationMs:l}:{}},sizeBytes:k?T:b,...f?{truncated:!0}:{}},cookies:Array.isArray(p)?p.map(e=>({name:String(e?.name??""),value:String(e?.value??""),domain:e?.domain,path:e?.path})):[],replays:O}},io(e,t,r,n,o){"http"===r?.type&&r.source&&"collection"!==r.source&&O.push({url:St(o),method:o?.method??"",status:"number"==typeof n?.code?n.code:0,reason:String(r.source)})},exception(e,t){B("error",`[exception] ${c(t).message}`)},done(e){if(e&&!P&&!(!!a||"stopping"===u))return u="finalized",D=w(D),C=w(C),j=w(j),I?.(),N?.destroyAll(),void n.reject(i("RUNTIME_RUN",e.message??"Run failed",e));F()}})}),n.promise}function bt(e){try{e()}catch{}}function wt(e,t){try{const r=e?.headers?.get?.(t);return null==r?void 0:String(r)}catch{return}}function $t(e){try{return String("function"==typeof e?.reason?e.reason()??"":e?.status??"")}catch{return""}}function St(e){try{return"function"==typeof e?.url?.toString?e.url.toString():""}catch{return""}}var Et=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=Ze(e.located,e.spec,e.options);return{...t,environment:Oe(`${e.spec?.info?.title??"API"} Environment`,t.baseUrl,e.options.variables),streaming:De(e.located.operation,e.options.values)}}execute(e,t,r){return vt({collectionJson:e.collection,baseUrl:e.baseUrl,streamingHint:e.streaming},t,r)}};var At=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function xt(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(!At.test(t))throw i("BAD_WS_OPTIONS",`Invalid WebSocket subprotocol ${JSON.stringify(t)}: must be an HTTP token`);r.includes(t)||r.push(t)}}return r}function Tt(e,t,r){const n=r.websocket??{},o=e.operation?.["x-websocket"],s=o&&"object"==typeof o?o:{},a={...r.variables??{}};let c;if(n.url)c=String(n.url);else if("string"==typeof s.url&&s.url)c=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(/^\/+/,"")}`}(Te(e.servers,r)),n=e.path.replace(/\{([^}]+)\}/g,(e,t)=>{const n=r.values?.path?.[t];return null==n?e:encodeURIComponent(String(n))});c=`${t.replace(/\/+$/,"")}/${n.replace(/^\//,"")}`}c=m(c,a);const l=c.match(/\{\{([^}]+)\}\}/);if(l)throw i("BAD_WS_URL",`Unresolved variable {{${l[1]}}} in WebSocket URL: ${c}`);let u;try{u=new URL(c)}catch{throw i("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${c}`)}if("ws:"!==u.protocol&&"wss:"!==u.protocol)throw i("BAD_WS_URL",`WebSocket URL must use ws: or wss:, received ${u.protocol}${c}`);for(const[e,t]of Object.entries(r.values?.query??{}))if(null!=t)if(Array.isArray(t)){u.searchParams.delete(e);for(const r of t)null!=r&&u.searchParams.append(e,String(r))}else u.searchParams.set(e,String(t));"apikey"===r.auth?.type&&"query"===r.auth.in&&u.searchParams.set(r.auth.key??"api_key",r.auth.value??""),c=u.toString();const d={},p=e=>{if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(d[t]=m(String(r),a))};p(r.values?.header),p(s.headers),p(n.headers);const f=r.auth;if(f&&"none"!==f.type&&!Object.keys(d).some(e=>"authorization"===e.toLowerCase()))if("bearer"===f.type)d.Authorization=`Bearer ${f.token??""}`;else if("basic"===f.type){const e=`${f.username??""}:${f.password??""}`;d.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===f.type&&"header"===(f.in??"header")&&(d[f.key??"X-API-Key"]=f.value??"");for(const e of["sec-websocket-key","sec-websocket-version","sec-websocket-extensions","sec-websocket-protocol","upgrade","connection"])for(const t of Object.keys(d))t.toLowerCase()===e&&delete d[t];const h=n.send??s.send??[],y=(Array.isArray(h)?h:[h]).map(e=>function(e,t){if(null==e)return null;if("string"==typeof e)return m(e,t);if(e instanceof Uint8Array)return e;if(Buffer.isBuffer(e))return new Uint8Array(e);try{return m(JSON.stringify(e),t)}catch{return null}}(e,a)).filter(e=>null!==e),g=n.keepAlive??s.keepAlive;return{url:c,subprotocols:xt(n.subprotocols??s.subprotocols),headers:d,send:y,sendDelayMs:kt(n.sendDelayMs,0,"websocket.sendDelayMs"),idleTimeoutMs:kt(n.idleTimeoutMs,0,"websocket.idleTimeoutMs"),maxMessages:_t(n.maxMessages??r.maxEvents,100,"websocket.maxMessages"),maxSessionMs:_t(n.maxSessionMs??r.maxStreamMs,3e4,"websocket.maxSessionMs"),keepAlive:g?{intervalMs:_t(g.intervalMs,15e3,"websocket.keepAlive.intervalMs"),payload:String(g.payload??"ping")}:void 0,closeCode:Ot(n.closeCode),closeReason:String(n.closeReason??"Client finished sampling"),closeTimeoutMs:_t(n.closeTimeoutMs,3e3,"websocket.closeTimeoutMs"),rejectUnauthorized:!1!==n.rejectUnauthorized,maxPayloadBytes:_t(n.maxPayloadBytes,262144,"websocket.maxPayloadBytes"),clientOptions:n.clientOptions&&"object"==typeof n.clientOptions?{...n.clientOptions}:{}}}function kt(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<0)throw i("BAD_WS_OPTIONS",`${r} must be a non-negative finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function _t(e,t,r){if(null==e)return t;const n=Number(e);if(!Number.isFinite(n)||n<=0)throw i("BAD_WS_OPTIONS",`${r} must be a positive finite number, received ${JSON.stringify(e)}`);return Math.floor(n)}function Ot(e){if(null==e)return 1e3;const t=Number(e);if(1e3===t||Number.isInteger(t)&&t>=3e3&&t<=4999)return t;throw i("BAD_WS_OPTIONS",`websocket.closeCode must be 1000 or within 3000-4999, received ${JSON.stringify(e)}`)}import Pt from"ws";var Mt=new Set([1e3,1001,1005]);function Dt(e,t,r){const n=b(),o=Date.now();let s,i,a,l="connecting",u=0,d=0,p=0,f=!1,m=0,h=!1,y=!1;const g=[],v={};let $,S,E=0,A=null,x=null,T=null,k=null;const _=[];let O=null,P=!1;const M=e=>(e&&"function"==typeof e.unref&&e.unref(),e),D=t=>{const r=Date.now(),n=!t&&E>0&&E<400,a={...v};var c,l;return $&&(c=a,l="sec-websocket-protocol",!Object.keys(c).some(e=>e.toLowerCase()===l))&&(a["sec-websocket-protocol"]=$),{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:E||(t?0:101),statusText:t?"WebSocket error":n?"Switching Protocols":"Connection closed",headers:a,contentType:h&&!y?"application/octet-stream":"application/json",events:g,timings:{startedAt:o,endedAt:r,durationMs:r-o,firstByteMs:s?s-o:void 0},sizeBytes:p,...f?{truncated:!0}:{},...i?{stopReason:i}:{},...m?{droppedEvents:m}:{}},...t?{error:t}:{}}},C=e=>{"finalized"!==l&&(l="finalized",(()=>{if(A=w(A),x=w(x),T=w(T),k){try{clearInterval(k)}catch{}k=null}for(const e of _.splice(0))w(e)})(),O?.(),O=null,n.resolve(D(e??S)))},j=(t,r)=>{if("closing"!==l&&"finalized"!==l){l="closing",i=t,f=!0;try{I&&I.readyState===Pt.OPEN?I.close(e.closeCode,Ct(Buffer.from(`${e.closeReason}: ${r}`,"utf8"),123)):I?.terminate?.()}catch{}T=M(setTimeout(()=>{try{I?.terminate?.()}catch{}C()},e.closeTimeoutMs))}};let I;try{I=new Pt(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 l="finalized",Promise.resolve(D(c(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}),O=()=>e.removeEventListener("abort",t)}}const N=()=>{e.idleTimeoutMs&&(x=w(x),x=M(setTimeout(()=>j("idleTimeout",`no data frame within ${e.idleTimeoutMs}ms`),e.idleTimeoutMs)))},B=e=>{g.push(e);try{t.onEvent?.(e)}catch{}},R=e=>{for(const[t,r]of Object.entries(e?.headers??{}))v[t]=Array.isArray(r)?r.join(", "):String(r)};return I.on("upgrade",e=>{E=e?.statusCode??101,R(e)}),I.on("unexpected-response",(e,t)=>{E=t?.statusCode??0,R(t),S={message:`Handshake rejected with HTTP ${E}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}try{I.terminate()}catch{}C(S)}),I.on("open",()=>{if("connecting"===l){l="open",s=Date.now(),$=I.protocol||void 0,E||(E=101);try{t.onOpen?.({url:e.url,protocol:$,headers:v})}catch{}if(e.send.forEach((t,r)=>{const n=()=>{"open"===l&&I.readyState===Pt.OPEN&&I.send(t,e=>{e?S=S??c(e):(d+=1,B({id:String(d),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?jt(t):void 0,receivedAt:Date.now(),direction:"out"}))})},o=e.sendDelayMs*r;o<=0?n():_.push(M(setTimeout(n,o)))}),e.keepAlive){const{intervalMs:t,payload:r}=e.keepAlive;k=M(setInterval(()=>{if("open"===l&&I.readyState===Pt.OPEN)if(P)j("idleTimeout",`keep-alive ping unanswered for ${t}ms`);else try{I.ping(r),P=!0}catch{}},t))}N()}}),I.on("message",(t,r)=>{if("open"!==l)return;const n=function(e){if(Buffer.isBuffer(e))return e;if(Array.isArray(e))return Buffer.concat(e);try{return Buffer.from(e)}catch{return Buffer.alloc(0)}}(t);p+=n.length,d+=1,u+=1,r?h=!0:y=!0;const o=n.length>e.maxPayloadBytes;o&&(f=!0,m+=1);const s=r?`<binary ${n.length} bytes>`:o?`${Ct(n,e.maxPayloadBytes)}...`:n.toString("utf8");B({id:String(d),event:r?"binary":"text",data:s,parsed:r||o?void 0:jt(s),receivedAt:Date.now(),direction:"in"}),N(),u>=e.maxMessages&&j("maxEvents",`maxMessages (${e.maxMessages}) reached`)}),I.on("ping",e=>{"finalized"!==l&&(d+=1,B({id:String(d),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}))}),I.on("pong",()=>{P=!1}),I.on("error",e=>{"closing"!==l&&"finalized"!==l&&(S=S??c(e),I.readyState===Pt.CLOSED&&C(S))}),I.on("close",(e,t)=>{a=e;const r=t?.length?t.toString("utf8"):"";S||("closing"===l||!!i)||Mt.has(e)||(S={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),1009===e&&(f=!0,m+=1),C(S)}),A=M(setTimeout(()=>j("maxSessionMs",`maxSessionMs (${e.maxSessionMs}ms) reached`),e.maxSessionMs)),n.promise}function Ct(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 jt(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}import It from"ws";function Nt(e){let t="idle";function r(e){t=e,o.setState(e)}const o=n("websocket","websocket",`ws_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,"number"==typeof e.maxEvents&&e.maxEvents>=0?Math.floor(e.maxEvents):1e3),s="number"==typeof e.openTimeoutMs&&e.openTimeoutMs>0?Math.floor(e.openTimeoutMs):15e3;let i=null,a=()=>{},c=l();function l(){return new Promise(e=>{a=e})}function u(e){const{direction:t,receivedAt:r,event:n,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),o.emit({direction:t,kind:n,at:r,state:o.state,data:s,meta:Object.keys(y).length?y:void 0,error:h})}function d(){if(!i||"open"!==t||i.readyState!==It.OPEN)throw new Error("WebSocket session is not open");return i}function p(e){const t=E(e);u({direction:"meta",receivedAt:Date.now(),event:"error",data:t,error:t})}return{get protocol(){return"websocket"},get state(){return t},get events(){return o.events},onEvent:e=>o.onEvent(e),async open(){if("idle"!==t&&"closed"!==t&&"error"!==t)throw new Error(`WebSocket session cannot open from state "${t}"`);if(e.signal?.aborted)throw r("closed"),new Error("WebSocket open aborted");if(!e.url?.trim())throw new Error("WebSocket URL is required");c=l(),r("connecting"),await new Promise((n,o)=>{const c={headers:e.headers};void 0!==e.rejectUnauthorized&&(c.rejectUnauthorized=e.rejectUnauthorized);const l=e.subprotocols?.filter(Boolean)??[],d=l.length>0?new It(e.url,l,c):new It(e.url,c);i=d;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(),o(e))};if(f=setTimeout(()=>{const e=new Error(`WebSocket handshake timed out after ${s}ms`);r("error"),p(e),v(e);try{d.terminate()}catch{}},s),"function"==typeof f?.unref&&f.unref(),e.signal){const t=()=>{const e=new Error("WebSocket open aborted");r("closed"),p(e),v(e);try{d.terminate()}catch{}a()};if(e.signal.aborted)return void t();e.signal.addEventListener("abort",t,{once:!0}),m=()=>e.signal?.removeEventListener("abort",t)}d.once("upgrade",e=>{u({direction:"meta",receivedAt:Date.now(),event:"upgrade",statusCode:e.statusCode,statusMessage:e.statusMessage,headers:e.headers})}),d.once("unexpected-response",(e,t)=>{y=!0,u({direction:"meta",receivedAt:Date.now(),event:"unexpected-response",statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers}),t.resume();const n=[t.statusCode,t.statusMessage].filter(e=>void 0!==e&&""!==e).join(" "),o=new Error("WebSocket handshake failed"+(n?`: ${n}`:""));r("error"),p(o),v(o),d.readyState!==It.CONNECTING&&d.readyState!==It.OPEN||d.terminate()}),d.once("open",()=>{r("open"),u({direction:"meta",receivedAt:Date.now(),event:"open",statusCode:101,statusMessage:"Switching Protocols",protocol:d.protocol||void 0,extensions:d.extensions||void 0}),h||(h=!0,g(),n())}),d.on("message",(e,t)=>{if(t){const t=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):(ArrayBuffer,Buffer.from(e));return void u({direction:"in",receivedAt:Date.now(),event:"binary",data:t.toString("base64")})}const r=Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):(ArrayBuffer,Buffer.from(e).toString("utf8"));u({direction:"in",receivedAt:Date.now(),event:"text",data:r,parsed:S(r)})}),d.on("error",e=>{r("error"),p(e),v(e)}),d.once("close",(e,n)=>{const o=n.toString("utf8"),s=1e3===e;"error"!==t&&r("closed"),u({direction:"meta",receivedAt:Date.now(),event:"close",code:e,reason:o,wasClean:s}),a(),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=d();if(void 0!==r.delayMs&&r.delayMs>0&&await T(r.delayMs,e.signal),e.signal?.aborted)throw new Error("WebSocket send aborted");let o,s,i,a;if(d(),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=S(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 p(r),void t(r);u({direction:"out",receivedAt:Date.now(),event:s,data:i,parsed:a}),e()})})},async close(e={}){if(!i)return r("closed"),void a();if("closed"!==t){if("closing"!==t)return r("closing"),i.readyState===It.CONNECTING?(i.terminate(),void await c):i.readyState===It.OPEN?(i.close(e.code??1e3,e.reason??"Closed"),void await c):void(i.readyState!==It.CLOSING?(r("closed"),a()):await c);await c}else a()},async waitForClose(){await c}}}var Bt=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=Tt(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:x(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 Dt(e.config,t,r)}};function Rt(e,t,r){const n=r.graphql??{},o=e.operation?.["x-graphql"],s=o&&"object"==typeof o?o:{},a={...r.variables??{}};let c;if(c=n.endpoint?n.endpoint:"string"==typeof s.endpoint&&s.endpoint?s.endpoint:Te(e.servers,r),c=m(c,a),/\{\{[^}]+\}\}/.test(c))throw i("BAD_GRAPHQL_ENDPOINT",`Unresolved variable in GraphQL endpoint: ${c}`);try{const e=new URL(c);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw i("BAD_GRAPHQL_ENDPOINT",`GraphQL endpoint must be an absolute http(s) URL, received: ${c}`)}const l=n.query??s.query;if("string"!=typeof l||!l.trim())throw i("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 u=n.operationName??("string"==typeof(d=s.operationName)&&d.length?d:void 0);var d;const p=v(s.variablesSchema)?ye(s.variablesSchema):void 0,f=v(s.variables)?s.variables:void 0,h=v(r.values?.body)?r.values.body:void 0,y={...v(p)?p:{},...f??{},...h??{},...n.variables??{}},g={},b=e=>{if(v(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&(g[t]=m(String(r),a))};b(r.values?.header),b(s.headers),b(n.headers),qt(g,"content-type")||n.useGet||(g["Content-Type"]="application/json"),qt(g,"accept")||(g.Accept="application/json, text/event-stream");const w=r.auth;if(w&&"none"!==w.type&&!qt(g,"authorization"))if("bearer"===w.type)g.Authorization=`Bearer ${w.token??""}`;else if("basic"===w.type){const e=`${w.username??""}:${w.password??""}`;g.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===w.type&&"header"===(w.in??"header")&&(g[w.key??"X-API-Key"]=w.value??"");return{endpoint:c,query:l,operationName:u,variables:y,headers:g,useGet:!0===n.useGet}}function qt(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}function Lt(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}async function Ft(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,l=new AbortController,u=()=>l.abort();o?.addEventListener("abort",u,{once:!0});const d=setTimeout(()=>l.abort(),a);let p;d.unref?.();try{p=await fetch(s,{method:e.useGet?"GET":"POST",headers:e.headers,body:i,signal:l.signal})}catch(t){clearTimeout(d),o?.removeEventListener("abort",u);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"}:c(t)}}const f=Date.now(),m=p.headers.get("content-type")??void 0,h=!!m&&/text\/event-stream/i.test(m);let y,g,v,b,w=0;try{if(h&&p.body){const e=new lt({maxBufferChars:t.maxBufferChars,maxEventChars:t.maxEventChars,inheritEventId:t.inheritEventId});v=[];const r="number"==typeof t.maxEvents&&t.maxEvents>0?t.maxEvents:100,n=p.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(v.push(t),v.length>=r)break;if(v.length>=r){try{await n.cancel()}catch{}break}}for(const t of e.flush())v.length<r&&v.push(t)}else{const e=await p.text();if(w=e.length,g=e,m&&/json/i.test(m)&&e.trim())try{y=JSON.parse(e)}catch{}}}catch(e){b=c(e)}finally{clearTimeout(d),o?.removeEventListener("abort",u)}const $=Date.now();if(!b&&!h&&Ut(y)){const e=void 0!==y.data&&null!==y.data,t=Array.isArray(y.errors)?y.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||p.ok||Ut(y)||(b={message:`GraphQL endpoint responded HTTP ${p.status}`,code:String(p.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:p.status,statusText:p.statusText,headers:Lt(p.headers),contentType:m,...h?{events:v}:{body:y,text:g},timings:{startedAt:n,endedAt:$,durationMs:$-n,firstByteMs:f-n},sizeBytes:w},...b?{error:b}:{}}}function Ut(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}var zt="\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 Vt(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:zt}),signal:t.signal})}catch(e){throw i("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 i("GRAPHQL_INTROSPECTION_FAILED",`Introspection response was not valid JSON (HTTP ${r.status})`,void 0,{cause:e})}if(!r.ok||!n?.data?.__schema){throw i("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 Gt(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 Wt={ID:{type:"string"},String:{type:"string"},Int:{type:"integer"},Float:{type:"number"},Boolean:{type:"boolean"}};function Jt(e,t,r){const{named:n,nullable:o,listDepth:s}=Gt(e.type);let i;const a=n?t.types.get(n):void 0;if(n&&Wt[n])i={...Wt[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]=Jt(o,t,r);Gt(o.type).nullable||null!=o.defaultValue||n.push(o.name)}i={type:"object",properties:e,...n.length?{required:n}:{}}}else n&&!Wt[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}function Yt(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=>!Gt(e.type).nullable))continue;const{named:o,listDepth:i}=Gt(e.type),a=o?t.types.get(o):void 0;if(!a||"SCALAR"===a.kind||"ENUM"===a.kind||!!Wt[o??""])s.push(e.name);else if("OBJECT"===a?.kind||"INTERFACE"===a?.kind||"UNION"===a?.kind){if(r<=1)continue;const i=Yt(o,t,r-1,new Set(n));s.push(`${e.name} { ${i} }`)}if(s.length>=12)break}return s.length?s.join(" "):"__typename"}function Ht(e,t,r){const n=[],o={},s=[],i=[],a=[];for(const e of t.args??[]){const{named:t,nullable:c,listDepth:l}=Gt(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]=Jt(e,r,n),c||null!=e.defaultValue||s.push(e.name)}const{named:c,listDepth:l}=Gt(t.type),u=c?r.types.get(c):void 0,d=u&&("OBJECT"===u.kind||"INTERFACE"===u.kind||"UNION"===u.kind)?` { ${Yt(c,r,2,new Set)} }`:"",p=`${Xt(e)}_${Xt(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 Kt(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(Ht(o,n,e))}return t}function Xt(e){return e?e[0].toUpperCase()+e.slice(1):e}function Qt(e){return`/graphql/${e.operationType}/${e.fieldName}`}function Zt(e,t,r,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw i("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,s=d(e);v(s.paths)||(s.paths={});for(const e of r){const r=Qt(e);!o&&v(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 er(e,t,r={}){const{schema:n}=await Vt(t,{headers:r.headers,signal:r.signal}),o=Kt(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:Zt(e,t,o,r),operations:o,warnings:s}}var tr=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=Rt(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:x(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 Ft(e.config,t,r)}};var rr=new Set(["tools/call","resources/read","prompts/get","tools/list","resources/list","resources/templates/list","prompts/list"]);function nr(e,t,r){const n=r.mcp??{},o=e.operation?.["x-mcp"],s=o&&"object"==typeof o?o:{},a={...r.variables??{}},c=n.transport??s.transport??"streamable-http";if("streamable-http"!==c&&"stdio"!==c)throw i("BAD_MCP_TRANSPORT",`Unsupported MCP transport: ${JSON.stringify(c)}`);const l=c;let u,d,p,f,h,y,g,b;if("streamable-http"===l){if(u=n.endpoint||("string"==typeof s.endpoint?s.endpoint:Te(e.servers,r)),u=m(u,a),/\{\{[^}]+\}\}/.test(u))throw i("BAD_MCP_ENDPOINT",`Unresolved variable in MCP endpoint: ${u}`);try{const e=new URL(u);if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error("not http(s)")}catch{throw i("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${u}`)}}else{const e=n.command??s.command;if("string"!=typeof e||!e.trim())throw i("BAD_MCP_STDIO_COMMAND","MCP stdio transport requires command.");if(d=m(e.trim(),a),/\{\{[^}]+\}\}/.test(d))throw i("BAD_MCP_STDIO_COMMAND",`Unresolved variable in MCP command: ${d}`);const t=n.args??s.args;if(null!=t){if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw i("BAD_MCP_STDIO_CONFIG","MCP stdio args must be an array of strings.");p=t.map(e=>m(e,a))}const r=n.cwd??s.cwd;if(null!=r){if("string"!=typeof r||!r)throw i("BAD_MCP_STDIO_CONFIG","MCP stdio cwd must be a non-empty string.");f=m(r,a)}const o=n.env??s.env;if(null!=o){if(!v(o))throw i("BAD_MCP_STDIO_CONFIG","MCP stdio env must be an object.");h={};for(const[e,t]of Object.entries(o))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(h[e]=null==t?void 0:m(String(t),a))}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 i("BAD_MCP_STDIO_CONFIG",`${e} must be a positive finite number.`);"timeoutMs"===e?y=t:"maxBufferBytes"===e?g=t:b=t}}const w=n.method??s.method;if("string"!=typeof w||!rr.has(w))throw i("BAD_MCP_METHOD",`options.mcp.method (or x-mcp.method) must be one of: ${Array.from(rr).join(", ")}. Received: ${JSON.stringify(w)}`);const $=n.name??s.name,S=v(s.arguments)?s.arguments:void 0,E=v(s.argumentsSchema)?s.argumentsSchema:void 0,A=E?ye(E):void 0,x=v(r.values?.body)?r.values.body:void 0,T={...v(A)?A:{},...S??{},...x??{},...n.arguments??{}};let k;if("tools/call"===w){if(!$)throw i("BAD_MCP_TARGET","tools/call requires options.mcp.name (or x-mcp.name).");k={name:$,arguments:T}}else if("prompts/get"===w){if(!$)throw i("BAD_MCP_TARGET","prompts/get requires options.mcp.name (or x-mcp.name).");k={name:$,arguments:T}}else if("resources/read"===w){const e=T.uri??s.uri??n.arguments?.uri;if("string"!=typeof e||!e)throw i("BAD_MCP_TARGET","resources/read requires a `uri` (via options.mcp.arguments.uri or x-mcp.uri).");k={uri:e}}else k=T;const _={"Content-Type":"application/json"},O=e=>{if(v(e))for(const[t,r]of Object.entries(e))null!=r&&"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(_[t]=m(String(r),a))};O(r.values?.header),O(s.headers),O(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)}(_,"Authorization"))if("bearer"===P.type)_.Authorization=`Bearer ${P.token??""}`;else if("basic"===P.type){const e=`${P.username??""}:${P.password??""}`;_.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===P.type&&"header"===(P.in??"header")&&(_[P.key??"X-API-Key"]=P.value??"");return{transport:l,..."streamable-http"===l&&u?{endpoint:u}:{},..."stdio"===l&&d?{command:d,...p?{args:p}:{},...f?{cwd:f}:{},...h?{env:h}:{},...null!=y?{timeoutMs:y}:{},...null!=g?{maxBufferBytes:g}:{},...null!=b?{maxStderrBytes:b}:{}}:{},method:w,params:k,headers:_,sessionId:n.sessionId??or(s.sessionId),protocolVersion:n.protocolVersion??or(s.protocolVersion),clientInfo:n.clientInfo??{name:"protokit",version:"0.1.0"}}}function or(e){return"string"==typeof e&&e.length?e:void 0}var sr=0;function ir(){return sr+=1}async function ar(e,t,r){const n=new AbortController;let o,s,a;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{a=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 i("MCP_TRANSPORT_FAILED",`Could not reach MCP endpoint: ${e?.message??e}`,void 0,{cause:e})}finally{s&&clearTimeout(s),o?.()}const c=Date.now()-r.startedAt,l=function(e){const t={};return e.forEach((e,r)=>{t[r]=t[r]?`${t[r]}, ${e}`:e}),t}(a.headers),u=a.headers.get("content-type")??void 0,d=a.headers.get("mcp-session-id")??void 0;if(202===a.status||204===a.status)return{message:void 0,status:a.status,statusText:a.statusText,headers:l,contentType:u,sessionId:d,sizeBytes:0,firstByteMs:c};if(u&&/text\/event-stream/i.test(u)&&a.body){const e=new lt,n=a.body.getReader();let o=0;const s="number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0?r.maxResponseBytes:0;let p;for(;;){const{done:r,value:a}=await n.read();if(r)break;if(o+=a?.byteLength??0,s>0&&o>s){try{await n.cancel()}catch{}throw i("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${s} bytes while reading event stream.`)}for(const r of e.push(a))if(r.parsed&&"object"==typeof r.parsed){const e=r.parsed;void 0!==t.id&&e.id!==t.id||(p=e)}if(void 0!==p){try{await n.cancel()}catch{}break}}if(void 0===p)for(const t of e.flush())t.parsed&&"object"==typeof t.parsed&&(p=t.parsed);return{message:p,status:a.status,statusText:a.statusText,headers:l,contentType:u,sessionId:d,sizeBytes:o,firstByteMs:c}}let p,f;try{if(p=await a.text(),"number"==typeof r.maxResponseBytes&&r.maxResponseBytes>0&&p.length>r.maxResponseBytes)throw i("MCP_RESPONSE_TOO_LARGE",`MCP response exceeded ${r.maxResponseBytes} bytes.`);p.trim()&&(f=JSON.parse(p))}catch(e){return{message:void 0,status:a.status,statusText:a.statusText,headers:l,contentType:u,sessionId:d,rawText:p,sizeBytes:p?.length??0,firstByteMs:c}}return{message:f,status:a.status,statusText:a.statusText,headers:l,contentType:u,sessionId:d,rawText:p,sizeBytes:p?.length??0,firstByteMs:c}}function cr(e){return!!e&&"object"==typeof e&&v(e.error)}var lr="2025-06-18",ur=new Set([-32601,-32600]),dr={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};async function pr(e,t={}){const r=Date.now(),n=await ar(e,{jsonrpc:"2.0",id:ir(),method:"initialize",params:{protocolVersion:lr,capabilities:t.capabilities??{},clientInfo:t.clientInfo??{name:"protokit",version:"0.1.0"}}},{headers:t.headers,signal:t.signal,startedAt:r});if(cr(n.message))throw i("MCP_INITIALIZE_FAILED",`initialize failed: ${n.message.error.message}`,n.message.error);if(!n.message?.result)throw i("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 ar(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 fr(e,t,r,n){const o=Date.now(),s={...n.headers??{},...r.sessionId?{"Mcp-Session-Id":r.sessionId}:{}},a=dr[t],c=[],l=new Set;let u,d=0;for(;;){const p=await ar(e,{jsonrpc:"2.0",id:ir(),method:t,params:u?{cursor:u}:{}},{headers:s,signal:n.signal,startedAt:o,protocolVersion:r.protocolVersion});if(cr(p.message)){const{code:e,message:r}=p.message.error;if(ur.has(e))return;throw i("MCP_LIST_FAILED",`${t} failed (${e}): ${r}`,p.message.error)}const f=p.message?.result;if(!f){if(p.status>=400)throw i("MCP_LIST_FAILED",`${t} returned HTTP ${p.status} ${p.statusText} with no JSON-RPC result.`);return c}d+=1,Array.isArray(f[a])&&c.push(...f[a]);const m="string"==typeof f.nextCursor?f.nextCursor:void 0;if(!m)break;if(l.has(m)||d>=1e3)break;l.add(m),u=m}return c}async function mr(e,t={}){const r=await pr(e,t),n=[],o=[],s=await fr(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 fr(e,"resources/list",r,t),a=await fr(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 fr(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}}import{spawn as hr}from"child_process";import{once as yr}from"events";function gr(e){if(!e||"string"!=typeof e.command||!e.command.trim())throw i("BAD_MCP_STDIO_COMMAND","MCP stdio requires a non-empty command.");const t=vr(e.timeoutMs,3e4,"timeoutMs"),r=vr(e.maxBufferBytes,4194304,"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=hr(e.command,e.args??[],{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],shell:!1,windowsHide:!0})}catch(e){throw i("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${E(e)}`,void 0,{cause:e})}let s=!1,a=0,c="",l="";const u=new Map,d=(e,t)=>{u.get(e)===t&&u.delete(e),t.timer&&clearTimeout(t.timer),t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort)},p=e=>{for(const[t,r]of u)d(t,r),r.reject(e)},f=e=>{if(s)return;const t=i("MCP_STDIO_PROTOCOL_ERROR",e);p(t),h()};function m(e){if(s||o.stdin.destroyed||!o.stdin.writable)return Promise.reject(i("MCP_STDIO_CLOSED","MCP stdio process is closed."));let t;try{t=JSON.stringify(e)+"\n"}catch(e){return Promise.reject(i("MCP_STDIO_SERIALIZE_FAILED",`Could not serialize MCP JSON-RPC message: ${E(e)}`,void 0,{cause:e}))}return new Promise((e,r)=>{o.stdin.write(t,"utf8",t=>{t?r(t):e()})})}async function h(){if(s)return;if(s=!0,p(i("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{}},1500);e.unref?.();try{await Promise.race([yr(o,"exit").then(()=>{}),T(2e3)])}finally{clearTimeout(e)}}return o.stdout.setEncoding("utf8"),o.stdout.on("data",e=>{if(!s)if(c+=e,Buffer.byteLength(c,"utf8")>r)f(`MCP stdio stdout buffer exceeded ${r} bytes without a complete JSON-RPC line.`);else for(;;){const e=c.indexOf("\n");if(e<0)break;const t=c.slice(0,e).replace(/\r$/,"");if(c=c.slice(e+1),!t.trim())continue;if(Buffer.byteLength(t,"utf8")>r)return void f(`MCP stdio JSON-RPC message exceeded ${r} bytes.`);let n;try{n=JSON.parse(t)}catch{return void f(`MCP stdio emitted invalid JSON-RPC: ${t.slice(0,512)}`)}if(!br(n))return void f("MCP stdio emitted an invalid JSON-RPC envelope.");if(void 0===n.id)continue;const o=u.get(n.id);o&&(d(n.id,o),void 0!==n.error?o.reject(i("MCP_RPC_ERROR",`${n.error.code}: ${n.error.message}`,n.error)):Object.prototype.hasOwnProperty.call(n,"result")?o.resolve(n.result):o.reject(i("MCP_STDIO_PROTOCOL_ERROR","MCP stdio response contained neither result nor error.")))}}),o.stderr.setEncoding("utf8"),o.stderr.on("data",e=>{l=(l+e).slice(-65536)}),o.once("error",e=>{s||(s=!0,p(i("MCP_STDIO_SPAWN_FAILED",`Could not start MCP stdio process: ${E(e)}`,void 0,{cause:e})))}),o.once("exit",(e,t)=>{if(s)return;s=!0;const r=l.trim()?` stderr: ${l.trim().slice(-2048)}`:"";p(i("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(i("MCP_ABORTED","MCP request was aborted before send."));if(s)return Promise.reject(i("MCP_STDIO_CLOSED","MCP stdio process is closed."));const o=++a;return new Promise((s,a)=>{const c={resolve:s,reject:a};c.timer=setTimeout(()=>{d(o,c),a(i("MCP_TIMEOUT",`${e} timed out after ${t}ms`))},t),c.timer.unref?.(),n&&(c.signal=n,c.onAbort=()=>{d(o,c),a(i("MCP_ABORTED",`${e} was aborted.`))},n.addEventListener("abort",c.onAbort,{once:!0})),u.set(o,c),m({jsonrpc:"2.0",id:o,method:e,...void 0===r?{}:{params:r}}).catch(e=>{d(o,c),a(e)})})},notify:async function(e,t,r){if(r?.aborted)throw i("MCP_ABORTED","MCP notification was aborted before send.");await m({jsonrpc:"2.0",method:e,...void 0===t?{}:{params:t}})},close:h}}function vr(e,t,r){const n=e??t;if(!Number.isFinite(n)||n<=0)throw i("BAD_MCP_STDIO_CONFIG",`MCP stdio ${r} must be a positive finite number.`);return n}function br(e){return!!e&&"object"==typeof e&&"2.0"===e.jsonrpc}async function wr(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:ir(),method:e.method,params:e.params},a=gr({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??lr,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:c(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 pr(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:c(t),replays:s}}const l={...e.headers,...i?{"Mcp-Session-Id":i}:{}},u={jsonrpc:"2.0",id:ir(),method:e.method,params:e.params};try{const t=await ar(e.endpoint,u,{headers:l,signal:o,startedAt:n,protocolVersion:a}),r=Date.now(),i=cr(t.message)?t.message.error:void 0;return{protocol:"mcp",request:{method:"POST",url:e.endpoint,headers:l,body:u},response:{status:t.status,statusText:t.statusText,headers:t.headers,contentType:t.contentType,body:i?t.message:t.message?.result,text:t.rawText,timings:{startedAt: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:l,body:u},response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:n,endedAt:r,durationMs:r-n},sizeBytes:0},error:c(t),replays:s}}}(e,t,r)}function $r(e){const t=[];if("tool"===e.kind){const r=e.inputSchema??{type:"object",properties:{}},n=ye(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=ye(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 Sr(e){return e.map($r)}function Er(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Ar(e){return`/mcp/${"tool"===e.kind?"tools":"prompt"===e.kind?"prompts":"resources"}/${Er(e.name)}`}function xr(e,t,r,n={}){if(!e||"object"!=typeof e||Array.isArray(e))throw i("BAD_SPEC","spec must be an object");const o=!1!==n.overwrite,s=d(e);v(s.paths)||(s.paths={});for(const e of r){const{capability:r}=e,n=Ar(r);!o&&v(s.paths[n])||(s.paths[n]={post:{operationId:`mcp_${r.kind}_${Er(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 Tr(e,t,r={}){const n=await mr(t,r);return{spec:xr(e,t,Sr(n.capabilities),r),capabilities:n.capabilities,warnings:n.warnings}}function kr(e){if(!e||!e.endpoint)throw i("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 pr(t,n);return{sessionId:o.sessionId,serverInfo:o.serverInfo,protocolVersion:o.protocolVersion??e.protocolVersion??lr}},call:(e,n)=>ar(t,e,{headers:{...n.headers??r},signal:n.signal,startedAt:n.startedAt,protocolVersion:n.protocolVersion}),notify:(e,n)=>ar(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 _r(e){const t=gr(e);let r=!1;return{transport:"stdio",async open(e){const r=await t.request("initialize",{protocolVersion:e.protocolVersion??lr,capabilities:e.capabilities??{},clientInfo:e.clientInfo??{name:"protokit",version:"0.1.0"}},e.signal);if(!r||"object"!=typeof r)throw i("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??lr}},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 Or={"tools/list":"tools","prompts/list":"prompts","resources/list":"resources","resources/templates/list":"resourceTemplates"};function Pr(e,t=0,r=new WeakSet){if(t>8)return"[depth-limit]";if(!v(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=>Pr(e,t+1,r));const n={};for(const[o,s]of Object.entries(e))n[o]=x(o)&&null!=s?"[redacted]":Pr(s,t+1,r);return n}function Mr(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 Dr(e){try{const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("not http(s)");return e}catch{throw i("BAD_MCP_ENDPOINT",`MCP endpoint must be an absolute http(s) URL, received: ${e}`)}}function Cr(e,t){const r=t.timeoutMs??3e4,o=(t.maxEvents,!1!==t.redactSecrets),s=!0===t.serialize,a=n("mcp",t.transport??"http",`mcp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,t.maxEvents??1e3);let l="idle";const u=()=>l,d=e=>{l=e,a.setState(e)};let p,f,m,h,y,g;const b=new Promise(e=>{g=e}),w=new Set;function $(e){const t=o?Pr(e.parsed):e.parsed;a.emit({direction:e.direction,kind:e.event,at:e.at,state:u(),data:e.data,meta:void 0!==t?{parsed:t}:void 0})}function S(e){const t=u();if("open"!==t){if("idle"===t||"connecting"===t)throw i("MCP_NOT_OPEN",`Call open() before ${e}; session is "${t}".`);throw i("MCP_SESSION_CLOSED",`Cannot ${e} on a ${t} session.`)}}async function E(e){const t=e.then(()=>{},()=>{});w.add(t);try{return await e}finally{w.delete(t)}}async function A(n,o,s){const a=o?.timeoutMs??r,l=Mr(a,t.signal,o?.signal);try{o?.delayMs&&await(u=o.delayMs,m=l.signal,u>0?new Promise((e,t)=>{const r=()=>{clearTimeout(n),t(i("MCP_ABORTED","Aborted while waiting to send."))},n=setTimeout(()=>{m?.removeEventListener("abort",r),e()},u);if(m?.aborted)return r();m?.addEventListener("abort",r,{once:!0})}):Promise.resolve()),$({direction:"out",at:Date.now(),event:s,parsed:n});const r={signal:l.signal,timeoutMs:a,startedAt:Date.now(),protocolVersion:f,sessionId:p,headers:{...t.headers??{},...p?{"Mcp-Session-Id":p}:{}}},c="notification"===s?await e.notify(n,r):await e.call(n,r);if(c.sessionId&&c.sessionId!==p&&(p=c.sessionId,$({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{sessionIdChanged:p}})),$({direction:"in",at:Date.now(),event:s,parsed:c.message??{status:c.status,statusText:c.statusText,empty:!0}}),404===c.status&&p)throw d("closed"),g(),i("MCP_SESSION_EXPIRED",`Server no longer recognises session ${p} (HTTP 404).`);return c}catch(e){const t=c(e);if($({direction:"meta",at:Date.now(),event:"error",parsed:t}),l.timedOut())throw i("MCP_TIMEOUT",`${String(n.method)} timed out after ${a}ms`,t);throw e}finally{l.dispose()}var u,m}async function x(e,t,r){if("string"!=typeof e||!e)throw i("BAD_MCP_METHOD","request() requires a non-empty method name.");S(`request("${e}")`);const n={jsonrpc:"2.0",id:ir(),method:e,...void 0===t?{}:{params:t}},o=await E(A(n,r,"jsonrpc"));if(r?.raw)return o;if(cr(o.message))throw i("MCP_RPC_ERROR",`${e} failed (${o.message.error.code}): ${o.message.error.message}`,o.message.error);if(void 0===o.message)throw i("MCP_EMPTY_RESPONSE",`${e} returned no JSON-RPC message (HTTP ${o.status} ${o.statusText}).`);return o.message.result}async function T(e,t){const r=Or[e],n=[],o=new Set;let s,i=0;for(;;){const a=await x(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>=1e3){$({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 k(){if("closed"!==u()){if("closing"===u())return y;if("idle"===u())return d("closed"),g(),void await e.dispose();if("connecting"!==u()||(await(h?.catch(()=>{})),"closed"!==u()))return d("closing"),y=(async()=>{if(await Promise.allSettled([...w]),p){const n=Mr(r);try{const r=await e.terminate({sessionId:p,protocolVersion:f,signal:n.signal,headers:t.headers});$({direction:"meta",at:Date.now(),event:"lifecycle",parsed:{terminate:r.status,outcome:r.outcome,...r.reason?{reason:r.reason}:{}}})}catch(e){$({direction:"meta",at:Date.now(),event:"error",parsed:{terminate:"failed",reason:c(e).message}})}finally{n.dispose()}}await e.dispose(),d("closed"),g(),y=void 0})(),y}}t.signal&&(t.signal.aborted?(d("closed"),g()):t.signal.addEventListener("abort",()=>{k().catch(()=>{})},{once:!0}));const _={get protocol(){return"mcp"},get state(){return u()},get events(){return a.events},onEvent:e=>a.onEvent(e),get sessionId(){return p},get protocolVersion(){return f},get serverInfo(){return m},open:async function(){const n=u();if("open"===n)return;if("connecting"===n)return h;if("closing"===n||"closed"===n)throw i("MCP_SESSION_CLOSED","This session has been closed; create a new one.");d("connecting");const o=Mr(r,t.signal);return h=(async()=>{try{const r=await e.open({clientInfo:t.clientInfo,capabilities:t.capabilities,signal:o.signal});p=r.sessionId,f=r.protocolVersion??f??void 0,m=r.serverInfo,d("open"),$({direction:"in",at:Date.now(),event:"session",parsed:{sessionId:p,protocolVersion:f,serverInfo:m}})}catch(e){d("closed"),g();const t=c(e);if($({direction:"meta",at:Date.now(),event:"error",parsed:t}),o.timedOut())throw i("MCP_TIMEOUT",`initialize timed out after ${r}ms`,t);throw e}finally{o.dispose(),h=void 0}})(),h},request:x,send:async function(e,t){S("send()");const r=v(e)?e:"string"==typeof e?{method:e}:void 0;if(!r||"string"!=typeof r.method||!r.method)throw i("BAD_MCP_MESSAGE","send() expects a method name or an object with a string `method`.");const n=r.method.startsWith("notifications/");return E(A({jsonrpc:"2.0",...r,...void 0!==r.id?{id:r.id}:n?{}:{id:ir()}},t,n?"notification":"jsonrpc"))},notify:async function(e,t,r){if("string"!=typeof e||!e)throw i("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(A(n,r,"notification"))},ping:e=>x("ping",{},e).then(()=>{}),listTools:e=>T("tools/list",e),listPrompts:e=>T("prompts/list",e),listResources:e=>T("resources/list",e),listResourceTemplates:e=>T("resources/templates/list",e),async listSources(e){const t=await(async()=>{if(s){const t=[];for(const r of["resources/list","resources/templates/list"])try{t.push({status:"fulfilled",value:await T(r,e)})}catch(e){t.push({status:"rejected",reason:e})}return t}return Promise.allSettled([T("resources/list",e),T("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 i("BAD_MCP_TARGET","callTool() requires a tool name.");return x("tools/call",{name:t.name,arguments:t.arguments??{}},t.opts??r)}const n=e;if(!n)throw i("BAD_MCP_TARGET","callTool() requires a tool name.");return x("tools/call",{name:n,arguments:t??{}},r)},getPrompt(e,t,r){if(!e)throw i("BAD_MCP_TARGET","getPrompt() requires a prompt name.");return x("prompts/get",{name:e,arguments:t??{}},r)},readResource(e,t){if(!e)throw i("BAD_MCP_TARGET","readResource() requires a uri.");return x("resources/read",{uri:e},t)},close:k,waitForClose:()=>b};return _[Symbol.asyncDispose]=()=>k(),_}function jr(e){if(!e||"object"!=typeof e)throw i("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 i("BAD_MCP_STDIO_COMMAND","MCP stdio sessions require a non-empty `command`.");return _r({command:e.command,args:e.args,cwd:e.cwd,env:e.env,timeoutMs:e.timeoutMs,maxBufferBytes:e.maxBufferBytes})}if(!e.endpoint)throw i("BAD_MCP_ENDPOINT",'MCP http sessions require an `endpoint` (or set transport: "stdio" with a `command`).');return kr({endpoint:Dr(e.endpoint),headers:e.headers})}(e);return Cr(t,e)}function Ir(e){return jr({...e,transport:"stdio"})}var Nr=jr,Br=class{name="mcp";supports(e){const t=e.located.operation??{};return"mcp"===t["x-protocol"]?20:v(t["x-mcp"])||e.options.mcp?.method||e.options.mcp?.endpoint?15:"mcp"===e.located.pathItem?.["x-protocol"]?12:0}plan(e){const t=nr(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:x(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 wr(e.config,t,r)}};import{createRequire as Rr}from"module";import{readFileSync as qr}from"fs";import{dirname as Lr,join as Fr}from"path";var Ur,zr,Vr="@grpc/grpc-js",Gr="@grpc/proto-loader",Wr=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}},Jr=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 Yr(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 Wr([e],t);throw new Jr(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 Jr(r,`its module namespace has no "${t}" export, so the installed version is not the package this library expects.`)}(r,t,e)}function Hr(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 Jr(t,`expected "${n}" to be a ${o}, found ${s}. The installed package is not the one this library supports.`)}}function Kr(e){try{const t=Rr(import.meta.url);let r=Lr(t.resolve(e));for(let t=0;t<8;t++){try{const t=qr(Fr(r,"package.json"),"utf8"),n=JSON.parse(t);if(n.name===e&&"string"==typeof n.version)return n.version}catch{}const t=Lr(r);if(t===r)break;r=t}}catch{}}async function Xr(){return zr||(Ur||(Ur=async function(){const e=await Promise.allSettled([Yr(Vr,"Client"),Yr(Gr,"load")]),t=[];for(const r of e)"rejected"===r.status&&r.reason instanceof Wr&&t.push(...r.reason.missing);if(t.length>0){const r=e.find(e=>"rejected"===e.status&&e.reason instanceof Wr);throw new Wr(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 Hr(r,Vr,{Client:"function",Metadata:"function",credentials:"object"}),Hr(n,Gr,{load:"function"}),{grpc:r,protoLoader:n,capabilities:{descriptorSetFromBuffer:"function"==typeof n.loadFileDescriptorSetFromBuffer,grpcVersion:Kr(Vr),protoLoaderVersion:Kr(Gr)}}}().then(e=>(zr=e,e),e=>{throw Ur=void 0,e})),Ur)}async function Qr(){try{return await Xr(),!0}catch{return!1}}function Zr(e,t){switch(t){case"descriptorSetFromBuffer":{if(e.capabilities.descriptorSetFromBuffer)return;const t=e.capabilities.protoLoaderVersion?` (found ${e.capabilities.protoLoaderVersion})`:"";throw new Jr(Gr,`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 en(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 tn(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=en(n.rootCerts,"rootCerts"),s=en(n.privateKey,"privateKey"),i=en(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 rn(e,t){return tn(e,t).credentials}async function nn(e){return rn(e,await Xr())}async function on(e){return tn(e,await Xr())}import{readdir as sn,realpath as an,stat as cn}from"fs/promises";import{dirname as ln,join as un,resolve as dn,sep as pn}from"path";var fn=["node_modules",".git","dist","build","out",".venv"];function mn(e){return e.toLowerCase().endsWith(".proto")}function hn(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 yn(e){try{const t=await cn(e);return t.isDirectory()?"dir":t.isFile()?"file":"other"}catch{return"error"}}async function gn(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??fn),r=e.maxFiles??5e3,n=new Set,o=[],s=[],i=[],a=new Set,c=new Map;let l=!1,u=0;const d=e=>{i.length>=40?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 an(t)}catch(e){return void d(hn(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 an(r)}catch(e){return void d(hn(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 sn(r,{withFileTypes:!0})}catch(e){return void d(hn(r,e))}for(const o of s){if(l)return;const s=un(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 cn(s)}catch(e){d(hn(s,e));continue}r.isDirectory()?t.has(o.name)||await f(s,!0):r.isFile()&&mn(o.name)&&await p(dn(s),!0);continue}if(o.isDirectory()){t.has(o.name)||await f(s,n);continue}if(o.isFile()){mn(o.name)&&await p(dn(s),n);continue}if(o.isFIFO()||o.isSocket()||o.isBlockDevice()||o.isCharacterDevice())continue;const i=await yn(s);"dir"===i?t.has(o.name)||await f(s,n):"file"===i?mn(o.name)&&await p(dn(s),n):"error"===i&&mn(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=dn(t);let r;try{r=await cn(e)}catch(e){throw new Error(hn(t,e),{cause:e})}if(r.isFile()){if(!mn(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(pn)?t:t+pn;return e===t||e.startsWith(r)}function bn(e){const t=[],r=new Set;for(const t of e.rootDirs)r.add(t);for(const t of e.fileRoots)r.add(ln(t));const n=[...r],o=[];for(const t of e.files){const e=ln(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=[1,128,16384,2097152,268435456,34359738368,4398046511104,562949953421312,72057594037927940,0x8000000000000000],$n=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>=wn.length)throw new Error("varint longer than 10 bytes");e=this.buf[this.pos++],t+=(127&e)*wn[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 0:return void this.varint();case 1:return void this.advance(8);case 2: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 Sn(e,t){const r=new $n(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 En(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 An(e,t){return En(8*e+t)}function xn(e,t){return Buffer.concat([An(e,2),En(t.length),t])}function Tn(e,t){return xn(e,Buffer.from(t,"utf8"))}function kn(e){return"list"===e?"the service list":e.slice(e.indexOf(":")+1)}function _n(e){let t,r={kind:"other",field:0};return Sn(e,(e,n,o)=>{if(2!==n)return!1;switch(e){case 2:return t=function(e){let t;return Sn(e,(e,r,n)=>2===r&&(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 Sn(o.view(),(t,r,n)=>1===t&&2===r&&(e.push(n.bytes()),!0)),r={kind:"files",descriptors:e},!0}case 6:{const e=[];return Sn(o.view(),(t,r,n)=>1===t&&2===r&&(Sn(n.view(),(t,r,n)=>1===t&&2===r&&(e.push(n.string()),!0)),!0)),r={kind:"services",services:e},!0}case 7:{let e=2,t="";return Sn(o.view(),(r,n,o)=>1===r&&0===n?(e=o.varint(),!0):2===r&&2===n&&(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 On(e){let t="";const r=[];return Sn(e,(e,n,o)=>2===n&&(1===e?(t=o.string(),!0):3===e&&(r.push(o.string()),!0))),{name:t,dependencies:r}}var Pn=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}},Mn=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}},Dn=class extends Error{detail;constructor(e,t){super(t?`${e} (${t})`:e),this.name="ReflectionProtocolError",this.detail=t}},Cn={v1:"/grpc.reflection.v1.ServerReflection/ServerReflectionInfo",v1alpha:"/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo"};function jn(e){return"object"==typeof e&&null!==e&&!0===e.versionMissing}function In(e){const t=e?.code;return"number"==typeof t?t:void 0}function Nn(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 Bn(e){if("string"!=typeof e.address||""===e.address)throw new TypeError("reflection requires a non-empty address.");if(Nn("timeoutMs",e.timeoutMs,1),Nn("maxFiles",e.maxFiles,1),Nn("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 Rn(e,t){const r=e.version?[e.version]:["v1","v1alpha"];let n;for(const[o,s]of r.entries())try{const n=await qn(e,t,s);return o>0&&n.notes.unshift(`reflection ${r[0]} was unimplemented; used ${s}.`),n}catch(e){if(!jn(e))throw e;n=e.cause}throw new Pn(e.address,r,n)}function qn(e,t,r){const n=e.timeoutMs??5e3,o=e.maxFiles??2e3,s=e.maxBytes??33554432,i=e.host??"";return Xr().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: ${E(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 Mn(e.address,void 0,`the channel could not be created: ${E(t)}. Expected host:port`)}try{u=l.makeBidiStreamRequest(Cn[r],e=>e,e=>e,c,{deadline:new Date(Date.now()+n)})}catch(t){try{l.close()}catch{}throw new Mn(e.address,In(t),E(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 $=()=>{if(0===f.size)return;const e=[...f.keys()].slice(0,5).join(", ");return`still awaiting ${f.size} reply(ies): ${e}${f.size>5?", …":""}`},S=setTimeout(()=>{x(new Dn(`reflection session at ${e.address} did not complete within ${n}ms`,$()))},n+250);S.unref?.();const A=()=>{clearTimeout(S);try{u.cancel()}catch{}try{l.close()}catch{}};function x(e){v||(v=!0,A(),c(e))}function T(t){x(w?new Dn(`the reflection stream at ${e.address} failed after the server had already answered, so ${r} is served here; ${d.size} file(s) were discarded`,E(t)):{versionMissing:!0,cause:t})}function k(){if(!v){v=!0,clearTimeout(S);try{u.end()}catch{}try{l.close()}catch{}a({services:"symbols"===t.kind?void 0:h??[],descriptors:d,version:r,notes:p})}}const _=(t,r)=>{if(!v&&!m.has(t))if(m.size>=o)x(new Dn(`reflection closure exceeded maxFiles=${o}`,`while requesting ${kn(t)}`));else{m.add(t),f.set(t,{key:t,primary:r});try{u.write(function(e,t){const r=[];return t&&r.push(Tn(1,t)),"list"===e?r.push(Tn(7,"*")):e.startsWith("file:")?r.push(Tn(3,e.slice(5))):r.push(Tn(4,e.slice(4))),Buffer.concat(r)}(t,i))}catch(r){x(new Mn(e.address,In(r),`writing the request for ${kn(t)} failed: ${E(r)}`))}}};if(u.on("data",e=>{if(v)return;let r;try{r=_n(e)}catch(e){return w=!0,void x(new Dn("malformed ServerReflectionResponse",E(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 x(new Dn(`reflection request for ${n?kn(n.key):"(unknown)"} failed`,o));p.push(`server could not supply ${kn(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 ${kn(n.key)}.`),(e=>{for(const t of e){if(v)return;if(g+=t.length,g>s)return void x(new Dn(`reflection payload exceeded maxBytes=${s}`,`after ${d.size} file(s)`));let e;try{e=On(t)}catch(e){return void x(new Dn("server returned a FileDescriptorProto that could not be parsed",E(e)))}if(e.name){if(!d.has(e.name)){d.set(e.name,t);for(const t of e.dependencies)if(d.has(t)||_(`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(_(`sym:${t}`,!0),v)return}break;case"other":p.push(`ignored an unexpected reflection response variant (field ${r.body.field}) for ${n?kn(n.key):"(unknown request)"}.`)}0!==f.size||y||k()}),u.on("error",t=>{if(v)return;const r=In(t);12!==r&&5!==r?x(new Mn(e.address,r,E(t))):T(t)}),u.on("status",t=>{if(v)return;const r=t;if(0!==r.code){const t=`${r.code} ${r.details??""}`.trim();return 12===r.code||5===r.code?void T(Object.assign(new Error(`reflection stream ended: ${t}`),{code:r.code,details:r.details})):void x(new Mn(e.address,r.code,r.details||"the stream ended with a non-OK status"))}f.size>0||y?x(new Dn("server closed the reflection stream before answering everything",$()??"the service list was requested but never returned")):k()}),u.on("end",()=>{v||0!==f.size||y||k()}),"symbols"===t.kind){for(const e of t.symbols)if(_(`sym:${e}`,!0),v)return}else _("list",!0)})})}function Ln(e){const t=new Map;for(const[r,n]of e){let o;try{o=On(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 Fn(e){const{ordered:t}=Ln(e);return Buffer.concat(t.map(t=>xn(1,e.get(t))))}async function Un(e){Bn(e);const t=await Rn(e,{kind:"list"});return{services:(t.services??[]).filter(e=>!e.startsWith("grpc.reflection.")).sort(),version:t.version,notes:t.notes}}async function zn(e){return(await Un(e)).services}function Vn(e,t){if(0===e.descriptors.size)throw new Dn(`reflection returned no file descriptors for ${t}`,e.notes.join(" ")||void 0);const{ordered:r,cycles:n}=Ln(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=>xn(1,e.descriptors.get(t)))),files:r,version:e.version,notes:o}}async function Gn(e){if(Bn(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 Vn(await Rn(e,{kind:"symbols",symbols:e.symbols}),e.symbols.join(", "))}async function Wn(e){Bn(e);const t=await Rn(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,...Vn(t,r.join(", "))}}var Jn=class extends Error{constructor(e){super(`descriptor decode failed: ${e}`),this.name="DescriptorDecodeError"}};function Yn(e){let t=0n,r=0n;for(;;){if(e.pos>=e.end)throw new Jn("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 Jn("varint too long")}}function Hn(e,t,r){switch(t){case 0:return void Yn(e);case 1:return void Kn(e,8);case 5:return void Kn(e,4);case 2:return void Kn(e,Number(Yn(e)));case 3:if(r>32)throw new Jn("group nesting too deep");for(;;){if(e.pos>=e.end)throw new Jn("unterminated group");const t=7&Number(Yn(e));if(4===t)return;Hn(e,t,r+1)}default:throw new Jn(`unsupported wire type ${t}`)}}function Kn(e,t){if(t<0||e.pos+t>e.end)throw new Jn("length exceeds buffer");e.pos+=t}function Xn(e){const t={buf:e,pos:0,end:e.length},r=new Map;for(;t.pos<t.end;){const n=Number(Yn(t)),o=n>>>3,s=7&n;if(0===o)throw new Jn("field number 0 is invalid");let i;if(0===s)i={wireType:s,varint:Yn(t)};else if(2===s){const r=Number(Yn(t));if(r<0||t.pos+r>t.end)throw new Jn("length-delimited field overruns");i={wireType:s,bytes:e.subarray(t.pos,t.pos+r)},t.pos+=r}else{const r=t.pos;Hn(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 Qn=new TextDecoder("utf-8",{fatal:!0});function Zn(e,t){const r=e.get(t)?.at(-1);if(r?.bytes)try{return Qn.decode(r.bytes)}catch{throw new Jn(`field ${t} is not valid UTF-8`)}}function eo(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 to(e,t){const r=e.get(t)?.at(-1);return void 0!==r?.varint&&0n!==r.varint}function ro(e,t){const r=e.get(t);return r?r.map(e=>{if(!e.bytes)throw new Jn(`field ${t} was expected to be length-delimited`);return e.bytes}):[]}function no(e,t){if(void 0===e||""===e)throw new Jn(`${t} is missing or empty`);return e}function oo(e){const t=Xn(e),r=eo(t,4),n=eo(t,5);if(void 0===r)throw new Jn("FieldDescriptorProto.label is missing");if(void 0===n)throw new Jn("FieldDescriptorProto.type is missing");return{name:no(Zn(t,1),"FieldDescriptorProto.name"),number:eo(t,3)??0,label:r,type:n,type_name:Zn(t,6),json_name:Zn(t,10),oneof_index:eo(t,9),proto3_optional:to(t,17)}}function so(e){const t=Xn(e);return{name:no(Zn(t,1),"EnumDescriptorProto.name"),value:ro(t,2).map(e=>{const t=Xn(e);return{name:no(Zn(t,1),"EnumValueDescriptorProto.name"),number:eo(t,2)??0}})}}function io(e,t=0){if(t>64)throw new Jn("message nesting too deep");const r=Xn(e),n=ro(r,7).at(-1);const o=n?Xn(n):void 0;return{name:no(Zn(r,1),"DescriptorProto.name"),field:ro(r,2).map(oo),nested_type:ro(r,3).map(e=>io(e,t+1)),enum_type:ro(r,4).map(so),oneof_decl:ro(r,8).map(e=>({name:no(Zn(Xn(e),1),"OneofDescriptorProto.name")})),options:{map_entry:!!o&&to(o,7)}}}function ao(e){const t=Xn(e);return{name:no(Zn(t,1),"ServiceDescriptorProto.name"),method:ro(t,2).map(e=>{const t=Xn(e);return{name:no(Zn(t,1),"MethodDescriptorProto.name"),input_type:no(Zn(t,2),"MethodDescriptorProto.input_type"),output_type:no(Zn(t,3),"MethodDescriptorProto.output_type"),client_streaming:to(t,5),server_streaming:to(t,6)}})}}function co(e){const t=Xn(e);return{name:Zn(t,1),package:Zn(t,2),syntax:Zn(t,12),dependency:ro(t,3).map(e=>function(e,t){try{return Qn.decode(e)}catch{throw new Jn(`${t} is not valid UTF-8`)}}(e,"FileDescriptorProto.dependency")),message_type:ro(t,4).map(e=>io(e)),enum_type:ro(t,5).map(so),service:ro(t,6).map(ao)}}function lo(e){const t=Xn(e),r=ro(t,1),n=[...t.keys()].filter(e=>1!==e);if(n.length>0)throw new Jn(`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(co)}var uo=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 ${po(t)} with keys [${o}]`+(n.length>24?` ...+${n.length-24} more`:"")+(r?`. ${r}`:"")),this.name="DescriptorShapeError",this.expected=e,this.observedKeys=n}};function po(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 fo(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 mo(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 ho(e,t,r,n){if(!mo(e,t,r))return[];const o=fo(e,t,r);if(void 0===o)return[];if(null===o||!Array.isArray(o))throw new uo(`${n}.${r} to be a repeated field`,e,`field "${r}" is ${po(o)}.`);return o}function yo(e,t,r,n){const o=fo(e,t,r);if("string"!=typeof o||0===o.length)throw new uo(`${n}.${r} to be a non-empty string`,e,`got ${po(o)}.`);return o}function go(e,t,r,n){const o=fo(e,t,r),s="string"==typeof o&&""!==o.trim()?Number(o):o;if("number"!=typeof s||!Number.isFinite(s))throw new uo(`${n}.${r} to be a number`,e,`got ${po(o)}.`);return s}function vo(e,t,r){const n=fo(e,t,r);return!0===n||1===n||"true"===n}var bo={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"},wo={1:"LABEL_OPTIONAL",2:"LABEL_REQUIRED",3:"LABEL_REPEATED"},$o=new Set(Object.values(bo)),So=new Set(Object.values(wo));function Eo(e,t,r,n,o){if("string"==typeof e){if(r.has(e))return e;throw new uo(`${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 uo(`${n}.${o} to be a known enum number`,e,`${e} has no mapping; the descriptor may use a newer protobuf revision.`)}throw new uo(`${n}.${o} to be present`,e,`got ${po(e)}.`)}function Ao(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 xo(e){To(e);return ho(e,"field","field","DescriptorProto").map((e,t)=>{const r=`FieldDescriptorProto[${t}]`,n=fo(e,"typeName","type_name"),o=fo(e,"jsonName","json_name"),s=fo(e,"oneofIndex","oneof_index"),i=Eo(fo(e,"type","type"),bo,$o,r,"type");if(("TYPE_MESSAGE"===i||"TYPE_ENUM"===i||"TYPE_GROUP"===i)&&"string"!=typeof n)throw new uo(`${r}.type_name to be present for ${i}`,e,`a ${i} field cannot be resolved without its type name.`);return{name:yo(e,"name","name",r),number:go(e,"number","number",r),type:i,label:Eo(fo(e,"label","label"),wo,So,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:vo(e,"proto3Optional","proto3_optional")}})}function To(e){var t;if(!(t=e)||"object"!=typeof t||!mo(t,"name","name")||mo(t,"method","method")||mo(t,"value","value")||Ao(t))throw new uo("a DescriptorProto (message descriptor)",e,Ao(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 ko(e){if(!e||"object"!=typeof e)return!1;return vo(fo(e,"options","options"),"mapEntry","map_entry")}function _o(e){if(!((t=e)&&"object"==typeof t&&mo(t,"name","name")&&mo(t,"value","value")))throw new uo("an EnumDescriptorProto",e,"the descriptor source did not produce enum descriptors.");var t;return ho(e,"value","value","EnumDescriptorProto").map((e,t)=>yo(e,"name","name",`EnumValueDescriptorProto[${t}]`))}function Oo(e){if(!((t=e)&&"object"==typeof t&&mo(t,"name","name")&&mo(t,"method","method")))throw new uo("a ServiceDescriptorProto",e,Ao(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 ho(e,"method","method","ServiceDescriptorProto").map((e,t)=>{const r=`MethodDescriptorProto[${t}]`;return{name:yo(e,"name","name",r),inputType:yo(e,"inputType","input_type",r),outputType:yo(e,"outputType","output_type",r),clientStreaming:vo(e,"clientStreaming","client_streaming"),serverStreaming:vo(e,"serverStreaming","server_streaming")}})}var Po={keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0};function Mo(e,t){return e?`${e}.${t}`:t}function Do(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 Co(e,t,r){const n=fo(e,t,r);return Array.isArray(n)?n:[]}function jo(e,t,r,n,o){e.notes.push(`duplicate definition of ${t} "${r}" (${n} and ${o}); the first one was kept.`)}function Io(e,t,r,n){const o=String(fo(n,"name","name")??"");if(!o)return void e.notes.push(`${t}: a message with no name was skipped.`);const s=Mo(r,o);if(ko(n))e.mapEntries.add(s);else{const r=e.symbols.get(s);r?jo(e,"message",s,r.file,t):e.symbols.set(s,{kind:"message",type:n,file:t})}for(const r of Co(n,"nestedType","nested_type"))Io(e,t,s,r);for(const r of Co(n,"enumType","enum_type"))No(e,t,s,r)}function No(e,t,r,n){const o=String(fo(n,"name","name")??"");if(!o)return void e.notes.push(`${t}: an enum with no name was skipped.`);const s=Mo(r,o),i=e.symbols.get(s);i?jo(e,"enum",s,i.file,t):e.symbols.set(s,{kind:"enum",type:n,file:t})}function Bo(e,t){const r=fo(t,"name","name"),n="string"==typeof r&&""!==r?r:`(unnamed #${++e.unnamedSeq})`,o=String(fo(t,"package","package")??"");for(const r of Co(t,"messageType","message_type"))Io(e,n,o,r);for(const r of Co(t,"enumType","enum_type"))No(e,n,o,r);for(const r of Co(t,"service","service")){const t=String(fo(r,"name","name")??"");if(!t){e.notes.push(`${n}: a service with no name was skipped.`);continue}const s=Mo(o,t),i=e.symbols.get(s);i?"service"===i.kind?jo(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 Ro(e){return null!==e&&"object"==typeof e&&"string"==typeof e.path}function qo(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 Lo(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 Xr(),{protoLoader:r}=t,n=[];let o,s,i,a;if(!0===e.reflection){Zr(t,"descriptorSetFromBuffer");const{credentials:c,mode:l,warnings:u}=tn(e,t);n.push(...u);const d=await Wn({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,Po);try{s=lo(d.descriptorSet)}catch(t){if(!(t instanceof Jn))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 gn({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=bn(c);l=e.includeDirs,n.push(...e.notes)}o=await r.load(c.files,{...Po,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(co(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)Bo(c,e);const{symbols:l,serviceDescriptors:u,mapEntries:d}=c,p=s.map(e=>{const t=fo(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&&qo(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 Co(s,"field","field")){const s=fo(o,"typeName","type_name");"string"==typeof s&&""!==s&&void 0===Do(t,e,s)&&n(s,r)}for(const t of Co(s,"nestedType","nested_type")){const n=String(fo(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 Co(o,"method","method"))for(const[o,s]of[["inputType","input_type"],["outputType","output_type"]]){const i=fo(e,o,s);"string"==typeof i&&""!==i&&void 0===Do(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(Ro)&&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 Fo(e,t){return e&&t?"bidi_streaming":e?"client_streaming":t?"server_streaming":"unary"}function Uo(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}(Do(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 zo(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 Vo(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Go(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 Lo(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(!zo(o))continue;const s=Vo(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 Oo(n)}catch(e){if(!(e instanceof uo))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 ${Fo(f.clientStreaming,f.serverStreaming)}, runtime says ${Fo(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?Uo(r,h,f.inputType,"request",o):void 0,g=f?Uo(r,h,f.outputType,"response",o):void 0;return{name:c.name,kind:Fo(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 Wo={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"};function Jo(e,t){return{code:e,codeName:Wo[e]??`CODE_${e}`,details:t}}function Yo(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 Ho=new Set(["max_messages","idle_timeout","max_session","aborted"]);function Ko(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 Xo(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),Ko("idleTimeoutMs",t.idleTimeoutMs),Ko("maxSessionMs",t.maxSessionMs),Ko("sendIntervalMs",t.sendIntervalMs),Ko("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 Xr(),{grpc:i}=s,a=r??await(async()=>{const t=await Lo(e);return{catalog:t.catalog,packageDefinition:t.packageDefinition,includeSourceNotes:!1}})(),c=await Go(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 $=tn(e,s);u.push(...$.warnings);const S=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,$.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,$=!1,x=!1,T=!1,k=!1;const _=e=>{if($)return;const r={...e,seq:b++,at:Date.now()};if(d.push(r),t.onEvent)try{t.onEvent(r)}catch{}},O=(e,t)=>{x||(x=!0,h=e,y=t)},P=e=>{T||w||(T=!0,m=e)},M=o=>{if(!$){o&&(w=!0,f=o,Ho.has(o)&&O(Jo(1,`call stopped by the client (${o}); the server never reported a status`),"synthesized")),k&&!x&&(O(Jo(0),"synthesized"),u.push("the response was received but the server's status did not arrive within 200ms; OK was inferred from the successful response and no trailing metadata is available.")),k=!1,$=!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=()=>{$||void 0!==t.idleTimeoutMs&&(clearTimeout(r),r=setTimeout(()=>M("idle_timeout"),t.idleTimeoutMs))},C=e=>{$||(p.push(e),_({direction:"inbound",payload:e}),D(),void 0!==t.maxMessages&&p.length>=t.maxMessages&&M("max_messages"))},j=()=>{$||x?M():(k=!0,clearTimeout(r),i=setTimeout(()=>M(),200))},I=e=>{const t=e,r=Jo(t.code??2,t.details??t.message),n=void 0===t.code?"client":"server";O(r,n),P(t.message??String(e)),_({direction:"status",status:r,statusOrigin:n}),M()},N=(e,t,r)=>{const n=Jo(e,t);O(n,"client"),P(r instanceof Error?r.message:String(r)),_({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(3,`request message #${t} does not match ${c.inputType??"the request type"}`,e),!1}},L=e=>{e.on("metadata",e=>{g=Yo(e),_({direction:"meta",metadata:g})}),e.on("status",e=>{const t=e;v=Yo(t.metadata);const r=Jo(t.code,t.details);O(r,"server"),_({direction:"status",status:r,statusOrigin:"server",metadata:v}),(c.responseStream||k)&&M()})},F=e=>{let r=0;const n=()=>{if($)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),_({direction:"outbound",payload:a}),D()}catch(e){return void N(2,`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;_({direction:"outbound",payload:e}),"unary"===c.kind?(a=E.makeUnaryRequest(c.path,B,R,e,S,A,(e,t)=>{e?I(e):(C(t),j())}),L(a),a.on("error",I)):(a=E.makeServerStreamRequest(c.path,B,R,e,S,A),L(a),a.on("data",e=>C(e)),a.on("error",I),a.on("end",()=>{O(Jo(0),"synthesized"),M()}))}else"client_streaming"===c.kind?(a=E.makeClientStreamRequest(c.path,B,R,S,A,(e,t)=>{e?I(e):(C(t),j())}),L(a),a.on("error",I),F(a)):(a=E.makeBidiStreamRequest(c.path,B,R,S,A),L(a),a.on("data",e=>C(e)),a.on("error",I),a.on("end",()=>{O(Jo(0),"synthesized"),M()}),F(a))}catch(e){return void N(2,"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 Qo=Symbol("omit"),Zo={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"},es={"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":[]},ts=new Set(["google.protobuf.Value","google.protobuf.Any"]);function rs(e){return e.startsWith(".")?e.slice(1):e}function ns(e,t){return e?`${e}.${t}`:t}var os=!0===Po.keepCase?"declared":"json";function ss(e){return"declared"===os?e.name:e.jsonName??e.name.replace(/_([a-z0-9])/g,(e,t)=>t.toUpperCase())}function is(e,t,r={}){const n={catalog:e,maxDepth:r.maxDepth??4,seedCollections:!1!==r.seedCollections,fillExplicitOptional:!0===r.fillExplicitOptional,fillMessageFields:!1!==r.fillMessageFields,keyOf:ss,oneofs:[],enums:[],collections:[],presence:[],warnings:[],stack:[],hintDepth:0},o=rs(t),s=us(n,"",t)??o;let i={};try{i=hs(n,s,"",0)??{}}catch(e){if(!(e instanceof uo))throw e;n.warnings.push(`template generation stopped: ${e.message}. The request must be composed by hand.`)}return{message:s,example:i,keyStyle:os,oneofs:n.oneofs,enums:n.enums,collections:n.collections,presence:n.presence,warnings:n.warnings}}function as(e){return 0===e.hintDepth}function cs(e,t){as(e)&&e.warnings.push(t)}function ls(e,t){e.hintDepth++;try{return t()}finally{e.hintDepth--}}function us(e,t,r){const n=Do(e.catalog,t,r);if(void 0!==n)return"message"===e.catalog.symbols.get(n)?.kind?n:void 0}function ds(e,t){const r=e.catalog.symbols.get(t);return"message"===r?.kind?r.type:void 0}function ps(e,t,r){return r.typeName?Do(e.catalog,t,r.typeName)??rs(r.typeName):r.type}function fs(e,t,r){const n=ds(e,t);if(!n)return;const o=rs(r),s=o.slice(o.lastIndexOf(".")+1);try{for(const e of(To(i=n),ho(i,"nestedType","nested_type","DescriptorProto"))){if(String(fo(e,"name","name")??"")!==s)continue;if(!ko(e))continue;const t=xo(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 uo))throw e;return}var i}function ms(e,t){return 1===t.length&&("LABEL_REPEATED"!==t[0].label&&(void 0===e||e===`_${t[0].name}`))}function hs(e,t,r,n){if(n>e.maxDepth)return cs(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 cs(e,`cyclic reference to ${t} at "${r}"; the value is an empty message, which on the wire means "set with all defaults".`),{};const o=ds(e,t);if(!o)return cs(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=xo(o),a=(To(s=o),ho(s,"oneofDecl","oneof_decl","DescriptorProto").map((e,t)=>yo(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)||ms(a[r],n))for(const e of n)d.add(e.name);else{const o=n.filter(e=>e.proto3Optional);if(o.length>0){cs(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=ns(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=ys(e,t,i,ns(r,i.name),n),d={};l!==Qo&&(d[e.keyOf(i)]=l),ls(e,()=>{for(const o of s.slice(1)){const s=ys(e,t,o,ns(r,o.name),n);s!==Qo&&(d[e.keyOf(o)]=s)}}),as(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!==Qo&&(c[e.keyOf(i)]=l);continue}if(o.proto3Optional||d.has(o.name)){const r=ls(e,()=>ys(e,t,o,i,n));as(e)&&e.presence.push({at:i,reason:"proto3_optional",presentInExample:e.fillExplicitOptional,valueIfSet:r===Qo?void 0:r}),e.fillExplicitOptional&&r!==Qo&&(c[s]=r);continue}const l=ys(e,t,o,i,n);l!==Qo&&(c[s]=l)}return c}finally{e.stack.pop()}var s}function ys(e,t,r,n,o){const s="LABEL_REPEATED"===r.label;if(s&&"TYPE_MESSAGE"===r.type&&r.typeName){const s=fs(e,t,r.typeName);if(s){if(as(e)&&e.collections.push({at:n,kind:"map",of:ps(e,t,s.valueField),keyOf:s.keyType}),!e.seedCollections)return{};const r="TYPE_STRING"===s.keyType?"key":"0",i=gs(e,t,s.valueField,`${n}.${r}`,o);return i===Qo?{}:{[r]:i}}cs(e,`"${n}" is a repeated ${rs(r.typeName)} that could not be read as a map entry; treating it as a repeated message field.`)}if(s){if(as(e)&&e.collections.push({at:n,kind:"repeated",of:ps(e,t,r)}),!e.seedCollections)return[];const s=gs(e,t,r,`${n}[0]`,o);return s===Qo?[]:[s]}return gs(e,t,r,n,o)}function gs(e,t,r,n,o){if("TYPE_ENUM"===r.type){const o=r.typeName,s=function(e,t,r){const n=Do(e.catalog,t,r);if(void 0!==n)return"enum"===e.catalog.symbols.get(n)?.kind?n:void 0}(e,t,o),i=s??rs(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=_o(t)}catch(t){if(!(t instanceof uo))throw t;cs(e,`enum "${i}" at "${n}" is unreadable: ${t.message}`)}}return 0===a.length?(cs(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.`),""):(as(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=rs(s),a=us(e,t,s),c=a??i;if("google.protobuf.Any"===c||"google.protobuf.Any"===i)return cs(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(ts.has(c)||ts.has(i))return cs(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 es)return es[c];if(i in es)return es[i];if(void 0===a)return cs(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.`),as(e)&&e.presence.push({at:n,reason:"message",presentInExample:e.fillMessageFields,valueIfSet:{}}),e.fillMessageFields?{}:Qo;const l=hs(e,a,n,o+1)??{};return as(e)&&e.presence.push({at:n,reason:"message",presentInExample:e.fillMessageFields,valueIfSet:l}),e.fillMessageFields?l:Qo}return r.type in Zo?Zo[r.type]:(cs(e,`unhandled field type ${r.type} at "${n}"; the example uses null, which will not serialise.`),null)}var vs=(e,t)=>e.name<t.name?-1:e.name>t.name?1:0;function bs(e,t){return e&&t?"bidi_streaming":e?"client_streaming":t?"server_streaming":"unary"}function ws(e){return e.startsWith(".")?e.slice(1):e}function $s(e){const t=e.lastIndexOf(".");return-1===t?"":e.slice(0,t)}function Ss(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function Es(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=Ss(o.path),i=r.get(s);i&&i.key===s||r.set(s,o)}return r}function As(e,t,r){const n=e.serviceDescriptors.get(t);if(void 0!==n)try{return Oo(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 xs(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=As(e,r,s),a=Es(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:bs(c.clientStreaming,c.serverStreaming),inputType:ws(c.inputType),outputType:ws(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=is(e,u.inputType,d)}catch(e){if(!(e instanceof uo))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=is(e,u.outputType,d)}catch(e){if(!(e instanceof uo))throw e;s.push(`response shape unavailable: ${e.message}`)}return{...u,service:r,request:p,response:f,notes:s}}function Ts(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=bs(i.clientStreaming,i.serverStreaming),o=bs(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:bs(i.clientStreaming,i.serverStreaming),inputType:ws(i.inputType),outputType:ws(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:bs(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(vs),{name:e,package:$s(e),methods:o,views:t&&r.size>0?"both":t?"descriptor_only":"runtime_only"}}(e,As(t,e,n),Es(r,e),n));return{address:e.address,source:t.source,services:o,files:t.files,notes:n}}async function ks(e){const{catalog:t,packageDefinition:r}=await Lo(e);return Ts(e,t,r)}function _s(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 Os(e){return Array.isArray(e)?[...e].filter(e=>"string"==typeof e).sort():[]}function Ps(e){return!0===e.reflection?JSON.stringify({kind:"reflection",address:e.address,version:e.reflectionVersion??null,host:e.reflectionHost??null,tls:_s(e.tls)}):JSON.stringify({kind:"proto",address:e.address,protoPaths:Os(e.protoPaths),includeDirs:Os(e.includeDirs),ignoreDirs:Os(e.ignoreDirs),followSymlinks:!0===e.followSymlinks,tls:_s(e.tls)})}function Ms(e){return"string"==typeof e&&e.length>0}function Ds(e){if(!e||"object"!=typeof e)return!1;const t=e;return!!Ms(t.address)&&(!0===t.reflection||Array.isArray(t.protoPaths)&&t.protoPaths.length>0&&t.protoPaths.every(Ms))}var Cs=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(!Ds(e))return!1;const t=e;return Ms(t.service)&&Ms(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(!Ds(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=Ps(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=Lo(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=Ps(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 Go(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.",...js(t)]);return{streaming:o.requestStream||o.responseStream,warnings:s,environment:{baseUrl:t.address},collection:Is(t,o)}}async run(e,t){const r=this.assertSupported(e),{catalog:n,packageDefinition:o}=await this.catalogFor(r);return Xo(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 Ts(t,r,n)}async describeMethod(e,t,r,n={}){const o=this.assertEndpoint(e);if(!Ms(t)||!Ms(r))throw new TypeError("describeMethod needs a non-empty service and method name.");const{catalog:s,packageDefinition:i}=await this.catalogFor(o);return xs(s,i,t,r,{includeResponse:!0,...n})}};function js(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 Is(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 Ns(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 Bs(e,t,r={}){const n=await ks(t);return{spec:Ns(e,n,t,r),discovery:n}}var Rs=class{name="grpc";adapter=new Cs;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 i("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 i("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 Xo(e.target,s))}};function qs(e={}){const t=new fe,r=e.adapters??[new Et,new Bt,new tr,new Br,new Rs];for(const n of[...r,...e.extraAdapters??[]])t.register(n);const n=e=>{if(!e||"object"!=typeof e)throw i("BAD_OPTIONS","send() requires an options object");if(!e.spec||"object"!=typeof e.spec)throw i("BAD_OPTIONS","send() requires options.spec");const r=D(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:a}=n(t),l=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(s.isProtoKitError(t))throw t;throw i("EXECUTION_FAILED",`Adapter "${e.name}" failed: ${c(t).message}`,t)}})(o,a,t),u=a,d=Array.isArray(u?.warnings)?[...u.warnings]:[];let p,f,m,h;try{p=ae(l,e.response)}catch(e){f=`response fragment error: ${c(e).message}`,p={response:{description:"Fragment generation failed"},statusCode:String(l.response.status||"default")},d.push(f)}if(f)h=f;else if(!1===t.writeBack)h="disabled by options.writeBack";else if(l.response.status<=0)h="no response was received";else if(l.scripts?.skipped)h="request was skipped by a script";else if(!1!==e.writeBack?.requirePassingTests&&!1===l.scripts?.passed)h="one or more assertions failed";else if(l.response.truncated&&!1===e.writeBackTruncated)h=`stream was truncated (${l.response.stopReason??"unknown limit"})`;else{l.response.truncated&&d.push(`Schema inferred from a truncated stream (${l.response.stopReason??"unknown limit"}); fields appearing later were not observed.`),l.response.droppedEvents&&d.push(`${l.response.droppedEvents} event(s) exceeded the size caps and were not fully retained.`);try{m=de(t.spec,r.path,r.method,p,e.writeBack)}catch(e){h=`write-back error: ${c(e).message}`}}return{...l,collection:u?.collection,environment:u?.environment,responseFragment:p.response,responseStatusCode:p.statusCode,patchedSpec:m,writeBackSkippedReason:h,...d.length?{writeBackWarnings:d}:{}}}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 i("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:c(t).message})}}return{spec:n,results:s}}}}import*as Ls from"@grpc/grpc-js";import*as Fs from"@grpc/proto-loader";function Us(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 zs(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?Ls.credentials.createSsl():Ls.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 Vs(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 Lo(t),o=Us(Ls.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 zs(o,e,"reflection")}async function Gs(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 gn({paths:t});if(!r.files.length)throw new Error("No .proto files were found under the given protoPaths.");const n=bn(r),o=await Fs.load(r.files,{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:n.includeDirs,...e.loaderOptions??{}}),s=Us(Ls.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 zs(s,e,"proto")}(e):Vs(e)}function Ws(e){const t=n("grpc","grpc",`grpc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,1e3),r=[];let o,s,i,a,c,l,u="idle",d=0,p=()=>{};const f=new Promise(e=>{p=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){u=e,t.setState(e)}function g(){"closed"!==u&&(y("closed"),p())}function v(){if(!i)throw new Error("gRPC session is not open");return i}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"),p()),m=null,h({direction:"status",event:"status",code:e.code,statusName:Ls.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?Ls.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),p(),m=null}),e.on("end",()=>{"server_streaming"!==o&&"bidi_streaming"!==o||g(),h({direction:"meta",event:"end",at:Date.now()})})}function w(){if(m)return m;const e=v(),t={};return c&&(t.deadline=c),"client_streaming"===e.kind?(m=e.client[e.methodName](a,t,(e,t)=>{if(e)return y("error"),h({direction:"status",event:"error",code:e?.code,statusName:"number"==typeof e?.code?Ls.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),p(),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](a,t),b(m),m.on("data",e=>{"closing"!==u&&"closed"!==u&&h({direction:"inbound",event:"data",payload:e,at:Date.now()})}),m):null}return{get protocol(){return"grpc"},get state(){return u},get kind(){return o},get source(){return s},get events(){return t.events},onEvent:e=>t.onEvent(e),get warnings(){return r},async open(){if(l)return l;if("idle"!==u&&"closed"!==u&&"error"!==u)throw new Error(`gRPC session cannot open from state "${u}"`);return y("connecting"),l=(async()=>{try{const t=await Gs(e);i=t,o=t.kind,s=t.source,a=function(e){const t=new Ls.Metadata;for(const[r,n]of Object.entries(e??{}))t.set(r,n);return t}(e.metadata),c=function(e){if(e&&!(e<=0))return new Date(Date.now()+e)}(e.deadlineMs),"client_streaming"!==o&&"bidi_streaming"!==o||w(),y("open"),h({direction:"meta",event:"open",payload:{address:e.address,service:e.service,method:t.methodName,requestedMethod:e.method,kind:o,descriptorSource:s},at:Date.now()})}catch(e){throw y("error"),p(),h({direction:"status",event:"error",error:e instanceof Error?e.message:String(e),at:Date.now()}),e}finally{l=void 0}})(),l},async send(e){if("open"!==u)throw new Error("gRPC session is not open");h({direction:"outbound",event:"data",payload:e,at:Date.now()});const t=v(),r={};if(c&&(r.deadline=c),"unary"===t.kind){if(d>0)throw new Error("Unary gRPC call only supports one send()");return d+=1,void await new Promise((n,o)=>{const s=t.client[t.methodName](e,a,r,(e,t)=>{if(e)return y("error"),h({direction:"status",event:"error",code:e?.code,statusName:"number"==typeof e?.code?Ls.status[e.code]:void 0,details:e?.details??e?.message,metadata:e?.metadata?.getMap?.()??void 0,error:e?.message??String(e),at:Date.now()}),p(),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(d>0)throw new Error("Server-streaming gRPC call only supports one send()");d+=1;const n=t.client[t.methodName](e,a,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):(d+=1,r())})})}throw new Error(`Unsupported gRPC method kind: ${t.kind}`)},async close(){"closed"!==u&&("open"===u||"error"===u||"closing"===u?(y("closing"),h({direction:"meta",event:"close",at:Date.now()}),"client_streaming"===o||"bidi_streaming"===o?m&&"function"==typeof m.end?m.end():g():m&&"function"==typeof m.cancel?m.cancel():g(),await f):g())},async waitForClose(){await f}}}function Js(e){if(!e||"object"!=typeof e)throw new Error("createManualSession requires an options object");switch(e.kind){case"websocket":return Nt(e);case"mcp":return jr(e);case"grpc":return Ws(e);default:throw new Error(`Unknown manual session kind: ${String(e.kind)}`)}}function Ys(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 Hs(e={}){const t=qs(e);return{prepare:function(e){if(!e||!e.spec)throw new Error("prepare() requires an options object with spec");const t=D(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 De(r)?"sse":"none"}(r,n,t);return{protocol:r,transport:n,target:e.target,operation:t,display:{mode:Ys(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 Js(e)},discover:async function(e){const t=String(e?.protocol??"").toLowerCase();if("mcp"===t)return mr(e);if("grpc"===t)return ks(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=D(t,r.target),i=ae(n,e.response);return de(t,s.path,s.method,i,{...e.writeBack,...o})},dispose:function(){},probeStreamingResponse:Ne}}export{fe as AdapterRegistry,Le as BUILTIN_CAPTURE_TEST,Jn as DescriptorDecodeError,tr as GraphQLAdapter,Cs as GrpcAdapter,Jr as GrpcDependencyBrokenError,Wr as GrpcDependencyMissingError,Rs as GrpcProtocolAdapter,Et as HttpAdapter,zt as INTROSPECTION_QUERY,Po as LOADER_OPTIONS,lr as MCP_PROTOCOL_VERSION,Br as McpAdapter,s as ProtoKitError,Dn as ReflectionProtocolError,Pn as ReflectionUnavailableError,lt as SseParser,t as UnifiedSession,Bt as WebSocketAdapter,Ie as acceptHeaderFor,Lo as buildCatalog,rn as buildCredentials,nn as buildCredentialsAsync,tn as buildCredentialsChecked,on as buildCredentialsCheckedAsync,is as buildMessageTemplate,Hs as createClient,qs as createDebugger,n as createEventHub,Ws as createGrpcManualSession,kr as createHttpMcpTransport,Js as createManualSession,jr as createMcpManualSession,Ir as createMcpStdioSession,_r as createStdioMcpTransport,Nt as createWsManualSession,co as decodeFileDescriptorProto,lo as decodeFileDescriptorSet,bn as deriveIncludeDirsDetailed,er as discoverAndWriteGraphQLSchema,Bs as discoverAndWriteGrpcOperations,Tr as discoverAndWriteMcpCapabilities,ks as discoverGrpc,mr as discoverMcpCapabilities,Gn as fetchDescriptorSet,Wn as fetchFullDescriptorSet,Sr as generateAllMcpCalls,Kt as generateAllOperations,$r as generateMcpCall,Ht as generateOperation,Xo as grpcCall,ks as grpcDiscover,Ws as grpcManualSession,ee as inferSchema,te as inferSchemaFromMany,pr as initializeMcpSession,Vt as introspectSchema,Qr as isGrpcAvailable,Ce as isSseContentType,je as isStreamingContentType,De as isStreamingOperation,zn as listServices,Un as listServicesDetailed,Xr as loadGrpc,D as locateOperation,jr as mcpManualSession,U as mergeSchema,Ne as probeStreamingResponse,Zr as requireCapability,Rt as resolveGraphQLConfig,nr as resolveMcpConfig,Go as resolveMethod,Ft as runGraphQL,Nr as runMcpManualSession,Nt as runWebSocketSession,ye as sampleFromSchema,gn as scanProtoFiles,Fn as serializeDescriptorSet,e as toCloneable,ae as toResponseObject,de as writeBackResponse,Zt as writeGraphQLOperations,Ns as writeGrpcOperations,xr as writeMcpOperations,Nt as wsManualSession};
|