@powerduck/request 0.1.0
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/dist/index.cjs +1 -0
- package/dist/index.d.cts +124 -0
- package/dist/index.d.ts +124 -0
- package/dist/index.js +1 -0
- package/dist/protocol-58EyJAsY.d.cts +372 -0
- package/dist/protocol-58EyJAsY.d.ts +372 -0
- package/dist/protocols/http/index.cjs +1 -0
- package/dist/protocols/http/index.d.cts +86 -0
- package/dist/protocols/http/index.d.ts +86 -0
- package/dist/protocols/http/index.js +1 -0
- package/dist/protocols/ws/index.cjs +1 -0
- package/dist/protocols/ws/index.d.cts +53 -0
- package/dist/protocols/ws/index.d.ts +53 -0
- package/dist/protocols/ws/index.js +1 -0
- package/package.json +83 -0
- package/readme.md +463 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e,t=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,i=(e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of o(t))a.call(e,c)||c===s||r(e,c,{get:()=>t[c],enumerable:!(i=n(t,c))||i.enumerable});return e},c=(e,n,o)=>(o=null!=e?t(s(e)):{},i(!n&&e&&e.__esModule?o:r(o,"default",{value:e,enumerable:!0}),e)),u={};((e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})})(u,{AdapterRegistry:()=>d,BUILTIN_CAPTURE_TEST:()=>$,HttpAdapter:()=>oe,ProtoKitError:()=>l,WebSocketAdapter:()=>pe,createDebugger:()=>Te,inferSchema:()=>we,inferSchemaFromMany:()=>Se,locateOperation:()=>ne,mergeSchema:()=>me,sampleFromSchema:()=>m,toResponseObject:()=>Ae,writeBackResponse:()=>$e}),module.exports=(e=u,i(r({},"__esModule",{value:!0}),e));var l=class e extends Error{code;details;constructor(t,r,n){super(t),this.name="ProtoKitError",this.code=r,this.details=n,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function p(e,t,r){return new l(t,e,r)}function f(e){if(e instanceof l)return{message:e.message,code:e.code,name:e.name};if(e instanceof Error)return{message:e.message,code:e.code,name:e.name};if("string"==typeof e)return{message:e};try{return{message:JSON.stringify(e)}}catch{return{message:String(e)}}}var d=class{adapters=[];register(e){if(!e||"function"!=typeof e.supports)throw p("BAD_ADAPTER","Adapter must implement the ProtocolAdapter interface");const t=this.adapters.findIndex(t=>t.name===e.name);return t>=0&&this.adapters.splice(t,1),this.adapters.push(e),this}list(){return this.adapters.map(e=>e.name)}resolve(e){const t=this.adapters.map(t=>{let r=0;try{r=t.supports(e)||0}catch{r=0}return{adapter:t,score:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score);if(!t.length)throw p("NO_ADAPTER",`No protocol adapter matched operation "${e.located.method.toUpperCase()} ${e.located.path}"`);return t[0].adapter}};function m(e,t=0){if(!e||"object"!=typeof e||t>12)return null;if(void 0!==e.example)return e.example;if(void 0!==e.examples){if(Array.isArray(e.examples)&&e.examples.length)return e.examples[0];if("object"==typeof e.examples){const t=Object.values(e.examples)[0];if(void 0!==t)return t&&"object"==typeof t&&"value"in t?t.value:t}}if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length)return e.allOf.reduce((e,r)=>{const n=m(r,t+1);return n&&"object"==typeof n&&!Array.isArray(n)?{...e,...n}:null!=n?n:e},{});for(const r of["oneOf","anyOf"])if(Array.isArray(e[r])&&e[r].length)return m(e[r][0],t+1);switch((Array.isArray(e.type)?e.type.find(e=>"null"!==e)??"null":e.type)??(e.properties?"object":e.items?"array":(e.format,"string"))){case"object":{const r={},n=Array.isArray(e.required)?e.required:[],o=e.properties&&"object"==typeof e.properties?e.properties:{};for(const[e,s]of Object.entries(o))s&&!0===s.readOnly||t>2&&n.length&&!n.includes(e)||(r[e]=m(s,t+1));return!Object.keys(r).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(r.key=m(e.additionalProperties,t+1)),r}case"array":{const r=Math.max(1,Math.min(Number(e.minItems)||1,2));return Array.from({length:r},()=>m(e.items,t+1))}case"integer":return y(e,Math.trunc(e.minimum??0));case"number":return y(e,e.minimum??0);case"boolean":return!1;case"null":return null;default:return function(e){switch(e.format){case"date-time":return(new Date).toISOString();case"date":return(new Date).toISOString().slice(0,10);case"time":return(new Date).toISOString().slice(11,19);case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":return"user@example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"uri-reference":return"https://example.com";case"byte":case"binary":return"";case"password":return"password";default:{if("string"==typeof e.pattern)return"";const t=Number(e.minLength)||0,r="string";return t>r.length?r.padEnd(t,"x"):r}}}(e)}}function y(e,t){let r=t;return"number"==typeof e.minimum&&r<e.minimum&&(r=e.minimum),"number"==typeof e.maximum&&r>e.maximum&&(r=e.maximum),r}var h=/(token|secret|password|passwd|apikey|api_key|credential|private)/i;function g(e,t){if(t.serverUrl)return b(t.serverUrl);const r=Array.isArray(e)&&e.length?e[0]:{url:"/"};let n="string"==typeof r?.url&&r.url?r.url:"/";const o=r?.variables&&"object"==typeof r.variables?r.variables:{};for(const[e,r]of Object.entries(o)){const o=t.serverVariables?.[e],s=r?.default??(Array.isArray(r?.enum)&&r.enum.length?r.enum[0]:""),a=void 0!==o?o:s;n=n.split(`{${e}}`).join(String(a??""))}return n=n.replace(/\{[^}]*\}/g,""),b(n)}function b(e){return e.replace(/\/+$/,"")||e}function v(e,t,r={}){const n=[{key:"baseUrl",value:t,type:"default",enabled:!0},...Object.entries(r??{}).filter(([e])=>"baseUrl"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:h.test(e)?"secret":"default",enabled:!0}))];return{id:`protokit-env-${Date.now().toString(36)}`,name:e,values:n,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}var w=["text/event-stream","application/json-seq","application/x-ndjson","application/ndjson","application/jsonl"];function S(e,t){const r=Object.entries(t?.header??{}).find(([e])=>"accept"===e.toLowerCase())?.[1];if("string"==typeof r&&r.toLowerCase().includes("text/event-stream"))return!0;const n=e?.responses;if(!n||"object"!=typeof n)return!1;for(const e of Object.values(n)){const t=e?.content;if(t&&"object"==typeof t)for(const[e,r]of Object.entries(t)){const t=e.toLowerCase();if(t.startsWith("text/event-stream"))return!0;if(r&&"object"==typeof r.itemSchema&&w.some(e=>t.startsWith(e)))return!0}}return!1}function j(e){return!!e&&/text\/event-stream/i.test(e)}function x(e){if(!e)return!1;const t=e.toLowerCase();return w.some(e=>t.includes(e))}function A(e){if(!e)return[];return(Array.isArray(e)?e:[e]).filter(e=>!!e&&null!=e.exec)}function O(e,t){return t.map((t,r)=>{return{listen:e,script:{id:t.id??`protokit-${e}-${r}`,type:"text/javascript",exec:(n=t.exec,Array.isArray(n)?n.map(e=>String(e)):String(n).split(/\r?\n/))}};var n}).filter(e=>e.script.exec.some(e=>e.trim().length>0))}function k(e){const t=e?.["x-postman-scripts"];if(!t||"object"!=typeof t)return{pre:[],test:[]};const r=e=>null==e?[]:"string"==typeof e?[{exec:e}]:Array.isArray(e)?e.length?"string"==typeof e[0]?[{exec:e}]:e.filter(e=>e&&null!=e.exec):[]:"object"==typeof e&&null!=e.exec?[e]:[];return{pre:r(t.preRequest??t.prerequest??t.collectionPreRequest),test:r(t.test??t.tests??t.collectionTest)}}var $={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)) {"," pm.environment.set('__lastBody', pm.response.text());"," }","} catch (error) {"," console.warn('protokit capture failed: ' + error.message);","}"]},T=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"]);function C(e,t){const r=e.name,n=e.style??"form",o=e.explode??"form"===n;if(Array.isArray(t)){if(o)return t.map(e=>({key:r,value:P(e)}));const e="spaceDelimited"===n?" ":"pipeDelimited"===n?"|":",";return[{key:r,value:t.map(P).join(e)}]}if(t&&"object"==typeof t){const e=Object.entries(t);return"deepObject"===n?e.map(([e,t])=>({key:`${r}[${e}]`,value:P(t)})):o?e.map(([e,t])=>({key:e,value:P(t)})):[{key:r,value:e.flatMap(([e,t])=>[e,P(t)]).join(",")}]}return[{key:r,value:P(t)}]}function P(e){if(null==e)return"";if("object"==typeof e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function E(e,t,r){const n=r.values??{},o=g(e.servers,r),s=function(e,t){if(t?.contentType)return t.contentType;const r=e?.requestBody?.content;if(!r||"object"!=typeof r)return;const n=Object.keys(r);return n.length?n.find(e=>e.includes("json"))??n[0]:void 0}(e.operation,n),a=[];for(const t of e.parameters.filter(e=>"path"===e.in)){const e=n.path?.[t.name],r=void 0!==e?e:m(t.schema??{});a.push({key:t.name,value:P(r)})}const i=e.path.replace(/^\//,"").split("/").filter(e=>e.length>0).map(e=>e.replace(/\{([^}]+)\}/g,(e,t)=>`:${t}`)),c=[],u=new Set;for(const t of e.parameters.filter(e=>"query"===e.in)){u.add(t.name);const e=null!=n.query&&Object.prototype.hasOwnProperty.call(n.query,t.name)?n.query[t.name]:t.required?m(t.schema??{}):void 0;null!=e?c.push(...C(t,e)):t.required||c.push({key:t.name,value:"",disabled:!0})}for(const[e,t]of Object.entries(n.query??{}))u.has(e)||null==t||c.push({key:e,value:P(t)});const l=[],p=new Set,f=(e,t)=>{const r=e.toLowerCase();p.has(r)||(p.add(r),l.push({key:e,value:t}))};for(const[e,t]of Object.entries(n.header??{}))null!=t&&f(e,P(t));for(const t of e.parameters.filter(e=>"header"===e.in)){if(/^(accept|content-type|authorization)$/i.test(t.name))continue;const e=t.required?m(t.schema??{}):void 0;null!=e&&""!==e&&f(t.name,P(e))}s&&f("Content-Type",s);const d=function(e){const t=new Set,r=e?.responses;if(!r||"object"!=typeof r)return;for(const e of Object.values(r))for(const r of Object.keys(e?.content??{}))"*/*"!==r&&t.add(r);if(!t.size)return;const n=Array.from(t);return n.sort((e,t)=>Number(t.toLowerCase().startsWith("text/event-stream"))-Number(e.toLowerCase().startsWith("text/event-stream"))),n.slice(0,8).join(", ")}(e.operation);d&&f("Accept",d);const y=e.parameters.filter(e=>"cookie"===e.in),h=[];for(const e of y){const t=n.cookie?.[e.name],r=void 0!==t?t:e.required?m(e.schema??{}):void 0;null!=r&&h.push(`${e.name}=${encodeURIComponent(P(r))}`)}for(const[e,t]of Object.entries(n.cookie??{}))y.some(t=>t.name===e)||null==t||h.push(`${e}=${encodeURIComponent(P(t))}`);let b;h.length&&f("Cookie",h.join("; "));const v=e.operation.requestBody;if(v&&s){const e=v.content?.[s]?.schema,t=void 0!==n.body?n.body:m(e??{});b=s.includes("json")?{mode:"raw",raw:"string"==typeof t?t:JSON.stringify(t??{},null,2),options:{raw:{language:"json"}}}:s.includes("x-www-form-urlencoded")?{mode:"urlencoded",urlencoded:q(t).map(([e,t])=>({key:e,value:P(t),type:"text"}))}:s.includes("multipart/form-data")?{mode:"formdata",formdata:q(t).map(([e,t])=>t&&"object"==typeof t&&"__file"in t?{key:e,type:"file",src:String(t.__file)}:{key:e,type:"text",value:P(t)})}:s.includes("xml")||s.startsWith("text/")?{mode:"raw",raw:"string"==typeof t?t:P(t)}:{mode:"raw",raw:P(t)}}const w=c.filter(e=>!e.disabled);let S=`{{baseUrl}}/${i.join("/")}`;const j=[w.map(e=>`${encodeURIComponent(e.key)}=${encodeURIComponent(e.value)}`).join("&"),n.querystring?String(n.querystring).replace(/^\?/,""):""].filter(Boolean).join("&");j&&(S+=`?${j}`);const x={raw:S,host:["{{baseUrl}}"],path:i};c.length&&(x.query=c),a.length&&(x.variable=a);const $=e.method.toUpperCase(),E={method:$,header:l,url:x,description:e.operation.description??e.operation.summary};b&&(E.body=b);const D=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:k(e);return[...O("prerequest",[...r.pre,...A(t?.preRequest)]),...O("test",[...r.test,...A(t?.test)])]}(e.operation,r.scripts),_=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:k(e);return[...O("prerequest",[...r.pre,...A(t?.collectionPreRequest)]),...O("test",[...r.test,...A(t?.collectionTest)])]}(t,r.scripts),N=function(e){if(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:e.in??"header",type:"string"}]};default:return}}(r.auth),I={info:{_postman_id:`protokit-${Date.now().toString(36)}`,name:t?.info?.title??"OpenAPI Debug Session",description:t?.info?.description,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[{name:e.operation.operationId??`${$} ${e.path}`,...D.length?{event:D}:{},request:E,response:[]}],variable:[{key:"baseUrl",value:o}]};return N&&(I.auth=N),_.length&&(I.event=_),{collection:I,baseUrl:o,contentType:s,isCustomMethod:!T.has($)}}function q(e){return!e||"object"!=typeof e||Array.isArray(e)?[]:Object.entries(e)}var D=c(require("postman-runtime"),1),_=c(require("postman-collection"),1);function N(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return I(e)}function I(e){const t=new WeakSet;return JSON.parse(JSON.stringify(e,(e,r)=>{if(r&&"object"==typeof r){if(t.has(r))return;t.add(r)}return r}))}function M(e,t){const r=null==e?"":String(e);return-1===r.indexOf("{{")?r:r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t,r)?t[r]:e)}function U(e,t){if(!t)return e;const r={...e};for(const[e,n]of Object.entries(t)){if(void 0===n)continue;const t=r[e];B(t)&&B(n)?r[e]=U(t,n):r[e]=n}return r}function B(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function R(){let e,t,r=!1;return{promise:new Promise((r,n)=>{e=r,t=n}),get settled(){return r},resolve(t){r||(r=!0,e(t))},reject(e){r||(r=!0,t(e))}}}function L(e){if(e)try{clearTimeout(e)}catch{}return null}var z=new Set(["[DONE]","DONE"]),F=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;sequence=0;push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{const t=e instanceof Uint8Array?e:new Uint8Array(e);this.buffer+=this.decoder.decode(t,{stream:!0})}0===this.sequence&&65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1));const t=[],r=/\r\n\r\n|\n\n|\r\r/;for(;;){const e=r.exec(this.buffer);if(!e)break;const n=this.buffer.slice(0,e.index);this.buffer=this.buffer.slice(e.index+e[0].length);const o=this.parseBlock(n);o&&t.push(o)}return t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.buffer;if(this.buffer="",!e.trim())return[];const t=this.parseBlock(e);return t?[t]:[]}reset(){this.buffer="",this.lastEventId=void 0,this.sequence=0}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],n={data:"",receivedAt:Date.now(),direction:"in"};let o=!1;for(const e of t){if(""===e)continue;if(e.startsWith(":"))continue;const t=e.indexOf(":"),s=-1===t?e:e.slice(0,t);let a=-1===t?"":e.slice(t+1);switch(a.startsWith(" ")&&(a=a.slice(1)),s){case"data":r.push(a),o=!0;break;case"event":n.event=a,o=!0;break;case"id":a.includes("\0")||(n.id=a,this.lastEventId=a),o=!0;break;case"retry":{const e=Number(a);Number.isInteger(e)&&e>=0&&(n.retry=e),o=!0;break}}}if(!o)return null;n.data=r.join("\n"),void 0===n.id&&void 0!==this.lastEventId&&(n.id=this.lastEventId);const s=n.data.trim();if(s&&!z.has(s))try{n.parsed=JSON.parse(n.data)}catch{}return this.sequence+=1,n}},W=c(require("postman-collection"),1);function H(e,t=[]){const r=[...t,...Object.entries(e??{}).map(([e,t])=>({key:e,value:null==t?"":String(t)}))],n=new Map;for(const e of r)n.set(e.key,e);return new W.default.VariableScope({values:Array.from(n.values())})}function J(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 V(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)e&&!1!==e.enabled&&null!=e.key&&(n[String(e.key)]=null==e.value?"":String(e.value));return n}catch{return}}function G(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 I(t)}catch{return}}function K(e,t){const r=R(),n=Date.now();let o,s=e.streamingHint,a=!1,i=!1;const c=new F,u=[],l=[];let d=0;const m={prerequest:[],test:[],assertions:[],console:[],passed:!0,skipped:!1},y=[];let h=null,g=null,b=null,v=null;const w=t.maxEvents??100,S=t.maxStreamMs??3e4,A=t.runner?.timeout?.request??t.timeout??3e4,O=e=>{if(!a){a=!0,i=!0,m.console.push({level:"debug",messages:[`[protokit] stream sampling stopped: ${e}`],at:Date.now()});try{g?.abort?.()}catch{}}},k=(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:V(e?.result?.environment),globals:V(e?.result?.globals),return:e?.result?.return}),$=()=>{if(b=L(b),v=L(v),s)for(const e of c.flush())u.length<w&&(u.push(e),X(()=>t.onEvent?.(e)));if(h)s&&(h.response.events=u,i&&(h.response.truncated=!0));else{const e=Date.now();h={protocol:s?"sse":"http",request:{method:"",url:"",headers:{}},response:{status:a&&u.length?200:0,statusText:a?"Stream sampling stopped":"No response received",headers:{},contentType:s?"text/event-stream":void 0,...s?{events:u}:{},timings:{startedAt:n,endedAt:e,durationMs:e-n,firstByteMs:o?o-n:void 0},sizeBytes:d,...i?{truncated:!0}:{}},...a&&u.length?{}:{error:{message:"Runner finished without a response"}}}}h.scripts=m,r.resolve(h)};let T,C,P;v=setTimeout(()=>{if(!r.settled){m.console.push({level:"error",messages:["[protokit] hard timeout reached, forcing completion"],at:Date.now()});try{g?.abort?.()}catch{}i=!0,$()}},A+S+3e4),"object"==typeof v&&"function"==typeof v.unref&&v.unref();try{T=new _.default.Collection(I(e.collectionJson))}catch(e){return v=L(v),Promise.reject(p("BAD_COLLECTION",`Failed to construct collection: ${f(e).message}`,e))}try{C=function(e,t){const r=e.runner?.timeout?.request??e.timeout??3e4,n=U({iterationCount:1,stopOnError:!1,abortOnError:!1,stopOnFailure:!1,abortOnFailure:!1,timeout:{request:r,script:15e3,global:r+(t.streaming?e.maxStreamMs??3e4:0)+15e3},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}},{}),o=U(n,e.runner??{});return o.environment||(o.environment=H(e.variables,[{key:"baseUrl",value:t.baseUrl}])),!o.globals&&e.globals&&(o.globals=H(e.globals)),!o.localVariables&&e.localVariables&&(o.localVariables=H(e.localVariables)),Array.isArray(o.data)&&o.data.length&&void 0===e.runner?.iterationCount&&(o.iterationCount=o.data.length),o}(t,{baseUrl:e.baseUrl,streaming:e.streamingHint})}catch(e){return v=L(v),Promise.reject(p("BAD_RUN_OPTIONS",`Failed to build runtime options: ${f(e).message}`,e))}try{P=new D.default.Runner}catch(e){return v=L(v),Promise.reject(p("RUNTIME_INIT",`Failed to create runner: ${f(e).message}`,e))}return P.run(T,C,(e,A)=>{if(e)return v=L(v),void r.reject(p("RUNTIME_INIT",e.message??"Runner initialization failed",e));g=A,A.start({console(e,r,...n){const o={level:"string"==typeof r?r:"log",messages:n,at:Date.now()};m.console.push(o),X(()=>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||(m.passed=!1),m.assertions.push(r),X(()=>t.onAssertion?.(r))}},prerequest(e,t,r){for(const e of r??[])m.prerequest.push(k(e,"prerequest"))},test(e,t,r){for(const e of r??[])m.test.push(k(e,"test"))},item(e,t,r,n,o){o?.isSkipped&&(m.skipped=!0)},responseStart(e,r,n){o=Date.now();const a=Y(n,"content-type");(j(a)||x(a))&&(s=!0),X(()=>t.onResponseStart?.({status:n?.code??0,headers:J(n?.headers),contentType:a})),s&&!b&&(b=setTimeout(()=>O("maxStreamMs reached"),S),"object"==typeof b&&"function"==typeof b.unref&&b.unref())},responseData(e,r){if(a||null==r)return;let n;try{n=Buffer.isBuffer(r)?r:Buffer.from(r)}catch{return}if(d+=n.length,s)for(const e of c.push(n)){if(u.length>=w)return void O("maxEvents reached");if(u.push(e),X(()=>t.onEvent?.(e)),u.length>=w)return void O("maxEvents reached")}else l.push(n)},request(e,t,r,a,c,p){const m=Date.now(),g={method:a?.method??"",url:Q(a),headers:J(a?.headers),body:G(a)};if(e)return void(h={protocol:s?"sse":"http",request:g,response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:n,endedAt:m,durationMs:m-n},sizeBytes:d},error:f(e),replays:y});const b=Y(r,"content-type");let v,w;if((j(b)||x(b))&&(s=!0),!s){const e=l.length?Buffer.concat(l):r?.stream?Buffer.from(r.stream):Buffer.alloc(0);v=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"),w=function(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}}(v,b)}h={protocol:s?"sse":"http",request:g,response:{status:"number"==typeof r?.code?r.code:0,statusText:Z(r),headers:J(r?.headers),contentType:b,...s?{events:u}:{body:w,text:v},timings:{startedAt:n,endedAt:m,durationMs:"number"==typeof r?.responseTime?r.responseTime:m-n,firstByteMs:o?o-n:void 0},sizeBytes:d||r?.responseSize||0,...i?{truncated:!0}:{}},cookies:Array.isArray(p)?p.map(e=>({name:String(e?.name??""),value:String(e?.value??""),domain:e?.domain,path:e?.path})):[],replays:y}},io(e,t,r,n,o){"http"===r?.type&&r.source&&"collection"!==r.source&&y.push({url:Q(o),method:o?.method??"",status:"number"==typeof n?.code?n.code:0,reason:String(r.source)})},exception(e,t){m.console.push({level:"error",messages:[`[exception] ${f(t).message}`],at:Date.now()})},done(e){if(e&&!h&&!a)return b=L(b),v=L(v),void r.reject(p("RUNTIME_RUN",e.message??"Run failed",e));$()}})}),r.promise}function X(e){try{e()}catch{}}function Y(e,t){try{const r=e?.headers?.get?.(t);return null==r?void 0:String(r)}catch{return}}function Z(e){try{return String("function"==typeof e?.reason?e.reason()??"":e?.status??"")}catch{return""}}function Q(e){try{return"function"==typeof e?.url?.toString?e.url.toString():""}catch{return""}}var ee="__protokit_cycle__";function te(e){const t=new Map;function r(t){if("string"!=typeof t||!t.startsWith("#/"))throw p("EXTERNAL_REF",`Only local $ref pointers are supported, got: ${t}`);let r=e;const n=t.slice(2).split("/");for(const e of n){if(null==r||"object"!=typeof r)throw p("BAD_REF",`Cannot resolve pointer "${t}"`);r=r[decodeURIComponent(e).replace(/~1/g,"/").replace(/~0/g,"~")]}if(void 0===r)throw p("BAD_REF",`Pointer "${t}" resolves to undefined`);return r}function n(e){let t=e;const n=new Set;let o=0;for(;t&&"object"==typeof t&&"string"==typeof t.$ref;){if(n.has(t.$ref)||++o>100)return{type:"object",[ee]:!0};n.add(t.$ref),t=r(t.$ref)}return t}function o(e,t=0,r=new Set){if(null==e||"object"!=typeof e)return e;if(t>32)return{type:"object"};const s=n(e);if(null==s||"object"!=typeof s)return s;if(s[ee])return{type:"object"};if(r.has(s))return{type:"object"};const a=new Set(r);if(a.add(s),Array.isArray(s))return s.map(e=>o(e,t+1,a));const i={};for(const[e,r]of Object.entries(s))e!==ee&&(i[e]=o(r,t+1,a));return i}return{deref:n,deepDeref:function(e){const r=e&&"object"==typeof e?e.$ref:void 0;if("string"==typeof r&&t.has(r))return t.get(r);const n=o(e);return"string"==typeof r&&t.set(r,n),n},byPointer:r}}var re=["get","put","post","delete","options","head","patch","trace","query"];function ne(e,t){if(!e||"object"!=typeof e)throw p("BAD_SPEC","spec must be an object");if("string"!=typeof e.openapi)throw p("BAD_SPEC","spec.openapi version string is required");if(!t||"object"!=typeof t)throw p("BAD_TARGET","target is required");const r=te(e),n=e.paths;if(!n||"object"!=typeof n)throw p("BAD_SPEC","spec.paths is missing or invalid");const o=[];for(const[e,t]of Object.entries(n)){let n;try{n=r.deref(t)}catch{continue}if(!n||"object"!=typeof n)continue;for(const t of re)n[t]&&"object"==typeof n[t]&&o.push({path:e,method:t,rawOperation:n[t],pathItem:n,isCustomMethod:!1});const s=n.additionalOperations;if(s&&"object"==typeof s)for(const[t,r]of Object.entries(s))r&&"object"==typeof r&&o.push({path:e,method:t.toLowerCase(),rawOperation:r,pathItem:n,isCustomMethod:!0})}if(!o.length)throw p("EMPTY_SPEC","The document does not declare any operation");let s;if(t.operationId){if(s=o.find(e=>{try{return r.deref(e.rawOperation)?.operationId===t.operationId}catch{return!1}}),!s)throw p("OP_NOT_FOUND",`operationId "${t.operationId}" was not found`)}else{if(!t.path||!t.method)throw p("BAD_TARGET","Provide either operationId, or both path and method");const e=String(t.method).toLowerCase();if(s=o.find(r=>r.path===t.path&&r.method===e),!s)throw p("OP_NOT_FOUND",`Operation "${String(t.method).toUpperCase()} ${t.path}" was not found`)}const a=r.deepDeref(s.rawOperation)??{},i=r.deref(s.pathItem)??{},c=new Map,u=e=>{if(Array.isArray(e))for(const t of e){let e;try{e=r.deepDeref(t)}catch{continue}e&&"string"==typeof e.name&&"string"==typeof e.in&&c.set(`${e.in}:${e.name}`,e)}};u(i.parameters),u(s.rawOperation.parameters);const l=Array.isArray(a.servers)&&a.servers.length&&a.servers||Array.isArray(i.servers)&&i.servers.length&&i.servers||Array.isArray(e.servers)&&e.servers.length&&e.servers||[{url:"/"}];return{path:s.path,method:s.method,isCustomMethod:s.isCustomMethod,operation:a,pathItem:i,parameters:Array.from(c.values()),servers:l,security:a.security??e.security}}var oe=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=E(e.located,e.spec,e.options);return{...t,environment:v(`${e.spec?.info?.title??"API"} Environment`,t.baseUrl,e.options.variables),streaming:S(e.located.operation,e.options.values)}}execute(e,t){return K({collectionJson:e.collection,baseUrl:e.baseUrl,streamingHint:e.streaming},t)}};function se(e,t,r){const n=r.websocket??{},o=e.operation?.["x-websocket"]??{},s={...r.variables??{}};let a;if(n.url)a=n.url;else if("string"==typeof o.url&&o.url)a=o.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(/^\/+/,"")}`}(g(e.servers,r)),n=e.path.replace(/\{([^}]+)\}/g,(e,t)=>{const n=r.values?.path?.[t];return null==n?e:encodeURIComponent(String(n))});a=`${t.replace(/\/+$/,"")}/${n.replace(/^\//,"")}`}a=M(a,{baseUrl:"",...s});try{const e=new URL(a);for(const[t,n]of Object.entries(r.values?.query??{}))null!=n&&e.searchParams.set(t,String(n));"apikey"===r.auth?.type&&"query"===r.auth.in&&e.searchParams.set(r.auth.key??"api_key",r.auth.value??""),a=e.toString()}catch{throw p("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${a}`)}const i={};for(const[e,t]of Object.entries(r.values?.header??{}))null!=t&&(i[e]=String(t));for(const[e,t]of Object.entries(o.headers??{}))null!=t&&(i[e]=M(String(t),s));for(const[e,t]of Object.entries(n.headers??{}))null!=t&&(i[e]=M(String(t),s));const c=r.auth;if(c&&"none"!==c.type&&!Object.keys(i).some(e=>"authorization"===e.toLowerCase()))if("bearer"===c.type)i.Authorization=`Bearer ${c.token??""}`;else if("basic"===c.type){const e=`${c.username??""}:${c.password??""}`;i.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===c.type&&"header"===(c.in??"header")&&(i[c.key??"X-API-Key"]=c.value??"");const u=n.send??o.send??[],l=(Array.isArray(u)?u:[u]).map(e=>function(e){if(null==e)return null;if("string"==typeof e)return e;if(e instanceof Uint8Array)return e;try{return JSON.stringify(e)}catch{return null}}("string"==typeof e?M(e,s):e)).filter(e=>null!==e),f=n.keepAlive??o.keepAlive;return{url:a,subprotocols:n.subprotocols??o.subprotocols??[],headers:i,send:l,sendDelayMs:ae(n.sendDelayMs,0),maxMessages:ae(n.maxMessages??r.maxEvents,100),maxSessionMs:ae(n.maxSessionMs??r.maxStreamMs,3e4),idleTimeoutMs:ae(n.idleTimeoutMs,0),keepAlive:f?{intervalMs:ae(f.intervalMs,15e3),payload:String(f.payload??"ping")}:void 0,closeCode:n.closeCode??1e3,closeReason:n.closeReason??"Client finished sampling",rejectUnauthorized:!1!==n.rejectUnauthorized,maxPayloadBytes:ae(n.maxPayloadBytes,262144),clientOptions:n.clientOptions??{}}}function ae(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?t:r}var ie=c(require("ws"),1),ce=new Set([1e3,1001,1005]);function ue(e,t){const r=R(),n=Date.now();let o,s=0,a=0,i=0,c=!1,u=!1;const l=[],p={};let d,m,y=0,h=null,g=null,b=null;const v=[];let w;try{w=new ie.default(e.url,e.subprotocols,{headers:e.headers,handshakeTimeout:Math.max(5e3,Math.min(e.maxSessionMs,3e4)),rejectUnauthorized:e.rejectUnauthorized,maxPayload:4*e.maxPayloadBytes,...e.clientOptions})}catch(e){return Promise.resolve(S(f(e)))}function S(t){const r=Date.now(),s=!t&&y>0&&y<400;return{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:y||(t?0:101),statusText:t?"WebSocket error":s?"Switching Protocols":"Connection closed",headers:p,contentType:"application/json",events:l,timings:{startedAt:n,endedAt:r,durationMs:r-n,firstByteMs:o?o-n:void 0},sizeBytes:i,...c?{truncated:!0}:{}},...d?{cookies:[]}:{},...t?{error:t}:{}}}const j=e=>{r.settled||((()=>{if(h=L(h),g=L(g),b){try{clearInterval(b)}catch{}b=null}for(const e of v.splice(0))L(e)})(),r.resolve(S(e??m)))},x=t=>{if(u)return;u=!0,c=!0;try{w.readyState===ie.default.OPEN?w.close(e.closeCode,`${e.closeReason}: ${t}`.slice(0,120)):w.terminate()}catch{}const r=setTimeout(()=>{try{w.terminate()}catch{}j()},3e3);"object"==typeof r&&"function"==typeof r.unref&&r.unref(),v.push(r)},A=()=>{e.idleTimeoutMs&&(g=L(g),g=setTimeout(()=>x("idle timeout"),e.idleTimeoutMs),"object"==typeof g&&"function"==typeof g.unref&&g.unref())},O=e=>{l.push(e);try{t.onEvent?.(e)}catch{}};return w.on("upgrade",e=>{y=e?.statusCode??101;for(const[t,r]of Object.entries(e?.headers??{}))p[t]=Array.isArray(r)?r.join(", "):String(r)}),w.on("unexpected-response",(e,t)=>{y=t?.statusCode??0;for(const[e,r]of Object.entries(t?.headers??{}))p[e]=Array.isArray(r)?r.join(", "):String(r);m={message:`Handshake rejected with HTTP ${y}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}j(m)}),w.on("open",()=>{o=Date.now(),d=w.protocol||void 0,y||(y=101);try{t.onOpen?.({url:e.url,protocol:d,headers:p})}catch{}e.send.forEach((t,r)=>{const n=()=>{w.readyState===ie.default.OPEN&&w.send(t,e=>{e?m=m??f(e):(a+=1,O({id:String(a),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?le(t):void 0,receivedAt:Date.now(),direction:"out"}))})},o=e.sendDelayMs*r;if(o<=0)n();else{const e=setTimeout(n,o);"object"==typeof e&&"function"==typeof e.unref&&e.unref(),v.push(e)}}),e.keepAlive&&(b=setInterval(()=>{if(w.readyState===ie.default.OPEN)try{w.ping(e.keepAlive.payload)}catch{}},e.keepAlive.intervalMs),"object"==typeof b&&"function"==typeof b.unref&&b.unref()),A()}),w.on("message",(t,r)=>{if(u)return;const n=function(e){return Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e)}(t);i+=n.length,a+=1,s+=1;const o=n.length>e.maxPayloadBytes,c=r?`<binary ${n.length} bytes>`:o?`${n.subarray(0,e.maxPayloadBytes).toString("utf8")}...`:n.toString("utf8");O({id:String(a),event:r?"binary":"text",data:c,parsed:r||o?void 0:le(c),receivedAt:Date.now(),direction:"in"}),A(),s>=e.maxMessages&&x("maxMessages reached")}),w.on("ping",e=>{a+=1,O({id:String(a),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}),A()}),w.on("error",e=>{m=m??f(e),w.readyState===ie.default.CLOSED&&j(m)}),w.on("close",(e,t)=>{const r=t?.length?t.toString("utf8"):"";m||ce.has(e)||u||(m={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),j(m)}),h=setTimeout(()=>x("maxSessionMs reached"),e.maxSessionMs),"object"==typeof h&&"function"==typeof h.unref&&h.unref(),r.promise}function le(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}var pe=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=se(e.located,e.spec,e.options);return{config:t,environment:{id:`protokit-ws-env-${Date.now().toString(36)}`,name:`${e.spec?.info?.title??"API"} WebSocket Environment`,values:[{key:"wsUrl",value:t.url,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).map(([e,t])=>({key:e,value:String(t??""),type:/token|secret|password|apikey/i.test(e)?"secret":"default",enabled:!0}))],_postman_variable_scope:"environment"}}}execute(e,t){return ue(e.config,t)}},fe=["null","boolean","integer","number","string","array","object"],de=e=>null==e?[]:Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[];function me(e,t,r=0){if(!e||"object"!=typeof e)return t??e;if(!t||"object"!=typeof t)return e;if(r>20)return{};if("string"==typeof e.$ref)return e;if("string"==typeof t.$ref)return t;const n={};let o=Array.from(new Set([...de(e.type),...de(t.type)]));if(o.includes("integer")&&o.includes("number")&&(o=o.filter(e=>"integer"!==e)),o.sort((e,t)=>fe.indexOf(e)-fe.indexOf(t)),1===o.length?n.type=o[0]:o.length>1&&(n.type=o),e.format&&e.format===t.format&&(n.format=e.format),e.properties||t.properties){const o={...e.properties??{}};for(const[e,n]of Object.entries(t.properties??{}))o[e]=o[e]?me(o[e],n,r+1):n;n.properties=o;const s=Array.isArray(e.required)?e.required:[],a=Array.isArray(t.required)?t.required:[];if(e.properties&&t.properties){const e=s.filter(e=>a.includes(e));e.length&&(n.required=e)}else{const t=e.properties?s:a;t.length&&(n.required=t)}}if((e.items||t.items)&&(n.items=me(e.items,t.items,r+1)),e.additionalProperties||t.additionalProperties){const o=e.additionalProperties,s=t.additionalProperties;n.additionalProperties="object"==typeof o&&"object"==typeof s?me(o,s,r+1):o??s}Array.isArray(e.enum)&&Array.isArray(t.enum)&&(n.enum=Array.from(new Set([...e.enum,...t.enum])).slice(0,50));const s=function(e){const t=new Set,r=[];for(const n of e){let e;try{e=JSON.stringify(n)}catch{continue}t.has(e)||(t.add(e),r.push(n))}return r}([...e.examples??[],...t.examples??[]]).slice(0,3);s.length&&(n.examples=s);for(const r of["title","description","deprecated","readOnly","writeOnly"])void 0===e[r]&&void 0===t[r]||(n[r]=e[r]??t[r]);return n}var ye=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,he=/^\d{4}-\d{2}-\d{2}$/,ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,be=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,ve=/^https?:\/\/\S+$/i;function we(e,t={},r=0){const n=t.maxDepth??12,o=!1!==t.includeExamples;if(r>n)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("string"===s){const r=e,n={type:"string"};if(ye.test(r)?n.format="date-time":he.test(r)?n.format="date":ge.test(r)?n.format="uuid":ve.test(r)?n.format="uri":be.test(r)&&(n.format="email"),o){const e=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.min(e.length,t.sampleArrayItems??20);let o=we(e[0],t,r+1);for(let s=1;s<n;s+=1)o=me(o,we(e[s],t,r+1),0);return{type:"array",items:o}}if("object"===s){const n={},o=[];for(const[s,a]of Object.entries(e))n[s]=we(a,t,r+1),null!=a&&o.push(s);const s={type:"object",properties:n};return o.length&&(s.required=o),s}return{}}function Se(e,t={}){let r=null;for(const n of e)r=r?me(r,we(n,t),0):we(n,t);return r??{}}var je=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-amzn-requestid","x-amz-cf-id","cf-ray","cf-cache-status","x-served-by","x-timer","x-cache"]),xe=new Set(["[DONE]","DONE","[done]"]);function Ae(e,t={}){const{response:r}=e,n=r.status>0?String(r.status):"default",o=(s=r.contentType)&&s.split(";")[0].trim().toLowerCase()||"application/octet-stream";var s;const a=!1!==t.includeExamples,i=t.maxExampleChars??4e3,c={description:r.statusText||ke(r.status)},u=function(e){const t={};for(const[r,n]of Object.entries(e??{})){const e=r.toLowerCase();"content-type"===e||je.has(e)||(t[r]={schema:{type:"string",examples:[String(n)]}})}return Object.keys(t).length?t:void 0}(r.headers);if(u&&(c.headers=u),("sse"===e.protocol||"websocket"===e.protocol)&&Array.isArray(r.events)){const t=r.events.filter(e=>!function(e){if(xe.has(e.data.trim()))return!0;const t=(e.event??"").toLowerCase();return"done"===t||"end"===t||"complete"===t}(e));if(!t.length)return{statusCode:n,response:c};let s=null,a=!0;for(const e of t)if(void 0!==e.parsed)s=me(s,we(e.parsed),0);else{a=!1;s=me(s,{type:"string",examples:[e.data.length>200?`${e.data.slice(0,200)}...`:e.data]},0)}const i=Array.from(new Set(t.map(e=>e.event).filter(e=>!!e))),u={type:"object",properties:{id:{type:"string"},event:i.length?{type:"string",enum:i}:{type:"string"},data:a?s??{type:"object"}:s??{type:"string"},retry:{type:"integer"}},required:["data"]},l="sse"===e.protocol?"text/event-stream":o;return c.content={[l]:{itemSchema:u,"x-protokit-sample-count":t.length,...r.truncated?{"x-protokit-truncated":!0}:{}}},{statusCode:n,response:c}}if(void 0!==r.body&&null!==r.body){const e={schema:we(r.body)};a&&(e.examples={capturedSample:{summary:"Captured from a live call",value:Oe(r.body,i)}}),c.content={[o]:e}}else if("string"==typeof r.text&&r.text.length){const e={schema:{type:"string"}};a&&(e.examples={capturedSample:{value:r.text.slice(0,i)}}),c.content={[o]:e}}else 204!==r.status&&r.sizeBytes>0&&(c.content={[o]:{schema:{type:"string",format:"binary"}}});return{statusCode:n,response:c}}function Oe(e,t){try{const r=JSON.stringify(e);return r&&r.length<=t?e:{"x-protokit-truncated":!0,preview:String(r).slice(0,t)}}catch{return String(e).slice(0,t)}}function ke(e){return e>=500?"Server error":e>=400?"Client error":e>=300?"Redirection":e>=200?"Successful response":"Response"}function $e(e,t,r,n,o={}){if(!e||"object"!=typeof e)throw p("BAD_SPEC","spec must be an object");const s=N(e),a=s.paths?.[t];if(!a)throw p("PATH_NOT_FOUND",`Path "${t}" is not present in the document`);const i=a[String(r).toLowerCase()]??a.additionalOperations?.[r.toUpperCase()]??a.additionalOperations?.[r];if(!i||"object"!=typeof i)throw p("OP_NOT_FOUND",`Operation "${r.toUpperCase()} ${t}" is not present in the document`);const c=n.statusCode;if(o.allowedStatusCodes?.length&&!o.allowedStatusCodes.includes(c))return s;i.responses&&"object"==typeof i.responses||(i.responses={});const u=N(n.response);if("replace"===o.strategy||!i.responses[c])return i.responses[c]=u,s;const l=i.responses[c];if("string"==typeof l.$ref)return s;if(!1!==o.keepExistingDescription&&l.description||(l.description=u.description??l.description),u.headers&&(l.headers={...l.headers??{},...u.headers}),u.content){l.content&&"object"==typeof l.content||(l.content={});for(const[e,t]of Object.entries(u.content)){const r=l.content[e];if(!r){l.content[e]=t;continue}const n=!1!==o.protectComponentRefs;t.itemSchema&&(r.itemSchema=n&&"string"==typeof r.itemSchema?.$ref?r.itemSchema:me(r.itemSchema,t.itemSchema,0)),t.schema&&(r.schema=n&&"string"==typeof r.schema?.$ref?r.schema:me(r.schema,t.schema,0)),t.examples&&(r.examples={...r.examples??{},...t.examples});for(const e of Object.keys(t))e.startsWith("x-")&&(r[e]=t[e])}}return s}function Te(e={}){const t=new d,r=e.adapters??[new oe,new pe];for(const n of[...r,...e.extraAdapters??[]])t.register(n);const n=e=>{if(!e||"object"!=typeof e)throw p("BAD_OPTIONS","send() requires an options object");const r=ne(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}};return{registry:t,toCollection(e,t,r={}){const o={...r,spec:e,target:t},{located:s,adapter:a,plan:i}=n(o),c=i;return{protocol:a.name,located:s,collection:c?.collection,environment:c?.environment,streaming:c?.streaming,plan:i}},async send(t){const{located:r,adapter:o,plan:s}=n(t);let a;try{a=await o.execute(s,t)}catch(e){throw p("EXECUTION_FAILED",`Adapter "${o.name}" failed: ${f(e).message}`,e)}const i=Ae(a,e.response),c=s;let u,l;if(!1===t.writeBack)l="disabled by options.writeBack";else if(a.response.status<=0)l="no response was received";else if(a.scripts?.skipped)l="request was skipped by a script";else if(!1!==e.writeBack?.requirePassingTests&&!1===a.scripts?.passed)l="one or more assertions failed";else try{u=$e(t.spec,r.path,r.method,i,e.writeBack)}catch(e){l=`write-back error: ${f(e).message}`}return{...a,collection:c?.collection,environment:c?.environment,responseFragment:i.response,responseStatusCode:i.statusCode,patchedSpec:u,writeBackSkippedReason:l}},async sendMany(e,t,r={}){let n=e;const o=[];for(const e of t)try{const t=await this.send({...r,...e,spec:n});t.patchedSpec&&(n=t.patchedSpec),o.push(t)}catch(t){o.push({target:e.target,error:f(t).message})}return{spec:n,results:o}}}}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { P as ProtocolAdapter, A as AdapterContext, E as ExecResult, J as Json, S as ScriptSource, L as LocatedOperation, O as OperationTarget, a as SendOptions, b as SendResult } from './protocol-58EyJAsY.cjs';
|
|
2
|
+
export { c as AssertionResult, d as AuthConfig, C as ConsoleLog, e as ProtocolName, R as ReplayRecord, f as RequestValues, g as RequesterOptions, h as RuntimeRunOptions, i as ScriptConfig, j as ScriptOutcome, k as ScriptReport, l as StreamEvent, W as WebSocketOptions, m as locateOperation } from './protocol-58EyJAsY.cjs';
|
|
3
|
+
export { HttpAdapter } from './protocols/http/index.cjs';
|
|
4
|
+
export { WebSocketAdapter } from './protocols/ws/index.cjs';
|
|
5
|
+
|
|
6
|
+
declare class AdapterRegistry {
|
|
7
|
+
private readonly adapters;
|
|
8
|
+
register(adapter: ProtocolAdapter<any>): this;
|
|
9
|
+
list(): string[];
|
|
10
|
+
resolve(ctx: AdapterContext): ProtocolAdapter<any>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ToResponseOptions {
|
|
14
|
+
/** Cap on the size of captured example payloads, in characters. */
|
|
15
|
+
maxExampleChars?: number;
|
|
16
|
+
/** Include a captured example under `content[mediaType].examples`. Defaults to true. */
|
|
17
|
+
includeExamples?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Convert a single execution result into an OpenAPI 3.2 Response Object. */
|
|
20
|
+
declare function toResponseObject(result: ExecResult, options?: ToResponseOptions): {
|
|
21
|
+
statusCode: string;
|
|
22
|
+
response: any;
|
|
23
|
+
};
|
|
24
|
+
interface WriteBackOptions {
|
|
25
|
+
/** 'merge' unions the new observation into the existing schema. Defaults to 'merge'. */
|
|
26
|
+
strategy?: "merge" | "replace";
|
|
27
|
+
/** Preserve a hand-written description instead of the HTTP reason phrase. Defaults to true. */
|
|
28
|
+
keepExistingDescription?: boolean;
|
|
29
|
+
/** Skip write-back when any assertion failed. Defaults to true. */
|
|
30
|
+
requirePassingTests?: boolean;
|
|
31
|
+
/** Only write back these status codes. Empty means all. */
|
|
32
|
+
allowedStatusCodes?: string[];
|
|
33
|
+
/** Refuse to touch responses whose schema is a $ref to a shared component. Defaults to true. */
|
|
34
|
+
protectComponentRefs?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Merge a response fragment into a copy of the spec.
|
|
38
|
+
* The input document is never mutated.
|
|
39
|
+
*/
|
|
40
|
+
declare function writeBackResponse(spec: any, path: string, method: string, fragment: {
|
|
41
|
+
statusCode: string;
|
|
42
|
+
response: any;
|
|
43
|
+
}, options?: WriteBackOptions): any;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Unified error type for the whole toolkit.
|
|
47
|
+
* `code` is a stable machine-readable identifier; `message` is human-facing.
|
|
48
|
+
*/
|
|
49
|
+
declare class ProtoKitError extends Error {
|
|
50
|
+
readonly code: string;
|
|
51
|
+
readonly details?: unknown;
|
|
52
|
+
constructor(message: string, code: string, details?: unknown);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface InferOptions {
|
|
56
|
+
/** Maximum nesting depth to inspect. Defaults to 12. */
|
|
57
|
+
maxDepth?: number;
|
|
58
|
+
/** Number of array elements sampled when unifying item schemas. Defaults to 20. */
|
|
59
|
+
sampleArrayItems?: number;
|
|
60
|
+
/** Maximum characters retained in string examples. Defaults to 120. */
|
|
61
|
+
maxExampleLength?: number;
|
|
62
|
+
/** Emit example values alongside the inferred schema. Defaults to true. */
|
|
63
|
+
includeExamples?: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** Derive a JSON Schema from an observed runtime value. */
|
|
66
|
+
declare function inferSchema(value: Json, options?: InferOptions, depth?: number): any;
|
|
67
|
+
/** Fold a list of observed values into a single unified schema. */
|
|
68
|
+
declare function inferSchemaFromMany(values: Json[], options?: InferOptions): any;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Merge two JSON Schemas into their least upper bound.
|
|
72
|
+
* Types become a union, object properties are unioned, and `required`
|
|
73
|
+
* shrinks to the intersection so optional fields stay optional.
|
|
74
|
+
*/
|
|
75
|
+
declare function mergeSchema(a: any, b: any, depth?: number): any;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Produce a representative value for a JSON Schema so that required
|
|
79
|
+
* parameters and request bodies are never left empty.
|
|
80
|
+
*/
|
|
81
|
+
declare function sampleFromSchema(schema: any, depth?: number): any;
|
|
82
|
+
|
|
83
|
+
/** Optional helper script that exposes the last response to subsequent requests. */
|
|
84
|
+
declare const BUILTIN_CAPTURE_TEST: ScriptSource;
|
|
85
|
+
|
|
86
|
+
interface DebuggerOptions {
|
|
87
|
+
/** Replaces the default adapter set when provided. */
|
|
88
|
+
adapters?: ProtocolAdapter<any>[];
|
|
89
|
+
/** Adapters appended to the default set. */
|
|
90
|
+
extraAdapters?: ProtocolAdapter<any>[];
|
|
91
|
+
writeBack?: WriteBackOptions;
|
|
92
|
+
response?: ToResponseOptions;
|
|
93
|
+
}
|
|
94
|
+
interface PlanResult {
|
|
95
|
+
protocol: string;
|
|
96
|
+
located: LocatedOperation;
|
|
97
|
+
collection?: any;
|
|
98
|
+
environment?: any;
|
|
99
|
+
streaming?: boolean;
|
|
100
|
+
plan: unknown;
|
|
101
|
+
}
|
|
102
|
+
declare function createDebugger(config?: DebuggerOptions): {
|
|
103
|
+
registry: AdapterRegistry;
|
|
104
|
+
/** Inspect the generated artifacts without performing any network I/O. */
|
|
105
|
+
toCollection(spec: any, target: OperationTarget, overrides?: Partial<Omit<SendOptions, "spec" | "target">>): PlanResult;
|
|
106
|
+
/** Execute the operation and fold the observed response back into the spec. */
|
|
107
|
+
send(options: SendOptions): Promise<SendResult>;
|
|
108
|
+
/**
|
|
109
|
+
* Run several operations in order, threading the patched spec through
|
|
110
|
+
* so that repeated observations accumulate into one schema.
|
|
111
|
+
*/
|
|
112
|
+
sendMany(spec: any, targets: Array<{
|
|
113
|
+
target: OperationTarget;
|
|
114
|
+
} & Partial<Omit<SendOptions, "spec" | "target">>>, shared?: Partial<Omit<SendOptions, "spec" | "target">>): Promise<{
|
|
115
|
+
spec: any;
|
|
116
|
+
results: Array<SendResult | {
|
|
117
|
+
target: OperationTarget;
|
|
118
|
+
error: string;
|
|
119
|
+
}>;
|
|
120
|
+
}>;
|
|
121
|
+
};
|
|
122
|
+
type ProtoKit = ReturnType<typeof createDebugger>;
|
|
123
|
+
|
|
124
|
+
export { AdapterContext, AdapterRegistry, BUILTIN_CAPTURE_TEST, type DebuggerOptions, ExecResult, Json, LocatedOperation, OperationTarget, type PlanResult, type ProtoKit, ProtoKitError, ProtocolAdapter, ScriptSource, SendOptions, SendResult, type ToResponseOptions, type WriteBackOptions, createDebugger, inferSchema, inferSchemaFromMany, mergeSchema, sampleFromSchema, toResponseObject, writeBackResponse };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { P as ProtocolAdapter, A as AdapterContext, E as ExecResult, J as Json, S as ScriptSource, L as LocatedOperation, O as OperationTarget, a as SendOptions, b as SendResult } from './protocol-58EyJAsY.js';
|
|
2
|
+
export { c as AssertionResult, d as AuthConfig, C as ConsoleLog, e as ProtocolName, R as ReplayRecord, f as RequestValues, g as RequesterOptions, h as RuntimeRunOptions, i as ScriptConfig, j as ScriptOutcome, k as ScriptReport, l as StreamEvent, W as WebSocketOptions, m as locateOperation } from './protocol-58EyJAsY.js';
|
|
3
|
+
export { HttpAdapter } from './protocols/http/index.js';
|
|
4
|
+
export { WebSocketAdapter } from './protocols/ws/index.js';
|
|
5
|
+
|
|
6
|
+
declare class AdapterRegistry {
|
|
7
|
+
private readonly adapters;
|
|
8
|
+
register(adapter: ProtocolAdapter<any>): this;
|
|
9
|
+
list(): string[];
|
|
10
|
+
resolve(ctx: AdapterContext): ProtocolAdapter<any>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ToResponseOptions {
|
|
14
|
+
/** Cap on the size of captured example payloads, in characters. */
|
|
15
|
+
maxExampleChars?: number;
|
|
16
|
+
/** Include a captured example under `content[mediaType].examples`. Defaults to true. */
|
|
17
|
+
includeExamples?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Convert a single execution result into an OpenAPI 3.2 Response Object. */
|
|
20
|
+
declare function toResponseObject(result: ExecResult, options?: ToResponseOptions): {
|
|
21
|
+
statusCode: string;
|
|
22
|
+
response: any;
|
|
23
|
+
};
|
|
24
|
+
interface WriteBackOptions {
|
|
25
|
+
/** 'merge' unions the new observation into the existing schema. Defaults to 'merge'. */
|
|
26
|
+
strategy?: "merge" | "replace";
|
|
27
|
+
/** Preserve a hand-written description instead of the HTTP reason phrase. Defaults to true. */
|
|
28
|
+
keepExistingDescription?: boolean;
|
|
29
|
+
/** Skip write-back when any assertion failed. Defaults to true. */
|
|
30
|
+
requirePassingTests?: boolean;
|
|
31
|
+
/** Only write back these status codes. Empty means all. */
|
|
32
|
+
allowedStatusCodes?: string[];
|
|
33
|
+
/** Refuse to touch responses whose schema is a $ref to a shared component. Defaults to true. */
|
|
34
|
+
protectComponentRefs?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Merge a response fragment into a copy of the spec.
|
|
38
|
+
* The input document is never mutated.
|
|
39
|
+
*/
|
|
40
|
+
declare function writeBackResponse(spec: any, path: string, method: string, fragment: {
|
|
41
|
+
statusCode: string;
|
|
42
|
+
response: any;
|
|
43
|
+
}, options?: WriteBackOptions): any;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Unified error type for the whole toolkit.
|
|
47
|
+
* `code` is a stable machine-readable identifier; `message` is human-facing.
|
|
48
|
+
*/
|
|
49
|
+
declare class ProtoKitError extends Error {
|
|
50
|
+
readonly code: string;
|
|
51
|
+
readonly details?: unknown;
|
|
52
|
+
constructor(message: string, code: string, details?: unknown);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface InferOptions {
|
|
56
|
+
/** Maximum nesting depth to inspect. Defaults to 12. */
|
|
57
|
+
maxDepth?: number;
|
|
58
|
+
/** Number of array elements sampled when unifying item schemas. Defaults to 20. */
|
|
59
|
+
sampleArrayItems?: number;
|
|
60
|
+
/** Maximum characters retained in string examples. Defaults to 120. */
|
|
61
|
+
maxExampleLength?: number;
|
|
62
|
+
/** Emit example values alongside the inferred schema. Defaults to true. */
|
|
63
|
+
includeExamples?: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** Derive a JSON Schema from an observed runtime value. */
|
|
66
|
+
declare function inferSchema(value: Json, options?: InferOptions, depth?: number): any;
|
|
67
|
+
/** Fold a list of observed values into a single unified schema. */
|
|
68
|
+
declare function inferSchemaFromMany(values: Json[], options?: InferOptions): any;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Merge two JSON Schemas into their least upper bound.
|
|
72
|
+
* Types become a union, object properties are unioned, and `required`
|
|
73
|
+
* shrinks to the intersection so optional fields stay optional.
|
|
74
|
+
*/
|
|
75
|
+
declare function mergeSchema(a: any, b: any, depth?: number): any;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Produce a representative value for a JSON Schema so that required
|
|
79
|
+
* parameters and request bodies are never left empty.
|
|
80
|
+
*/
|
|
81
|
+
declare function sampleFromSchema(schema: any, depth?: number): any;
|
|
82
|
+
|
|
83
|
+
/** Optional helper script that exposes the last response to subsequent requests. */
|
|
84
|
+
declare const BUILTIN_CAPTURE_TEST: ScriptSource;
|
|
85
|
+
|
|
86
|
+
interface DebuggerOptions {
|
|
87
|
+
/** Replaces the default adapter set when provided. */
|
|
88
|
+
adapters?: ProtocolAdapter<any>[];
|
|
89
|
+
/** Adapters appended to the default set. */
|
|
90
|
+
extraAdapters?: ProtocolAdapter<any>[];
|
|
91
|
+
writeBack?: WriteBackOptions;
|
|
92
|
+
response?: ToResponseOptions;
|
|
93
|
+
}
|
|
94
|
+
interface PlanResult {
|
|
95
|
+
protocol: string;
|
|
96
|
+
located: LocatedOperation;
|
|
97
|
+
collection?: any;
|
|
98
|
+
environment?: any;
|
|
99
|
+
streaming?: boolean;
|
|
100
|
+
plan: unknown;
|
|
101
|
+
}
|
|
102
|
+
declare function createDebugger(config?: DebuggerOptions): {
|
|
103
|
+
registry: AdapterRegistry;
|
|
104
|
+
/** Inspect the generated artifacts without performing any network I/O. */
|
|
105
|
+
toCollection(spec: any, target: OperationTarget, overrides?: Partial<Omit<SendOptions, "spec" | "target">>): PlanResult;
|
|
106
|
+
/** Execute the operation and fold the observed response back into the spec. */
|
|
107
|
+
send(options: SendOptions): Promise<SendResult>;
|
|
108
|
+
/**
|
|
109
|
+
* Run several operations in order, threading the patched spec through
|
|
110
|
+
* so that repeated observations accumulate into one schema.
|
|
111
|
+
*/
|
|
112
|
+
sendMany(spec: any, targets: Array<{
|
|
113
|
+
target: OperationTarget;
|
|
114
|
+
} & Partial<Omit<SendOptions, "spec" | "target">>>, shared?: Partial<Omit<SendOptions, "spec" | "target">>): Promise<{
|
|
115
|
+
spec: any;
|
|
116
|
+
results: Array<SendResult | {
|
|
117
|
+
target: OperationTarget;
|
|
118
|
+
error: string;
|
|
119
|
+
}>;
|
|
120
|
+
}>;
|
|
121
|
+
};
|
|
122
|
+
type ProtoKit = ReturnType<typeof createDebugger>;
|
|
123
|
+
|
|
124
|
+
export { AdapterContext, AdapterRegistry, BUILTIN_CAPTURE_TEST, type DebuggerOptions, ExecResult, Json, LocatedOperation, OperationTarget, type PlanResult, type ProtoKit, ProtoKitError, ProtocolAdapter, ScriptSource, SendOptions, SendResult, type ToResponseOptions, type WriteBackOptions, createDebugger, inferSchema, inferSchemaFromMany, mergeSchema, sampleFromSchema, toResponseObject, writeBackResponse };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class e extends Error{code;details;constructor(t,r,n){super(t),this.name="ProtoKitError",this.code=r,this.details=n,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function t(t,r,n){return new e(r,t,n)}function r(t){if(t instanceof e)return{message:t.message,code:t.code,name:t.name};if(t instanceof Error)return{message:t.message,code:t.code,name:t.name};if("string"==typeof t)return{message:t};try{return{message:JSON.stringify(t)}}catch{return{message:String(t)}}}var n=class{adapters=[];register(e){if(!e||"function"!=typeof e.supports)throw t("BAD_ADAPTER","Adapter must implement the ProtocolAdapter interface");const r=this.adapters.findIndex(t=>t.name===e.name);return r>=0&&this.adapters.splice(r,1),this.adapters.push(e),this}list(){return this.adapters.map(e=>e.name)}resolve(e){const r=this.adapters.map(t=>{let r=0;try{r=t.supports(e)||0}catch{r=0}return{adapter:t,score:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score);if(!r.length)throw t("NO_ADAPTER",`No protocol adapter matched operation "${e.located.method.toUpperCase()} ${e.located.path}"`);return r[0].adapter}};function o(e,t=0){if(!e||"object"!=typeof e||t>12)return null;if(void 0!==e.example)return e.example;if(void 0!==e.examples){if(Array.isArray(e.examples)&&e.examples.length)return e.examples[0];if("object"==typeof e.examples){const t=Object.values(e.examples)[0];if(void 0!==t)return t&&"object"==typeof t&&"value"in t?t.value:t}}if(void 0!==e.default)return e.default;if(void 0!==e.const)return e.const;if(Array.isArray(e.enum)&&e.enum.length)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length)return e.allOf.reduce((e,r)=>{const n=o(r,t+1);return n&&"object"==typeof n&&!Array.isArray(n)?{...e,...n}:null!=n?n:e},{});for(const r of["oneOf","anyOf"])if(Array.isArray(e[r])&&e[r].length)return o(e[r][0],t+1);switch((Array.isArray(e.type)?e.type.find(e=>"null"!==e)??"null":e.type)??(e.properties?"object":e.items?"array":(e.format,"string"))){case"object":{const r={},n=Array.isArray(e.required)?e.required:[],s=e.properties&&"object"==typeof e.properties?e.properties:{};for(const[e,i]of Object.entries(s))i&&!0===i.readOnly||t>2&&n.length&&!n.includes(e)||(r[e]=o(i,t+1));return!Object.keys(r).length&&e.additionalProperties&&"object"==typeof e.additionalProperties&&(r.key=o(e.additionalProperties,t+1)),r}case"array":{const r=Math.max(1,Math.min(Number(e.minItems)||1,2));return Array.from({length:r},()=>o(e.items,t+1))}case"integer":return s(e,Math.trunc(e.minimum??0));case"number":return s(e,e.minimum??0);case"boolean":return!1;case"null":return null;default:return function(e){switch(e.format){case"date-time":return(new Date).toISOString();case"date":return(new Date).toISOString().slice(0,10);case"time":return(new Date).toISOString().slice(11,19);case"uuid":return"00000000-0000-4000-8000-000000000000";case"email":return"user@example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"uri":case"url":case"uri-reference":return"https://example.com";case"byte":case"binary":return"";case"password":return"password";default:{if("string"==typeof e.pattern)return"";const t=Number(e.minLength)||0,r="string";return t>r.length?r.padEnd(t,"x"):r}}}(e)}}function s(e,t){let r=t;return"number"==typeof e.minimum&&r<e.minimum&&(r=e.minimum),"number"==typeof e.maximum&&r>e.maximum&&(r=e.maximum),r}var i=/(token|secret|password|passwd|apikey|api_key|credential|private)/i;function a(e,t){if(t.serverUrl)return c(t.serverUrl);const r=Array.isArray(e)&&e.length?e[0]:{url:"/"};let n="string"==typeof r?.url&&r.url?r.url:"/";const o=r?.variables&&"object"==typeof r.variables?r.variables:{};for(const[e,r]of Object.entries(o)){const o=t.serverVariables?.[e],s=r?.default??(Array.isArray(r?.enum)&&r.enum.length?r.enum[0]:""),i=void 0!==o?o:s;n=n.split(`{${e}}`).join(String(i??""))}return n=n.replace(/\{[^}]*\}/g,""),c(n)}function c(e){return e.replace(/\/+$/,"")||e}function u(e,t,r={}){const n=[{key:"baseUrl",value:t,type:"default",enabled:!0},...Object.entries(r??{}).filter(([e])=>"baseUrl"!==e).map(([e,t])=>({key:e,value:null==t?"":String(t),type:i.test(e)?"secret":"default",enabled:!0}))];return{id:`protokit-env-${Date.now().toString(36)}`,name:e,values:n,_postman_variable_scope:"environment",_postman_exported_at:(new Date).toISOString()}}var l=["text/event-stream","application/json-seq","application/x-ndjson","application/ndjson","application/jsonl"];function p(e,t){const r=Object.entries(t?.header??{}).find(([e])=>"accept"===e.toLowerCase())?.[1];if("string"==typeof r&&r.toLowerCase().includes("text/event-stream"))return!0;const n=e?.responses;if(!n||"object"!=typeof n)return!1;for(const e of Object.values(n)){const t=e?.content;if(t&&"object"==typeof t)for(const[e,r]of Object.entries(t)){const t=e.toLowerCase();if(t.startsWith("text/event-stream"))return!0;if(r&&"object"==typeof r.itemSchema&&l.some(e=>t.startsWith(e)))return!0}}return!1}function f(e){return!!e&&/text\/event-stream/i.test(e)}function d(e){if(!e)return!1;const t=e.toLowerCase();return l.some(e=>t.includes(e))}function m(e){if(!e)return[];return(Array.isArray(e)?e:[e]).filter(e=>!!e&&null!=e.exec)}function y(e,t){return t.map((t,r)=>{return{listen:e,script:{id:t.id??`protokit-${e}-${r}`,type:"text/javascript",exec:(n=t.exec,Array.isArray(n)?n.map(e=>String(e)):String(n).split(/\r?\n/))}};var n}).filter(e=>e.script.exec.some(e=>e.trim().length>0))}function h(e){const t=e?.["x-postman-scripts"];if(!t||"object"!=typeof t)return{pre:[],test:[]};const r=e=>null==e?[]:"string"==typeof e?[{exec:e}]:Array.isArray(e)?e.length?"string"==typeof e[0]?[{exec:e}]:e.filter(e=>e&&null!=e.exec):[]:"object"==typeof e&&null!=e.exec?[e]:[];return{pre:r(t.preRequest??t.prerequest??t.collectionPreRequest),test:r(t.test??t.tests??t.collectionTest)}}var g={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)) {"," pm.environment.set('__lastBody', pm.response.text());"," }","} catch (error) {"," console.warn('protokit capture failed: ' + error.message);","}"]},b=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"]);function v(e,t){const r=e.name,n=e.style??"form",o=e.explode??"form"===n;if(Array.isArray(t)){if(o)return t.map(e=>({key:r,value:w(e)}));const e="spaceDelimited"===n?" ":"pipeDelimited"===n?"|":",";return[{key:r,value:t.map(w).join(e)}]}if(t&&"object"==typeof t){const e=Object.entries(t);return"deepObject"===n?e.map(([e,t])=>({key:`${r}[${e}]`,value:w(t)})):o?e.map(([e,t])=>({key:e,value:w(t)})):[{key:r,value:e.flatMap(([e,t])=>[e,w(t)]).join(",")}]}return[{key:r,value:w(t)}]}function w(e){if(null==e)return"";if("object"==typeof e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function S(e,t,r){const n=r.values??{},s=a(e.servers,r),i=function(e,t){if(t?.contentType)return t.contentType;const r=e?.requestBody?.content;if(!r||"object"!=typeof r)return;const n=Object.keys(r);return n.length?n.find(e=>e.includes("json"))??n[0]:void 0}(e.operation,n),c=[];for(const t of e.parameters.filter(e=>"path"===e.in)){const e=n.path?.[t.name],r=void 0!==e?e:o(t.schema??{});c.push({key:t.name,value:w(r)})}const u=e.path.replace(/^\//,"").split("/").filter(e=>e.length>0).map(e=>e.replace(/\{([^}]+)\}/g,(e,t)=>`:${t}`)),l=[],p=new Set;for(const t of e.parameters.filter(e=>"query"===e.in)){p.add(t.name);const e=null!=n.query&&Object.prototype.hasOwnProperty.call(n.query,t.name)?n.query[t.name]:t.required?o(t.schema??{}):void 0;null!=e?l.push(...v(t,e)):t.required||l.push({key:t.name,value:"",disabled:!0})}for(const[e,t]of Object.entries(n.query??{}))p.has(e)||null==t||l.push({key:e,value:w(t)});const f=[],d=new Set,g=(e,t)=>{const r=e.toLowerCase();d.has(r)||(d.add(r),f.push({key:e,value:t}))};for(const[e,t]of Object.entries(n.header??{}))null!=t&&g(e,w(t));for(const t of e.parameters.filter(e=>"header"===e.in)){if(/^(accept|content-type|authorization)$/i.test(t.name))continue;const e=t.required?o(t.schema??{}):void 0;null!=e&&""!==e&&g(t.name,w(e))}i&&g("Content-Type",i);const S=function(e){const t=new Set,r=e?.responses;if(!r||"object"!=typeof r)return;for(const e of Object.values(r))for(const r of Object.keys(e?.content??{}))"*/*"!==r&&t.add(r);if(!t.size)return;const n=Array.from(t);return n.sort((e,t)=>Number(t.toLowerCase().startsWith("text/event-stream"))-Number(e.toLowerCase().startsWith("text/event-stream"))),n.slice(0,8).join(", ")}(e.operation);S&&g("Accept",S);const j=e.parameters.filter(e=>"cookie"===e.in),A=[];for(const e of j){const t=n.cookie?.[e.name],r=void 0!==t?t:e.required?o(e.schema??{}):void 0;null!=r&&A.push(`${e.name}=${encodeURIComponent(w(r))}`)}for(const[e,t]of Object.entries(n.cookie??{}))j.some(t=>t.name===e)||null==t||A.push(`${e}=${encodeURIComponent(w(t))}`);let k;A.length&&g("Cookie",A.join("; "));const O=e.operation.requestBody;if(O&&i){const e=O.content?.[i]?.schema,t=void 0!==n.body?n.body:o(e??{});k=i.includes("json")?{mode:"raw",raw:"string"==typeof t?t:JSON.stringify(t??{},null,2),options:{raw:{language:"json"}}}:i.includes("x-www-form-urlencoded")?{mode:"urlencoded",urlencoded:x(t).map(([e,t])=>({key:e,value:w(t),type:"text"}))}:i.includes("multipart/form-data")?{mode:"formdata",formdata:x(t).map(([e,t])=>t&&"object"==typeof t&&"__file"in t?{key:e,type:"file",src:String(t.__file)}:{key:e,type:"text",value:w(t)})}:i.includes("xml")||i.startsWith("text/")?{mode:"raw",raw:"string"==typeof t?t:w(t)}:{mode:"raw",raw:w(t)}}const $=l.filter(e=>!e.disabled);let C=`{{baseUrl}}/${u.join("/")}`;const T=[$.map(e=>`${encodeURIComponent(e.key)}=${encodeURIComponent(e.value)}`).join("&"),n.querystring?String(n.querystring).replace(/^\?/,""):""].filter(Boolean).join("&");T&&(C+=`?${T}`);const E={raw:C,host:["{{baseUrl}}"],path:u};l.length&&(E.query=l),c.length&&(E.variable=c);const P=e.method.toUpperCase(),D={method:P,header:f,url:E,description:e.operation.description??e.operation.summary};k&&(D.body=k);const q=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:h(e);return[...y("prerequest",[...r.pre,...m(t?.preRequest)]),...y("test",[...r.test,...m(t?.test)])]}(e.operation,r.scripts),_=function(e,t){const r=!1===t?.fromSpecExtensions?{pre:[],test:[]}:h(e);return[...y("prerequest",[...r.pre,...m(t?.collectionPreRequest)]),...y("test",[...r.test,...m(t?.collectionTest)])]}(t,r.scripts),N=function(e){if(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:e.in??"header",type:"string"}]};default:return}}(r.auth),I={info:{_postman_id:`protokit-${Date.now().toString(36)}`,name:t?.info?.title??"OpenAPI Debug Session",description:t?.info?.description,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:[{name:e.operation.operationId??`${P} ${e.path}`,...q.length?{event:q}:{},request:D,response:[]}],variable:[{key:"baseUrl",value:s}]};return N&&(I.auth=N),_.length&&(I.event=_),{collection:I,baseUrl:s,contentType:i,isCustomMethod:!b.has(P)}}function x(e){return!e||"object"!=typeof e||Array.isArray(e)?[]:Object.entries(e)}import j from"postman-runtime";import A from"postman-collection";function k(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof globalThis.structuredClone)try{return globalThis.structuredClone(e)}catch{}return O(e)}function O(e){const t=new WeakSet;return JSON.parse(JSON.stringify(e,(e,r)=>{if(r&&"object"==typeof r){if(t.has(r))return;t.add(r)}return r}))}function $(e,t){const r=null==e?"":String(e);return-1===r.indexOf("{{")?r:r.replace(/\{\{\s*([\w.$-]+)\s*\}\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t,r)?t[r]:e)}function C(e,t){if(!t)return e;const r={...e};for(const[e,n]of Object.entries(t)){if(void 0===n)continue;const t=r[e];T(t)&&T(n)?r[e]=C(t,n):r[e]=n}return r}function T(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function E(){let e,t,r=!1;return{promise:new Promise((r,n)=>{e=r,t=n}),get settled(){return r},resolve(t){r||(r=!0,e(t))},reject(e){r||(r=!0,t(e))}}}function P(e){if(e)try{clearTimeout(e)}catch{}return null}var D=new Set(["[DONE]","DONE"]),q=class{buffer="";decoder=new TextDecoder("utf-8");lastEventId;sequence=0;push(e){if(null==e)return[];if("string"==typeof e)this.buffer+=e;else{const t=e instanceof Uint8Array?e:new Uint8Array(e);this.buffer+=this.decoder.decode(t,{stream:!0})}0===this.sequence&&65279===this.buffer.charCodeAt(0)&&(this.buffer=this.buffer.slice(1));const t=[],r=/\r\n\r\n|\n\n|\r\r/;for(;;){const e=r.exec(this.buffer);if(!e)break;const n=this.buffer.slice(0,e.index);this.buffer=this.buffer.slice(e.index+e[0].length);const o=this.parseBlock(n);o&&t.push(o)}return t}flush(){try{this.buffer+=this.decoder.decode()}catch{}const e=this.buffer;if(this.buffer="",!e.trim())return[];const t=this.parseBlock(e);return t?[t]:[]}reset(){this.buffer="",this.lastEventId=void 0,this.sequence=0}parseBlock(e){const t=e.split(/\r\n|\n|\r/),r=[],n={data:"",receivedAt:Date.now(),direction:"in"};let o=!1;for(const e of t){if(""===e)continue;if(e.startsWith(":"))continue;const t=e.indexOf(":"),s=-1===t?e:e.slice(0,t);let i=-1===t?"":e.slice(t+1);switch(i.startsWith(" ")&&(i=i.slice(1)),s){case"data":r.push(i),o=!0;break;case"event":n.event=i,o=!0;break;case"id":i.includes("\0")||(n.id=i,this.lastEventId=i),o=!0;break;case"retry":{const e=Number(i);Number.isInteger(e)&&e>=0&&(n.retry=e),o=!0;break}}}if(!o)return null;n.data=r.join("\n"),void 0===n.id&&void 0!==this.lastEventId&&(n.id=this.lastEventId);const s=n.data.trim();if(s&&!D.has(s))try{n.parsed=JSON.parse(n.data)}catch{}return this.sequence+=1,n}};import _ from"postman-collection";function N(e,t=[]){const r=[...t,...Object.entries(e??{}).map(([e,t])=>({key:e,value:null==t?"":String(t)}))],n=new Map;for(const e of r)n.set(e.key,e);return new _.VariableScope({values:Array.from(n.values())})}function I(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 M(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)e&&!1!==e.enabled&&null!=e.key&&(n[String(e.key)]=null==e.value?"":String(e.value));return n}catch{return}}function U(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 O(t)}catch{return}}function B(e,n){const o=E(),s=Date.now();let i,a=e.streamingHint,c=!1,u=!1;const l=new q,p=[],m=[];let y=0;const h={prerequest:[],test:[],assertions:[],console:[],passed:!0,skipped:!1},g=[];let b=null,v=null,w=null,S=null;const x=n.maxEvents??100,k=n.maxStreamMs??3e4,$=n.runner?.timeout?.request??n.timeout??3e4,T=e=>{if(!c){c=!0,u=!0,h.console.push({level:"debug",messages:[`[protokit] stream sampling stopped: ${e}`],at:Date.now()});try{v?.abort?.()}catch{}}},D=(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:M(e?.result?.environment),globals:M(e?.result?.globals),return:e?.result?.return}),_=()=>{if(w=P(w),S=P(S),a)for(const e of l.flush())p.length<x&&(p.push(e),R(()=>n.onEvent?.(e)));if(b)a&&(b.response.events=p,u&&(b.response.truncated=!0));else{const e=Date.now();b={protocol:a?"sse":"http",request:{method:"",url:"",headers:{}},response:{status:c&&p.length?200:0,statusText:c?"Stream sampling stopped":"No response received",headers:{},contentType:a?"text/event-stream":void 0,...a?{events:p}:{},timings:{startedAt:s,endedAt:e,durationMs:e-s,firstByteMs:i?i-s:void 0},sizeBytes:y,...u?{truncated:!0}:{}},...c&&p.length?{}:{error:{message:"Runner finished without a response"}}}}b.scripts=h,o.resolve(b)};let B,F,J;S=setTimeout(()=>{if(!o.settled){h.console.push({level:"error",messages:["[protokit] hard timeout reached, forcing completion"],at:Date.now()});try{v?.abort?.()}catch{}u=!0,_()}},$+k+3e4),"object"==typeof S&&"function"==typeof S.unref&&S.unref();try{B=new A.Collection(O(e.collectionJson))}catch(e){return S=P(S),Promise.reject(t("BAD_COLLECTION",`Failed to construct collection: ${r(e).message}`,e))}try{F=function(e,t){const r=e.runner?.timeout?.request??e.timeout??3e4,n=C({iterationCount:1,stopOnError:!1,abortOnError:!1,stopOnFailure:!1,abortOnFailure:!1,timeout:{request:r,script:15e3,global:r+(t.streaming?e.maxStreamMs??3e4:0)+15e3},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}},{}),o=C(n,e.runner??{});return o.environment||(o.environment=N(e.variables,[{key:"baseUrl",value:t.baseUrl}])),!o.globals&&e.globals&&(o.globals=N(e.globals)),!o.localVariables&&e.localVariables&&(o.localVariables=N(e.localVariables)),Array.isArray(o.data)&&o.data.length&&void 0===e.runner?.iterationCount&&(o.iterationCount=o.data.length),o}(n,{baseUrl:e.baseUrl,streaming:e.streamingHint})}catch(e){return S=P(S),Promise.reject(t("BAD_RUN_OPTIONS",`Failed to build runtime options: ${r(e).message}`,e))}try{J=new j.Runner}catch(e){return S=P(S),Promise.reject(t("RUNTIME_INIT",`Failed to create runner: ${r(e).message}`,e))}return J.run(B,F,(e,j)=>{if(e)return S=P(S),void o.reject(t("RUNTIME_INIT",e.message??"Runner initialization failed",e));v=j,j.start({console(e,t,...r){const o={level:"string"==typeof t?t:"log",messages:r,at:Date.now()};h.console.push(o),R(()=>n.onConsole?.(o))},assertion(e,t){for(const e of t??[]){const t={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};t.passed||t.skipped||(h.passed=!1),h.assertions.push(t),R(()=>n.onAssertion?.(t))}},prerequest(e,t,r){for(const e of r??[])h.prerequest.push(D(e,"prerequest"))},test(e,t,r){for(const e of r??[])h.test.push(D(e,"test"))},item(e,t,r,n,o){o?.isSkipped&&(h.skipped=!0)},responseStart(e,t,r){i=Date.now();const o=L(r,"content-type");(f(o)||d(o))&&(a=!0),R(()=>n.onResponseStart?.({status:r?.code??0,headers:I(r?.headers),contentType:o})),a&&!w&&(w=setTimeout(()=>T("maxStreamMs reached"),k),"object"==typeof w&&"function"==typeof w.unref&&w.unref())},responseData(e,t){if(c||null==t)return;let r;try{r=Buffer.isBuffer(t)?t:Buffer.from(t)}catch{return}if(y+=r.length,a)for(const e of l.push(r)){if(p.length>=x)return void T("maxEvents reached");if(p.push(e),R(()=>n.onEvent?.(e)),p.length>=x)return void T("maxEvents reached")}else m.push(r)},request(e,t,n,o,c,l){const h=Date.now(),v={method:o?.method??"",url:W(o),headers:I(o?.headers),body:U(o)};if(e)return void(b={protocol:a?"sse":"http",request:v,response:{status:0,statusText:"Request failed",headers:{},timings:{startedAt:s,endedAt:h,durationMs:h-s},sizeBytes:y},error:r(e),replays:g});const w=L(n,"content-type");let S,x;if((f(w)||d(w))&&(a=!0),!a){const e=m.length?Buffer.concat(m):n?.stream?Buffer.from(n.stream):Buffer.alloc(0);S=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"),x=function(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}}(S,w)}b={protocol:a?"sse":"http",request:v,response:{status:"number"==typeof n?.code?n.code:0,statusText:z(n),headers:I(n?.headers),contentType:w,...a?{events:p}:{body:x,text:S},timings:{startedAt:s,endedAt:h,durationMs:"number"==typeof n?.responseTime?n.responseTime:h-s,firstByteMs:i?i-s:void 0},sizeBytes:y||n?.responseSize||0,...u?{truncated:!0}:{}},cookies:Array.isArray(l)?l.map(e=>({name:String(e?.name??""),value:String(e?.value??""),domain:e?.domain,path:e?.path})):[],replays:g}},io(e,t,r,n,o){"http"===r?.type&&r.source&&"collection"!==r.source&&g.push({url:W(o),method:o?.method??"",status:"number"==typeof n?.code?n.code:0,reason:String(r.source)})},exception(e,t){h.console.push({level:"error",messages:[`[exception] ${r(t).message}`],at:Date.now()})},done(e){if(e&&!b&&!c)return w=P(w),S=P(S),void o.reject(t("RUNTIME_RUN",e.message??"Run failed",e));_()}})}),o.promise}function R(e){try{e()}catch{}}function L(e,t){try{const r=e?.headers?.get?.(t);return null==r?void 0:String(r)}catch{return}}function z(e){try{return String("function"==typeof e?.reason?e.reason()??"":e?.status??"")}catch{return""}}function W(e){try{return"function"==typeof e?.url?.toString?e.url.toString():""}catch{return""}}var F="__protokit_cycle__";function J(e){const r=new Map;function n(r){if("string"!=typeof r||!r.startsWith("#/"))throw t("EXTERNAL_REF",`Only local $ref pointers are supported, got: ${r}`);let n=e;const o=r.slice(2).split("/");for(const e of o){if(null==n||"object"!=typeof n)throw t("BAD_REF",`Cannot resolve pointer "${r}"`);n=n[decodeURIComponent(e).replace(/~1/g,"/").replace(/~0/g,"~")]}if(void 0===n)throw t("BAD_REF",`Pointer "${r}" resolves to undefined`);return n}function o(e){let t=e;const r=new Set;let o=0;for(;t&&"object"==typeof t&&"string"==typeof t.$ref;){if(r.has(t.$ref)||++o>100)return{type:"object",[F]:!0};r.add(t.$ref),t=n(t.$ref)}return t}function s(e,t=0,r=new Set){if(null==e||"object"!=typeof e)return e;if(t>32)return{type:"object"};const n=o(e);if(null==n||"object"!=typeof n)return n;if(n[F])return{type:"object"};if(r.has(n))return{type:"object"};const i=new Set(r);if(i.add(n),Array.isArray(n))return n.map(e=>s(e,t+1,i));const a={};for(const[e,r]of Object.entries(n))e!==F&&(a[e]=s(r,t+1,i));return a}return{deref:o,deepDeref:function(e){const t=e&&"object"==typeof e?e.$ref:void 0;if("string"==typeof t&&r.has(t))return r.get(t);const n=s(e);return"string"==typeof t&&r.set(t,n),n},byPointer:n}}var H=["get","put","post","delete","options","head","patch","trace","query"];function V(e,r){if(!e||"object"!=typeof e)throw t("BAD_SPEC","spec must be an object");if("string"!=typeof e.openapi)throw t("BAD_SPEC","spec.openapi version string is required");if(!r||"object"!=typeof r)throw t("BAD_TARGET","target is required");const n=J(e),o=e.paths;if(!o||"object"!=typeof o)throw t("BAD_SPEC","spec.paths is missing or invalid");const s=[];for(const[e,t]of Object.entries(o)){let r;try{r=n.deref(t)}catch{continue}if(!r||"object"!=typeof r)continue;for(const t of H)r[t]&&"object"==typeof r[t]&&s.push({path:e,method:t,rawOperation:r[t],pathItem:r,isCustomMethod:!1});const o=r.additionalOperations;if(o&&"object"==typeof o)for(const[t,n]of Object.entries(o))n&&"object"==typeof n&&s.push({path:e,method:t.toLowerCase(),rawOperation:n,pathItem:r,isCustomMethod:!0})}if(!s.length)throw t("EMPTY_SPEC","The document does not declare any operation");let i;if(r.operationId){if(i=s.find(e=>{try{return n.deref(e.rawOperation)?.operationId===r.operationId}catch{return!1}}),!i)throw t("OP_NOT_FOUND",`operationId "${r.operationId}" was not found`)}else{if(!r.path||!r.method)throw t("BAD_TARGET","Provide either operationId, or both path and method");const e=String(r.method).toLowerCase();if(i=s.find(t=>t.path===r.path&&t.method===e),!i)throw t("OP_NOT_FOUND",`Operation "${String(r.method).toUpperCase()} ${r.path}" was not found`)}const a=n.deepDeref(i.rawOperation)??{},c=n.deref(i.pathItem)??{},u=new Map,l=e=>{if(Array.isArray(e))for(const t of e){let e;try{e=n.deepDeref(t)}catch{continue}e&&"string"==typeof e.name&&"string"==typeof e.in&&u.set(`${e.in}:${e.name}`,e)}};l(c.parameters),l(i.rawOperation.parameters);const p=Array.isArray(a.servers)&&a.servers.length&&a.servers||Array.isArray(c.servers)&&c.servers.length&&c.servers||Array.isArray(e.servers)&&e.servers.length&&e.servers||[{url:"/"}];return{path:i.path,method:i.method,isCustomMethod:i.isCustomMethod,operation:a,pathItem:c,parameters:Array.from(u.values()),servers:p,security:a.security??e.security}}var G=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=S(e.located,e.spec,e.options);return{...t,environment:u(`${e.spec?.info?.title??"API"} Environment`,t.baseUrl,e.options.variables),streaming:p(e.located.operation,e.options.values)}}execute(e,t){return B({collectionJson:e.collection,baseUrl:e.baseUrl,streamingHint:e.streaming},t)}};function K(e,r,n){const o=n.websocket??{},s=e.operation?.["x-websocket"]??{},i={...n.variables??{}};let c;if(o.url)c=o.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(/^\/+/,"")}`}(a(e.servers,n)),r=e.path.replace(/\{([^}]+)\}/g,(e,t)=>{const r=n.values?.path?.[t];return null==r?e:encodeURIComponent(String(r))});c=`${t.replace(/\/+$/,"")}/${r.replace(/^\//,"")}`}c=$(c,{baseUrl:"",...i});try{const e=new URL(c);for(const[t,r]of Object.entries(n.values?.query??{}))null!=r&&e.searchParams.set(t,String(r));"apikey"===n.auth?.type&&"query"===n.auth.in&&e.searchParams.set(n.auth.key??"api_key",n.auth.value??""),c=e.toString()}catch{throw t("BAD_WS_URL",`Resolved WebSocket URL is invalid: ${c}`)}const u={};for(const[e,t]of Object.entries(n.values?.header??{}))null!=t&&(u[e]=String(t));for(const[e,t]of Object.entries(s.headers??{}))null!=t&&(u[e]=$(String(t),i));for(const[e,t]of Object.entries(o.headers??{}))null!=t&&(u[e]=$(String(t),i));const l=n.auth;if(l&&"none"!==l.type&&!Object.keys(u).some(e=>"authorization"===e.toLowerCase()))if("bearer"===l.type)u.Authorization=`Bearer ${l.token??""}`;else if("basic"===l.type){const e=`${l.username??""}:${l.password??""}`;u.Authorization=`Basic ${Buffer.from(e,"utf8").toString("base64")}`}else"apikey"===l.type&&"header"===(l.in??"header")&&(u[l.key??"X-API-Key"]=l.value??"");const p=o.send??s.send??[],f=(Array.isArray(p)?p:[p]).map(e=>function(e){if(null==e)return null;if("string"==typeof e)return e;if(e instanceof Uint8Array)return e;try{return JSON.stringify(e)}catch{return null}}("string"==typeof e?$(e,i):e)).filter(e=>null!==e),d=o.keepAlive??s.keepAlive;return{url:c,subprotocols:o.subprotocols??s.subprotocols??[],headers:u,send:f,sendDelayMs:X(o.sendDelayMs,0),maxMessages:X(o.maxMessages??n.maxEvents,100),maxSessionMs:X(o.maxSessionMs??n.maxStreamMs,3e4),idleTimeoutMs:X(o.idleTimeoutMs,0),keepAlive:d?{intervalMs:X(d.intervalMs,15e3),payload:String(d.payload??"ping")}:void 0,closeCode:o.closeCode??1e3,closeReason:o.closeReason??"Client finished sampling",rejectUnauthorized:!1!==o.rejectUnauthorized,maxPayloadBytes:X(o.maxPayloadBytes,262144),clientOptions:o.clientOptions??{}}}function X(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?t:r}import Y from"ws";var Z=new Set([1e3,1001,1005]);function Q(e,t){const n=E(),o=Date.now();let s,i=0,a=0,c=0,u=!1,l=!1;const p=[],f={};let d,m,y=0,h=null,g=null,b=null;const v=[];let w;try{w=new Y(e.url,e.subprotocols,{headers:e.headers,handshakeTimeout:Math.max(5e3,Math.min(e.maxSessionMs,3e4)),rejectUnauthorized:e.rejectUnauthorized,maxPayload:4*e.maxPayloadBytes,...e.clientOptions})}catch(e){return Promise.resolve(S(r(e)))}function S(t){const r=Date.now(),n=!t&&y>0&&y<400;return{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:y||(t?0:101),statusText:t?"WebSocket error":n?"Switching Protocols":"Connection closed",headers:f,contentType:"application/json",events:p,timings:{startedAt:o,endedAt:r,durationMs:r-o,firstByteMs:s?s-o:void 0},sizeBytes:c,...u?{truncated:!0}:{}},...d?{cookies:[]}:{},...t?{error:t}:{}}}const x=e=>{n.settled||((()=>{if(h=P(h),g=P(g),b){try{clearInterval(b)}catch{}b=null}for(const e of v.splice(0))P(e)})(),n.resolve(S(e??m)))},j=t=>{if(l)return;l=!0,u=!0;try{w.readyState===Y.OPEN?w.close(e.closeCode,`${e.closeReason}: ${t}`.slice(0,120)):w.terminate()}catch{}const r=setTimeout(()=>{try{w.terminate()}catch{}x()},3e3);"object"==typeof r&&"function"==typeof r.unref&&r.unref(),v.push(r)},A=()=>{e.idleTimeoutMs&&(g=P(g),g=setTimeout(()=>j("idle timeout"),e.idleTimeoutMs),"object"==typeof g&&"function"==typeof g.unref&&g.unref())},k=e=>{p.push(e);try{t.onEvent?.(e)}catch{}};return w.on("upgrade",e=>{y=e?.statusCode??101;for(const[t,r]of Object.entries(e?.headers??{}))f[t]=Array.isArray(r)?r.join(", "):String(r)}),w.on("unexpected-response",(e,t)=>{y=t?.statusCode??0;for(const[e,r]of Object.entries(t?.headers??{}))f[e]=Array.isArray(r)?r.join(", "):String(r);m={message:`Handshake rejected with HTTP ${y}`,code:"WS_HANDSHAKE_FAILED"};try{t?.destroy?.()}catch{}x(m)}),w.on("open",()=>{s=Date.now(),d=w.protocol||void 0,y||(y=101);try{t.onOpen?.({url:e.url,protocol:d,headers:f})}catch{}e.send.forEach((t,n)=>{const o=()=>{w.readyState===Y.OPEN&&w.send(t,e=>{e?m=m??r(e):(a+=1,k({id:String(a),event:"string"==typeof t?"text":"binary",data:"string"==typeof t?t:`<binary ${t.byteLength} bytes>`,parsed:"string"==typeof t?ee(t):void 0,receivedAt:Date.now(),direction:"out"}))})},s=e.sendDelayMs*n;if(s<=0)o();else{const e=setTimeout(o,s);"object"==typeof e&&"function"==typeof e.unref&&e.unref(),v.push(e)}}),e.keepAlive&&(b=setInterval(()=>{if(w.readyState===Y.OPEN)try{w.ping(e.keepAlive.payload)}catch{}},e.keepAlive.intervalMs),"object"==typeof b&&"function"==typeof b.unref&&b.unref()),A()}),w.on("message",(t,r)=>{if(l)return;const n=function(e){return Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e)}(t);c+=n.length,a+=1,i+=1;const o=n.length>e.maxPayloadBytes,s=r?`<binary ${n.length} bytes>`:o?`${n.subarray(0,e.maxPayloadBytes).toString("utf8")}...`:n.toString("utf8");k({id:String(a),event:r?"binary":"text",data:s,parsed:r||o?void 0:ee(s),receivedAt:Date.now(),direction:"in"}),A(),i>=e.maxMessages&&j("maxMessages reached")}),w.on("ping",e=>{a+=1,k({id:String(a),event:"ping",data:e?.length?e.toString("utf8"):"",receivedAt:Date.now(),direction:"in"}),A()}),w.on("error",e=>{m=m??r(e),w.readyState===Y.CLOSED&&x(m)}),w.on("close",(e,t)=>{const r=t?.length?t.toString("utf8"):"";m||Z.has(e)||l||(m={message:`Connection closed with code ${e}${r?`: ${r}`:""}`,code:String(e)}),x(m)}),h=setTimeout(()=>j("maxSessionMs reached"),e.maxSessionMs),"object"==typeof h&&"function"==typeof h.unref&&h.unref(),n.promise}function ee(e){const t=e.trim();if(t&&/^[[{"\-\d]|^(true|false|null)$/.test(t))try{return JSON.parse(t)}catch{return}}var te=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=K(e.located,e.spec,e.options);return{config:t,environment:{id:`protokit-ws-env-${Date.now().toString(36)}`,name:`${e.spec?.info?.title??"API"} WebSocket Environment`,values:[{key:"wsUrl",value:t.url,type:"default",enabled:!0},...Object.entries(e.options.variables??{}).map(([e,t])=>({key:e,value:String(t??""),type:/token|secret|password|apikey/i.test(e)?"secret":"default",enabled:!0}))],_postman_variable_scope:"environment"}}}execute(e,t){return Q(e.config,t)}},re=["null","boolean","integer","number","string","array","object"],ne=e=>null==e?[]:Array.isArray(e)?e.filter(e=>"string"==typeof e):"string"==typeof e?[e]:[];function oe(e,t,r=0){if(!e||"object"!=typeof e)return t??e;if(!t||"object"!=typeof t)return e;if(r>20)return{};if("string"==typeof e.$ref)return e;if("string"==typeof t.$ref)return t;const n={};let o=Array.from(new Set([...ne(e.type),...ne(t.type)]));if(o.includes("integer")&&o.includes("number")&&(o=o.filter(e=>"integer"!==e)),o.sort((e,t)=>re.indexOf(e)-re.indexOf(t)),1===o.length?n.type=o[0]:o.length>1&&(n.type=o),e.format&&e.format===t.format&&(n.format=e.format),e.properties||t.properties){const o={...e.properties??{}};for(const[e,n]of Object.entries(t.properties??{}))o[e]=o[e]?oe(o[e],n,r+1):n;n.properties=o;const s=Array.isArray(e.required)?e.required:[],i=Array.isArray(t.required)?t.required:[];if(e.properties&&t.properties){const e=s.filter(e=>i.includes(e));e.length&&(n.required=e)}else{const t=e.properties?s:i;t.length&&(n.required=t)}}if((e.items||t.items)&&(n.items=oe(e.items,t.items,r+1)),e.additionalProperties||t.additionalProperties){const o=e.additionalProperties,s=t.additionalProperties;n.additionalProperties="object"==typeof o&&"object"==typeof s?oe(o,s,r+1):o??s}Array.isArray(e.enum)&&Array.isArray(t.enum)&&(n.enum=Array.from(new Set([...e.enum,...t.enum])).slice(0,50));const s=function(e){const t=new Set,r=[];for(const n of e){let e;try{e=JSON.stringify(n)}catch{continue}t.has(e)||(t.add(e),r.push(n))}return r}([...e.examples??[],...t.examples??[]]).slice(0,3);s.length&&(n.examples=s);for(const r of["title","description","deprecated","readOnly","writeOnly"])void 0===e[r]&&void 0===t[r]||(n[r]=e[r]??t[r]);return n}var se=/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/,ie=/^\d{4}-\d{2}-\d{2}$/,ae=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ce=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,ue=/^https?:\/\/\S+$/i;function le(e,t={},r=0){const n=t.maxDepth??12,o=!1!==t.includeExamples;if(r>n)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("string"===s){const r=e,n={type:"string"};if(se.test(r)?n.format="date-time":ie.test(r)?n.format="date":ae.test(r)?n.format="uuid":ue.test(r)?n.format="uri":ce.test(r)&&(n.format="email"),o){const e=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.min(e.length,t.sampleArrayItems??20);let o=le(e[0],t,r+1);for(let s=1;s<n;s+=1)o=oe(o,le(e[s],t,r+1),0);return{type:"array",items:o}}if("object"===s){const n={},o=[];for(const[s,i]of Object.entries(e))n[s]=le(i,t,r+1),null!=i&&o.push(s);const s={type:"object",properties:n};return o.length&&(s.required=o),s}return{}}function pe(e,t={}){let r=null;for(const n of e)r=r?oe(r,le(n,t),0):le(n,t);return r??{}}var fe=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-amzn-requestid","x-amz-cf-id","cf-ray","cf-cache-status","x-served-by","x-timer","x-cache"]),de=new Set(["[DONE]","DONE","[done]"]);function me(e,t={}){const{response:r}=e,n=r.status>0?String(r.status):"default",o=(s=r.contentType)&&s.split(";")[0].trim().toLowerCase()||"application/octet-stream";var s;const i=!1!==t.includeExamples,a=t.maxExampleChars??4e3,c={description:r.statusText||he(r.status)},u=function(e){const t={};for(const[r,n]of Object.entries(e??{})){const e=r.toLowerCase();"content-type"===e||fe.has(e)||(t[r]={schema:{type:"string",examples:[String(n)]}})}return Object.keys(t).length?t:void 0}(r.headers);if(u&&(c.headers=u),("sse"===e.protocol||"websocket"===e.protocol)&&Array.isArray(r.events)){const t=r.events.filter(e=>!function(e){if(de.has(e.data.trim()))return!0;const t=(e.event??"").toLowerCase();return"done"===t||"end"===t||"complete"===t}(e));if(!t.length)return{statusCode:n,response:c};let s=null,i=!0;for(const e of t)if(void 0!==e.parsed)s=oe(s,le(e.parsed),0);else{i=!1;s=oe(s,{type:"string",examples:[e.data.length>200?`${e.data.slice(0,200)}...`:e.data]},0)}const a=Array.from(new Set(t.map(e=>e.event).filter(e=>!!e))),u={type:"object",properties:{id:{type:"string"},event:a.length?{type:"string",enum:a}:{type:"string"},data:i?s??{type:"object"}:s??{type:"string"},retry:{type:"integer"}},required:["data"]},l="sse"===e.protocol?"text/event-stream":o;return c.content={[l]:{itemSchema:u,"x-protokit-sample-count":t.length,...r.truncated?{"x-protokit-truncated":!0}:{}}},{statusCode:n,response:c}}if(void 0!==r.body&&null!==r.body){const e={schema:le(r.body)};i&&(e.examples={capturedSample:{summary:"Captured from a live call",value:ye(r.body,a)}}),c.content={[o]:e}}else if("string"==typeof r.text&&r.text.length){const e={schema:{type:"string"}};i&&(e.examples={capturedSample:{value:r.text.slice(0,a)}}),c.content={[o]:e}}else 204!==r.status&&r.sizeBytes>0&&(c.content={[o]:{schema:{type:"string",format:"binary"}}});return{statusCode:n,response:c}}function ye(e,t){try{const r=JSON.stringify(e);return r&&r.length<=t?e:{"x-protokit-truncated":!0,preview:String(r).slice(0,t)}}catch{return String(e).slice(0,t)}}function he(e){return e>=500?"Server error":e>=400?"Client error":e>=300?"Redirection":e>=200?"Successful response":"Response"}function ge(e,r,n,o,s={}){if(!e||"object"!=typeof e)throw t("BAD_SPEC","spec must be an object");const i=k(e),a=i.paths?.[r];if(!a)throw t("PATH_NOT_FOUND",`Path "${r}" is not present in the document`);const c=a[String(n).toLowerCase()]??a.additionalOperations?.[n.toUpperCase()]??a.additionalOperations?.[n];if(!c||"object"!=typeof c)throw t("OP_NOT_FOUND",`Operation "${n.toUpperCase()} ${r}" is not present in the document`);const u=o.statusCode;if(s.allowedStatusCodes?.length&&!s.allowedStatusCodes.includes(u))return i;c.responses&&"object"==typeof c.responses||(c.responses={});const l=k(o.response);if("replace"===s.strategy||!c.responses[u])return c.responses[u]=l,i;const p=c.responses[u];if("string"==typeof p.$ref)return i;if(!1!==s.keepExistingDescription&&p.description||(p.description=l.description??p.description),l.headers&&(p.headers={...p.headers??{},...l.headers}),l.content){p.content&&"object"==typeof p.content||(p.content={});for(const[e,t]of Object.entries(l.content)){const r=p.content[e];if(!r){p.content[e]=t;continue}const n=!1!==s.protectComponentRefs;t.itemSchema&&(r.itemSchema=n&&"string"==typeof r.itemSchema?.$ref?r.itemSchema:oe(r.itemSchema,t.itemSchema,0)),t.schema&&(r.schema=n&&"string"==typeof r.schema?.$ref?r.schema:oe(r.schema,t.schema,0)),t.examples&&(r.examples={...r.examples??{},...t.examples});for(const e of Object.keys(t))e.startsWith("x-")&&(r[e]=t[e])}}return i}function be(e={}){const o=new n,s=e.adapters??[new G,new te];for(const t of[...s,...e.extraAdapters??[]])o.register(t);const i=e=>{if(!e||"object"!=typeof e)throw t("BAD_OPTIONS","send() requires an options object");const r=V(e.spec,e.target),n={spec:e.spec,options:e,located:r},s=o.resolve(n),i=s.plan(n);return{located:r,adapter:s,plan:i}};return{registry:o,toCollection(e,t,r={}){const n={...r,spec:e,target:t},{located:o,adapter:s,plan:a}=i(n),c=a;return{protocol:s.name,located:o,collection:c?.collection,environment:c?.environment,streaming:c?.streaming,plan:a}},async send(n){const{located:o,adapter:s,plan:a}=i(n);let c;try{c=await s.execute(a,n)}catch(e){throw t("EXECUTION_FAILED",`Adapter "${s.name}" failed: ${r(e).message}`,e)}const u=me(c,e.response),l=a;let p,f;if(!1===n.writeBack)f="disabled by options.writeBack";else if(c.response.status<=0)f="no response was received";else if(c.scripts?.skipped)f="request was skipped by a script";else if(!1!==e.writeBack?.requirePassingTests&&!1===c.scripts?.passed)f="one or more assertions failed";else try{p=ge(n.spec,o.path,o.method,u,e.writeBack)}catch(e){f=`write-back error: ${r(e).message}`}return{...c,collection:l?.collection,environment:l?.environment,responseFragment:u.response,responseStatusCode:u.statusCode,patchedSpec:p,writeBackSkippedReason:f}},async sendMany(e,t,n={}){let o=e;const s=[];for(const e of t)try{const t=await this.send({...n,...e,spec:o});t.patchedSpec&&(o=t.patchedSpec),s.push(t)}catch(t){s.push({target:e.target,error:r(t).message})}return{spec:o,results:s}}}}export{n as AdapterRegistry,g as BUILTIN_CAPTURE_TEST,G as HttpAdapter,e as ProtoKitError,te as WebSocketAdapter,be as createDebugger,le as inferSchema,pe as inferSchemaFromMany,V as locateOperation,oe as mergeSchema,o as sampleFromSchema,me as toResponseObject,ge as writeBackResponse};
|