@swifty.js/swifty 0.0.24 → 0.0.25
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.
|
@@ -19,7 +19,7 @@ ${ce}`,d++}else pp(E,B,z)?p=E.slice(E.charCodeAt(B+6)===qt?B+7:B+6,M)||void 0:y(
|
|
|
19
19
|
${vl}`,d++;return}if(pp(E,B,z)){p=E.slice(E.charCodeAt(B+6)===qt?B+7:B+6,M)||void 0;return}if(z===105&&E.charCodeAt(B+1)===100&&E.charCodeAt(B+2)===58){let mt=E.slice(E.charCodeAt(B+3)===qt?B+4:B+3,M);u=mt.includes("\0")?void 0:mt;return}if(z===58){if(o){let mt=E.slice(B,M);o(mt.slice(E.charCodeAt(B+1)===qt?2:1))}return}let D=E.slice(B,M),ce=D.indexOf(":");if(ce===-1){w(D,"",D);return}let qr=D.slice(0,ce),ao=D.charCodeAt(ce+1)===qt?2:1,co=D.slice(ce+ao);w(qr,co,D)}function w(E,B,M){switch(E){case"event":p=B||void 0;break;case"data":l=d===0?B:`${l}
|
|
20
20
|
${B}`,d++;break;case"id":u=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?s(parseInt(B,10)):r(new xs(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:M}));break;default:r(new xs(`Unknown field "${E.length>20?`${E.slice(0,20)}\u2026`:E}"`,{type:"unknown-field",field:E,value:B,line:M}));break}}function I(){d>0&&e({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0}function v(E={}){if(E.consume&&i.length>0){let B=i.join("");y(B,0,B.length)}c=!0,u=void 0,l="",d=0,p=void 0,i.length=0,a=0,m=!1}return{feed:g,reset:v}}function Ap(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function pp(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var hn=class extends Event{constructor(e,r){var s,o;super(e),this.code=(s=r?.code)!=null?s:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,s){return s(mp(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(mp(this),r)}};function BQ(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Sc(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Sc).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Sc(t.cause)}`:t.message:`${t}`}function mp(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var gp=t=>{throw TypeError(t)},Dc=(t,e,r)=>e.has(t)||gp("Cannot "+r),q=(t,e,r)=>(Dc(t,e,"read from private field"),r?r.call(t):e.get(t)),de=(t,e,r)=>e.has(t)?gp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),se=(t,e,r,s)=>(Dc(t,e,"write to private field"),e.set(t,r),r),at=(t,e,r)=>(Dc(t,e,"access private method"),r),xe,Gt,Qr,gn,En,Ds,kr,$s,kt,_r,Mr,Sr,Ts,He,kc,Mc,vc,fp,bc,xc,Rs,Tc,Rc,Ht=class extends EventTarget{constructor(e,r){var s,o;super(),de(this,He),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,de(this,xe),de(this,Gt),de(this,Qr),de(this,gn),de(this,En),de(this,Ds),de(this,kr),de(this,$s,null),de(this,kt),de(this,_r),de(this,Mr,null),de(this,Sr,null),de(this,Ts,null),de(this,Mc,async n=>{var i;q(this,_r).reset();let{body:a,redirected:c,status:u,headers:l}=n;if(u===204){at(this,He,Rs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?se(this,Qr,new URL(n.url)):se(this,Qr,void 0),u!==200){at(this,He,Rs).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){at(this,He,Rs).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(q(this,xe)===this.CLOSED)return;se(this,xe,this.OPEN);let d=new Event("open");if((i=q(this,Ts))==null||i.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){at(this,He,Rs).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,m=a.getReader(),g=!0;do{let{done:f,value:h}=await m.read();h&&q(this,_r).feed(p.decode(h,{stream:!f})),f&&(g=!1,q(this,_r).reset(),at(this,He,Tc).call(this))}while(g)}),de(this,vc,n=>{se(this,kt,void 0),!(n.name==="AbortError"||n.type==="aborted")&&at(this,He,Tc).call(this,Sc(n))}),de(this,bc,n=>{typeof n.id=="string"&&se(this,$s,n.id);let i=new MessageEvent(n.event||"message",{data:n.data,origin:q(this,Qr)?q(this,Qr).origin:q(this,Gt).origin,lastEventId:n.id||""});q(this,Sr)&&(!n.event||n.event==="message")&&q(this,Sr).call(this,i),this.dispatchEvent(i)}),de(this,xc,n=>{se(this,Ds,n)}),de(this,Rc,()=>{se(this,kr,void 0),q(this,xe)===this.CONNECTING&&at(this,He,kc).call(this)});try{if(e instanceof URL)se(this,Gt,e);else if(typeof e=="string")se(this,Gt,new URL(e,QQ()));else throw new Error("Invalid URL")}catch{throw BQ("An invalid or illegal string was specified")}se(this,_r,fn({onEvent:q(this,bc),onRetry:q(this,xc)})),se(this,xe,this.CONNECTING),se(this,Ds,3e3),se(this,En,(s=r?.fetch)!=null?s:globalThis.fetch),se(this,gn,(o=r?.withCredentials)!=null?o:!1),at(this,He,kc).call(this)}get readyState(){return q(this,xe)}get url(){return q(this,Gt).href}get withCredentials(){return q(this,gn)}get onerror(){return q(this,Mr)}set onerror(e){se(this,Mr,e)}get onmessage(){return q(this,Sr)}set onmessage(e){se(this,Sr,e)}get onopen(){return q(this,Ts)}set onopen(e){se(this,Ts,e)}addEventListener(e,r,s){let o=r;super.addEventListener(e,o,s)}removeEventListener(e,r,s){let o=r;super.removeEventListener(e,o,s)}close(){q(this,kr)&&clearTimeout(q(this,kr)),q(this,xe)!==this.CLOSED&&(q(this,kt)&&q(this,kt).abort(),se(this,xe,this.CLOSED),se(this,kt,void 0))}};xe=new WeakMap,Gt=new WeakMap,Qr=new WeakMap,gn=new WeakMap,En=new WeakMap,Ds=new WeakMap,kr=new WeakMap,$s=new WeakMap,kt=new WeakMap,_r=new WeakMap,Mr=new WeakMap,Sr=new WeakMap,Ts=new WeakMap,He=new WeakSet,kc=function(){se(this,xe,this.CONNECTING),se(this,kt,new AbortController),q(this,En)(q(this,Gt),at(this,He,fp).call(this)).then(q(this,Mc)).catch(q(this,vc))},Mc=new WeakMap,vc=new WeakMap,fp=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...q(this,$s)?{"Last-Event-ID":q(this,$s)}:void 0},cache:"no-store",signal:(t=q(this,kt))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},bc=new WeakMap,xc=new WeakMap,Rs=function(t,e){var r;q(this,xe)!==this.CLOSED&&se(this,xe,this.CLOSED);let s=new hn("error",{code:e,message:t});(r=q(this,Mr))==null||r.call(this,s),this.dispatchEvent(s)},Tc=function(t,e){var r;if(q(this,xe)===this.CLOSED)return;se(this,xe,this.CONNECTING);let s=new hn("error",{code:e,message:t});(r=q(this,Mr))==null||r.call(this,s),this.dispatchEvent(s),se(this,kr,setTimeout(q(this,Rc),q(this,Ds)))},Rc=new WeakMap,Ht.CONNECTING=0,Ht.OPEN=1,Ht.CLOSED=2;function QQ(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function vr(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function yn(t=fetch,e){return e?async(r,s)=>{let o={...e,...s,headers:s?.headers?{...vr(e.headers),...vr(s.headers)}:e.headers};return t(r,o)}:t}var $c;$c=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function _Q(t){return(await $c).getRandomValues(new Uint8Array(t))}async function SQ(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,s="";for(;s.length<t;){let o=await _Q(t-s.length);for(let n of o)n<r&&(s+=e[n%e.length])}return s}async function kQ(t){return await SQ(t)}async function MQ(t){let e=await(await $c).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Pc(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await kQ(t),r=await MQ(e);return{code_verifier:e,code_challenge:r}}var Ee=$l().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:zl.custom,message:"URL must be parseable",fatal:!0}),bl}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Ep=le({resource:A().url(),authorization_servers:_(Ee).optional(),jwks_uri:A().url().optional(),scopes_supported:_(A()).optional(),bearer_methods_supported:_(A()).optional(),resource_signing_alg_values_supported:_(A()).optional(),resource_name:A().optional(),resource_documentation:A().optional(),resource_policy_uri:A().url().optional(),resource_tos_uri:A().url().optional(),tls_client_certificate_bound_access_tokens:K().optional(),authorization_details_types_supported:_(A()).optional(),dpop_signing_alg_values_supported:_(A()).optional(),dpop_bound_access_tokens_required:K().optional()}),jc=le({issuer:A(),authorization_endpoint:Ee,token_endpoint:Ee,registration_endpoint:Ee.optional(),scopes_supported:_(A()).optional(),response_types_supported:_(A()),response_modes_supported:_(A()).optional(),grant_types_supported:_(A()).optional(),token_endpoint_auth_methods_supported:_(A()).optional(),token_endpoint_auth_signing_alg_values_supported:_(A()).optional(),service_documentation:Ee.optional(),revocation_endpoint:Ee.optional(),revocation_endpoint_auth_methods_supported:_(A()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(A()).optional(),introspection_endpoint:A().optional(),introspection_endpoint_auth_methods_supported:_(A()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(A()).optional(),code_challenge_methods_supported:_(A()).optional(),client_id_metadata_document_supported:K().optional()}),vQ=le({issuer:A(),authorization_endpoint:Ee,token_endpoint:Ee,userinfo_endpoint:Ee.optional(),jwks_uri:Ee,registration_endpoint:Ee.optional(),scopes_supported:_(A()).optional(),response_types_supported:_(A()),response_modes_supported:_(A()).optional(),grant_types_supported:_(A()).optional(),acr_values_supported:_(A()).optional(),subject_types_supported:_(A()),id_token_signing_alg_values_supported:_(A()),id_token_encryption_alg_values_supported:_(A()).optional(),id_token_encryption_enc_values_supported:_(A()).optional(),userinfo_signing_alg_values_supported:_(A()).optional(),userinfo_encryption_alg_values_supported:_(A()).optional(),userinfo_encryption_enc_values_supported:_(A()).optional(),request_object_signing_alg_values_supported:_(A()).optional(),request_object_encryption_alg_values_supported:_(A()).optional(),request_object_encryption_enc_values_supported:_(A()).optional(),token_endpoint_auth_methods_supported:_(A()).optional(),token_endpoint_auth_signing_alg_values_supported:_(A()).optional(),display_values_supported:_(A()).optional(),claim_types_supported:_(A()).optional(),claims_supported:_(A()).optional(),service_documentation:A().optional(),claims_locales_supported:_(A()).optional(),ui_locales_supported:_(A()).optional(),claims_parameter_supported:K().optional(),request_parameter_supported:K().optional(),request_uri_parameter_supported:K().optional(),require_request_uri_registration:K().optional(),op_policy_uri:Ee.optional(),op_tos_uri:Ee.optional(),client_id_metadata_document_supported:K().optional()}),yp=k({...vQ.shape,...jc.pick({code_challenge_methods_supported:!0}).shape}),wp=k({access_token:A(),id_token:A().optional(),token_type:A(),expires_in:Ul.number().optional(),scope:A().optional(),refresh_token:A().optional()}).strip(),Cp=k({error:A(),error_description:A().optional(),error_uri:A().optional()}),hp=Ee.optional().or(b("").transform(()=>{})),bQ=k({redirect_uris:_(Ee),token_endpoint_auth_method:A().optional(),grant_types:_(A()).optional(),response_types:_(A()).optional(),client_name:A().optional(),client_uri:Ee.optional(),logo_uri:hp,scope:A().optional(),contacts:_(A()).optional(),tos_uri:hp,policy_uri:A().optional(),jwks_uri:Ee.optional(),jwks:jl().optional(),software_id:A().optional(),software_version:A().optional(),software_statement:A().optional()}).strip(),xQ=k({client_id:A(),client_secret:A().optional(),client_id_issued_at:J().optional(),client_secret_expires_at:J().optional()}).strip(),Ip=bQ.merge(xQ),NR=k({error:A(),error_description:A().optional()}).strip(),zR=k({token:A(),token_type_hint:A().optional()}).strip();function Bp(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Qp({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),s=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==s.origin||r.pathname.length<s.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return o.startsWith(n)}var ae=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Ps=class extends ae{};Ps.errorCode="invalid_request";var Yt=class extends ae{};Yt.errorCode="invalid_client";var Jt=class extends ae{};Jt.errorCode="invalid_grant";var Wt=class extends ae{};Wt.errorCode="unauthorized_client";var js=class extends ae{};js.errorCode="unsupported_grant_type";var Ns=class extends ae{};Ns.errorCode="invalid_scope";var zs=class extends ae{};zs.errorCode="access_denied";var ct=class extends ae{};ct.errorCode="server_error";var Us=class extends ae{};Us.errorCode="temporarily_unavailable";var Fs=class extends ae{};Fs.errorCode="unsupported_response_type";var Os=class extends ae{};Os.errorCode="unsupported_token_type";var Ls=class extends ae{};Ls.errorCode="invalid_token";var qs=class extends ae{};qs.errorCode="method_not_allowed";var Gs=class extends ae{};Gs.errorCode="too_many_requests";var Vt=class extends ae{};Vt.errorCode="invalid_client_metadata";var Hs=class extends ae{};Hs.errorCode="insufficient_scope";var Ys=class extends ae{};Ys.errorCode="invalid_target";var _p={[Ps.errorCode]:Ps,[Yt.errorCode]:Yt,[Jt.errorCode]:Jt,[Wt.errorCode]:Wt,[js.errorCode]:js,[Ns.errorCode]:Ns,[zs.errorCode]:zs,[ct.errorCode]:ct,[Us.errorCode]:Us,[Fs.errorCode]:Fs,[Os.errorCode]:Os,[Ls.errorCode]:Ls,[qs.errorCode]:qs,[Gs.errorCode]:Gs,[Vt.errorCode]:Vt,[Hs.errorCode]:Hs,[Ys.errorCode]:Ys};var _e=class extends Error{constructor(e){super(e??"Unauthorized")}};function TQ(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Nc="code",zc="S256";function RQ(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&TQ(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function DQ(t,e,r,s){let{client_id:o,client_secret:n}=e;switch(t){case"client_secret_basic":$Q(o,n,r);return;case"client_secret_post":PQ(o,n,s);return;case"none":jQ(o,s);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function $Q(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let s=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${s}`)}function PQ(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function jQ(t,e){e.set("client_id",t)}async function kp(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let s=Cp.parse(JSON.parse(r)),{error:o,error_description:n,error_uri:i}=s,a=_p[o]||ct;return new a(n||"",i)}catch(s){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${s}. Raw body: ${r}`;return new ct(o)}}async function lt(t,e){try{return await Uc(t,e)}catch(r){if(r instanceof Yt||r instanceof Wt)return await t.invalidateCredentials?.("all"),await Uc(t,e);if(r instanceof Jt)return await t.invalidateCredentials?.("tokens"),await Uc(t,e);throw r}}async function Uc(t,{serverUrl:e,authorizationCode:r,scope:s,resourceMetadataUrl:o,fetchFn:n}){let i=await t.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await vp(c,{fetchFn:n}),!a)try{a=await Mp(e,{resourceMetadataUrl:l},n)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let I=await qQ(e,{resourceMetadataUrl:l,fetchFn:n});c=I.authorizationServerUrl,u=I.authorizationServerMetadata,a=I.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await zQ(e,t,a),p=s||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,m=await Promise.resolve(t.clientInformation());if(!m){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let I=u?.client_id_metadata_document_supported===!0,v=t.clientMetadataUrl;if(v&&!NQ(v))throw new Vt(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${v}`);if(I&&v)m={client_id:v},await t.saveClientInformation?.(m);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let B=await WQ(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:n});await t.saveClientInformation(B),m=B}}let g=!t.redirectUrl;if(r!==void 0||g){let I=await JQ(t,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:n});return await t.saveTokens(I),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let I=await YQ(c,{metadata:u,clientInformation:m,refreshToken:f.refresh_token,resource:d,addClientAuthentication:t.addClientAuthentication,fetchFn:n});return await t.saveTokens(I),"AUTHORIZED"}catch(I){if(!(!(I instanceof ae)||I instanceof ct))throw I}let h=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:w}=await GQ(c,{metadata:u,clientInformation:m,state:h,redirectUrl:t.redirectUrl,scope:p,resource:d});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(y),"REDIRECT"}function NQ(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function zQ(t,e,r){let s=Bp(t);if(e.validateResourceURL)return await e.validateResourceURL(s,r?.resource);if(r){if(!Qp({requestedResource:s,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${s} (or origin)`);return new URL(r.resource)}}function br(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,s]=e.split(" ");if(r.toLowerCase()!=="bearer"||!s)return{};let o=Fc(t,"resource_metadata")||void 0,n;if(o)try{n=new URL(o)}catch{}let i=Fc(t,"scope")||void 0,a=Fc(t,"error")||void 0;return{resourceMetadataUrl:n,scope:i,error:a}}function Fc(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let s=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(s);return o?o[1]||o[2]:null}async function Mp(t,e,r=fetch){let s=await OQ(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!s||s.status===404)throw await s?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await s.body?.cancel(),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return Ep.parse(await s.json())}async function Oc(t,e,r=fetch){try{return await r(t,{headers:e})}catch(s){if(s instanceof TypeError)return e?Oc(t,void 0,r):void 0;throw s}}function UQ(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Sp(t,e,r=fetch){return await Oc(t,{"MCP-Protocol-Version":e},r)}function FQ(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function OQ(t,e,r,s){let o=new URL(t),n=s?.protocolVersion??sr,i;if(s?.metadataUrl)i=new URL(s.metadataUrl);else{let c=UQ(e,o.pathname);i=new URL(c,s?.metadataServerUrl??o),i.search=o.search}let a=await Sp(i,n,r);if(!s?.metadataUrl&&FQ(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await Sp(c,n,r)}return a}function LQ(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",s=[];if(!r)return s.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),s.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),s;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),s.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),s.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),s.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),s}async function vp(t,{fetchFn:e=fetch,protocolVersion:r=sr}={}){let s={"MCP-Protocol-Version":r,Accept:"application/json"},o=LQ(t);for(let{url:n,type:i}of o){let a=await Oc(n,s,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${n}`)}return i==="oauth"?jc.parse(await a.json()):yp.parse(await a.json())}}}async function qQ(t,e){let r,s;try{r=await Mp(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(s=r.authorization_servers[0])}catch{}s||(s=String(new URL("/",t)));let o=await vp(s,{fetchFn:e?.fetchFn});return{authorizationServerUrl:s,authorizationServerMetadata:o,resourceMetadata:r}}async function GQ(t,{metadata:e,clientInformation:r,redirectUrl:s,scope:o,state:n,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Nc))throw new Error(`Incompatible auth server: does not support response type ${Nc}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(zc))throw new Error(`Incompatible auth server: does not support code challenge method ${zc}`)}else a=new URL("/authorize",t);let c=await Pc(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",Nc),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",zc),a.searchParams.set("redirect_uri",String(s)),n&&a.searchParams.set("state",n),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function HQ(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function bp(t,{metadata:e,tokenRequestParams:r,clientInformation:s,addClientAuthentication:o,resource:n,fetchFn:i}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(n&&r.set("resource",n.href),o)await o(c,r,a,e);else if(s){let l=e?.token_endpoint_auth_methods_supported??[],d=RQ(s,l);DQ(d,s,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await kp(u);return wp.parse(await u.json())}async function YQ(t,{metadata:e,clientInformation:r,refreshToken:s,resource:o,addClientAuthentication:n,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),c=await bp(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:n,resource:o,fetchFn:i});return{refresh_token:s,...c}}async function JQ(t,e,{metadata:r,resource:s,authorizationCode:o,fetchFn:n}={}){let i=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();a=HQ(o,u,t.redirectUrl)}let c=await t.clientInformation();return bp(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:s,fetchFn:n})}async function WQ(t,{metadata:e,clientMetadata:r,scope:s,fetchFn:o}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);let i=await(o??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...s!==void 0?{scope:s}:{}})});if(!i.ok)throw await kp(i);return Ip.parse(await i.json())}var Lc=class extends Error{constructor(e,r,s){super(`SSE error: ${r}`),this.code=e,this.event=s}},wn=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,s)=>{this._eventSource=new Ht(this._url.href,{...this._eventSourceInit,fetch:async(o,n)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(o,{...n,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=br(a);this._resourceMetadataUrl=c,this._scope=u}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,s);return}let n=new Lc(o.code,o.message,o);s(n),this.onerror?.(n)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let n=o;try{if(this._endpoint=new URL(n.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){s(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{let n=o,i;try{i=ht.parse(JSON.parse(n.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,s);if(!o.ok){let n=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=br(o);if(this._resourceMetadataUrl=i,this._scope=a,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${n}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var wm=lo(Em(),1);import Xc from"process";import{PassThrough as Q_}from"stream";var I_=10*1024*1024,In=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??I_}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
21
21
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),B_(r)}clear(){this._buffer=void 0}};function B_(t){return ht.parse(JSON.parse(t))}function ym(t){return JSON.stringify(t)+`
|
|
22
|
-
`}var __=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function S_(){let t={};for(let e of __){let r=Xc.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Bn=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new In({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Q_)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,wm.default)(this._serverParams.command,this._serverParams.args??[],{env:{...S_(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",s=>{r(s),this.onerror?.(s)}),this._process.on("spawn",()=>{e()}),this._process.on("close",s=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",s=>{this.onerror?.(s)}),this._process.stdout?.on("data",s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",s=>{this.onerror?.(s)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(s=>{e.once("close",()=>{s()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let s=ym(e);this._process.stdin.write(s)?r():this._process.stdin.once("drain",r)})}};var _m=lo(Qm(),1);function Sm(t){if(t)try{return _m.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Qn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:s,maxBufferSize:o}={}){let n;super({start(i){n=fn({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:s,maxBufferSize:o})},transform(i){n.feed(i)}})}};var $_={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Mt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},_n=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$_}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),r&&s.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:s,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Mt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(s){throw this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(s,e),o)}_scheduleReconnection(e,r=0){let s=this._reconnectionOptions.maxRetries;if(r>=s){this.onerror?.(new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,s){if(!e)return;let{onresumptiontoken:o,replayMessageId:n}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Qn({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:g}=await l.read();if(g)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let f=ht.parse(JSON.parse(m.data));bt(f)&&(c=!0,n!==void 0&&(f.id=n)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:s,onresumptiontoken:o}=r||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Jr(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let m=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Mt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:f}=br(a);if(this._resourceMetadataUrl=g,this._scope=f,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:f,error:h}=br(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Mt(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=y??void 0,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new _e;return this.send(e)}}throw new Mt(a.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iu(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let l=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,d=a.headers.get("content-type"),p=Sm(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let m=await a.json(),g=Array.isArray(m)?m.map(f=>ht.parse(f)):[ht.parse(m)];for(let f of g)this.onmessage?.(f)}else throw await a.body?.cancel(),new Mt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(s){throw this.onerror?.(s),s}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,r);if(await s.body?.cancel(),!s.ok&&s.status!==405)throw new Mt(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as P_,statSync as j_}from"fs";import{extname as N_}from"path";import tl from"sharp";var z_=R({module:"images"});function km(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var ol=5*1024*1024,rl=ol*3/4,vt=2e3,$D=10,Rr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},U_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function F_(t){return U_[N_(t).toLowerCase()]??null}function Mm(t){return F_(t)!==null}function O_(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function vm(t){if(!j_(t).isFile())throw new Error(`Not a file: ${t}`);let r=P_(t),s=O_(r);if(!s)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await nl(r,s);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}function sl(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Js(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function nl(t,e){if(t.length===0)throw new Rr("Image file is empty (0 bytes)");if(t.length<=rl)return sl(t,e);try{return await L_(t,e)}catch(r){throw r instanceof Rr?r:(z_.warn({err:r},"sharp compression failed"),new Rr(`Image is ${Js(t.length)} raw (${Js(t.length*4/3)} base64-encoded, API limit ${Js(ol)}) and compression failed. Please provide a smaller image.`))}}async function L_(t,e){let r=await tl(t).metadata(),s=r.width??vt,o=r.height??vt;s>vt&&(o=Math.max(1,Math.round(o*vt/s)),s=vt),o>vt&&(s=Math.max(1,Math.round(s*vt/o)),o=vt);let n=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(n){let a=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=rl)return sl(a,"image/png")}for(let a of[80,60,40,20]){let c=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=rl)return sl(c,"image/jpeg")}s=Math.max(1,Math.round(s/2)),o=Math.max(1,Math.round(o/2))}throw new Rr(`Unable to compress image (${Js(t.length)} raw) under the ${Js(ol)} API limit. Please provide a smaller image.`)}import{readFileSync as q_}from"fs";import bm from"path";import{fileURLToPath as G_}from"url";var H_=$.object({version:$.string()});function Y_(){return"0.0.24"}var xm=Y_();var Rm=R({module:"mcp"});function Tm(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,s)=>process.env[r||s]??"")}function J_(t){let e={};for(let[r,s]of Object.entries(t))e[r]=s??"";return e}var W_=new Set(["image/png","image/jpeg","image/gif","image/webp"]);async function V_(t){let e=[],r=[],s=!1;for(let n of t){let i=Ol(n)?n:{};if(i.type==="image"&&typeof i.data=="string"&&typeof i.mimeType=="string"&&W_.has(i.mimeType))try{let u=await nl(Buffer.from(i.data,"base64"),km(i.mimeType));r.push({type:"image",source:{type:"base64",media_type:u.mediaType,data:u.data}}),e.push(`[Image: ${u.mediaType}]`),s=!0;continue}catch(u){Rm.warn({err:u},"mcp image dropped (too large to fit the API limit)");let l="[note: an image returned by the tool was too large and was dropped]";e.push(l),r.push({type:"text",text:l});continue}if(i.type==="image"){let l=`[Unsupported image: ${typeof i.mimeType=="string"?i.mimeType:"unknown"}]`;e.push(l),r.push({type:"text",text:l});continue}let a=JSON.stringify(n),c=i.type==="text"&&typeof i.text=="string"?i.text:typeof a=="string"?a:String(n);e.push(c),r.push({type:"text",text:c})}let o=e.join(`
|
|
22
|
+
`}var __=Xc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function S_(){let t={};for(let e of __){let r=Xc.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Bn=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new In({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Q_)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,wm.default)(this._serverParams.command,this._serverParams.args??[],{env:{...S_(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Xc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",s=>{r(s),this.onerror?.(s)}),this._process.on("spawn",()=>{e()}),this._process.on("close",s=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",s=>{this.onerror?.(s)}),this._process.stdout?.on("data",s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",s=>{this.onerror?.(s)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(s=>{e.once("close",()=>{s()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let s=ym(e);this._process.stdin.write(s)?r():this._process.stdin.once("drain",r)})}};var _m=lo(Qm(),1);function Sm(t){if(t)try{return _m.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Qn=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:s,maxBufferSize:o}={}){let n;super({start(i){n=fn({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:s,maxBufferSize:o})},transform(i){n.feed(i)}})}};var $_={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Mt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},_n=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=yn(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$_}async _authThenStart(){if(!this._authProvider)throw new _e("No auth provider");let e;try{e=await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new _e;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=vr(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),r&&s.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:s,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Mt(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(s){throw this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(s,e),o)}_scheduleReconnection(e,r=0){let s=this._reconnectionOptions.maxRetries;if(r>=s){this.onerror?.(new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,s){if(!e)return;let{onresumptiontoken:o,replayMessageId:n}=r,i,a=!1,c=!1;(async()=>{try{let l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Qn({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){let{value:m,done:g}=await l.read();if(g)break;if(m.id&&(i=m.id,a=!0,o?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{let f=ht.parse(JSON.parse(m.data));bt(f)&&(c=!0,n!==void 0&&(f.id=n)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(s||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:n},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new _e("No auth provider");if(await lt(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:s,onresumptiontoken:o}=r||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:Jr(e)?e.id:void 0}).catch(m=>this.onerror?.(m));return}let n=await this._commonHeaders();n.set("content-type","application/json"),n.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let m=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Mt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:f}=br(a);if(this._resourceMetadataUrl=g,this._scope=f,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new _e;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:f,error:h}=br(a);if(h==="insufficient_scope"){let y=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Mt(403,"Server returned 403 after trying upscoping");if(f&&(this._scope=f),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=y??void 0,await lt(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new _e;return this.send(e)}}throw new Mt(a.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iu(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let l=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,d=a.headers.get("content-type"),p=Sm(d);if(l)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let m=await a.json(),g=Array.isArray(m)?m.map(f=>ht.parse(f)):[ht.parse(m)];for(let f of g)this.onmessage?.(f)}else throw await a.body?.cancel(),new Mt(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(s){throw this.onerror?.(s),s}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,r);if(await s.body?.cancel(),!s.ok&&s.status!==405)throw new Mt(s.status,`Failed to terminate session: ${s.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as P_,statSync as j_}from"fs";import{extname as N_}from"path";import tl from"sharp";var z_=R({module:"images"});function km(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var ol=5*1024*1024,rl=ol*3/4,vt=2e3,$D=10,Rr=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}},U_={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function F_(t){return U_[N_(t).toLowerCase()]??null}function Mm(t){return F_(t)!==null}function O_(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}async function vm(t){if(!j_(t).isFile())throw new Error(`Not a file: ${t}`);let r=P_(t),s=O_(r);if(!s)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await nl(r,s);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}function sl(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Js(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function nl(t,e){if(t.length===0)throw new Rr("Image file is empty (0 bytes)");if(t.length<=rl)return sl(t,e);try{return await L_(t,e)}catch(r){throw r instanceof Rr?r:(z_.warn({err:r},"sharp compression failed"),new Rr(`Image is ${Js(t.length)} raw (${Js(t.length*4/3)} base64-encoded, API limit ${Js(ol)}) and compression failed. Please provide a smaller image.`))}}async function L_(t,e){let r=await tl(t).metadata(),s=r.width??vt,o=r.height??vt;s>vt&&(o=Math.max(1,Math.round(o*vt/s)),s=vt),o>vt&&(s=Math.max(1,Math.round(s*vt/o)),o=vt);let n=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(n){let a=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=rl)return sl(a,"image/png")}for(let a of[80,60,40,20]){let c=await tl(t).resize(s,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=rl)return sl(c,"image/jpeg")}s=Math.max(1,Math.round(s/2)),o=Math.max(1,Math.round(o/2))}throw new Rr(`Unable to compress image (${Js(t.length)} raw) under the ${Js(ol)} API limit. Please provide a smaller image.`)}import{readFileSync as q_}from"fs";import bm from"path";import{fileURLToPath as G_}from"url";var H_=$.object({version:$.string()});function Y_(){return"0.0.25"}var xm=Y_();var Rm=R({module:"mcp"});function Tm(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,s)=>process.env[r||s]??"")}function J_(t){let e={};for(let[r,s]of Object.entries(t))e[r]=s??"";return e}var W_=new Set(["image/png","image/jpeg","image/gif","image/webp"]);async function V_(t){let e=[],r=[],s=!1;for(let n of t){let i=Ol(n)?n:{};if(i.type==="image"&&typeof i.data=="string"&&typeof i.mimeType=="string"&&W_.has(i.mimeType))try{let u=await nl(Buffer.from(i.data,"base64"),km(i.mimeType));r.push({type:"image",source:{type:"base64",media_type:u.mediaType,data:u.data}}),e.push(`[Image: ${u.mediaType}]`),s=!0;continue}catch(u){Rm.warn({err:u},"mcp image dropped (too large to fit the API limit)");let l="[note: an image returned by the tool was too large and was dropped]";e.push(l),r.push({type:"text",text:l});continue}if(i.type==="image"){let l=`[Unsupported image: ${typeof i.mimeType=="string"?i.mimeType:"unknown"}]`;e.push(l),r.push({type:"text",text:l});continue}let a=JSON.stringify(n),c=i.type==="text"&&typeof i.text=="string"?i.text:typeof a=="string"?a:String(n);e.push(c),r.push({type:"text",text:c})}let o=e.join(`
|
|
23
23
|
`);return s?{output:o,contentBlocks:r}:{output:o}}var Sn=class{name;config;client=null;transport=null;constructor(e){this.name=e.name,this.config=e}async connect(){if(this.config.command){let e=process.env;if(this.config.env)for(let[r,s]of Object.entries(this.config.env))e[r]=Tm(s);this.transport=new Bn({command:this.config.command,args:this.config.args??[],env:J_(e),stderr:"ignore"})}else if(this.config.url){let e=new URL(this.config.url),r={};if(this.config.headers)for(let[o,n]of Object.entries(this.config.headers))r[o]=Tm(n);let s={requestInit:{headers:r}};this.transport=this.config.transport==="sse"?new wn(e,s):new _n(e,s)}else throw new Error(`MCP server '${this.name}': needs either 'command' (stdio) or 'url' (http/sse)`);this.client=new mn({name:"swifty",version:xm},{}),await this.client.connect(this.transport)}getInstructions(){return this.client?.getInstructions()??""}async listTools(){if(!this.client)throw new Error("Not connected");return(await this.client.listTools()).tools.map(({name:r,description:s,inputSchema:{properties:o,...n}})=>({name:r,description:s??"",inputSchema:{...n,properties:o??{}}}))}async callTool(e,r){if(!this.client)throw new Error("Not connected");let s=await this.client.callTool({name:e,arguments:r});return{...s.content&&Array.isArray(s.content)?await V_(s.content):{output:JSON.stringify(s)},isError:s.isError===!0}}async disconnect(){try{await this.client?.close()}catch(e){Rm.error({err:e},"mcp operation failed")}this.client=null,this.transport=null}};var K_=R({module:"mcp"}),Dm=class{clients=new Map;async connectAll(e){let r={tools:[],servers:[],errors:[],instructions:[]};for(let s of e){if(this.clients.has(s.name))continue;let o=new Sn(s);try{await o.connect();let n=await o.listTools();this.clients.set(s.name,o),r.servers.push(s.name);for(let a of n)r.tools.push({serverName:s.name,tool:a});let i=o.getInstructions();i&&r.instructions.push({serverName:s.name,text:i})}catch(n){K_.error({err:n},"mcp operation failed"),r.errors.push({serverName:s.name,error:O(n)}),await o.disconnect()}}return r}getClient(e){return this.clients.get(e)}connectedServers(){return[...this.clients.keys()]}missingServers(e){return e.filter(r=>!this.clients.has(r.name)).map(r=>r.name)}async disconnectAll(){for(let e of this.clients.values())await e.disconnect();this.clients.clear()}};import{execSync as Lm}from"child_process";import{platform as Z_,arch as X_}from"os";function $m(){return{name:"Identity",priority:0,content:`You are Swifty, an AI programming assistant running in a terminal.
|
|
24
24
|
You assist users with software engineering tasks, including writing code, debugging, refactoring, explaining code, and executing commands.
|
|
25
25
|
|
package/dist/lib/index.js
CHANGED
|
@@ -2609,7 +2609,7 @@ var PackageJsonSchema = z5.object({
|
|
|
2609
2609
|
});
|
|
2610
2610
|
function resolveVersion() {
|
|
2611
2611
|
if (true) {
|
|
2612
|
-
return "0.0.
|
|
2612
|
+
return "0.0.25";
|
|
2613
2613
|
}
|
|
2614
2614
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
2615
2615
|
for (const levels of ["..", "../.."]) {
|