@bkm016/basalt 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +275 -2
- package/chunk-09vr609h.js +2 -0
- package/chunk-0hbjv3y6.js +11 -0
- package/chunk-0qqb6v41.js +3753 -0
- package/chunk-0szjy61m.js +2 -0
- package/chunk-0yytz0r1.js +59 -0
- package/chunk-1aspj1hn.js +3 -0
- package/chunk-1b7gbe8g.js +10 -0
- package/chunk-1v7st27a.js +25 -0
- package/chunk-1yzt0qm0.js +2 -0
- package/chunk-2bb01ddq.js +16 -0
- package/chunk-2wkaw73s.js +9 -0
- package/chunk-2zqny2sy.js +2 -0
- package/chunk-32at88hc.js +3 -0
- package/chunk-3m7qwfm3.js +7 -0
- package/chunk-44ek81ad.js +3 -0
- package/chunk-45cz26ap.js +39 -0
- package/chunk-501zkf9b.js +3 -0
- package/chunk-58vz2qsq.js +2 -0
- package/chunk-6e49xsf5.js +3 -0
- package/chunk-6qertm2t.js +3 -0
- package/chunk-8dxzqwq3.js +2 -0
- package/chunk-9mmz6wt3.js +2 -0
- package/chunk-a3tqx584.js +10 -0
- package/chunk-a6r4z44b.js +2 -0
- package/chunk-a8nyk4k9.js +2 -0
- package/chunk-agntrqs9.js +2 -0
- package/chunk-bhqyxyap.js +3 -0
- package/chunk-bpw6q7g0.js +3 -0
- package/chunk-c25s4w6a.js +5 -0
- package/chunk-cv5wsd9m.js +8 -0
- package/chunk-d48bfd2e.js +3 -0
- package/chunk-dakrpbe6.js +3 -0
- package/chunk-dhm42y04.js +7 -0
- package/chunk-exnn1867.js +2 -0
- package/chunk-f7egr55n.js +31 -0
- package/chunk-g2t6t8fk.js +3 -0
- package/chunk-h6sw8fbt.js +5 -0
- package/chunk-hat3s3pr.js +3 -0
- package/chunk-hcn9cf6v.js +2 -0
- package/chunk-jhd54p1b.js +3 -0
- package/chunk-k7w7ac9q.js +18 -0
- package/chunk-kf8hq21a.js +25 -0
- package/chunk-kfq8wyd3.js +3 -0
- package/chunk-n6e43rvk.js +3 -0
- package/chunk-nt2gntad.js +2 -0
- package/chunk-pmc3y1z8.js +2 -0
- package/chunk-pvncysbb.js +3 -0
- package/chunk-q8zx3kt6.js +2 -0
- package/chunk-qczbfccb.js +12 -0
- package/chunk-qnr1f5pj.js +3 -0
- package/chunk-qx0m82rw.js +2 -0
- package/chunk-r9aatvwm.js +3 -0
- package/chunk-rm3kcxq9.js +20 -0
- package/chunk-rv06x0kn.js +7 -0
- package/chunk-ry0z4ev6.js +2 -0
- package/chunk-s37s3k24.js +12 -0
- package/chunk-sh74qzvt.js +5 -0
- package/chunk-szat3vp4.js +3 -0
- package/chunk-t057xfrt.js +5 -0
- package/chunk-tvm4zmgj.js +3 -0
- package/chunk-v9fea96h.js +3 -0
- package/chunk-vgvq3q12.js +3 -0
- package/chunk-vkkj4awb.js +2 -0
- package/chunk-vv7fp27r.js +3 -0
- package/chunk-wjd9fr23.js +2 -0
- package/chunk-wx7kdf0b.js +2 -0
- package/chunk-x3dnb9sz.js +3 -0
- package/chunk-xsbxykr4.js +2 -0
- package/chunk-xysny0ve.js +3 -0
- package/chunk-y69ewdn2.js +3 -0
- package/chunk-yskm0hsy.js +2 -0
- package/chunk-zef13k3h.js +471 -0
- package/cli.js +89 -0
- package/compiled.js +23 -0
- package/icon-dp9pmcvp.png +0 -0
- package/package.json +21 -4
- package/ui-test-worker.js +226 -0
- package/web/KaTeX_AMS-Regular-n7eqehx2.woff2 +0 -0
- package/web/KaTeX_Caligraphic-Bold-20r3b6fv.woff2 +0 -0
- package/web/KaTeX_Caligraphic-Regular-kkjm8f18.woff2 +0 -0
- package/web/KaTeX_Fraktur-Bold-pz5vg4t0.woff2 +0 -0
- package/web/KaTeX_Fraktur-Regular-a1e9wkwk.woff2 +0 -0
- package/web/KaTeX_Main-Bold-mcp098h8.woff2 +0 -0
- package/web/KaTeX_Main-BoldItalic-fy74z249.woff2 +0 -0
- package/web/KaTeX_Main-Italic-hw2gxy7f.woff2 +0 -0
- package/web/KaTeX_Main-Regular-xvp1b75c.woff2 +0 -0
- package/web/KaTeX_Math-BoldItalic-mf5nf33d.woff2 +0 -0
- package/web/KaTeX_Math-Italic-ap60jrna.woff2 +0 -0
- package/web/KaTeX_SansSerif-Bold-we3bymb6.woff2 +0 -0
- package/web/KaTeX_SansSerif-Italic-ent92bjx.woff2 +0 -0
- package/web/KaTeX_SansSerif-Regular-0573pbz9.woff2 +0 -0
- package/web/KaTeX_Script-Regular-z2rtj6vq.woff2 +0 -0
- package/web/KaTeX_Size1-Regular-dfr3w1hv.woff2 +0 -0
- package/web/KaTeX_Size2-Regular-kted78zb.woff2 +0 -0
- package/web/KaTeX_Size3-Regular-e6k1k5jk.woff2 +0 -0
- package/web/KaTeX_Size4-Regular-abedc1pd.woff2 +0 -0
- package/web/KaTeX_Typewriter-Regular-scw9zx1z.woff2 +0 -0
- package/web/apple-touch-icon-7dkm33qp.png +0 -0
- package/web/apple-touch-icon.png +0 -0
- package/web/chunk-05w4fyzc.js +1 -0
- package/web/chunk-0mrkjnte.js +1 -0
- package/web/chunk-0pbjgdgp.js +2 -0
- package/web/chunk-0s80zw00.js +1 -0
- package/web/chunk-0vt9fg48.js +2 -0
- package/web/chunk-20q90epj.js +2 -0
- package/web/chunk-22a4ety5.js +1 -0
- package/web/chunk-24mfx6w1.js +2 -0
- package/web/chunk-2j4m0bh1.js +2 -0
- package/web/chunk-2m12wyrb.js +16 -0
- package/web/chunk-2msj52w6.js +1 -0
- package/web/chunk-2ps6mepk.js +120 -0
- package/web/chunk-2pver6r4.js +1 -0
- package/web/chunk-2scce33n.js +1 -0
- package/web/chunk-37ajk6zg.js +2 -0
- package/web/chunk-3ee04tmm.js +200 -0
- package/web/chunk-3jhyzmnf.js +292 -0
- package/web/chunk-45fzdcgz.js +30 -0
- package/web/chunk-4gavbw65.js +1 -0
- package/web/chunk-4ks96e4r.js +1 -0
- package/web/chunk-4rm1vy7w.js +1 -0
- package/web/chunk-4v8en1yw.js +40 -0
- package/web/chunk-4wd9r73y.js +1 -0
- package/web/chunk-4wkm9fda.js +1 -0
- package/web/chunk-54thej0t.js +2 -0
- package/web/chunk-59kqahb3.js +1 -0
- package/web/chunk-5vw9rs4r.js +4 -0
- package/web/chunk-6beqrmtq.js +1 -0
- package/web/chunk-6m69hczt.js +2 -0
- package/web/chunk-70qwwwak.js +2 -0
- package/web/chunk-74j07k8k.js +2 -0
- package/web/chunk-8g239029.js +1 -0
- package/web/chunk-8p4tc9f4.js +70 -0
- package/web/chunk-90kp4pnz.js +2 -0
- package/web/chunk-9an7cjd9.js +291 -0
- package/web/chunk-9dxjafp2.js +78 -0
- package/web/chunk-9p12mgs6.js +2 -0
- package/web/chunk-9v1f6yc8.js +1 -0
- package/web/chunk-9yakxvjb.js +2 -0
- package/web/chunk-a1z5qx1r.js +36 -0
- package/web/chunk-a3verqw9.js +214 -0
- package/web/chunk-a5x2zveg.js +7 -0
- package/web/chunk-ad6x47yy.js +1 -0
- package/web/chunk-amzgyy1k.js +1 -0
- package/web/chunk-b1pe46zz.js +2 -0
- package/web/chunk-b4wbk7vc.js +217 -0
- package/web/chunk-bc78qf1m.js +7 -0
- package/web/chunk-bgnnrpna.js +89 -0
- package/web/chunk-bj90t5gh.js +99 -0
- package/web/chunk-bjkc94mv.js +1 -0
- package/web/chunk-ca682sm6.js +370 -0
- package/web/chunk-cff5hcm8.js +8 -0
- package/web/chunk-cg3jterp.js +2 -0
- package/web/chunk-d18r4m14.js +141 -0
- package/web/chunk-dmqtdeb4.js +1 -0
- package/web/chunk-dt462hk9.js +332 -0
- package/web/chunk-dy2gm1fs.js +1 -0
- package/web/chunk-dzwxgqgm.js +39 -0
- package/web/chunk-e32y85kx.js +1 -0
- package/web/chunk-e53wfgb8.js +1 -0
- package/web/chunk-e6jxqbv7.js +3 -0
- package/web/chunk-esp1mmgr.js +1 -0
- package/web/chunk-ew3cgdtd.js +1 -0
- package/web/chunk-f26smjjf.js +2 -0
- package/web/chunk-f91wzwtk.js +1 -0
- package/web/chunk-fk0dh93x.js +89 -0
- package/web/chunk-fm2ybfj5.js +98 -0
- package/web/chunk-fscafg24.js +34 -0
- package/web/chunk-fz06t6km.js +55 -0
- package/web/chunk-g1ev11wx.js +1 -0
- package/web/chunk-g4azyef7.js +106 -0
- package/web/chunk-gjq1pxw3.js +1 -0
- package/web/chunk-gqw3f02j.js +140 -0
- package/web/chunk-h5ejbf6e.js +1 -0
- package/web/chunk-hev4hq89.js +2 -0
- package/web/chunk-hfaffkrh.js +1 -0
- package/web/chunk-hp167dbv.js +1 -0
- package/web/chunk-j2vt8c8v.js +1 -0
- package/web/chunk-jjh5jvva.js +1 -0
- package/web/chunk-jrcyc9s9.js +38 -0
- package/web/chunk-jwzd9tzk.js +24 -0
- package/web/chunk-k5btcvbg.js +1 -0
- package/web/chunk-ka3q31t1.js +1 -0
- package/web/chunk-kdyjnwdx.js +2 -0
- package/web/chunk-kpvgecwy.js +1 -0
- package/web/chunk-kq40ss39.js +1 -0
- package/web/chunk-m2d1sp30.js +1 -0
- package/web/chunk-n1dmrz44.js +2 -0
- package/web/chunk-n90cqdvg.js +2 -0
- package/web/chunk-nj0cv1cq.js +257 -0
- package/web/chunk-nzey7cpv.js +1 -0
- package/web/chunk-p3b9crsa.js +2 -0
- package/web/chunk-pf2ab8p8.js +1 -0
- package/web/chunk-pxe3vna4.js +1 -0
- package/web/chunk-q0p5xqe1.js +84 -0
- package/web/chunk-q5ke7a33.js +24 -0
- package/web/chunk-q7dsnvpf.js +1 -0
- package/web/chunk-qd8bxxdj.js +1 -0
- package/web/chunk-qefasa1j.js +2 -0
- package/web/chunk-qh7265qw.js +4 -0
- package/web/chunk-qnaqf0cr.js +1 -0
- package/web/chunk-r1dnh0s8.js +1 -0
- package/web/chunk-r5eakmw6.js +1 -0
- package/web/chunk-rg426vkf.js +1 -0
- package/web/chunk-rpmpttbk.js +12 -0
- package/web/chunk-rtf2zzzv.js +1 -0
- package/web/chunk-ry9256r7.js +1 -0
- package/web/chunk-rykfak98.js +2 -0
- package/web/chunk-scpwc9ev.js +1 -0
- package/web/chunk-srrfphes.js +1 -0
- package/web/chunk-ss1bcb0n.js +2 -0
- package/web/chunk-ssy07dd2.js +1 -0
- package/web/chunk-t6agpn2z.js +1 -0
- package/web/chunk-taynqrgq.js +142 -0
- package/web/chunk-tgpbhzn9.js +1 -0
- package/web/chunk-tmvakq7n.js +19 -0
- package/web/chunk-tqmwd9qp.js +139 -0
- package/web/chunk-ts7zrf5b.js +2 -0
- package/web/chunk-ttg6tbwx.js +2 -0
- package/web/chunk-v28fx2nd.js +1 -0
- package/web/chunk-v5cnt7c8.js +1 -0
- package/web/chunk-vt40e1kp.js +1136 -0
- package/web/chunk-w53rba6g.js +1 -0
- package/web/chunk-w86n42dy.js +1 -0
- package/web/chunk-w880psmw.js +1 -0
- package/web/chunk-wptv8atc.js +2 -0
- package/web/chunk-wtawdeej.css +1 -0
- package/web/chunk-xbty0rv7.js +41 -0
- package/web/chunk-xet1jjy9.js +1 -0
- package/web/chunk-xjxv8dg8.js +169 -0
- package/web/chunk-xrxne80b.js +62 -0
- package/web/chunk-xzp7jf7e.js +2 -0
- package/web/chunk-y0m8hrwz.js +303 -0
- package/web/chunk-y49fhfda.js +7 -0
- package/web/chunk-yd46jhqv.js +1 -0
- package/web/chunk-ydtrc1ay.js +2 -0
- package/web/chunk-z09emmrb.js +1 -0
- package/web/chunk-z7dcbxws.js +1 -0
- package/web/chunk-zbj1trar.js +2 -0
- package/web/chunk-zde7mj43.js +1 -0
- package/web/icon-192.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/icon-maskable-512.png +0 -0
- package/web/icon-yx2p2pye.svg +13 -0
- package/web/icon.svg +13 -0
- package/web/index.html +23 -0
- package/web/install.ps1 +91 -0
- package/web/install.sh +177 -0
- package/web/inter-latin-wght-normal-an0py913.woff2 +0 -0
- package/web/jetbrains-mono-latin-wght-normal-hj2e42wt.woff2 +0 -0
- package/web/manifest-txf6vfbq.webmanifest +35 -0
- package/web/manifest.webmanifest +35 -0
- package/web/source-serif-4-latin-wght-italic-ta5tqqvz.woff2 +0 -0
- package/web/source-serif-4-latin-wght-normal-1yyvbhsz.woff2 +0 -0
- package/web/sw.js +90 -0
- package/worker.js +2 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{M,Ve}from"./chunk-6e49xsf5.js";function z(e,t,r){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:r}}function G(e){return typeof e.result==="function"}async function F(e,t){for await(let r of t)e.push(r);e.end(G(t)?await t.result():void 0)}function Ie(e,t){let r=Date.now(),n=new M;return t().then((s)=>F(n,s)).catch((s)=>{let o=z(e,s,r);n.push({type:"error",reason:"error",error:o}),n.end(o)}),n}function te(e,t){let r={stream:(n,s,o)=>Ie(n,async()=>(await e()).stream(n,s,o)),streamSimple:(n,s,o)=>Ie(n,async()=>(await e()).streamSimple(n,s,o))};if(t?.fetchDeferred)r.fetchDeferred=(n,s,o)=>Ie(n,async()=>{let i=await e();if(!i.fetchDeferred)throw Error("API does not support deferred responses");return i.fetchDeferred(n,s,o)});if(t?.cancelDeferred)r.cancelDeferred=async(n,s,o)=>{let i=await e();if(!i.cancelDeferred)throw Error("API cannot cancel deferred responses");await i.cancelDeferred(n,s,o)};return r}var J=function(e,t){if(typeof e==="string"&&/^\.\.?\//.test(e))return e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,o,i){return n?t?".jsx":".js":s&&(!o||!i)?r:s+o+"."+i.toLowerCase()+"js"});return e},R=(e)=>import(J(e));function V(){return globalThis.process?.env}function Do(){return{async env(e){let t=V()?.[e];return typeof t==="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await R("node:fs/promises"),r=e;if(r.startsWith("~"))r=(await R("node:os")).homedir()+r.slice(1);return await t.access(r),!0}catch{return!1}}}}function q(e){if(e.reason!==void 0)return e.reason;let t=Error("The operation was aborted");return t.name="AbortError",t}function g(e){return e??new AbortController().signal}function v(e,t){if(t.aborted)return e.catch(()=>{}),Promise.reject(q(t));return new Promise((r,n)=>{let s=!1,o=()=>t.removeEventListener("abort",i),i=()=>{if(s)return;s=!0,o(),n(q(t))};if(t.addEventListener("abort",i,{once:!0}),e.then((c)=>{if(s)return;s=!0,o(),r(c)},(c)=>{if(s)return;s=!0,o(),n(c)}),t.aborted)i()})}class qn{credentials=new Map;chains=new Map;enqueue(e,t,r){let n=g(r?.signal),s=this.chains.get(e)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),n.throwIfAborted(),t()))(),i=o.catch(()=>{});return this.chains.set(e,i),i.then(()=>{if(this.chains.get(e)===i)this.chains.delete(e)}),v(o,n)}async read(e,t){return t?.signal?.throwIfAborted(),this.credentials.get(e)}async list(e){return e?.signal?.throwIfAborted(),[...this.credentials].map(([t,r])=>({providerId:t,type:r.type}))}modify(e,t,r){return this.enqueue(e,async()=>{let n=this.credentials.get(e),s=await t(n);if(r?.signal?.throwIfAborted(),s!==void 0)this.credentials.set(e,s);return s??n},r)}delete(e,t){return this.enqueue(e,async()=>{this.credentials.delete(e)},t)}}class C extends Error{code;constructor(e,t,r){super(Y(t,r?.cause),r);this.name="ModelsError",this.code=e}}function Y(e,t){if(t===void 0||t===null)return e;let r=Ve(t).trim();if(!r||e.includes(r))return e;return`${e}: ${r}`}function T(e,t,r,n){let s=g(n?.signal);return v(X(e,t,r,n,s),s)}async function X(e,t,r,n,s){s.throwIfAborted();let o=n?.env?B(r,n.env):r;if(n?.apiKey!==void 0&&e.auth.apiKey)return E(o,e.auth.apiKey,e.id,{type:"api_key",key:n.apiKey,env:n.env},s);let i=await oe(t,e.id,s);if(i){if(i.type==="oauth"&&e.auth.oauth)return se(t,e.id,e.auth.oauth,i,s,n?.minOAuthValidityMs);if(i.type==="api_key"&&e.auth.apiKey){let c=n?.env?{...i,env:{...i.env,...n.env}}:i;return E(o,e.auth.apiKey,e.id,c,s)}return}return e.auth.apiKey?E(o,e.auth.apiKey,e.id,void 0,s):void 0}function B(e,t){return{env:async(r)=>t[r]||await e.env(r),fileExists:(r)=>e.fileExists(r)}}var Z=300000,ee=15000;async function k(e,t,r,n,s){let o,i=new AbortController,c=()=>i.abort(s.reason);if(s.addEventListener("abort",c,{once:!0}),s.aborted)c();try{o=await e.modify(t,async(u)=>{if(s.removeEventListener("abort",c),s.throwIfAborted(),u?.type!=="oauth")return;if(!n(u))return;try{return await r.refresh(u,AbortSignal.timeout(ee))}catch(f){throw new C("oauth",`OAuth refresh failed for ${t}`,{cause:f})}},{signal:i.signal})}catch(u){if(u instanceof C)throw u;throw s.throwIfAborted(),new C("auth",`Credential store modify failed for ${t}`,{cause:u})}finally{s.removeEventListener("abort",c)}return o?.type==="oauth"?o:void 0}async function se(e,t,r,n,s,o){let i=Math.max(Z,o??0),c=(f)=>Date.now()+i>=f.expires,u=n;if(c(u)){let f=await k(e,t,r,c,s);if(!f)return;if(u=f,o!==void 0&&c(u))throw new C("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await r.toAuth(u),source:"OAuth"}}catch(f){throw new C("oauth",`OAuth auth derivation failed for ${t}`,{cause:f})}}async function E(e,t,r,n,s){try{return await t.resolve({ctx:e,credential:n,signal:s})}catch(o){throw new C("auth",`API key auth failed for provider ${r}`,{cause:o})}}async function oe(e,t,r){try{return await e.read(t,{signal:r})}catch(n){throw new C("auth",`Credential store read failed for ${t}`,{cause:n})}}class Hn{entries=new Map;async read(e,t){t?.signal?.throwIfAborted();let r=this.entries.get(e);return r?structuredClone(r):void 0}async write(e,t,r){r?.signal?.throwIfAborted(),this.entries.set(e,structuredClone(t))}async delete(e,t){t?.signal?.throwIfAborted(),this.entries.delete(e)}}function mt(e){return e.type??"chat"}function Ce(e,t){return mt(e)===t}function _(e){if(!Ce(e,"chat"))throw new C("provider",`Model ${e.provider}/${e.id} is not a chat model`)}function K(e){if(!Ce(e,"image"))throw new C("provider",`Model ${e.provider}/${e.id} is not an image model`)}function I(e){if(!Ce(e,"classifier"))throw new C("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}function L(e,t){if(t.images?.length&&!e.input.includes("image"))throw new C("provider",`Model ${e.provider}/${e.id} does not accept image input`)}function D(e,t,r=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:r?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function O(e,t,r=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:r?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function ur(e,t=`
|
|
3
|
+
`){if(typeof e==="string")return e;return e.filter((r)=>r.type==="text").map((r)=>r.text).join(t)}function N(e){let t=[ur(e.content)];for(let r of Object.values(e.sections??{}))if(r!==null)t.push(r);return t.filter((r)=>r.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`)}function Me(e){let t=[],r=ur(e.content);if(r.length>0)t.push(r);for(let[n,s]of Object.entries(e.sections??{}))t.push(s===null?`Removed system prompt section "${n}".`:`Updated system prompt section "${n}":
|
|
6
|
+
|
|
7
|
+
${s}`);return t.join(`
|
|
8
|
+
|
|
9
|
+
`)}function Gn(e,t){let r=e!==void 0&&e.length>0,n=t!==void 0&&t.length>0;if(!r&&!n)return;return{role:"system",content:e??"",...n?{toolsAdded:t}:{},timestamp:0}}function ht(e){let t=Gn(e.systemPrompt,e.tools);return{messages:t?[t,...e.messages]:e.messages}}function x(e){return e.role==="system"}function ue(e){let t=e[0];return t&&x(t)?t:void 0}function $t(e){return ue(e)?e.slice(1):e}function ne(e){let t=new Map;for(let r of e){if(!x(r))continue;for(let n of r.toolsRemoved??[])t.delete(n.name);for(let n of r.toolsAdded??[])t.set(n.name,n)}return[...t.values()]}function jr(e){let t=[],r=new Map,n;for(let o of e){if(!x(o))continue;n??=o.timestamp;let i=ur(o.content);if(i.length>0)t.push(i);for(let[c,u]of Object.entries(o.sections??{}))if(u===null)r.delete(c);else r.set(c,u)}let s=ne(e);if(n===void 0&&s.length===0)return;return{role:"system",content:t.join(`
|
|
10
|
+
|
|
11
|
+
`),...r.size>0?{sections:Object.fromEntries(r)}:{},...s.length>0?{toolsAdded:s}:{},timestamp:n??0}}function Uo(e){let t=jr(e);return t?N(t):""}function Le(e){let t=jr(e.messages),r=e.messages.filter((n)=>n.role!=="system");return{messages:t?[t,...r]:r}}function re(e,t){return t?e:Le(e)}function nt(e){return{name:e.name,description:e.description,parameters:JSON.parse(JSON.stringify(e.parameters)),...e.constrainedSampling===void 0?{}:{constrainedSampling:e.constrainedSampling}}}function zn(e,t){return JSON.stringify(nt(e))===JSON.stringify(nt(t))}function Fo(e,t){let r=new Map(e.map((s)=>[s.name,s])),n=new Map(t.map((s)=>[s.name,s]));return{toolsAdded:t.filter((s)=>{let o=r.get(s.name);return o===void 0||!zn(o,s)}).map(nt),toolsRemoved:e.filter((s)=>{let o=n.get(s.name);return o===void 0||!zn(s,o)}).map((s)=>({name:s.name}))}}function ge(e){let t=new Map;for(let r of e){if(!x(r))continue;for(let n of r.toolsAdded??[])t.set(n.name,n)}return[...t.values()]}function _i(e){let t=new Map;for(let r of e){if(!x(r))continue;for(let n of r.toolsAdded??[]){let s=t.get(n.name);if(s!==void 0&&!zn(s,n))return!0;t.set(n.name,n)}}return!1}function Si(e){let t=new Set;for(let r of e){if(!x(r))continue;if((r.toolsRemoved?.length??0)>0)return!0;for(let n of r.toolsAdded??[]){if(t.has(n.name))return!0;t.add(n.name)}}return!1}function ye(e,t){let r=t&&!Si(e);return{requestTools:r?ue(e)?.toolsAdded??[]:ne(e),anchorsAdditions:r}}var ie={chat:!0,image:!0,classifier:!0};function U(e){return Object.hasOwn(ie,mt(e))}function ae(e){return{...e,models:e.models.filter(U)}}function W(e,t){if(!e&&!t)return;let r={...e};for(let[n,s]of Object.entries(t??{})){let o=n.toLowerCase();for(let i of Object.keys(r))if(i.toLowerCase()===o)delete r[i];r[n]=s}return r}class j{providers=new Map;credentials;modelsStore;authContext;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(e){this.credentials=e?.credentials??new qn,this.modelsStore=e?.modelsStore??new Hn,this.authContext=e?.authContext??Do()}setProvider(e){this.supersedeProviderRefresh(e.id),this.providers.set(e.id,e)}deleteProvider(e){this.supersedeProviderRefresh(e),this.providers.delete(e)}clearProviders(){for(let e of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(e);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let r=this.providers.get(e);if(!r)return[];try{return r.getModels()}catch{return[]}}let t=[];for(let r of this.providers.values())try{t.push(...r.getModels())}catch{}return t}getAllModels(e){if(e!==void 0){let r=this.providers.get(e);if(!r)return[];try{return r.getAllModels?.()??r.getModels()}catch{return[]}}let t=[];for(let r of this.providers.values())try{t.push(...r.getAllModels?.()??r.getModels())}catch{}return t}getModelsOfType(e,t){return this.getAllModels(t).filter((r)=>Ce(r,e))}getModel(e,t){return this.getModels(e).find((r)=>r.id===t)}getModelOfType(e,t,r){return this.getModelsOfType(e,t).find((n)=>n.id===r)}supersedeProviderRefresh(e){let t=(this.refreshGenerations.get(e)??0)+1;this.refreshGenerations.set(e,t);let r=this.refreshControllers.get(e);if(r)this.refreshControllers.delete(e),r.abort();return t}beginProviderRefresh(e){let t=this.supersedeProviderRefresh(e),r=new AbortController;return this.refreshControllers.set(e,r),{generation:t,controller:r}}publishProviderModels(e,t,r,n){let s=this.publicationChains.get(e)??Promise.resolve(),o=(async()=>{if(await s.catch(()=>{}),r.aborted||this.refreshGenerations.get(e)!==t)return!1;if(n.persist===null)await this.modelsStore.delete(e,{signal:r});else if(n.persist!==void 0)await this.modelsStore.write(e,structuredClone(n.persist),{signal:r});if(r.aborted||this.refreshGenerations.get(e)!==t)return!1;return n.update?.(),!0})(),i=o.catch(()=>{});return this.publicationChains.set(e,i),i.then(()=>{if(this.publicationChains.get(e)===i)this.publicationChains.delete(e)}),v(o,r)}async runProviderRefreshPhase(e,t,r,n,s,o){let i=await this.modelsStore.read(e.id,{signal:o});await e.refreshModels({credential:t,stored:i?ae(structuredClone(i)):void 0,publish:(c)=>this.publishProviderModels(e.id,s,o,c),allowNetwork:r,force:r?n:void 0,signal:o,baseUrl:e.baseUrl})}async refresh(e={}){let t=e.allowNetwork??!0,r=g(e.signal),n=new Map;if(r.aborted)return{aborted:!0,errors:n};let s=e.providers?new Set(e.providers):void 0,o=Array.from(this.providers.values()).filter((c)=>c.refreshModels!==void 0&&(!s||s.has(c.id))),i=Promise.all(o.map(async(c)=>{let{generation:u,controller:f}=this.beginProviderRefresh(c.id),m=AbortSignal.any([r,f.signal]),b=(async()=>{let w,y;try{w=await this.readCredential(c.id,m)}catch(a){y=a}if(await this.runProviderRefreshPhase(c,w,!1,void 0,u,m),y!==void 0)throw y;if(!t||m.aborted)return;let A=await this.resolveRefreshCredential(c,w,m);if(!A)return;await this.runProviderRefreshPhase(c,A,!0,e.force,u,m)})();try{await v(b,m)}catch(w){if(!m.aborted)n.set(c.id,w instanceof Error?w:new C("model_source",`Model refresh failed for ${c.id}`,{cause:w}))}finally{if(this.refreshControllers.get(c.id)===f)this.refreshControllers.delete(c.id)}}));try{await v(i,r)}catch(c){if(!r.aborted)throw c}return{aborted:r.aborted,errors:new Map(n)}}async resolveRefreshCredential(e,t,r){if(t?.type==="oauth"){let i=e.auth.oauth;if(!i)return;if(Date.now()<t.expires)return t;if(r.aborted)return;return k(this.credentials,e.id,i,(c)=>Date.now()>=c.expires,r)}let n=e.auth.apiKey;if(!n)return;let s=t?.type==="api_key"?t:void 0,o=await n.resolve({ctx:this.authContext,credential:s,signal:r});if(!o)return;return{type:"api_key",key:o.auth.apiKey,env:o.env}}async readCredential(e,t){try{return await this.credentials.read(e,{signal:t})}catch(r){throw new C("auth",`Credential store read failed for ${e}`,{cause:r})}}async checkProviderAuth(e,t,r){if(t?.type==="oauth")return e.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let n=e.auth.apiKey;if(!n)return;if(n.check)try{return await n.check({ctx:this.authContext,credential:t?.type==="api_key"?t:void 0,signal:r})}catch(o){throw new C("auth",`API key auth check failed for provider ${e.id}`,{cause:o})}let s=await T(e,this.credentials,this.authContext,{signal:r});return s?{source:s.source,type:"api_key"}:void 0}checkAuth(e,t){let r=g(t?.signal),n=(async()=>{r.throwIfAborted();let s=this.providers.get(e);if(!s)return;return this.checkProviderAuth(s,await this.readCredential(e,r),r)})();return v(n,r)}async getAuthenticatedProviders(e,t){t.throwIfAborted();let r=e?[this.providers.get(e)].filter((s)=>s!==void 0):this.getProviders();return(await Promise.all(r.map(async(s)=>{let o=await this.readCredential(s.id,t);return{provider:s,credential:o,auth:await this.checkProviderAuth(s,o,t)}}))).filter((s)=>s.auth!==void 0)}getAvailable(e,t){let r=g(t?.signal),n=(async()=>(await this.getAuthenticatedProviders(e,r)).flatMap(({provider:o,credential:i})=>{let c=o.getModels();return o.filterModels?.(c,i)??c}))();return v(n,r)}async getAvailableOfType(e,t,r){return(await this.getAllAvailable(t,r)).filter((n)=>Ce(n,e))}getAllAvailable(e,t){let r=g(t?.signal),n=(async()=>(await this.getAuthenticatedProviders(e,r)).flatMap(({provider:o,credential:i})=>{let c=o.getAllModels?.()??o.getModels();if(o.filterAllModels)return o.filterAllModels(c,i);if(!o.filterModels)return c;let u=new Set(o.filterModels(o.getModels(),i).map((f)=>f.id));return c.filter((f)=>!Ce(f,"chat")||u.has(f.id))}))();return v(n,r)}async getAuth(e,t){let r=g(t?.signal),n=typeof e==="string"?e:e.provider,s=this.providers.get(n);if(!s)return;let o=await T(s,this.credentials,this.authContext,{...t,signal:r});if(!o||typeof e==="string"||!e.headers)return o;return{...o,auth:{...o.auth,headers:W(o.auth.headers,e.headers)}}}async login(e,t,r,n){let s=g(r.signal);s.throwIfAborted();let o=this.providers.get(e);if(!o)throw new C("provider",`Unknown provider: ${e}`);let i=t==="oauth"?o.auth.oauth:o.auth.apiKey;if(!i?.login)throw new C("auth",`${o.name} does not support ${t} login`);let c=i.login({...r,signal:s},n),u=await v(c,s),f=!1,m,b=new Promise((y)=>{m=y}),w=this.credentials.modify(e,async()=>(f=!0,m?.(),u),{signal:s});w.catch(()=>{});try{await new Promise((y,A)=>{let a=()=>{if(!f)A(s.reason)};if(s.addEventListener("abort",a,{once:!0}),Promise.race([b,w]).then(()=>{s.removeEventListener("abort",a),y()},(l)=>{s.removeEventListener("abort",a),A(l)}),s.aborted)a()}),await w}catch(y){throw s.throwIfAborted(),new C("auth",`Credential store modify failed for ${e}`,{cause:y})}return u}async logout(e,t){let r=g(t?.signal);r.throwIfAborted();try{await this.credentials.delete(e,{signal:r})}catch(n){throw r.throwIfAborted(),new C("auth",`Credential store delete failed for ${e}`,{cause:n})}}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new C("provider",`Unknown provider: ${e.provider}`);return t}requireChatProvider(e){return _(e),this.requireProvider(e)}async applyAuth(e,t){this.requireProvider(e);let r=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!r)throw new C("auth",`Provider is not configured: ${e.provider}`);let n=r.auth,s=t?.apiKey??n.apiKey,o=W(n.headers,t?.headers);if(t?.transformHeaders)o=await t.transformHeaders(o??{});let i=r.env||t?.env?{...r.env??{},...t?.env??{}}:void 0,c=n.baseUrl?{...e,baseUrl:n.baseUrl}:e,{transformHeaders:u,...f}=t??{},m={...f,apiKey:s,headers:o,env:i};return{requestModel:c,requestOptions:m}}stream(e,t,r){let n=ht(t);return Ie(e,async()=>{let s=this.requireChatProvider(e),{requestModel:o,requestOptions:i}=await this.applyAuth(e,r);return s.stream(o,n,i)})}async complete(e,t,r){return this.stream(e,t,r).result()}streamSimple(e,t,r){let n=ht(t);return Ie(e,async()=>{let s=this.requireChatProvider(e),{requestModel:o,requestOptions:i}=await this.applyAuth(e,r);return s.streamSimple(o,n,i)})}async completeSimple(e,t,r){return this.streamSimple(e,t,r).result()}streamDeferred(e,t,r){return Ie(e,async()=>{let n=this.requireChatProvider(e);if(!n.fetchDeferred)throw new C("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:s,requestOptions:o}=await this.applyAuth(e,r);return n.fetchDeferred(s,t,o)})}async fetchDeferred(e,t,r){return this.streamDeferred(e,t,r).result()}async cancelDeferred(e,t,r){let n=this.requireChatProvider(e);if(!n.cancelDeferred)throw new C("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:s,requestOptions:o}=await this.applyAuth(e,r);await n.cancelDeferred(s,t,o)}async generateImages(e,t,r){try{K(e);let n=this.requireProvider(e);if(!n.generateImages)throw new C("provider",`Provider ${e.provider} does not support image generation`);let{requestModel:s,requestOptions:o}=await this.applyAuth(e,r);return await n.generateImages(s,t,o)}catch(n){return D(e,n,r?.signal?.aborted)}}async classify(e,t,r){try{I(e),L(e,t);let n=this.requireProvider(e);if(!n.classify)throw new C("provider",`Provider ${e.provider} does not support classification`);let{requestModel:s,requestOptions:o}=await this.applyAuth(e,r);return await n.classify(s,t,o)}catch(n){return O(e,n,r?.signal?.aborted)}}}function jn(e){return new j(e)}function d(e){let t=e.api&&typeof e.api.stream==="function"?e.api:void 0,r=t||!e.api?void 0:e.api,{images:n,classifiers:s}=e,o=t?[t]:Object.values(r??{}).filter((a)=>a!==void 0),i=Object.values(n??{}).filter((a)=>a!==void 0),c=Object.values(s??{}).filter((a)=>a!==void 0);if(o.length===0&&i.length===0&&c.length===0)throw Error(`Provider ${e.id}: at least one of "api", "images", or "classifiers" is required.`);let u=e.models,f=[],m=e.fetchModels,b=()=>{let a=[...u];for(let l of f){let h=a.findIndex((p)=>mt(p)===mt(l)&&p.id===l.id);if(h>=0)a[h]=l;else a.push(l)}return a},w=(a)=>t??r?.[a.api],y=(a,l)=>{let h=w(a);if(!h)return Ie(a,async()=>{throw new C("stream",`Provider ${e.id} has no API implementation for "${a.api}"`)});return l(h)},A={id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:()=>b().filter((a)=>Ce(a,"chat")),getAllModels:b,refreshModels:m?async(a)=>{if(a.stored){let p=a.stored.models.filter((P)=>P.provider===e.id).map((P)=>P);if(!await a.publish({update:()=>{f=p}}))return}if(!a.allowNetwork||a.signal.aborted)return;let l=await m(a);if(a.signal.aborted)return;let h=l.filter(U);await a.publish({persist:{models:h,checkedAt:Date.now()},update:()=>{f=h}})}:void 0,filterModels:e.filterModels,filterAllModels:e.filterAllModels,stream:(a,l,h)=>y(a,(p)=>p.stream(a,l,h)),streamSimple:(a,l,h)=>y(a,(p)=>p.streamSimple(a,l,h))};if(o.some((a)=>a.fetchDeferred!==void 0))A.fetchDeferred=(a,l,h)=>Ie(a,async()=>{let p=w(a);if(!p?.fetchDeferred)throw new C("provider",`Provider ${e.id} does not support deferred responses for "${a.api}"`);return p.fetchDeferred(a,l,h)});if(o.some((a)=>a.cancelDeferred!==void 0))A.cancelDeferred=async(a,l,h)=>{let p=w(a);if(!p?.cancelDeferred)throw new C("provider",`Provider ${e.id} cannot cancel deferred responses for "${a.api}"`);await p.cancelDeferred(a,l,h)};if(n&&i.length>0)A.generateImages=async(a,l,h)=>{let p=n[a.api];if(!p)return D(a,new C("provider",`Provider ${e.id} has no image generation implementation for "${a.api}"`));return p.generateImages(a,l,h)};if(s&&c.length>0)A.classify=async(a,l,h)=>{let p=s[a.api];if(!p)return O(a,new C("provider",`Provider ${e.id} has no classifier implementation for "${a.api}"`));return p.classify(a,l,h)};return A}function Pi(e,t){return Ce(e,"chat")&&e.api===t}function Q(e,t){let r=t.input+t.cacheRead+t.cacheWrite,n=e.cost,s=-1;for(let c of e.cost.tiers??[])if(r>c.inputTokensAbove&&c.inputTokensAbove>s)n=c,s=c.inputTokensAbove;let o=t.cacheWrite1h??0,i=t.cacheWrite-o;return t.cost.input=n.input/1e6*t.input,t.cost.output=n.output/1e6*t.output,t.cost.cacheRead=n.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(n.cacheWrite*i+n.input*2*o)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var S=["off","minimal","low","medium","high","xhigh","max"];function Vr(e){if(!e.reasoning)return["off"];return S.filter((t)=>{let r=e.thinkingLevelMap?.[t];if(r===null)return!1;if(t==="xhigh"||t==="max")return r!==void 0;return!0})}function H(e,t){let r=Vr(e);if(r.includes(t))return t;let n=S.indexOf(t);if(n===-1)return r[0]??"off";for(let s=n;s<S.length;s++){let o=S[s];if(r.includes(o))return o}for(let s=n-1;s>=0;s--){let o=S[s];if(r.includes(o))return o}return r[0]??"off"}function Ti(e,t){if(!e||!t)return!1;return mt(e)===mt(t)&&e.id===t.id&&e.provider===t.provider}
|
|
12
|
+
export{Ie,te,Do,qn,C,Hn,mt,Ce,ur,N,Me,Gn,ht,ue,$t,ne,jr,Uo,Le,re,nt,zn,Fo,ge,_i,Si,ye,jn,d,Pi,Q,Vr,H,Ti};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var l=Object.create;var{getPrototypeOf:m,defineProperty:f,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var q,r,i=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?q??=new WeakMap:r??=new WeakMap,j=h.get(a);if(j)return j}c=a!=null?l(m(a)):{};let e=b||!a||!a.__esModule||!k.call(a,"default")?f(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(e,g))f(e,g,{get:o.bind(a,g),enumerable:!0})}if(d)h.set(a,e);return e};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=(a)=>a;function u(a,b){this[a]=s.bind(null,b)}var Ye=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:u.bind(b,c)})};var Gt=(a,b,c)=>{for(var d in b)f(a,d,{get:b[d],set:c[d],enumerable:!0,configurable:!0})},p=import.meta.require;
|
|
3
|
+
export{i,t,Ye,Gt,p};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function At(e){return e.some((t)=>{if(t.role==="user"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");if(t.role==="toolResult"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");return!1})}function Et(e){let t={"X-Initiator":r(e.messages),"Openai-Intent":"conversation-edits"};if(e.hasImages)t["Copilot-Vision-Request"]="true";return t}
|
|
3
|
+
export{At,Et};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ve,L}from"./chunk-0hbjv3y6.js";import{gt,Ne,be,Y,b,X,B}from"./chunk-k7w7ac9q.js";import{t}from"./chunk-qnr1f5pj.js";var zo=t(function(Is){var{hasOwn:ie,fromUtf8:pr,fromHex:ys,toHex:te,toUint8Array:we,isArrayBuffer:Ss}=X(),{normalizeProvider:yr}=Y(),{escapeUri:ze,HttpRequest:xr}=B();class Er{format(e){let r=[];for(let o in e){if(!ie(e,o))continue;let i=pr(o);r.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(e[o]))}let n=new Uint8Array(r.reduce((o,i)=>o+i.byteLength,0)),s=0;for(let o of r)n.set(o,s),s+=o.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let r=new DataView(new ArrayBuffer(3));return r.setUint8(0,3),r.setInt16(1,e.value,!1),new Uint8Array(r.buffer);case"integer":let n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":let s=new Uint8Array(9);return s[0]=5,s.set(e.value.bytes,1),s;case"binary":let o=new DataView(new ArrayBuffer(3+e.value.byteLength));o.setUint8(0,6),o.setUint16(1,e.value.byteLength,!1);let i=new Uint8Array(o.buffer);return i.set(e.value,3),i;case"string":let c=pr(e.value),a=new DataView(new ArrayBuffer(3+c.byteLength));a.setUint8(0,7),a.setUint16(1,c.byteLength,!1);let f=new Uint8Array(a.buffer);return f.set(c,3),f;case"timestamp":let u=new Uint8Array(9);return u[0]=8,u.set(St.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!ws.test(e.value))throw Error(`Invalid UUID received: ${e.value}`);let h=new Uint8Array(17);return h[0]=9,h.set(ys(e.value.replace(/-/g,"")),1),h}}}var Sr;(function(e){e[e.boolTrue=0]="boolTrue",e[e.boolFalse=1]="boolFalse",e[e.byte=2]="byte",e[e.short=3]="short",e[e.integer=4]="integer",e[e.long=5]="long",e[e.byteArray=6]="byteArray",e[e.string=7]="string",e[e.timestamp=8]="timestamp",e[e.uuid=9]="uuid"})(Sr||(Sr={}));var ws=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class St{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776000||e<-9223372036854776000)throw Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let r=new Uint8Array(8);for(let n=7,s=Math.abs(Math.round(e));n>-1&&s>0;n--,s/=256)r[n]=s;if(e<0)wr(r);return new St(r)}valueOf(){let e=this.bytes.slice(0),r=e[0]&128;if(r)wr(e);return parseInt(te(e),16)*(r?-1:1)}toString(){return String(this.valueOf())}}function wr(e){for(let r=0;r<8;r++)e[r]^=255;for(let r=7;r>-1;r--)if(e[r]++,e[r]!==0)break}var Nr="X-Amz-Algorithm",_r="X-Amz-Credential",wt="X-Amz-Date",Cr="X-Amz-SignedHeaders",Ar="X-Amz-Expires",bt="X-Amz-Signature",xt="X-Amz-Security-Token",bs="X-Amz-Region-Set",Et="authorization",Nt=wt.toLowerCase(),Tr="date",Ir=[Et,Nt,Tr],kr=bt.toLowerCase(),Fe="x-amz-content-sha256",Rr=xt.toLowerCase(),xs="host",Mr={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},Br=/^proxy-/,Ur=/^sec-/,Es=[/^proxy-/i,/^sec-/i],Oe="AWS4-HMAC-SHA256",Ns="AWS4-ECDSA-P256-SHA256",Dr="AWS4-HMAC-SHA256-PAYLOAD",jr="UNSIGNED-PAYLOAD",zr=50,_t="aws4_request",Or=604800,Lr=({query:e={}})=>{let r=[],n={};for(let s in e){if(!ie(e,s))continue;if(s.toLowerCase()===kr)continue;let o=ze(s);r.push(o);let i=e[s];if(typeof i==="string")n[o]=`${o}=${ze(i)}`;else if(Array.isArray(i))n[o]=i.slice(0).reduce((c,a)=>c.concat([`${o}=${ze(a)}`]),[]).sort().join("&")}return r.sort().map((s)=>n[s]).filter((s)=>s).join("&")},_s=(e)=>Cs(e).toISOString().replace(/\.\d{3}Z$/,"Z"),Cs=(e)=>{if(typeof e==="number")return new Date(e*1000);if(typeof e==="string"){if(Number(e))return new Date(Number(e)*1000);return new Date(e)}return e};class Ct{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:r,region:n,service:s,sha256:o,uriEscapePath:i=!0}){this.service=s,this.sha256=o,this.uriEscapePath=i,this.applyChecksum=typeof e==="boolean"?e:!0,this.regionProvider=yr(n),this.credentialProvider=yr(r)}createCanonicalRequest(e,r,n){let s=Object.keys(r).sort();return`${e.method}
|
|
3
|
+
${this.getCanonicalPath(e)}
|
|
4
|
+
${Lr(e)}
|
|
5
|
+
${s.map((o)=>`${o}:${r[o]}`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
|
|
8
|
+
${s.join(";")}
|
|
9
|
+
${n}`}async createStringToSign(e,r,n,s){let o=new this.sha256;o.update(we(n));let i=await o.digest();return`${s}
|
|
10
|
+
${e}
|
|
11
|
+
${r}
|
|
12
|
+
${te(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let o of e.split("/")){if(o?.length===0)continue;if(o===".")continue;if(o==="..")r.pop();else r.push(o)}let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return ze(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!=="object"||typeof e.accessKeyId!=="string"||typeof e.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(e){let r=_s(e).replace(/[-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}var se={},Le=[],$e=(e,r,n)=>`${e}/${r}/${n}/${_t}`,$r=async(e,r,n,s,o)=>{let i=await br(e,r.secretAccessKey,r.accessKeyId),c=`${n}:${s}:${o}:${te(i)}:${r.sessionToken}`;if(c in se)return se[c];Le.push(c);while(Le.length>zr)delete se[Le.shift()];let a=`AWS4${r.secretAccessKey}`;for(let f of[n,s,o,_t])a=await br(e,a,f);return se[c]=a},As=()=>{Le.length=0,Object.keys(se).forEach((e)=>{delete se[e]})},br=(e,r,n)=>{let s=new e(r);return s.update(we(n)),s.digest()},pt=({headers:e},r,n)=>{let s={};for(let o of Object.keys(e).sort()){if(e[o]==null)continue;let i=o.toLowerCase();if(i in Mr||r?.has(i)||Br.test(i)||Ur.test(i)){if(!n||n&&!n.has(i))continue}s[i]=e[o].replace(/[\r\n]/g," ").replace(/[ \t]+/g," ").replace(/^ | $/g,"")}return s},Ve=async({headers:e,body:r},n)=>{for(let s in e){if(!ie(e,s))continue;if(s.toLowerCase()===Fe)return e[s]}if(r==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof r==="string"||ArrayBuffer.isView(r)||Ss(r)){let s=new n;return s.update(we(r)),te(await s.digest())}return jr},Vr=(e,r)=>{e=e.toLowerCase();for(let n in r){if(!ie(r,n))continue;if(e===n.toLowerCase())return!0}return!1},Fr=(e,r={})=>{let{headers:n,query:s={}}=xr.clone(e);for(let o in n){if(!ie(n,o))continue;let i=o.toLowerCase();if(i.slice(0,6)==="x-amz-"&&!r.unhoistableHeaders?.has(i)||r.hoistableHeaders?.has(i))s[o]=n[o],delete n[o]}return{...e,headers:n,query:s}},yt=(e)=>{e=xr.clone(e);for(let r in e.headers){if(!ie(e.headers,r))continue;if(Ir.indexOf(r.toLowerCase())>-1)delete e.headers[r]}return e};class Pr extends Ct{headerFormatter=new Er;constructor({applyChecksum:e,credentials:r,region:n,service:s,sha256:o,uriEscapePath:i=!0}){super({applyChecksum:e,credentials:r,region:n,service:s,sha256:o,uriEscapePath:i})}async presign(e,r={}){let{signingDate:n=new Date,expiresIn:s=3600,unsignableHeaders:o,unhoistableHeaders:i,signableHeaders:c,hoistableHeaders:a,signingRegion:f,signingService:u}=r,h=await this.credentialProvider();this.validateResolvedCredentials(h);let l=f??await this.regionProvider(),{longDate:d,shortDate:m}=this.formatDate(n);if(s>Or)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=$e(m,l,u??this.service),g=Fr(yt(e),{unhoistableHeaders:i,hoistableHeaders:a});if(h.sessionToken)g.query[xt]=h.sessionToken;g.query[Nr]=Oe,g.query[_r]=`${h.accessKeyId}/${y}`,g.query[wt]=d,g.query[Ar]=s.toString(10);let N=pt(g,o,c);return g.query[Cr]=this.getCanonicalHeaderList(N),g.query[bt]=await this.getSignature(d,y,this.getSigningKey(h,l,m,u),this.createCanonicalRequest(g,N,await Ve(e,this.sha256))),g}async sign(e,r){if(typeof e==="string")return this.signString(e,r);else if(e.headers&&e.payload)return this.signEvent(e,r);else if(e.message)return this.signMessage(e,r);else return this.signRequest(e,r)}async signEvent({headers:e,payload:r},{signingDate:n=new Date,priorSignature:s,signingRegion:o,signingService:i,eventStreamCredentials:c}){let a=o??await this.regionProvider(),{shortDate:f,longDate:u}=this.formatDate(n),h=$e(f,a,i??this.service),l=await Ve({headers:{},body:r},this.sha256),d=new this.sha256;d.update(e);let m=te(await d.digest()),y=[Dr,u,h,s,m,l].join(`
|
|
13
|
+
`);return this.signString(y,{signingDate:n,signingRegion:a,signingService:i,eventStreamCredentials:c})}async signMessage(e,{signingDate:r=new Date,signingRegion:n,signingService:s,eventStreamCredentials:o}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:r,signingRegion:n,signingService:s,priorSignature:e.priorSignature,eventStreamCredentials:o}).then((c)=>({message:e.message,signature:c}))}async signString(e,{signingDate:r=new Date,signingRegion:n,signingService:s,eventStreamCredentials:o}={}){let i=o??await this.credentialProvider();this.validateResolvedCredentials(i);let c=n??await this.regionProvider(),{shortDate:a}=this.formatDate(r),f=new this.sha256(await this.getSigningKey(i,c,a,s));return f.update(we(e)),te(await f.digest())}async signRequest(e,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:s,signingRegion:o,signingService:i}={}){let c=await this.credentialProvider();this.validateResolvedCredentials(c);let a=o??await this.regionProvider(),f=yt(e),{longDate:u,shortDate:h}=this.formatDate(r),l=$e(h,a,i??this.service);if(f.headers[Nt]=u,c.sessionToken)f.headers[Rr]=c.sessionToken;let d=await Ve(f,this.sha256);if(!Vr(Fe,f.headers)&&this.applyChecksum)f.headers[Fe]=d;let m=pt(f,s,n),y=await this.getSignature(u,l,this.getSigningKey(c,a,h,i),this.createCanonicalRequest(f,m,d));return f.headers[Et]=`${Oe} Credential=${c.accessKeyId}/${l}, SignedHeaders=${this.getCanonicalHeaderList(m)}, Signature=${y}`,f}async getSignature(e,r,n,s){let o=await this.createStringToSign(e,r,s,Oe),i=new this.sha256(await n);return i.update(we(o)),te(await i.digest())}getSigningKey(e,r,n,s){return $r(this.sha256,e,n,r,s||this.service)}}var Ts={SignatureV4a:null};Is.ALGORITHM_IDENTIFIER=Oe;Is.ALGORITHM_IDENTIFIER_V4A=Ns;Is.ALGORITHM_QUERY_PARAM=Nr;Is.ALWAYS_UNSIGNABLE_HEADERS=Mr;Is.AMZ_DATE_HEADER=Nt;Is.AMZ_DATE_QUERY_PARAM=wt;Is.AUTH_HEADER=Et;Is.CREDENTIAL_QUERY_PARAM=_r;Is.DATE_HEADER=Tr;Is.EVENT_ALGORITHM_IDENTIFIER=Dr;Is.EXPIRES_QUERY_PARAM=Ar;Is.GENERATED_HEADERS=Ir;Is.HOST_HEADER=xs;Is.KEY_TYPE_IDENTIFIER=_t;Is.MAX_CACHE_SIZE=zr;Is.MAX_PRESIGNED_TTL=Or;Is.PROXY_HEADER_PATTERN=Br;Is.REGION_SET_PARAM=bs;Is.SEC_HEADER_PATTERN=Ur;Is.SHA256_HEADER=Fe;Is.SIGNATURE_HEADER=kr;Is.SIGNATURE_QUERY_PARAM=bt;Is.SIGNED_HEADERS_QUERY_PARAM=Cr;Is.SignatureV4=Pr;Is.SignatureV4Base=Ct;Is.TOKEN_HEADER=Rr;Is.TOKEN_QUERY_PARAM=xt;Is.UNSIGNABLE_PATTERNS=Es;Is.UNSIGNED_PAYLOAD=jr;Is.clearCredentialCache=As;Is.createScope=$e;Is.getCanonicalHeaders=pt;Is.getCanonicalQuery=Lr;Is.getPayloadHash=Ve;Is.getSigningKey=$r;Is.hasHeader=Vr;Is.moveHeadersToQuery=Fr;Is.prepareRequest=yt;Is.signatureV4aContainer=Ts});var Ue=t(function(Ui){var{ProviderError:Hr,booleanSelector:Kr,SelectorType:qr,loadConfig:mi}=b(),{setCredentialFeature:gi}=L(),{normalizeProvider:oe,memoizeIdentityProvider:pi,isIdentityExpired:yi,doesIdentityRequireRefresh:Si}=ve(),{SignatureV4:Qr}=zo(),{HttpResponse:vr,HttpRequest:en}=B(),{SMITHY_CONTEXT_KEY:wi}=gt(),Gr=(e)=>vr.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,Wr=(e)=>vr.isInstance(e)?e.headers?.age??e.headers?.Age:void 0,tn=(e)=>new Date(Date.now()+e),Xr=(e,r,n,s)=>{if(s!==void 0)return r;let o=Date.parse(e),i=Date.now();if(n!==void 0&&i-n>900000)return r;return n!==void 0?o-(n+i)/2:o-i},xe=(e,r)=>{if(!r)throw Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return r},bi=(e)=>e.context?.[wi]?.eventStream?.output===!0,At=async(e)=>{let r=xe("context",e.context),n=xe("config",e.config),s=r.endpointV2?.properties?.authSchemes?.[0],i=await xe("signer",n.signer)(s),c=e?.signingRegion,a=e?.signingRegionSet,f=e?.signingName;return{config:n,signer:i,signingRegion:c,signingRegionSet:a,signingName:f}};class Pe{async sign(e,r,n){if(!en.isInstance(e))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let s=await At(n),{config:o,signer:i}=s,{signingRegion:c,signingName:a}=s,f=n.context;if(f?.authSchemes?.length??!1){let[d,m]=f.authSchemes;if(d?.name==="sigv4a"&&m?.name==="sigv4")c=m?.signingRegion??c,a=m?.signingName??a}let u=await o.disableClockSkewCorrection?.()===!0;n._disableClockSkewCorrection=u;let h=u||bi(n);if(n._skipClockSkewSampling=h,!h)n._preRequestSystemClockOffset=o.systemClockOffset,n._requestSentAt=Date.now();return await i.sign(e,{signingDate:u?new Date:tn(o.systemClockOffset),signingRegion:c,signingService:a})}errorHandler(e){return(r)=>{let n=r;if(!e._skipClockSkewSampling&&!e._disableClockSkewCorrection){let s=n.ServerTime??Gr(n.$response);if(s){let o=xe("config",e.config),{_preRequestSystemClockOffset:i,_requestSentAt:c}=e,a=Wr(n.$response),f=Xr(s,o.systemClockOffset,c,a);if(o.systemClockOffset=f,Math.abs(f)>=240000&&(f!==i||i!==void 0&&i!==f)&&n.$metadata)n.$metadata.clockSkewCorrected=!0}}throw r}}successHandler(e,r){if(r._skipClockSkewSampling||r._disableClockSkewCorrection)return;let n=Gr(e);if(n){let s=xe("config",r.config),o=r._requestSentAt,i=Wr(e);s.systemClockOffset=Xr(n,s.systemClockOffset,o,i)}}}var xi=Pe;class rn extends Pe{async sign(e,r,n){if(!en.isInstance(e))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:s,signer:o,signingRegion:i,signingRegionSet:c,signingName:a}=await At(n),u=(await s.sigv4aSigningRegionSet?.()??c??[i]).join(","),h=await s.disableClockSkewCorrection?.()===!0;if(n._disableClockSkewCorrection=h,!h)n._preRequestSystemClockOffset=s.systemClockOffset,n._requestSentAt=Date.now();return await o.sign(e,{signingDate:h?new Date:tn(s.systemClockOffset),signingRegion:u,signingService:a})}}var Jr=(e)=>typeof e==="string"&&e.length>0?e.split(",").map((r)=>r.trim()):[],nn=(e)=>`AWS_BEARER_TOKEN_${e.replace(/[\s-]/g,"_").toUpperCase()}`,Zr="AWS_AUTH_SCHEME_PREFERENCE",Yr="auth_scheme_preference",Ei={environmentVariableSelector:(e,r)=>{if(r?.signingName){if(nn(r.signingName)in e)return["httpBearerAuth"]}if(!(Zr in e))return;return Jr(e[Zr])},configFileSelector:(e)=>{if(!(Yr in e))return;return Jr(e[Yr])},default:[]},Ni=(e)=>(e.sigv4aSigningRegionSet=oe(e.sigv4aSigningRegionSet),e),_i={environmentVariableSelector(e){if(e.AWS_SIGV4A_SIGNING_REGION_SET)return e.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((r)=>r.trim());throw new Hr("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(e){if(e.sigv4a_signing_region_set)return(e.sigv4a_signing_region_set??"").split(",").map((r)=>r.trim());throw new Hr("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},Ci=(e)=>(r)=>{let n=r.credentials,s=!!r.credentials,o=void 0;Object.defineProperty(r,"credentials",{set(h){if(h&&h!==n&&h!==o)s=!0;n=h;let l=Ai(r,{credentials:n,credentialDefaultProvider:r.credentialDefaultProvider}),d=Ti(r,l);if(s&&!d.attributed){let m=typeof n==="object"&&n!==null;o=async(y)=>{let N=await d(y);if(m&&(!N.$source||Object.keys(N.$source).length===0))return gi(N,"CREDENTIALS_CODE","e");return N},o.memoized=d.memoized,o.configBound=d.configBound,o.attributed=!0}else o=d},get(){return o},enumerable:!0,configurable:!0}),r.credentials=n;let{signingEscapePath:i=!0,systemClockOffset:c=r.systemClockOffset||0,sha256:a}=r,f;if(r.signer)f=oe(r.signer);else if(r.regionInfoProvider)f=()=>oe(r.region)().then(async(h)=>[await r.regionInfoProvider(h,{useFipsEndpoint:await r.useFipsEndpoint(),useDualstackEndpoint:await r.useDualstackEndpoint()})||{},h]).then(([h,l])=>{let{signingRegion:d,signingService:m}=h;r.signingRegion=r.signingRegion||d||l,r.signingName=r.signingName||m||r.serviceId;let y={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:a,uriEscapePath:i};return new(r.signerConstructor||Qr)(y)});else f=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:r.signingName||r.defaultSigningName,signingRegion:await oe(r.region)(),properties:{}},h);let l=h.signingRegion,d=h.signingName;r.signingRegion=r.signingRegion||l,r.signingName=r.signingName||d||r.serviceId;let m={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:a,uriEscapePath:i};return new(r.signerConstructor||Qr)(m)};return Object.assign(r,{systemClockOffset:c,signingEscapePath:i,signer:f,disableClockSkewCorrection:oe(r.disableClockSkewCorrection??e)})};function Ai(e,{credentials:r,credentialDefaultProvider:n}){let s;if(r)if(!r?.memoized)s=pi(r,yi,Si);else s=r;else if(n)s=oe(n(Object.assign({},e,{parentClientConfig:e})));else s=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return s.memoized=!0,s}function Ti(e,r){if(r.configBound)return r;let n=async(s)=>r({...s,callerClientConfig:e});return n.memoized=r.memoized,n.configBound=!0,n}var Ii="AWS_DISABLE_CLOCK_SKEW_CORRECTION",ki="disable_clock_skew_correction",Ri={environmentVariableSelector:(e)=>Kr(e,Ii,qr.ENV),configFileSelector:(e)=>Kr(e,ki,qr.CONFIG),default:!1},Mi=mi(Ri),sn=Ci(Mi),Bi=sn;Ui.AWSSDKSigV4Signer=xi;Ui.AwsSdkSigV4ASigner=rn;Ui.AwsSdkSigV4Signer=Pe;Ui.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=Ei;Ui.NODE_SIGV4A_CONFIG_OPTIONS=_i;Ui.getBearerTokenEnvKey=nn;Ui.resolveAWSSDKSigV4Config=Bi;Ui.resolveAwsSdkSigV4AConfig=Ni;Ui.resolveAwsSdkSigV4Config=sn;Ui.validateSigningProperties=At});var Bn=t(function($o){var{nv:pn,NumericValue:Ie,calculateBodyLength:Ki,generateIdempotencyToken:yn,fromBase64:Ot,_parseEpochTimestamp:Ae}=X(),{hasOwn:D,getSmithyContext:qi}=Ne(),{HttpRequest:Qi,collectBody:Gi,SerdeContext:ke,RpcProtocol:Wi}=B(),{NormalizedSchema:F,deref:Xi,TypeRegistry:on}=be();function de(e){return typeof Buffer<"u"?Buffer.alloc(e):new Uint8Array(e)}var Re=Symbol("@smithy/core/cbor::tagSymbol");function Lt(e){return e[Re]=!0,e}var Sn=typeof Buffer<"u",$t=new TextDecoder,C=de(0),Vt=!1,P=new DataView(C.buffer,C.byteOffset,C.byteLength),E=0;function Ji(e){C=e,Vt=Sn&&C instanceof Buffer,P=new DataView(C.buffer,C.byteOffset,C.byteLength)}function Z(e,r){if(e>=r)throw Error("unexpected end of (decode) payload.");let n=(C[e]&224)>>5,s=C[e]&31;if(s===31&&2<=n&&n<=5)return Zi(e,r);switch(n){case 0:case 1:case 6:{let o,i;if(s<24)o=s,i=1;else switch(s){case 24:if(r-e<2)q(1);o=C[e+1],i=2;break;case 25:if(r-e<3)q(2);o=P.getUint16(e+1),i=3;break;case 26:if(r-e<5)q(4);o=P.getUint32(e+1),i=5;break;case 27:if(r-e<9)q(8);{let c=P.getUint32(e+1);if(c<2097152)o=c*4294967296+P.getUint32(e+5);else o=P.getBigUint64(e+1)}i=9;break;default:Pt(s)}if(n===0)return E=i,Bt(o);else if(n===1){let c;if(typeof o==="bigint")c=BigInt(-1)-o;else c=-1-o;return E=i,Bt(c)}else return io(e,r,s,o,i)}case 3:return Te(e,r);case 5:return vi(e,r);case 4:return ro(e,r);case 2:return Ft(e,r);default:return oo(e,r)}}function Zi(e,r){let n=(C[e]&224)>>5;if((C[e]&31)===31)switch(n){case 3:return fo(e,r);case 5:return co(e,r);case 4:return ao(e,r);case 2:return uo(e,r)}}function Yi(e,r){let n=e>>7,s=(e&124)>>2,o=(e&3)<<8|r,i=n===0?1:-1;if(s===0){if(o===0)return 0;return i*(Math.pow(2,-14)*(o/1024))}else if(s===31){if(o===0)return i*(1/0);return NaN}return i*(Math.pow(2,s-15)*(1+o/1024))}function vi(e,r){let n=Me(e,r);if(n<25)return to(e,r,n);return eo(e,r,n)}function eo(e,r,n){let s=E;e+=s;let o=e,i=Object.create(null);for(let c=0;c<n;++c){let a=Te(e,r);if(e+=E,(C[e]&224)>>5===3)i[a]=Te(e,r);else i[a]=Z(e,r);e+=E}return E=s+(e-o),Object.setPrototypeOf(i,Object.prototype),i}function to(e,r,n){let s=E;e+=s;let o=e,i={};for(let c=0;c<n;++c){let a=Te(e,r);e+=E,i[a]=Z(e,r),e+=E}return E=s+(e-o),i}function ro(e,r){let n=Me(e,r),s=E;e+=s;let o=e,i=Array(n);for(let c=0;c<n;++c)i[c]=Z(e,r),e+=E;return E=s+(e-o),i}function Te(e,r){let n=Me(e,r),s=E;if(e+=s,r-e<n)q(n);if(E=s+n,n<24)return so(e,n);if(Vt)return C.toString("utf-8",e,e+n);return $t.decode(C.subarray(e,e+n))}var cn=Array(2048),Tt=new Uint16Array(2048),Ee=0;function no(){Ee=Ee+1&65535}function so(e,r){let n=r;for(let c=0;c<r;++c)n=n*31+C[e+c]|0;let s=n>>>0&2047,o=cn[s];if(o!==void 0){if(o.length===r){let c=!0;for(let a=0;a<r;++a)if(o.charCodeAt(a)!==C[e+a]){c=!1;break}if(c)return Tt[s]=Ee,o}}let i=Vt?C.toString("utf-8",e,e+r):$t.decode(C.subarray(e,e+r));if(Tt[s]!==Ee)cn[s]=i,Tt[s]=Ee;return i}function Ft(e,r){let n=Me(e,r),s=E;if(e+=s,r-e<n)q(n);let o=C.subarray(e,e+n);return E=s+n,o}function io(e,r,n,s,o){if(n===2||n===3){let i=Me(e+o,r),c=BigInt(0),a=e+o+E;for(let f=a;f<a+i;++f)c=c<<BigInt(8)|BigInt(C[f]);return E=o+E+i,n===3?-c-BigInt(1):c}else if(n===4){let i=Z(e+o,r),[c,a]=i,f=a<0?-1:1,u=BigInt(f)*BigInt(a),h=String(u),l=a<0?"-":"",d;if(typeof c==="number"&&Math.abs(c)<=268435456){let y=c,g="0".repeat(Math.abs(y)+1)+h;if(d=y===0?g:g.slice(0,g.length+y)+"."+g.slice(y),d=d.replace(/^0+/g,""),d==="")d="0";if(d[0]===".")d="0"+d;d=l+d}else{let y=BigInt(c);if(h.length===1)d=l+h+"e"+String(y);else{let g=y+BigInt(h.length-1);d=l+h[0]+"."+h.slice(1)+"e"+String(g)}}return E=o+E,pn(d)}else{let i=Z(e+o,r);return E=o+E,Lt({tag:Bt(s),value:i})}}function oo(e,r){let n=C[e]&31;switch(n){case 21:case 20:return E=1,n===21;case 22:return E=1,null;case 23:return E=1,null;case 25:if(r-e<3)throw Error("incomplete float16 at end of buf.");return E=3,Yi(C[e+1],C[e+2]);case 26:if(r-e<5)throw Error("incomplete float32 at end of buf.");return E=5,P.getFloat32(e+1);case 27:if(r-e<9)throw Error("incomplete float64 at end of buf.");return E=9,P.getFloat64(e+1);default:Pt(n)}}function Me(e,r){let n=C[e]&31;if(n<24)return E=1,n;switch(n){case 24:if(r-e<2)q(1);return E=2,C[e+1];case 25:if(r-e<3)q(2);return E=3,P.getUint16(e+1);case 26:if(r-e<5)q(4);return E=5,P.getUint32(e+1);case 27:if(r-e<9)q(8);return E=9,ho(P.getBigUint64(e+1));default:Pt(n)}}function co(e,r){e+=1;let n=e,s={};for(;e<r;){if(C[e]===255)return E=e-n+2,s;let o=Te(e,r);e+=E,s[o]=Z(e,r),e+=E}throw Error("expected break marker.")}function ao(e,r){e+=1;let n=[];for(let s=e;e<r;){if(C[e]===255)return E=e-s+2,n;n.push(Z(e,r)),e+=E}throw Error("expected break marker.")}function fo(e,r){e+=1;let n=[];for(let s=e;e<r;){if(C[e]===255){let f=de(n.length);if(f.set(n,0),E=e-s+2,Sn)return f.toString("utf-8",0,f.length);return $t.decode(f)}let o=(C[e]&224)>>5,i=C[e]&31;if(o!==3)wn(o);if(i===31)throw Error("nested indefinite string.");let c=Ft(e,r);e+=E;for(let f=0;f<c.length;++f)n.push(c[f])}throw Error("expected break marker.")}function uo(e,r){e+=1;let n=[];for(let s=e;e<r;){if(C[e]===255){let f=de(n.length);return f.set(n,0),E=e-s+2,f}let o=(C[e]&224)>>5,i=C[e]&31;if(o!==2)wn(o);if(i===31)throw Error("nested indefinite string.");let c=Ft(e,r);e+=E;for(let f=0;f<c.length;++f)n.push(c[f])}throw Error("expected break marker.")}function Bt(e){if(typeof e==="number")return e;let r=Number(e);if(Number.MIN_SAFE_INTEGER<=r&&r<=Number.MAX_SAFE_INTEGER)return r;return e}function ho(e){let r=Number(e);if(r<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<r)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${e}) to ${r} with loss of precision.`));return r}function q(e){throw Error(`length ${e} greater than remaining buf len.`)}function Pt(e){throw Error(`unexpected minor value ${e}.`)}function wn(e){throw Error(`unexpected major type ${e} in indefinite string.`)}var lo=typeof Buffer<"u",ce=new Map,_e=0,Ut=!1,mo=2048,w=de(mo),V=new DataView(w.buffer,w.byteOffset,w.byteLength),p=0;function go(e){let r=[e];while(r.length){let n=r.pop();if(typeof n==="string"){let s=n.length;if(lo)if(ae(s*3+9),s>23)It(3,Buffer.byteLength(n)),p+=w.write(n,p);else yo(n);else{let o=s*3;ae(o+9);let i=p,a=new TextEncoder().encodeInto(n,w.subarray(p+9)).written,f;if(a<24)f=1;else if(a<256)f=2;else if(a<65536)f=3;else if(a<4294967296)f=5;else f=9;if(f<9)w.copyWithin(i+f,i+9,i+9+a);p=i,re(3,a),p+=a}continue}if(w.byteLength-p<9)ae(64);if(typeof n==="number"){if(Number.isInteger(n)&&n>=-9007199254740992&&n<=9007199254740991){let s=n>=0,o=s?0:1,i=s?n:-n-1;if(i<24)w[p++]=o<<5|i;else if(i<256)w[p++]=o<<5|24,w[p++]=i;else if(i<65536)w[p++]=o<<5|25,w[p++]=i>>8,w[p++]=i&255;else if(i<4294967296)w[p++]=o<<5|26,V.setUint32(p,i),p+=4;else{w[p++]=o<<5|27;let c=i/4294967296|0,a=i-c*4294967296|0;V.setUint32(p,c),V.setUint32(p+4,a),p+=8}continue}w[p++]=251,V.setFloat64(p,n),p+=8;continue}else if(typeof n==="bigint"){let s=n>=0,o=s?0:1,i=s?n:-n-BigInt(1);if(i<BigInt("18446744073709551616")){let c=Number(i);if(c<4294967296)re(o,c);else w[p++]=o<<5|27,V.setBigUint64(p,i),p+=8}else{let c=i.toString(2),a=new Uint8Array(Math.ceil(c.length/8)),f=i,u=0;while(a.byteLength-++u>=0)a[a.byteLength-u]=Number(f&BigInt(255)),f>>=BigInt(8);ae(a.byteLength*2+16),w[p++]=s?194:195,It(2,a.byteLength),w.set(a,p),p+=a.byteLength}continue}else if(n===null){w[p++]=246;continue}else if(typeof n==="boolean"){w[p++]=224|(n?21:20);continue}else if(typeof n>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(n)){re(4,n.length),ae(n.length*9+64);for(let s=n.length-1;s>=0;--s)r.push(n[s]);continue}else if(typeof n.byteLength==="number"){ae(n.length*2+9),re(2,n.length),w.set(n,p),p+=n.byteLength;continue}else if(typeof n==="object"){if(n instanceof Ie){let i=n.string,c=BigInt(0),a=i.search(/[eE]/);if(a!==-1)c=BigInt(i.slice(a+1)),i=i.slice(0,a);let f=i.indexOf("."),u=f===-1?0:i.length-f-1,h=c-BigInt(u),l=BigInt(i.replace(".",""));w[p++]=196,re(4,2),r.push(l),r.push(h>=-0x20000000000000n&&h<=0x1fffffffffffffn?Number(h):h);continue}if(n[Re])if("tag"in n&&"value"in n){r.push(n.value),It(6,n.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(n));let s=Object.keys(n),o=s.length;re(5,o);for(let i=o-1;i>=0;--i)r.push(n[s[i]]),r.push(s[i]);continue}throw Error(`data type ${n?.constructor?.name??typeof n} not compatible for encoding.`)}}function po(){_e=_e+1&65535,Ut=!1}function an(){let e=de(p);return e.set(w.subarray(0,p),0),p=0,e}function Dt(e){let r=w;if(w=de(e),r)if(r.copy)r.copy(w,0,0,r.byteLength);else w.set(r,0);V=new DataView(w.buffer,w.byteOffset,w.byteLength)}function yo(e){let r=ce.get(e);if(r!==void 0){w.set(r.bytes,p),p+=r.bytes.length,r.epoch=_e;return}let n=p,s=Buffer.byteLength(e);re(3,s),p+=w.write(e,p);let o=Uint8Array.prototype.slice.call(w,n,p);if(ce.size>=2048){if(Ut)return;let i=0;for(let[c,a]of ce){if(i>=1024)break;if(a.epoch!==_e)ce.delete(c),i++}if(i===0){Ut=!0;return}}if(ce.size<2048)ce.set(e,{epoch:_e,bytes:o})}function ae(e){if(w.byteLength-p<e)if(p<16000000)Dt(Math.max(w.byteLength*4,w.byteLength+e));else Dt(w.byteLength+e+16000000)}function It(e,r){if(r<24)w[p++]=e<<5|r;else if(r<256)w[p++]=e<<5|24,w[p++]=r;else if(r<65536)w[p++]=e<<5|25,V.setUint16(p,r),p+=2;else if(r<4294967296)w[p++]=e<<5|26,V.setUint32(p,r),p+=4;else w[p++]=e<<5|27,V.setBigUint64(p,typeof r==="bigint"?r:BigInt(r)),p+=8}function re(e,r){if(r<24)w[p++]=e<<5|r;else if(r<256)w[p++]=e<<5|24,w[p++]=r;else if(r<65536)w[p++]=e<<5|25,w[p++]=r>>8,w[p++]=r&255;else if(r<4294967296)w[p++]=e<<5|26,V.setUint32(p,r),p+=4;else{w[p++]=e<<5|27;let n=r/4294967296|0,s=r-n*4294967296|0;V.setUint32(p,n),V.setUint32(p+4,s),p+=8}}var Ge={deserialize(e){return no(),Ji(e),Z(0,e.length)},serialize(e){po();try{return go(e),an()}catch(r){throw an(),r}},resizeEncodingBuffer(e){Dt(e)}},bn=(e,r)=>Gi(e,r).then(async(n)=>{if(n.length)try{return Ge.deserialize(n)}catch(s){throw Object.defineProperty(s,"$responseBodyText",{value:r.utf8Encoder(n)}),s}return{}}),He=(e)=>Lt({tag:1,value:e.getTime()/1000}),So=async(e,r)=>{let n=await bn(e,r);return n.message=n.message??n.Message,n},xn=(e,r)=>{let n=(s)=>{let o=s;if(typeof o==="number")o=o.toString();if(o.indexOf(",")>=0)o=o.split(",")[0];if(o.indexOf(":")>=0)o=o.split(":")[0];return o};if(r.__type!==void 0)return n(r.__type)},wo=(e)=>{if(String(e.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+e.statusCode)},bo=async(e,r,n,s,o)=>{let i=await e.endpoint(),{hostname:c,protocol:a="https",port:f,path:u}=i,h={protocol:a,hostname:c,port:f,method:"POST",path:u.endsWith("/")?u.slice(0,-1)+n:u+n,headers:{...r}};if(s!==void 0)h.hostname=s;if(i.headers)for(let l in i.headers){if(!D(i.headers,l))continue;h.headers[l]=i.headers[l]}if(o!==void 0){h.body=o;try{h.headers["content-length"]=String(Ki(o))}catch(l){}}return new Qi(h)};class Ht extends ke{write(e,r){x=0;let n=F.of(e);ue(n,r,void 0,this.serdeContext)}flush(){let e=_.subarray(0,x);return x=0,_=En(jt),ne=new DataView(_.buffer,_.byteOffset,_.byteLength),e}}var fn=Symbol.for("@smithy/cbor-struct-cache");function Kt(e){let r=e.getSchema(),n=r[fn];if(n)return n;let s=[],o=[];for(let[a,f]of e.structIterator())s.push(a),o.push(f);let i=Array(s.length);for(let a=0;a<s.length;++a)i[a]=xo(s[a]);let c={memberNames:s,memberSchemas:o,encodedKeys:i};return r[fn]=c,c}function xo(e){let r;if(We)r=Buffer.from(e,"utf-8");else r=new TextEncoder().encode(e);let n=r.length,s;if(n<24)s=1;else if(n<256)s=2;else s=3;let o=new Uint8Array(s+n);if(s===1)o[0]=96|n;else if(s===2)o[0]=120,o[1]=n;else o[0]=121,o[1]=n>>8,o[2]=n&255;return o.set(r,s),o}var We=typeof Buffer<"u",Eo=new TextEncoder,jt=2048,_=We?Buffer.allocUnsafe(jt):new Uint8Array(jt),ne=new DataView(_.buffer,_.byteOffset,_.byteLength),x=0,un=2048,fe=new Map,kt=0,hn=!1;function En(e){return We?Buffer.allocUnsafe(e):new Uint8Array(e)}function ue(e,r,n,s){if(r==null){if(r===void 0&&e.isIdempotencyToken()){Q(yn());return}A(1),_[x++]=246;return}if(e.isUnitSchema()){A(1),M(5,0);return}if(typeof r==="object"){if(e.isBlobSchema()){if(r instanceof Uint8Array){Ke(r);return}}if(e.isTimestampSchema()){if(r instanceof Date){zt(r);return}}if(e.isStructSchema()){No(e,r,s);return}if(Array.isArray(r)&&(e.isListSchema()||e.isDocumentSchema())){ln(e,r,e.isDocumentSchema(),s);return}if(e.isMapSchema()){Rt(e,r,!1,s);return}if(r instanceof Date){zt(r);return}if(r instanceof Uint8Array){Ke(r);return}if(r instanceof Ie){Cn(r);return}if(r[Re]){let i=r;_n(i.tag,i.value);return}if(e.isDocumentSchema()){if(Array.isArray(r))ln(e,r,!0,s);else Rt(e,r,!0,s);return}if(e.isBigDecimalSchema()){he(r);return}Rt(e,r,!0,s);return}if(typeof r==="string"){if(e.isBlobSchema()){let i=(s?.base64Decoder??Ot)(r);Ke(i);return}Q(r);return}if(typeof r==="number"){if(A(9),Number.isInteger(r)&&r>=-9007199254740992&&r<=9007199254740991)Xe(r);else qt(r);return}if(typeof r==="boolean"){A(1),_[x++]=224|(r?21:20);return}if(typeof r==="bigint"){Qe(r);return}Q(String(r))}function No(e,r,n){if(e.isUnionSchema()){let l=!1;for(let[d,m]of e.structIterator()){let y=r[d];if(y!=null){A(9),M(5,1),Q(d),ue(m,y,e,n),l=!0;break}}if(!l){let{$unknown:d}=r;if(Array.isArray(d))A(9),M(5,1),Q(d[0]),he(d[1]);else A(9),M(5,0)}return}let s=Kt(e),{memberNames:o,memberSchemas:i,encodedKeys:c}=s,a=o.length,f;if(a<24)f=1;else if(a<256)f=2;else f=3;A(f);let u=x;x+=f;let h=0;for(let l=0;l<a;++l){let d=r[o[l]];if(d==null&&!i[l].isIdempotencyToken())continue;let m=c[l];A(m.length),_.set(m,x),x+=m.length,ue(i[l],d,e,n),++h}if(typeof r.__type==="string")for(let l in r){if(!D(r,l))continue;if(!o.includes(l))Q(l),he(r[l]),++h}if(f===1)_[u]=160|h;else if(f===2)_[u]=184,_[u+1]=h;else _[u]=185,_[u+1]=h>>8,_[u+2]=h&255}function ln(e,r,n,s){let o=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(n||o){let c=[];for(let a=0;a<r.length;++a){let f=r[a];if(n){if(f!==void 0)c.push(f)}else if(f!=null||o)c.push(f)}A(9),M(4,c.length);for(let a=0;a<c.length;++a)ue(i,c[a],void 0,s)}else{let c=0;for(let a=0;a<r.length;++a)if(r[a]!=null)++c;A(9),M(4,c);for(let a=0;a<r.length;++a)if(r[a]!=null)ue(i,r[a],void 0,s)}}function Rt(e,r,n,s){let o=!!e.getMergedTraits().sparse,i=e.getValueSchema(),c=[];for(let a in r){if(!D(r,a))continue;let f=r[a];if(n?f!==void 0:f!=null||o)c.push(a)}A(9),M(5,c.length);for(let a=0;a<c.length;++a){let f=c[a];Q(f),ue(i,r[f],void 0,s)}}function he(e){if(e==null){A(1),_[x++]=246;return}if(typeof e==="string"){Q(e);return}if(typeof e==="number"){if(A(9),Number.isInteger(e)&&e>=-9007199254740992&&e<=9007199254740991)Xe(e);else qt(e);return}if(typeof e==="boolean"){A(1),_[x++]=224|(e?21:20);return}if(typeof e==="bigint"){Qe(e);return}if(e instanceof Uint8Array){Ke(e);return}if(e instanceof Date){zt(e);return}if(e instanceof Ie){Cn(e);return}if(e[Re]){let r=e;_n(r.tag,r.value);return}if(Array.isArray(e)){A(9),M(4,e.length);for(let r=0;r<e.length;++r)he(e[r]);return}if(typeof e==="object"){let r=Object.keys(e);A(9),M(5,r.length);for(let n=0;n<r.length;++n)Q(r[n]),he(e[r[n]]);return}Q(String(e))}function A(e){if(x+e>_.length){let r=_.length*2;while(r<x+e)r*=2;let n=En(r);n.set(_.subarray(0,x)),_=n,ne=new DataView(n.buffer,n.byteOffset,n.byteLength)}}function M(e,r){if(r<24)_[x++]=e<<5|r;else if(r<256)_[x++]=e<<5|24,_[x++]=r;else if(r<65536)_[x++]=e<<5|25,_[x++]=r>>8,_[x++]=r&255;else if(r<4294967296)_[x++]=e<<5|26,ne.setUint32(x,r),x+=4;else{_[x++]=e<<5|27;let n=r/4294967296|0,s=r-n*4294967296|0;ne.setUint32(x,n),ne.setUint32(x+4,s),x+=8}}function Nn(e,r){let n=Number(r);if(n<4294967296){M(e,n);return}_[x++]=e<<5|27,ne.setBigUint64(x,r),x+=8}function Q(e){let r=e.length;if(r<=23){let n=fe.get(e);if(n){A(n.bytes.length),_.set(n.bytes,x),x+=n.bytes.length,n.epoch=kt;return}let s=x;dn(e,r);let o=x,i=Uint8Array.prototype.slice.call(_,s,o);if(fe.size>=un){if(hn)return;let c=0;for(let[a,f]of fe){if(c>=1024)break;if(f.epoch!==kt)fe.delete(a),++c}if(c===0){hn=!0;return}}if(fe.size<un)fe.set(e,{epoch:kt,bytes:i});return}dn(e,r)}function dn(e,r){if(We){let n=r*3;A(n+9);let s=Buffer.byteLength(e);M(3,s),x+=_.write(e,x)}else{let n=r*3;A(n+9);let s=x,i=Eo.encodeInto(e,_.subarray(s+9)).written,c;if(i<24)c=1;else if(i<256)c=2;else if(i<65536)c=3;else if(i<4294967296)c=5;else c=9;if(c<9)_.copyWithin(s+c,s+9,s+9+i);x=s,M(3,i),x+=i}}function qt(e){A(9),_[x++]=251,ne.setFloat64(x,e),x+=8}function Xe(e){A(9);let r=e>=0,n=r?0:1,s=r?e:-e-1;M(n,s)}function Qe(e){let r=e>=0,n=r?0:1,s=r?e:-e-BigInt(1);if(s<BigInt("18446744073709551616"))A(9),Nn(n,s);else{let o=s.toString(2),i=Math.ceil(o.length/8),c=new Uint8Array(i),a=s;for(let f=i-1;f>=0;--f)c[f]=Number(a&BigInt(255)),a>>=BigInt(8);A(i+16),_[x++]=r?194:195,M(2,i),_.set(c,x),x+=i}}function Ke(e){A(e.length+9),M(2,e.length),_.set(e,x),x+=e.length}function _n(e,r){if(A(9),typeof e==="bigint")Nn(6,e);else M(6,e);he(r)}function Cn(e){let r=e.string,n=BigInt(0),s=r.search(/[eE]/);if(s!==-1)n=BigInt(r.slice(s+1)),r=r.slice(0,s);let o=r.indexOf("."),i=o===-1?0:r.length-o-1,c=n-BigInt(i),a=BigInt(r.replace(".",""));if(A(9),_[x++]=196,M(4,2),A(9),c>=-0x20000000000000n&&c<=0x1fffffffffffffn)Xe(Number(c));else Qe(c);Qe(a)}function zt(e){A(18),M(6,1);let r=e.getTime()/1000;if(Number.isInteger(r))Xe(r);else qt(r)}class Qt extends ke{read(e,r){return k=r,Wt=An&&r instanceof Buffer,J=new DataView(r.buffer,r.byteOffset,r.byteLength),S=0,R=r.length,Ce=Ce+1&65535,O(F.of(e))}readValue(e,r){return qe(F.of(e),r)}}var An=typeof Buffer<"u",Gt=new TextDecoder,k=new Uint8Array(0),Wt=!1,J=new DataView(new ArrayBuffer(0)),S=0,R=0,Xt=2048,mn=Array(Xt),Mt=new Uint16Array(Xt),Ce=0;function O(e){if(S>=R)throw Error("unexpected end of CBOR payload.");let r=(k[S]&224)>>5;if((k[S]&31)===31&&r>=2&&r<=5)return Io(e,r);switch(r){case 0:return Uo();case 1:return Do();case 2:return Ye();case 3:return le();case 4:return _o(e);case 5:return Co(e);case 6:return To();case 7:return Oo();default:throw Error(`unexpected CBOR major type ${r}.`)}}function _o(e){let r=Ze(),n=e.isListSchema()?e.getValueSchema():e,s=Array(r);for(let o=0;o<r;++o)s[o]=O(n);return s}function Co(e){let r=Ze();if(e.isStructSchema())return Ao(e,r,S);let n=e.isMapSchema()?e.getValueSchema():e,s={};for(let o=0;o<r;++o){let i=le();s[i]=O(n)}return s}function Ao(e,r,n){let s=e.isUnionSchema(),o=Kt(e),{memberSchemas:i,encodedKeys:c,memberNames:a}=o,f=c.length,u={},h,l,d=0,m=!1,y=0;for(let g=0;g<r;++g){let N=Tn(c,f,y);if(N>=0){if(y=N+1,y>=f)y=0;let I=O(i[N]);if(I!=null)u[a[N]]=I}else{let I=le(),j=O(F.of(15));if(I==="__type"&&typeof j==="string")m=!0;else h=I,l=j,++d}}if(s){let g=!0;for(let N in u){if(!D(u,N))continue;g=!1;break}if(g&&d===1)u.$unknown=[h,l]}else if(m){S=n;let g=F.of(15);for(let N=0;N<r;++N){let I=le(),j=O(g);if(!(I in u))u[I]=j}}return u}function To(e){let r=Je(),n=typeof r==="bigint"?Number(r):r;if(n===1){let i=F.of(15),c=O(i);return Ae(c)}if(n===2||n===3){let i=Ye(),c=BigInt(0);for(let a=0;a<i.length;++a)c=c<<BigInt(8)|BigInt(i[a]);return n===3?-c-BigInt(1):c}if(n===4){let i=F.of(15),c=O(i),[a,f]=c,u=f<0?-1:1,h=BigInt(u)*BigInt(f),l=String(h),d=f<0?"-":"",m;if(typeof a==="number"&&Math.abs(a)<=268435456){let g=a,N="0".repeat(Math.abs(g)+1)+l;if(m=g===0?N:N.slice(0,N.length+g)+"."+N.slice(g),m=m.replace(/^0+/g,""),m==="")m="0";if(m[0]===".")m="0"+m;m=d+m}else{let g=BigInt(a);if(l.length===1)m=d+l+"e"+String(g);else{let N=g+BigInt(l.length-1);m=d+l[0]+"."+l.slice(1)+"e"+String(N)}}return pn(m)}let s=F.of(15),o=O(s);return{tag:In(r),value:o}}function Io(e,r){switch(r){case 3:return ko();case 2:return Ro();case 4:return Mo(e);case 5:return Bo(e);default:throw Error(`unexpected indefinite length for major ${r}.`)}}function ko(){S+=1;let e=[],r=0;while(S<R){if(k[S]===255){S+=1;let s=new Uint8Array(r),o=0;for(let i=0;i<e.length;++i)s.set(e[i],o),o+=e[i].length;if(An)return Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("utf-8");return Gt.decode(s)}let n=Ye();e.push(n),r+=n.length}throw Error("expected break marker.")}function Ro(){S+=1;let e=[],r=0;while(S<R){if(k[S]===255){S+=1;let s=new Uint8Array(r),o=0;for(let i=0;i<e.length;++i)s.set(e[i],o),o+=e[i].length;return s}let n=Ye();e.push(n),r+=n.length}throw Error("expected break marker.")}function Mo(e){S+=1;let r=e.isListSchema()?e.getValueSchema():e,n=[];while(S<R){if(k[S]===255)return S+=1,n;n.push(O(r))}throw Error("expected break marker.")}function Bo(e){if(S+=1,e.isStructSchema()){let s=Kt(e),{memberSchemas:o,encodedKeys:i,memberNames:c}=s,a=i.length,f=e.isUnionSchema(),u={},h,l,d=0,m=0;while(S<R){if(k[S]===255){if(S+=1,f){let g=!0;for(let N in u){if(!D(u,N))continue;g=!1;break}if(g&&d===1)u.$unknown=[h,l]}return u}let y=Tn(i,a,m);if(y>=0){if(m=y+1,m>=a)m=0;let g=O(o[y]);if(g!=null)u[c[y]]=g}else{let g=le(),N=O(F.of(15));if(g!=="__type")h=g,l=N,++d}}throw Error("expected break marker.")}let r=e.isMapSchema()?e.getValueSchema():e,n={};while(S<R){if(k[S]===255)return S+=1,n;let s=le();n[s]=O(r)}throw Error("expected break marker.")}function Tn(e,r,n){let s=e[n];if(S+s.length<=R&&gn(S,s))return S+=s.length,n;for(let o=0;o<r;++o){if(o===n)continue;let i=e[o];if(S+i.length<=R&&gn(S,i))return S+=i.length,o}return-1}function gn(e,r){let n=r.length;if(k[e]!==r[0])return!1;for(let s=1;s<n;++s)if(k[e+s]!==r[s])return!1;return!0}function Je(){let e=k[S]&31;if(e<24)return S+=1,e;switch(e){case 24:if(R-S<2)W(1);return S+=2,k[S-1];case 25:if(R-S<3)W(2);return S+=3,J.getUint16(S-2);case 26:if(R-S<5)W(4);return S+=5,J.getUint32(S-4);case 27:{if(R-S<9)W(8);S+=9;let r=J.getUint32(S-8);if(r<2097152)return r*4294967296+J.getUint32(S-4);return J.getBigUint64(S-8)}default:throw Error(`unexpected minor value ${e}.`)}}function Ze(){let e=Je();return typeof e==="bigint"?Number(e):e}function Uo(){let e=Je();return In(e)}function Do(){let e=Je();if(typeof e==="bigint")return BigInt(-1)-e;return-1-e}function Ye(){let e=Ze();if(R-S<e)W(e);let r=S;return S+=e,k.subarray(r,r+e)}function le(){let e=Ze();if(R-S<e)W(e);let r=S;if(S+=e,e<24)return jo(r,e);if(Wt)return k.toString("utf-8",r,r+e);return Gt.decode(k.subarray(r,r+e))}function jo(e,r){let n=r;for(let c=0;c<r;++c)n=n*31+k[e+c]|0;let s=n>>>0&Xt-1,o=mn[s];if(o!==void 0&&o.length===r){let c=!0;for(let a=0;a<r;++a)if(o.charCodeAt(a)!==k[e+a]){c=!1;break}if(c)return Mt[s]=Ce,o}let i=Wt?k.toString("utf-8",e,e+r):Gt.decode(k.subarray(e,e+r));if(Mt[s]!==Ce)mn[s]=i,Mt[s]=Ce;return i}function Oo(){let e=S,r=k[e]&31;switch(r){case 21:return S=e+1,!0;case 20:return S=e+1,!1;case 22:return S=e+1,null;case 23:return S=e+1,null;case 25:{if(R-e<3)W(2);return S=e+3,Lo(k[e+1],k[e+2])}case 26:{if(R-e<5)W(4);return S=e+5,J.getFloat32(e+1)}case 27:{if(R-e<9)W(8);return S=e+9,J.getFloat64(e+1)}default:throw Error(`unexpected minor value ${r} for major 7.`)}}function Lo(e,r){let n=e>>7,s=(e&124)>>2,o=(e&3)<<8|r,i=n===0?1:-1;if(s===0){if(o===0)return 0;return i*(Math.pow(2,-14)*(o/1024))}else if(s===31){if(o===0)return i*(1/0);return NaN}return i*(Math.pow(2,s-15)*(1+o/1024))}function In(e){if(typeof e==="number")return e;let r=Number(e);if(Number.MIN_SAFE_INTEGER<=r&&r<=Number.MAX_SAFE_INTEGER)return r;return e}function W(e){throw Error(`CBOR: length ${e} greater than remaining buffer length.`)}function qe(e,r){if(e.isTimestampSchema()){if(typeof r==="number")return Ae(r);if(typeof r==="object"&&r!==null){if(r.tag===1&&"value"in r)return Ae(r.value)}}if(e.isBlobSchema())return r;if(typeof r>"u"||typeof r==="boolean"||typeof r==="number"||typeof r==="string"||typeof r==="bigint"||typeof r==="symbol")return r;if(typeof r!=="object"||r===null)return r;if("byteLength"in r)return r;if(r instanceof Date)return r;if(r instanceof Ie)return r;if(e.isDocumentSchema())return r;if(e.isListSchema()){let s=e.getValueSchema(),o=[];for(let i of r)o.push(qe(s,i));return o}let n={};if(e.isMapSchema()){let s=e.getValueSchema();for(let o in r){if(!D(r,o))continue;n[o]=qe(s,r[o])}}else if(e.isStructSchema()){let s=e.isUnionSchema(),o;if(s){o=new Set;for(let i in r){if(!D(r,i))continue;if(i!=="__type")o.add(i)}}for(let[i,c]of e.structIterator()){if(s)o.delete(i);if(r[i]!=null)n[i]=qe(c,r[i])}if(s&&o?.size===1){let i=!0;for(let c in n){if(!D(n,c))continue;i=!1;break}if(i){let c=o.values().next().value;n.$unknown=[c,r[c]]}}else if(typeof r.__type==="string")for(let i in r){if(!D(r,i))continue;if(!(i in n))n[i]=r[i]}}return n}class Jt extends ke{createSerializer(){let e=new Ht;return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Qt;return e.setSerdeContext(this.serdeContext),e}}class kn extends Wi{codec=new Jt;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:e,errorTypeRegistries:r}){super({defaultNamespace:e,errorTypeRegistries:r})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n);if(Object.assign(s.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),Xi(e.input)==="unit")delete s.body,delete s.headers["content-type"];else{if(!s.body)this.serializer.write(15,{}),s.body=this.serializer.flush();if(s.body instanceof Uint8Array)s.headers["content-length"]=String(s.body.byteLength)}let{service:o,operation:i}=qi(n),c=`/service/${o}/operation/${i}`;if(s.path.endsWith("/"))s.path+=c.slice(1);else s.path+=c;return s}async deserializeResponse(e,r,n){return super.deserializeResponse(e,r,n)}async handleError(e,r,n,s,o){let i=xn(n,s)??"Unknown",c=["*"],{defaultNamespace:a}=this.options;c.unshift(a);let[f,u]=(()=>{if(i.includes("#"))return i.split("#");return[void 0,i]})();if(f)c.unshift(f);let h={$metadata:o,$fault:n.statusCode<500?"client":"server"},l=[this.compositeErrorRegistry];if(f)l.push(on.for(f));l.push(on.for(a));let[d,m,y]=this.resolveError(u,c,l);if(y==="native"||y==="synthetic"){if(s.Message)s.message=s.Message;let z=y==="synthetic"?new m({name:u}):Error(u);throw Object.assign(z,h,s)}let g=F.of(d),N=s.message??s.Message??"Unknown",I=new m({}),j={};for(let[z,ee]of g.structIterator())j[z]=this.deserializer.readValue(ee,s[z]);throw Object.assign(I,h,{$fault:g.getMergedTraits().error,message:N},j)}getDefaultContentType(){return"application/cbor"}}class Rn extends ke{value;write(e,r){this.value=this.serialize(e,r)}serialize(e,r){let n=F.of(e);if(r==null){if(n.isIdempotencyToken())return yn();return r}if(n.isBlobSchema()){if(typeof r==="string")return(this.serdeContext?.base64Decoder??Ot)(r);return r}if(n.isTimestampSchema()){if(typeof r==="number"||typeof r==="bigint")return He(new Date(Number(r)/1000|0));return He(r)}if(typeof r==="function"||typeof r==="object"){let s=r;if(n.isListSchema()&&Array.isArray(s)){let i=!!n.getMergedTraits().sparse,c=[],a=0;for(let f of s){let u=this.serialize(n.getValueSchema(),f);if(u!=null||i)c[a++]=u}return c}if(s instanceof Date)return He(s);let o={};if(n.isMapSchema()){let i=!!n.getMergedTraits().sparse;for(let c in s){if(!D(s,c))continue;let a=this.serialize(n.getValueSchema(),s[c]);if(a!=null||i)o[c]=a}}else if(n.isStructSchema()){for(let[c,a]of n.structIterator()){let f=this.serialize(a,s[c]);if(f!=null)o[c]=f}if(n.isUnionSchema()&&Array.isArray(s.$unknown)){let[c,a]=s.$unknown;o[c]=a}else if(typeof s.__type==="string")for(let c in s){if(!D(s,c))continue;if(!(c in o))o[c]=this.serialize(15,s[c])}}else if(n.isDocumentSchema()){if(Array.isArray(s)){let i=[],c=0;for(let a of s)i[c++]=this.serialize(n.getValueSchema(),a);return i}for(let i in s){if(!D(s,i))continue;o[i]=this.serialize(n.getValueSchema(),s[i])}}else if(n.isBigDecimalSchema())return s;return o}return r}flush(){let e=Ge.serialize(this.value);return this.value=void 0,e}}class Mn extends ke{read(e,r){let n=Ge.deserialize(r);return this.readValue(e,n)}readValue(e,r){let n=F.of(e);if(n.isTimestampSchema()){if(typeof r==="number")return Ae(r);if(typeof r==="object"){if(r.tag===1&&"value"in r)return Ae(r.value)}}if(n.isBlobSchema()){if(typeof r==="string")return(this.serdeContext?.base64Decoder??Ot)(r);return r}if(typeof r>"u"||typeof r==="boolean"||typeof r==="number"||typeof r==="string"||typeof r==="bigint"||typeof r==="symbol")return r;else if(typeof r==="object"){if(r===null)return null;if("byteLength"in r)return r;if(r instanceof Date)return r;if(n.isDocumentSchema())return r;if(n.isListSchema()){let o=[],i=n.getValueSchema();for(let c of r){let a=this.readValue(i,c);o.push(a)}return o}let s={};if(n.isMapSchema()){let o=n.getValueSchema();for(let i in r){if(!D(r,i))continue;let c=this.readValue(o,r[i]);s[i]=c}}else if(n.isStructSchema()){let o=n.isUnionSchema(),i;if(o){i=new Set;for(let c in r){if(!D(r,c))continue;if(c!=="__type")i.add(c)}}for(let[c,a]of n.structIterator()){if(o)i.delete(c);if(r[c]!=null)s[c]=this.readValue(a,r[c])}if(o&&i?.size===1){let c=!0;for(let a in s){if(!D(s,a))continue;c=!1;break}if(c){let a=i.values().next().value;s.$unknown=[a,r[a]]}}else if(typeof r.__type==="string")for(let c in r){if(!D(r,c))continue;if(!(c in s))s[c]=r[c]}}else if(r instanceof Ie)return r;return s}else return r}}$o.CborCodec=Jt;$o.CborShapeDeserializer=Mn;$o.CborShapeDeserializer2=Qt;$o.CborShapeSerializer=Rn;$o.CborShapeSerializer2=Ht;$o.SmithyRpcV2CborProtocol=kn;$o.buildHttpRpcRequest=bo;$o.cbor=Ge;$o.checkCborResponse=wo;$o.dateToTag=He;$o.loadSmithyRpcV2CborErrorCode=xn;$o.parseCborBody=bn;$o.parseCborErrorBody=So;$o.tag=Lt;$o.tagSymbol=Re});var Un=t(function(ac){var tc=/[&<>"]/g,rc={"&":"&","<":"<",">":">",'"':"""};function nc(e){return e.replace(tc,(r)=>rc[r])}var sc=/[&"'<>\r\n\u0085\u2028]/g,ic={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function oc(e){return e.replace(sc,(r)=>ic[r])}class Yt{value;constructor(e){this.value=e}toString(){return oc(""+this.value)}}class Be{name;children;attributes={};static of(e,r,n){let s=new Be(e);if(r!==void 0)s.addChildNode(new Yt(r));if(n!==void 0)s.withName(n);return s}constructor(e,r=[]){this.name=e,this.children=r}withName(e){return this.name=e,this}addAttribute(e,r){return this.attributes[e]=r,this}addChildNode(e){return this.children.push(e),this}removeAttribute(e){return delete this.attributes[e],this}n(e){return this.name=e,this}c(e){return this.children.push(e),this}a(e,r){if(r!=null)this.attributes[e]=r;return this}cc(e,r,n=r){if(e[r]!=null){let s=Be.of(r,e[r]).withName(n);this.c(s)}}l(e,r,n,s){if(e[r]!=null)s().map((i)=>{i.withName(n),this.c(i)})}lc(e,r,n,s){if(e[r]!=null){let o=s(),i=new Be(n);o.map((c)=>{i.c(c)}),this.c(i)}}toString(){let e=Boolean(this.children.length),r=`<${this.name}`,n=this.attributes;for(let s of Object.keys(n)){let o=n[s];if(o!=null)r+=` ${s}="${nc(""+o)}"`}return r+=!e?"/>":`>${this.children.map((s)=>s.toString()).join("")}</${this.name}>`}}function Zt(e){Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function cc(e){return new vt(e).parse()}class vt{x;i=0;z;constructor(e){this.x=e,this.x=e.replace(/\r\n?/g,`
|
|
14
|
+
`),this.z=this.x.length}parse(){let e=this,{z:r}=e;while(e.i<r){if(e.trim(),e.i>=r)break;if(e.isNext("<?"))e.readTo("?>"),e.trim();else if(e.isNext("<!--"))e.readTo("-->"),e.trim();else if(e.isNext("<!DOCTYPE",!1))e.skipDoctype(),e.trim();else if(e.x[e.i]==="<"){let n=e.parseTag();return{[n.tag]:n.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(e,r=!0){let n=this;if(r)return n.x.startsWith(e,n.i);return n.x.toLowerCase().startsWith(e.toLowerCase(),n.i)}readTo(e){let r=this,n=r.x.indexOf(e,r.i);if(n===-1)throw Error(`@aws-sdk XML parse error: expected "${e}" not found.`);let s=r.x.slice(r.i,n);return r.i=n+e.length,s}trim(){let e=this;while(e.i<e.z&&` \r
|
|
15
|
+
`.includes(e.x[e.i]))++e.i}readAttrValue(){let e=this,r=e.x[e.i];++e.i;let n="";while(e.i<e.z&&e.x[e.i]!==r)n+=e.x[e.i++];return++e.i,e.decodeEntities(n)}parseTag(){let e=this;++e.i;let r="";while(e.i<e.z&&!` \r
|
|
16
|
+
>/`.includes(e.x[e.i]))r+=e.x[e.i++];let n=!1,s={};while(e.i<e.z){if(e.trim(),">/".includes(e.x[e.i]))break;let u="";while(e.i<e.z&&!`= \r
|
|
17
|
+
>/?`.includes(e.x[e.i]))u+=e.x[e.i++];if(e.trim(),e.x[e.i]!=="=")break;if(++e.i,e.trim(),u==="__proto__")Zt(s);s[u]=e.readAttrValue(),n=!0}if(e.i>=e.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(e.x[e.i]==="/"){if(++e.i,e.i>=e.z||e.x[e.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++e.i,{tag:r,value:n?s:""}}if(e.x[e.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++e.i;let o=[],i=[],c=!1;while(e.i<e.z){if(e.isNext("</"))break;if(e.x[e.i]==="<")if(e.isNext("<!--"))e.readTo("-->");else if(e.isNext("<![CDATA["))e.i+=9,o.push(e.readTo("]]>"));else if(e.isNext("<?"))e.readTo("?>");else c=!0,i.push(e.parseTag());else{let u="";while(e.i<e.z&&e.x[e.i]!=="<")u+=e.x[e.i++];o.push(e.decodeEntities(u))}}if(!e.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${r}>.`);e.i+=2;let a=e.readTo(">").trim();if(a!==r)throw Error(`@aws-sdk XML parse error: mismatched tags <${r}> and </${a}>.`);if(!n&&o.length===0&&!c)return{tag:r,value:""};if(!n&&!c){let u=o.length===1?o[0]:o.join("");if(u.trim()===""&&u.includes(`
|
|
18
|
+
`))return{tag:r,value:""};return{tag:r,value:u}}let f={};for(let u of o){if(u.trim()===""&&u.includes(`
|
|
19
|
+
`))continue;f["#text"]="#text"in f?f["#text"]+u:u}for(let u of i){if(u.tag==="__proto__")Zt(f);if(u.tag in f)if(Array.isArray(f[u.tag]))f[u.tag].push(u.value);else f[u.tag]=[f[u.tag],u.value];else f[u.tag]=u.value}for(let[u,h]of Object.entries(s)){if(u==="__proto__")Zt(f);f[u]=h}return{tag:r,value:f}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let e=this;e.i+=9;let r=0;while(e.i<e.z){let n=e.x[e.i];if(n==="[")++r;else if(n==="]")--r;else if(n===">"&&r===0){++e.i;return}++e.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(e){return e.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(r,n,s,o)=>{if(n)return String.fromCharCode(parseInt(n,16));if(s)return String.fromCharCode(parseInt(s,10));return vt.ENTITIES[o]??""})}}ac.XmlNode=Be;ac.XmlText=Yt;ac.parseXML=cc});var ot=t(function(Rc){var{SmithyRpcV2CborProtocol:lc,loadSmithyRpcV2CborErrorCode:dc}=Bn(),{TypeRegistry:Dn,NormalizedSchema:T,deref:qn}=be(),{decorateServiceException:jn,getValueFromTextNode:Qn}=Y(),{collectBody:nt,determineTimestampFormat:pe,RpcProtocol:Gn,HttpBindingProtocol:Wn,HttpInterceptingShapeSerializer:Xn,HttpInterceptingShapeDeserializer:Jn,FromStringShapeDeserializer:mc,extendedEncodeURIComponent:zn}=B(),{NumericValue:U,toUtf8:sr,fromBase64:ir,LazyJsonString:ct,parseEpochTimestamp:Zn,parseRfc7231DateTime:Yn,parseRfc3339DateTimeWithOffset:vn,generateIdempotencyToken:at,toBase64:ge,dateToUtcString:je,expectUnion:gc}=X(),{parseXML:es,XmlNode:H,XmlText:On}=Un();class ye{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,r){let n=r.getMemberSchemas(),s=Object.values(n).find((o)=>!!o.getMergedTraits().httpPayload);if(s){let o=s.getMergedTraits().mediaType;if(o)return o;else if(s.isStringSchema())return"text/plain";else if(s.isBlobSchema())return"application/octet-stream";else return e}else if(!r.isUnitSchema()){if(Object.values(n).find((i)=>{let{httpQuery:c,httpQueryParams:a,httpHeader:f,httpLabel:u,httpPrefixHeaders:h}=i.getMergedTraits();return!c&&!a&&!f&&!u&&h===void 0}))return e}}async getErrorSchemaOrThrowBaseException(e,r,n,s,o,i){let c=e;if(e.includes("#"))[,c]=e.split("#");let a={$metadata:o,$fault:n.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:i?.(this.errorRegistry,c)??this.errorRegistry.getSchema(e),errorMetadata:a}}catch(f){s.message=s.message??s.Message??"UnknownError";let u=this.errorRegistry,h=u.getBaseException();if(h){let m=u.getErrorCtor(h)??Error;throw this.decorateServiceException(Object.assign(new m({name:c}),a),s)}let l=s,d=l?.message??l?.Message??l?.Error?.Message??l?.Error?.message;throw this.decorateServiceException(Object.assign(Error(d),{name:c},a),s)}}compose(e,r,n){let s=n;if(r.includes("#"))[s]=r.split("#");let o=Dn.for(s),i=Dn.for("smithy.ts.sdk.synthetic."+n);e.copyFrom(o),e.copyFrom(i),this.errorRegistry=e}decorateServiceException(e,r={}){if(this.queryCompat){let n=e.Message??r.Message,s=jn(e,r);if(n)s.message=n;let o=s.Error??{};o.Type=s.Error?.Type,o.Code=s.Error?.Code,o.Message=s.Error?.message??s.Error?.Message??n,s.Error=o;let i=s.$metadata.requestId;if(i)s.RequestId=i;return s}return jn(e,r)}setQueryCompatError(e,r){let n=r.headers?.["x-amzn-query-error"];if(e!==void 0&&n!=null){let[s,o]=n.split(";"),i=Object.keys(e),c={Code:s,Type:o};e.Code=s,e.Type=o;for(let a=0;a<i.length;a++){let f=i[a];c[f==="message"?"Message":f]=e[f]}delete c.__type,e.Error=c}}queryCompatOutput(e,r){if(e.Error)r.Error=e.Error;if(e.Type)r.Type=e.Type;if(e.Code)r.Code=e.Code}findQueryCompatibleError(e,r){try{return e.getSchema(r)}catch(n){return e.find((s)=>T.of(s).getMergedTraits().awsQueryError?.[0]===r)}}}class ts extends lc{awsQueryCompatible;mixin;constructor({defaultNamespace:e,errorTypeRegistries:r,awsQueryCompatible:n}){super({defaultNamespace:e,errorTypeRegistries:r});this.awsQueryCompatible=!!n,this.mixin=new ye(this.awsQueryCompatible)}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n);if(this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";return s}async handleError(e,r,n,s,o){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(s,n);let i=(()=>{let m=n.headers["x-amzn-query-error"];if(m&&this.awsQueryCompatible)return m.split(";")[0];return dc(n,s)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:c,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,n,s,o,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),f=T.of(c),u=s.message??s.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),d={};for(let[m,y]of f.structIterator())if(s[m]!=null)d[m]=this.deserializer.readValue(y,s[m]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(s,d);throw this.mixin.decorateServiceException(Object.assign(l,a,{$fault:f.getMergedTraits().error,message:u},d),s)}}class K{serdeContext;setSerdeContext(e){this.serdeContext=e}}class ft{from;to;keys;constructor(e,r){this.from=e,this.to=r;let n=Object.keys(this.from),s=new Set(n);s.delete("__type"),this.keys=s}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let e=this.keys.values().next().value,r=this.from[e];this.to.$unknown=[e,r]}}}var De;function rs(){if(De===void 0)try{if(typeof Buffer!=="function")De=!1;else{let e=JSON.parse(Buffer.from([123,125]));De=e!==null&&typeof e==="object"}}catch{De=!1}return De}function or(e,r,n){if(n?.source){let s=n.source;if(typeof r==="number")if(r<=Number.MAX_SAFE_INTEGER&&r>=Number.MIN_SAFE_INTEGER){if(yc(s,r))return r;return new U(s,"bigDecimal")}else{if(pc(s))return new U(s,"bigDecimal");if(/[eE]/.test(s))return Sc(s);return BigInt(s)}}return r}function pc(e){let r=e.indexOf(".");if(r===-1)return!1;let n=e.search(/[eE]/);if(n===-1)return!0;let s=n-r-1;return parseInt(e.slice(n+1),10)<s}function yc(e,r){if(e===String(r))return!0;if(Object.is(r,-0))return!0;if(/[eE]/.test(e))return er(e)===er(String(r));let n=e.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),s=String(r);if(n===s)return!0;if(/[eE]/.test(s))return n===er(s);return!1}function er(e){let r=e.startsWith("-"),n=r?e.slice(1):e,s=n.search(/[eE]/),o;if(s===-1)o=n;else{let i=parseInt(n.slice(s+1),10),c=n.slice(0,s),a=c.indexOf("."),f,u;if(a===-1)f=c,u=c.length;else f=c.slice(0,a)+c.slice(a+1),u=a;f=f.replace(/0+$/,"")||"0";let h=u+i;if(f==="0")o="0";else if(h<=0)o="0."+"0".repeat(-h)+f;else if(h>=f.length)o=f+"0".repeat(h-f.length);else o=f.slice(0,h)+"."+f.slice(h)}if(o.includes("."))o=o.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return(r?"-":"")+o}function Sc(e){let r=e.search(/[eE]/),n=parseInt(e.slice(r+1),10),s=e.startsWith("-"),o=e.slice(s?1:0,r),i=o.indexOf("."),c,a;if(i===-1)c=o,a=n;else{c=o.slice(0,i)+o.slice(i+1);let u=o.length-i-1;a=n-u}c=c.replace(/0+$/,"")||"0";let f=BigInt(c)*10n**BigInt(a+(o.replace(".","").length-c.length));return s?-f:f}var tr=Symbol.for("@aws-sdk/reviver");function cr(e){let r=T.of(e),n=r.getSchema();if(Array.isArray(n)&&r.isStructSchema()){if(tr in n)return n[tr];let s=st(r,new Set);return n[tr]=s,s}return st(r,new Set)}function st(e,r){let n=e.getSchema();if(r.has(n))return!1;if(r.add(n),e.isBigIntegerSchema()||e.isBigDecimalSchema())return!0;if(e.isStructSchema()){for(let[,s]of e.structIterator())if(st(s,r))return!0}else if(e.isListSchema()||e.isMapSchema()){if(st(e.getValueSchema(),r))return!0}else if(e.isDocumentSchema())return!0;return!1}var ns=(e,r)=>nt(e,r).then((n)=>(r?.utf8Encoder??sr)(n));async function ut(e,r,n){let s;if(rs()&&typeof e?.[Symbol.asyncIterator]==="function"){let i=await nt(e,r);if(typeof Buffer==="function")if(Buffer.isBuffer(i))s=i;else s=Buffer.from(i.buffer,i.byteOffset,i.byteLength)}if(!s)s=await ns(e,r);if(s.length===0)return{};let o=n&&cr(n)?or:void 0;try{return JSON.parse(s,o)}catch(i){if(i?.name==="SyntaxError")Object.defineProperty(i,"$responseBodyText",{value:typeof s==="string"?s:s.toString("utf8")});throw i}}var wc=async(e,r)=>{let n=await ut(e,r);return n.message=n.message??n.Message,n},Ln=(e,r)=>Object.keys(e).find((n)=>n.toLowerCase()===r.toLowerCase()),rr=(e)=>{let r=e;if(typeof r==="number")r=r.toString();if(r.indexOf(",")>=0)r=r.split(",")[0];if(r.indexOf(":")>=0)r=r.split(":")[0];if(r.indexOf("#")>=0)r=r.split("#")[1];return r},ss=(e,r)=>os(e,r,["header","code","type"]),is=(e,r,n=!1)=>os(e,r,n?["code","header","type"]:["type","code","header"]),os=({headers:e},r,n)=>{while(n.length>0)switch(n.shift()){case"header":let o=Ln(e??{},"x-amzn-errortype");if(o!==void 0)return rr(e[o]);break;case"code":let i=Ln(r??{},"code");if(i&&r[i]!==void 0)return rr(r[i]);break;case"type":if(r?.__type!==void 0)return rr(r.__type);break}};function v(e){Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}class ar extends K{settings;constructor(e){super();this.settings=e}async read(e,r){let n=cr(e)?or:void 0,s;if(typeof r==="string"){if(r.length===0)return{};s=JSON.parse(r,n)}else if(r instanceof Uint8Array&&rs()){if(r.byteLength===0)return{};let o=Buffer.isBuffer(r)?r:Buffer.from(r.buffer,r.byteOffset,r.byteLength);s=JSON.parse(o,n)}else s=await ut(r,this.serdeContext,e);return this._read(e,s)}readObject(e,r){return this._read(e,r)}_read(e,r){let n=r!==null&&typeof r==="object",s=T.of(e);if(n){if(s.isStructSchema())return this._readStruct(s,r);if(Array.isArray(r)&&s.isListSchema()){let i=s.getValueSchema();if(this.needsTransform(i))for(let c=0;c<r.length;++c)r[c]=this._read(i,r[c]);return r}if(s.isMapSchema()){let i=s.getValueSchema(),c=r;if(this.needsTransform(i))for(let a in c){if(a==="__proto__")v(c);c[a]=this._read(i,c[a])}return c}}if(s.isBlobSchema()&&typeof r==="string")return ir(r);let o=s.getMergedTraits().mediaType;if(s.isStringSchema()&&typeof r==="string"&&o){if(o==="application/json"||o.endsWith("+json"))return ct.from(r);return r}if(s.isTimestampSchema()&&r!=null)switch(pe(s,this.settings)){case 5:return vn(r);case 6:return Yn(r);case 7:return Zn(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(s.isBigIntegerSchema()&&(typeof r==="number"||typeof r==="string"))return BigInt(r);if(s.isBigDecimalSchema()&&r!=null){if(r instanceof U)return r;let i=r;if(i.type==="bigDecimal"&&"string"in i)return new U(i.string,i.type);return new U(String(r),"bigDecimal")}if(s.isNumericSchema()&&typeof r==="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(s.isDocumentSchema()){if(n)if(Array.isArray(r))for(let i=0;i<r.length;++i){let c=r[i];if(!(c instanceof U))r[i]=this._read(s,c)}else{let i=r;for(let c in i){if(c==="__proto__")v(i);let a=i[c];if(!(a instanceof U))i[c]=this._read(s,a)}}}return r}_readStruct(e,r){let n=e.isUnionSchema(),s={},o,i=typeof r.__type==="string",{jsonName:c}=this.settings;if(c&&i)o={};let a;if(n)a=new ft(r,s);for(let[f,u]of e.structIterator()){let h=f;if(c){if(h=u.getMergedTraits().jsonName??h,i)o[h]=f}if(n)a.mark(h);if(r[h]!=null)s[f]=this._read(u,r[h])}if(n)a.writeUnknown();else if(i)for(let f in r){let u=r[f],h=c?o[f]??f:f;if(!(h in s))s[h]=u}return s}needsTransform(e){if(e.isBlobSchema()||e.isTimestampSchema()||e.isBigIntegerSchema()||e.isBigDecimalSchema())return!0;if(e.isDocumentSchema()||e.isStructSchema()||e.isListSchema()||e.isMapSchema())return!0;if(e.isStringSchema()&&e.getMergedTraits().mediaType)return!0;return!1}}class it extends Uint8Array{string=null;static allocUnsafe(e){if(typeof Buffer==="function"){let r=Buffer.allocUnsafe(e);return new it(r.buffer,r.byteOffset,r.byteLength)}return new it(e)}toString(){return this.s()}valueOf(){return this.s()}includes(e,r){if(typeof e==="string")return this.s().includes(e,r);return Uint8Array.prototype.includes.call(this,e,r)}indexOf(e,r){if(typeof e==="string")return this.s().indexOf(e,r);return Uint8Array.prototype.indexOf.call(this,e,r)}lastIndexOf(e,r){if(typeof e==="string")return this.s().lastIndexOf(e,r);let n=Uint8Array.prototype.lastIndexOf;if(r!==void 0)return n.call(this,e,r);return n.call(this,e)}startsWith(e,r){return this.s().startsWith(e,r)}endsWith(e,r){return this.s().endsWith(e,r)}match(e){return this.s().match(e)}replace(e,r){return this.s().replace(e,r)}search(e){return this.s().search(e)}split(e,r){return this.s().split(e,r)}substring(e,r){return this.s().substring(e,r)}trim(){return this.s().trim()}trimStart(){return this.s().trimStart()}trimEnd(){return this.s().trimEnd()}charAt(e){return this.s().charAt(e)}charCodeAt(e){return this.s().charCodeAt(e)}padStart(e,r){return this.s().padStart(e,r)}padEnd(e,r){return this.s().padEnd(e,r)}repeat(e){return this.s().repeat(e)}toUpperCase(){return this.s().toUpperCase()}toLowerCase(){return this.s().toLowerCase()}s(){if(this.string==null){let e=Date.now();if(e>$n+60000)console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. It has been automatically converted to string. In a future version this will throw an error."),$n=e;this.string=sr(this)}return this.string}}var $n=0,et=new TextEncoder,Vn=123,Fn=125,bc=91,xc=93,me=34,tt=58,rt=44,Pn=92,Ec=new Uint8Array([116,114,117,101]),Nc=new Uint8Array([102,97,108,115,101]),_c=new Uint8Array([110,117,108,108]),G=Array(128).fill(null);G[8]="b";G[9]="t";G[10]="n";G[12]="f";G[13]="r";G[34]='"';G[92]="\\";for(let e=0;e<32;e++)if(G[e]===null)G[e]="u00"+e.toString(16).padStart(2,"0");var Hn=2048;function nr(e){return it.allocUnsafe(e)}class ht extends K{settings;json;i=0;rootSchema;rawValue;passthrough=!1;constructor(e){super();this.settings=e,this.json=nr(Hn)}write(e,r){if(this.i=0,this.rawValue=r,this.rootSchema=T.of(e),this.passthrough=this.rootSchema.isBlobSchema()||this.rootSchema.isStringSchema(),!this.passthrough)this.writeValue(this.rootSchema,r,void 0)}writeDiscriminatedDocument(e,r){this.i=0,this.rootSchema=T.of(e);let n=this.rootSchema;if(n.isStructSchema()&&r!=null&&typeof r==="object"){this.writeValue(n,r,void 0);let s=`"__type":"${n.getName(!0)??"Unknown"}",`,o=s.length;this.ensure(o),this.json.copyWithin(1+o,1,this.i),et.encodeInto(s,this.json.subarray(1)),this.i+=o}else this.writeValue(n,r,void 0)}flush(){this.rootSchema=void 0;let e=this.i;this.i=0;let r=this.rawValue;if(this.rawValue=void 0,e===0)return r;let n=this.json.subarray(0,e);return this.json=nr(Hn),n}ensure(e){let{i:r,json:n}=this;if(r+e>n.length){let s=n.length*2;while(s<r+e)s*=2;let o=nr(s);o.set(this.json),this.json=o}}writeAscii(e){let r=e.length;this.ensure(r);let{i:n,json:s}=this;for(let o=0;o<r;++o)s[n]=e.charCodeAt(o),n+=1;this.i=n}writeAsciiQuoted(e){let r=e.length;this.ensure(r+4);let{json:n,i:s}=this;n[s++]=me;for(let o=0;o<r;++o)n[s++]=e.charCodeAt(o);n[s++]=me,this.i=s}writeJsonString(e){this.ensure(e.length*3+2),this.json[this.i++]=me;let r=e.length;for(let n=0;n<r;++n){let s=e.charCodeAt(n);if(s>34&&s<92)this.json[this.i++]=s;else if(s<128){let o=G[s];if(o!==null){this.ensure(o.length+1),this.json[this.i++]=Pn;for(let i=0;i<o.length;i++)this.json[this.i++]=o.charCodeAt(i)}else this.json[this.i++]=s}else if(s>=55296&&s<=56319){let o=n+1<r?e.charCodeAt(n+1):0;if(o>=56320&&o<=57343){this.ensure(4);let{written:i}=et.encodeInto(e.substring(n,n+2),this.json.subarray(this.i));this.i+=i,++n}else this.ensure(6),this.writeUnicodeEscape(s)}else if(s>=56320&&s<=57343)this.ensure(6),this.writeUnicodeEscape(s);else{let{i:o,json:i}=this;if(s<2048)i[o++]=192|s>>6,i[o++]=128|s&63;else i[o++]=224|s>>12,i[o++]=128|s>>6&63,i[o++]=128|s&63;this.i=o}}this.json[this.i++]=me}writeUnicodeEscape(e){let{json:r,i:n}=this;r[n++]=Pn,r[n++]=117;let s=e.toString(16).padStart(4,"0");for(let o=0;o<4;++o)r[n++]=s.charCodeAt(o);this.i=n}static B64=(()=>{let r=new Uint8Array(64);for(let n=0;n<64;++n)r[n]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(n);return r})();writeBase64(e){let r=Math.ceil(e.length/3)*4;this.ensure(r+2);let n=this.json,s=ht.B64,o=this.i;n[o++]=me;let i=e.length,c=i%3,a=i-c;for(let f=0;f<a;f+=3){let u=e[f],h=e[f+1],l=e[f+2];n[o++]=s[u>>2],n[o++]=s[(u&3)<<4|h>>4],n[o++]=s[(h&15)<<2|l>>6],n[o++]=s[l&63]}if(c===2){let f=e[a],u=e[a+1];n[o++]=s[f>>2],n[o++]=s[(f&3)<<4|u>>4],n[o++]=s[(u&15)<<2],n[o++]=61}else if(c===1){let f=e[a];n[o++]=s[f>>2],n[o++]=s[(f&3)<<4],n[o++]=61,n[o++]=61}n[o++]=me,this.i=o}writeValue(e,r,n){if(r==null){if(n?.isStructSchema()){if(r===void 0){if(T.of(e).isIdempotencyToken()){this.writeAsciiQuoted(at());return}}return}this.ensure(4),this.json.set(_c,this.i),this.i+=4;return}let s=T.of(e),o=typeof r==="object";if(s.isStringSchema()){let i=s.getMergedTraits().mediaType;if(i){if(i==="application/json"||i.endsWith("+json")){this.writeJsonString(ct.from(r).toString());return}}}if(o){if(s.isStructSchema()){this.writeStruct(s,r);return}if(Array.isArray(r)&&(s.isListSchema()||s.isDocumentSchema())){this.writeList(s,r,s.isDocumentSchema());return}if(s.isMapSchema()){this.writeMap(s,r,!1);return}if(r instanceof Uint8Array&&(s.isBlobSchema()||s.isDocumentSchema())){this.writeBase64(r);return}if(r instanceof Date&&(s.isTimestampSchema()||s.isDocumentSchema())){this.writeTimestamp(s,r);return}if(r instanceof U){this.writeAscii(r.string);return}if(s.isDocumentSchema()){if(Array.isArray(r))this.writeList(s,r,!0);else this.writeMap(s,r,!0);return}let i=JSON.stringify(r);this.writeAscii(i);return}if(typeof r==="string"){if(s.isBlobSchema()){let i=(this.serdeContext?.base64Encoder??ge)(r);this.writeAsciiQuoted(i);return}this.writeJsonString(r);return}if(typeof r==="number"){if(Math.abs(r)===1/0||Number.isNaN(r)){this.writeAsciiQuoted(String(r));return}let i=String(r);this.writeAscii(i);return}if(typeof r==="boolean"){this.ensure(5);let{i,json:c}=this;if(r)c.set(Ec,i),i+=4;else c.set(Nc,i),i+=5;this.i=i;return}if(typeof r==="bigint"){this.writeAscii(r.toString());return}this.writeAscii(String(r))}writeStruct(e,r){this.ensure(2),this.json[this.i++]=Vn;let n=!1,s=typeof r.__type==="string",o;if(s)o=new Set;for(let[i,c]of e.structIterator()){let a=r[i];if(a==null&&!c.isIdempotencyToken())continue;if(n)this.ensure(1),this.json[this.i++]=rt;n=!0;let f=this.settings.jsonName?c.getMergedTraits().jsonName??i:i;if(o)o.add(i),o.add(f);this.writeAsciiQuoted(f),this.json[this.i++]=tt,this.writeValue(c,a,e)}if(!n&&e.isUnionSchema()){let{$unknown:i}=r;if(Array.isArray(i)){let[c,a]=i;this.writeAsciiQuoted(c),this.ensure(1),this.json[this.i++]=tt,this.writeValue(15,a,e)}}else if(s)for(let i in r){if(o.has(i))continue;o.add(i);let c=r[i];if(n)this.ensure(1),this.json[this.i++]=rt;n=!0,this.writeAsciiQuoted(i),this.ensure(1),this.json[this.i++]=tt,this.writeValue(15,c,void 0)}this.ensure(1),this.json[this.i++]=Fn}writeList(e,r,n){let s=!!e.getMergedTraits().sparse,o=e.getValueSchema();if(!n){if(o.isStringSchema()||o.isNumericSchema()||o.isBooleanSchema()){let c=!1;for(let f=0;f<r.length;++f){let u=r[f];if(Number.isNaN(u)||u===1/0||u===-1/0||u==null&&!s){c=!0;break}}let a;if(!c)a=JSON.stringify(r);else{let f=[];for(let u=0;u<r.length;++u){let h=r[u];if(h==null&&!s)continue;if(Number.isNaN(h)||h===1/0||h===-1/0)f.push(String(h));else f.push(h)}a=JSON.stringify(f)}this.ensure(a.length*3),this.i+=et.encodeInto(a,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=bc;let i=!1;for(let c=0;c<r.length;++c){let a=r[c];if(n?a===void 0:a==null&&!s)continue;if(i)this.ensure(1),this.json[this.i++]=rt;this.writeValue(o,a,void 0),i=!0}this.ensure(1),this.json[this.i++]=xc}writeMap(e,r,n){let s=!!e.getMergedTraits().sparse,o=e.getValueSchema();if(!n){if(o.isStringSchema()||o.isNumericSchema()||o.isBooleanSchema()){let c;for(let f in r){let u=r[f];if(Number.isNaN(u)||u===1/0||u===-1/0)(c??={})[f]=u,r[f]=String(u);else if(u===null&&!s)(c??={})[f]=null,r[f]=void 0}let a=JSON.stringify(r);if(c)Object.assign(r,c);this.ensure(a.length*3),this.i+=et.encodeInto(a,this.json.subarray(this.i)).written;return}}this.ensure(2),this.json[this.i++]=Vn;let i=!0;for(let c in r){let a=r[c];if(n?a===void 0:a==null&&!s)continue;if(!i)this.ensure(1),this.json[this.i++]=rt;i=!1,this.writeJsonString(c),this.ensure(1),this.json[this.i++]=tt,this.writeValue(o,a,void 0)}this.ensure(1),this.json[this.i++]=Fn}writeTimestamp(e,r){switch(pe(e,this.settings)){case 5:{let s=r.toISOString().replace(".000Z","Z");this.writeAsciiQuoted(s);return}case 6:{this.writeAsciiQuoted(je(r));return}case 7:{let s=String(r.getTime()/1000);this.writeAscii(s);return}default:{let s=String(r.getTime()/1000);this.writeAscii(s);return}}}}class lt extends K{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new ht(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new ar(this.settings);return e.setSerdeContext(this.serdeContext),e}}class dt extends Gn{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:n,awsQueryCompatible:s,jsonCodec:o}){super({defaultNamespace:e,errorTypeRegistries:r});this.serviceTarget=n,this.codec=o??new lt({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!s,this.mixin=new ye(this.awsQueryCompatible)}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,s.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";if(qn(e.input)==="unit"||!s.body)s.body="{}";return s}getPayloadCodec(){return this.codec}async handleError(e,r,n,s,o){let{awsQueryCompatible:i}=this;if(i)this.mixin.setQueryCompatError(s,n);let c=is(n,s,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,c,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:f}=await this.mixin.getErrorSchemaOrThrowBaseException(c,this.options.defaultNamespace,n,s,o,i?this.mixin.findQueryCompatibleError:void 0),u=T.of(a),h=s.message??s.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(a)??Error)({}),m={},y=this.codec.createDeserializer();for(let[g,N]of u.structIterator())if(s[g]!=null)m[g]=y.readObject(N,s[g]);if(i)this.mixin.queryCompatOutput(s,m);throw this.mixin.decorateServiceException(Object.assign(d,f,{$fault:u.getMergedTraits().error,message:h},m),s)}}class cs extends dt{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:n,awsQueryCompatible:s,jsonCodec:o}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:n,awsQueryCompatible:s,jsonCodec:o})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class as extends dt{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:n,awsQueryCompatible:s,jsonCodec:o}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:n,awsQueryCompatible:s,jsonCodec:o})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class fs extends Wn{serializer;deserializer;codec;mixin=new ye;constructor({defaultNamespace:e,errorTypeRegistries:r,jsonCodec:n}){super({defaultNamespace:e,errorTypeRegistries:r});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=n??new lt(s),this.serializer=new Xn(this.codec.createSerializer(),s),this.deserializer=new Jn(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n),o=T.of(e.input);if(!s.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),o);if(i)s.headers["content-type"]=i}if(s.body==null&&s.headers["content-type"]===this.getDefaultContentType())s.body="{}";return s}async deserializeResponse(e,r,n){let s=await super.deserializeResponse(e,r,n),o=T.of(e.output);for(let[i,c]of o.structIterator())if(c.getMemberTraits().httpPayload&&!(i in s))s[i]=null;return s}async handleError(e,r,n,s,o){let i=ss(n,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:c,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,n,s,o),f=T.of(c),u=s.message??s.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({});await this.deserializeHttpMessage(c,r,n,s);let d={},m=this.codec.createDeserializer();for(let[y,g]of f.structIterator()){let N=g.getMergedTraits().jsonName??y;d[y]=m.readObject(g,s[N])}throw this.mixin.decorateServiceException(Object.assign(l,a,{$fault:f.getMergedTraits().error,message:u},d),s)}getDefaultContentType(){return"application/json"}}class fr extends K{settings;constructor(e){super();this.settings=e}async read(e,r){let n=cr(e)?or:void 0;return this._read(e,typeof r==="string"?JSON.parse(r,n):await ut(r,this.serdeContext,e))}readObject(e,r){return this._read(e,r)}_read(e,r){let n=r!==null&&typeof r==="object",s=T.of(e);if(n){if(s.isStructSchema()){let i=r,c=s.isUnionSchema(),a={},f=void 0,{jsonName:u}=this.settings;if(u)f={};let h;if(c)h=new ft(i,a);for(let[l,d]of s.structIterator()){let m=l;if(u)m=d.getMergedTraits().jsonName??m,f[m]=l;if(c)h.mark(m);if(i[m]!=null)a[l]=this._read(d,i[m])}if(c)h.writeUnknown();else if(typeof i.__type==="string")for(let l in i){let d=i[l],m=u?f[l]??l:l;if(!(m in a))a[m]=d}return a}if(Array.isArray(r)&&s.isListSchema()){let i=s.getValueSchema(),c=[];for(let a of r)c.push(this._read(i,a));return c}if(s.isMapSchema()){let i=s.getValueSchema(),c={};for(let a in r){if(a==="__proto__")v(c);c[a]=this._read(i,r[a])}return c}}if(s.isBlobSchema()&&typeof r==="string")return ir(r);let o=s.getMergedTraits().mediaType;if(s.isStringSchema()&&typeof r==="string"&&o){if(o==="application/json"||o.endsWith("+json"))return ct.from(r);return r}if(s.isTimestampSchema()&&r!=null)switch(pe(s,this.settings)){case 5:return vn(r);case 6:return Yn(r);case 7:return Zn(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(s.isBigIntegerSchema()&&(typeof r==="number"||typeof r==="string"))return BigInt(r);if(s.isBigDecimalSchema()&&r!=null){if(r instanceof U)return r;let i=r;if(i.type==="bigDecimal"&&"string"in i)return new U(i.string,i.type);return new U(String(r),"bigDecimal")}if(s.isNumericSchema()&&typeof r==="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(s.isDocumentSchema())if(n){let i=Array.isArray(r)?[]:{};for(let c in r){if(c==="__proto__")v(i);let a=r[c];if(a instanceof U)i[c]=a;else i[c]=this._read(s,a)}return i}else return structuredClone(r);return r}}var Kn=String.fromCharCode(925);class us{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,r)=>{if(r instanceof U){let n=`${Kn+"nv"+this.counter++}_`+r.string;return this.values.set(`"${n}"`,r.string),n}if(typeof r==="bigint"){let n=r.toString(),s=`${Kn+"b"+this.counter++}_`+n;return this.values.set(`"${s}"`,n),s}return r}}replaceInJson(e){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(let[r,n]of this.values)e=e.replace(r,n);return e}}class ur extends K{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super();this.settings=e}write(e,r){this.rootSchema=T.of(e),this.buffer=this._write(this.rootSchema,r)}flush(){let{rootSchema:e,useReplacer:r}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!r)return JSON.stringify(this.buffer);let n=new us;return n.replaceInJson(JSON.stringify(this.buffer,n.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,r){if(this.write(e,r),typeof this.buffer==="object")this.buffer.__type=T.of(e).getName(!0)}_write(e,r,n){let s=r!==null&&typeof r==="object",o=T.of(e);if(s){if(o.isStructSchema()){let i=r,c={},{jsonName:a}=this.settings,f=void 0;if(a)f={};let u=0;for(let[h,l]of o.structIterator()){let d=this._write(l,i[h],o);if(d!==void 0){let m=h;if(a)m=l.getMergedTraits().jsonName??h,f[h]=m;c[m]=d,u++}}if(o.isUnionSchema()&&u===0){let{$unknown:h}=i;if(Array.isArray(h)){let[l,d]=h;if(l==="__proto__")v(c);c[l]=this._write(15,d)}}else if(typeof i.__type==="string")for(let h in i){let l=i[h],d=a?f[h]??h:h;if(!(d in c))c[d]=this._write(15,l)}return c}if(Array.isArray(r)&&o.isListSchema()){let i=o.getValueSchema(),c=[],a=!!o.getMergedTraits().sparse;for(let f of r)if(a||f!=null)c.push(this._write(i,f));return c}if(o.isMapSchema()){let i=o.getValueSchema(),c={},a=!!o.getMergedTraits().sparse;for(let f in r){let u=r[f];if(a||u!=null){if(f==="__proto__")v(c);c[f]=this._write(i,u)}}return c}if(r instanceof Uint8Array&&o.isBlobSchema()){if(o===this.rootSchema)return r;return(this.serdeContext?.base64Encoder??ge)(r)}if(r instanceof Date&&(o.isTimestampSchema()||o.isDocumentSchema()))switch(pe(o,this.settings)){case 5:return r.toISOString().replace(".000Z","Z");case 6:return je(r);case 7:return r.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",r),r.getTime()/1000}if(r instanceof U)this.useReplacer=!0}if(r===null&&n?.isStructSchema())return;if(o.isStringSchema()){if(typeof r>"u"&&o.isIdempotencyToken())return at();let i=o.getMergedTraits().mediaType;if(r!=null&&i){if(i==="application/json"||i.endsWith("+json"))return ct.from(r)}return r}if(typeof r==="number"){if(Math.abs(r)===1/0||isNaN(r))return String(r);return r}if(typeof r==="string"&&o.isBlobSchema()){if(o===this.rootSchema)return r;return(this.serdeContext?.base64Encoder??ge)(r)}if(typeof r==="bigint")this.useReplacer=!0;if(o.isDocumentSchema())if(s){if(r instanceof Uint8Array)return(this.serdeContext?.base64Encoder??ge)(r);let i=Array.isArray(r)?[]:{};for(let c in r){let a=r[c];if(c==="__proto__")v(i);if(a instanceof U)this.useReplacer=!0,i[c]=a;else i[c]=this._write(o,a)}return i}else return structuredClone(r);return r}}class hs extends K{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new ur(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new fr(this.settings);return e.setSerdeContext(this.serdeContext),e}}class mt extends K{settings;stringDeserializer;constructor(e){super();this.settings=e,this.stringDeserializer=new mc(e)}setSerdeContext(e){this.serdeContext=e,this.stringDeserializer.setSerdeContext(e)}read(e,r,n){let s=T.of(e),o=s.getMemberSchemas();if(s.isStructSchema()&&s.isMemberSchema()&&!!Object.values(o).find((f)=>!!f.getMemberTraits().eventPayload)){let f={},u=Object.keys(o)[0];if(o[u].isBlobSchema())f[u]=r;else f[u]=this.read(o[u],r);return f}let c=(this.serdeContext?.utf8Encoder??sr)(r),a=this.parseXml(c);return this.readSchema(e,n?a[n]:a)}readSchema(e,r){let n=T.of(e);if(n.isUnitSchema())return;let s=n.getMergedTraits();if(n.isListSchema()&&!Array.isArray(r))return this.readSchema(n,[r]);if(r==null)return r;if(typeof r==="object"){let o=!!s.xmlFlattened;if(n.isListSchema()){let c=n.getValueSchema(),a=[],f=c.getMergedTraits().xmlName??"member",u=o?r:(r[0]??r)[f];if(u==null)return a;let h=Array.isArray(u)?u:[u];for(let l of h)a.push(this.readSchema(c,l));return a}let i={};if(n.isMapSchema()){let c=n.getKeySchema(),a=n.getValueSchema(),f;if(o)f=Array.isArray(r)?r:[r];else f=Array.isArray(r.entry)?r.entry:[r.entry];let u=c.getMergedTraits().xmlName??"key",h=a.getMergedTraits().xmlName??"value";for(let l of f){let d=l[u],m=l[h];if(d==="__proto__")v(i);i[d]=this.readSchema(a,m)}return i}if(n.isStructSchema()){let c=n.isUnionSchema(),a;if(c)a=new ft(r,i);for(let[f,u]of n.structIterator()){let h=u.getMergedTraits(),l=!h.httpPayload?u.getMemberTraits().xmlName??f:h.xmlName??u.getName();if(c)a.mark(l);if(r[l]!=null)i[f]=this.readSchema(u,r[l])}if(c)a.writeUnknown();return i}if(n.isDocumentSchema())return r;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${n.getName(!0)}`)}if(n.isListSchema())return[];if(n.isMapSchema()||n.isStructSchema())return{};return this.stringDeserializer.read(n,r)}parseXml(e){if(e.length){let r;try{r=es(e)}catch(i){if(i&&typeof i==="object")Object.defineProperty(i,"$responseBodyText",{value:e});throw i}let n="#text",s=Object.keys(r)[0],o=r[s];if(o[n])o[s]=o[n],delete o[n];return Qn(o)}return{}}}class hr extends K{settings;buffer;constructor(e){super();this.settings=e}write(e,r,n=""){if(this.buffer===void 0)this.buffer="";let s=T.of(e);if(n&&!n.endsWith("."))n+=".";if(s.isBlobSchema()){if(typeof r==="string"||r instanceof Uint8Array)this.writeKey(n),this.writeValue((this.serdeContext?.base64Encoder??ge)(r))}else if(s.isBooleanSchema()||s.isNumericSchema()||s.isStringSchema()){if(r!=null)this.writeKey(n),this.writeValue(String(r));else if(s.isIdempotencyToken())this.writeKey(n),this.writeValue(at())}else if(s.isBigIntegerSchema()){if(r!=null)this.writeKey(n),this.writeValue(String(r))}else if(s.isBigDecimalSchema()){if(r!=null)this.writeKey(n),this.writeValue(r instanceof U?r.string:String(r))}else if(s.isTimestampSchema()){if(r instanceof Date)switch(this.writeKey(n),pe(s,this.settings)){case 5:this.writeValue(r.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(je(r));break;case 7:this.writeValue(String(r.getTime()/1000));break}}else if(s.isDocumentSchema())if(Array.isArray(r))this.write(79,r,n);else if(r instanceof Date)this.write(4,r,n);else if(r instanceof Uint8Array)this.write(21,r,n);else if(r&&typeof r==="object")this.write(143,r,n);else this.writeKey(n),this.writeValue(String(r));else if(s.isListSchema()){if(Array.isArray(r))if(r.length===0){if(this.settings.serializeEmptyLists)this.writeKey(n),this.writeValue("")}else{let o=s.getValueSchema(),i=this.settings.flattenLists||s.getMergedTraits().xmlFlattened,c=1;for(let a of r){if(a==null)continue;let f=o.getMergedTraits(),u=this.getKey("member",f.xmlName,f.ec2QueryName),h=i?`${n}${c}`:`${n}${u}.${c}`;this.write(o,a,h),++c}}}else if(s.isMapSchema()){if(r&&typeof r==="object"){let o=s.getKeySchema(),i=s.getValueSchema(),c=s.getMergedTraits().xmlFlattened,a=1;for(let f in r){let u=r[f];if(u==null)continue;let h=o.getMergedTraits(),l=this.getKey("key",h.xmlName,h.ec2QueryName),d=c?`${n}${a}.${l}`:`${n}entry.${a}.${l}`,m=i.getMergedTraits(),y=this.getKey("value",m.xmlName,m.ec2QueryName),g=c?`${n}${a}.${y}`:`${n}entry.${a}.${y}`;this.write(o,f,d),this.write(i,u,g),++a}}}else if(s.isStructSchema()){if(r&&typeof r==="object"){let o=!1;for(let[i,c]of s.structIterator()){if(r[i]==null&&!c.isIdempotencyToken())continue;let a=c.getMergedTraits(),f=this.getKey(i,a.xmlName,a.ec2QueryName,"struct"),u=`${n}${f}`;this.write(c,r[i],u),o=!0}if(!o&&s.isUnionSchema()){let{$unknown:i}=r;if(Array.isArray(i)){let[c,a]=i,f=`${n}${c}`;this.write(15,a,f)}}}}else if(s.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${s.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let e=this.buffer;return delete this.buffer,e}getKey(e,r,n,s){let{ec2:o,capitalizeKeys:i}=this.settings;if(o&&n)return n;let c=r??e;if(i&&s==="struct")return c[0].toUpperCase()+c.slice(1);return c}writeKey(e){if(e.endsWith("."))e=e.slice(0,e.length-1);this.buffer+=`&${zn(e)}=`}writeValue(e){this.buffer+=zn(e)}}class lr extends Gn{options;serializer;deserializer;mixin=new ye;constructor(e){super({defaultNamespace:e.defaultNamespace,errorTypeRegistries:e.errorTypeRegistries});this.options=e;let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace,serializeEmptyLists:!0};this.serializer=new hr(r),this.deserializer=new mt(r)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(e){this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]="application/x-www-form-urlencoded",qn(e.input)==="unit"||!s.body)s.body="";let o=e.name.split("#")[1]??e.name;if(s.body=`Action=${o}&Version=${this.options.version}`+s.body,s.body.endsWith("&"))s.body=s.body.slice(-1);return s}async deserializeResponse(e,r,n){let s=this.deserializer,o=T.of(e.output),i={};if(n.statusCode>=300){let u=await nt(n.body,r);if(u.byteLength>0)Object.assign(i,await s.read(15,u));await this.handleError(e,r,n,i,this.deserializeMetadata(n))}for(let u in n.headers){let h=n.headers[u];delete n.headers[u],n.headers[u.toLowerCase()]=h}let c=e.name.split("#")[1]??e.name,a=o.isStructSchema()&&this.useNestedResult()?c+"Result":void 0,f=await nt(n.body,r);if(f.byteLength>0)Object.assign(i,await s.read(o,f,a));return i.$metadata=this.deserializeMetadata(n),i}useNestedResult(){return!0}async handleError(e,r,n,s,o){let i=this.loadQueryErrorCode(n,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let c=this.loadQueryError(s)??{},a=this.loadQueryErrorMessage(s);c.message=a,c.Error={Type:c.Type,Code:c.Code,Message:a};let{errorSchema:f,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,n,c,o,this.mixin.findQueryCompatibleError),h=T.of(f),d=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),m={Type:c.Error.Type,Code:c.Error.Code,Error:c.Error};for(let[y,g]of h.structIterator()){let N=g.getMergedTraits().xmlName??y,I=c[N]??s[N];m[y]=this.deserializer.readSchema(g,I)}throw this.mixin.decorateServiceException(Object.assign(d,u,{$fault:h.getMergedTraits().error,message:a},m),s)}loadQueryErrorCode(e,r){let n=(r.Errors?.[0]?.Error??r.Errors?.Error??r.Error)?.Code;if(n!==void 0)return n;if(e.statusCode==404)return"NotFound"}loadQueryError(e){return e.Errors?.[0]?.Error??e.Errors?.Error??e.Error}loadQueryErrorMessage(e){let r=this.loadQueryError(e);return r?.message??r?.Message??e.message??e.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class ls extends lr{options;constructor(e){super(e);this.options=e;let r={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,r)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var ds=(e,r)=>ns(e,r).then((n)=>{if(n.length){let s;try{s=es(n)}catch(a){if(a&&typeof a==="object")Object.defineProperty(a,"$responseBodyText",{value:n});throw a}let o="#text",i=Object.keys(s)[0],c=s[i];if(c[o])c[i]=c[o],delete c[o];return Qn(c)}return{}}),Cc=async(e,r)=>{let n=await ds(e,r);if(n.Error)n.Error.message=n.Error.message??n.Error.Message;return n},ms=(e,r)=>{if(r?.Error?.Code!==void 0)return r.Error.Code;if(r?.Code!==void 0)return r.Code;if(e.statusCode==404)return"NotFound"};class dr extends K{settings;stringBuffer;byteBuffer;buffer;constructor(e){super();this.settings=e}write(e,r){let n=T.of(e);if(n.isStringSchema()&&typeof r==="string")this.stringBuffer=r;else if(n.isBlobSchema())this.byteBuffer="byteLength"in r?r:(this.serdeContext?.base64Decoder??ir)(r);else{this.buffer=this.writeStruct(n,r,void 0);let s=n.getMergedTraits();if(s.httpPayload&&!s.xmlName)this.buffer.withName(n.getName())}}flush(){if(this.byteBuffer!==void 0){let r=this.byteBuffer;return delete this.byteBuffer,r}if(this.stringBuffer!==void 0){let r=this.stringBuffer;return delete this.stringBuffer,r}let e=this.buffer;if(this.settings.xmlNamespace){if(!e?.attributes?.xmlns)e.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,e.toString()}writeStruct(e,r,n){let s=e.getMergedTraits(),o=e.isMemberSchema()&&!s.httpPayload?e.getMemberTraits().xmlName??e.getMemberName():s.xmlName??e.getName();if(!o||!e.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${e.getName(!0)}.`);let i=H.of(o),[c,a]=this.getXmlnsAttribute(e,n);for(let[u,h]of e.structIterator()){let l=r[u];if(l!=null||h.isIdempotencyToken()){if(h.getMergedTraits().xmlAttribute){i.addAttribute(h.getMergedTraits().xmlName??u,this.writeSimple(h,l));continue}if(h.isListSchema())this.writeList(h,l,i,a);else if(h.isMapSchema())this.writeMap(h,l,i,a);else if(h.isStructSchema())i.addChildNode(this.writeStruct(h,l,a));else{let d=H.of(h.getMergedTraits().xmlName??h.getMemberName());this.writeSimpleInto(h,l,d,a),i.addChildNode(d)}}}let{$unknown:f}=r;if(f&&e.isUnionSchema()&&Array.isArray(f)&&Object.keys(r).length===1){let[u,h]=f,l=H.of(u);if(typeof h!=="string")if(r instanceof H||r instanceof On)i.addChildNode(r);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,h,l,a),i.addChildNode(l)}if(a)i.addAttribute(c,a);return i}writeList(e,r,n,s){if(!e.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${e.getName(!0)}`);let o=e.getMergedTraits(),i=e.getValueSchema(),c=i.getMergedTraits(),a=!!c.sparse,f=!!o.xmlFlattened,[u,h]=this.getXmlnsAttribute(e,s),l=(d,m)=>{if(i.isListSchema())this.writeList(i,Array.isArray(m)?m:[m],d,h);else if(i.isMapSchema())this.writeMap(i,m,d,h);else if(i.isStructSchema()){let y=this.writeStruct(i,m,h);d.addChildNode(y.withName(f?o.xmlName??e.getMemberName():c.xmlName??"member"))}else{let y=H.of(f?o.xmlName??e.getMemberName():c.xmlName??"member");this.writeSimpleInto(i,m,y,h),d.addChildNode(y)}};if(f){for(let d of r)if(a||d!=null)l(n,d)}else{let d=H.of(o.xmlName??e.getMemberName());if(h)d.addAttribute(u,h);for(let m of r)if(a||m!=null)l(d,m);n.addChildNode(d)}}writeMap(e,r,n,s,o=!1){if(!e.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${e.getName(!0)}`);let i=e.getMergedTraits(),c=e.getKeySchema(),f=c.getMergedTraits().xmlName??"key",u=e.getValueSchema(),h=u.getMergedTraits(),l=h.xmlName??"value",d=!!h.sparse,m=!!i.xmlFlattened,[y,g]=this.getXmlnsAttribute(e,s),N=(I,j,z)=>{let ee=H.of(f,j),[ps,gr]=this.getXmlnsAttribute(c,g);if(gr)ee.addAttribute(ps,gr);I.addChildNode(ee);let Se=H.of(l);if(u.isListSchema())this.writeList(u,z,Se,g);else if(u.isMapSchema())this.writeMap(u,z,Se,g,!0);else if(u.isStructSchema())Se=this.writeStruct(u,z,g);else this.writeSimpleInto(u,z,Se,g);I.addChildNode(Se)};if(m)for(let I in r){let j=r[I];if(d||j!=null){let z=H.of(i.xmlName??e.getMemberName());N(z,I,j),n.addChildNode(z)}}else{let I;if(!o){if(I=H.of(i.xmlName??e.getMemberName()),g)I.addAttribute(y,g);n.addChildNode(I)}for(let j in r){let z=r[j];if(d||z!=null){let ee=H.of("entry");N(ee,j,z),(o?n:I).addChildNode(ee)}}}}writeSimple(e,r){if(r===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let n=T.of(e),s=null;if(r&&typeof r==="object")if(n.isBlobSchema())s=(this.serdeContext?.base64Encoder??ge)(r);else if(n.isTimestampSchema()&&r instanceof Date)switch(pe(n,this.settings)){case 5:s=r.toISOString().replace(".000Z","Z");break;case 6:s=je(r);break;case 7:s=String(r.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",r),s=je(r);break}else if(n.isBigDecimalSchema()&&r){if(r instanceof U)return r.string;return String(r)}else if(n.isMapSchema()||n.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${n.getName(!0)}`);if(n.isBooleanSchema()||n.isNumericSchema()||n.isBigIntegerSchema()||n.isBigDecimalSchema())s=String(r);if(n.isStringSchema())if(r===void 0&&n.isIdempotencyToken())s=at();else s=String(r);if(s===null)throw Error(`Unhandled schema-value pair ${n.getName(!0)}=${r}`);return s}writeSimpleInto(e,r,n,s){let o=this.writeSimple(e,r),i=T.of(e),c=new On(o),[a,f]=this.getXmlnsAttribute(i,s);if(f)n.addAttribute(a,f);n.addChildNode(c)}getXmlnsAttribute(e,r){let n=e.getMergedTraits(),[s,o]=n.xmlNamespace??[];if(o&&o!==r)return[s?`xmlns:${s}`:"xmlns",o];return[void 0,void 0]}}class mr extends K{settings;constructor(e){super();this.settings=e}createSerializer(){let e=new dr(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new mt(this.settings);return e.setSerdeContext(this.serdeContext),e}}class gs extends Wn{codec;serializer;deserializer;mixin=new ye;constructor(e){super(e);let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace};this.codec=new mr(r),this.serializer=new Xn(this.codec.createSerializer(),r),this.deserializer=new Jn(this.codec.createDeserializer(),r)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(e,r,n){let s=await super.serializeRequest(e,r,n),o=T.of(e.input);if(!s.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),o);if(i)s.headers["content-type"]=i}if(typeof s.body==="string"&&s.headers["content-type"]===this.getDefaultContentType()&&!s.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(o))s.body='<?xml version="1.0" encoding="UTF-8"?>'+s.body;return s}async deserializeResponse(e,r,n){return super.deserializeResponse(e,r,n)}async handleError(e,r,n,s,o){let i=ms(n,s)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace),s.Error&&typeof s.Error==="object"){for(let y of Object.keys(s.Error))if(s[y]=s.Error[y],y.toLowerCase()==="message")s.message=s.Error[y]}if(s.RequestId&&!o.requestId)o.requestId=s.RequestId;let{errorSchema:c,errorMetadata:a}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,n,s,o),f=T.of(c),u=s.Error?.message??s.Error?.Message??s.message??s.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({});await this.deserializeHttpMessage(c,r,n,s);let d={},m=this.codec.createDeserializer();for(let[y,g]of f.structIterator()){let N=g.getMergedTraits().xmlName??y,I=s.Error?.[N]??s[N];d[y]=m.readSchema(g,I)}throw this.mixin.decorateServiceException(Object.assign(l,a,{$fault:f.getMergedTraits().error,message:u},d),s)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(e){for(let[,r]of e.structIterator())if(r.getMergedTraits().httpPayload)return!(r.isStructSchema()||r.isMapSchema()||r.isListSchema());return!1}}var Ac=(e)=>{if(e==null)return;if(typeof e==="object"&&"__type"in e)delete e.__type;return gc(e)},Tc=(e)=>{if(e==null)return e;if(typeof e==="number"||typeof e==="bigint"){let r=Error(`Received number ${e} where a string was expected.`);return r.name="Warning",console.warn(r),String(e)}if(typeof e==="boolean"){let r=Error(`Received boolean ${e} where a string was expected.`);return r.name="Warning",console.warn(r),String(e)}return e},Ic=(e)=>{if(e==null)return e;if(typeof e==="string"){let r=e.toLowerCase();if(e!==""&&r!=="false"&&r!=="true"){let n=Error(`Received string "${e}" where a boolean was expected.`);n.name="Warning",console.warn(n)}return e!==""&&r!=="false"}return e},kc=(e)=>{if(e==null)return e;if(typeof e==="string"){let r=Number(e);if(r.toString()!==e){let n=Error(`Received string "${e}" where a number was expected.`);return n.name="Warning",console.warn(n),e}return r}return e};Rc.AwsEc2QueryProtocol=ls;Rc.AwsJson1_0Protocol=cs;Rc.AwsJson1_1Protocol=as;Rc.AwsJsonRpcProtocol=dt;Rc.AwsQueryProtocol=lr;Rc.AwsRestJsonProtocol=fs;Rc.AwsRestXmlProtocol=gs;Rc.AwsSmithyRpcV2CborProtocol=ts;Rc.JsonCodec=hs;Rc.JsonCodec2=lt;Rc.JsonShapeDeserializer=fr;Rc.JsonShapeDeserializer2=ar;Rc.JsonShapeSerializer=ur;Rc.JsonShapeSerializer2=ht;Rc.QueryShapeSerializer=hr;Rc.XmlCodec=mr;Rc.XmlShapeDeserializer=mt;Rc.XmlShapeSerializer=dr;Rc._toBool=Ic;Rc._toNum=kc;Rc._toStr=Tc;Rc.awsExpectUnion=Ac;Rc.loadJsonRpcErrorCode=is;Rc.loadRestJsonErrorCode=ss;Rc.loadRestXmlErrorCode=ms;Rc.parseJsonBody=ut;Rc.parseJsonErrorBody=wc;Rc.parseXmlBody=ds;Rc.parseXmlErrorBody=Cc});
|
|
20
|
+
export{zo,Ue,ot};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Fe}from"./chunk-t057xfrt.js";import{L}from"./chunk-0hbjv3y6.js";import{b,X,B}from"./chunk-k7w7ac9q.js";import{i}from"./chunk-qnr1f5pj.js";var w=i(L()),d=i(b()),R=i(Fe());import k from"fs/promises";var A=i(b());var y="169.254.170.2",v="169.254.170.23",U="[fd00:ec2::23]",C=(e,o)=>{if(e.protocol==="https:")return;if(e.hostname===y||e.hostname===v||e.hostname===U)return;if(e.hostname.includes("[")){if(e.hostname==="[::1]"||e.hostname==="[0000:0000:0000:0000:0000:0000:0000:0001]")return}else{if(e.hostname==="localhost")return;let n=e.hostname.split("."),r=(t)=>{let s=parseInt(t,10);return 0<=s&&s<=255};if(n[0]==="127"&&r(n[1])&&r(n[2])&&r(n[3])&&n.length===4)return}throw new A.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
|
|
3
|
+
- loopback CIDR 127.0.0.0/8 or [::1/128]
|
|
4
|
+
- ECS container host 169.254.170.2
|
|
5
|
+
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:o})};var c=i(b()),p=i(B()),_=i(X()),f=i(X());function I(e){return new p.HttpRequest({protocol:e.protocol,hostname:e.hostname,port:Number(e.port),path:e.pathname,query:Array.from(e.searchParams.entries()).reduce((o,[n,r])=>(o[n]=r,o),{}),fragment:e.hash})}async function u(e,o){let r=await f.sdkStreamMixin(e.body).transformToString();if(e.statusCode===200){let t=JSON.parse(r);if(typeof t.AccessKeyId!=="string"||typeof t.SecretAccessKey!=="string"||typeof t.Token!=="string"||typeof t.Expiration!=="string")throw new c.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:o});return{accessKeyId:t.AccessKeyId,secretAccessKey:t.SecretAccessKey,sessionToken:t.Token,expiration:_.parseRfc3339DateTime(t.Expiration)}}if(e.statusCode>=400&&e.statusCode<500){let t={};try{t=JSON.parse(r)}catch(s){}throw Object.assign(new c.CredentialsProviderError(`Server responded with status: ${e.statusCode}`,{logger:o}),{Code:t.Code,Message:t.Message})}throw new c.CredentialsProviderError(`Server responded with status: ${e.statusCode}`,{logger:o})}var E=(e,o,n)=>async()=>{for(let r=0;r<o;++r)try{return await e()}catch(t){await new Promise((s)=>setTimeout(s,n))}return await e()};var H="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",K="http://169.254.170.2",P="AWS_CONTAINER_CREDENTIALS_FULL_URI",F="AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",x="AWS_CONTAINER_AUTHORIZATION_TOKEN",D=(e={})=>{e.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let o,n=e.awsContainerCredentialsRelativeUri??process.env[H],r=e.awsContainerCredentialsFullUri??process.env[P],t=e.awsContainerAuthorizationToken??process.env[x],s=e.awsContainerAuthorizationTokenFile??process.env[F],a=e.logger?.constructor?.name==="NoOpLogger"||!e.logger?.warn?console.warn:e.logger.warn.bind(e.logger);if(n&&r)a("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."),a("awsContainerCredentialsRelativeUri will take precedence.");if(t&&s)a("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."),a("awsContainerAuthorizationTokenFile will take precedence.");if(n)o=`${K}${n}`;else if(r)o=r;else throw new d.CredentialsProviderError(`No HTTP credential provider host provided.
|
|
6
|
+
Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`,{logger:e.logger});let h=new URL(o);C(h,e.logger);let l=R.NodeHttpHandler.create({connectionTimeout:e.timeout??1000}),g=e.timeout??1000,S=E(async()=>{let m=I(h);if(s)m.headers.Authorization=N((await k.readFile(s)).toString());else if(t)m.headers.Authorization=N(t);try{let T=await l.handle(m,{requestTimeout:g});return u(T.response).then((O)=>w.setCredentialFeature(O,"CREDENTIALS_HTTP","z"))}catch(T){throw new d.CredentialsProviderError(String(T),{logger:e.logger})}},e.maxRetries??3,e.timeout??1000);return async()=>{try{return await S()}finally{l.destroy?.()}}},N=(e)=>{if(e.includes(`\r
|
|
7
|
+
`))throw new d.CredentialsProviderError("Authorization token contains invalid \\r\\n sequence.");return e};export{D as fromHttp};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{F}from"./chunk-c25s4w6a.js";import{Ze}from"./chunk-g2t6t8fk.js";import{de,Mr,Lr,ce,Jt,me}from"./chunk-1aspj1hn.js";import{g}from"./chunk-n6e43rvk.js";import{N,Me,re,ye,Q}from"./chunk-qczbfccb.js";function j(a,o){let l={v:1,id:a};if(o)l.phase=o;return JSON.stringify(l)}function E(a){if(!a)return;if(a.startsWith("{"))try{let o=JSON.parse(a);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:a}}function W(a,o){let l=o.filter((c)=>c.type==="text").map((c)=>c.text).join(`
|
|
3
|
+
`),d=o.filter((c)=>c.type==="image"),u=l.length>0;if(d.length===0||!a.input.includes("image"))return g(u?l:d.length>0?"(see attached image)":"(no tool output)");let p=[];if(u)p.push({type:"input_text",text:g(l)});for(let c of d)p.push({type:"input_image",detail:"auto",image_url:`data:${c.mimeType};base64,${c.data}`});return p}function at(a,o,l,d){let u=re(o,d?.supportsMidConvoSystemMessages),p=[],c=(n)=>{let s=n.replace(/[^a-zA-Z0-9_-]/g,"_");return(s.length>64?s.slice(0,64):s).replace(/_+$/,"")},b=(n)=>{let s=`fc_${Ze(n)}`;return s.length>64?s.slice(0,64):s},k=(n,s,i)=>{if(!l.has(a.provider))return c(n);if(!n.includes("|"))return c(n);let[r,_]=n.split("|"),y=c(r),x=i.provider!==a.provider||i.api!==a.api?b(_):c(_);if(!x.startsWith("fc_"))x=c(`fc_${x}`);return`${y}|${x}`},m=me(u.messages,a,k),I=ye(u.messages,(d?.supportsAdditionalTools??!1)||(d?.supportsToolSearch??!1)),v=(n,s)=>{let i=I.anchorsAdditions?n.toolsAdded??[]:[];if(i.length===0)return;if(d?.supportsAdditionalTools){p.push({type:"additional_tools",role:"developer",tools:Je(i,d.toolOptions)});return}if(!d?.supportsToolSearch)return;let r=i.map((y)=>y.name),_=`pi_tool_load_${Ze(`${s}:${r.join(",")}`)}`;p.push({type:"tool_search_call",call_id:_,execution:"client",status:"completed",arguments:{query:r.join(" "),limit:r.length}}),p.push({type:"tool_search_output",call_id:_,execution:"client",status:"completed",tools:Je(i,{...d.toolOptions,toolSearchResult:!0})})},C=d?.includeSystemPrompt??!0,w=a.compat,M=a.reasoning&&w?.supportsDeveloperRole!==!1?"developer":"system",t=0,e=0;for(let n of m){let s=e++===0&&n.role==="system";if(n.role==="system"){if(!s)v(n,`system:${t}`);if(!s||C){let i=s?N(n):Me(n);if(i.length>0)p.push({role:M,content:g(i)})}}else if(n.role==="user")if(typeof n.content==="string")p.push({role:"user",content:[{type:"input_text",text:g(n.content)}]});else{let i=n.content.map((r)=>{if(r.type==="text")return{type:"input_text",text:g(r.text)};return{type:"input_image",detail:"auto",image_url:`data:${r.mimeType};base64,${r.data}`}});if(i.length===0)continue;p.push({role:"user",content:i})}else if(n.role==="assistant"){let i=[],r=n,_=r.provider===a.provider&&r.api===a.api,y=_&&r.model===a.id,P=_&&r.model!==a.id,x=0;for(let S of n.content)if(S.type==="thinking"){if(S.thinkingSignature){let f=JSON.parse(S.thinkingSignature);i.push(f)}}else if(S.type==="text"){let f=S,T=E(f.textSignature),J=x===0?`msg_pi_${t}`:`msg_pi_${t}_${x}`;x++;let h=T?.id;if(!h)h=J;else if(h.length>64)h=`msg_${Ze(h)}`;i.push({type:"message",role:"assistant",content:[{type:"output_text",text:g(f.text),annotations:[]}],status:"completed",id:h,phase:T?.phase})}else if(S.type==="toolCall"){let f=S,[T,J]=f.id.split("|"),h=d?.grammarToolInputProperties?.get(f.name),R=J,A=h===void 0?"fc_":"ctc_";if(P||!R?.startsWith(A))R=void 0;if(h!==void 0)i.push({type:"custom_tool_call",id:R,call_id:T,name:f.name,input:g(Mr(f.name,f.arguments,h)),...y&&f.namespace!==void 0?{namespace:f.namespace}:{}});else i.push({type:"function_call",id:R,call_id:T,name:f.name,arguments:JSON.stringify(f.arguments),...y&&f.namespace!==void 0?{namespace:f.namespace}:{}})}if(i.length===0)continue;p.push(...i)}else if(n.role==="toolResult"){let[i]=n.toolCallId.split("|"),r=W(a,n.content);if(d?.grammarToolInputProperties?.has(n.toolName))p.push({type:"custom_tool_call_output",call_id:i,output:r});else p.push({type:"function_call_output",call_id:i,output:r})}if(!s)t++}return p}function Je(a,o){let l=o?.strict===void 0?!1:o.strict,d=o?.supportsStrictMode??!0,u=o?.supportsOpenAIGrammarTools??!1;return a.map((p)=>{let c=Jt(p,u);if(c)return{type:"custom",name:p.name,description:p.description,format:{type:"grammar",syntax:c.format,definition:c.definition},...o?.toolSearchResult?{defer_loading:!0}:{}};let k=ce(p,d)??l,m={type:"function",name:p.name,description:p.description,parameters:de(p,k===!0),...o?.toolSearchResult?{defer_loading:!0}:{}};if(d)m.strict=k;return m})}function z(a){let o=a.customInput?.property;if(o===void 0)return"";let l=a.arguments[o];return typeof l==="string"?l:""}function O(a,o,l){let d=a.customInput;if(!d)return;let u=Lr(d.jsonBuffer,d.property,o,l);return a.arguments={[d.property]:o},u}async function lt(a,o,l,d,u){let p=!1,c=new Map,b=new Map,k=(t)=>{if(t.type==="message"&&t.phase==="final_answer")o.stopReason="stop"},m=(t,e)=>{let n=c.get(t);return n?.type===e?n:void 0},I=(t,e)=>{if(e===void 0)return;l.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},v=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){k(e);let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},...e.namespace!==void 0?{namespace:e.namespace}:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=u?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",i={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},...e.namespace!==void 0?{namespace:e.namespace}:{},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(i);let r={type:"toolCall",block:i,contentIndex:o.content.length-1};return c.set(t,r),l.push({type:"toolcall_start",contentIndex:r.contentIndex,partial:o}),r}return},C=(t,e)=>c.get(t)??v(t,e),w=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=b.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},M=(t)=>{if(p=!0,w(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let r=t.usage.input_tokens_details,_=r?.cached_tokens||0,y=r?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-_-y),output:t.usage.output_tokens||0,cacheRead:_,cacheWrite:y,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(Q(d,o.usage),u?.applyServiceTierPricing){let r=u.resolveServiceTier?u.resolveServiceTier(t?.service_tier,u.serviceTier):t?.service_tier??u.serviceTier;u.applyServiceTierPricing(o.usage,r)}let e=t?.status,n=t?.incomplete_details,s=typeof n?.reason==="string"?n.reason:void 0;o.rawStopReason=s?`${e}.${s}`:e;let i=B(e,s);if(o.stopReason=i.stopReason,i.errorMessage===void 0)delete o.errorMessage;else o.errorMessage=i.errorMessage;if(o.content.some((r)=>r.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of a)if(await u?.onProviderStreamEvent?.(t,d),t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")v(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
4
|
+
|
|
5
|
+
`,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
6
|
+
|
|
7
|
+
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=F(e.block.partialJson),I(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=F(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)I(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,z(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item;k(e);let n=C(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((r)=>r.text).join(`
|
|
8
|
+
|
|
9
|
+
`)||"",i=e.content?.map((r)=>r.text).join(`
|
|
10
|
+
|
|
11
|
+
`)||"";n.block.thinking=s||i||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),b.set(e.id,n.block),l.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),c.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=j(e.id,e.phase??void 0),l.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),c.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0){if(n.block.arguments=F(e.arguments||n.block.partialJson||"{}"),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.partialJson,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput){if(I(n,O(n.block,e.input??z(n.block),!0)),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.customInput,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}}else if(t.type==="response.completed"||t.type==="response.incomplete")M(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){p=!0,o.rawStopReason=t.response?.status;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!p)throw Error("OpenAI Responses stream ended before a terminal response event");if(o.stopReason==="toolUse")for(let t of o.content){if(t.type!=="toolCall")continue;let e=t;if(e.partialJson!==void 0||e.customInput!==void 0)throw Error(`OpenAI Responses stream completed with an unfinished tool call: ${e.name} (${e.id})`)}}function B(a,o){if(!a)return{stopReason:"stop"};switch(a){case"completed":return{stopReason:"stop"};case"incomplete":if(o==="max_output_tokens")return{stopReason:"length"};return{stopReason:"error",errorMessage:o?`Response incomplete: ${o}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:throw Error(`Unhandled stop reason: ${a}`)}}
|
|
12
|
+
export{at,Je,lt};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{F}from"./chunk-c25s4w6a.js";import{xr}from"./chunk-v9fea96h.js";import{Ze}from"./chunk-g2t6t8fk.js";import{ee}from"./chunk-tvm4zmgj.js";import{de,ce,V,me}from"./chunk-1aspj1hn.js";import{g}from"./chunk-n6e43rvk.js";import{z}from"./chunk-dakrpbe6.js";import{N,Me,ne,re,Q,H}from"./chunk-qczbfccb.js";import{M}from"./chunk-6e49xsf5.js";var S=9,U=4000,D=(t,e,n)=>{let r=new M,o=re(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=B(t);try{let l=n?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let f=J(),u=me(o.messages,t,(d)=>f(d)),a=se(t,o,u,n),i=await n?.onPayload?.(a,t);if(i!==void 0)a=i;let c=await Z(t,a,l,n);if(r.push({type:"start",partial:s}),await ie(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw Error("Request was aborted");if(s.stopReason==="pending")throw Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=K(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Ee=(t,e,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${t.provider}`);let o={...V(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?H(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return D(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function B(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function J(){let t=new Map,e=new Map;return(n)=>{let r=t.get(n);if(r)return r;let o=0;while(!0){let s=P(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function P(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===S)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return Ze(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,S)}function K(t){if(t instanceof Error){let e=t,n=typeof e.statusCode==="number"?e.statusCode:void 0,r=typeof e.body==="string"?e.body.trim():void 0;if(n!==void 0&&r)return`Mistral API error (${n}): ${W(r,U)}`;if(n!==void 0)return`Mistral API error (${n}): ${t.message}`;return t.message}return q(t)}function W(t,e){if(t.length<=e)return t;return`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function q(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function Z(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=G(t,n,r),f=r?.timeoutMs??60000,u=AbortSignal.timeout(f),a=xr([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(X(e)),signal:a.signal})}catch(c){if(u.aborted&&!r?.signal?.aborted)throw Error(`Mistral response headers timed out after ${f}ms`);throw c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:z(i.headers)},t),!i.ok){let c=await i.text();throw new O(i.status,c,i.statusText)}if(!i.body)throw Error("Mistral response has no body");return oe(i.body,r?.signal)}class O extends Error{statusCode;body;constructor(t,e,n){super(n||`Request failed with status ${t}`);this.name="MistralHttpError",this.statusCode=t,this.body=e}}function G(t,e,n){let r=new Headers({"User-Agent":ee(),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});A(r,t.headers),A(r,n?.headers);let o=I(t.headers,"x-affinity")||I(n?.headers,"x-affinity");if(L(n)&&!o)r.set("x-affinity",n.sessionId);return r}function A(t,e){if(!e)return;for(let[n,r]of Object.entries(e))if(r===null)t.delete(n);else t.set(n,r)}function I(t,e){return!!t&&Object.keys(t).some((n)=>n.toLowerCase()===e)}function X(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map((r)=>Y(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function Y(t){let e={...t};if(k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content))e.content=t.content.map((n)=>te(n));return e}function te(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){if(!(e in t))return;t[n]=t[e],delete t[e]}function w(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*oe(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{while(!0){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=E(o);while(u){let a=v(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;if(a)yield a;u=E(o)}if(l)break}if(o.trim()){let l=v(o);if(l!==b&&l)yield l}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function E(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function v(t){let e=t.split(/\r\n|\r|\n/u).filter((r)=>r.startsWith("data:")).map((r)=>r.slice(5).trimStart()).join(`
|
|
3
|
+
`).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw Error("Invalid Mistral streaming event");return{data:n}}function se(t,e,n,r){let o={model:t.id,stream:!0,messages:fe(n,t.input.includes("image"))},s=ne(e.messages);if(s.length>0)o.tools=le(s);if(r?.temperature!==void 0)o.temperature=r.temperature;if(r?.maxTokens!==void 0)o.maxTokens=r.maxTokens;if(r?.toolChoice)o.toolChoice=pe(r.toolChoice);if(r?.promptMode)o.promptMode=r.promptMode;if(r?.reasoningEffort)o.reasoningEffort=r.reasoningEffort;if(L(r))o.promptCacheKey=r.sessionId;return o}function L(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ae(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r==="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function ie(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=(i)=>{if(!i)return;if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}if(i.type==="thinking")n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ae(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,Q(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=he(d.finish_reason);if(e.stopReason=p.stopReason,p.errorMessage)e.errorMessage=p.errorMessage}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content==="string"?[x.content]:x.content;for(let h of p){if(typeof h==="string"){let m=g(h);if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map((y)=>y.text??"").filter((y)=>y.length>0).join(""),_=g(m);if(!_)continue;if(!s||s.type!=="thinking")a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e});s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=g(h.text??"");if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let j=x.tool_calls||[];for(let p of j){if(s)a(s),s=null;let h=p.id&&p.id!=="null"?p.id:P(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),y;if(_!==void 0){let R=e.content[_];if(R?.type==="toolCall")y=R}if(!y)y={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(y),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e});let C=typeof p.function.arguments==="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});y.partialArgs=(y.partialArgs||"")+C,y.arguments=F(y.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;d.arguments=F(d.partialArgs),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function le(t){return t.map((e)=>{let n=ce(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(de(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map((e)=>T(e));if(t&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function fe(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?N(o):Me(o);if(a.length>0)n.push({role:"system",content:g(a)});continue}if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",content:g(o.content)});continue}let a=o.content.some((c)=>c.type==="image"),i=o.content.filter((c)=>c.type==="text"||e).map((c)=>{if(c.type==="text")return{type:"text",text:g(c.text)};return{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`}});if(i.length>0){n.push({role:"user",content:i});continue}if(a&&!e)n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){if(d.text.trim().length>0)a.push({type:"text",text:g(d.text)});continue}if(d.type==="thinking"){if(d.thinking.trim().length>0)a.push({type:"thinking",thinking:[{type:"text",text:g(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};if(a.length>0)c.content=a;if(i.length>0)c.toolCalls=i;if(a.length>0||i.length>0)n.push(c);continue}let s=[],l=o.content.filter((a)=>a.type==="text").map((a)=>a.type==="text"?g(a.text):"").join(`
|
|
4
|
+
`),f=o.content.some((a)=>a.type==="image"),u=ue(l,f,e,o.isError);s.push({type:"text",text:u});for(let a of o.content){if(!e)continue;if(a.type!=="image")continue;s.push({type:"image_url",imageUrl:`data:${a.mimeType};base64,${a.data}`})}n.push({role:"tool",toolCallId:o.toolCallId,name:o.toolName,content:s})}return n}function ue(t,e,n,r){let o=t.trim(),s=r?"[tool error] ":"";if(o.length>0)return`${s}${o}${e&&!n?`
|
|
5
|
+
[tool image omitted: model does not support images]`:""}`;if(e){if(n)return r?"[tool error] (see attached image)":"(see attached image)";return r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)"}return r?"[tool error] (no tool output)":"(no tool output)"}function pe(t){if(!t)return;if(t==="auto"||t==="none"||t==="any"||t==="required")return t;return{type:"function",function:{name:t.function.name}}}function he(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{D as stream,Ee as streamSimple};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var f=new Set;function $n(r){return f.add(r),()=>{f.delete(r)}}function Ei(r){let t=[];for(let s of f)try{s(r)}catch(e){t.push(e)}if(t.length>0)throw AggregateError(t,"Failed to cleanup session resources")}var a=(1n<<41n)-1n,u=-1,n;function Gr(r){let t=r??Date.now();if(!Number.isInteger(t)||t<0||t>281474976710655)throw RangeError("UUIDv7 timestamp must be an integer between 0 and 281474976710655");let s=r===void 0?Math.max(t,u):r;if(r===void 0)u=s;let e=new Uint8Array(16);if(globalThis.crypto.getRandomValues(e),n===void 0)n=BigInt(e[1])<<32n|BigInt(e[2])<<24n|BigInt(e[3])<<16n|BigInt(e[4])<<8n|BigInt(e[5]);else{if(n===a)throw RangeError("UUIDv7 generator sequence exhausted");n++}let c=BigInt(s);for(let o=5;o>=0;o--)e[o]=Number(c>>BigInt((5-o)*8))&255;e[6]=112|Number(n>>37n&0x0fn),e[7]=Number(n>>29n&0xffn),e[8]=128|Number(n>>23n&0x3fn),e[9]=Number(n>>15n&0xffn),e[10]=Number(n>>7n&0xffn),e[11]=Number((n&0x7fn)<<1n)|e[11]&1;let i=Array.from(e,(o)=>o.toString(16).padStart(2,"0"));return`${i.slice(0,4).join("")}-${i.slice(4,6).join("")}-${i.slice(6,8).join("")}-${i.slice(8,10).join("")}-${i.slice(10).join("")}`}
|
|
3
|
+
export{$n,Ei,Gr};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{X,B}from"./chunk-k7w7ac9q.js";import{t,p}from"./chunk-qnr1f5pj.js";var Fe=t(function(me){var{hasOwn:Q}=X(),{streamCollector:ne}=X();me.streamCollector=ne;var{buildQueryString:J,HttpResponse:G}=B(),A=p("https"),{Readable:se}=p("stream"),O=p("http2");function M(e){let o=e&&typeof e==="object"&&"reason"in e?e.reason:void 0;if(o){if(o instanceof Error){let r=Error("Request aborted");return r.name="AbortError",r.cause=o,r}let s=Error(String(o));return s.name="AbortError",s}let n=Error("Request aborted");return n.name="AbortError",n}var re=["ECONNRESET","EPIPE","ETIMEDOUT"],Y=(e)=>{let o={};for(let n in e){if(!Q(e,n))continue;let s=e[n];o[n]=Array.isArray(s)?s.join(","):s}return o},l={setTimeout:(e,o)=>setTimeout(e,o),clearTimeout:(e)=>clearTimeout(e)},j=1000,ie=(e,o,n=0)=>{if(!n)return-1;let s=(r)=>{let c=l.setTimeout(()=>{e.destroy(),o(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${n} ms.`),{name:"TimeoutError"}))},n-r),a=(u)=>{if(u?.connecting)u.on("connect",()=>{l.clearTimeout(c)});else l.clearTimeout(c)};if(e.socket)a(e.socket);else e.on("socket",a)};if(n<2000)return s(0),0;return l.setTimeout(s.bind(null,j),j)},ce=(e,o,n=0,s,r)=>{if(n)return l.setTimeout(()=>{let c=`@smithy/node-http-handler - [${s?"ERROR":"WARN"}] a request has exceeded the configured ${n} ms requestTimeout.`;if(s){let a=Object.assign(Error(c),{name:"TimeoutError",code:"ETIMEDOUT"});e.destroy(a),o(a)}else c+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",r?.warn?.(c)},n);return-1},ae=3000,ue=(e,{keepAlive:o,keepAliveMsecs:n},s=ae)=>{if(o!==!0)return-1;let r=()=>{if(e.socket)e.socket.setKeepAlive(o,n||0);else e.on("socket",(c)=>{c.setKeepAlive(o,n||0)})};if(s===0)return r(),0;return l.setTimeout(r,s)},W=3000,fe=(e,o,n=0)=>{let s=(r)=>{let c=n-r,a=()=>{e.destroy(),o(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${n} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(e.socket)e.socket.setTimeout(c,a),e.on("close",()=>e.socket?.removeListener("timeout",a));else e.setTimeout(c,a)};if(0<n&&n<6000)return s(0),0;return l.setTimeout(s.bind(null,n===0?0:W),W)},z=6000;async function Z(e,o,n=z,s=!1){let r=o.headers,c=r?r.Expect||r.expect:void 0,a=-1,u=!0;if(!s&&c==="100-continue")u=await Promise.race([new Promise((f)=>{a=Number(l.setTimeout(()=>f(!0),Math.max(z,n)))}),new Promise((f)=>{e.on("continue",()=>{l.clearTimeout(a),f(!0)}),e.on("response",()=>{l.clearTimeout(a),f(!1)}),e.on("error",()=>{l.clearTimeout(a),f(!1)})})]);if(u)de(e,o.body)}function de(e,o){if(o instanceof se){o.pipe(e);return}if(o){let n=Buffer.isBuffer(o);if(n||typeof o==="string"){if(n&&o.byteLength===0)e.end();else e.end(o);return}let r=o;if(typeof r==="object"&&r.buffer&&typeof r.byteOffset==="number"&&typeof r.byteLength==="number"){e.end(Buffer.from(r.buffer,r.byteOffset,r.byteLength));return}e.end(Buffer.from(o));return}e.end()}var he=0,L=void 0,V=void 0;class U{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(e){if(typeof e?.handle==="function")return e;return new U(e)}static checkSocketUsage(e,o,n=console){let{sockets:s,requests:r,maxSockets:c}=e;if(typeof c!=="number"||c===1/0)return o;let a=15000;if(Date.now()-a<o)return o;if(s&&r)for(let u in s){if(!Q(s,u))continue;let f=s[u]?.length??0,m=r[u]?.length??0;if(f>=c&&m>=2*c)return n?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${f} and ${m} additional requests are enqueued.
|
|
3
|
+
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
|
|
4
|
+
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return o}constructor(e){this.configProvider=new Promise((o,n)=>{if(typeof e==="function")e().then((s)=>{o(this.resolveDefaultConfig(s))}).catch(n);else o(this.resolveDefaultConfig(e))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(e,{abortSignal:o,requestTimeout:n}={}){if(!this.config)this.config=await this.configProvider;let s=this.config,r=s.logger,c=e.protocol==="https:";if(!c&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((a,u)=>{let f=void 0,m=-1,g=-1,w=-1,v=-1,C=-1,_=()=>{l.clearTimeout(m),l.clearTimeout(g),l.clearTimeout(w),l.clearTimeout(v),l.clearTimeout(C)},F=async(i)=>{await f,_(),a(i)},E=async(i)=>{await f,_(),u(i)};if(o?.aborted){let i=M(o);E(i);return}let D=e.headers,H=D?(D.Expect??D.expect)==="100-continue":!1,P=c?s.httpsAgent:s.httpAgent;if(H&&!this.externalAgent)P=new(c?A.Agent:L)({keepAlive:!1,maxSockets:1/0});m=l.setTimeout(()=>{this.socketWarningTimestamp=U.checkSocketUsage(P,this.socketWarningTimestamp,r)},s.socketAcquisitionWarningTimeout??(s.requestTimeout??2000)+(s.connectionTimeout??1000));let I=e.query?J(e.query):"",b=void 0;if(e.username!=null||e.password!=null){let i=e.username??"",d=e.password??"";b=`${i}:${d}`}let k=e.path;if(I)k+=`?${I}`;if(e.fragment)k+=`#${e.fragment}`;let y=e.hostname??"";if(y[0]==="["&&y.endsWith("]"))y=e.hostname.slice(1,-1);else y=e.hostname;let S={headers:e.headers,host:y,method:e.method,path:k,port:e.port,agent:P,auth:b},T=(c?A.request:V)(S,(i)=>{let d=new G({statusCode:i.statusCode||-1,reason:i.statusMessage,headers:Y(i.headers),body:i});F({response:d})});if(T.on("error",(i)=>{if(re.includes(i.code))E(Object.assign(i,{name:"TimeoutError"}));else E(i)}),o){let i=()=>{T.destroy();let d=M(o);E(d)};if(typeof o.addEventListener==="function"){let d=o;d.addEventListener("abort",i,{once:!0}),T.once("close",()=>d.removeEventListener("abort",i))}else o.onabort=i}let R=n??s.requestTimeout;g=ie(T,E,s.connectionTimeout),w=ce(T,E,R,s.throwOnRequestTimeout,r??console),v=fe(T,E,s.socketTimeout);let h=S.agent;if(typeof h==="object"&&"keepAlive"in h)C=ue(T,{keepAlive:h.keepAlive,keepAliveMsecs:h.keepAliveMsecs});f=Z(T,e,R,this.externalAgent).catch((i)=>(_(),u(i)))})}updateHttpClientConfig(e,o){this.config=void 0,this.configProvider=this.configProvider.then((n)=>{if(e===Symbol.for("logger"))return{...n,logger:n.logger??o};return{...n,[e]:o}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(e){let{requestTimeout:o,connectionTimeout:n,socketTimeout:s,socketAcquisitionWarningTimeout:r,httpAgent:c,httpsAgent:a,throwOnRequestTimeout:u,logger:f}=e||{},m=!0,g=50;return{connectionTimeout:n,requestTimeout:o,socketTimeout:s,socketAcquisitionWarningTimeout:r,throwOnRequestTimeout:u,httpAgentProvider:async()=>{let w=p("http"),{Agent:v,request:C}=w.default??w;if(V=C,L=v,c instanceof L||typeof c?.destroy==="function")return this.externalAgent=!0,c;return new L({keepAlive:!0,maxSockets:50,...c})},httpsAgent:(()=>{if(a instanceof A.Agent||typeof a?.destroy==="function")return this.externalAgent=!0,a;return new A.Agent({keepAlive:!0,maxSockets:50,...a})})(),logger:f}}}var le=new Uint16Array(1);class N{id=le[0]++;total=0;max=0;session;refs=0;constructor(e){e.unref(),this.session=e}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.setTimeout(0),this.session.destroy()}useCount(){return this.refs}}class ee{sessions=[];maxConcurrency=0;constructor(e){this.sessions=(e??[]).map((o)=>new N(o))}poll(){let e=!1;for(let o of this.sessions){if(o.deref().destroyed){e=!0;continue}if(!this.maxConcurrency||o.useCount()<this.maxConcurrency)return o}if(e){for(let o of this.sessions)if(o.deref().destroyed)this.remove(o)}}offerLast(e){this.sessions.push(e)}remove(e){let o=this.sessions.indexOf(e);if(o>-1)this.sessions.splice(o,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(e){this.maxConcurrency=e}destroy(e){this.remove(e),e.destroy()}}class te{config;connectOptions;connectionPools=new Map;constructor(e){if(this.config=e,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(e,o){let n=this.getUrlString(e),s=this.getPool(n);if(!this.config.disableConcurrency&&!o.isEventStream){let f=s.poll();if(f)return f.retain(),f}let r=new N(this.connect(n)),c=r.deref();if(this.config.maxConcurrency)c.settings({maxConcurrentStreams:this.config.maxConcurrency},(f)=>{if(f)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+e.destination.toString())});let a=()=>{this.removeFromPoolAndClose(n,r)},u=()=>{this.removeFromPoolAndCheckedDestroy(n,r)};if(c.on("goaway",a),c.on("error",u),c.on("frameError",u),c.on("close",u),o.requestTimeout)c.setTimeout(o.requestTimeout,u);return s.offerLast(r),r.retain(),r}release(e,o){o.free()}createIsolatedSession(e,o){let n=this.getUrlString(e),s=new N(this.connect(n)),r=s.deref();r.settings({maxConcurrentStreams:1});let c=()=>{s.destroy()};r.on("error",c),r.on("frameError",c),r.on("close",c);let a=o.requestTimeout??300000;return r.setTimeout(a,c),s.retain(),s}destroy(){for(let[e,o]of this.connectionPools){for(let n of[...o])n.destroy();this.connectionPools.delete(e)}}setMaxConcurrentStreams(e){if(e&&e<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=e;for(let o of this.connectionPools.values())o.setMaxConcurrency(e)}setDisableConcurrentStreams(e){this.config.disableConcurrency=e}setNodeHttp2ConnectOptions(e){this.connectOptions=e}debug(){let e={};for(let[o,n]of this.connectionPools){let s=[];for(let r of n)s.push({id:r.id,active:r.useCount(),maxConcurrent:r.max,totalRequests:r.total});e[o]={sessions:s}}return e}removeFromPoolAndClose(e,o){this.connectionPools.get(e)?.remove(o),o.close()}removeFromPoolAndCheckedDestroy(e,o){this.connectionPools.get(e)?.remove(o),o.destroy()}getPool(e){if(!this.connectionPools.has(e)){let o=new ee;if(this.config.maxConcurrency)o.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(e,o)}return this.connectionPools.get(e)}getUrlString(e){return e.destination.toString()}connect(e){return this.connectOptions===void 0?O.connect(e):O.connect(e,this.connectOptions)}}var{constants:K}=O;class q{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new te({});static create(e){if(typeof e?.handle==="function")return e;return new q(e)}constructor(e){this.configProvider=new Promise((o,n)=>{if(typeof e==="function")e().then((s)=>{o(s||{})}).catch(n);else o(e||{})})}destroy(){this.connectionManager.destroy()}async handle(e,{abortSignal:o,requestTimeout:n,isEventStream:s}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:f,maxConcurrentStreams:m,nodeHttp2ConnectOptions:g}=this.config;if(this.connectionManager.setDisableConcurrentStreams(f??!1),m)this.connectionManager.setMaxConcurrentStreams(m);if(g)this.connectionManager.setNodeHttp2ConnectOptions(g)}let{requestTimeout:r,disableConcurrentStreams:c}=this.config,a=c||s,u=n??r;return new Promise((f,m)=>{let g=!1,w=void 0,v=async(i)=>{await w,f(i)},C=async(i)=>{await w,m(i)};if(o?.aborted){g=!0;let i=M(o);C(i);return}let{hostname:_,method:F,port:E,protocol:D,query:H}=e,P="";if(e.username!=null||e.password!=null){let i=e.username??"",d=e.password??"";P=`${i}:${d}@`}let I=`${D}//${P}${_}${E?`:${E}`:""}`,b={destination:new URL(I)},k={requestTimeout:this.config?.sessionTimeout,isEventStream:s},y=a?this.connectionManager.createIsolatedSession(b,k):this.connectionManager.lease(b,k),S=y.deref(),x=(i)=>{if(a)y.destroy();g=!0,C(i)},T=H?J(H):"",R=e.path;if(T)R+=`?${T}`;if(e.fragment)R+=`#${e.fragment}`;let h=S.request({...e.headers,[K.HTTP2_HEADER_PATH]:R,[K.HTTP2_HEADER_METHOD]:F});if(u)h.setTimeout(u,()=>{h.close();let i=Error(`Stream timed out because of no activity for ${u} ms`);i.name="TimeoutError",x(i)});if(o){let i=()=>{h.close();let d=M(o);x(d)};if(typeof o.addEventListener==="function"){let d=o;d.addEventListener("abort",i,{once:!0}),h.once("close",()=>d.removeEventListener("abort",i))}else o.onabort=i}h.on("frameError",(i,d,oe)=>{x(Error(`Frame type id ${i} in stream id ${oe} has failed with code ${d}.`))}),h.on("error",x),h.on("aborted",()=>{x(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${h.rstCode}.`))}),h.on("response",(i)=>{let d=new G({statusCode:i[":status"]??-1,headers:Y(i),body:h});if(g=!0,v({response:d}),a)S.close(),h.on("end",()=>{y.destroy()})}),h.on("close",()=>{if(a)y.destroy();else this.connectionManager.release(b,y);if(!g){let i=Error("Unexpected error: http2 request did not get a response");if(S.destroyed)i.name="TimeoutError";x(i)}}),w=Z(h,e,u)})}updateHttpClientConfig(e,o){this.config=void 0,this.configProvider=this.configProvider.then((n)=>({...n,[e]:o}))}httpHandlerConfigs(){return this.config??{}}}me.DEFAULT_REQUEST_TIMEOUT=he;me.NodeHttp2Handler=q;me.NodeHttpHandler=U});
|
|
5
|
+
export{Fe};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function xr(i){let e=i.filter((n)=>n!==void 0);if(e.length===0)return{cleanup:()=>{}};if(e.length===1)return{signal:e[0],cleanup:()=>{}};let r=new AbortController,o=[],s=(n)=>{if(!r.signal.aborted)r.abort(n.reason)};for(let n of e){if(n.aborted){s(n);break}let t=()=>s(n);n.addEventListener("abort",t,{once:!0}),o.push({signal:n,listener:t})}return{signal:r.signal,cleanup:()=>{for(let{signal:n,listener:t}of o)n.removeEventListener("abort",t)}}}
|
|
3
|
+
export{xr};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function n(t,r,o,i,s){if(i==="m")throw TypeError("Private method is not writable");if(i==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof r==="function"?t!==r||!s:!r.has(t))throw TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(t,o):s?s.value=o:r.set(t,o),o}function e(t,r,o,i){if(o==="a"&&!i)throw TypeError("Private accessor was defined without a getter");if(typeof r==="function"?t!==r||!i:!r.has(t))throw TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?i:o==="a"?i.call(t):i?i.value:r.get(t)}function He(t){return typeof t==="object"&&t!==null&&(("name"in t)&&t.name==="AbortError"||("message"in t)&&String(t.message).includes("FetchRequestCanceledException"))}var Ot=(t)=>{if(t instanceof Error)return t;if(typeof t==="object"&&t!==null){try{let r=Object.prototype.toString.call(t);if(r==="[object Error]"||r==="[object DOMException]"){let o=Error(t.message,t.cause?{cause:t.cause}:{});if(t.stack)o.stack=t.stack;if(t.cause&&!o.cause)o.cause=t.cause;if(t.name)o.name=t.name;return o}}catch{}try{return Error(JSON.stringify(t))}catch{}}return Error(t)};var c=(()=>{class t extends Error{}return t})();class Z extends c{constructor(t,r,o,i,s){super(`${Z.makeMessage(t,r,o)}`);this.status=t,this.headers=i,this.requestID=i?.get("request-id"),this.workspaceID=i?.get("anthropic-workspace-id"),this.error=r,this.type=s??null}static makeMessage(t,r,o){let i=r?.message?typeof r.message==="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):o;if(t&&i)return`${t} ${i}`;if(t)return`${t} status code (no body)`;if(i)return i;return"(no status code or body)"}static generate(t,r,o,i){if(!t||!i)return new xt({message:o,cause:Ot(r)});let s=r,u=s?.error?.type;if(t===400)return new hn(t,s,o,i,u);if(t===401)return new fn(t,s,o,i,u);if(t===403)return new gn(t,s,o,i,u);if(t===404)return new yn(t,s,o,i,u);if(t===409)return new bn(t,s,o,i,u);if(t===422)return new Sn(t,s,o,i,u);if(t===429)return new xn(t,s,o,i,u);if(t>=500)return new wn(t,s,o,i,u);return new Z(t,s,o,i,u)}}class Ae extends Z{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class xt extends Z{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0);if(r)this.cause=r}}class mn extends xt{constructor({message:t}={}){super({message:t??"Request timed out."})}}class yo extends c{constructor(t,{cause:r}={}){super(t??"Retryable error.");if(r!==void 0)this.cause=r}}class hn extends Z{}class fn extends Z{}class gn extends Z{}class yn extends Z{}class bn extends Z{}class Sn extends Z{}class xn extends Z{}class wn extends Z{}var b=/^[a-z][a-z0-9+.-]*:/i,ti=(t)=>b.test(t),xe=(t)=>(xe=Array.isArray,xe(t)),bo=xe;function Tr(t){if(typeof t!=="object")return{};return t??{}}function So(t){if(!t)return!0;for(let r in t)return!1;return!0}function l(t,r){return Object.prototype.hasOwnProperty.call(t,r)}function xo(t){return t!=null&&typeof t==="object"&&!Array.isArray(t)}var vn=(t,r)=>{if(typeof r!=="number"||!Number.isInteger(r))throw new c(`${t} must be an integer`);if(r<0)throw new c(`${t} must be a positive integer`);return r};var An=(t)=>{try{return JSON.parse(t)}catch(r){return}};function wt(t){}var k=(t)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0;return};function ri(t){let r=0;for(let s of t)r+=s.length;let o=new Uint8Array(r),i=0;for(let s of t)o.set(s,i),i+=s.length;return o}var y;function Nt(t){let r;return(y??(r=new globalThis.TextEncoder,y=r.encode.bind(r)))(t)}var w;function vt(t){let r;return(w??(r=new globalThis.TextDecoder,w=r.decode.bind(r)))(t)}var kr="warn",a={off:0,error:200,warn:300,info:400,debug:500},En=(t,r,o)=>{if(!t)return;if(l(a,t))return t;o.warn(`${r} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(a))}`);return};function f(){}function p(t,r,o){if(!r||a[t]>a[o])return f;else return r[t].bind(r)}var O={error:f,warn:f,info:f,debug:f},h=new WeakMap;function x(t,r){let o=h.get(t);if(o&&o[0]===r)return o[1];let i={error:p("error",t,r),warn:p("warn",t,r),info:p("info",t,r),debug:p("debug",t,r)};return h.set(t,[r,i]),i}function T(t){let r=t.logger,o=t.logLevel??"off";if(!r)return O;return x(r,o)}var m,d;function ni(){let t=k("ANTHROPIC_LOG");if(!d||t!==m)m=t,d=x(console,En(t,"process.env['ANTHROPIC_LOG']",x(console,kr))??kr);return d}function Xe(t,r,o){if(t.debug===f)return;t.debug(r,L(o))}var L=(t)=>{if(t.options)t.options={...t.options},delete t.options.headers;if(t.headers)t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([r,o])=>[r,r.toLowerCase()==="authorization"||r.toLowerCase()==="api-key"||r.toLowerCase()==="x-api-key"||r.toLowerCase()==="cookie"||r.toLowerCase()==="set-cookie"?"***":o]));if("retryOfRequestLogID"in t){if(t.retryOfRequestLogID)t.retryOf=t.retryOfRequestLogID;delete t.retryOfRequestLogID}return t};function le(t,r){return t instanceof Z&&t.status===r}function R(t){return t instanceof Z&&typeof t.status==="number"&&t.status>=400&&t.status<500}function Dt(t){return R(t)&&!le(t,408)&&!le(t,409)&&!le(t,429)}function _n(t,r,o){return Math.min(r*2**t,o)}function oi(t,r){return t+Math.random()*(r-t)}function Pn(t){return t*(1-Math.random()*0.25)}var E=(()=>{class t extends Error{constructor(r){let o=typeof r==="string"?r:r.map((i)=>{if(i.type==="text")return i.text;return`[${i.type}]`}).join(" ");super(o);this.name="ToolError",this.content=r}}return t})();var wo=15000,g=5000;function Rr(t,r){if(!(t>=g))throw new c(`${r} must be at least ${g}ms (got ${t}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`)}function Ut(){let t,r;return{promise:new Promise((i,s)=>{t=i,r=s}),resolve:t,reject:r}}
|
|
3
|
+
export{n,e,He,Ot,c,Z,Ae,xt,mn,yo,hn,fn,gn,yn,bn,Sn,xn,wn,ti,xe,bo,Tr,So,xo,vn,An,wt,k,ri,Nt,vt,kr,En,T,ni,Xe,le,Dt,_n,oi,Pn,E,wo,Rr,Ut};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{L}from"./chunk-0hbjv3y6.js";import{b}from"./chunk-k7w7ac9q.js";import{i}from"./chunk-qnr1f5pj.js";var u=i(b());var B=i(b());var p=i(L()),d=i(b());var P=i(L()),f=i(b()),S=(e,t,r)=>{let o={EcsContainer:async(s)=>{let{fromHttp:a}=await import("./chunk-rv06x0kn.js"),{fromContainerMetadata:n}=await import("./chunk-32at88hc.js");return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>f.chain(a(s??{}),n(s))().then(m)},Ec2InstanceMetadata:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:a}=await import("./chunk-32at88hc.js");return async()=>a(s)().then(m)},Environment:async(s)=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:a}=await import("./chunk-58vz2qsq.js");return async()=>a(s)().then(m)}};if(e in o)return o[e];else throw new f.CredentialsProviderError(`Unsupported credential source in profile ${t}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},m=(e)=>P.setCredentialFeature(e,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p");var I=(e,{profile:t="default",logger:r}={})=>Boolean(e)&&typeof e==="object"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1&&["undefined","string"].indexOf(typeof e.external_id)>-1&&["undefined","string"].indexOf(typeof e.mfa_serial)>-1&&(q(e,{profile:t,logger:r})||H(e,{profile:t,logger:r})),q=(e,{profile:t,logger:r})=>{let o=typeof e.source_profile==="string"&&typeof e.credential_source>"u";if(o)r?.debug?.(` ${t} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`);return o},H=(e,{profile:t,logger:r})=>{let o=typeof e.credential_source==="string"&&typeof e.source_profile>"u";if(o)r?.debug?.(` ${t} isCredentialSourceProfile credential_source=${e.credential_source}`);return o},R=async(e,t,r,o,s={},a)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let n=t[e],{source_profile:c,region:K}=n;if(!r.roleAssumer){let{getDefaultRoleAssumer:l}=await import("./chunk-wx7kdf0b.js");r.roleAssumer=l({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...o,...r?.parentClientConfig,region:K??r?.parentClientConfig?.region??o?.region}},r.clientPlugins)}if(c&&c in s)throw new d.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${d.getProfileName(r)}. Profiles visited: `+Object.keys(s).join(", "),{logger:r.logger});r.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${c?`source_profile=[${c}]`:`profile=[${e}]`}`);let E=c?a(c,t,r,o,{...s,[c]:!0},v(t[c]??{})):(await S(n.credential_source,e,r.logger)(r))();if(v(n))return E.then((l)=>p.setCredentialFeature(l,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));else{let l={RoleArn:n.role_arn,RoleSessionName:n.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:n.external_id,DurationSeconds:parseInt(n.duration_seconds||"3600",10)},{mfa_serial:_}=n;if(_){if(!r.mfaCodeProvider)throw new d.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});l.SerialNumber=_,l.TokenCode=await r.mfaCodeProvider(_)}let G=await E;return r.roleAssumer(G,l).then((U)=>p.setCredentialFeature(U,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},v=(e)=>!e.role_arn&&!!e.credential_source;var A=i(L()),O=(e)=>Boolean(e&&e.login_session),x=async(e,t,r)=>{let{fromLoginCredentials:o}=await import("./chunk-agntrqs9.js"),s=await o({...t,profile:e})({callerClientConfig:r});return A.setCredentialFeature(s,"CREDENTIALS_PROFILE_LOGIN","AC")};var k=i(L()),F=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.credential_process==="string",h=async(e,t)=>{let{fromProcess:r}=await import("./chunk-a6r4z44b.js"),o=await r({...e,profile:t})();return k.setCredentialFeature(o,"CREDENTIALS_PROFILE_PROCESS","v")};var C=i(L()),D=async(e,t,r={},o)=>{let{fromSSO:s}=await import("./chunk-501zkf9b.js");return s({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then((a)=>{if(t.sso_session)return C.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO","r");else return C.setCredentialFeature(a,"CREDENTIALS_PROFILE_SSO_LEGACY","t")})},T=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var W=i(L()),y=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.aws_access_key_id==="string"&&typeof e.aws_secret_access_key==="string"&&["undefined","string"].indexOf(typeof e.aws_session_token)>-1&&["undefined","string"].indexOf(typeof e.aws_account_id)>-1,g=async(e,t)=>{t?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let r={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return W.setCredentialFeature(r,"CREDENTIALS_PROFILE","n")};var N=i(L()),j=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.web_identity_token_file==="string"&&typeof e.role_arn==="string"&&["undefined","string"].indexOf(typeof e.role_session_name)>-1,M=async(e,t,r)=>{let{fromTokenFile:o}=await import("./chunk-0szjy61m.js"),s=await o({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:t.roleAssumerWithWebIdentity,logger:t.logger,parentClientConfig:t.parentClientConfig})({callerClientConfig:r});return N.setCredentialFeature(s,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")};var w=async(e,t,r,o,s={},a=!1)=>{let n=t[e];if(Object.keys(s).length>0&&y(n))return g(n,r);if(a||I(n,{profile:e,logger:r.logger}))return R(e,t,r,o,s,w);if(y(n))return g(n,r);if(j(n))return M(n,r,o);if(F(n))return h(r,e);if(T(n))return await D(e,n,r,o);if(O(n))return x(e,r,o);throw new B.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:r.logger})};var V=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let r=await u.parseKnownFiles(e);return w(u.getProfileName({profile:e.profile??t?.profile}),r,e,t)};export{V as fromIni};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var A=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],I=["content-type","cache-control","allow"];function p(e){let r=e.path;if(!r?.startsWith("/api/")||/[\\\r\n#]/.test(r))throw Error("request path must start with /api/");let n=new URL(r,"http://basalt.internal");if(n.origin!=="http://basalt.internal"||!n.pathname.startsWith("/api/"))throw Error("request path must stay within /api/");let o=e.method??"GET";if(!A.includes(o))throw Error("Unsupported request method");if(e.body!==void 0&&(!e.body||typeof e.body!=="object"||Array.isArray(e.body)))throw Error("request body must be a JSON object");if(e.body!==void 0&&(o==="GET"||o==="HEAD"))throw Error("GET and HEAD requests cannot have a body");let s=e.timeoutMs??1e4;if(!Number.isSafeInteger(s)||s<1||s>60000)throw Error("timeoutMs must be an integer between 1 and 60000");return{url:n,method:o,timeoutMs:s}}function g(e){let r={};for(let n of I){let o=e.headers.get(n);if(o)r[n]=o.slice(0,500)}return r}async function M(e,r){let n=e.getReader();r(()=>n.cancel());let o=[],s=0,i=!1;while(!0){let t=await n.read();if(t.done)break;let d=20480-s;if(o.push(t.value.subarray(0,d)),s+=Math.min(t.value.length,d),t.value.length>d){i=!0,await n.cancel();break}}let u=new Uint8Array(s),c=0;for(let t of o)u.set(t,c),c+=t.length;return{text:new TextDecoder().decode(u,{stream:i}),truncated:i}}async function Xt(e,r,n){let{url:o,method:s,timeoutMs:i}=p(r),u=e.http;if(!u)throw Error("HTTP API is not attached; start the Basalt server first");let c=new AbortController,t=n?AbortSignal.any([n,c.signal]):c.signal;t.throwIfAborted();let d,b=()=>{d?.().catch(()=>{})},E=async()=>{let h=r.body!==void 0,a=await u.request(new Request(o.toString(),{method:s,headers:h?{"content-type":"application/json"}:void 0,body:h?JSON.stringify(r.body):void 0,signal:t}));if(t.aborted)throw await a.body?.cancel(),Error("API request cancelled");let m=a.body?await M(a.body,(T)=>{d=T}):{text:"",truncated:!1};return{status:a.status,headers:g(a),body:m.text,truncated:m.truncated}},f,l,y=new Promise((h,a)=>{if(l=()=>{a(Error("API request cancelled")),b()},t.addEventListener("abort",l,{once:!0}),t.aborted)l()}),w=new Promise((h,a)=>{f=setTimeout(()=>{a(Error(`API request timed out after ${i}ms`)),c.abort(),b()},i)});try{return await Promise.race([E(),y,w])}finally{if(clearTimeout(f),l)t.removeEventListener("abort",l)}}
|
|
3
|
+
export{Xt};
|