(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[13892],{95101:function(e,t,r){"use strict";r.d(t,{bF:function(){return i}});var n=r(4556);let s=(e,t=21)=>(r=t)=>{let n="",s=r;for(;s--;)n+=e[Math.random()*e.length|0];return n};r(60035),r(25566);var i=({prefix:e,size:t=7,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:i="-"}={})=>{let o=s(r,t);if(null==e)return o;if(r.includes(i))throw new n.RU({argument:"separator",message:`The separator "${i}" must not be part of the alphabet "${r}".`});return t=>`${e}${i}${o(t)}`};i(),Symbol.for("vercel.ai.validator");var{btoa:o,atob:a}=globalThis},4556:function(e,t,r){"use strict";r.d(t,{AX:function(){return u},A_:function(){return E},JJ:function(){return w},RU:function(){return m},e$:function(){return d}});var n,s,i,o,a="vercel.ai.error",l=Symbol.for(a),c=class e extends Error{constructor({name:e,message:t,cause:r}){super(t),this[n]=!0,this.name=e,this.cause=r}static isInstance(t){return e.hasMarker(t,a)}static hasMarker(e,t){let r=Symbol.for(t);return null!=e&&"object"==typeof e&&r in e&&"boolean"==typeof e[r]&&!0===e[r]}toJSON(){return{name:this.name,message:this.message}}};n=l;var u=c;function d(e){return null==e?"unknown error":"string"==typeof e?e:e instanceof Error?e.message:JSON.stringify(e)}Symbol.for("vercel.ai.error.AI_APICallError"),Symbol.for("vercel.ai.error.AI_EmptyResponseBodyError");var f="AI_InvalidArgumentError",h=`vercel.ai.error.${f}`,p=Symbol.for(h),m=class extends u{constructor({message:e,cause:t,argument:r}){super({name:f,message:e,cause:t}),this[s]=!0,this.argument=r}static isInstance(e){return u.hasMarker(e,h)}};s=p,Symbol.for("vercel.ai.error.AI_InvalidPromptError"),Symbol.for("vercel.ai.error.AI_InvalidResponseDataError"),Symbol.for("vercel.ai.error.AI_JSONParseError"),Symbol.for("vercel.ai.error.AI_LoadAPIKeyError"),Symbol.for("vercel.ai.error.AI_LoadSettingError"),Symbol.for("vercel.ai.error.AI_NoContentGeneratedError");var g="AI_NoSuchModelError",y=`vercel.ai.error.${g}`,b=Symbol.for(y),w=class extends u{constructor({errorName:e=g,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[i]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return u.hasMarker(e,y)}static isNoSuchModelError(e){return e instanceof Error&&e.name===g&&"string"==typeof e.modelId&&"string"==typeof e.modelType}toJSON(){return{name:this.name,message:this.message,stack:this.stack,modelId:this.modelId,modelType:this.modelType}}};i=b,Symbol.for("vercel.ai.error.AI_TooManyEmbeddingValuesForCallError"),Symbol.for("vercel.ai.error.AI_TypeValidationError");var v="AI_UnsupportedFunctionalityError",_=`vercel.ai.error.${v}`,S=Symbol.for(_),E=class extends u{constructor({functionality:e}){super({name:v,message:`'${e}' functionality not supported.`}),this[o]=!0,this.functionality=e}static isInstance(e){return u.hasMarker(e,_)}static isUnsupportedFunctionalityError(e){return e instanceof Error&&e.name===v&&"string"==typeof e.functionality}toJSON(){return{name:this.name,message:this.message,stack:this.stack,functionality:this.functionality}}};o=S},91018:function(e,t,r){"use strict";r.d(t,{vl:function(){return v}}),r(60035),Symbol("Let zodToJsonSchema decide on which parser to use");let n=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};var s={code:"0",name:"text",parse:e=>{if("string"!=typeof e)throw Error('"text" parts expect a string value.');return{type:"text",value:e}}},i={code:"1",name:"function_call",parse:e=>{if(null==e||"object"!=typeof e||!("function_call"in e)||"object"!=typeof e.function_call||null==e.function_call||!("name"in e.function_call)||!("arguments"in e.function_call)||"string"!=typeof e.function_call.name||"string"!=typeof e.function_call.arguments)throw Error('"function_call" parts expect an object with a "function_call" property.');return{type:"function_call",value:e}}},o={code:"2",name:"data",parse:e=>{if(!Array.isArray(e))throw Error('"data" parts expect an array value.');return{type:"data",value:e}}},a={code:"3",name:"error",parse:e=>{if("string"!=typeof e)throw Error('"error" parts expect a string value.');return{type:"error",value:e}}},l={code:"4",name:"assistant_message",parse:e=>{if(null==e||"object"!=typeof e||!("id"in e)||!("role"in e)||!("content"in e)||"string"!=typeof e.id||"string"!=typeof e.role||"assistant"!==e.role||!Array.isArray(e.content)||!e.content.every(e=>null!=e&&"object"==typeof e&&"type"in e&&"text"===e.type&&"text"in e&&null!=e.text&&"object"==typeof e.text&&"value"in e.text&&"string"==typeof e.text.value))throw Error('"assistant_message" parts expect an object with an "id", "role", and "content" property.');return{type:"assistant_message",value:e}}},c={code:"5",name:"assistant_control_data",parse:e=>{if(null==e||"object"!=typeof e||!("threadId"in e)||!("messageId"in e)||"string"!=typeof e.threadId||"string"!=typeof e.messageId)throw Error('"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.');return{type:"assistant_control_data",value:{threadId:e.threadId,messageId:e.messageId}}}},u={code:"6",name:"data_message",parse:e=>{if(null==e||"object"!=typeof e||!("role"in e)||!("data"in e)||"string"!=typeof e.role||"data"!==e.role)throw Error('"data_message" parts expect an object with a "role" and "data" property.');return{type:"data_message",value:e}}},d={code:"7",name:"tool_calls",parse:e=>{if(null==e||"object"!=typeof e||!("tool_calls"in e)||"object"!=typeof e.tool_calls||null==e.tool_calls||!Array.isArray(e.tool_calls)||e.tool_calls.some(e=>null==e||"object"!=typeof e||!("id"in e)||"string"!=typeof e.id||!("type"in e)||"string"!=typeof e.type||!("function"in e)||null==e.function||"object"!=typeof e.function||!("arguments"in e.function)||"string"!=typeof e.function.name||"string"!=typeof e.function.arguments))throw Error('"tool_calls" parts expect an object with a ToolCallPayload.');return{type:"tool_calls",value:e}}},f={code:"8",name:"message_annotations",parse:e=>{if(!Array.isArray(e))throw Error('"message_annotations" parts expect an array value.');return{type:"message_annotations",value:e}}},h={code:"9",name:"tool_call",parse:e=>{if(null==e||"object"!=typeof e||!("toolCallId"in e)||"string"!=typeof e.toolCallId||!("toolName"in e)||"string"!=typeof e.toolName||!("args"in e)||"object"!=typeof e.args)throw Error('"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.');return{type:"tool_call",value:e}}},p={code:"a",name:"tool_result",parse:e=>{if(null==e||"object"!=typeof e||!("toolCallId"in e)||"string"!=typeof e.toolCallId||!("result"in e))throw Error('"tool_result" parts expect an object with a "toolCallId" and a "result" property.');return{type:"tool_result",value:e}}},m={code:"b",name:"tool_call_streaming_start",parse:e=>{if(null==e||"object"!=typeof e||!("toolCallId"in e)||"string"!=typeof e.toolCallId||!("toolName"in e)||"string"!=typeof e.toolName)throw Error('"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.');return{type:"tool_call_streaming_start",value:e}}},g={code:"c",name:"tool_call_delta",parse:e=>{if(null==e||"object"!=typeof e||!("toolCallId"in e)||"string"!=typeof e.toolCallId||!("argsTextDelta"in e)||"string"!=typeof e.argsTextDelta)throw Error('"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.');return{type:"tool_call_delta",value:e}}},y={code:"d",name:"finish_message",parse:e=>{if(null==e||"object"!=typeof e||!("finishReason"in e)||"string"!=typeof e.finishReason)throw Error('"finish_message" parts expect an object with a "finishReason" property.');let t={finishReason:e.finishReason};return"usage"in e&&null!=e.usage&&"object"==typeof e.usage&&"promptTokens"in e.usage&&"completionTokens"in e.usage&&(t.usage={promptTokens:"number"==typeof e.usage.promptTokens?e.usage.promptTokens:Number.NaN,completionTokens:"number"==typeof e.usage.completionTokens?e.usage.completionTokens:Number.NaN}),{type:"finish_message",value:t}}},b={code:"e",name:"finish_step",parse:e=>{if(null==e||"object"!=typeof e||!("finishReason"in e)||"string"!=typeof e.finishReason)throw Error('"finish_step" parts expect an object with a "finishReason" property.');let t={finishReason:e.finishReason,isContinued:!1};return"usage"in e&&null!=e.usage&&"object"==typeof e.usage&&"promptTokens"in e.usage&&"completionTokens"in e.usage&&(t.usage={promptTokens:"number"==typeof e.usage.promptTokens?e.usage.promptTokens:Number.NaN,completionTokens:"number"==typeof e.usage.completionTokens?e.usage.completionTokens:Number.NaN}),"isContinued"in e&&"boolean"==typeof e.isContinued&&(t.isContinued=e.isContinued),{type:"finish_step",value:t}}},w=[s,i,o,a,l,c,u,d,f,h,p,m,g,y,b];function v(e,t){let r=w.find(t=>t.name===e);if(!r)throw Error(`Invalid stream part type: ${e}`);return`${r.code}:${JSON.stringify(t)}
`}s.code,i.code,o.code,a.code,l.code,c.code,u.code,d.code,f.code,h.code,p.code,m.code,g.code,y.code,b.code,s.name,s.code,i.name,i.code,o.name,o.code,a.name,a.code,l.name,l.code,c.name,c.code,u.name,u.code,d.name,d.code,f.name,f.code,h.name,h.code,p.name,p.code,m.name,m.code,g.name,g.code,y.name,y.code,b.name,b.code,w.map(e=>e.code),Symbol.for("vercel.ai.schema")},4346:function(e,t,r){"use strict";let n,s,i,o,a,l;r.d(t,{$B:function(){return i},Pz:function(){return o},Rz:function(){return l},YR:function(){return u},he:function(){return s},pF:function(){return n},us:function(){return a}});let c=!1;function u(e,t={auto:!1}){if(c)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${e.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(n)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${e.kind}'\` after \`import '@anthropic-ai/sdk/shims/${n}'\``);c=t.auto,n=e.kind,s=e.fetch,e.Request,e.Response,e.Headers,e.FormData,e.Blob,i=e.File,o=e.ReadableStream,e.getMultipartRequestOptions,a=e.getDefaultAgent,l=e.fileFromPath,e.isFsReadStream}},97735:function(e,t,r){"use strict";r.d(t,{O:function(){return s}});class n{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function s({manuallyImported:e}={}){let t,r,s,i;let o=e?"You may need to use polyfills":`Add one of these imports before your first \`import … from '@anthropic-ai/sdk'\`:
- \`import '@anthropic-ai/sdk/shims/node'\` (if you're running on Node)
- \`import '@anthropic-ai/sdk/shims/web'\` (otherwise)
`;try{t=fetch,r=Request,s=Response,i=Headers}catch(e){throw Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${o}`)}return{kind:"web",fetch:t,Request:r,Response:s,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${o}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${o}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${o}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${o}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new n(e)}),getDefaultAgent:e=>void 0,fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:e=>!1}}},54076:function(e,t,r){"use strict";let n;r.d(t,{ZP:function(){return tD}});var s,i,o,a,l,c,u,d,f,h,p,m,g,y,b,w,v,_,S,E,A,x,R,O,k,P,C,I,T,M,$,N,j,U,D,L,q,F,B,H,W,z,K,V,J,G={};r.r(G),r.d(G,{APIConnectionError:function(){return eX},APIConnectionTimeoutError:function(){return eY},APIError:function(){return eG},APIUserAbortError:function(){return eZ},AnthropicError:function(){return eJ},AuthenticationError:function(){return e0},BadRequestError:function(){return eQ},ConflictError:function(){return e3},InternalServerError:function(){return e5},NotFoundError:function(){return e2},PermissionDeniedError:function(){return e1},RateLimitError:function(){return e6},UnprocessableEntityError:function(){return e4}});let Z="0.30.1";var X=r(4346),Y=r(97735);X.pF||X.YR(Y.O(),{auto:!0});var Q=r(9109).Buffer;class ee{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];let r=ee.NEWLINE_CHARS.has(t[t.length-1]||""),n=t.split(ee.NEWLINE_REGEXP);return(r&&n.pop(),1!==n.length||r)?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),r||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if(void 0!==Q){if(e instanceof Q)return e.toString();if(e instanceof Uint8Array)return Q.from(e).toString();throw new eJ(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new eJ(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new eJ("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}ee.NEWLINE_CHARS=new Set(["\n","\r"]),ee.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class et{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;return new et(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(let r of er(e,t)){if("completion"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("message_start"===r.event||"message_delta"===r.event||"message_stop"===r.event||"content_block_start"===r.event||"content_block_delta"===r.event||"content_block_stop"===r.event)try{yield JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("ping"!==r.event&&"error"===r.event)throw eG.generate(void 0,`SSE Error: ${r.data}`,r.data,eR(e.headers))}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}},t)}static fromReadableStream(e,t){let r=!1;async function*n(){let t=new ee;for await(let r of ei(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new et(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(let t of n())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{e||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new et(()=>n(e),this.controller),new et(()=>n(t),this.controller)]}toReadableStream(){let e;let t=this,r=new TextEncoder;return new X.Pz({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:n,done:s}=await e.next();if(s)return t.close();let i=r.encode(JSON.stringify(n)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*er(e,t){if(!e.body)throw t.abort(),new eJ("Attempted to iterate over a response with no body");let r=new es,n=new ee;for await(let t of en(ei(e.body)))for(let e of n.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of n.flush()){let t=r.decode(e);t&&(yield t)}}async function*en(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?new TextEncoder().encode(r):r,s=new Uint8Array(t.length+n.length);for(s.set(t),s.set(n,t.length),t=s;-1!==(e=function(e){for(let t=0;t<e.length-2;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class es{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){let r=e.indexOf(":");return -1!==r?[e.substring(0,r),":",e.substring(r+t.length)]:[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}function ei(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var eo=r(9109).Buffer;let ea=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,el=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ec(e),ec=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,eu=e=>el(e)||ea(e)||isFsReadStream(e);async function ed(e,t,r){var n;if(el(e=await e))return e;if(ea(e)){let n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let s=ec(n)?[await n.arrayBuffer()]:[n];return new X.$B(s,t,r)}let s=await ef(e);if(t||(t=(eh((n=e).name)||eh(n.filename)||eh(n.path)?.split(/[\\/]/).pop())??"unknown_file"),!r?.type){let e=s[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new X.$B(s,t,r)}async function ef(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ec(e))t.push(await e.arrayBuffer());else if(ep(e))for await(let r of e)t.push(r);else throw Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){let t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`);return t}let eh=e=>"string"==typeof e?e:void 0!==eo&&e instanceof eo?String(e):void 0,ep=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],em=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],eg=e=>{if(eu(e))return!0;if(Array.isArray(e))return e.some(eg);if(e&&"object"==typeof e){for(let t in e)if(eg(e[t]))return!0}return!1};var ey=r(9109).Buffer,eb=r(25566),ew=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},ev=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function e_(e){let{response:t}=e;if(e.options.stream)return(eH("response",t.status,t.url,t.headers,t.body),e.options.__streamClass)?e.options.__streamClass.fromSSEResponse(t,e.controller):et.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let e=await t.json();return eH("response",t.status,t.url,t.headers,e),e}let n=await t.text();return eH("response",t.status,t.url,t.headers,n),n}class eS extends Promise{constructor(e,t=e_){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new eS(this.responsePromise,async t=>e(await this.parseResponse(t),t))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class eE{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=eU("maxRetries",t),this.timeout=eU("timeout",r),this.httpAgent=n,this.fetch=s??X.he}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...eT(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${eW()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(async r=>{let n=r&&ec(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if(void 0!==ey)return ey.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder)return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let{method:r,path:n,query:s,headers:i={}}=e,o=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:em(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(o),l=this.buildURL(n,s);"timeout"in e&&eU("timeout",e.timeout);let c=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??(0,X.us)(l),d=c+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let f=this.buildHeaders({options:e,headers:i,contentLength:a,retryCount:t});return{req:{method:r,...o&&{body:o},headers:f,...u&&{agent:u},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let s={};r&&(s["content-length"]=r);let i=this.defaultHeaders(e);return eB(s,i),eB(s,t),em(e.body)&&"node"!==X.pF&&delete s["content-type"],void 0===eV(i,"x-stainless-retry-count")&&void 0===eV(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,r,n){return eG.generate(e,t,r,n)}request(e,t=null){return new eS(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);let{req:s,url:i,timeout:o}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:i,options:r}),eH("request",i,r,s.headers),r.signal?.aborted)throw new eZ;let a=new AbortController,l=await this.fetchWithTimeout(i,s,o,a).catch(eD);if(l instanceof Error){if(r.signal?.aborted)throw new eZ;if(t)return this.retryRequest(r,t);if("AbortError"===l.name)throw new eY;throw new eX({cause:l})}let c=eR(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let e=`retrying, ${t} attempts remaining`;return eH(`response (error; ${e})`,l.status,i,c),this.retryRequest(r,t,c)}let e=await l.text().catch(e=>eD(e).message),n=eM(e),s=n?void 0:e,o=t?"(error; no more retries left)":"(error; not retryable)";throw eH(`response (error; ${o})`,l.status,i,c,s),this.makeStatusError(l.status,n,s,c)}return{response:l,options:r,controller:a}}requestAPIList(e,t){return new ex(this,this.makeRequest(t,null),e)}buildURL(e,t){let r=new URL(eN(e)?e:this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return eq(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new eJ(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,n){let{signal:s,...i}=t||{};s&&s.addEventListener("abort",()=>n.abort());let o=setTimeout(()=>n.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...i}).finally(()=>{clearTimeout(o)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,r){let n;let s=r?.["retry-after-ms"];if(s){let e=parseFloat(s);Number.isNaN(e)||(n=e)}let i=r?.["retry-after"];if(i&&!n){let e=parseFloat(i);n=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){let r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await ej(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Z}`}}class eA{constructor(e,t,r,n){a.set(this,void 0),ew(this,a,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new eJ("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){for(let[r,n]of[...Object.entries(t.query||{}),...e.url.searchParams.entries()])e.url.searchParams.set(r,n);t.query=void 0,t.path=e.url.toString()}return await ev(this,a,"f").requestAPIList(this.constructor,t)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(a=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class ex extends eS{constructor(e,t,r){super(t,async t=>new r(e,t.response,await e_(t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}let eR=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),eO={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},ek=e=>"object"==typeof e&&null!==e&&!eq(e)&&Object.keys(e).every(e=>eF(eO,e)),eP=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z,"X-Stainless-OS":eI(Deno.build.os),"X-Stainless-Arch":eC(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":eb.version};if("[object process]"===Object.prototype.toString.call(void 0!==eb?eb:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z,"X-Stainless-OS":eI(eb.platform),"X-Stainless-Arch":eC(eb.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":eb.version};let e=function(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,s=r[3]||0;return{browser:e,version:`${t}.${n}.${s}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},eC=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",eI=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",eT=()=>n??(n=eP()),eM=e=>{try{return JSON.parse(e)}catch(e){return}},e$=RegExp("^(?:[a-z]+:)?//","i"),eN=e=>e$.test(e),ej=e=>new Promise(t=>setTimeout(t,e)),eU=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new eJ(`${e} must be an integer`);if(t<0)throw new eJ(`${e} must be a positive integer`);return t},eD=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return Error(JSON.stringify(e))}catch{}return Error(String(e))},eL=e=>void 0!==eb?eb.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function eq(e){if(!e)return!0;for(let t in e)return!1;return!0}function eF(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function eB(e,t){for(let r in t){if(!eF(t,r))continue;let n=r.toLowerCase();if(!n)continue;let s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}function eH(e,...t){void 0!==eb&&eb?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${e}`,...t)}let eW=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),ez=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,eK=e=>"function"==typeof e?.get,eV=(e,t)=>{let r=t.toLowerCase();if(eK(e)){let n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,r)=>t+r.toUpperCase());for(let s of[t,r,t.toUpperCase(),n]){let t=e.get(s);if(t)return t}}for(let[n,s]of Object.entries(e))if(n.toLowerCase()===r){if(Array.isArray(s)){if(s.length<=1)return s[0];return console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]}return s}};class eJ extends Error{}class eG extends eJ{constructor(e,t,r,n){super(`${eG.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,r){let n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){return e?400===e?new eQ(e,t,r,n):401===e?new e0(e,t,r,n):403===e?new e1(e,t,r,n):404===e?new e2(e,t,r,n):409===e?new e3(e,t,r,n):422===e?new e4(e,t,r,n):429===e?new e6(e,t,r,n):e>=500?new e5(e,t,r,n):new eG(e,t,r,n):new eX({message:r,cause:eD(t)})}}class eZ extends eG{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class eX extends eG{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class eY extends eX{constructor({message:e}={}){super({message:e??"Request timed out."})}}class eQ extends eG{constructor(){super(...arguments),this.status=400}}class e0 extends eG{constructor(){super(...arguments),this.status=401}}class e1 extends eG{constructor(){super(...arguments),this.status=403}}class e2 extends eG{constructor(){super(...arguments),this.status=404}}class e3 extends eG{constructor(){super(...arguments),this.status=409}}class e4 extends eG{constructor(){super(...arguments),this.status=422}}class e6 extends eG{constructor(){super(...arguments),this.status=429}}class e5 extends eG{}class e8 extends eA{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let e=this.first_id;return e?{params:{before_id:e}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}}class e9{constructor(e){this._client=e}}class e7 extends e9{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}}e7||(e7={});let te=e=>{let t=0,r=[];for(;t<e.length;){let n=e[t];if("\\"===n){t++;continue}if("{"===n){r.push({type:"brace",value:"{"}),t++;continue}if("}"===n){r.push({type:"brace",value:"}"}),t++;continue}if("["===n){r.push({type:"paren",value:"["}),t++;continue}if("]"===n){r.push({type:"paren",value:"]"}),t++;continue}if(":"===n){r.push({type:"separator",value:":"}),t++;continue}if(","===n){r.push({type:"delimiter",value:","}),t++;continue}if('"'===n){let s="",i=!1;for(n=e[++t];'"'!==n;){if(t===e.length){i=!0;break}if("\\"===n){if(++t===e.length){i=!0;break}s+=n+e[t],n=e[++t]}else s+=n,n=e[++t]}n=e[++t],i||r.push({type:"string",value:s});continue}let s=/\s/;if(n&&s.test(n)){t++;continue}let i=/[0-9]/;if(n&&i.test(n)||"-"===n||"."===n){let s="";for("-"===n&&(s+=n,n=e[++t]);n&&i.test(n)||"."===n;)s+=n,n=e[++t];r.push({type:"number",value:s});continue}let o=/[a-z]/i;if(n&&o.test(n)){let s="";for(;n&&o.test(n)&&t!==e.length;)s+=n,n=e[++t];"true"==s||"false"==s||"null"===s?r.push({type:"name",value:s}):t++;continue}t++}return r},tt=e=>{if(0===e.length)return e;let t=e[e.length-1];switch(t.type){case"separator":return tt(e=e.slice(0,e.length-1));case"number":let r=t.value[t.value.length-1];if("."===r||"-"===r)return tt(e=e.slice(0,e.length-1));case"string":let n=e[e.length-2];if(n?.type==="delimiter"||n?.type==="brace"&&"{"===n.value)return tt(e=e.slice(0,e.length-1));break;case"delimiter":return tt(e=e.slice(0,e.length-1))}return e},tr=e=>{let t=[];return e.map(e=>{"brace"===e.type&&("{"===e.value?t.push("}"):t.splice(t.lastIndexOf("}"),1)),"paren"===e.type&&("["===e.value?t.push("]"):t.splice(t.lastIndexOf("]"),1))}),t.length>0&&t.reverse().map(t=>{"}"===t?e.push({type:"brace",value:"}"}):"]"===t&&e.push({type:"paren",value:"]"})}),e},tn=e=>{let t="";return e.map(e=>{"string"===e.type?t+='"'+e.value+'"':t+=e.value}),t},ts=e=>JSON.parse(tn(tr(tt(te(e)))));var ti=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},to=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};let ta="__json_buf";class tl{constructor(){l.add(this),this.messages=[],this.receivedMessages=[],c.set(this,void 0),this.controller=new AbortController,u.set(this,void 0),d.set(this,()=>{}),f.set(this,()=>{}),h.set(this,void 0),p.set(this,()=>{}),m.set(this,()=>{}),g.set(this,{}),y.set(this,!1),b.set(this,!1),w.set(this,!1),v.set(this,!1),E.set(this,e=>{if(ti(this,b,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eZ),e instanceof eZ)return ti(this,w,!0,"f"),this._emit("abort",e);if(e instanceof eJ)return this._emit("error",e);if(e instanceof Error){let t=new eJ(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eJ(String(e)))}),ti(this,u,new Promise((e,t)=>{ti(this,d,e,"f"),ti(this,f,t,"f")}),"f"),ti(this,h,new Promise((e,t)=>{ti(this,p,e,"f"),ti(this,m,t,"f")}),"f"),to(this,u,"f").catch(()=>{}),to(this,h,"f").catch(()=>{})}static fromReadableStream(e){let t=new tl;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new tl;for(let e of t.messages)n._addMessageParam(e);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},to(this,E,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),to(this,l,"m",A).call(this);let s=await e.create({...t,stream:!0},{...r,signal:this.controller.signal});for await(let e of(this._connected(),s))to(this,l,"m",x).call(this,e);if(s.controller.signal?.aborted)throw new eZ;to(this,l,"m",R).call(this)}_connected(){this.ended||(to(this,d,"f").call(this),this._emit("connect"))}get ended(){return to(this,y,"f")}get errored(){return to(this,b,"f")}get aborted(){return to(this,w,"f")}abort(){this.controller.abort()}on(e,t){return(to(this,g,"f")[e]||(to(this,g,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=to(this,g,"f")[e];if(!r)return this;let n=r.findIndex(e=>e.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(to(this,g,"f")[e]||(to(this,g,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{ti(this,v,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){ti(this,v,!0,"f"),await to(this,h,"f")}get currentMessage(){return to(this,c,"f")}async finalMessage(){return await this.done(),to(this,l,"m",_).call(this)}async finalText(){return await this.done(),to(this,l,"m",S).call(this)}_emit(e,...t){if(to(this,y,"f"))return;"end"===e&&(ti(this,y,!0,"f"),to(this,p,"f").call(this));let r=to(this,g,"f")[e];if(r&&(to(this,g,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];to(this,v,"f")||r?.length||Promise.reject(e),to(this,f,"f").call(this,e),to(this,m,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];to(this,v,"f")||r?.length||Promise.reject(e),to(this,f,"f").call(this,e),to(this,m,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",to(this,l,"m",_).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),to(this,l,"m",A).call(this),this._connected();let n=et.fromReadableStream(e,this.controller);for await(let e of n)to(this,l,"m",x).call(this,e);if(n.controller.signal?.aborted)throw new eZ;to(this,l,"m",R).call(this)}[(c=new WeakMap,u=new WeakMap,d=new WeakMap,f=new WeakMap,h=new WeakMap,p=new WeakMap,m=new WeakMap,g=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,v=new WeakMap,E=new WeakMap,l=new WeakSet,_=function(){if(0===this.receivedMessages.length)throw new eJ("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},S=function(){if(0===this.receivedMessages.length)throw new eJ("stream ended without producing a Message with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new eJ("stream ended without producing a content block with type=text");return e.join(" ")},A=function(){this.ended||ti(this,c,void 0,"f")},x=function(e){if(this.ended)return;let t=to(this,l,"m",O).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);"text_delta"===e.delta.type&&"text"===r.type?this._emit("text",e.delta.text,r.text||""):"input_json_delta"===e.delta.type&&"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break}case"message_stop":this._addMessageParam(t),this._addMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":ti(this,c,t,"f")}},R=function(){if(this.ended)throw new eJ("stream has ended, this shouldn't happen");let e=to(this,c,"f");if(!e)throw new eJ("request ended without sending any chunks");return ti(this,c,void 0,"f"),e},O=function(e){let t=to(this,c,"f");if("message_start"===e.type){if(t)throw new eJ(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new eJ(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{let r=t.content.at(e.index);if(r?.type==="text"&&"text_delta"===e.delta.type)r.text+=e.delta.text;else if(r?.type==="tool_use"&&"input_json_delta"===e.delta.type){let t=r[ta]||"";Object.defineProperty(r,ta,{value:t+=e.delta.partial_json,enumerable:!1,writable:!0}),t&&(r.input=ts(t))}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class tc extends e9{create(e,t){return e.model in tu&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${tu[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}stream(e,t){return tl.createMessage(this,e,t)}}let tu={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024"};tc||(tc={});class td{constructor(e,t){this.iterator=e,this.controller=t}async *decoder(){let e=new ee;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new eJ("Attempted to iterate over a response with no body");return new td(ei(e.body),t)}}class tf extends e9{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(ek(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(ek(e))return this.list({},e);let{betas:r,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",th,{query:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}cancel(e,t={},r){if(ek(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(ek(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new eJ(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:s}=t;return this._client.get(n.results_url,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...r?.headers},__binaryResponse:!0})._thenUnwrap((e,t)=>td.fromResponse(t.response,t.controller))}}class th extends e8{}(tf||(tf={})).BetaMessageBatchesPage=th;class tp extends e9{constructor(){super(...arguments),this.batches=new tf(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}}(s=tp||(tp={})).Batches=tf,s.BetaMessageBatchesPage=th;var tm=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},tg=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};let ty="__json_buf";class tb{constructor(){k.add(this),this.messages=[],this.receivedMessages=[],P.set(this,void 0),this.controller=new AbortController,C.set(this,void 0),I.set(this,()=>{}),T.set(this,()=>{}),M.set(this,void 0),$.set(this,()=>{}),N.set(this,()=>{}),j.set(this,{}),U.set(this,!1),D.set(this,!1),L.set(this,!1),q.set(this,!1),H.set(this,e=>{if(tm(this,D,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new eZ),e instanceof eZ)return tm(this,L,!0,"f"),this._emit("abort",e);if(e instanceof eJ)return this._emit("error",e);if(e instanceof Error){let t=new eJ(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new eJ(String(e)))}),tm(this,C,new Promise((e,t)=>{tm(this,I,e,"f"),tm(this,T,t,"f")}),"f"),tm(this,M,new Promise((e,t)=>{tm(this,$,e,"f"),tm(this,N,t,"f")}),"f"),tg(this,C,"f").catch(()=>{}),tg(this,M,"f").catch(()=>{})}static fromReadableStream(e){let t=new tb;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new tb;for(let e of t.messages)n._addPromptCachingBetaMessageParam(e);return n._run(()=>n._createPromptCachingBetaMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},tg(this,H,"f"))}_addPromptCachingBetaMessageParam(e){this.messages.push(e)}_addPromptCachingBetaMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createPromptCachingBetaMessage(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),tg(this,k,"m",W).call(this);let s=await e.create({...t,stream:!0},{...r,signal:this.controller.signal});for await(let e of(this._connected(),s))tg(this,k,"m",z).call(this,e);if(s.controller.signal?.aborted)throw new eZ;tg(this,k,"m",K).call(this)}_connected(){this.ended||(tg(this,I,"f").call(this),this._emit("connect"))}get ended(){return tg(this,U,"f")}get errored(){return tg(this,D,"f")}get aborted(){return tg(this,L,"f")}abort(){this.controller.abort()}on(e,t){return(tg(this,j,"f")[e]||(tg(this,j,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=tg(this,j,"f")[e];if(!r)return this;let n=r.findIndex(e=>e.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(tg(this,j,"f")[e]||(tg(this,j,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{tm(this,q,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){tm(this,q,!0,"f"),await tg(this,M,"f")}get currentMessage(){return tg(this,P,"f")}async finalMessage(){return await this.done(),tg(this,k,"m",F).call(this)}async finalText(){return await this.done(),tg(this,k,"m",B).call(this)}_emit(e,...t){if(tg(this,U,"f"))return;"end"===e&&(tm(this,U,!0,"f"),tg(this,$,"f").call(this));let r=tg(this,j,"f")[e];if(r&&(tg(this,j,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];tg(this,q,"f")||r?.length||Promise.reject(e),tg(this,T,"f").call(this,e),tg(this,N,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];tg(this,q,"f")||r?.length||Promise.reject(e),tg(this,T,"f").call(this,e),tg(this,N,"f").call(this,e),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalPromptCachingBetaMessage",tg(this,k,"m",F).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),tg(this,k,"m",W).call(this),this._connected();let n=et.fromReadableStream(e,this.controller);for await(let e of n)tg(this,k,"m",z).call(this,e);if(n.controller.signal?.aborted)throw new eZ;tg(this,k,"m",K).call(this)}[(P=new WeakMap,C=new WeakMap,I=new WeakMap,T=new WeakMap,M=new WeakMap,$=new WeakMap,N=new WeakMap,j=new WeakMap,U=new WeakMap,D=new WeakMap,L=new WeakMap,q=new WeakMap,H=new WeakMap,k=new WeakSet,F=function(){if(0===this.receivedMessages.length)throw new eJ("stream ended without producing a PromptCachingBetaMessage with role=assistant");return this.receivedMessages.at(-1)},B=function(){if(0===this.receivedMessages.length)throw new eJ("stream ended without producing a PromptCachingBetaMessage with role=assistant");let e=this.receivedMessages.at(-1).content.filter(e=>"text"===e.type).map(e=>e.text);if(0===e.length)throw new eJ("stream ended without producing a content block with type=text");return e.join(" ")},W=function(){this.ended||tm(this,P,void 0,"f")},z=function(e){if(this.ended)return;let t=tg(this,k,"m",V).call(this,e);switch(this._emit("streamEvent",e,t),e.type){case"content_block_delta":{let r=t.content.at(-1);"text_delta"===e.delta.type&&"text"===r.type?this._emit("text",e.delta.text,r.text||""):"input_json_delta"===e.delta.type&&"tool_use"===r.type&&r.input&&this._emit("inputJson",e.delta.partial_json,r.input);break}case"message_stop":this._addPromptCachingBetaMessageParam(t),this._addPromptCachingBetaMessage(t,!0);break;case"content_block_stop":this._emit("contentBlock",t.content.at(-1));break;case"message_start":tm(this,P,t,"f")}},K=function(){if(this.ended)throw new eJ("stream has ended, this shouldn't happen");let e=tg(this,P,"f");if(!e)throw new eJ("request ended without sending any chunks");return tm(this,P,void 0,"f"),e},V=function(e){let t=tg(this,P,"f");if("message_start"===e.type){if(t)throw new eJ(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new eJ(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case"message_stop":case"content_block_stop":return t;case"message_delta":return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t;case"content_block_start":return t.content.push(e.content_block),t;case"content_block_delta":{let r=t.content.at(e.index);if(r?.type==="text"&&"text_delta"===e.delta.type)r.text+=e.delta.text;else if(r?.type==="tool_use"&&"input_json_delta"===e.delta.type){let t=r[ty]||"";Object.defineProperty(r,ty,{value:t+=e.delta.partial_json,enumerable:!1,writable:!0}),t&&(r.input=ts(t))}return t}}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class tw extends e9{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages?beta=prompt_caching",{body:n,timeout:this._client._options.timeout??6e5,...t,headers:{"anthropic-beta":[...r??[],"prompt-caching-2024-07-31"].toString(),...t?.headers},stream:e.stream??!1})}stream(e,t){return tb.createMessage(this,e,t)}}tw||(tw={});class tv extends e9{constructor(){super(...arguments),this.messages=new tw(this._client)}}(tv||(tv={})).Messages=tw;class t_ extends e9{constructor(){super(...arguments),this.messages=new tp(this._client),this.promptCaching=new tv(this._client)}}(i=t_||(t_={})).Messages=tp,i.PromptCaching=tv;class tS extends eE{constructor({baseURL:e=eL("ANTHROPIC_BASE_URL"),apiKey:t=eL("ANTHROPIC_API_KEY")??null,authToken:r=eL("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){let s={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!s.dangerouslyAllowBrowser&&ez())throw new eJ("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n\nTODO: link!\n");super({baseURL:s.baseURL,timeout:s.timeout??6e5,httpAgent:s.httpAgent,maxRetries:s.maxRetries,fetch:s.fetch}),this.completions=new e7(this),this.messages=new tc(this),this.beta=new t_(this),this._options=s,this.apiKey=t,this.authToken=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if((!this.apiKey||!e["x-api-key"])&&null!==t["x-api-key"]&&(!this.authToken||!e.authorization)&&null!==t.authorization)throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let t=this.apiKeyAuth(e),r=this.bearerAuth(e);return null==t||eq(t)?null==r||eq(r)?{}:r:t}apiKeyAuth(e){return null==this.apiKey?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return null==this.authToken?{}:{Authorization:`Bearer ${this.authToken}`}}}J=tS,tS.Anthropic=J,tS.HUMAN_PROMPT="\n\nHuman:",tS.AI_PROMPT="\n\nAssistant:",tS.DEFAULT_TIMEOUT=6e5,tS.AnthropicError=eJ,tS.APIError=eG,tS.APIConnectionError=eX,tS.APIConnectionTimeoutError=eY,tS.APIUserAbortError=eZ,tS.NotFoundError=e2,tS.ConflictError=e3,tS.RateLimitError=e6,tS.BadRequestError=eQ,tS.AuthenticationError=e0,tS.InternalServerError=e5,tS.PermissionDeniedError=e1,tS.UnprocessableEntityError=e4,tS.toFile=ed,tS.fileFromPath=X.Rz;let{HUMAN_PROMPT:tE,AI_PROMPT:tA}=tS,{AnthropicError:tx,APIError:tR,APIConnectionError:tO,APIConnectionTimeoutError:tk,APIUserAbortError:tP,NotFoundError:tC,ConflictError:tI,RateLimitError:tT,BadRequestError:tM,AuthenticationError:t$,InternalServerError:tN,PermissionDeniedError:tj,UnprocessableEntityError:tU}=G;X.Rz,(o=tS||(tS={})).Page=e8,o.Completions=e7,o.Messages=tc,o.Beta=t_;var tD=tS},20424:function(e,t,r){"use strict";var n=r(4346),s=r(97735);(0,n.YR)((0,s.O)({manuallyImported:!0}))},40859:function(e,t,r){"use strict";let n;r.d(t,{A:function(){return no}});var s,i,o,a,l,c,u,d,f=r(96108);let h=e=>t=>async r=>{if(!f.aW.isInstance(r.request))return t(r);let{request:n}=r,{handlerProtocol:s=""}=e.requestHandler.metadata||{};if(s.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let e=n.hostname;null!=n.port&&(e+=`:${n.port}`),n.headers.host=e}return t(r)},p={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},m=e=>({applyToStack:t=>{t.add(h(e),p)}}),g=()=>(e,t)=>async r=>{try{let n=await e(r),{clientName:s,commandName:i,logger:o,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:c}=a,u=l??t.inputFilterSensitiveLog,d=c??t.outputFilterSensitiveLog,{$metadata:f,...h}=n.output;return o?.info?.({clientName:s,commandName:i,input:u(r.input),output:d(h),metadata:f}),n}catch(l){let{clientName:e,commandName:n,logger:s,dynamoDbDocumentClientOptions:i={}}=t,{overrideInputFilterSensitiveLog:o}=i,a=o??t.inputFilterSensitiveLog;throw s?.error?.({clientName:e,commandName:n,input:a(r.input),error:l,metadata:l.$metadata}),l}},y={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},b=e=>({applyToStack:e=>{e.add(g(),y)}});var w=r(25566);let v="X-Amzn-Trace-Id",_=e=>t=>async r=>{let n;let{request:s}=r;if(!f.aW.isInstance(s)||"node"!==e.runtime||s.headers.hasOwnProperty(v))return t(r);let i=w.env.AWS_LAMBDA_FUNCTION_NAME,o=w.env._X_AMZN_TRACE_ID;return"string"==typeof i&&i.length>0&&"string"==typeof(n=o)&&n.length>0&&(s.headers[v]=o),t({...r,request:s})},S={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},E=e=>({applyToStack:t=>{t.add(_(e),S)}});var A=r(53620);let x=void 0;class R{constructor({size:e,params:t}){this.data=new Map,this.parameters=[],this.capacity=e??50,t&&(this.parameters=t)}get(e,t){let r=this.hash(e);if(!1===r)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){let e=this.data.keys(),t=0;for(;;){let{value:r,done:n}=e.next();if(this.data.delete(r),n||++t>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="",{parameters:r}=this;if(0===r.length)return!1;for(let n of r){let r=String(e[n]??"");if(r.includes("|;"))return!1;t+=r+"|;"}return t}}let O=RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),k=e=>O.test(e)||e.startsWith("[")&&e.endsWith("]"),P=RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),C=(e,t=!1)=>{if(!t)return P.test(e);for(let t of e.split("."))if(!C(t))return!1;return!0},I={},T="endpoints";function M(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${M(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(M).join(", ")})`:JSON.stringify(e,null,2)}class $ extends Error{constructor(e){super(e),this.name="EndpointError"}}let N=e=>{let t=e.split("."),r=[];for(let n of t){let t=n.indexOf("[");if(-1!==t){if(n.indexOf("]")!==n.length-1)throw new $(`Path: '${e}' does not end with ']'`);let s=n.slice(t+1,-1);if(Number.isNaN(parseInt(s)))throw new $(`Invalid array index: '${s}' in path: '${e}'`);0!==t&&r.push(n.slice(0,t)),r.push(s)}else r.push(n)}return r},j=(e,t)=>N(t).reduce((r,n)=>{if("object"!=typeof r)throw new $(`Index '${n}' in '${t}' not found in '${JSON.stringify(e)}'`);return Array.isArray(r)?r[parseInt(n)]:r[n]},e);var U=r(30349);let D={[U.cj.HTTP]:80,[U.cj.HTTPS]:443},L={booleanEquals:(e,t)=>e===t,getAttr:j,isSet:e=>null!=e,isValidHostLabel:C,not:e=>!e,parseURL:e=>{let t=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){let{hostname:t,port:r,protocol:n="",path:s="",query:i={}}=e,o=new URL(`${n}//${t}${r?`:${r}`:""}${s}`);return o.search=Object.entries(i).map(([e,t])=>`${e}=${t}`).join("&"),o}return new URL(e)}catch(e){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;let r=t.href,{host:n,hostname:s,pathname:i,protocol:o,search:a}=t;if(a)return null;let l=o.slice(0,-1);if(!Object.values(U.cj).includes(l))return null;let c=k(s),u=r.includes(`${n}:${D[l]}`)||"string"==typeof e&&e.includes(`${n}:${D[l]}`),d=`${n}${u?`:${D[l]}`:""}`;return{scheme:l,authority:d,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:c}},stringEquals:(e,t)=>e===t,substring:(e,t,r,n)=>t>=r||e.length<r?null:n?e.substring(e.length-r,e.length-t):e.substring(t,r),uriEncode:e=>encodeURIComponent(e).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)},q=(e,t)=>{let r=[],n={...t.endpointParams,...t.referenceRecord},s=0;for(;s<e.length;){let t=e.indexOf("{",s);if(-1===t){r.push(e.slice(s));break}r.push(e.slice(s,t));let i=e.indexOf("}",t);if(-1===i){r.push(e.slice(t));break}"{"===e[t+1]&&"}"===e[i+1]&&(r.push(e.slice(t+1,i)),s=i+2);let o=e.substring(t+1,i);if(o.includes("#")){let[e,t]=o.split("#");r.push(j(n[e],t))}else r.push(n[o]);s=i+1}return r.join("")},F=({ref:e},t)=>({...t.endpointParams,...t.referenceRecord})[e],B=(e,t,r)=>{if("string"==typeof e)return q(e,r);if(e.fn)return H(e,r);if(e.ref)return F(e,r);throw new $(`'${t}': ${String(e)} is not a string, function or reference.`)},H=({fn:e,argv:t},r)=>{let n=t.map(e=>["boolean","number"].includes(typeof e)?e:B(e,"arg",r)),s=e.split(".");return s[0]in I&&null!=s[1]?I[s[0]][s[1]](...n):L[e](...n)},W=({assign:e,...t},r)=>{if(e&&e in r.referenceRecord)throw new $(`'${e}' is already defined in Reference Record.`);let n=H(t,r);return r.logger?.debug?.(`${T} evaluateCondition: ${M(t)} = ${M(n)}`),{result:""===n||!!n,...null!=e&&{toAssign:{name:e,value:n}}}},z=(e=[],t)=>{let r={};for(let n of e){let{result:e,toAssign:s}=W(n,{...t,referenceRecord:{...t.referenceRecord,...r}});if(!e)return{result:e};s&&(r[s.name]=s.value,t.logger?.debug?.(`${T} assign: ${s.name} := ${M(s.value)}`))}return{result:!0,referenceRecord:r}},K=(e,t)=>Object.entries(e).reduce((e,[r,n])=>({...e,[r]:n.map(e=>{let n=B(e,"Header value entry",t);if("string"!=typeof n)throw new $(`Header '${r}' value '${n}' is not a string`);return n})}),{}),V=(e,t)=>{if(Array.isArray(e))return e.map(e=>V(e,t));switch(typeof e){case"string":return q(e,t);case"object":if(null===e)throw new $(`Unexpected endpoint property: ${e}`);return J(e,t);case"boolean":return e;default:throw new $(`Unexpected endpoint property type: ${typeof e}`)}},J=(e,t)=>Object.entries(e).reduce((e,[r,n])=>({...e,[r]:V(n,t)}),{}),G=(e,t)=>{let r=B(e,"Endpoint URL",t);if("string"==typeof r)try{return new URL(r)}catch(e){throw console.error(`Failed to construct URL with ${r}`,e),e}throw new $(`Endpoint URL must be a string, got ${typeof r}`)},Z=(e,t)=>{let{conditions:r,endpoint:n}=e,{result:s,referenceRecord:i}=z(r,t);if(!s)return;let o={...t,referenceRecord:{...t.referenceRecord,...i}},{url:a,properties:l,headers:c}=n;return t.logger?.debug?.(`${T} Resolving endpoint from template: ${M(n)}`),{...void 0!=c&&{headers:K(c,o)},...void 0!=l&&{properties:J(l,o)},url:G(a,o)}},X=(e,t)=>{let{conditions:r,error:n}=e,{result:s,referenceRecord:i}=z(r,t);if(s)throw new $(B(n,"Error",{...t,referenceRecord:{...t.referenceRecord,...i}}))},Y=(e,t)=>{let{conditions:r,rules:n}=e,{result:s,referenceRecord:i}=z(r,t);if(s)return Q(n,{...t,referenceRecord:{...t.referenceRecord,...i}})},Q=(e,t)=>{for(let r of e)if("endpoint"===r.type){let e=Z(r,t);if(e)return e}else if("error"===r.type)X(r,t);else if("tree"===r.type){let e=Y(r,t);if(e)return e}else throw new $(`Unknown endpoint rule: ${r}`);throw new $("Rules evaluation failed")},ee=(e,t)=>{let{endpointParams:r,logger:n}=t,{parameters:s,rules:i}=e;t.logger?.debug?.(`${T} Initial EndpointParams: ${M(r)}`);let o=Object.entries(s).filter(([,e])=>null!=e.default).map(([e,t])=>[e,t.default]);if(o.length>0)for(let[e,t]of o)r[e]=r[e]??t;for(let e of Object.entries(s).filter(([,e])=>e.required).map(([e])=>e))if(null==r[e])throw new $(`Missing required parameter: '${e}'`);let a=Q(i,{endpointParams:r,logger:n,referenceRecord:{}});return t.logger?.debug?.(`${T} Resolved endpoint: ${M(a)}`),a},et=(e,t=!1)=>{if(t){for(let t of e.split("."))if(!et(t))return!1;return!0}return!(!C(e)||e.length<3||e.length>63||e!==e.toLowerCase()||k(e))};var er=JSON.parse('{"partitions":[{"id":"aws","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-east-1","name":"aws","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^(us|eu|ap|sa|ca|me|af|il|mx)\\\\-\\\\w+\\\\-\\\\d+$","regions":{"af-south-1":{"description":"Africa (Cape Town)"},"ap-east-1":{"description":"Asia Pacific (Hong Kong)"},"ap-northeast-1":{"description":"Asia Pacific (Tokyo)"},"ap-northeast-2":{"description":"Asia Pacific (Seoul)"},"ap-northeast-3":{"description":"Asia Pacific (Osaka)"},"ap-south-1":{"description":"Asia Pacific (Mumbai)"},"ap-south-2":{"description":"Asia Pacific (Hyderabad)"},"ap-southeast-1":{"description":"Asia Pacific (Singapore)"},"ap-southeast-2":{"description":"Asia Pacific (Sydney)"},"ap-southeast-3":{"description":"Asia Pacific (Jakarta)"},"ap-southeast-4":{"description":"Asia Pacific (Melbourne)"},"ap-southeast-5":{"description":"Asia Pacific (Malaysia)"},"aws-global":{"description":"AWS Standard global region"},"ca-central-1":{"description":"Canada (Central)"},"ca-west-1":{"description":"Canada West (Calgary)"},"eu-central-1":{"description":"Europe (Frankfurt)"},"eu-central-2":{"description":"Europe (Zurich)"},"eu-north-1":{"description":"Europe (Stockholm)"},"eu-south-1":{"description":"Europe (Milan)"},"eu-south-2":{"description":"Europe (Spain)"},"eu-west-1":{"description":"Europe (Ireland)"},"eu-west-2":{"description":"Europe (London)"},"eu-west-3":{"description":"Europe (Paris)"},"il-central-1":{"description":"Israel (Tel Aviv)"},"me-central-1":{"description":"Middle East (UAE)"},"me-south-1":{"description":"Middle East (Bahrain)"},"sa-east-1":{"description":"South America (Sao Paulo)"},"us-east-1":{"description":"US East (N. Virginia)"},"us-east-2":{"description":"US East (Ohio)"},"us-west-1":{"description":"US West (N. California)"},"us-west-2":{"description":"US West (Oregon)"}}},{"id":"aws-cn","outputs":{"dnsSuffix":"amazonaws.com.cn","dualStackDnsSuffix":"api.amazonwebservices.com.cn","implicitGlobalRegion":"cn-northwest-1","name":"aws-cn","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^cn\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-cn-global":{"description":"AWS China global region"},"cn-north-1":{"description":"China (Beijing)"},"cn-northwest-1":{"description":"China (Ningxia)"}}},{"id":"aws-us-gov","outputs":{"dnsSuffix":"amazonaws.com","dualStackDnsSuffix":"api.aws","implicitGlobalRegion":"us-gov-west-1","name":"aws-us-gov","supportsDualStack":true,"supportsFIPS":true},"regionRegex":"^us\\\\-gov\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-us-gov-global":{"description":"AWS GovCloud (US) global region"},"us-gov-east-1":{"description":"AWS GovCloud (US-East)"},"us-gov-west-1":{"description":"AWS GovCloud (US-West)"}}},{"id":"aws-iso","outputs":{"dnsSuffix":"c2s.ic.gov","dualStackDnsSuffix":"c2s.ic.gov","implicitGlobalRegion":"us-iso-east-1","name":"aws-iso","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-iso\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-global":{"description":"AWS ISO (US) global region"},"us-iso-east-1":{"description":"US ISO East"},"us-iso-west-1":{"description":"US ISO WEST"}}},{"id":"aws-iso-b","outputs":{"dnsSuffix":"sc2s.sgov.gov","dualStackDnsSuffix":"sc2s.sgov.gov","implicitGlobalRegion":"us-isob-east-1","name":"aws-iso-b","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isob\\\\-\\\\w+\\\\-\\\\d+$","regions":{"aws-iso-b-global":{"description":"AWS ISOB (US) global region"},"us-isob-east-1":{"description":"US ISOB East (Ohio)"}}},{"id":"aws-iso-e","outputs":{"dnsSuffix":"cloud.adc-e.uk","dualStackDnsSuffix":"cloud.adc-e.uk","implicitGlobalRegion":"eu-isoe-west-1","name":"aws-iso-e","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^eu\\\\-isoe\\\\-\\\\w+\\\\-\\\\d+$","regions":{"eu-isoe-west-1":{"description":"EU ISOE West"}}},{"id":"aws-iso-f","outputs":{"dnsSuffix":"csp.hci.ic.gov","dualStackDnsSuffix":"csp.hci.ic.gov","implicitGlobalRegion":"us-isof-south-1","name":"aws-iso-f","supportsDualStack":false,"supportsFIPS":true},"regionRegex":"^us\\\\-isof\\\\-\\\\w+\\\\-\\\\d+$","regions":{}}],"version":"1.1"}');let en=()=>"",es={isVirtualHostableS3Bucket:et,parseArn:e=>{let t=e.split(":");if(t.length<6)return null;let[r,n,s,i,o,...a]=t;return"arn"!==r||""===n||""===s||""===a.join(":")?null:{partition:n,service:s,region:i,accountId:o,resourceId:a.map(e=>e.split("/")).flat()}},partition:e=>{let{partitions:t}=er;for(let r of t){let{regions:t,outputs:n}=r;for(let[r,s]of Object.entries(t))if(r===e)return{...n,...s}}for(let r of t){let{regionRegex:t,outputs:n}=r;if(new RegExp(t).test(e))return{...n}}let r=t.find(e=>"aws"===e.id);if(!r)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...r.outputs}}};function ei(e,t,r){e.__aws_sdk_context?e.__aws_sdk_context.features||(e.__aws_sdk_context.features={}):e.__aws_sdk_context={features:{}},e.__aws_sdk_context.features[t]=r}I.aws=es;let eo=/\d{12}\.ddb/;async function ea(e,t,r){let n=r.request;if(n?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&ei(e,"PROTOCOL_RPC_V2_CBOR","M"),"function"==typeof t.retryStrategy){let r=await t.retryStrategy();"function"==typeof r.acquireInitialRetryToken?r.constructor?.name?.includes("Adaptive")?ei(e,"RETRY_MODE_ADAPTIVE","F"):ei(e,"RETRY_MODE_STANDARD","E"):ei(e,"RETRY_MODE_LEGACY","D")}if("function"==typeof t.accountIdEndpointMode){let r=e.endpointV2;switch(String(r?.url?.hostname).match(eo)&&ei(e,"ACCOUNT_ID_ENDPOINT","O"),await t.accountIdEndpointMode?.()){case"disabled":ei(e,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":ei(e,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":ei(e,"ACCOUNT_ID_MODE_REQUIRED","R")}}let s=e.__smithy_context?.selectedHttpAuthScheme?.identity;if(s?.$source)for(let[t,r]of(s.accountId&&ei(e,"RESOLVED_ACCOUNT_ID","T"),Object.entries(s.$source??{})))ei(e,t,r)}let el="user-agent",ec="x-amz-user-agent",eu=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g,ed=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g,ef=e=>(t,r)=>async n=>{let{request:s}=n;if(!f.aW.isInstance(s))return t(n);let{headers:i}=s,o=r?.userAgent?.map(eh)||[],a=(await e.defaultUserAgentProvider()).map(eh);await ea(r,e,n),a.push(`m/${function(e){let t="";for(let r in e){let n=e[r];if(t.length+n.length+1<=1024){t.length?t+=","+n:t+=n;continue}break}return t}(Object.assign({},r.__smithy_context?.features,r.__aws_sdk_context?.features))}`);let l=e?.customUserAgent?.map(eh)||[],c=await e.userAgentAppId();c&&a.push(eh([`app/${c}`]));let u=en(),d=(u?[u]:[]).concat([...a,...o,...l]).join(" "),h=[...a.filter(e=>e.startsWith("aws-sdk-")),...l].join(" ");return"browser"!==e.runtime?(h&&(i[ec]=i[ec]?`${i[el]} ${h}`:h),i[el]=d):i[ec]=d,t({...n,request:s})},eh=e=>{let t=e[0].split("/").map(e=>e.replace(eu,"-")).join("/"),r=e[1]?.replace(ed,"-"),n=t.indexOf("/"),s=t.substring(0,n),i=t.substring(n+1);return"api"===s&&(i=i.toLowerCase()),[s,i,r].filter(e=>e&&e.length>0).reduce((e,t,r)=>{switch(r){case 0:return t;case 1:return`${e}/${t}`;default:return`${e}#${t}`}},"")},ep={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},em=e=>({applyToStack:t=>{t.add(ef(e),ep)}});(s=l||(l={})).ENV="env",s.CONFIG="shared config entry";var eg=r(81232);let ey=e=>"string"==typeof e&&(e.startsWith("fips-")||e.endsWith("-fips")),eb=e=>ey(e)?["fips-aws-global","aws-fips"].includes(e)?"us-east-1":e.replace(/fips-(dkr-|prod-)?|-fips/,""):e,ew=e=>{let{region:t,useFipsEndpoint:r}=e;if(!t)throw Error("Region is missing");return{...e,region:async()=>"string"==typeof t?eb(t):eb(await t()),useFipsEndpoint:async()=>!!ey("string"==typeof t?t:await t())||("function"!=typeof r?Promise.resolve(!!r):r())}},ev=e=>({...e,eventStreamMarshaller:e.eventStreamSerdeProvider(e)}),e_="content-length",eS={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},eE=e=>({applyToStack:t=>{var r;t.add((r=e.bodyLengthChecker,e=>async t=>{let n=t.request;if(f.aW.isInstance(n)){let{body:e,headers:t}=n;if(e&&-1===Object.keys(t).map(e=>e.toLowerCase()).indexOf(e_))try{let t=r(e);n.headers={...n.headers,[e_]:String(t)}}catch(e){}}return e({...t,request:n})}),eS)}});var eA=r(93833);(i=c||(c={})).STANDARD="standard",i.ADAPTIVE="adaptive";let ex=c.STANDARD,eR=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],eO=["TimeoutError","RequestTimeout","RequestTimeoutException"],ek=[500,502,503,504],eP=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],eC=e=>e.$metadata?.clockSkewCorrected,eI=e=>e.$metadata?.httpStatusCode===429||eR.includes(e.name)||e.$retryable?.throttling==!0,eT=e=>eC(e)||eO.includes(e.name)||eP.includes(e?.code||"")||ek.includes(e.$metadata?.httpStatusCode||0),eM=e=>{if(e.$metadata?.httpStatusCode!==void 0){let t=e.$metadata.httpStatusCode;if(500<=t&&t<=599&&!eT(e))return!0}return!1};class e${constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;let t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){let t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise(e=>setTimeout(e,t))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){let e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}let t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),eI(e)){let e=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());let r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){let e=Math.floor(2*this.getCurrentTimeInSeconds())/2;if(this.requestCount++,e>this.lastTxRateBucket){let t=this.requestCount/(e-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(t*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=e}}getPrecise(e){return parseFloat(e.toFixed(8))}}let eN=()=>{let e=100;return{computeNextBackoffDelay:t=>Math.floor(Math.min(2e4,Math.random()*2**t*e)),setDelayBase:t=>{e=t}}},ej=({retryDelay:e,retryCount:t,retryCost:r})=>({getRetryCount:()=>t,getRetryDelay:()=>Math.min(2e4,e),getRetryCost:()=>r});class eU{constructor(e){this.maxAttempts=e,this.mode=c.STANDARD,this.capacity=500,this.retryBackoffStrategy=eN(),this.maxAttemptsProvider="function"==typeof e?e:async()=>e}async acquireInitialRetryToken(e){return ej({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(e,t){let r=await this.getMaxAttempts();if(this.shouldRetry(e,t,r)){let r=t.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===r?500:100);let n=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),s=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,n):n,i=this.getCapacityCost(r);return this.capacity-=i,ej({retryDelay:s,retryCount:e.getRetryCount()+1,retryCost:i})}throw Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(e){return console.warn("Max attempts provider could not resolve. Using default of 3"),3}}shouldRetry(e,t,r){return e.getRetryCount()+1<r&&this.capacity>=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return"TRANSIENT"===e?10:5}isRetryableError(e){return"THROTTLING"===e||"TRANSIENT"===e}}class eD{constructor(e,t){this.maxAttemptsProvider=e,this.mode=c.ADAPTIVE;let{rateLimiter:r}=t??{};this.rateLimiter=r??new e$,this.standardRetryStrategy=new eU(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}var eL={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let eq=new Uint8Array(16),eF=[];for(let e=0;e<256;++e)eF.push((e+256).toString(16).slice(1));var eB=function(e,t,r){if(eL.randomUUID&&!t&&!e)return eL.randomUUID();let s=(e=e||{}).random||(e.rng||function(){if(!n&&!(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(eq)})();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=s[e];return t}return function(e,t=0){return eF[e[t+0]]+eF[e[t+1]]+eF[e[t+2]]+eF[e[t+3]]+"-"+eF[e[t+4]]+eF[e[t+5]]+"-"+eF[e[t+6]]+eF[e[t+7]]+"-"+eF[e[t+8]]+eF[e[t+9]]+"-"+eF[e[t+10]]+eF[e[t+11]]+eF[e[t+12]]+eF[e[t+13]]+eF[e[t+14]]+eF[e[t+15]]}(s)};let eH=e=>e instanceof Error?e:e instanceof Object?Object.assign(Error(),e):"string"==typeof e?Error(e):Error(`AWS SDK error wrapper for ${e}`),eW=e=>{let{retryStrategy:t}=e,r=(0,eg.$)(e.maxAttempts??3);return{...e,maxAttempts:r,retryStrategy:async()=>t||(await (0,eg.$)(e.retryMode)()===c.ADAPTIVE?new eD(r):new eU(r))}};var ez=r(35023);let eK=e=>e?.body instanceof ReadableStream,eV=e=>(t,r)=>async n=>{let s=await e.retryStrategy(),i=await e.maxAttempts();if(!eJ(s))return s?.mode&&(r.userAgent=[...r.userAgent||[],["cfg/retry-mode",s.mode]]),s.retry(t,n);{let e=await s.acquireInitialRetryToken(r.partition_id),o=Error(),a=0,l=0,{request:c}=n,u=f.aW.isInstance(c);for(u&&(c.headers["amz-sdk-invocation-id"]=eB());;)try{u&&(c.headers["amz-sdk-request"]=`attempt=${a+1}; max=${i}`);let{response:r,output:o}=await t(n);return s.recordSuccess(e),o.$metadata.attempts=a+1,o.$metadata.totalRetryDelay=l,{response:r,output:o}}catch(i){let t=eG(i);if(o=eH(i),u&&eK(c))throw(r.logger instanceof ez.vk?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),o;try{e=await s.refreshRetryTokenForRetry(e,t)}catch(e){throw o.$metadata||(o.$metadata={}),o.$metadata.attempts=a+1,o.$metadata.totalRetryDelay=l,o}a=e.getRetryCount();let n=e.getRetryDelay();l+=n,await new Promise(e=>setTimeout(e,n))}}},eJ=e=>void 0!==e.acquireInitialRetryToken&&void 0!==e.refreshRetryTokenForRetry&&void 0!==e.recordSuccess,eG=e=>{let t={error:e,errorType:eZ(e)},r=eQ(e.$response);return r&&(t.retryAfterHint=r),t},eZ=e=>eI(e)?"THROTTLING":eT(e)?"TRANSIENT":eM(e)?"SERVER_ERROR":"CLIENT_ERROR",eX={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},eY=e=>({applyToStack:t=>{t.add(eV(e),eX)}}),eQ=e=>{if(!f.Zn.isInstance(e))return;let t=Object.keys(e.headers).find(e=>"retry-after"===e.toLowerCase());if(!t)return;let r=e.headers[t],n=Number(r);return new Date(Number.isNaN(n)?r:1e3*n)};var e0=r(58010);let e1=e=>encodeURIComponent(e).replace(/[!'()*]/g,e2),e2=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;var e3=r(80102);let e4=e=>"string"==typeof e?(0,e3.$)(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),e6="X-Amz-Date",e5="X-Amz-Signature",e8="X-Amz-Security-Token",e9="authorization",e7=e6.toLowerCase(),te=[e9,e7,"date"],tt=e5.toLowerCase(),tr="x-amz-content-sha256",tn=e8.toLowerCase(),ts={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},ti=/^proxy-/,to=/^sec-/,ta="AWS4-HMAC-SHA256",tl="aws4_request",tc={},tu=[],td=(e,t,r)=>`${e}/${t}/${r}/${tl}`,tf=async(e,t,r,n,s)=>{let i=await th(e,t.secretAccessKey,t.accessKeyId),o=`${r}:${n}:${s}:${(0,e0.N)(i)}:${t.sessionToken}`;if(o in tc)return tc[o];for(tu.push(o);tu.length>50;)delete tc[tu.shift()];let a=`AWS4${t.secretAccessKey}`;for(let t of[r,n,s,tl])a=await th(e,a,t);return tc[o]=a},th=(e,t,r)=>{let n=new e(t);return n.update(e4(r)),n.digest()},tp=({headers:e},t,r)=>{let n={};for(let s of Object.keys(e).sort()){if(void 0==e[s])continue;let i=s.toLowerCase();(!(i in ts||t?.has(i)||ti.test(i)||to.test(i))||r&&(!r||r.has(i)))&&(n[i]=e[s].trim().replace(/\s+/g," "))}return n},tm=({query:e={}})=>{let t=[],r={};for(let n of Object.keys(e)){if(n.toLowerCase()===tt)continue;let s=e1(n);t.push(s);let i=e[n];"string"==typeof i?r[s]=`${s}=${e1(i)}`:Array.isArray(i)&&(r[s]=i.slice(0).reduce((e,t)=>e.concat([`${s}=${e1(t)}`]),[]).sort().join("&"))}return t.sort().map(e=>r[e]).filter(e=>e).join("&")},tg=e=>"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(e),ty=async({headers:e,body:t},r)=>{for(let t of Object.keys(e))if(t.toLowerCase()===tr)return e[t];if(void 0==t)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof t||ArrayBuffer.isView(t)||tg(t)){let e=new r;return e.update(e4(t)),(0,e0.N)(await e.digest())}return"UNSIGNED-PAYLOAD"};class tb{format(e){let t=[];for(let r of Object.keys(e)){let n=(0,e3.$)(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}let r=new Uint8Array(t.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let e of t)r.set(e,n),n+=e.byteLength;return r}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 t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let s=new DataView(new ArrayBuffer(3+e.value.byteLength));s.setUint8(0,6),s.setUint16(1,e.value.byteLength,!1);let i=new Uint8Array(s.buffer);return i.set(e.value,3),i;case"string":let o=(0,e3.$)(e.value),a=new DataView(new ArrayBuffer(3+o.byteLength));a.setUint8(0,7),a.setUint16(1,o.byteLength,!1);let l=new Uint8Array(a.buffer);return l.set(o,3),l;case"timestamp":let c=new Uint8Array(9);return c[0]=8,c.set(tv.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!tw.test(e.value))throw Error(`Invalid UUID received: ${e.value}`);let u=new Uint8Array(17);return u[0]=9,u.set((0,e0.H)(e.value.replace(/\-/g,"")),1),u}}}(o=u||(u={}))[o.boolTrue=0]="boolTrue",o[o.boolFalse=1]="boolFalse",o[o.byte=2]="byte",o[o.short=3]="short",o[o.integer=4]="integer",o[o.long=5]="long",o[o.byteArray=6]="byteArray",o[o.string=7]="string",o[o.timestamp=8]="timestamp",o[o.uuid=9]="uuid";let tw=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class tv{constructor(e){if(this.bytes=e,8!==e.byteLength)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x7fffffffffffffff||e<-0x8000000000000000)throw Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&t_(t),new tv(t)}valueOf(){let e=this.bytes.slice(0),t=128&e[0];return t&&t_(e),parseInt((0,e0.N)(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function t_(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}let tS=(e,t)=>{for(let r of(e=e.toLowerCase(),Object.keys(t)))if(e===r.toLowerCase())return!0;return!1},tE=(e,t={})=>{let{headers:r,query:n={}}=f.aW.clone(e);for(let e of Object.keys(r)){let s=e.toLowerCase();("x-amz-"===s.slice(0,6)&&!t.unhoistableHeaders?.has(s)||t.hoistableHeaders?.has(s))&&(n[e]=r[e],delete r[e])}return{...e,headers:r,query:n}},tA=e=>{for(let t of Object.keys((e=f.aW.clone(e)).headers))te.indexOf(t.toLowerCase())>-1&&delete e.headers[t];return e},tx=e=>tR(e).toISOString().replace(/\.\d{3}Z$/,"Z"),tR=e=>"number"==typeof e?new Date(1e3*e):"string"==typeof e?new Date(Number(e)?1e3*Number(e):e):e;class tO{constructor({applyChecksum:e,credentials:t,region:r,service:n,sha256:s,uriEscapePath:i=!0}){this.headerFormatter=new tb,this.service=n,this.sha256=s,this.uriEscapePath=i,this.applyChecksum="boolean"!=typeof e||e,this.regionProvider=(0,eg.$)(r),this.credentialProvider=(0,eg.$)(t)}async presign(e,t={}){let{signingDate:r=new Date,expiresIn:n=3600,unsignableHeaders:s,unhoistableHeaders:i,signableHeaders:o,hoistableHeaders:a,signingRegion:l,signingService:c}=t,u=await this.credentialProvider();this.validateResolvedCredentials(u);let d=l??await this.regionProvider(),{longDate:f,shortDate:h}=tk(r);if(n>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let p=td(h,d,c??this.service),m=tE(tA(e),{unhoistableHeaders:i,hoistableHeaders:a});u.sessionToken&&(m.query[e8]=u.sessionToken),m.query["X-Amz-Algorithm"]=ta,m.query["X-Amz-Credential"]=`${u.accessKeyId}/${p}`,m.query[e6]=f,m.query["X-Amz-Expires"]=n.toString(10);let g=tp(m,s,o);return m.query["X-Amz-SignedHeaders"]=tP(g),m.query[e5]=await this.getSignature(f,p,this.getSigningKey(u,d,h,c),this.createCanonicalRequest(m,g,await ty(e,this.sha256))),m}async sign(e,t){return"string"==typeof e?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:r=new Date,priorSignature:n,signingRegion:s,signingService:i}){let o=s??await this.regionProvider(),{shortDate:a,longDate:l}=tk(r),c=td(a,o,i??this.service),u=await ty({headers:{},body:t},this.sha256),d=new this.sha256;d.update(e);let f=["AWS4-HMAC-SHA256-PAYLOAD",l,c,n,(0,e0.N)(await d.digest()),u].join("\n");return this.signString(f,{signingDate:r,signingRegion:o,signingService:i})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:n}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:n,priorSignature:e.priorSignature}).then(t=>({message:e.message,signature:t}))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:n}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let i=r??await this.regionProvider(),{shortDate:o}=tk(t),a=new this.sha256(await this.getSigningKey(s,i,o,n));return a.update(e4(e)),(0,e0.N)(await a.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:n,signingRegion:s,signingService:i}={}){let o=await this.credentialProvider();this.validateResolvedCredentials(o);let a=s??await this.regionProvider(),l=tA(e),{longDate:c,shortDate:u}=tk(t),d=td(u,a,i??this.service);l.headers[e7]=c,o.sessionToken&&(l.headers[tn]=o.sessionToken);let f=await ty(l,this.sha256);!tS(tr,l.headers)&&this.applyChecksum&&(l.headers[tr]=f);let h=tp(l,n,r),p=await this.getSignature(c,d,this.getSigningKey(o,a,u,i),this.createCanonicalRequest(l,h,f));return l.headers[e9]=`${ta} Credential=${o.accessKeyId}/${d}, SignedHeaders=${tP(h)}, Signature=${p}`,l}createCanonicalRequest(e,t,r){let n=Object.keys(t).sort();return`${e.method}
${this.getCanonicalPath(e)}
${tm(e)}
${n.map(e=>`${e}:${t[e]}`).join("\n")}

${n.join(";")}
${r}`}async createStringToSign(e,t,r){let n=new this.sha256;n.update(e4(r));let s=await n.digest();return`${ta}
${e}
${t}
${(0,e0.N)(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let t=[];for(let r of e.split("/"))r?.length!==0&&"."!==r&&(".."===r?t.pop():t.push(r));return e1(`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`).replace(/%2F/g,"/")}return e}async getSignature(e,t,r,n){let s=await this.createStringToSign(e,t,n),i=new this.sha256(await r);return i.update(e4(s)),(0,e0.N)(await i.digest())}getSigningKey(e,t,r,n){return tf(this.sha256,e,r,t,n||this.service)}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw Error("Resolved credential object is not valid")}}let tk=e=>{let t=tx(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}},tP=e=>Object.keys(e).sort().join(";"),tC=e=>{let t,r,n=!1;e.credentials&&(n=!0,t=(0,A.CU)(e.credentials,A.BP,A.zV)),t||(t=e.credentialDefaultProvider?(0,A.$E)(e.credentialDefaultProvider(Object.assign({},e,{parentClientConfig:e}))):async()=>{throw Error("`credentials` is missing")});let{signingEscapePath:s=!0,systemClockOffset:i=e.systemClockOffset||0,sha256:o}=e;return r=e.signer?(0,A.$E)(e.signer):e.regionInfoProvider?()=>(0,A.$E)(e.region)().then(async t=>[await e.regionInfoProvider(t,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},t]).then(([r,n])=>{let{signingRegion:i,signingService:a}=r;e.signingRegion=e.signingRegion||i||n,e.signingName=e.signingName||a||e.serviceId;let l={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:s};return new(e.signerConstructor||tO)(l)}):async r=>{let n=(r=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await (0,A.$E)(e.region)(),properties:{}},r)).signingRegion,i=r.signingName;e.signingRegion=e.signingRegion||n,e.signingName=e.signingName||i||e.serviceId;let a={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:s};return new(e.signerConstructor||tO)(a)},{...e,systemClockOffset:i,signingEscapePath:s,credentials:n?async()=>t().then(e=>(e.$source||(e.$source={}),e.$source.CREDENTIALS_CODE="e",e)):t,signer:r}},tI=async(e,t,r)=>({operation:(0,eg.J)(t).operation,region:await (0,eg.$)(e.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),tT=e=>{let t=[];return e.operation,t.push({schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:e.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}),t},tM=e=>({...tC(e)});var t$=r(47375),tN={i8:"3.679.0"},tj=r(9109).Buffer,tU=void 0!==tj&&tj.from?function(e){return tj.from(e,"utf8")}:e=>new TextEncoder().encode(e);function tD(e){return e instanceof Uint8Array?e:"string"==typeof e?tU(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function tL(e){return"string"==typeof e?0===e.length:0===e.byteLength}var tq={name:"SHA-256"},tF={name:"HMAC",hash:tq},tB=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);let tH={};function tW(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:tH}var tz=function(){function e(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return e.prototype.update=function(e){if(!tL(e)){var t=tD(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},e.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return tW().crypto.subtle.sign(tF,t,e.toHash).then(function(e){return new Uint8Array(e)})}):tL(this.toHash)?Promise.resolve(tB):Promise.resolve().then(function(){return tW().crypto.subtle.digest(tq,e.toHash)}).then(function(e){return Promise.resolve(new Uint8Array(e))})},e.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&void 0!==this.secret&&(this.key=new Promise(function(t,r){tW().crypto.subtle.importKey("raw",tD(e.secret),tF,!1,["sign"]).then(t,r)}),this.key.catch(function(){}))},e}(),tK=r(60160),tV=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),tJ=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],tG=function(){function e(){this.state=Int32Array.from(tJ),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(e){if(this.finished)throw Error("Attempted to update an already finished hash.");var t=0,r=e.byteLength;if(this.bytesHashed+=r,8*this.bytesHashed>9007199254740991)throw Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,64===this.bufferLength&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var e=8*this.bytesHashed,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(t.setUint8(this.bufferLength++,128),r%64>=56){for(var n=this.bufferLength;n<64;n++)t.setUint8(n,0);this.hashBuffer(),this.bufferLength=0}for(var n=this.bufferLength;n<56;n++)t.setUint8(n,0);t.setUint32(56,Math.floor(e/4294967296),!0),t.setUint32(60,e),this.hashBuffer(),this.finished=!0}for(var s=new Uint8Array(32),n=0;n<8;n++)s[4*n]=this.state[n]>>>24&255,s[4*n+1]=this.state[n]>>>16&255,s[4*n+2]=this.state[n]>>>8&255,s[4*n+3]=this.state[n]>>>0&255;return s},e.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,r=t[0],n=t[1],s=t[2],i=t[3],o=t[4],a=t[5],l=t[6],c=t[7],u=0;u<64;u++){if(u<16)this.temp[u]=(255&e[4*u])<<24|(255&e[4*u+1])<<16|(255&e[4*u+2])<<8|255&e[4*u+3];else{var d=this.temp[u-2],f=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,h=((d=this.temp[u-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[u]=(f+this.temp[u-7]|0)+(h+this.temp[u-16]|0)}var p=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&a^~o&l)|0)+(c+(tV[u]+this.temp[u]|0)|0)|0,m=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&n^r&s^n&s)|0;c=l,l=a,a=o,o=i+p|0,i=s,s=n,n=r,r=p+m|0}t[0]+=r,t[1]+=n,t[2]+=s,t[3]+=i,t[4]+=o,t[5]+=a,t[6]+=l,t[7]+=c},e}(),tZ=function(){function e(e){this.secret=e,this.hash=new tG,this.reset()}return e.prototype.update=function(e){if(!tL(e)&&!this.error)try{this.hash.update(tD(e))}catch(e){this.error=e}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return(0,tK.mG)(this,void 0,void 0,function(){return(0,tK.Jh)(this,function(e){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new tG,this.secret){this.outer=new tG;var e=function(e){var t=tD(e);if(t.byteLength>64){var r=new tG;r.update(t),t=r.digest()}var n=new Uint8Array(64);return n.set(t),n}(this.secret),t=new Uint8Array(64);t.set(e);for(var r=0;r<64;r++)e[r]^=54,t[r]^=92;this.hash.update(e),this.outer.update(t);for(var r=0;r<e.byteLength;r++)e[r]=0}},e}(),tX=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"],tY=function(){function e(e){var t,r,n;"object"==typeof(r=t=tW())&&"object"==typeof r.crypto&&"function"==typeof r.crypto.getRandomValues&&"object"==typeof t.crypto.subtle&&(n=t.crypto.subtle)&&tX.every(function(e){return"function"==typeof n[e]})?this.hash=new tz(e):this.hash=new tZ(e)}return e.prototype.update=function(e,t){this.hash.update(tD(e))},e.prototype.digest=function(){return this.hash.digest()},e.prototype.reset=function(){this.hash.reset()},e}(),tQ=r(22510),t0=r.n(tQ);let t1=({serviceId:e,clientVersion:t})=>async r=>{let n="undefined"!=typeof window&&window?.navigator?.userAgent?t0().parse(window.navigator.userAgent):void 0,s=[["aws-sdk-js",t],["ua","2.1"],[`os/${n?.os?.name||"other"}`,n?.os?.version],["lang/js"],["md/browser",`${n?.browser?.name??"unknown"}_${n?.browser?.version??"unknown"}`]];e&&s.push([`api/${e}`,t]);let i=await r?.userAgentAppId?.();return i&&s.push([`app/${i}`]),s};!function(){function e(){this.crc32=new t2}e.prototype.update=function(e){tL(e)||this.crc32.update(tD(e))},e.prototype.digest=function(){return(0,tK.mG)(this,void 0,void 0,function(){return(0,tK.Jh)(this,function(e){var t;return[2,new Uint8Array([(4278190080&(t=this.crc32.digest()))>>24,(16711680&t)>>16,(65280&t)>>8,255&t])]})})},e.prototype.reset=function(){this.crc32=new t2}}();var t2=function(){function e(){this.checksum=4294967295}return e.prototype.update=function(e){var t,r;try{for(var n=(0,tK.XA)(e),s=n.next();!s.done;s=n.next()){var i=s.value;this.checksum=this.checksum>>>8^t3[(this.checksum^i)&255]}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}return this},e.prototype.digest=function(){return(4294967295^this.checksum)>>>0},e}(),t3=function(e){if(!Uint32Array.from){for(var t=new Uint32Array(e.length),r=0;r<e.length;)t[r]=e[r],r+=1;return t}return Uint32Array.from(e)}([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);class t4{constructor(e){if(this.bytes=e,8!==e.byteLength)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>0x7fffffffffffffff||e<-0x8000000000000000)throw Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,n=Math.abs(Math.round(e));r>-1&&n>0;r--,n/=256)t[r]=n;return e<0&&t6(t),new t4(t)}valueOf(){let e=this.bytes.slice(0),t=128&e[0];return t&&t6(e),parseInt((0,e0.N)(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function t6(e){for(let t=0;t<8;t++)e[t]^=255;for(let t=7;t>-1&&(e[t]++,0===e[t]);t--);}class t5{constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){let t=[];for(let r of Object.keys(e)){let n=this.fromUtf8(r);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[r]))}let r=new Uint8Array(t.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let e of t)r.set(e,n),n+=e.byteLength;return r}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 t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let s=new DataView(new ArrayBuffer(3+e.value.byteLength));s.setUint8(0,6),s.setUint16(1,e.value.byteLength,!1);let i=new Uint8Array(s.buffer);return i.set(e.value,3),i;case"string":let o=this.fromUtf8(e.value),a=new DataView(new ArrayBuffer(3+o.byteLength));a.setUint8(0,7),a.setUint16(1,o.byteLength,!1);let l=new Uint8Array(a.buffer);return l.set(o,3),l;case"timestamp":let c=new Uint8Array(9);return c[0]=8,c.set(t4.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!ro.test(e.value))throw Error(`Invalid UUID received: ${e.value}`);let u=new Uint8Array(17);return u[0]=9,u.set((0,e0.H)(e.value.replace(/\-/g,"")),1),u}}parse(e){let t={},r=0;for(;r<e.byteLength;){let n=e.getUint8(r++),s=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,n));switch(r+=n,e.getUint8(r++)){case 0:t[s]={type:t8,value:!0};break;case 1:t[s]={type:t8,value:!1};break;case 2:t[s]={type:t9,value:e.getInt8(r++)};break;case 3:t[s]={type:t7,value:e.getInt16(r,!1)},r+=2;break;case 4:t[s]={type:re,value:e.getInt32(r,!1)},r+=4;break;case 5:t[s]={type:rt,value:new t4(new Uint8Array(e.buffer,e.byteOffset+r,8))},r+=8;break;case 6:let i=e.getUint16(r,!1);r+=2,t[s]={type:rr,value:new Uint8Array(e.buffer,e.byteOffset+r,i)},r+=i;break;case 7:let o=e.getUint16(r,!1);r+=2,t[s]={type:rn,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,o))},r+=o;break;case 8:t[s]={type:rs,value:new Date(new t4(new Uint8Array(e.buffer,e.byteOffset+r,8)).valueOf())},r+=8;break;case 9:let a=new Uint8Array(e.buffer,e.byteOffset+r,16);r+=16,t[s]={type:ri,value:`${(0,e0.N)(a.subarray(0,4))}-${(0,e0.N)(a.subarray(4,6))}-${(0,e0.N)(a.subarray(6,8))}-${(0,e0.N)(a.subarray(8,10))}-${(0,e0.N)(a.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}(a=d||(d={}))[a.boolTrue=0]="boolTrue",a[a.boolFalse=1]="boolFalse",a[a.byte=2]="byte",a[a.short=3]="short",a[a.integer=4]="integer",a[a.long=5]="long",a[a.byteArray=6]="byteArray",a[a.string=7]="string",a[a.timestamp=8]="timestamp",a[a.uuid=9]="uuid";let t8="boolean",t9="byte",t7="short",re="integer",rt="long",rr="binary",rn="string",rs="timestamp",ri="uuid",ro=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class ra{constructor(e,t){this.headerMarshaller=new t5(e,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){let e=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage:()=>e,isEndOfStream:()=>t}}getAvailableMessages(){let e=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return{getMessages:()=>e,isEndOfStream:()=>t}}encode({headers:e,body:t}){let r=this.headerMarshaller.format(e),n=r.byteLength+t.byteLength+16,s=new Uint8Array(n),i=new DataView(s.buffer,s.byteOffset,s.byteLength),o=new t2;return i.setUint32(0,n,!1),i.setUint32(4,r.byteLength,!1),i.setUint32(8,o.update(s.subarray(0,8)).digest(),!1),s.set(r,12),s.set(t,r.byteLength+12),i.setUint32(n-4,o.update(s.subarray(8,n-4)).digest(),!1),s}decode(e){let{headers:t,body:r}=function({byteLength:e,byteOffset:t,buffer:r}){if(e<16)throw Error("Provided message too short to accommodate event stream message overhead");let n=new DataView(r,t,e),s=n.getUint32(0,!1);if(e!==s)throw Error("Reported message length does not match received message length");let i=n.getUint32(4,!1),o=n.getUint32(8,!1),a=n.getUint32(e-4,!1),l=new t2().update(new Uint8Array(r,t,8));if(o!==l.digest())throw Error(`The prelude checksum specified in the message (${o}) does not match the calculated CRC32 checksum (${l.digest()})`);if(l.update(new Uint8Array(r,t+8,e-12)),a!==l.digest())throw Error(`The message checksum (${l.digest()}) did not match the expected value of ${a}`);return{headers:new DataView(r,t+8+4,i),body:new Uint8Array(r,t+8+4+i,s-i-16)}}(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class rl{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async *asyncIterator(){for await(let e of this.options.inputStream){let t=this.options.decoder.decode(e);yield t}}}class rc{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async *asyncIterator(){for await(let e of this.options.messageStream){let t=this.options.encoder.encode(e);yield t}this.options.includeEndFrame&&(yield new Uint8Array(0))}}class ru{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async *asyncIterator(){for await(let e of this.options.messageStream){let t=await this.options.deserializer(e);void 0!==t&&(yield t)}}}class rd{constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async *asyncIterator(){for await(let e of this.options.inputStream){let t=this.options.serializer(e);yield t}}}class rf{constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new ra(e,t),this.utfEncoder=e}deserialize(e,t){var r;return new ru({messageStream:new rl({inputStream:function(e){let t=0,r=0,n=null,s=null,i=e=>{if("number"!=typeof e)throw Error("Attempted to allocate an event message where size was not a number: "+e);t=e,r=4,new DataView((n=new Uint8Array(e)).buffer).setUint32(0,e,!1)};return{[Symbol.asyncIterator]:async function*(){let o=e[Symbol.asyncIterator]();for(;;){let{value:e,done:a}=await o.next();if(a){if(t){if(t===r)yield n;else throw Error("Truncated event message received.")}return}let l=e.length,c=0;for(;c<l;){if(!n){let t=l-c;s||(s=new Uint8Array(4));let n=Math.min(4-r,t);if(s.set(e.slice(c,c+n),r),r+=n,c+=n,r<4)break;i(new DataView(s.buffer).getUint32(0,!1)),s=null}let o=Math.min(t-r,l-c);n.set(e.slice(c,c+o),r),r+=o,c+=o,t&&t===r&&(yield n,n=null,t=0,r=0)}}}}}(e),decoder:this.eventStreamCodec}),deserializer:(r=this.utfEncoder,async function(e){let{value:n}=e.headers[":message-type"];if("error"===n){let t=Error(e.headers[":error-message"].value||"UnknownError");throw t.name=e.headers[":error-code"].value,t}if("exception"===n){let n=e.headers[":exception-type"].value,s=await t({[n]:e});if(s.$unknown){let t=Error(r(e.body));throw t.name=n,t}throw s[n]}if("event"===n){let r={[e.headers[":event-type"].value]:e},n=await t(r);if(n.$unknown)return;return n}throw Error(`Unrecognizable event type: ${e.headers[":event-type"].value}`)})})}serialize(e,t){return new rc({messageStream:new rd({inputStream:e,serializer:t}),encoder:this.eventStreamCodec,includeEndFrame:!0})}}let rh=e=>({[Symbol.asyncIterator]:async function*(){let t=e.getReader();try{for(;;){let{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}}}),rp=e=>{let t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(e){let{done:r,value:n}=await t.next();if(r)return e.close();e.enqueue(n)}})};class rm{constructor({utf8Encoder:e,utf8Decoder:t}){this.universalMarshaller=new rf({utf8Decoder:t,utf8Encoder:e})}deserialize(e,t){let r=rg(e)?rh(e):e;return this.universalMarshaller.deserialize(r,t)}serialize(e,t){let r=this.universalMarshaller.serialize(e,t);return"function"==typeof ReadableStream?rp(r):r}}let rg=e=>"function"==typeof ReadableStream&&e instanceof ReadableStream,ry=e=>new rm(e),rb={supported:void 0};class rw{static create(e){return"function"==typeof e?.handle?e:new rw(e)}constructor(e){"function"==typeof e?this.configProvider=e().then(e=>e||{}):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===rb.supported&&(rb.supported=!!("undefined"!=typeof Request&&"keepalive"in new Request("https://[::1]")))}destroy(){}async handle(e,{abortSignal:t}={}){this.config||(this.config=await this.configProvider);let r=this.config.requestTimeout,n=!0===this.config.keepAlive,s=this.config.credentials;if(t?.aborted){let e=Error("Request aborted");return e.name="AbortError",Promise.reject(e)}let i=e.path,o=function(e){let t=[];for(let r of Object.keys(e).sort()){let n=e[r];if(r=e1(r),Array.isArray(n))for(let e=0,s=n.length;e<s;e++)t.push(`${r}=${e1(n[e])}`);else{let e=r;(n||"string"==typeof n)&&(e+=`=${e1(n)}`),t.push(e)}}return t.join("&")}(e.query||{});o&&(i+=`?${o}`),e.fragment&&(i+=`#${e.fragment}`);let a="";if(null!=e.username||null!=e.password){let t=e.username??"",r=e.password??"";a=`${t}:${r}@`}let{port:l,method:c}=e,u=`${e.protocol}//${a}${e.hostname}${l?`:${l}`:""}${i}`,d="GET"===c||"HEAD"===c?void 0:e.body,h={body:d,headers:new Headers(e.headers),method:c,credentials:s};this.config?.cache&&(h.cache=this.config.cache),d&&(h.duplex="half"),"undefined"!=typeof AbortController&&(h.signal=t),rb.supported&&(h.keepalive=n),"function"==typeof this.config.requestInit&&Object.assign(h,this.config.requestInit(e));let p=()=>{},m=[fetch(new Request(u,h)).then(e=>{let t=e.headers,r={};for(let e of t.entries())r[e[0]]=e[1];return void 0!=e.body?{response:new f.Zn({headers:r,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then(t=>({response:new f.Zn({headers:r,reason:e.statusText,statusCode:e.status,body:t})}))}),function(e=0){return new Promise((t,r)=>{e&&setTimeout(()=>{let t=Error(`Request did not complete within ${e} ms`);t.name="TimeoutError",r(t)},e)})}(r)];return t&&m.push(new Promise((e,r)=>{let n=()=>{let e=Error("Request aborted");e.name="AbortError",r(e)};"function"==typeof t.addEventListener?(t.addEventListener("abort",n,{once:!0}),p=()=>t.removeEventListener("abort",n)):t.onabort=n})),Promise.race(m).finally(p)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then(r=>(r[e]=t,r))}httpHandlerConfigs(){return this.config??{}}}var rv=r(80880);let r_=e=>"function"==typeof Blob&&e instanceof Blob?rS(e):rE(e);async function rS(e){let t=await new Promise((t,r)=>{let n=new FileReader;n.onloadend=()=>{if(2!==n.readyState)return r(Error("Reader aborted too early"));let e=n.result??"",s=e.indexOf(","),i=s>-1?s+1:e.length;t(e.substring(i))},n.onabort=()=>r(Error("Read aborted")),n.onerror=()=>r(n.error),n.readAsDataURL(e)});return new Uint8Array((0,rv.G)(t))}async function rE(e){let t=[],r=e.getReader(),n=!1,s=0;for(;!n;){let{done:e,value:i}=await r.read();i&&(t.push(i),s+=i.length),n=e}let i=new Uint8Array(s),o=0;for(let e of t)i.set(e,o),o+=e.length;return i}let rA=e=>()=>Promise.reject(e),rx="function"==typeof TextEncoder?new TextEncoder:null,rR=e=>{if("string"==typeof e){if(rx)return rx.encode(e).byteLength;let t=e.length;for(let r=t-1;r>=0;r--){let n=e.charCodeAt(r);n>127&&n<=2047?t++:n>2047&&n<=65535&&(t+=2),n>=56320&&n<=57343&&r--}return t}if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;throw Error(`Body Length computation failed for ${e}`)},rO=e=>new Date(Date.now()+e),rk=e=>f.Zn.isInstance(e)?e.headers?.date??e.headers?.Date:void 0,rP=(e,t)=>Math.abs(rO(t).getTime()-e)>=3e5,rC=(e,t)=>{let r=Date.parse(e);return rP(r,t)?r-Date.now():t},rI=(e,t)=>{if(!t)throw Error(`Property \`${e}\` is not resolved for AWS SDK SigV4Auth`);return t},rT=async e=>{let t=rI("context",e.context),r=rI("config",e.config),n=t.endpointV2?.properties?.authSchemes?.[0],s=rI("signer",r.signer),i=await s(n);return{config:r,signer:i,signingRegion:e?.signingRegion,signingRegionSet:e?.signingRegionSet,signingName:e?.signingName}};class rM{async sign(e,t,r){if(!f.aW.isInstance(e))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let n=await rT(r),{config:s,signer:i}=n,{signingRegion:o,signingName:a}=n,l=r.context;if(l?.authSchemes?.length){let[e,t]=l.authSchemes;e?.name==="sigv4a"&&t?.name==="sigv4"&&(o=t?.signingRegion??o,a=t?.signingName??a)}return await i.sign(e,{signingDate:rO(s.systemClockOffset),signingRegion:o,signingService:a})}errorHandler(e){return t=>{let r=t.ServerTime??rk(t.$response);if(r){let n=rI("config",e.config),s=n.systemClockOffset;n.systemClockOffset=rC(r,n.systemClockOffset),n.systemClockOffset!==s&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){let r=rk(e);if(r){let e=rI("config",t.config);e.systemClockOffset=rC(r,e.systemClockOffset)}}}var r$=r(69296),rN=r(10637);let rj="required",rU="argv",rD="isSet",rL="booleanEquals",rq="error",rF="endpoint",rB="tree",rH="PartitionResult",rW={[rj]:!1,type:"String"},rz={[rj]:!0,default:!1,type:"Boolean"},rK={ref:"Endpoint"},rV={fn:rL,[rU]:[{ref:"UseFIPS"},!0]},rJ={fn:rL,[rU]:[{ref:"UseDualStack"},!0]},rG={},rZ={fn:"getAttr",[rU]:[{ref:rH},"supportsFIPS"]},rX={fn:rL,[rU]:[!0,{fn:"getAttr",[rU]:[{ref:rH},"supportsDualStack"]}]},rY=[rV],rQ=[rJ],r0=[{ref:"Region"}],r1={version:"1.0",parameters:{Region:rW,UseDualStack:rz,UseFIPS:rz,Endpoint:rW},rules:[{conditions:[{fn:rD,[rU]:[rK]}],rules:[{conditions:rY,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:rq},{rules:[{conditions:rQ,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:rq},{endpoint:{url:rK,properties:rG,headers:rG},type:rF}],type:rB}],type:rB},{rules:[{conditions:[{fn:rD,[rU]:r0}],rules:[{conditions:[{fn:"aws.partition",[rU]:r0,assign:rH}],rules:[{conditions:[rV,rJ],rules:[{conditions:[{fn:rL,[rU]:[!0,rZ]},rX],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:rG,headers:rG},type:rF}],type:rB}],type:rB},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:rq}],type:rB},{conditions:rY,rules:[{conditions:[{fn:rL,[rU]:[rZ,!0]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:rG,headers:rG},type:rF}],type:rB}],type:rB},{error:"FIPS is enabled but this partition does not support FIPS",type:rq}],type:rB},{conditions:rQ,rules:[{conditions:[rX],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:rG,headers:rG},type:rF}],type:rB}],type:rB},{error:"DualStack is enabled but this partition does not support DualStack",type:rq}],type:rB},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:rG,headers:rG},type:rF}],type:rB}],type:rB}],type:rB},{error:"Invalid Configuration: Missing Region",type:rq}],type:rB}]},r2=new R({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),r3=(e,t={})=>r2.get(e,()=>ee(r1,{endpointParams:e,logger:t.logger}));I.aws=es;let r4=e=>({apiVersion:"2023-09-30",base64Decoder:e?.base64Decoder??rv.G,base64Encoder:e?.base64Encoder??rv.s,disableHostPrefix:e?.disableHostPrefix??!1,endpointProvider:e?.endpointProvider??r3,extensions:e?.extensions??[],httpAuthSchemeProvider:e?.httpAuthSchemeProvider??tT,httpAuthSchemes:e?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new rM}],logger:e?.logger??new ez.vk,serviceId:e?.serviceId??"Bedrock Runtime",urlParser:e?.urlParser??r$.e,utf8Decoder:e?.utf8Decoder??e3.$,utf8Encoder:e?.utf8Encoder??rN.G}),r6=(e,t,r)=>{let n,s,i;let o=!1,a=async()=>{s||(s=e());try{n=await s,i=!0,o=!1}finally{s=void 0}return n};return void 0===t?async e=>((!i||e?.forceRefresh)&&(n=await a()),n):async e=>((!i||e?.forceRefresh)&&(n=await a()),o||(r&&!r(n)?o=!0:t(n)&&await a()),n)},r5=["in-region","cross-region","mobile","standard","legacy"],r8=({defaultsMode:e}={})=>r6(async()=>{let t="function"==typeof e?await e():e;switch(t?.toLowerCase()){case"auto":return Promise.resolve(r9()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${r5.join(", ")}, got ${t}`)}}),r9=()=>{let e="undefined"!=typeof window&&window?.navigator?.userAgent?t0().parse(window.navigator.userAgent):void 0,t=e?.platform?.type;return"tablet"===t||"mobile"===t},r7=e=>{let t=r8(e),r=()=>t().then(ez.jv),n=r4(e);return{...n,...e,runtime:"browser",defaultsMode:t,bodyLengthChecker:e?.bodyLengthChecker??rR,credentialDefaultProvider:e?.credentialDefaultProvider??(e=>()=>Promise.reject(Error("Credential is missing"))),defaultUserAgentProvider:e?.defaultUserAgentProvider??t1({serviceId:n.serviceId,clientVersion:tN.i8}),eventStreamSerdeProvider:e?.eventStreamSerdeProvider??ry,maxAttempts:e?.maxAttempts??3,region:e?.region??rA("Region is missing"),requestHandler:rw.create(e?.requestHandler??r),retryMode:e?.retryMode??(async()=>(await r()).retryMode||ex),sha256:e?.sha256??tY,streamCollector:e?.streamCollector??r_,useDualstackEndpoint:e?.useDualstackEndpoint??(()=>Promise.resolve(!1)),useFipsEndpoint:e?.useFipsEndpoint??(()=>Promise.resolve(!1))}},ne=e=>{let t=async()=>{if(void 0===e.region)throw Error("Region is missing from runtimeConfig");let t=e.region;return"string"==typeof t?t:t()};return{setRegion(e){t=e},region:()=>t}},nt=e=>({region:e.region()}),nr=e=>{let t=e.httpAuthSchemes,r=e.httpAuthSchemeProvider,n=e.credentials;return{setHttpAuthScheme(e){let r=t.findIndex(t=>t.schemeId===e.schemeId);-1===r?t.push(e):t.splice(r,1,e)},httpAuthSchemes:()=>t,setHttpAuthSchemeProvider(e){r=e},httpAuthSchemeProvider:()=>r,setCredentials(e){n=e},credentials:()=>n}},nn=e=>({httpAuthSchemes:e.httpAuthSchemes(),httpAuthSchemeProvider:e.httpAuthSchemeProvider(),credentials:e.credentials()}),ns=e=>e,ni=(e,t)=>{let r={...ns(ne(e)),...ns((0,ez.kE)(e)),...ns((0,f.cA)(e)),...ns(nr(e))};return t.forEach(e=>e.configure(r)),{...e,...nt(r),...(0,ez.SQ)(r),...(0,f.AO)(r),...nn(r)}};class no extends ez.KU{constructor(...[e]){let t=r7(e||{}),r=ew(eW(function(e){let t=(0,A.$E)(e.userAgentAppId??x);return{...e,customUserAgent:"string"==typeof e.customUserAgent?[[e.customUserAgent]]:e.customUserAgent,userAgentAppId:async()=>{let r=await t();if(!(void 0===r||"string"==typeof r&&r.length<=50)){let t=e.logger?.constructor?.name!=="NoOpLogger"&&e.logger?e.logger:console;"string"!=typeof r?t?.warn("userAgentAppId must be a string or undefined."):r.length>50&&t?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}}}((0,t$.z)(t)))),n=ni(tM(ev((0,eA.uW)(r))),e?.extensions||[]);super(n),this.config=n,this.middlewareStack.use(em(this.config)),this.middlewareStack.use(eY(this.config)),this.middlewareStack.use(eE(this.config)),this.middlewareStack.use(m(this.config)),this.middlewareStack.use(b(this.config)),this.middlewareStack.use(E(this.config)),this.middlewareStack.use((0,A.tZ)(this.config,{httpAuthSchemeParametersProvider:tI,identityProviderConfigProvider:async e=>new A.K5({"aws.auth#sigv4":e.credentials})})),this.middlewareStack.use((0,A.aZ)(this.config))}destroy(){super.destroy()}}},44971:function(e,t,r){"use strict";r.d(t,{L:function(){return eE}});var n,s,i,o,a,l,c,u,d,f,h,p,m,g,y,b=r(93833),w=r(14464),v=r(35023),_=r(47375);class S extends v.sI{constructor(e){super(e),Object.setPrototypeOf(this,S.prototype)}}class E extends S{constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),this.name="AccessDeniedException",this.$fault="client",Object.setPrototypeOf(this,E.prototype)}}(n||(n={})).visit=(e,t)=>void 0!==e.text?t.text(e.text):t._(e.$unknown[0],e.$unknown[1]);class A extends S{constructor(e){super({name:"InternalServerException",$fault:"server",...e}),this.name="InternalServerException",this.$fault="server",Object.setPrototypeOf(this,A.prototype)}}class x extends S{constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),this.name="ResourceNotFoundException",this.$fault="client",Object.setPrototypeOf(this,x.prototype)}}class R extends S{constructor(e){super({name:"ServiceQuotaExceededException",$fault:"client",...e}),this.name="ServiceQuotaExceededException",this.$fault="client",Object.setPrototypeOf(this,R.prototype)}}class O extends S{constructor(e){super({name:"ThrottlingException",$fault:"client",...e}),this.name="ThrottlingException",this.$fault="client",Object.setPrototypeOf(this,O.prototype)}}class k extends S{constructor(e){super({name:"ValidationException",$fault:"client",...e}),this.name="ValidationException",this.$fault="client",Object.setPrototypeOf(this,k.prototype)}}(s||(s={})).visit=(e,t)=>void 0!==e.bytes?t.bytes(e.bytes):t._(e.$unknown[0],e.$unknown[1]),(i||(i={})).visit=(e,t)=>void 0!==e.text?t.text(e.text):t._(e.$unknown[0],e.$unknown[1]),(o||(o={})).visit=(e,t)=>void 0!==e.bytes?t.bytes(e.bytes):t._(e.$unknown[0],e.$unknown[1]),(a||(a={})).visit=(e,t)=>void 0!==e.json?t.json(e.json):void 0!==e.text?t.text(e.text):void 0!==e.image?t.image(e.image):void 0!==e.document?t.document(e.document):t._(e.$unknown[0],e.$unknown[1]),(l||(l={})).visit=(e,t)=>void 0!==e.text?t.text(e.text):void 0!==e.image?t.image(e.image):void 0!==e.document?t.document(e.document):void 0!==e.toolUse?t.toolUse(e.toolUse):void 0!==e.toolResult?t.toolResult(e.toolResult):void 0!==e.guardContent?t.guardContent(e.guardContent):t._(e.$unknown[0],e.$unknown[1]),(c||(c={})).visit=(e,t)=>void 0!==e.text?t.text(e.text):void 0!==e.guardContent?t.guardContent(e.guardContent):t._(e.$unknown[0],e.$unknown[1]),(u||(u={})).visit=(e,t)=>void 0!==e.auto?t.auto(e.auto):void 0!==e.any?t.any(e.any):void 0!==e.tool?t.tool(e.tool):t._(e.$unknown[0],e.$unknown[1]),(d||(d={})).visit=(e,t)=>void 0!==e.json?t.json(e.json):t._(e.$unknown[0],e.$unknown[1]),(f||(f={})).visit=(e,t)=>void 0!==e.toolSpec?t.toolSpec(e.toolSpec):t._(e.$unknown[0],e.$unknown[1]),(h||(h={})).visit=(e,t)=>void 0!==e.message?t.message(e.message):t._(e.$unknown[0],e.$unknown[1]);class P extends S{constructor(e){super({name:"ModelErrorException",$fault:"client",...e}),this.name="ModelErrorException",this.$fault="client",Object.setPrototypeOf(this,P.prototype),this.originalStatusCode=e.originalStatusCode,this.resourceName=e.resourceName}}class C extends S{constructor(e){super({name:"ModelNotReadyException",$fault:"client",...e}),this.name="ModelNotReadyException",this.$fault="client",this.$retryable={},Object.setPrototypeOf(this,C.prototype)}}class I extends S{constructor(e){super({name:"ModelTimeoutException",$fault:"client",...e}),this.name="ModelTimeoutException",this.$fault="client",Object.setPrototypeOf(this,I.prototype)}}class T extends S{constructor(e){super({name:"ServiceUnavailableException",$fault:"server",...e}),this.name="ServiceUnavailableException",this.$fault="server",Object.setPrototypeOf(this,T.prototype)}}(p||(p={})).visit=(e,t)=>void 0!==e.text?t.text(e.text):void 0!==e.toolUse?t.toolUse(e.toolUse):t._(e.$unknown[0],e.$unknown[1]),(m||(m={})).visit=(e,t)=>void 0!==e.toolUse?t.toolUse(e.toolUse):t._(e.$unknown[0],e.$unknown[1]);class M extends S{constructor(e){super({name:"ModelStreamErrorException",$fault:"client",...e}),this.name="ModelStreamErrorException",this.$fault="client",Object.setPrototypeOf(this,M.prototype),this.originalStatusCode=e.originalStatusCode,this.originalMessage=e.originalMessage}}(g||(g={})).visit=(e,t)=>void 0!==e.messageStart?t.messageStart(e.messageStart):void 0!==e.contentBlockStart?t.contentBlockStart(e.contentBlockStart):void 0!==e.contentBlockDelta?t.contentBlockDelta(e.contentBlockDelta):void 0!==e.contentBlockStop?t.contentBlockStop(e.contentBlockStop):void 0!==e.messageStop?t.messageStop(e.messageStop):void 0!==e.metadata?t.metadata(e.metadata):void 0!==e.internalServerException?t.internalServerException(e.internalServerException):void 0!==e.modelStreamErrorException?t.modelStreamErrorException(e.modelStreamErrorException):void 0!==e.validationException?t.validationException(e.validationException):void 0!==e.throttlingException?t.throttlingException(e.throttlingException):void 0!==e.serviceUnavailableException?t.serviceUnavailableException(e.serviceUnavailableException):t._(e.$unknown[0],e.$unknown[1]),(y||(y={})).visit=(e,t)=>void 0!==e.chunk?t.chunk(e.chunk):void 0!==e.internalServerException?t.internalServerException(e.internalServerException):void 0!==e.modelStreamErrorException?t.modelStreamErrorException(e.modelStreamErrorException):void 0!==e.validationException?t.validationException(e.validationException):void 0!==e.throttlingException?t.throttlingException(e.throttlingException):void 0!==e.modelTimeoutException?t.modelTimeoutException(e.modelTimeoutException):void 0!==e.serviceUnavailableException?t.serviceUnavailableException(e.serviceUnavailableException):t._(e.$unknown[0],e.$unknown[1]);let $=e=>({...e,...e.body&&{body:v.oc}}),N=e=>({...e,...e.body&&{body:"STREAMING_CONTENT"}}),j=(e,t)=>(0,v.Wg)(e,t).then(e=>t.utf8Encoder(e)),U=(e,t)=>j(e,t).then(e=>{if(e.length)try{return JSON.parse(e)}catch(t){throw t?.name==="SyntaxError"&&Object.defineProperty(t,"$responseBodyText",{value:e}),t}return{}}),D=async(e,t)=>{let r=await U(e,t);return r.message=r.message??r.Message,r},L=(e,t)=>{let r,n;let s=e=>{let t=e;return"number"==typeof t&&(t=t.toString()),t.indexOf(",")>=0&&(t=t.split(",")[0]),t.indexOf(":")>=0&&(t=t.split(":")[0]),t.indexOf("#")>=0&&(t=t.split("#")[1]),t},i=(r=e.headers,n="x-amzn-errortype",Object.keys(r).find(e=>e.toLowerCase()===n.toLowerCase()));return void 0!==i?s(e.headers[i]):void 0!==t.code?s(t.code):void 0!==t.__type?s(t.__type):void 0};var q=r(53620);let F=async(e,t)=>{let r;let n=(0,q.cu)(e,t),s=(0,v.UI)({},v.gj,{[ep]:e[eh]||"application/octet-stream",[eb]:e[ef],[eS]:e[ey],[ev]:e[em],[e_]:e[eg]});return n.bp("/model/{modelId}/invoke-with-response-stream"),n.p("modelId",()=>e.modelId,"{modelId}",!1),void 0!==e.body&&(r=e.body),n.m("POST").h(s).b(r),n.build()},B=async(e,t)=>{if(200!==e.statusCode&&e.statusCode>=300)return H(e,t);let r=(0,v.UI)({$metadata:ed(e),[eh]:[,e.headers[ew]]}),n=e.body;return r.body=er(n,t),r},H=async(e,t)=>{let r={...e,body:await D(e.body,t)},n=L(e,r.body);switch(n){case"AccessDeniedException":case"com.amazonaws.bedrockruntime#AccessDeniedException":throw await z(r,t);case"InternalServerException":case"com.amazonaws.bedrockruntime#InternalServerException":throw await K(r,t);case"ResourceNotFoundException":case"com.amazonaws.bedrockruntime#ResourceNotFoundException":throw await X(r,t);case"ServiceQuotaExceededException":case"com.amazonaws.bedrockruntime#ServiceQuotaExceededException":throw await Y(r,t);case"ThrottlingException":case"com.amazonaws.bedrockruntime#ThrottlingException":throw await ee(r,t);case"ValidationException":case"com.amazonaws.bedrockruntime#ValidationException":throw await et(r,t);case"ModelErrorException":case"com.amazonaws.bedrockruntime#ModelErrorException":throw await V(r,t);case"ModelNotReadyException":case"com.amazonaws.bedrockruntime#ModelNotReadyException":throw await J(r,t);case"ModelTimeoutException":case"com.amazonaws.bedrockruntime#ModelTimeoutException":throw await Z(r,t);case"ServiceUnavailableException":case"com.amazonaws.bedrockruntime#ServiceUnavailableException":throw await Q(r,t);case"ModelStreamErrorException":case"com.amazonaws.bedrockruntime#ModelStreamErrorException":throw await G(r,t);default:return W({output:e,parsedBody:r.body,errorCode:n})}},W=(0,v.PC)(S),z=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new E({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},K=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new A({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},V=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY,originalStatusCode:v.u$,resourceName:v.pY}));let s=new P({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},J=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new C({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},G=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY,originalMessage:v.pY,originalStatusCode:v.u$}));let s=new M({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},Z=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new I({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},X=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new x({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},Y=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new R({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},Q=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new T({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},ee=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new O({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},et=async(e,t)=>{let r=(0,v.UI)({}),n=e.body;Object.assign(r,(0,v.qn)(n,{message:v.pY}));let s=new k({$metadata:ed(e),...r});return(0,v.to)(s,e.body)},er=(e,t)=>t.eventStreamMarshaller.deserialize(e,async r=>null!=r.chunk?{chunk:await eo(r.chunk,t)}:null!=r.internalServerException?{internalServerException:await en(r.internalServerException,t)}:null!=r.modelStreamErrorException?{modelStreamErrorException:await es(r.modelStreamErrorException,t)}:null!=r.validationException?{validationException:await ec(r.validationException,t)}:null!=r.throttlingException?{throttlingException:await el(r.throttlingException,t)}:null!=r.modelTimeoutException?{modelTimeoutException:await ei(r.modelTimeoutException,t)}:null!=r.serviceUnavailableException?{serviceUnavailableException:await ea(r.serviceUnavailableException,t)}:{$unknown:e}),en=async(e,t)=>K({...e,body:await U(e.body,t)},t),es=async(e,t)=>G({...e,body:await U(e.body,t)},t),ei=async(e,t)=>Z({...e,body:await U(e.body,t)},t),eo=async(e,t)=>{let r={};return Object.assign(r,eu(await U(e.body,t),t)),r},ea=async(e,t)=>Q({...e,body:await U(e.body,t)},t),el=async(e,t)=>ee({...e,body:await U(e.body,t)},t),ec=async(e,t)=>et({...e,body:await U(e.body,t)},t),eu=(e,t)=>(0,v.qn)(e,{bytes:t.base64Decoder}),ed=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),ef="accept",eh="contentType",ep="content-type",em="guardrailIdentifier",eg="guardrailVersion",ey="trace",eb="x-amzn-bedrock-accept",ew="x-amzn-bedrock-content-type",ev="x-amzn-bedrock-guardrailidentifier",e_="x-amzn-bedrock-guardrailversion",eS="x-amzn-bedrock-trace";class eE extends v.mY.classBuilder().ep(_.q).m(function(e,t,r,n){return[(0,w.p2)(r,this.serialize,this.deserialize),(0,b.a3)(r,e.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","InvokeModelWithResponseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","InvokeModelWithResponseStreamCommand").f($,N).ser(F).de(B).build(){}},47375:function(e,t,r){"use strict";r.d(t,{q:function(){return s},z:function(){return n}});let n=e=>({...e,useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),s={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}},74089:function(e,t,r){"use strict";r.d(t,{_:function(){return n}});class n extends Error{constructor(e){super(e),this.name="AbortError"}}},29506:function(e,t,r){"use strict";r.d(t,{s5:function(){return n},cQ:function(){return s}});class n{get key(){return this._key}constructor(e){if(!e)throw Error("key must be a non-empty string");this._key=e}update(e){this._key=e}}function s(e){return e&&"function"==typeof e.getToken&&(void 0===e.signRequest||e.getToken.length>0)}r(56380)},56380:function(e,t,r){"use strict";var n,s,i,o,a;function l(e,t){return e=Math.ceil(e),Math.floor(Math.random()*((t=Math.floor(t))-e+1))+e}function c(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function u(e){if(c(e)){let t="string"==typeof e.name,r="string"==typeof e.message;return t&&r}return!1}function d(e){if(u(e))return e.message;{let t;try{t="object"==typeof e&&e?JSON.stringify(e):String(e)}catch(e){t="[unable to stringify input]"}return`Unknown error ${t}`}}function f(e,t){switch(t){case"utf-8":return new TextEncoder().encode(e);case"base64":return h(e);case"base64url":return h(e.replace(/-/g,"+").replace(/_/g,"/"));case"hex":return function(e){let t=new Uint8Array(e.length/2);for(let r=0;r<e.length/2;++r){let n=e[2*r],s=e[2*r+1];if(!p.has(n)||!p.has(s))return t.slice(0,r);t[r]=parseInt(`${n}${s}`,16)}return t}(e)}}function h(e){return new Uint8Array([...atob(e)].map(e=>e.charCodeAt(0)))}r.d(t,{e$:function(){return d},b1:function(){return l},VZ:function(){return u},Lr:function(){return y},Kn:function(){return c},HP:function(){return g},sy:function(){return f}}),r(74089);let p=new Set("0123456789abcdefABCDEF"),m="function"==typeof(null===(n=null==globalThis?void 0:globalThis.crypto)||void 0===n?void 0:n.randomUUID)?globalThis.crypto.randomUUID.bind(globalThis.crypto):function(){let e="";for(let t=0;t<32;t++){let r=Math.floor(16*Math.random());12===t?e+="4":16===t?e+=3&r|8:e+=r.toString(16),(7===t||11===t||15===t||19===t)&&(e+="-")}return e};function g(){return m()}"undefined"!=typeof window&&window.document,"object"==typeof self&&"function"==typeof(null==self?void 0:self.importScripts)&&((null===(s=self.constructor)||void 0===s?void 0:s.name)==="DedicatedWorkerGlobalScope"||(null===(i=self.constructor)||void 0===i?void 0:i.name)==="ServiceWorkerGlobalScope"||null===(o=self.constructor)||void 0===o||o.name),"undefined"!=typeof Deno&&void 0!==Deno.version&&Deno.version.deno,"undefined"!=typeof Bun&&Bun.version;let y=void 0!==globalThis.process&&!!globalThis.process.version&&!!(null===(a=globalThis.process.versions)||void 0===a?void 0:a.node);"undefined"!=typeof navigator&&(null==navigator||navigator.product)},71877:function(e,t,r){"use strict";let n,s,i;r.d(t,{D:function(){return te}});var o,a,l=r(60160),c=r(29506);let u=new Set(["Deserialize","Serialize","Retry","Sign"]);class d{constructor(e){var t;this._policies=[],this._policies=null!==(t=null==e?void 0:e.slice(0))&&void 0!==t?t:[],this._orderedPolicies=void 0}addPolicy(e,t={}){if(t.phase&&t.afterPhase)throw Error("Policies inside a phase cannot specify afterPhase.");if(t.phase&&!u.has(t.phase))throw Error(`Invalid phase name: ${t.phase}`);if(t.afterPhase&&!u.has(t.afterPhase))throw Error(`Invalid afterPhase name: ${t.afterPhase}`);this._policies.push({policy:e,options:t}),this._orderedPolicies=void 0}removePolicy(e){let t=[];return this._policies=this._policies.filter(r=>(!e.name||r.policy.name!==e.name)&&(!e.phase||r.options.phase!==e.phase)||(t.push(r.policy),!1)),this._orderedPolicies=void 0,t}sendRequest(e,t){return this.getOrderedPolicies().reduceRight((e,t)=>r=>t.sendRequest(r,e),t=>e.sendRequest(t))(t)}getOrderedPolicies(){return this._orderedPolicies||(this._orderedPolicies=this.orderPolicies()),this._orderedPolicies}clone(){return new d(this._policies)}static create(){return new d}orderPolicies(){let e=[],t=new Map;function r(e){return{name:e,policies:new Set,hasRun:!1,hasAfterPolicies:!1}}let n=r("Serialize"),s=r("None"),i=r("Deserialize"),o=r("Retry"),a=r("Sign"),l=[n,s,i,o,a];function c(e){return"Retry"===e?o:"Serialize"===e?n:"Deserialize"===e?i:"Sign"===e?a:s}for(let e of this._policies){let r=e.policy,n=e.options,s=r.name;if(t.has(s))throw Error("Duplicate policy names not allowed in pipeline");let i={policy:r,dependsOn:new Set,dependants:new Set};n.afterPhase&&(i.afterPhase=c(n.afterPhase),i.afterPhase.hasAfterPolicies=!0),t.set(s,i),c(n.phase).policies.add(i)}for(let e of this._policies){let{policy:r,options:n}=e,s=r.name,i=t.get(s);if(!i)throw Error(`Missing node for policy ${s}`);if(n.afterPolicies)for(let e of n.afterPolicies){let r=t.get(e);r&&(i.dependsOn.add(r),r.dependants.add(i))}if(n.beforePolicies)for(let e of n.beforePolicies){let r=t.get(e);r&&(r.dependsOn.add(i),i.dependants.add(r))}}function u(r){for(let n of(r.hasRun=!0,r.policies))if((!n.afterPhase||n.afterPhase.hasRun&&!n.afterPhase.policies.size)&&0===n.dependsOn.size){for(let t of(e.push(n.policy),n.dependants))t.dependsOn.delete(n);t.delete(n.policy.name),r.policies.delete(n)}}let d=0;for(;t.size>0;){d++;let t=e.length;if(!function(){for(let e of l){if(u(e),e.policies.size>0&&e!==s){s.hasRun||u(s);return}e.hasAfterPolicies&&u(s)}}(),e.length<=t&&d>1)throw Error("Cannot satisfy policy dependencies due to requirements cycle.")}return e}}var f=r(25566);let h=void 0!==f&&f.env&&f.env.DEBUG||void 0,p=[],m=[],g=[];h&&b(h);let y=Object.assign(e=>v(e),{enable:b,enabled:w,disable:function(){let e=n||"";return b(""),e},log:function(...e){if(e.length>0){let t=String(e[0]);t.includes(":error")?console.error(...e):t.includes(":warning")?console.warn(...e):t.includes(":info")?console.info(...e):(t.includes(":verbose"),console.debug(...e))}}});function b(e){n=e,p=[],m=[];let t=/\*/g;for(let r of e.split(",").map(e=>e.trim().replace(t,".*?")))r.startsWith("-")?m.push(RegExp(`^${r.substr(1)}$`)):p.push(RegExp(`^${r}$`));for(let e of g)e.enabled=w(e.namespace)}function w(e){if(e.endsWith("*"))return!0;for(let t of m)if(t.test(e))return!1;for(let t of p)if(t.test(e))return!0;return!1}function v(e){let t=Object.assign(function(...r){t.enabled&&(r.length>0&&(r[0]=`${e} ${r[0]}`),t.log(...r))},{enabled:w(e),destroy:_,log:y.log,namespace:e,extend:S});return g.push(t),t}function _(){let e=g.indexOf(this);return e>=0&&(g.splice(e,1),!0)}function S(e){let t=v(`${this.namespace}:${e}`);return t.log=this.log,t}var E=r(25566);let A=new Set,x=void 0!==E&&E.env&&E.env.AZURE_LOG_LEVEL||void 0,R=y("azure");R.log=(...e)=>{y.log(...e)};let O=["verbose","info","warning","error"];x&&(M(x)?function(e){if(e&&!M(e))throw Error(`Unknown log level '${e}'. Acceptable values: ${O.join(",")}`);s=e;let t=[];for(let e of A)T(e)&&t.push(e.namespace);y.enable(t.join(","))}(x):console.error(`AZURE_LOG_LEVEL set to unknown log level '${x}'; logging is not enabled. Acceptable values: ${O.join(", ")}.`));let k={verbose:400,info:300,warning:200,error:100};function P(e){let t=R.extend(e);return C(R,t),{error:I(t,"error"),warning:I(t,"warning"),info:I(t,"info"),verbose:I(t,"verbose")}}function C(e,t){t.log=(...t)=>{e.log(...t)}}function I(e,t){let r=Object.assign(e.extend(t),{level:t});if(C(e,r),T(r)){let e=y.disable();y.enable(e+","+r.namespace)}return A.add(r),r}function T(e){return!!(s&&k[e.level]<=k[s])}function M(e){return O.includes(e)}let $=P("core-rest-pipeline");var N=r(56380);let j="REDACTED",U=["x-ms-client-request-id","x-ms-return-client-request-id","x-ms-useragent","x-ms-correlation-request-id","x-ms-request-id","client-request-id","ms-cv","return-client-request-id","traceparent","Access-Control-Allow-Credentials","Access-Control-Allow-Headers","Access-Control-Allow-Methods","Access-Control-Allow-Origin","Access-Control-Expose-Headers","Access-Control-Max-Age","Access-Control-Request-Headers","Access-Control-Request-Method","Origin","Accept","Accept-Encoding","Cache-Control","Connection","Content-Length","Content-Type","Date","ETag","Expires","If-Match","If-Modified-Since","If-None-Match","If-Unmodified-Since","Last-Modified","Pragma","Request-Id","Retry-After","Server","Transfer-Encoding","User-Agent","WWW-Authenticate"],D=["api-version"];class L{constructor({additionalAllowedHeaderNames:e=[],additionalAllowedQueryParameters:t=[]}={}){e=U.concat(e),t=D.concat(t),this.allowedHeaderNames=new Set(e.map(e=>e.toLowerCase())),this.allowedQueryParameters=new Set(t.map(e=>e.toLowerCase()))}sanitize(e){let t=new Set;return JSON.stringify(e,(e,r)=>{if(r instanceof Error)return Object.assign(Object.assign({},r),{name:r.name,message:r.message});if("headers"===e)return this.sanitizeHeaders(r);if("url"===e)return this.sanitizeUrl(r);if("query"===e)return this.sanitizeQuery(r);if("body"!==e){if("response"===e)return;if("operationSpec"===e)return;else if(Array.isArray(r)||(0,N.Kn)(r)){if(t.has(r))return"[Circular]";t.add(r)}return r}},2)}sanitizeHeaders(e){let t={};for(let r of Object.keys(e))this.allowedHeaderNames.has(r.toLowerCase())?t[r]=e[r]:t[r]=j;return t}sanitizeQuery(e){if("object"!=typeof e||null===e)return e;let t={};for(let r of Object.keys(e))this.allowedQueryParameters.has(r.toLowerCase())?t[r]=e[r]:t[r]=j;return t}sanitizeUrl(e){if("string"!=typeof e||null===e)return e;let t=new URL(e);if(!t.search)return e;for(let[e]of t.searchParams)this.allowedQueryParameters.has(e.toLowerCase())||t.searchParams.set(e,j);return t.toString()}}let q=["GET","HEAD"];async function F(e,t,r,n=0){let{request:s,status:i,headers:o}=t,a=o.get("location");if(a&&(300===i||301===i&&q.includes(s.method)||302===i&&q.includes(s.method)||303===i&&"POST"===s.method||307===i)&&n<r){let t=new URL(a,s.url);s.url=t.toString(),303===i&&(s.method="GET",s.headers.delete("Content-Length"),delete s.body),s.headers.delete("Authorization");let o=await e(s);return F(e,o,r,n+1)}return t}let B="1.16.0";function H(e){let t=new Map;t.set("core-rest-pipeline",B),function(e){var t,r,n;let s=globalThis.navigator;e.set("OS",(null!==(n=null!==(r=null===(t=null==s?void 0:s.userAgentData)||void 0===t?void 0:t.platform)&&void 0!==r?r:null==s?void 0:s.platform)&&void 0!==n?n:"unknown").replace(" ",""))}(t);let r=function(e){let t=[];for(let[r,n]of e){let e=n?`${r}/${n}`:r;t.push(e)}return t.join(" ")}(t);return e?`${e} ${r}`:r}let W="x-ms-useragent",z={arrayBuffer:()=>{throw Error("Not implemented")},slice:()=>{throw Error("Not implemented")},text:()=>{throw Error("Not implemented")}},K=Symbol("rawContent");function V(e,t,r={}){var n,s,i;return N.Lr?Object.assign(Object.assign({},z),{type:null!==(n=r.type)&&void 0!==n?n:"",lastModified:null!==(s=r.lastModified)&&void 0!==s?s:new Date().getTime(),webkitRelativePath:null!==(i=r.webkitRelativePath)&&void 0!==i?i:"",size:e.byteLength,name:t,arrayBuffer:async()=>e.buffer,stream:()=>new Blob([e]).stream(),[K]:()=>e}):new File([e],t,r)}function J(e){return!!(e&&"function"==typeof e.pipe)}function G(e){return!!(e&&"function"==typeof e.getReader&&"function"==typeof e.tee)}async function Z(e){if(e instanceof Blob||e instanceof Uint8Array)return e;if(G(e))return new Response(e).blob();let t="function"==typeof e[K]?e[K]():e.stream();if(J(t))throw Error("Encountered unexpected type. In the browser, `concat` supports Web ReadableStream, Blob, Uint8Array, and files created using `createFile` only.");return Z(t)}async function X(e){let t=[];for(let r of e)t.push(await Z("function"==typeof r?r():r));return new Blob(t)}async function Y(e,t,r){let n=[(0,N.sy)(`--${r}`,"utf-8"),...t.flatMap(e=>[(0,N.sy)("\r\n","utf-8"),(0,N.sy)(function(e){let t="";for(let[r,n]of e)t+=`${r}: ${n}\r
`;return t}(e.headers),"utf-8"),(0,N.sy)("\r\n","utf-8"),e.body,(0,N.sy)(`\r
--${r}`,"utf-8")]),(0,N.sy)("--\r\n\r\n","utf-8")],s=function(e){let t=0;for(let r of e){let e=r instanceof Uint8Array?r.byteLength:"function"==typeof r.stream?-1===r.size?void 0:r.size:void 0;if(void 0===e)return;t+=e}return t}(n);s&&e.headers.set("Content-Length",s),e.body=await X(n)}let Q="multipartPolicy",ee=new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?");var et=r(74089);function er(e,t,r){return new Promise((n,s)=>{let i,o;let a=()=>s(new et._((null==r?void 0:r.abortErrorMsg)?null==r?void 0:r.abortErrorMsg:"The operation was aborted.")),l=()=>{(null==r?void 0:r.abortSignal)&&o&&r.abortSignal.removeEventListener("abort",o)};if(o=()=>(i&&clearTimeout(i),l(),a()),(null==r?void 0:r.abortSignal)&&r.abortSignal.aborted)return a();i=setTimeout(()=>{l(),n(t)},e),(null==r?void 0:r.abortSignal)&&r.abortSignal.addEventListener("abort",o)})}let en="Retry-After",es=["retry-after-ms","x-ms-retry-after-ms",en];function ei(e){if(e&&[429,503].includes(e.status))try{for(let t of es){let r=function(e,t){let r=e.headers.get(t);if(!r)return;let n=Number(r);if(!Number.isNaN(n))return n}(e,t);if(0===r||r){let e=t===en?1e3:1;return r*e}}let t=e.headers.get(en);if(!t)return;let r=Date.parse(t)-Date.now();return Number.isFinite(r)?Math.max(0,r):void 0}catch(e){return}}let eo=P("core-rest-pipeline retryPolicy");function ea(e){return e.toLowerCase()}class el{constructor(e){if(this._headersMap=new Map,e)for(let t of Object.keys(e))this.set(t,e[t])}set(e,t){this._headersMap.set(ea(e),{name:e,value:String(t).trim()})}get(e){var t;return null===(t=this._headersMap.get(ea(e)))||void 0===t?void 0:t.value}has(e){return this._headersMap.has(ea(e))}delete(e){this._headersMap.delete(ea(e))}toJSON(e={}){let t={};if(e.preserveCase)for(let e of this._headersMap.values())t[e.name]=e.value;else for(let[e,r]of this._headersMap)t[e]=r.value;return t}toString(){return JSON.stringify(this.toJSON({preserveCase:!0}))}[Symbol.iterator](){return function*(e){for(let t of e.values())yield[t.name,t.value]}(this._headersMap)}}function ec(e){return new el(e)}async function eu(e,t){let r=t.headers.get("Content-Type");if(r&&!r.startsWith("multipart/form-data"))return;t.headers.set("Content-Type",null!=r?r:"multipart/form-data");let n=[];for(let[t,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])if("string"==typeof e)n.push({headers:ec({"Content-Disposition":`form-data; name="${t}"`}),body:(0,N.sy)(e,"utf-8")});else if(null==e||"object"!=typeof e)throw Error(`Unexpected value for key ${t}: ${e}. Value should be serialized to string first.`);else{let r=e.name||"blob",s=ec();s.set("Content-Disposition",`form-data; name="${t}"; filename="${r}"`),s.set("Content-Type",e.type||"application/octet-stream"),n.push({headers:s,body:e})}t.multipartBody={parts:n}}let ed={span:Symbol.for("@azure/core-tracing span"),namespace:Symbol.for("@azure/core-tracing namespace")};class ef{constructor(e){this._contextMap=e instanceof ef?new Map(e._contextMap):new Map}setValue(e,t){let r=new ef(this);return r._contextMap.set(e,t),r}getValue(e){return this._contextMap.get(e)}deleteValue(e){let t=new ef(this);return t._contextMap.delete(e),t}}let eh={instrumenterImplementation:void 0};function ep(){return eh.instrumenterImplementation||(eh.instrumenterImplementation={createRequestHeaders:()=>({}),parseTraceparentHeader:()=>{},startSpan:(e,t)=>({span:{end:()=>{},isRecording:()=>!1,recordException:()=>{},setAttribute:()=>{},setStatus:()=>{},addEvent:()=>{}},tracingContext:function(e={}){let t=new ef(e.parentContext);return e.span&&(t=t.setValue(ed.span,e.span)),e.namespace&&(t=t.setValue(ed.namespace,e.namespace)),t}({parentContext:t.tracingContext})}),withContext:(e,t,...r)=>t(...r)}),eh.instrumenterImplementation}let em={},eg=new L;class ey extends Error{constructor(e,t={}){super(e),this.name="RestError",this.code=t.code,this.statusCode=t.statusCode,this.request=t.request,this.response=t.response,Object.setPrototypeOf(this,ey.prototype)}[em](){return`RestError: ${this.message} 
 ${eg.sanitize(this)}`}}ey.REQUEST_SEND_ERROR="REQUEST_SEND_ERROR",ey.PARSE_ERROR="PARSE_ERROR";class eb{async sendRequest(e){if("https:"!==new URL(e.url).protocol&&!e.allowInsecureConnection)throw Error(`Cannot connect to ${e.url} while allowInsecureConnection is false.`);if(e.proxySettings)throw Error("HTTP proxy is not supported in browser environment");try{return await ew(e)}catch(r){var t;throw r&&(null==r?void 0:r.name)==="AbortError"?r:new ey(`Error sending request: ${r.message}`,{code:null!==(t=null==r?void 0:r.code)&&void 0!==t?t:ey.REQUEST_SEND_ERROR,request:e})}}}async function ew(e){let{abortController:t,abortControllerCleanup:r}=function(e){let t,r;let n=new AbortController;if(e.abortSignal){if(e.abortSignal.aborted)throw new et._("The operation was aborted.");r=e=>{"abort"===e.type&&n.abort()},e.abortSignal.addEventListener("abort",r),t=()=>{var t;r&&(null===(t=e.abortSignal)||void 0===t||t.removeEventListener("abort",r))}}return e.timeout>0&&setTimeout(()=>{n.abort()},e.timeout),{abortController:n,abortControllerCleanup:t}}(e);try{var n;let s=function(e){let t=new Headers;for(let[r,n]of e)t.append(r,n);return t}(e.headers),{streaming:i,body:o}=function(e){let t="function"==typeof e.body?e.body():e.body;if(J(t))throw Error("Node streams are not supported in browser environment.");return G(t)?{streaming:!0,body:e_(t,{onProgress:e.onUploadProgress})}:{streaming:!1,body:t}}(e),a=Object.assign(Object.assign({body:o,method:e.method,headers:s,signal:t.signal},"credentials"in Request.prototype?{credentials:e.withCredentials?"include":"same-origin"}:{}),"cache"in Request.prototype?{cache:"no-store"}:{});i&&(a.duplex="half");let l=await fetch(e.url,a);return n=e.body,("function"==typeof Blob||"object"==typeof Blob)&&n instanceof Blob&&e.onUploadProgress&&e.onUploadProgress({loadedBytes:e.body.size}),ev(l,e,r)}catch(e){throw null==r||r(),e}}async function ev(e,t,r){var n,s;let i={request:t,headers:function(e){let t=ec();for(let[r,n]of e.headers)t.set(r,n);return t}(e),status:e.status},o=G(e.body)?e_(e.body,{onProgress:t.onDownloadProgress,onEnd:r}):e.body;if((null===(n=t.streamResponseStatusCodes)||void 0===n?void 0:n.has(Number.POSITIVE_INFINITY))||(null===(s=t.streamResponseStatusCodes)||void 0===s?void 0:s.has(i.status))){if(t.enableBrowserStreams)i.browserStreamBody=null!=o?o:void 0;else{let e=new Response(o);i.blobBody=e.blob(),null==r||r()}}else{let e=new Response(o);i.bodyAsText=await e.text(),null==r||r()}return i}function e_(e,t={}){let r=0,{onProgress:n,onEnd:s}=t;if(void 0!==e.pipeThrough&&void 0!==self.TransformStream)return e.pipeThrough(new TransformStream({transform(e,t){if(null===e){t.terminate();return}t.enqueue(e),r+=e.length,n&&n({loadedBytes:r})},flush(){null==s||s()}}));{let t=e.getReader();return new ReadableStream({async pull(e){var i;let{done:o,value:a}=await t.read();if(o||!a){null==s||s(),e.close(),t.releaseLock();return}r+=null!==(i=null==a?void 0:a.length)&&void 0!==i?i:0,e.enqueue(a),n&&n({loadedBytes:r})},cancel:e=>(null==s||s(),t.cancel(e))})}}class eS{constructor(e){var t,r,n,s,i,o,a;this.url=e.url,this.body=e.body,this.headers=null!==(t=e.headers)&&void 0!==t?t:ec(),this.method=null!==(r=e.method)&&void 0!==r?r:"GET",this.timeout=null!==(n=e.timeout)&&void 0!==n?n:0,this.multipartBody=e.multipartBody,this.formData=e.formData,this.disableKeepAlive=null!==(s=e.disableKeepAlive)&&void 0!==s&&s,this.proxySettings=e.proxySettings,this.streamResponseStatusCodes=e.streamResponseStatusCodes,this.withCredentials=null!==(i=e.withCredentials)&&void 0!==i&&i,this.abortSignal=e.abortSignal,this.tracingOptions=e.tracingOptions,this.onUploadProgress=e.onUploadProgress,this.onDownloadProgress=e.onDownloadProgress,this.requestId=e.requestId||(0,N.HP)(),this.allowInsecureConnection=null!==(o=e.allowInsecureConnection)&&void 0!==o&&o,this.enableBrowserStreams=null!==(a=e.enableBrowserStreams)&&void 0!==a&&a}}let eE={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:12e4};async function eA(e,t,r){async function n(){if(Date.now()<r)try{return await e()}catch(e){return null}else{let t=await e();if(null===t)throw Error("Failed to refresh access token.");return t}}let s=await n();for(;null===s;)await er(t),s=await n();return s}async function ex(e){let{scopes:t,getAccessToken:r,request:n}=e,s={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions},i=await r(t,s);i&&e.request.headers.set("Authorization",`Bearer ${i.token}`)}function eR(e){var t,r,n,s,i,o;return{allowInsecureConnection:null===(t=e.requestOptions)||void 0===t?void 0:t.allowInsecureConnection,timeout:null===(r=e.requestOptions)||void 0===r?void 0:r.timeout,skipUrlEncoding:null===(n=e.requestOptions)||void 0===n?void 0:n.skipUrlEncoding,abortSignal:e.abortSignal,onUploadProgress:null===(s=e.requestOptions)||void 0===s?void 0:s.onUploadProgress,onDownloadProgress:null===(i=e.requestOptions)||void 0===i?void 0:i.onDownloadProgress,tracingOptions:e.tracingOptions,headers:Object.assign({},null===(o=e.requestOptions)||void 0===o?void 0:o.headers),onResponse:e.onResponse}}async function eO(e,t,r,n={},s){var o;let a=null!=s?s:(i||(i=new eb),i),l=function(e,t,r={}){var n,s,i;let o=function(e={}){var t,r,n;return null!==(n=null!==(t=e.contentType)&&void 0!==t?t:null===(r=e.headers)||void 0===r?void 0:r["content-type"])&&void 0!==n?n:function(e){if(ArrayBuffer.isView(e))return"application/octet-stream";if("string"==typeof e)try{JSON.parse(e)}catch(e){return}return"application/json; charset=UTF-8"}(e.body)}(r),{body:a,formData:l}=function(e,t=""){if(void 0===e)return{body:void 0};if(e&&"function"==typeof e.getReader&&"function"==typeof e.tee)return{body:e};let r=t.split(";")[0];if("application/json"===r)return{body:JSON.stringify(e)};if(ArrayBuffer.isView(e))return{body:e instanceof Uint8Array?e:JSON.stringify(e)};switch(r){case"multipart/form-data":return void 0!==e&&e instanceof Object&&Object.values(e).every(e=>ek(e)||Array.isArray(e)&&e.every(ek))?{formData:function(e){let t={};for(let r in e){let n=e[r];t[r]=Array.isArray(n)?n.map(eP):eP(n)}return t}(e)}:{body:JSON.stringify(e)};case"text/plain":return{body:String(e)};default:if("string"==typeof e)return{body:e};return{body:JSON.stringify(e)}}}(r.body,o),c=ec(Object.assign(Object.assign(Object.assign({},r.headers?r.headers:{}),{accept:null!==(i=null!==(n=r.accept)&&void 0!==n?n:null===(s=r.headers)||void 0===s?void 0:s.accept)&&void 0!==i?i:"application/json"}),(void 0!==a||void 0!==l)&&o&&{"content-type":o}));return new eS({url:t,method:e,body:a,formData:l,headers:c,allowInsecureConnection:r.allowInsecureConnection,tracingOptions:r.tracingOptions,abortSignal:r.abortSignal,onUploadProgress:r.onUploadProgress,onDownloadProgress:r.onDownloadProgress,timeout:r.timeout,enableBrowserStreams:!0,streamResponseStatusCodes:r.responseAsStream?new Set([Number.POSITIVE_INFINITY]):void 0})}(e,t,n),c=await r.sendRequest(a,l),u=c.headers.toJSON(),d=null!==(o=c.readableStreamBody)&&void 0!==o?o:c.browserStreamBody,f=n.responseAsStream||void 0!==d?void 0:function(e){var t,r;let n=(null!==(t=e.headers.get("content-type"))&&void 0!==t?t:"").split(";")[0],s=null!==(r=e.bodyAsText)&&void 0!==r?r:"";if("text/plain"===n)return String(s);try{return s?JSON.parse(s):void 0}catch(t){if("application/json"===n)throw function(e,t){var r;let n=`Error "${t}" occurred while parsing the response body - ${e.bodyAsText}.`,s=null!==(r=t.code)&&void 0!==r?r:ey.PARSE_ERROR;return new ey(n,{code:s,statusCode:e.status,request:e.request,response:e})}(e,t);return String(s)}}(c),h=null!=d?d:f;return(null==n?void 0:n.onResponse)&&n.onResponse(Object.assign(Object.assign({},c),{request:l,rawHeaders:u,parsedBody:f})),{request:l,headers:u,status:`${c.status}`,body:h}}function ek(e){return"string"==typeof e||e instanceof Uint8Array||"function"==typeof e.stream}function eP(e){return e instanceof Uint8Array?V(e,"blob"):e}function eC(e,t,r,n,s,i){var o;return s=null!==(o=n.allowInsecureConnection)&&void 0!==o?o:s,{then:function(o,a){return eO(e,t,r,Object.assign(Object.assign({},n),{allowInsecureConnection:s}),i).then(o,a)},asBrowserStream:async()=>eO(e,t,r,Object.assign(Object.assign({},n),{allowInsecureConnection:s,responseAsStream:!0}),i),asNodeStream:async()=>eO(e,t,r,Object.assign(Object.assign({},n),{allowInsecureConnection:s,responseAsStream:!0}),i)}}let eI=P("openai");var eT=function(e,t,r={}){var n,s,i,o,a,l,u,f;let h=null!==(n=r.baseUrl)&&void 0!==n?n:`${e}/openai`;r.apiVersion=null!==(s=r.apiVersion)&&void 0!==s?s:"2024-03-01-preview";let p="azsdk-js-openai-rest/1.0.0-beta.12",m=r.userAgentOptions&&r.userAgentOptions.userAgentPrefix?`${r.userAgentOptions.userAgentPrefix} ${p}`:`${p}`;return function(e,t,r={}){var n,s;let i;t&&(void 0!==t.key||(0,c.cQ)(t)?i=t:r=null!=t?t:{});let o=function(e,t,r={}){let n=function(e){var t,r;let n=d.create();return N.Lr&&(e.tlsOptions&&n.addPolicy((r=e.tlsOptions,{name:"tlsPolicy",sendRequest:async(e,t)=>(e.tlsSettings||(e.tlsSettings=r),t(e))})),n.addPolicy(function(){throw Error("proxyPolicy is not supported in browser environment")}(e.proxyOptions)),n.addPolicy(function(){throw Error("decompressResponsePolicy is not supported in browser environment")}())),n.addPolicy({name:"formDataPolicy",async sendRequest(e,t){if(N.Lr&&"undefined"!=typeof FormData&&e.body instanceof FormData&&(e.formData=function(e){var t;let r={};for(let[n,s]of e.entries())null!==(t=r[n])&&void 0!==t||(r[n]=[]),r[n].push(s);return r}(e.body),e.body=void 0),e.formData){let t=e.headers.get("Content-Type");t&&-1!==t.indexOf("application/x-www-form-urlencoded")?e.body=function(e){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(Array.isArray(n))for(let e of n)t.append(r,e.toString());else t.append(r,n.toString());return t.toString()}(e.formData):await eu(e.formData,e),e.formData=void 0}return t(e)}},{beforePolicies:[Q]}),n.addPolicy(function(e={}){let t=H(e.userAgentPrefix);return{name:"userAgentPolicy",sendRequest:async(e,r)=>(e.headers.has(W)||e.headers.set(W,t),r(e))}}(e.userAgentOptions)),n.addPolicy(function(e="x-ms-client-request-id"){return{name:"setClientRequestIdPolicy",sendRequest:async(t,r)=>(t.headers.has(e)||t.headers.set(e,t.requestId),r(t))}}(null===(t=e.telemetryOptions)||void 0===t?void 0:t.clientRequestIdHeaderName)),n.addPolicy({name:Q,async sendRequest(e,t){var r;if(!e.multipartBody)return t(e);if(e.body)throw Error("multipartBody and regular body cannot be set at the same time");let n=e.multipartBody.boundary,s=null!==(r=e.headers.get("Content-Type"))&&void 0!==r?r:"multipart/mixed",i=s.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);if(!i)throw Error(`Got multipart request body, but content-type header was not multipart: ${s}`);let[,o,a]=i;if(a&&n&&a!==n)throw Error(`Multipart boundary was specified as ${a} in the header, but got ${n} in the request body`);return null!=n||(n=a),n?function(e){if(e.length>70)throw Error(`Multipart boundary "${e}" exceeds maximum length of 70 characters`);if(Array.from(e).some(e=>!ee.has(e)))throw Error(`Multipart boundary "${e}" contains invalid characters`)}(n):n=`----AzSDKFormBoundary${(0,N.HP)()}`,e.headers.set("Content-Type",`${o}; boundary=${n}`),await Y(e,e.multipartBody.parts,n),e.multipartBody=void 0,t(e)}},{afterPhase:"Deserialize"}),n.addPolicy(function(e={}){var t;return{name:"defaultRetryPolicy",sendRequest:function(e,t={maxRetries:3}){let r=t.logger||eo;return{name:"retryPolicy",async sendRequest(n,s){var i,o;let a,l;let c=-1;e:for(;;){c+=1,a=void 0,l=void 0;try{r.info(`Retry ${c}: Attempting to send request`,n.requestId),a=await s(n),r.info(`Retry ${c}: Received a response from request`,n.requestId)}catch(e){if(r.error(`Retry ${c}: Received an error from request`,n.requestId),l=e,!e||"RestError"!==l.name)throw e;a=l.response}if(null===(i=n.abortSignal)||void 0===i?void 0:i.aborted)throw r.error(`Retry ${c}: Request aborted.`),new et._;if(c>=(null!==(o=t.maxRetries)&&void 0!==o?o:3)){if(r.info(`Retry ${c}: Maximum retries reached. Returning the last received response, or throwing the last received error.`),l)throw l;if(a)return a;throw Error("Maximum retries reached with no response or error to throw")}for(let t of(r.info(`Retry ${c}: Processing ${e.length} retry strategies.`),e)){let e=t.logger||eo;e.info(`Retry ${c}: Processing retry strategy ${t.name}.`);let r=t.retry({retryCount:c,response:a,responseError:l});if(r.skipStrategy){e.info(`Retry ${c}: Skipped.`);continue}let{errorToThrow:s,retryAfterInMs:i,redirectTo:o}=r;if(s)throw e.error(`Retry ${c}: Retry strategy ${t.name} throws error:`,s),s;if(i||0===i){e.info(`Retry ${c}: Retry strategy ${t.name} retries after ${i}`),await er(i,void 0,{abortSignal:n.abortSignal});continue e}if(o){e.info(`Retry ${c}: Retry strategy ${t.name} redirects to ${o}`),n.url=o;continue e}}if(l)throw r.info("None of the retry strategies could work with the received error. Throwing it."),l;if(a)return r.info("None of the retry strategies could work with the received response. Returning it."),a}}}}([{name:"throttlingRetryStrategy",retry({response:e}){let t=ei(e);return Number.isFinite(t)?{retryAfterInMs:t}:{skipStrategy:!0}}},function(e={}){var t,r;let n=null!==(t=e.retryDelayInMs)&&void 0!==t?t:1e3,s=null!==(r=e.maxRetryDelayInMs)&&void 0!==r?r:64e3,i=n;return{name:"exponentialRetryStrategy",retry({retryCount:t,response:r,responseError:n}){let o=!!n&&("ETIMEDOUT"===n.code||"ESOCKETTIMEDOUT"===n.code||"ECONNREFUSED"===n.code||"ECONNRESET"===n.code||"ENOENT"===n.code||"ENOTFOUND"===n.code),a=o&&e.ignoreSystemErrors,l=!!(r&&void 0!==r.status&&(r.status>=500||408===r.status)&&501!==r.status&&505!==r.status),c=l&&e.ignoreHttpStatusCodes;if(r&&(Number.isFinite(ei(r))||!l)||c||a)return{skipStrategy:!0};if(n&&!o&&!l)return{errorToThrow:n};let u=Math.min(s,i*Math.pow(2,t));return{retryAfterInMs:i=u/2+(0,N.b1)(0,u/2)}}}}(e)],{maxRetries:null!==(t=e.maxRetries)&&void 0!==t?t:3}).sendRequest}}(e.retryOptions),{phase:"Retry"}),n.addPolicy(function(e={}){let t=H(e.userAgentPrefix),r=function(){try{return function(e){let{namespace:t,packageName:r,packageVersion:n}=e;function s(e,s,i){var o;let a=ep().startSpan(e,Object.assign(Object.assign({},i),{packageName:r,packageVersion:n,tracingContext:null===(o=null==s?void 0:s.tracingOptions)||void 0===o?void 0:o.tracingContext})),l=a.tracingContext,c=a.span;return l.getValue(ed.namespace)||(l=l.setValue(ed.namespace,t)),c.setAttribute("az.namespace",l.getValue(ed.namespace)),{span:c,updatedOptions:Object.assign({},s,{tracingOptions:Object.assign(Object.assign({},null==s?void 0:s.tracingOptions),{tracingContext:l})})}}async function i(e,t,r,n){let{span:i,updatedOptions:a}=s(e,t,n);try{let e=await o(a.tracingOptions.tracingContext,()=>Promise.resolve(r(a,i)));return i.setStatus({status:"success"}),e}catch(e){throw i.setStatus({status:"error",error:e}),e}finally{i.end()}}function o(e,t,...r){return ep().withContext(e,t,...r)}return{startSpan:s,withSpan:i,withContext:o,parseTraceparentHeader:function(e){return ep().parseTraceparentHeader(e)},createRequestHeaders:function(e){return ep().createRequestHeaders(e)}}}({namespace:"",packageName:"@azure/core-rest-pipeline",packageVersion:B})}catch(e){$.warning(`Error when creating the TracingClient: ${(0,N.e$)(e)}`);return}}();return{name:"tracingPolicy",async sendRequest(e,n){var s,i;if(!r||!(null===(s=e.tracingOptions)||void 0===s?void 0:s.tracingContext))return n(e);let{span:o,tracingContext:a}=null!==(i=function(e,t,r){try{let{span:n,updatedOptions:s}=e.startSpan(`HTTP ${t.method}`,{tracingOptions:t.tracingOptions},{spanKind:"client",spanAttributes:{"http.method":t.method,"http.url":t.url,requestId:t.requestId}});if(!n.isRecording()){n.end();return}r&&n.setAttribute("http.user_agent",r);let i=e.createRequestHeaders(s.tracingOptions.tracingContext);for(let[e,r]of Object.entries(i))t.headers.set(e,r);return{span:n,tracingContext:s.tracingOptions.tracingContext}}catch(e){$.warning(`Skipping creating a tracing span due to an error: ${(0,N.e$)(e)}`);return}}(r,e,t))&&void 0!==i?i:{};if(!o||!a)return n(e);try{let t=await r.withContext(a,n,e);return function(e,t){try{e.setAttribute("http.status_code",t.status);let r=t.headers.get("x-ms-request-id");r&&e.setAttribute("serviceRequestId",r),e.setStatus({status:"success"}),e.end()}catch(e){$.warning(`Skipping tracing span processing due to an error: ${(0,N.e$)(e)}`)}}(o,t),t}catch(e){throw function(e,t){try{e.setStatus({status:"error",error:(0,N.VZ)(t)?t:void 0}),(t instanceof ey||(0,N.VZ)(t)&&"RestError"===t.name)&&t.statusCode&&e.setAttribute("http.status_code",t.statusCode),e.end()}catch(e){$.warning(`Skipping tracing span processing due to an error: ${(0,N.e$)(e)}`)}}(o,e),e}}}}(e.userAgentOptions),{afterPhase:"Retry"}),N.Lr&&n.addPolicy(function(e={}){let{maxRetries:t=20}=e;return{name:"redirectPolicy",async sendRequest(e,r){let n=await r(e);return F(r,n,t)}}}(e.redirectOptions),{afterPhase:"Retry"}),n.addPolicy(function(e={}){var t;let r=null!==(t=e.logger)&&void 0!==t?t:$.info,n=new L({additionalAllowedHeaderNames:e.additionalAllowedHeaderNames,additionalAllowedQueryParameters:e.additionalAllowedQueryParameters});return{name:"logPolicy",async sendRequest(e,t){if(!r.enabled)return t(e);r(`Request: ${n.sanitize(e)}`);let s=await t(e);return r(`Response status code: ${s.status}`),r(`Headers: ${n.sanitize(s.headers)}`),s}}}(e.loggingOptions),{afterPhase:"Sign"}),n}(r);return n.addPolicy({name:"ApiVersionPolicy",sendRequest:(e,t)=>{let n=new URL(e.url);return!n.searchParams.get("api-version")&&r.apiVersion&&(e.url=`${e.url}${Array.from(n.searchParams.keys()).length>0?"&":"?"}api-version=${r.apiVersion}`),t(e)}}),!function(e,t,r={}){var n,s,i,o,a;let{credential:l,clientOptions:u}=r;if(l){if((0,c.cQ)(l)){let r=function(e){var t;let{credential:r,scopes:n,challengeCallbacks:s}=e,i=e.logger||$,o=Object.assign({authorizeRequest:null!==(t=null==s?void 0:s.authorizeRequest)&&void 0!==t?t:ex,authorizeRequestOnChallenge:null==s?void 0:s.authorizeRequestOnChallenge},s),a=r?function(e,t){let r,n=null,s=null,i=Object.assign(Object.assign({},eE),void 0),o={get isRefreshing(){return null!==n},get shouldRefresh(){var a;return!o.isRefreshing&&(null!==(a=null==s?void 0:s.expiresOnTimestamp)&&void 0!==a?a:0)-i.refreshWindowInMs<Date.now()},get mustRefresh(){return null===s||s.expiresOnTimestamp-i.forcedRefreshWindowInMs<Date.now()}};function l(t,a){var l;return o.isRefreshing||(n=eA(()=>e.getToken(t,a),i.retryIntervalInMs,null!==(l=null==s?void 0:s.expiresOnTimestamp)&&void 0!==l?l:Date.now()).then(e=>(n=null,s=e,r=a.tenantId,s)).catch(e=>{throw n=null,s=null,r=void 0,e})),n}return async(e,t)=>r!==t.tenantId||t.claims||o.mustRefresh?l(e,t):(o.shouldRefresh&&l(e,t),s)}(r):()=>Promise.resolve(null);return{name:"bearerTokenAuthenticationPolicy",async sendRequest(e,t){let r,s;if(!e.url.toLowerCase().startsWith("https://"))throw Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");await o.authorizeRequest({scopes:Array.isArray(n)?n:[n],request:e,getAccessToken:a,logger:i});try{r=await t(e)}catch(e){s=e,r=e.response}if(o.authorizeRequestOnChallenge&&(null==r?void 0:r.status)===401&&function(e){let t=e.headers.get("WWW-Authenticate");if(401===e.status&&t)return t}(r)&&await o.authorizeRequestOnChallenge({scopes:Array.isArray(n)?n:[n],request:e,response:r,getAccessToken:a,logger:i}))return t(e);if(!s)return r;throw s}}}({credential:l,scopes:null!==(s=null===(n=null==u?void 0:u.credentials)||void 0===n?void 0:n.scopes)&&void 0!==s?s:`${t}/.default`});e.addPolicy(r)}else if(void 0!==l.key){if(!(null===(i=null==u?void 0:u.credentials)||void 0===i?void 0:i.apiKeyHeaderName))throw Error("Missing API Key Header Name");let t=(a=null===(o=null==u?void 0:u.credentials)||void 0===o?void 0:o.apiKeyHeaderName,{name:"keyCredentialAuthenticationPolicy",sendRequest:async(e,t)=>(e.headers.set(a,l.key),t(e))});e.addPolicy(t)}}}(n,e,{credential:t,clientOptions:r}),n}(e,i,r);if(null===(n=r.additionalPolicies)||void 0===n?void 0:n.length)for(let{policy:e,position:t}of r.additionalPolicies){let r="perRetry"===t?"Sign":void 0;o.addPolicy(e,{afterPhase:r})}let{allowInsecureConnection:a,httpClient:l}=r,u=null!==(s=r.endpoint)&&void 0!==s?s:e,f=(e,...t)=>{let r=r=>(function(e,t,r,n={}){return t.startsWith("https://")||t.startsWith("http://")?t:(e=function(e,t){var r,n,s,i;if(!t.pathParameters)return e;for(let[o,a]of Object.entries(t.pathParameters)){if(null==a)throw Error(`Path parameters ${o} must not be undefined or null`);if(!a.toString||"function"!=typeof a.toString)throw Error(`Path parameters must be able to be represented as string, ${o} can't`);let l=void 0!==a.toISOString?a.toISOString():String(a);t.skipUrlEncoding||(l=encodeURIComponent(a)),e=null!==(n=e,s=`{${o}}`,i=l,r=n&&s?n.split(s).join(i||""):n)&&void 0!==r?r:""}return e}(e,n),t=function(e,t,r={}){for(let n of t){let t=n;r.skipUrlEncoding||(t=encodeURIComponent(n)),e=e.replace(/\{\w+\}/,t)}return e}(t,r,n),new URL(function(e,t={}){if(!t.queryParameters)return e;let r=new URL(e),n=t.queryParameters;for(let e of Object.keys(n)){let t=n[e];if(null==t)continue;if(!t.toString||"function"!=typeof t.toString)throw Error(`Query parameters must be able to be represented as string, ${e} can't`);let s=void 0!==t.toISOString?t.toISOString():t.toString();r.searchParams.append(e,s)}return t.skipUrlEncoding&&(r=function(e){if(!e)return e;let t=[];for(let[r,n]of e.searchParams)t.push(`${r}=${n}`);return e.search=t.length?`?${t.join("&")}`:"",e}(r)),r.toString()}(`${e}/${t}`,n)).toString().replace(/([^:]\/)\/+/g,"$1"))})(u,e,t,Object.assign({allowInsecureConnection:a},r));return{get:(e={})=>eC("GET",r(e),o,e,a,l),post:(e={})=>eC("POST",r(e),o,e,a,l),put:(e={})=>eC("PUT",r(e),o,e,a,l),patch:(e={})=>eC("PATCH",r(e),o,e,a,l),delete:(e={})=>eC("DELETE",r(e),o,e,a,l),head:(e={})=>eC("HEAD",r(e),o,e,a,l),options:(e={})=>eC("OPTIONS",r(e),o,e,a,l),trace:(e={})=>eC("TRACE",r(e),o,e,a,l)}};return{path:f,pathUnchecked:f,pipeline:o}}(h,t,r=Object.assign(Object.assign({},r),{userAgentOptions:{userAgentPrefix:m},loggingOptions:{logger:null!==(o=null===(i=r.loggingOptions)||void 0===i?void 0:i.logger)&&void 0!==o?o:eI.info},credentials:{scopes:null!==(l=null===(a=r.credentials)||void 0===a?void 0:a.scopes)&&void 0!==l?l:["https://cognitiveservices.azure.com/.default"],apiKeyHeaderName:null!==(f=null===(u=r.credentials)||void 0===u?void 0:u.apiKeyHeaderName)&&void 0!==f?f:"api-key"}}))};function eM(e,t){try{return e()}catch(e){throw Error(`${t}: ${e}`,{cause:e})}}function e$(e){if("object"!=typeof e||!e)return e;if(Array.isArray(e))return e.map(e=>e$(e));for(let t of Object.keys(e)){let r=e[t],n=t.toLowerCase().replace(/([_][a-z])/g,e=>e.toUpperCase().replace("_",""));n!==t&&delete e[t],e[n]="object"==typeof e[n]?e$(r):r}return e}function eN(e){if("object"!=typeof e||!e)return e;if(Array.isArray(e))return e.map(e=>eN(e));for(let t of Object.keys(e)){let r=e[t],n=t.replace(/([A-Z])/g,e=>`_${e.toLowerCase()}`).replace(/^_/,"");n!==t&&delete e[t],e[n]="object"==typeof e[n]?eN(r):r}return e}function ej(e){if("image_url"===e.type)return{type:e.type,image_url:{url:e.imageUrl.url,detail:e.imageUrl.detail}};return e}function eU(e){switch(e.type){case"connection_string":return{type:e.type,connection_string:e.connectionString};case"key_and_key_id":return{type:e.type,key:e.key,key_id:e.keyId};case"encoded_api_key":return{type:e.type,encoded_api_key:e.encodedApiKey};case"access_token":return{type:e.type,access_token:e.accessToken};case"user_assigned_managed_identity":return{type:e.type,managed_identity_resource_id:e.managedIdentityResourceId};default:return e}}function eD(e){switch(e.type){case"endpoint":return{type:e.type,endpoint:e.endpoint,authentication:eU(e.authentication)};case"deployment_name":return{type:e.type,deployment_name:e.deploymentName};case"model_id":return{type:e.type,model_id:e.modelId};default:return e}}let eL={"POST /deployments/{deploymentId}/audio/transcriptions":["200"],"POST /deployments/{deploymentId}/audio/translations":["200"],"POST /deployments/{deploymentId}/completions":["200"],"POST /deployments/{deploymentId}/chat/completions":["200"],"POST /deployments/{deploymentId}/images/generations":["200"],"POST /deployments/{deploymentId}/embeddings":["200"],"GET /operations/images/{operationId}":["200"],"POST /images/generations:submit":["202"],"GET /images/generations:submit":["200","202"]};function eq(e){let t=e.headers["x-ms-original-url"],r=new URL(null!=t?t:e.request.url),n=e.request.method,s=eL[`${n} ${r.pathname}`];return s||(s=function(e,t){var r,n,s,i;let o=t.split("/"),a=-1,l=[];for(let[t,c]of Object.entries(eL)){if(!t.startsWith(e))continue;let u=function(e){let t=e.indexOf("/");return e.slice(t)}(t),d=u.split("/"),f=!0;for(let e=d.length-1,t=o.length-1;e>=1&&t>=1;e--,t--){if((null===(r=d[e])||void 0===r?void 0:r.startsWith("{"))&&(null===(n=d[e])||void 0===n?void 0:n.indexOf("}"))!==-1){let r=d[e].indexOf("}")+1,n=null===(s=d[e])||void 0===s?void 0:s.length;if(!RegExp(`${null===(i=d[e])||void 0===i?void 0:i.slice(r,n)}`).test(o[t]||"")){f=!1;break}continue}if(d[e]!==o[t]){f=!1;break}}f&&u.length>a&&(a=u.length,l=c)}return l}(n,r.pathname)),!s.includes(e.status)}function eF(e){return(0,l.FC)(this,arguments,function*(){let t=e.getReader();try{for(;;){let{value:e,done:r}=yield(0,l.qq)(t.read());if(r)return yield(0,l.qq)(void 0);yield yield(0,l.qq)(e)}}finally{let e=t.cancel();t.releaseLock(),yield(0,l.qq)(e)}})}async function eB(e){let t=e.getReader(),r=[],n=0;try{for(;;){let{value:e,done:s}=await t.read();if(s)return new TextDecoder().decode(function(e,t){let r=new Uint8Array(null!=t?t:e.reduce((e,t)=>e+t.length,0));for(let t=0,n=0;t<e.length;t++){let s=e[t];r.set(s,n),n+=s.length}return r}(r,n));n+=e.length,r.push(e)}}finally{t.releaseLock()}}async function eH(e){let{body:t,status:r}=await e.asBrowserStream();if("200"!==r&&void 0!==t){let e=await eB(t);throw eM(()=>JSON.parse(e).error,"Error parsing response body")}if(!t)throw Error("No stream found in response. Did you enable the stream option?");return t}function eW(e){e[Symbol.asyncIterator]||(e[Symbol.asyncIterator]=()=>ez(e)),e.values||(e.values=()=>ez(e))}function ez(e){return(0,l.FC)(this,arguments,function*(){let t=e.getReader();try{for(;;){let{value:e,done:r}=yield(0,l.qq)(t.read());if(r)return yield(0,l.qq)(void 0);yield yield(0,l.qq)(e)}}finally{let e=t.cancel();t.releaseLock(),yield(0,l.qq)(e)}})}function eK(){return{data:void 0,event:"",id:"",retry:void 0}}async function eV(e,t){var r,n;let s=function(e){var t,r,n;let{cancel:s,iterable:i}=e&&"function"==typeof e.getReader&&"function"==typeof e.tee?(eW(e),{cancel:()=>e.cancel(),iterable:e}):{cancel:async()=>{var t;null===(t=e.socket)||void 0===t||t.end()},iterable:e};return t=function(e){return(0,l.FC)(this,arguments,function*(){var t,r,n,s;let i=eK(),o=new TextDecoder;try{for(var c,u=!0,d=(0,l.KL)(e);!(t=(c=yield(0,l.qq)(d.next())).done);u=!0){s=c.value,u=!1;let{line:e,fieldLen:t}=s;if(0===e.length&&void 0!==i.data)yield yield(0,l.qq)(i),i=eK();else if(t>0){let r=o.decode(e.subarray(0,t)),n=t+(e[t+1]===a.Space?2:1),s=o.decode(e.subarray(n));switch(r){case"data":i.data=i.data?i.data+"\n"+s:s;break;case"event":i.event=s;break;case"id":i.id=s;break;case"retry":{let e=parseInt(s,10);isNaN(e)||(i.retry=e)}}}}}catch(e){r={error:e}}finally{try{!u&&!t&&(n=d.return)&&(yield(0,l.qq)(n.call(d)))}finally{if(r)throw r.error}}})}(function(e){return(0,l.FC)(this,arguments,function*(){let t;let r=0,n=-1,s=!1;try{for(var i,o,c,u,d,f=!0,h=(0,l.KL)(e);!(i=(d=yield(0,l.qq)(h.next())).done);f=!0){u=d.value,f=!1,void 0===t?(t=u,r=0,n=-1):t=function(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}(t,u);let e=t.length,i=0;for(;r<e;){s&&(t[r]===a.NewLine&&(i=++r),s=!1);let o=-1;for(;r<e&&-1===o;++r)switch(t[r]){case a.Colon:-1===n&&(n=r-i);break;case a.CarriageReturn:s=!0,o=r;break;case a.NewLine:o=r}if(-1===o)break;yield yield(0,l.qq)({line:t.subarray(i,o),fieldLen:n}),i=r,n=-1}i===e?t=void 0:0!==i&&(t=t.subarray(i),r-=i)}}catch(e){o={error:e}}finally{try{!f&&!i&&(c=h.return)&&(yield(0,l.qq)(c.call(h)))}finally{if(o)throw o.error}}})}(i)),eW(r=new ReadableStream({async pull(e){let{value:r,done:n}=await t.next();n?e.close():e.enqueue(r)},cancel:s})),null!==(n=Symbol.asyncDispose)&&void 0!==n||(Symbol.asyncDispose=Symbol("Symbol.asyncDispose")),r[Symbol.asyncDispose]||(r[Symbol.asyncDispose]=()=>s()),r}(await eH(e)),i=new TransformStream({transform:async(e,r)=>{"[DONE]"!==e.data&&r.enqueue(t(eM(()=>JSON.parse(e.data),"Error parsing an event. See 'cause' for more details")))}});return(n=r=s.pipeThrough(i))[Symbol.asyncIterator]||(n[Symbol.asyncIterator]=()=>eF(n)),n.values||(n.values=()=>eF(n)),r}async function eJ(e,t,r,n,s){let i=null!=s?s:"string"==typeof n?{}:null!=n?n:{},o="string"==typeof n?n:void 0,{abortSignal:a,onResponse:c,requestOptions:u,tracingOptions:d}=i,f=(0,l._T)(i,["abortSignal","onResponse","requestOptions","tracingOptions"]),{body:h,status:p}=await e.pathUnchecked("deployments/{deploymentName}/audio/transcriptions",t).post(Object.assign(Object.assign({},eR({abortSignal:a,onResponse:c,tracingOptions:d,requestOptions:u})),{contentType:"multipart/form-data",body:Object.assign(Object.assign(Object.assign({},eN(f)),{file:V(r,"placeholder.wav")}),o?{response_format:o}:{})}));if("200"!==p)throw h.error;return"verbose_json"!==o?h:e$(h)}async function eG(e,t,r,n,s){let i=null!=s?s:"string"==typeof n?{}:null!=n?n:{},o="string"==typeof n?n:void 0,{abortSignal:a,onResponse:c,requestOptions:u,tracingOptions:d}=i,f=(0,l._T)(i,["abortSignal","onResponse","requestOptions","tracingOptions"]),{body:h,status:p}=await e.pathUnchecked("deployments/{deploymentName}/audio/translations",t).post(Object.assign(Object.assign({},eR({abortSignal:a,onResponse:c,tracingOptions:d,requestOptions:u})),{contentType:"multipart/form-data",body:Object.assign(Object.assign(Object.assign({},eN(f)),{file:V(r,"placeholder.wav")}),o?{response_format:o}:{})}));if("200"!==p)throw h.error;return"verbose_json"!==o?h:e$(h)}function eZ(e,t,r,n={requestOptions:{}}){return e.path("/deployments/{deploymentId}/completions",t).post(Object.assign(Object.assign({},eR(n)),{body:{prompt:r.prompt,max_tokens:r.maxTokens,temperature:r.temperature,top_p:r.topP,logit_bias:r.logitBias,user:r.user,n:r.n,logprobs:r.logprobs,suffix:r.suffix,echo:r.echo,stop:r.stop,presence_penalty:r.presencePenalty,frequency_penalty:r.frequencyPenalty,best_of:r.bestOf,stream:r.stream,model:r.model}}))}async function eX(e){if(eq(e))throw e.body.error;return eY(e.body)}function eY(e){let{created:t,choices:r,prompt_filter_results:n,prompt_annotations:s}=e;return Object.assign(Object.assign(Object.assign(Object.assign({},e$((0,l._T)(e,["created","choices","prompt_filter_results","prompt_annotations"]))),{created:new Date(t)}),{promptFilterResults:e9({prompt_filter_results:n,prompt_annotations:s})}),{choices:r.map(e=>{var{content_filter_results:t}=e;return Object.assign(Object.assign({},e$((0,l._T)(e,["content_filter_results"]))),t?{contentFilterResults:e7(t)}:{})})})}async function eQ(e,t,r,n={requestOptions:{}}){return eX(await eZ(e,t,r,n))}async function e0(e){if(eq(e))throw e.body.error;return e1(e.body)}function e1(e){let{created:t,choices:r,prompt_filter_results:n,prompt_annotations:s,usage:i}=e;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e$((0,l._T)(e,["created","choices","prompt_filter_results","prompt_annotations","usage"]))),{created:new Date(t)}),{promptFilterResults:e9({prompt_filter_results:n,prompt_annotations:s})}),i?{usage:{completionTokens:i.completion_tokens,promptTokens:i.prompt_tokens,totalTokens:i.total_tokens}}:{}),{choices:r?r.map(e=>{var{content_filter_results:t}=e;return Object.assign(Object.assign({},e$((0,l._T)(e,["content_filter_results"]))),t?{contentFilterResults:e7(t)}:{})}):[]})}async function e2(e,t,r,n={requestOptions:{}}){return e0(await e3(e,t,r,n))}function e3(e,t,r,n={requestOptions:{}}){let{azureExtensionOptions:s,abortSignal:i,onResponse:o,requestOptions:a,tracingOptions:c}=n,u=(0,l._T)(n,["azureExtensionOptions","abortSignal","onResponse","requestOptions","tracingOptions"]),d=Object.assign(Object.assign({},(null==s?void 0:s.extensions)?{dataSources:s.extensions}:{}),(null==s?void 0:s.enhancements)?{enhancements:s.enhancements}:{});return function(e,t,r,n={requestOptions:{}}){var s,i,o,a,c,u,d;return e.path("/deployments/{deploymentId}/chat/completions",t).post(Object.assign(Object.assign({},eR(n)),{body:{model:r.model,stream:r.stream,max_tokens:r.maxTokens,temperature:r.temperature,top_p:r.topP,logit_bias:r.logitBias,user:r.user,n:r.n,stop:r.stop,presence_penalty:r.presencePenalty,frequency_penalty:r.frequencyPenalty,data_sources:void 0===r.dataSources?r.dataSources:r.dataSources.map(e=>(function(e){var t,r,n,s,i,o,a,l,c,u,d,f,h;switch(e.type){case"azure_search":return{type:e.type,parameters:{authentication:e.authentication?eU(e.authentication):e.authentication,top_n_documents:e.topNDocuments,in_scope:e.inScope,strictness:e.strictness,role_information:e.roleInformation,endpoint:e.endpoint,index_name:e.indexName,fields_mapping:e.fieldsMapping?{title_field:null===(t=e.fieldsMapping)||void 0===t?void 0:t.titleField,url_field:null===(r=e.fieldsMapping)||void 0===r?void 0:r.urlField,filepath_field:null===(n=e.fieldsMapping)||void 0===n?void 0:n.filepathField,content_fields:null===(s=e.fieldsMapping)||void 0===s?void 0:s.contentFields,content_fields_separator:null===(i=e.fieldsMapping)||void 0===i?void 0:i.contentFieldsSeparator,vector_fields:null===(o=e.fieldsMapping)||void 0===o?void 0:o.vectorFields,image_vector_fields:null===(a=e.fieldsMapping)||void 0===a?void 0:a.imageVectorFields}:void 0,query_type:e.queryType,semantic_configuration:e.semanticConfiguration,filter:e.filter,embedding_dependency:e.embeddingDependency?eD(e.embeddingDependency):e.embeddingDependency}};case"azure_ml_index":return{type:e.type,parameters:{authentication:e.authentication?eU(e.authentication):e.authentication,top_n_documents:e.topNDocuments,in_scope:e.inScope,strictness:e.strictness,role_information:e.roleInformation,project_resource_id:e.projectResourceId,name:e.name,version:e.version,filter:e.filter}};case"azure_cosmos_db":return{type:e.type,parameters:{authentication:e.authentication?eU(e.authentication):e.authentication,top_n_documents:e.topNDocuments,in_scope:e.inScope,strictness:e.strictness,role_information:e.roleInformation,database_name:e.databaseName,container_name:e.containerName,index_name:e.indexName,fields_mapping:{title_field:e.fieldsMapping.titleField,url_field:e.fieldsMapping.urlField,filepath_field:e.fieldsMapping.filepathField,content_fields:e.fieldsMapping.contentFields,content_fields_separator:e.fieldsMapping.contentFieldsSeparator,vector_fields:e.fieldsMapping.vectorFields},embedding_dependency:eD(e.embeddingDependency)}};case"elasticsearch":return{type:e.type,parameters:{authentication:e.authentication?eU(e.authentication):e.authentication,top_n_documents:e.topNDocuments,in_scope:e.inScope,strictness:e.strictness,role_information:e.roleInformation,endpoint:e.endpoint,index_name:e.indexName,fields_mapping:e.fieldsMapping?{title_field:null===(l=e.fieldsMapping)||void 0===l?void 0:l.titleField,url_field:null===(c=e.fieldsMapping)||void 0===c?void 0:c.urlField,filepath_field:null===(u=e.fieldsMapping)||void 0===u?void 0:u.filepathField,content_fields:null===(d=e.fieldsMapping)||void 0===d?void 0:d.contentFields,content_fields_separator:null===(f=e.fieldsMapping)||void 0===f?void 0:f.contentFieldsSeparator,vector_fields:null===(h=e.fieldsMapping)||void 0===h?void 0:h.vectorFields}:void 0,query_type:e.queryType,embedding_dependency:e.embeddingDependency?eD(e.embeddingDependency):e.embeddingDependency}};case"pinecone":return{type:e.type,parameters:{authentication:e.authentication?eU(e.authentication):e.authentication,top_n_documents:e.topNDocuments,in_scope:e.inScope,strictness:e.strictness,role_information:e.roleInformation,environment:e.environment,index_name:e.indexName,fields_mapping:{title_field:e.fieldsMapping.titleField,url_field:e.fieldsMapping.urlField,filepath_field:e.fieldsMapping.filepathField,content_fields:e.fieldsMapping.contentFields,content_fields_separator:e.fieldsMapping.contentFieldsSeparator},embedding_dependency:eD(e.embeddingDependency)}};default:return e}})(e)),enhancements:r.enhancements?{grounding:(null===(s=r.enhancements)||void 0===s?void 0:s.grounding)?{enabled:null===(o=null===(i=r.enhancements)||void 0===i?void 0:i.grounding)||void 0===o?void 0:o.enabled}:void 0,ocr:(null===(a=r.enhancements)||void 0===a?void 0:a.ocr)?{enabled:null===(u=null===(c=r.enhancements)||void 0===c?void 0:c.ocr)||void 0===u?void 0:u.enabled}:void 0}:void 0,seed:r.seed,logprobs:r.logprobs,top_logprobs:r.topLogprobs,response_format:r.responseFormat?{type:null===(d=r.responseFormat)||void 0===d?void 0:d.type}:void 0,tool_choice:r.toolChoice,tools:r.tools,functions:void 0===r.functions?r.functions:r.functions.map(e=>({name:e.name,description:e.description,parameters:e.parameters})),function_call:r.functionCall,messages:r.messages.map(e=>(function(e){switch(e.role){case"user":return{role:e.role,content:"string"==typeof e.content?e.content:e.content.map(ej),name:e.name};case"assistant":return function(e){void 0===e.content&&(e.content=null);let{functionCall:t,toolCalls:r}=e;return Object.assign(Object.assign(Object.assign({},eN((0,l._T)(e,["functionCall","toolCalls"]))),r&&0!==r.length?{tool_calls:r}:{}),t?{function_call:t}:{})}(e);case"tool":return{role:e.role,content:e.content,tool_call_id:e.toolCallId};default:return e}})(e))}}))}(e,t,Object.assign(Object.assign({messages:r},u),d),{abortSignal:i,onResponse:o,requestOptions:a,tracingOptions:c})}async function e4(e){if(eq(e))throw e.body.error;return{created:new Date(e.body.created),data:e.body.data.map(e=>{var t,r,n,s,i,o,a,l,c,u,d,f,h,p,m,g,y,b,w,v,_,S,E,A,x,R,O,k,P,C,I,T,M,$,N,j,U,D,L,q,F,B,H,W,z,K,V,J,G,Z;return{url:e.url,base64Data:e.b64_json,contentFilterResults:e.content_filter_results?{sexual:(null===(t=e.content_filter_results)||void 0===t?void 0:t.sexual)?{severity:null===(n=null===(r=e.content_filter_results)||void 0===r?void 0:r.sexual)||void 0===n?void 0:n.severity,filtered:null===(i=null===(s=e.content_filter_results)||void 0===s?void 0:s.sexual)||void 0===i?void 0:i.filtered}:void 0,violence:(null===(o=e.content_filter_results)||void 0===o?void 0:o.violence)?{severity:null===(l=null===(a=e.content_filter_results)||void 0===a?void 0:a.violence)||void 0===l?void 0:l.severity,filtered:null===(u=null===(c=e.content_filter_results)||void 0===c?void 0:c.violence)||void 0===u?void 0:u.filtered}:void 0,hate:(null===(d=e.content_filter_results)||void 0===d?void 0:d.hate)?{severity:null===(h=null===(f=e.content_filter_results)||void 0===f?void 0:f.hate)||void 0===h?void 0:h.severity,filtered:null===(m=null===(p=e.content_filter_results)||void 0===p?void 0:p.hate)||void 0===m?void 0:m.filtered}:void 0,selfHarm:(null===(g=e.content_filter_results)||void 0===g?void 0:g.self_harm)?{severity:null===(b=null===(y=e.content_filter_results)||void 0===y?void 0:y.self_harm)||void 0===b?void 0:b.severity,filtered:null===(v=null===(w=e.content_filter_results)||void 0===w?void 0:w.self_harm)||void 0===v?void 0:v.filtered}:void 0}:void 0,revisedPrompt:e.revised_prompt,promptFilterResults:e.prompt_filter_results?{sexual:(null===(_=e.prompt_filter_results)||void 0===_?void 0:_.sexual)?{severity:null===(E=null===(S=e.prompt_filter_results)||void 0===S?void 0:S.sexual)||void 0===E?void 0:E.severity,filtered:null===(x=null===(A=e.prompt_filter_results)||void 0===A?void 0:A.sexual)||void 0===x?void 0:x.filtered}:void 0,violence:(null===(R=e.prompt_filter_results)||void 0===R?void 0:R.violence)?{severity:null===(k=null===(O=e.prompt_filter_results)||void 0===O?void 0:O.violence)||void 0===k?void 0:k.severity,filtered:null===(C=null===(P=e.prompt_filter_results)||void 0===P?void 0:P.violence)||void 0===C?void 0:C.filtered}:void 0,hate:(null===(I=e.prompt_filter_results)||void 0===I?void 0:I.hate)?{severity:null===(M=null===(T=e.prompt_filter_results)||void 0===T?void 0:T.hate)||void 0===M?void 0:M.severity,filtered:null===(N=null===($=e.prompt_filter_results)||void 0===$?void 0:$.hate)||void 0===N?void 0:N.filtered}:void 0,selfHarm:(null===(j=e.prompt_filter_results)||void 0===j?void 0:j.self_harm)?{severity:null===(D=null===(U=e.prompt_filter_results)||void 0===U?void 0:U.self_harm)||void 0===D?void 0:D.severity,filtered:null===(q=null===(L=e.prompt_filter_results)||void 0===L?void 0:L.self_harm)||void 0===q?void 0:q.filtered}:void 0,profanity:(null===(F=e.prompt_filter_results)||void 0===F?void 0:F.profanity)?{filtered:null===(H=null===(B=e.prompt_filter_results)||void 0===B?void 0:B.profanity)||void 0===H?void 0:H.filtered,detected:null===(z=null===(W=e.prompt_filter_results)||void 0===W?void 0:W.profanity)||void 0===z?void 0:z.detected}:void 0,jailbreak:(null===(K=e.prompt_filter_results)||void 0===K?void 0:K.jailbreak)?{filtered:null===(J=null===(V=e.prompt_filter_results)||void 0===V?void 0:V.jailbreak)||void 0===J?void 0:J.filtered,detected:null===(Z=null===(G=e.prompt_filter_results)||void 0===G?void 0:G.jailbreak)||void 0===Z?void 0:Z.detected}:void 0}:void 0}})}}async function e6(e,t,r,n={requestOptions:{}}){return e4(await function(e,t,r,n={requestOptions:{}}){return e.path("/deployments/{deploymentId}/images/generations",t).post(Object.assign(Object.assign({},eR(n)),{body:{model:r.model,prompt:r.prompt,n:r.n,size:r.size,response_format:r.responseFormat,quality:r.quality,style:r.style,user:r.user}}))}(e,t,r,n))}async function e5(e){if(eq(e))throw e.body.error;return{data:e.body.data.map(e=>({embedding:e.embedding,index:e.index})),usage:{promptTokens:e.body.usage.prompt_tokens,totalTokens:e.body.usage.total_tokens}}}async function e8(e,t,r,n={requestOptions:{}}){return e5(await function(e,t,r,n={requestOptions:{}}){return e.path("/deployments/{deploymentId}/embeddings",t).post(Object.assign(Object.assign({},eR(n)),{body:{user:r.user,model:r.model,input:r.input,dimensions:r.dimensions}}))}(e,t,r,n))}function e9({prompt_annotations:e,prompt_filter_results:t}){let r=null!=t?t:e;return null==r?void 0:r.map(e=>{var{content_filter_results:t}=e;return Object.assign(Object.assign({},e$((0,l._T)(e,["content_filter_results"]))),{contentFilterResults:function(e={}){var t,{error:r}=e,n=(0,l._T)(e,["error"]);return r?{error:Object.assign(Object.assign({},r),{details:null!==(t=r.details)&&void 0!==t?t:[]})}:e$(n)}(t)})})}function e7(e={}){var t,{error:r}=e,n=(0,l._T)(e,["error"]);return r?{error:Object.assign(Object.assign({},r),{details:null!==(t=r.details)&&void 0!==t?t:[]})}:e$(n)}(o=a||(a={}))[o.NewLine=10]="NewLine",o[o.CarriageReturn=13]="CarriageReturn",o[o.Space=32]="Space",o[o.Colon=58]="Colon";class te{constructor(e,t={},r={}){var n,s;let i,o,a;if(this._isAzure=!1,(0,c.cQ)(t)||void 0!==t.key)o=e,a=t,i=r,this._isAzure=!0;else{o="https://api.openai.com/v1",a=e;let{credentials:r}=t,s=(0,l._T)(t,["credentials"]);i=Object.assign({credentials:{apiKeyHeaderName:null!==(n=null==r?void 0:r.apiKeyHeaderName)&&void 0!==n?n:"Authorization",scopes:null==r?void 0:r.scopes}},s)}this._client=function(e,t,r={}){return eT(e,t,r)}(o,a,Object.assign(Object.assign({},i),this._isAzure?{}:{additionalPolicies:[...null!==(s=i.additionalPolicies)&&void 0!==s?s:[],{position:"perCall",policy:{name:"openAiEndpoint",sendRequest:(e,t)=>{let r=new URL(e.url),n=r.pathname.split("/");switch(n[n.length-1]){case"completions":"chat"===n[n.length-2]?r.pathname=`${n[1]}/chat/completions`:r.pathname=`${n[1]}/completions`;break;case"embeddings":r.pathname=`${n[1]}/embeddings`;break;case"generations":if("images"===n[n.length-2])r.pathname=`${n[1]}/images/generations`;else throw Error("Unexpected path");break;case"transcriptions":r.pathname=`${n[1]}/audio/transcriptions`;break;case"translations":r.pathname=`${n[1]}/audio/translations`}return r.searchParams.delete("api-version"),e.url=r.toString(),t(e)}}}]}))}setModel(e,t){this._isAzure||(t.model=e)}async getAudioTranslation(e,t,r,n){let s=null!=n?n:"string"==typeof r?{}:null!=r?r:{},i="string"==typeof r?r:void 0;return(this.setModel(e,s),void 0===i)?eG(this._client,e,t,s):eG(this._client,e,t,i,s)}async getAudioTranscription(e,t,r,n){let s=null!=n?n:"string"==typeof r?{}:null!=r?r:{},i="string"==typeof r?r:void 0;return(this.setModel(e,s),void 0===i)?eJ(this._client,e,t,s):eJ(this._client,e,t,i,s)}getCompletions(e,t,r={requestOptions:{}}){this.setModel(e,r);let{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o}=r,a=(0,l._T)(r,["abortSignal","onResponse","requestOptions","tracingOptions"]);return eQ(this._client,e,Object.assign({prompt:t},a),{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o})}streamCompletions(e,t,r={}){return this.setModel(e,r),function(e,t,r,n={requestOptions:{}}){let{abortSignal:s,onResponse:i,requestOptions:o,tracingOptions:a}=n;return eV(eZ(e,t,Object.assign(Object.assign({prompt:r},(0,l._T)(n,["abortSignal","onResponse","requestOptions","tracingOptions"])),{stream:!0}),{abortSignal:s,onResponse:i,requestOptions:o,tracingOptions:a}),eY)}(this._client,e,t,r)}getChatCompletions(e,t,r={requestOptions:{}}){return this.setModel(e,r),e2(this._client,e,t,r)}streamChatCompletions(e,t,r={requestOptions:{}}){return this.setModel(e,r),function(e,t,r,n={requestOptions:{}}){return eV(e3(e,t,r,Object.assign(Object.assign({},n),{stream:!0})),e1)}(this._client,e,t,r)}getImages(e,t,r={requestOptions:{}}){this.setModel(e,r);let{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o}=r,a=(0,l._T)(r,["abortSignal","onResponse","requestOptions","tracingOptions"]);return e6(this._client,e,Object.assign({prompt:t},a),{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o})}getEmbeddings(e,t,r={requestOptions:{}}){this.setModel(e,r);let{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o}=r,a=(0,l._T)(r,["abortSignal","onResponse","requestOptions","tracingOptions"]);return e8(this._client,e,Object.assign({input:t},a),{abortSignal:n,onResponse:s,requestOptions:i,tracingOptions:o})}}},52024:function(e,t,r){"use strict";var n,s,i,o,a,l,c,u,d,f,h,p,m,g,y,b,w,v,_,S,E,A,x,R;r.d(t,{$D:function(){return ei},XQ:function(){return n}}),(m=n||(n={})).STRING="string",m.NUMBER="number",m.INTEGER="integer",m.BOOLEAN="boolean",m.ARRAY="array",m.OBJECT="object",(g=s||(s={})).LANGUAGE_UNSPECIFIED="language_unspecified",g.PYTHON="python",(y=i||(i={})).OUTCOME_UNSPECIFIED="outcome_unspecified",y.OUTCOME_OK="outcome_ok",y.OUTCOME_FAILED="outcome_failed",y.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded";let O=["user","model","function","system"];(b=o||(o={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",b.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",b.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",b.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",b.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",(w=a||(a={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",w.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",w.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",w.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",w.BLOCK_NONE="BLOCK_NONE",(v=l||(l={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",v.NEGLIGIBLE="NEGLIGIBLE",v.LOW="LOW",v.MEDIUM="MEDIUM",v.HIGH="HIGH",(_=c||(c={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",_.SAFETY="SAFETY",_.OTHER="OTHER",(S=u||(u={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",S.STOP="STOP",S.MAX_TOKENS="MAX_TOKENS",S.SAFETY="SAFETY",S.RECITATION="RECITATION",S.LANGUAGE="LANGUAGE",S.OTHER="OTHER",(E=d||(d={})).TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",E.RETRIEVAL_QUERY="RETRIEVAL_QUERY",E.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",E.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",E.CLASSIFICATION="CLASSIFICATION",E.CLUSTERING="CLUSTERING",(A=f||(f={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",A.AUTO="AUTO",A.ANY="ANY",A.NONE="NONE",(x=h||(h={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",x.MODE_DYNAMIC="MODE_DYNAMIC";class k extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class P extends k{constructor(e,t){super(e),this.response=t}}class C extends k{constructor(e,t,r,n){super(e),this.status=t,this.statusText=r,this.errorDetails=n}}class I extends k{}(R=p||(p={})).GENERATE_CONTENT="generateContent",R.STREAM_GENERATE_CONTENT="streamGenerateContent",R.COUNT_TOKENS="countTokens",R.EMBED_CONTENT="embedContent",R.BATCH_EMBED_CONTENTS="batchEmbedContents";class T{constructor(e,t,r,n,s){this.model=e,this.task=t,this.apiKey=r,this.stream=n,this.requestOptions=s}toString(){var e,t;let r=(null===(e=this.requestOptions)||void 0===e?void 0:e.apiVersion)||"v1beta",n=(null===(t=this.requestOptions)||void 0===t?void 0:t.baseUrl)||"https://generativelanguage.googleapis.com",s=`${n}/${r}/${this.model}:${this.task}`;return this.stream&&(s+="?alt=sse"),s}}async function M(e){var t;let r=new Headers;r.append("Content-Type","application/json"),r.append("x-goog-api-client",function(e){let t=[];return(null==e?void 0:e.apiClient)&&t.push(e.apiClient),t.push("genai-js/0.21.0"),t.join(" ")}(e.requestOptions)),r.append("x-goog-api-key",e.apiKey);let n=null===(t=e.requestOptions)||void 0===t?void 0:t.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new I(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,t]of n.entries()){if("x-goog-api-key"===e)throw new I(`Cannot set reserved header name ${e}`);if("x-goog-api-client"===e)throw new I(`Header name ${e} can only be set using the apiClient field`);r.append(e,t)}}return r}async function $(e,t,r,n,s,i){let o=new T(e,t,r,n,i);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},function(e){let t={};if((null==e?void 0:e.signal)!==void 0||(null==e?void 0:e.timeout)>=0){let r=new AbortController;(null==e?void 0:e.timeout)>=0&&setTimeout(()=>r.abort(),e.timeout),(null==e?void 0:e.signal)&&e.signal.addEventListener("abort",()=>{r.abort()}),t.signal=r.signal}return t}(i)),{method:"POST",headers:await M(o),body:s})}}async function N(e,t,r,n,s,i={},o=fetch){let{url:a,fetchOptions:l}=await $(e,t,r,n,s,i);return j(a,l,o)}async function j(e,t,r=fetch){let n;try{n=await r(e,t)}catch(t){!function(e,t){let r=e;throw e instanceof C||e instanceof I||((r=new k(`Error fetching from ${t.toString()}: ${e.message}`)).stack=e.stack),r}(t,e)}return n.ok||await U(n,e),n}async function U(e,t){let r,n="";try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch(e){}throw new C(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function D(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),F(e.candidates[0]))throw new P(`${B(e)}`,e);return function(e){var t,r,n,s;let i=[];if(null===(r=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===r?void 0:r.parts)for(let t of null===(s=null===(n=e.candidates)||void 0===n?void 0:n[0].content)||void 0===s?void 0:s.parts)t.text&&i.push(t.text),t.executableCode&&i.push("\n```"+t.executableCode.language+"\n"+t.executableCode.code+"\n```\n"),t.codeExecutionResult&&i.push("\n```\n"+t.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}(e)}if(e.promptFeedback)throw new P(`Text not available. ${B(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),F(e.candidates[0]))throw new P(`${B(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),L(e)[0]}if(e.promptFeedback)throw new P(`Function call not available. ${B(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),F(e.candidates[0]))throw new P(`${B(e)}`,e);return L(e)}if(e.promptFeedback)throw new P(`Function call not available. ${B(e)}`,e)},e}function L(e){var t,r,n,s;let i=[];if(null===(r=null===(t=e.candidates)||void 0===t?void 0:t[0].content)||void 0===r?void 0:r.parts)for(let t of null===(s=null===(n=e.candidates)||void 0===n?void 0:n[0].content)||void 0===s?void 0:s.parts)t.functionCall&&i.push(t.functionCall);return i.length>0?i:void 0}let q=[u.RECITATION,u.SAFETY,u.LANGUAGE];function F(e){return!!e.finishReason&&q.includes(e.finishReason)}function B(e){var t,r,n;let s="";if((!e.candidates||0===e.candidates.length)&&e.promptFeedback)s+="Response was blocked",(null===(t=e.promptFeedback)||void 0===t?void 0:t.blockReason)&&(s+=` due to ${e.promptFeedback.blockReason}`),(null===(r=e.promptFeedback)||void 0===r?void 0:r.blockReasonMessage)&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(null===(n=e.candidates)||void 0===n?void 0:n[0]){let t=e.candidates[0];F(t)&&(s+=`Candidate was blocked due to ${t.finishReason}`,t.finishMessage&&(s+=`: ${t.finishMessage}`))}return s}function H(e){return this instanceof H?(this.v=e,this):new H(e)}"function"==typeof SuppressedError&&SuppressedError;let W=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;async function z(e){let t=[],r=e.getReader();for(;;){let{done:e,value:n}=await r.read();if(e)return D(function(e){let t=e[e.length-1],r={promptFeedback:null==t?void 0:t.promptFeedback};for(let t of e){if(t.candidates)for(let e of t.candidates){let t=e.index;if(r.candidates||(r.candidates=[]),r.candidates[t]||(r.candidates[t]={index:e.index}),r.candidates[t].citationMetadata=e.citationMetadata,r.candidates[t].groundingMetadata=e.groundingMetadata,r.candidates[t].finishReason=e.finishReason,r.candidates[t].finishMessage=e.finishMessage,r.candidates[t].safetyRatings=e.safetyRatings,e.content&&e.content.parts){r.candidates[t].content||(r.candidates[t].content={role:e.content.role||"user",parts:[]});let n={};for(let s of e.content.parts)s.text&&(n.text=s.text),s.functionCall&&(n.functionCall=s.functionCall),s.executableCode&&(n.executableCode=s.executableCode),s.codeExecutionResult&&(n.codeExecutionResult=s.codeExecutionResult),0===Object.keys(n).length&&(n.text=""),r.candidates[t].content.parts.push(n)}}t.usageMetadata&&(r.usageMetadata=t.usageMetadata)}return r}(t));t.push(n)}}async function K(e,t,r,n){return function(e){let[t,r]=(function(e){let t=e.getReader();return new ReadableStream({start(e){let r="";return function n(){return t.read().then(({value:t,done:s})=>{let i;if(s){if(r.trim()){e.error(new k("Failed to parse stream"));return}e.close();return}let o=(r+=t).match(W);for(;o;){try{i=JSON.parse(o[1])}catch(t){e.error(new k(`Error parsing JSON response: "${o[1]}"`));return}e.enqueue(i),o=(r=r.substring(o[0].length)).match(W)}return n()})}()}})})(e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0}))).tee();return{stream:function(e){return function(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(e,t||[]),i=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(e){s[e]&&(n[e]=function(t){return new Promise(function(r,n){i.push([e,t,r,n])>1||a(e,t)})})}function a(e,t){try{var r;(r=s[e](t)).value instanceof H?Promise.resolve(r.value.v).then(l,c):u(i[0][2],r)}catch(e){u(i[0][3],e)}}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:r}=yield H(t.read());if(r)break;yield yield H(D(e))}})}(t),response:z(r)}}(await N(t,p.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(r),n))}async function V(e,t,r,n){let s=await N(t,p.GENERATE_CONTENT,e,!1,JSON.stringify(r),n);return{response:D(await s.json())}}function J(e){if(null!=e){if("string"==typeof e)return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function G(e){let t=[];if("string"==typeof e)t=[{text:e}];else for(let r of e)"string"==typeof r?t.push({text:r}):t.push(r);return function(e){let t={role:"user",parts:[]},r={role:"function",parts:[]},n=!1,s=!1;for(let i of e)"functionResponse"in i?(r.parts.push(i),s=!0):(t.parts.push(i),n=!0);if(n&&s)throw new k("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!s)throw new k("No content is provided for sending chat message.");return n?t:r}(t)}function Z(e){let t;return t=e.contents?e:{contents:[G(e)]},e.systemInstruction&&(t.systemInstruction=J(e.systemInstruction)),t}let X=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Y={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]},Q="SILENT_ERROR";class ee{constructor(e,t,r,n={}){this.model=t,this.params=r,this._requestOptions=n,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,(null==r?void 0:r.history)&&(function(e){let t=!1;for(let r of e){let{role:e,parts:n}=r;if(!t&&"user"!==e)throw new k(`First content should be with role 'user', got ${e}`);if(!O.includes(e))throw new k(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(O)}`);if(!Array.isArray(n))throw new k("Content should have 'parts' property with an array of Parts");if(0===n.length)throw new k("Each Content should have at least one part");let s={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of n)for(let t of X)t in e&&(s[t]+=1);let i=Y[e];for(let t of X)if(!i.includes(t)&&s[t]>0)throw new k(`Content with role '${e}' can't contain '${t}' part`);t=!0}}(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){var r,n,s,i,o,a;let l;await this._sendPromise;let c=G(e),u={safetySettings:null===(r=this.params)||void 0===r?void 0:r.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(i=this.params)||void 0===i?void 0:i.toolConfig,systemInstruction:null===(o=this.params)||void 0===o?void 0:o.systemInstruction,cachedContent:null===(a=this.params)||void 0===a?void 0:a.cachedContent,contents:[...this._history,c]},d=Object.assign(Object.assign({},this._requestOptions),t);return this._sendPromise=this._sendPromise.then(()=>V(this._apiKey,this.model,u,d)).then(e=>{var t;if(e.response.candidates&&e.response.candidates.length>0){this._history.push(c);let r=Object.assign({parts:[],role:"model"},null===(t=e.response.candidates)||void 0===t?void 0:t[0].content);this._history.push(r)}else{let t=B(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}l=e}),await this._sendPromise,l}async sendMessageStream(e,t={}){var r,n,s,i,o,a;await this._sendPromise;let l=G(e),c={safetySettings:null===(r=this.params)||void 0===r?void 0:r.safetySettings,generationConfig:null===(n=this.params)||void 0===n?void 0:n.generationConfig,tools:null===(s=this.params)||void 0===s?void 0:s.tools,toolConfig:null===(i=this.params)||void 0===i?void 0:i.toolConfig,systemInstruction:null===(o=this.params)||void 0===o?void 0:o.systemInstruction,cachedContent:null===(a=this.params)||void 0===a?void 0:a.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),t),d=K(this._apiKey,this.model,c,u);return this._sendPromise=this._sendPromise.then(()=>d).catch(e=>{throw Error(Q)}).then(e=>e.response).then(e=>{if(e.candidates&&e.candidates.length>0){this._history.push(l);let t=Object.assign({},e.candidates[0].content);t.role||(t.role="model"),this._history.push(t)}else{let t=B(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==Q&&console.error(e)}),d}}async function et(e,t,r,n){return(await N(t,p.COUNT_TOKENS,e,!1,JSON.stringify(r),n)).json()}async function er(e,t,r,n){return(await N(t,p.EMBED_CONTENT,e,!1,JSON.stringify(r),n)).json()}async function en(e,t,r,n){let s=r.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await N(t,p.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),n)).json()}class es{constructor(e,t,r={}){this.apiKey=e,this._requestOptions=r,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=J(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){var r;let n=Z(e),s=Object.assign(Object.assign({},this._requestOptions),t);return V(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(r=this.cachedContent)||void 0===r?void 0:r.name},n),s)}async generateContentStream(e,t={}){var r;let n=Z(e),s=Object.assign(Object.assign({},this._requestOptions),t);return K(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(r=this.cachedContent)||void 0===r?void 0:r.name},n),s)}startChat(e){var t;return new ee(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:null===(t=this.cachedContent)||void 0===t?void 0:t.name},e),this._requestOptions)}async countTokens(e,t={}){let r=function(e,t){var r;let n={model:null==t?void 0:t.model,generationConfig:null==t?void 0:t.generationConfig,safetySettings:null==t?void 0:t.safetySettings,tools:null==t?void 0:t.tools,toolConfig:null==t?void 0:t.toolConfig,systemInstruction:null==t?void 0:t.systemInstruction,cachedContent:null===(r=null==t?void 0:t.cachedContent)||void 0===r?void 0:r.name,contents:[]},s=null!=e.generateContentRequest;if(e.contents){if(s)throw new I("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=e.contents}else if(s)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=G(e);n.contents=[t]}return{generateContentRequest:n}}(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),n=Object.assign(Object.assign({},this._requestOptions),t);return et(this.apiKey,this.model,r,n)}async embedContent(e,t={}){let r="string"==typeof e||Array.isArray(e)?{content:G(e)}:e,n=Object.assign(Object.assign({},this._requestOptions),t);return er(this.apiKey,this.model,r,n)}async batchEmbedContents(e,t={}){let r=Object.assign(Object.assign({},this._requestOptions),t);return en(this.apiKey,this.model,e,r)}}class ei{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new k("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new es(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,r){if(!e.name)throw new I("Cached content must contain a `name` field.");if(!e.model)throw new I("Cached content must contain a `model` field.");for(let r of["model","systemInstruction"])if((null==t?void 0:t[r])&&e[r]&&(null==t?void 0:t[r])!==e[r]){if("model"===r&&(t.model.startsWith("models/")?t.model.replace("models/",""):t.model)===(e.model.startsWith("models/")?e.model.replace("models/",""):e.model))continue;throw new I(`Different value for "${r}" specified in modelParams (${t[r]}) and cachedContent (${e[r]})`)}let n=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new es(this.apiKey,n,r)}}},48269:function(e,t,r){"use strict";r.d(t,{LF:function(){return V}});var n=Object.defineProperty,s={};function i(e){return/^http(s?):/.test(e)||e.startsWith("/")}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(s,{audioClassification:()=>g,audioToAudio:()=>w,automaticSpeechRecognition:()=>y,chatCompletion:()=>F,chatCompletionStream:()=>B,documentQuestionAnswering:()=>H,featureExtraction:()=>k,fillMask:()=>P,imageClassification:()=>v,imageSegmentation:()=>_,imageToImage:()=>R,imageToText:()=>S,objectDetection:()=>E,questionAnswering:()=>C,request:()=>f,sentenceSimilarity:()=>I,streamingRequest:()=>p,summarization:()=>T,tableQuestionAnswering:()=>M,tabularClassification:()=>K,tabularRegression:()=>z,textClassification:()=>$,textGeneration:()=>j,textGenerationStream:()=>U,textToImage:()=>A,textToSpeech:()=>b,tokenClassification:()=>D,translation:()=>L,visualQuestionAnswering:()=>W,zeroShotClassification:()=>q,zeroShotImageClassification:()=>O});var o=new Map,a="https://huggingface.co";async function l(e,t,r){if(i(e))return null;let n=`${e}:${t}`,s=o.get(n);if(s&&s.date<new Date(Date.now()-6e5)&&(o.delete(n),s=void 0),void 0===s){let i=await (r?.fetch??fetch)(`${a}/api/models/${e}?expand[]=pipeline_tag`,{headers:t?{Authorization:`Bearer ${t}`}:{}}).then(e=>e.json()).then(e=>e.pipeline_tag).catch(()=>null);if(!i)return null;s={task:i,date:new Date},o.set(n,{task:i,date:new Date}),o.size>1e3&&o.delete(o.keys().next().value)}return s.task}var c="https://api-inference.huggingface.co",u=null;async function d(e,t){let r;let{accessToken:n,endpointUrl:s,...o}=e,{model:l}=e,{forceTask:d,includeCredentials:f,taskHint:h,wait_for_model:p,use_cache:m,dont_load_model:g,chatCompletion:y}=t??{},b={};if(n&&(b.Authorization=`Bearer ${n}`),!l&&!u&&h){let e=await fetch(`${a}/api/tasks`);e.ok&&(u=await e.json())}if(!l&&u&&h){let e=u[h];e&&(l=e.models[0].id)}if(!l)throw Error("No model provided, and no default model found for this task");let w="data"in e&&!!e.data;w||(b["Content-Type"]="application/json"),p&&(b["X-Wait-For-Model"]="true"),!1===m&&(b["X-Use-Cache"]="false"),g&&(b["X-Load-Model"]="0");let v=(()=>{if(s&&i(l))throw TypeError("Both model and endpointUrl cannot be URLs");return i(l)?(console.warn("Using a model URL is deprecated, please use the `endpointUrl` parameter instead"),l):s||(d?`${c}/pipeline/${d}/${l}`:`${c}/models/${l}`)})();return y&&!v.endsWith("/chat/completions")&&(v+="/v1/chat/completions"),"string"==typeof f?r=f:!0===f&&(r="include"),{url:v,info:{headers:b,method:"POST",body:w?e.data:JSON.stringify({...o.model&&i(o.model)?function(e,t){let r=Array.isArray(t)?t:[t];return Object.assign({},...Object.keys(e).filter(e=>!r.includes(e)).map(t=>{if(void 0!==e[t])return{[t]:e[t]}}))}(o,"model"):o}),...r&&{credentials:r},signal:t?.signal}}}async function f(e,t){let{url:r,info:n}=await d(e,t),s=await (t?.fetch??fetch)(r,n);if(t?.retry_on_error!==!1&&503===s.status&&!t?.wait_for_model)return f(e,{...t,wait_for_model:!0});if(!s.ok){if(s.headers.get("Content-Type")?.startsWith("application/json")){let r=await s.json();if([400,422,404,500].includes(s.status)&&t?.chatCompletion)throw Error(`Server ${e.model} does not seem to support chat completion. Error: ${r.error}`);if(r.error)throw Error(JSON.stringify(r.error))}throw Error("An error occurred while fetching the blob")}return s.headers.get("Content-Type")?.startsWith("application/json")?await s.json():await s.blob()}function h(){return{data:"",event:"",id:"",retry:void 0}}async function*p(e,t){var r;let n,s,i,o;let{url:a,info:l}=await d({...e,stream:!0},t),c=await (t?.fetch??fetch)(a,l);if(t?.retry_on_error!==!1&&503===c.status&&!t?.wait_for_model)return yield*p(e,{...t,wait_for_model:!0});if(!c.ok){if(c.headers.get("Content-Type")?.startsWith("application/json")){let r=await c.json();if([400,422,404,500].includes(c.status)&&t?.chatCompletion)throw Error(`Server ${e.model} does not seem to support chat completion. Error: ${r.error}`);if(r.error)throw Error(r.error)}throw Error(`Server response contains error: ${c.status}`)}if(!c.headers.get("content-type")?.startsWith("text/event-stream"))throw Error("Server does not support event stream content type, it returned "+c.headers.get("content-type"));if(!c.body)return;let u=c.body.getReader(),f=[],m=(r=function(e,t,r){let n=h(),s=new TextDecoder;return function(i,o){if(0===i.length)r?.(n),n=h();else if(o>0){let r=s.decode(i.subarray(0,o)),a=o+(32===i[o+1]?2:1),l=s.decode(i.subarray(a));switch(r){case"data":n.data=n.data?n.data+"\n"+l:l;break;case"event":n.event=l;break;case"id":e(n.id=l);break;case"retry":let c=parseInt(l,10);isNaN(c)||t(n.retry=c)}}}}(()=>{},()=>{},e=>{f.push(e)}),o=!1,function(e){void 0===n?(n=e,s=0,i=-1):n=function(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}(n,e);let t=n.length,a=0;for(;s<t;){o&&(10===n[s]&&(a=++s),o=!1);let e=-1;for(;s<t&&-1===e;++s)switch(n[s]){case 58:-1===i&&(i=s-a);break;case 13:o=!0;case 10:e=s}if(-1===e)break;r(n.subarray(a,e),i),a=s,i=-1}a===t?n=void 0:0!==a&&(n=n.subarray(a),s-=a)});try{for(;;){let{done:e,value:t}=await u.read();if(e)return;for(let e of(m(t),f))if(e.data.length>0){if("[DONE]"===e.data)return;let t=JSON.parse(e.data);if("object"==typeof t&&null!==t&&"error"in t)throw Error(t.error);yield t}f=[]}}finally{u.releaseLock()}}var m=class extends TypeError{constructor(e){super(`Invalid inference output: ${e}. Use the 'request' method with the same parameters to do a custom call with no type checking.`),this.name="InferenceOutputError"}};async function g(e,t){let r=await f(e,{...t,taskHint:"audio-classification"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e.label&&"number"==typeof e.score)))throw new m("Expected Array<{label: string, score: number}>");return r}async function y(e,t){let r=await f(e,{...t,taskHint:"automatic-speech-recognition"});if("string"!=typeof r?.text)throw new m("Expected {text: string}");return r}async function b(e,t){let r=await f(e,{...t,taskHint:"text-to-speech"});if(!(r&&r instanceof Blob))throw new m("Expected Blob");return r}async function w(e,t){let r=await f(e,{...t,taskHint:"audio-to-audio"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e.label&&"string"==typeof e.blob&&"string"==typeof e["content-type"])))throw new m("Expected Array<{label: string, blob: string, content-type: string}>");return r}async function v(e,t){let r=await f(e,{...t,taskHint:"image-classification"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e.label&&"number"==typeof e.score)))throw new m("Expected Array<{label: string, score: number}>");return r}async function _(e,t){let r=await f(e,{...t,taskHint:"image-segmentation"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e.label&&"string"==typeof e.mask&&"number"==typeof e.score)))throw new m("Expected Array<{label: string, mask: string, score: number}>");return r}async function S(e,t){let r=(await f(e,{...t,taskHint:"image-to-text"}))?.[0];if("string"!=typeof r?.generated_text)throw new m("Expected {generated_text: string}");return r}async function E(e,t){let r=await f(e,{...t,taskHint:"object-detection"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e.label&&"number"==typeof e.score&&"number"==typeof e.box.xmin&&"number"==typeof e.box.ymin&&"number"==typeof e.box.xmax&&"number"==typeof e.box.ymax)))throw new m("Expected Array<{label:string; score:number; box:{xmin:number; ymin:number; xmax:number; ymax:number}}>");return r}async function A(e,t){let r=await f(e,{...t,taskHint:"text-to-image"});if(!(r&&r instanceof Blob))throw new m("Expected Blob");return r}function x(e){if(globalThis.Buffer)return globalThis.Buffer.from(e).toString("base64");{let t=[];return e.forEach(e=>{t.push(String.fromCharCode(e))}),globalThis.btoa(t.join(""))}}async function R(e,t){let r;r=e.parameters?{...e,inputs:x(new Uint8Array(e.inputs instanceof ArrayBuffer?e.inputs:await e.inputs.arrayBuffer()))}:{accessToken:e.accessToken,model:e.model,data:e.inputs};let n=await f(r,{...t,taskHint:"image-to-image"});if(!(n&&n instanceof Blob))throw new m("Expected Blob");return n}async function O(e,t){let r={...e,inputs:{image:x(new Uint8Array(e.inputs.image instanceof ArrayBuffer?e.inputs.image:await e.inputs.image.arrayBuffer()))}},n=await f(r,{...t,taskHint:"zero-shot-image-classification"});if(!(Array.isArray(n)&&n.every(e=>"string"==typeof e.label&&"number"==typeof e.score)))throw new m("Expected Array<{label: string, score: number}>");return n}async function k(e,t){let r=e.model?await l(e.model,e.accessToken,t):void 0,n=await f(e,{...t,taskHint:"feature-extraction",..."sentence-similarity"===r&&{forceTask:"feature-extraction"}}),s=(e,t,r=0)=>!(r>t)&&(e.every(e=>Array.isArray(e))?e.every(e=>s(e,t,r+1)):e.every(e=>"number"==typeof e));if(!(Array.isArray(n)&&s(n,3,0)))throw new m("Expected Array<number[][][] | number[][] | number[] | number>");return n}async function P(e,t){let r=await f(e,{...t,taskHint:"fill-mask"});if(!(Array.isArray(r)&&r.every(e=>"number"==typeof e.score&&"string"==typeof e.sequence&&"number"==typeof e.token&&"string"==typeof e.token_str)))throw new m("Expected Array<{score: number, sequence: string, token: number, token_str: string}>");return r}async function C(e,t){let r=await f(e,{...t,taskHint:"question-answering"});if(!("object"==typeof r&&r&&"string"==typeof r.answer&&"number"==typeof r.end&&"number"==typeof r.score&&"number"==typeof r.start))throw new m("Expected {answer: string, end: number, score: number, start: number}");return r}async function I(e,t){let r=e.model?await l(e.model,e.accessToken,t):void 0,n=await f(e,{...t,taskHint:"sentence-similarity",..."feature-extraction"===r&&{forceTask:"sentence-similarity"}});if(!(Array.isArray(n)&&n.every(e=>"number"==typeof e)))throw new m("Expected number[]");return n}async function T(e,t){let r=await f(e,{...t,taskHint:"summarization"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e?.summary_text)))throw new m("Expected Array<{summary_text: string}>");return r?.[0]}async function M(e,t){let r=await f(e,{...t,taskHint:"table-question-answering"});if(!("string"==typeof r?.aggregator&&"string"==typeof r.answer&&Array.isArray(r.cells)&&r.cells.every(e=>"string"==typeof e)&&Array.isArray(r.coordinates)&&r.coordinates.every(e=>Array.isArray(e)&&e.every(e=>"number"==typeof e))))throw new m("Expected {aggregator: string, answer: string, cells: string[], coordinates: number[][]}");return r}async function $(e,t){let r=(await f(e,{...t,taskHint:"text-classification"}))?.[0];if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e?.label&&"number"==typeof e.score)))throw new m("Expected Array<{label: string, score: number}>");return r}function N(e){return Array.isArray(e)?e:[e]}async function j(e,t){let r=N(await f(e,{...t,taskHint:"text-generation"}));if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e?.generated_text)))throw new m("Expected Array<{generated_text: string}>");return r?.[0]}async function*U(e,t){yield*p(e,{...t,taskHint:"text-generation"})}async function D(e,t){let r=N(await f(e,{...t,taskHint:"token-classification"}));if(!(Array.isArray(r)&&r.every(e=>"number"==typeof e.end&&"string"==typeof e.entity_group&&"number"==typeof e.score&&"number"==typeof e.start&&"string"==typeof e.word)))throw new m("Expected Array<{end: number, entity_group: string, score: number, start: number, word: string}>");return r}async function L(e,t){let r=await f(e,{...t,taskHint:"translation"});if(!(Array.isArray(r)&&r.every(e=>"string"==typeof e?.translation_text)))throw new m("Expected type Array<{translation_text: string}>");return r?.length===1?r?.[0]:r}async function q(e,t){let r=N(await f(e,{...t,taskHint:"zero-shot-classification"}));if(!(Array.isArray(r)&&r.every(e=>Array.isArray(e.labels)&&e.labels.every(e=>"string"==typeof e)&&Array.isArray(e.scores)&&e.scores.every(e=>"number"==typeof e)&&"string"==typeof e.sequence)))throw new m("Expected Array<{labels: string[], scores: number[], sequence: string}>");return r}async function F(e,t){let r=await f(e,{...t,taskHint:"text-generation",chatCompletion:!0});if(!("object"==typeof r&&Array.isArray(r?.choices)&&"number"==typeof r?.created&&"string"==typeof r?.id&&"string"==typeof r?.model&&"string"==typeof r?.system_fingerprint&&"object"==typeof r?.usage))throw new m("Expected ChatCompletionOutput");return r}async function*B(e,t){yield*p(e,{...t,taskHint:"text-generation",chatCompletion:!0})}async function H(e,t){let r={...e,inputs:{question:e.inputs.question,image:x(new Uint8Array(e.inputs.image instanceof ArrayBuffer?e.inputs.image:await e.inputs.image.arrayBuffer()))}},n=N(await f(r,{...t,taskHint:"document-question-answering"}))?.[0];if(!("string"==typeof n?.answer&&("number"==typeof n.end||void 0===n.end)&&("number"==typeof n.score||void 0===n.score)&&("number"==typeof n.start||void 0===n.start)))throw new m("Expected Array<{answer: string, end?: number, score?: number, start?: number}>");return n}async function W(e,t){let r={...e,inputs:{question:e.inputs.question,image:x(new Uint8Array(e.inputs.image instanceof ArrayBuffer?e.inputs.image:await e.inputs.image.arrayBuffer()))}},n=(await f(r,{...t,taskHint:"visual-question-answering"}))?.[0];if(!("string"==typeof n?.answer&&"number"==typeof n.score))throw new m("Expected Array<{answer: string, score: number}>");return n}async function z(e,t){let r=await f(e,{...t,taskHint:"tabular-regression"});if(!(Array.isArray(r)&&r.every(e=>"number"==typeof e)))throw new m("Expected number[]");return r}async function K(e,t){let r=await f(e,{...t,taskHint:"tabular-classification"});if(!(Array.isArray(r)&&r.every(e=>"number"==typeof e)))throw new m("Expected number[]");return r}var V=class{accessToken;defaultOptions;constructor(e="",t={}){for(let[r,n]of(this.accessToken=e,this.defaultOptions=t,Object.entries(s)))Object.defineProperty(this,r,{enumerable:!1,value:(r,s)=>n({...r,accessToken:e},{...t,...s})})}endpoint(e){return new J(e,this.accessToken,this.defaultOptions)}},J=class{constructor(e,t="",r={}){for(let[n,i]of Object.entries(s))Object.defineProperty(this,n,{enumerable:!1,value:(n,s)=>i({...n,accessToken:t,endpointUrl:e},{...r,...s})})}}},93662:function(e,t,r){"use strict";r.d(t,{Vi:function(){return i}});var n=r(69719),s=r(7768),i=function(e,t){return(0,s.Z)((0,s.Z)({},t),{},(0,n.Z)({},"X-Lobe-Plugin-Settings","string"==typeof e?e:JSON.stringify(e)))}},26047:function(e,t,r){"use strict";r.d(t,{p:function(){return o}});var n=r(12603),s=n.z.object({properties:n.z.object({}),required:n.z.array(n.z.string()).optional(),type:n.z.enum(["object"])}),i=n.z.object({description:n.z.string(),name:n.z.string(),parameters:s,url:n.z.string().url().optional()}),o=n.z.object({api:n.z.array(i),author:n.z.string().optional(),createAt:n.z.string().optional(),gateway:n.z.string().optional(),homepage:n.z.string().optional(),identifier:n.z.string(),meta:n.z.object({avatar:n.z.string().optional(),description:n.z.string().optional(),tags:n.z.array(n.z.string()).optional(),title:n.z.string().optional()}),openapi:n.z.string().optional(),settings:s.optional(),systemRole:n.z.string().optional(),type:n.z.enum(["default","markdown","standalone"]).optional(),ui:n.z.object({height:n.z.number().optional(),mode:n.z.enum(["iframe","module"]).optional(),url:n.z.string(),width:n.z.number().optional()}).optional()})},53620:function(e,t,r){"use strict";r.d(t,{K5:function(){return g},zV:function(){return b},tZ:function(){return o},aZ:function(){return f},BP:function(){return y},CU:function(){return w},$E:function(){return h},cu:function(){return p.cu},hr:function(){return m}}),r(30349);var n=r(81232);let s=(e,t)=>(r,s)=>async i=>{let o=e.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(e,s,i.input)),a=function(e){let t=new Map;for(let r of e)t.set(r.schemeId,r);return t}(e.httpAuthSchemes),l=(0,n.J)(s),c=[];for(let r of o){let n=a.get(r.schemeId);if(!n){c.push(`HttpAuthScheme \`${r.schemeId}\` was not enabled for this service.`);continue}let i=n.identityProvider(await t.identityProviderConfigProvider(e));if(!i){c.push(`HttpAuthScheme \`${r.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:o={},signingProperties:u={}}=r.propertiesExtractor?.(e,s)||{};r.identityProperties=Object.assign(r.identityProperties||{},o),r.signingProperties=Object.assign(r.signingProperties||{},u),l.selectedHttpAuthScheme={httpAuthOption:r,identity:await i(r.identityProperties),signer:n.signer};break}if(!l.selectedHttpAuthScheme)throw Error(c.join("\n"));return r(i)},i={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},o=(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(s(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),i)}});r(14464).JK.name;var a=r(96108);let l=e=>e=>{throw e},c=(e,t)=>{},u=e=>(e,t)=>async r=>{if(!a.aW.isInstance(r.request))return e(r);let s=(0,n.J)(t).selectedHttpAuthScheme;if(!s)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:i={}},identity:o,signer:u}=s,d=await e({...r,request:await u.sign(r.request,o,i)}).catch((u.errorHandler||l)(i));return(u.successHandler||c)(d.response,i),d},d={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},f=e=>({applyToStack:t=>{t.addRelativeTo(u(e),d)}}),h=e=>{if("function"==typeof e)return e;let t=Promise.resolve(e);return()=>t};var p=r(26576);function m(e,t,r){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=r}class g{constructor(e){for(let[t,r]of(this.authSchemes=new Map,Object.entries(e)))void 0!==r&&this.authSchemes.set(t,r)}getIdentityProvider(e){return this.authSchemes.get(e)}}let y=e=>b(e)&&e.expiration.getTime()-Date.now()<3e5,b=e=>void 0!==e.expiration,w=(e,t,r)=>{let n,s,i;if(void 0===e)return;let o="function"!=typeof e?async()=>Promise.resolve(e):e,a=!1,l=async e=>{s||(s=o(e));try{n=await s,i=!0,a=!1}finally{s=void 0}return n};return void 0===t?async e=>((!i||e?.forceRefresh)&&(n=await l(e)),n):async e=>((!i||e?.forceRefresh)&&(n=await l(e)),a||(r(n)?t(n)&&await l(e):a=!0),n)}},26576:function(e,t,r){"use strict";r.d(t,{Wg:function(){return l},cu:function(){return c},Is:function(){return f}});var n=r(80880),s=r(10637),i=r(80102);class o extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return"base64"===t?o.mutate((0,n.G)(e)):o.mutate((0,i.$)(e));throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,o.prototype),e}transformToString(e="utf-8"){return function(e,t="utf-8"){return"base64"===t?(0,n.s)(e):(0,s.G)(e)}(this,e)}}var a=r(96108);r(58010),"function"==typeof ReadableStream&&ReadableStream;let l=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return o.mutate(e);if(!e)return o.mutate(new Uint8Array);let r=t.streamCollector(e);return o.mutate(await r)};function c(e,t){return new u(e,t)}class u{constructor(e,t){this.input=e,this.context=t,this.query={},this.method="",this.headers={},this.path="",this.body=null,this.hostname="",this.resolvePathStack=[]}async build(){let{hostname:e,protocol:t="https",port:r,path:n}=await this.context.endpoint();for(let e of(this.path=n,this.resolvePathStack))e(this.path);return new a.aW({protocol:t,hostname:this.hostname||e,port:r,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push(t=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+e}),this}p(e,t,r,n){return this.resolvePathStack.push(s=>{this.path=f(s,this.input,e,t,r,n)}),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}function d(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}let f=(e,t,r,n,s,i)=>{if(null!=t&&void 0!==t[r]){let t=n();if(t.length<=0)throw Error("Empty value provided for input HTTP label: "+r+".");e=e.replace(s,i?t.split("/").map(e=>d(e)).join("/"):d(t))}else throw Error("No value provided for input HTTP label: "+r+".");return e}},93833:function(e,t,r){"use strict";r.d(t,{a3:function(){return w},uW:function(){return v}});var n=r(53620),s=r(81232);let i=async e=>{let t=e?.Bucket||"";if("string"==typeof e.Bucket&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),u(t)){if(!0===e.ForcePathStyle)throw Error("Path-style addressing cannot be used with ARN buckets")}else c(t)&&(-1===t.indexOf(".")||String(e.Endpoint).startsWith("http:"))&&t.toLowerCase()===t&&!(t.length<3)||(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e},o=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,a=/(\d+\.){3}\d+/,l=/\.\./,c=e=>o.test(e)&&!a.test(e)&&!l.test(e),u=e=>{let[t,r,n,,,s]=e.split(":"),i="arn"===t&&e.split(":").length>=6,o=!!(i&&r&&n&&s);if(i&&!o)throw Error(`Invalid ARN: ${e} was an invalid ARN.`);return o},d=(e,t,r)=>{let n=async()=>{let n=r[e]??r[t];return"function"==typeof n?n():n};return"credentialScope"===e||"CredentialScope"===t?async()=>{let e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.credentialScope??e?.CredentialScope}:"accountId"===e||"AccountId"===t?async()=>{let e="function"==typeof r.credentials?await r.credentials():r.credentials;return e?.accountId??e?.AccountId}:"endpoint"===e||"endpoint"===t?async()=>{let e=await n();if(e&&"object"==typeof e){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:t,hostname:r,port:n,path:s}=e;return`${t}//${r}${n?":"+n:""}${s}`}}return e}:n},f=async e=>void 0;var h=r(69296);let p=e=>"object"==typeof e?"url"in e?(0,h.e)(e.url):e:(0,h.e)(e),m=async(e,t,r,n)=>{if(!r.endpoint){let e;(e=r.serviceConfiguredEndpoint?await r.serviceConfiguredEndpoint():await f(r.serviceId))&&(r.endpoint=()=>Promise.resolve(p(e)))}let s=await g(e,t,r);if("function"!=typeof r.endpointProvider)throw Error("config.endpointProvider is not set.");return r.endpointProvider(s,n)},g=async(e,t,r)=>{let n={},s=t?.getEndpointParameterInstructions?.()||{};for(let[t,i]of Object.entries(s))switch(i.type){case"staticContextParams":n[t]=i.value;break;case"contextParams":n[t]=e[i.name];break;case"clientContextParams":case"builtInParams":n[t]=await d(i.name,t,r)();break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(i))}return 0===Object.keys(s).length&&Object.assign(n,r),"s3"===String(r.serviceId).toLowerCase()&&await i(n),n},y=({config:e,instructions:t})=>(r,i)=>async o=>{e.endpoint&&(0,n.hr)(i,"ENDPOINT_OVERRIDE","N");let a=await m(o.input,{getEndpointParameterInstructions:()=>t},{...e},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;let l=i.authSchemes?.[0];if(l){i.signing_region=l.signingRegion,i.signing_service=l.signingName;let e=(0,s.J)(i),t=e?.selectedHttpAuthScheme?.httpAuthOption;t&&(t.signingProperties=Object.assign(t.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return r({...o})},b={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:r(14464).JK.name},w=(e,t)=>({applyToStack:r=>{r.addRelativeTo(y({config:e,instructions:t}),b)}}),v=e=>{let t;let r=e.tls??!0,{endpoint:n}=e,i={...e,endpoint:null!=n?async()=>p(await (0,s.$)(n)()):void 0,tls:r,isCustomEndpoint:!!n,useDualstackEndpoint:(0,s.$)(e.useDualstackEndpoint??!1),useFipsEndpoint:(0,s.$)(e.useFipsEndpoint??!1)};return i.serviceConfiguredEndpoint=async()=>(e.serviceId&&!t&&(t=f(e.serviceId)),t),i}},14464:function(e,t,r){"use strict";r.d(t,{p2:function(){return a},JK:function(){return o}});let n=(e,t)=>r=>async n=>{let{response:s}=await r(n);try{let r=await t(s,e);return{response:s,output:r}}catch(e){throw Object.defineProperty(e,"$response",{value:s}),"$metadata"in e||(e.message+="\n  Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.",void 0!==e.$responseBodyText&&e.$response&&(e.$response.body=e.$responseBodyText)),e}},s=(e,t)=>(r,n)=>async s=>{let i=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint;if(!i)throw Error("No valid endpoint provider available.");let o=await t(s.input,{...e,endpoint:i});return r({...s,request:o})},i={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},o={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function a(e,t,r){return{applyToStack:a=>{a.add(n(e,r),i),a.add(s(e,t),o)}}}},96108:function(e,t,r){"use strict";r.d(t,{aW:function(){return i},Zn:function(){return o},cA:function(){return n},AO:function(){return s}});let n=e=>{let t=e.httpHandler;return{setHttpHandler(e){t=e},httpHandler:()=>t,updateHttpClientConfig(e,r){t.updateHttpClientConfig(e,r)},httpHandlerConfigs:()=>t.httpHandlerConfigs()}},s=e=>({httpHandler:e.httpHandler()});r(30349);class i{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.slice(-1)?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){var t;let r=new i({...e,headers:{...e.headers}});return r.query&&(r.query=Object.keys(t=r.query).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})),r}static isInstance(e){return!!e&&"method"in e&&"protocol"in e&&"hostname"in e&&"path"in e&&"object"==typeof e.query&&"object"==typeof e.headers}clone(){return i.clone(this)}}class o{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){return!!e&&"number"==typeof e.statusCode&&"object"==typeof e.headers}}},35023:function(e,t,r){"use strict";r.d(t,{KU:function(){return l},mY:function(){return d},vk:function(){return N},oc:function(){return h},sI:function(){return _},Wg:function(){return c.Wg},to:function(){return S},u$:function(){return m},pY:function(){return b},kE:function(){return I},gj:function(){return M},jv:function(){return R},UI:function(){return j},SQ:function(){return T},qn:function(){return U},PC:function(){return A}});let n=(e,t)=>{let r=[];if(e&&r.push(e),t)for(let e of t)r.push(e);return r},s=(e,t)=>`${e||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`,i=()=>{let e=[],t=[],r=!1,l=new Set,c=e=>e.sort((e,t)=>o[t.step]-o[e.step]||a[t.priority||"normal"]-a[e.priority||"normal"]),u=r=>{let s=!1,i=e=>{let t=n(e.name,e.aliases);if(t.includes(r)){for(let e of(s=!0,t))l.delete(e);return!1}return!0};return e=e.filter(i),t=t.filter(i),s},d=r=>{let s=!1,i=e=>{if(e.middleware===r){for(let t of(s=!0,n(e.name,e.aliases)))l.delete(t);return!1}return!0};return e=e.filter(i),t=t.filter(i),s},f=r=>(e.forEach(e=>{r.add(e.middleware,{...e})}),t.forEach(e=>{r.addRelativeTo(e.middleware,{...e})}),r.identifyOnResolve?.(m.identifyOnResolve()),r),h=e=>{let t=[];return e.before.forEach(e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...h(e))}),t.push(e),e.after.reverse().forEach(e=>{0===e.before.length&&0===e.after.length?t.push(e):t.push(...h(e))}),t},p=(r=!1)=>{let i=[],o=[],a={};return e.forEach(e=>{let t={...e,before:[],after:[]};for(let e of n(t.name,t.aliases))a[e]=t;i.push(t)}),t.forEach(e=>{let t={...e,before:[],after:[]};for(let e of n(t.name,t.aliases))a[e]=t;o.push(t)}),o.forEach(e=>{if(e.toMiddleware){let t=a[e.toMiddleware];if(void 0===t){if(r)return;throw Error(`${e.toMiddleware} is not found when adding ${s(e.name,e.aliases)} middleware ${e.relation} ${e.toMiddleware}`)}"after"===e.relation&&t.after.push(e),"before"===e.relation&&t.before.push(e)}}),c(i).map(h).reduce((e,t)=>(e.push(...t),e),[])},m={add:(t,r={})=>{let{name:i,override:o,aliases:a}=r,c={step:"initialize",priority:"normal",middleware:t,...r},u=n(i,a);if(u.length>0){if(u.some(e=>l.has(e))){if(!o)throw Error(`Duplicate middleware name '${s(i,a)}'`);for(let t of u){let r=e.findIndex(e=>e.name===t||e.aliases?.some(e=>e===t));if(-1===r)continue;let n=e[r];if(n.step!==c.step||c.priority!==n.priority)throw Error(`"${s(n.name,n.aliases)}" middleware with ${n.priority} priority in ${n.step} step cannot be overridden by "${s(i,a)}" middleware with ${c.priority} priority in ${c.step} step.`);e.splice(r,1)}}for(let e of u)l.add(e)}e.push(c)},addRelativeTo:(e,r)=>{let{name:i,override:o,aliases:a}=r,c={middleware:e,...r},u=n(i,a);if(u.length>0){if(u.some(e=>l.has(e))){if(!o)throw Error(`Duplicate middleware name '${s(i,a)}'`);for(let e of u){let r=t.findIndex(t=>t.name===e||t.aliases?.some(t=>t===e));if(-1===r)continue;let n=t[r];if(n.toMiddleware!==c.toMiddleware||n.relation!==c.relation)throw Error(`"${s(n.name,n.aliases)}" middleware ${n.relation} "${n.toMiddleware}" middleware cannot be overridden by "${s(i,a)}" middleware ${c.relation} "${c.toMiddleware}" middleware.`);t.splice(r,1)}}for(let e of u)l.add(e)}t.push(c)},clone:()=>f(i()),use:e=>{e.applyToStack(m)},remove:e=>"string"==typeof e?u(e):d(e),removeByTag:r=>{let s=!1,i=e=>{let{tags:t,name:i,aliases:o}=e;if(t&&t.includes(r)){for(let e of n(i,o))l.delete(e);return s=!0,!1}return!0};return e=e.filter(i),t=t.filter(i),s},concat:e=>{let t=f(i());return t.use(e),t.identifyOnResolve(r||t.identifyOnResolve()||(e.identifyOnResolve?.()??!1)),t},applyToStack:f,identify:()=>p(!0).map(e=>{let t=e.step??e.relation+" "+e.toMiddleware;return s(e.name,e.aliases)+" - "+t}),identifyOnResolve:e=>("boolean"==typeof e&&(r=e),r),resolve:(e,t)=>{for(let r of p().map(e=>e.middleware).reverse())e=r(e,t);return r&&console.log(m.identify()),e}};return m},o={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},a={high:3,normal:2,low:1};class l{constructor(e){this.config=e,this.middlewareStack=i()}send(e,t,r){let n;let s="function"!=typeof t?t:void 0,i="function"==typeof t?t:r;if(void 0===s&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);let t=this.handlers;t.has(e.constructor)?n=t.get(e.constructor):(n=e.resolveMiddleware(this.middlewareStack,this.config,s),t.set(e.constructor,n))}else delete this.handlers,n=e.resolveMiddleware(this.middlewareStack,this.config,s);if(!i)return n(e).then(e=>e.output);n(e).then(e=>i(null,e.output),e=>i(e)).catch(()=>{})}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var c=r(26576),u=r(30349);class d{constructor(){this.middlewareStack=i()}static classBuilder(){return new f}resolveMiddlewareWithContext(e,t,r,{middlewareFn:n,clientName:s,commandName:i,inputFilterSensitiveLog:o,outputFilterSensitiveLog:a,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let s of n.bind(this)(d,e,t,r))this.middlewareStack.use(s);let f=e.concat(this.middlewareStack),{logger:h}=t,p={logger:h,clientName:s,commandName:i,inputFilterSensitiveLog:o,outputFilterSensitiveLog:a,[u.zK]:{commandInstance:this,...l},...c},{requestHandler:m}=t;return f.resolve(e=>m.handle(e.request,r||{}),p)}}class f{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=e=>e,t=e=>e){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}build(){let e;let t=this;return e=class extends d{static getEndpointParameterInstructions(){return t._ep}constructor(...[e]){super(),this.serialize=t._serializer,this.deserialize=t._deserializer,this.input=e??{},t._init(this)}resolveMiddleware(r,n,s){return this.resolveMiddlewareWithContext(r,n,s,{CommandCtor:e,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog,outputFilterSensitiveLog:t._outputFilterSensitiveLog,smithyContext:t._smithyContext,additionalContext:t._additionalContext})}}}}let h="***SensitiveInformation***",p=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw TypeError(`Expected integer, got ${typeof e}: ${e}`)}},m=e=>g(e,32),g=(e,t)=>{let r=p(e);if(void 0!==r&&y(r,t)!==r)throw TypeError(`Expected ${t}-bit integer, got ${e}`);return r},y=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},b=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return v.warn(w(`Expected string, got ${typeof e}: ${e}`)),String(e);throw TypeError(`Expected string, got ${typeof e}: ${e}`)}},w=e=>String(TypeError(e).stack||e).split("\n").slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join("\n"),v={warn:console.warn};class _ extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,_.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}}let S=(e,t={})=>{Object.entries(t).filter(([,e])=>void 0!==e).forEach(([t,r])=>{(void 0==e[t]||""===e[t])&&(e[t]=r)});let r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e},E=({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{let s=x(e),i=s.httpStatusCode?s.httpStatusCode+"":void 0;throw S(new r({name:t?.code||t?.Code||n||i||"UnknownError",$fault:"client",$metadata:s}),t)},A=e=>({output:t,parsedBody:r,errorCode:n})=>{E({output:t,parsedBody:r,exceptionCtor:e,errorCode:n})},x=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}),R=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},O=e=>{let t=[];for(let r in u.f3){let n=u.f3[r];void 0!==e[n]&&t.push({algorithmId:()=>n,checksumConstructor:()=>e[n]})}return{_checksumAlgorithms:t,addChecksumAlgorithm(e){this._checksumAlgorithms.push(e)},checksumAlgorithms(){return this._checksumAlgorithms}}},k=e=>{let t={};return e.checksumAlgorithms().forEach(e=>{t[e.algorithmId()]=e.checksumConstructor()}),t},P=e=>{let t=e.retryStrategy;return{setRetryStrategy(e){t=e},retryStrategy:()=>t}},C=e=>{let t={};return t.retryStrategy=e.retryStrategy(),t},I=e=>({...O(e),...P(e)}),T=e=>({...k(e),...C(e)}),M=e=>null!=e,$=function(){let e=Object.getPrototypeOf(this).constructor,t=Function.bind.apply(String,[null,...arguments]),r=new t;return Object.setPrototypeOf(r,e.prototype),r};$.prototype=Object.create(String.prototype,{constructor:{value:$,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf($,String);class N{trace(){}debug(){}info(){}warn(){}error(){}}function j(e,t,r){let n,s;if(void 0===t&&void 0===r)n={},s=e;else{if(n=e,"function"==typeof t)return D(n,t,s=r);s=t}for(let e of Object.keys(s)){if(!Array.isArray(s[e])){n[e]=s[e];continue}L(n,null,s,e)}return n}let U=(e,t)=>{let r={};for(let n in t)L(r,e,t,n);return r},D=(e,t,r)=>j(e,Object.entries(r).reduce((e,[r,n])=>(Array.isArray(n)?e[r]=n:"function"==typeof n?e[r]=[t,n()]:e[r]=[t,n],e),{})),L=(e,t,r,n)=>{if(null!==t){let s=r[n];"function"==typeof s&&(s=[,s]);let[i=q,o=F,a=n]=s;("function"==typeof i&&i(t[a])||"function"!=typeof i&&i)&&(e[n]=o(t[a]));return}let[s,i]=r[n];if("function"==typeof i){let t;let r=void 0===s&&null!=(t=i()),o="function"==typeof s&&!!s(void 0)||"function"!=typeof s&&!!s;r?e[n]=t:o&&(e[n]=i())}else{let t=void 0===s&&null!=i,r="function"==typeof s&&!!s(i)||"function"!=typeof s&&!!s;(t||r)&&(e[n]=i)}},q=e=>null!=e,F=e=>e},30349:function(e,t,r){"use strict";var n,s,i,o,a,l,c,u,d,f,h,p,m,g;r.d(t,{f3:function(){return o},cj:function(){return i},zK:function(){return y}}),(u=n||(n={})).HEADER="header",u.QUERY="query",(d=s||(s={})).HEADER="header",d.QUERY="query",(f=i||(i={})).HTTP="http",f.HTTPS="https",(h=o||(o={})).MD5="md5",h.CRC32="crc32",h.CRC32C="crc32c",h.SHA1="sha1",h.SHA256="sha256",(p=a||(a={}))[p.HEADER=0]="HEADER",p[p.TRAILER=1]="TRAILER";let y="__smithy_context";(m=l||(l={})).PROFILE="profile",m.SSO_SESSION="sso-session",m.SERVICES="services",(g=c||(c={})).HTTP_0_9="http/0.9",g.HTTP_1_0="http/1.0",g.TDS_8_0="tds/8.0"},69296:function(e,t,r){"use strict";r.d(t,{e:function(){return n}});let n=e=>{let t;if("string"==typeof e)return n(new URL(e));let{hostname:r,pathname:s,port:i,protocol:o,search:a}=e;return a&&(t=function(e){let t={};if(e=e.replace(/^\?/,""))for(let r of e.split("&")){let[e,n=null]=r.split("=");e=decodeURIComponent(e),n&&(n=decodeURIComponent(n)),e in t?Array.isArray(t[e])?t[e].push(n):t[e]=[t[e],n]:t[e]=n}return t}(a)),{hostname:r,port:i?parseInt(i):void 0,protocol:o,path:s,query:t}}},80880:function(e,t,r){"use strict";r.d(t,{G:function(){return i},s:function(){return a}});let n={},s=Array(64);for(let e=0;e+65<=90;e++){let t=String.fromCharCode(e+65);n[t]=e,s[e]=t}for(let e=0;e+97<=122;e++){let t=String.fromCharCode(e+97),r=e+26;n[t]=r,s[r]=t}for(let e=0;e<10;e++){n[e.toString(10)]=e+52;let t=e.toString(10),r=e+52;n[t]=r,s[r]=t}n["+"]=62,s[62]="+",n["/"]=63,s[63]="/";let i=e=>{let t=e.length/4*3;"=="===e.slice(-2)?t-=2:"="===e.slice(-1)&&t--;let r=new ArrayBuffer(t),s=new DataView(r);for(let t=0;t<e.length;t+=4){let r=0,i=0;for(let s=t,o=t+3;s<=o;s++)if("="!==e[s]){if(!(e[s]in n))throw TypeError(`Invalid character ${e[s]} in base64 string.`);r|=n[e[s]]<<(o-s)*6,i+=6}else r>>=6;let o=t/4*3;r>>=i%8;let a=Math.floor(i/8);for(let e=0;e<a;e++){let t=(a-e-1)*8;s.setUint8(o+e,(r&255<<t)>>t)}}return new Uint8Array(r)};var o=r(80102);function a(e){let t;let r="object"==typeof(t="string"==typeof e?(0,o.$)(e):e)&&"number"==typeof t.length,n="object"==typeof t&&"number"==typeof t.byteOffset&&"number"==typeof t.byteLength;if(!r&&!n)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let e=0;e<t.length;e+=3){let r=0,n=0;for(let s=e,i=Math.min(e+3,t.length);s<i;s++)r|=t[s]<<(i-s-1)*8,n+=8;let o=Math.ceil(n/6);r<<=6*o-n;for(let e=1;e<=o;e++){let t=(o-e)*6;i+=s[(r&63<<t)>>t]}i+="==".slice(0,4-o)}return i}},58010:function(e,t,r){"use strict";r.d(t,{H:function(){return i},N:function(){return o}});let n={},s={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),n[e]=t,s[t]=e}function i(e){if(e.length%2!=0)throw Error("Hex encoded strings must have an even number length");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2){let n=e.slice(r,r+2).toLowerCase();if(n in s)t[r/2]=s[n];else throw Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return t}function o(e){let t="";for(let r=0;r<e.byteLength;r++)t+=n[e[r]];return t}},81232:function(e,t,r){"use strict";r.d(t,{J:function(){return s},$:function(){return i}});var n=r(30349);let s=e=>e[n.zK]||(e[n.zK]={}),i=e=>{if("function"==typeof e)return e;let t=Promise.resolve(e);return()=>t}},80102:function(e,t,r){"use strict";r.d(t,{$:function(){return n}});let n=e=>new TextEncoder().encode(e)},10637:function(e,t,r){"use strict";r.d(t,{G:function(){return n}});let n=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(e)}},25231:function(e,t,r){"use strict";function n(e){return"<s>[INST] "+e.map(({content:e,role:t},r)=>{if("user"===t)return e.trim();if("assistant"===t)return` [/INST] ${e}</s><s>[INST] `;if("function"===t)throw Error("Llama 2 does not support function calls.");if("system"===t&&0===r)return`<<SYS>>
${e}
<</SYS>>

`;throw Error(`Invalid message role: ${t}`)}).join("")+" [/INST]"}r.d(t,{k0:function(){return n}})},22510:function(e){var t;t=function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var s=t[n]={i:n,l:!1,exports:{}};return e[n].call(s.exports,s,s.exports,r),s.l=!0,s.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t||4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var s in e)r.d(n,s,(function(t){return e[t]}).bind(null,s));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=90)}({17:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n=r(18),s=function(){function e(){}return e.getFirstMatch=function(e,t){var r=t.match(e);return r&&r.length>0&&r[1]||""},e.getSecondMatch=function(e,t){var r=t.match(e);return r&&r.length>1&&r[2]||""},e.matchAndReturnConst=function(e,t,r){if(e.test(t))return r},e.getWindowsVersionName=function(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0});if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e.getAndroidVersionName=function(e){var t=e.split(".").splice(0,2).map(function(e){return parseInt(e,10)||0});if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0},e.getVersionPrecision=function(e){return e.split(".").length},e.compareVersions=function(t,r,n){void 0===n&&(n=!1);var s=e.getVersionPrecision(t),i=e.getVersionPrecision(r),o=Math.max(s,i),a=0,l=e.map([t,r],function(t){var r=o-e.getVersionPrecision(t),n=t+Array(r+1).join(".0");return e.map(n.split("."),function(e){return Array(20-e.length).join("0")+e}).reverse()});for(n&&(a=o-Math.min(s,i)),o-=1;o>=a;){if(l[0][o]>l[1][o])return 1;if(l[0][o]===l[1][o]){if(o===a)return 0;o-=1}else if(l[0][o]<l[1][o])return -1}},e.map=function(e,t){var r,n=[];if(Array.prototype.map)return Array.prototype.map.call(e,t);for(r=0;r<e.length;r+=1)n.push(t(e[r]));return n},e.find=function(e,t){var r,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(r=0,n=e.length;r<n;r+=1){var s=e[r];if(t(s,r))return s}},e.assign=function(e){for(var t,r,n=arguments.length,s=Array(n>1?n-1:0),i=1;i<n;i++)s[i-1]=arguments[i];if(Object.assign)return Object.assign.apply(Object,[e].concat(s));for(t=0,r=s.length;t<r;t+=1)(function(){var r=s[t];"object"==typeof r&&null!==r&&Object.keys(r).forEach(function(t){e[t]=r[t]})})();return e},e.getBrowserAlias=function(e){return n.BROWSER_ALIASES_MAP[e]},e.getBrowserTypeByAlias=function(e){return n.BROWSER_MAP[e]||""},e}();t.default=s,e.exports=t.default},18:function(e,t,r){"use strict";t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},t.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},t.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},t.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},t.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n,s=(n=r(91))&&n.__esModule?n:{default:n},i=r(18),o=function(){function e(){}return e.getParser=function(e,t){if(void 0===t&&(t=!1),"string"!=typeof e)throw Error("UserAgent should be a string");return new s.default(e,t)},e.parse=function(e){return new s.default(e).getResult()},function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(e,[{key:"BROWSER_MAP",get:function(){return i.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return i.ENGINE_MAP}},{key:"OS_MAP",get:function(){return i.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return i.PLATFORMS_MAP}}]),e}();t.default=o,e.exports=t.default},91:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n=l(r(92)),s=l(r(93)),i=l(r(94)),o=l(r(95)),a=l(r(17));function l(e){return e&&e.__esModule?e:{default:e}}var c=function(){function e(e,t){if(void 0===t&&(t=!1),null==e||""===e)throw Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}var t=e.prototype;return t.getUA=function(){return this._ua},t.test=function(e){return e.test(this._ua)},t.parseBrowser=function(){var e=this;this.parsedResult.browser={};var t=a.default.find(n.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA())),this.parsedResult.browser},t.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t.getBrowserName=function(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t.getBrowserVersion=function(){return this.getBrowser().version},t.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t.parseOS=function(){var e=this;this.parsedResult.os={};var t=a.default.find(s.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os},t.getOSName=function(e){var t=this.getOS().name;return e?String(t).toLowerCase()||"":t||""},t.getOSVersion=function(){return this.getOS().version},t.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t.getPlatformType=function(e){void 0===e&&(e=!1);var t=this.getPlatform().type;return e?String(t).toLowerCase()||"":t||""},t.parsePlatform=function(){var e=this;this.parsedResult.platform={};var t=a.default.find(i.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform},t.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t.getEngineName=function(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t.parseEngine=function(){var e=this;this.parsedResult.engine={};var t=a.default.find(o.default,function(t){if("function"==typeof t.test)return t.test(e);if(t.test instanceof Array)return t.test.some(function(t){return e.test(t)});throw Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine},t.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t.getResult=function(){return a.default.assign({},this.parsedResult)},t.satisfies=function(e){var t=this,r={},n=0,s={},i=0;if(Object.keys(e).forEach(function(t){var o=e[t];"string"==typeof o?(s[t]=o,i+=1):"object"==typeof o&&(r[t]=o,n+=1)}),n>0){var o=Object.keys(r),l=a.default.find(o,function(e){return t.isOS(e)});if(l){var c=this.satisfies(r[l]);if(void 0!==c)return c}var u=a.default.find(o,function(e){return t.isPlatform(e)});if(u){var d=this.satisfies(r[u]);if(void 0!==d)return d}}if(i>0){var f=Object.keys(s),h=a.default.find(f,function(e){return t.isBrowser(e,!0)});if(void 0!==h)return this.compareVersion(s[h])}},t.isBrowser=function(e,t){void 0===t&&(t=!1);var r=this.getBrowserName().toLowerCase(),n=e.toLowerCase(),s=a.default.getBrowserTypeByAlias(n);return t&&s&&(n=s.toLowerCase()),n===r},t.compareVersion=function(e){var t=[0],r=e,n=!1,s=this.getBrowserVersion();if("string"==typeof s)return">"===e[0]||"<"===e[0]?(r=e.substr(1),"="===e[1]?(n=!0,r=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?r=e.substr(1):"~"===e[0]&&(n=!0,r=e.substr(1)),t.indexOf(a.default.compareVersions(s,r,n))>-1},t.isOS=function(e){return this.getOSName(!0)===String(e).toLowerCase()},t.isPlatform=function(e){return this.getPlatformType(!0)===String(e).toLowerCase()},t.isEngine=function(e){return this.getEngineName(!0)===String(e).toLowerCase()},t.is=function(e,t){return void 0===t&&(t=!1),this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)},t.some=function(e){var t=this;return void 0===e&&(e=[]),e.some(function(e){return t.is(e)})},e}();t.default=c,e.exports=t.default},92:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n,s=(n=r(17))&&n.__esModule?n:{default:n},i=/version\/(\d+(\.?_?\d+)+)/i,o=[{test:[/googlebot/i],describe:function(e){var t={name:"Googlebot"},r=s.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/opera/i],describe:function(e){var t={name:"Opera"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opr\/|opios/i],describe:function(e){var t={name:"Opera"},r=s.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/SamsungBrowser/i],describe:function(e){var t={name:"Samsung Internet for Android"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Whale/i],describe:function(e){var t={name:"NAVER Whale Browser"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MZBrowser/i],describe:function(e){var t={name:"MZ Browser"},r=s.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/focus/i],describe:function(e){var t={name:"Focus"},r=s.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/swing/i],describe:function(e){var t={name:"Swing"},r=s.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/coast/i],describe:function(e){var t={name:"Opera Coast"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e){var t={name:"Opera Touch"},r=s.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/yabrowser/i],describe:function(e){var t={name:"Yandex Browser"},r=s.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/ucbrowser/i],describe:function(e){var t={name:"UC Browser"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/Maxthon|mxios/i],describe:function(e){var t={name:"Maxthon"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/epiphany/i],describe:function(e){var t={name:"Epiphany"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/puffin/i],describe:function(e){var t={name:"Puffin"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sleipnir/i],describe:function(e){var t={name:"Sleipnir"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/k-meleon/i],describe:function(e){var t={name:"K-Meleon"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/micromessenger/i],describe:function(e){var t={name:"WeChat"},r=s.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/qqbrowser/i],describe:function(e){var t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},r=s.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/msie|trident/i],describe:function(e){var t={name:"Internet Explorer"},r=s.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/\sedg\//i],describe:function(e){var t={name:"Microsoft Edge"},r=s.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/edg([ea]|ios)/i],describe:function(e){var t={name:"Microsoft Edge"},r=s.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/vivaldi/i],describe:function(e){var t={name:"Vivaldi"},r=s.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/seamonkey/i],describe:function(e){var t={name:"SeaMonkey"},r=s.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/sailfish/i],describe:function(e){var t={name:"Sailfish"},r=s.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return r&&(t.version=r),t}},{test:[/silk/i],describe:function(e){var t={name:"Amazon Silk"},r=s.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/phantom/i],describe:function(e){var t={name:"PhantomJS"},r=s.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/slimerjs/i],describe:function(e){var t={name:"SlimerJS"},r=s.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t={name:"BlackBerry"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t={name:"WebOS Browser"},r=s.default.getFirstMatch(i,e)||s.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/bada/i],describe:function(e){var t={name:"Bada"},r=s.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/tizen/i],describe:function(e){var t={name:"Tizen"},r=s.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/qupzilla/i],describe:function(e){var t={name:"QupZilla"},r=s.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/firefox|iceweasel|fxios/i],describe:function(e){var t={name:"Firefox"},r=s.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/electron/i],describe:function(e){var t={name:"Electron"},r=s.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/MiuiBrowser/i],describe:function(e){var t={name:"Miui"},r=s.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/chromium/i],describe:function(e){var t={name:"Chromium"},r=s.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/chrome|crios|crmo/i],describe:function(e){var t={name:"Chrome"},r=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/GSA/i],describe:function(e){var t={name:"Google Search"},r=s.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t={name:"Android Browser"},r=s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/playstation 4/i],describe:function(e){var t={name:"PlayStation 4"},r=s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/safari|applewebkit/i],describe:function(e){var t={name:"Safari"},r=s.default.getFirstMatch(i,e);return r&&(t.version=r),t}},{test:[/.*/i],describe:function(e){var t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:s.default.getFirstMatch(t,e),version:s.default.getSecondMatch(t,e)}}}];t.default=o,e.exports=t.default},93:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n,s=(n=r(17))&&n.__esModule?n:{default:n},i=r(18),o=[{test:[/Roku\/DVP/],describe:function(e){var t=s.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:i.OS_MAP.Roku,version:t}}},{test:[/windows phone/i],describe:function(e){var t=s.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:i.OS_MAP.WindowsPhone,version:t}}},{test:[/windows /i],describe:function(e){var t=s.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),r=s.default.getWindowsVersionName(t);return{name:i.OS_MAP.Windows,version:t,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e){var t={name:i.OS_MAP.iOS},r=s.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return r&&(t.version=r),t}},{test:[/macintosh/i],describe:function(e){var t=s.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),r=s.default.getMacOSVersionName(t),n={name:i.OS_MAP.MacOS,version:t};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe:function(e){var t=s.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:i.OS_MAP.iOS,version:t}}},{test:function(e){var t=!e.test(/like android/i),r=e.test(/android/i);return t&&r},describe:function(e){var t=s.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),r=s.default.getAndroidVersionName(t),n={name:i.OS_MAP.Android,version:t};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe:function(e){var t=s.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),r={name:i.OS_MAP.WebOS};return t&&t.length&&(r.version=t),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e){var t=s.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||s.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||s.default.getFirstMatch(/\bbb(\d+)/i,e);return{name:i.OS_MAP.BlackBerry,version:t}}},{test:[/bada/i],describe:function(e){var t=s.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:i.OS_MAP.Bada,version:t}}},{test:[/tizen/i],describe:function(e){var t=s.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:i.OS_MAP.Tizen,version:t}}},{test:[/linux/i],describe:function(){return{name:i.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:i.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e){var t=s.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:i.OS_MAP.PlayStation4,version:t}}}];t.default=o,e.exports=t.default},94:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n,s=(n=r(17))&&n.__esModule?n:{default:n},i=r(18),o=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e){var t=s.default.getFirstMatch(/(can-l01)/i,e)&&"Nova",r={type:i.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t&&(r.model=t),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(e){var t=e.test(/ipod|iphone/i),r=e.test(/like (ipod|iphone)/i);return t&&!r},describe:function(e){var t=s.default.getFirstMatch(/(ipod|iphone)/i,e);return{type:i.PLATFORMS_MAP.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(e){return"blackberry"===e.getBrowserName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e){return"bada"===e.getBrowserName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(e){return"windows phone"===e.getBrowserName()},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e){var t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(e){return"android"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(e){return"macos"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e){return"windows"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(e){return"linux"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(e){return"playstation 4"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(e){return"roku"===e.getOSName(!0)},describe:function(){return{type:i.PLATFORMS_MAP.tv}}}];t.default=o,e.exports=t.default},95:function(e,t,r){"use strict";t.__esModule=!0,t.default=void 0;var n,s=(n=r(17))&&n.__esModule?n:{default:n},i=r(18),o=[{test:function(e){return"microsoft edge"===e.getBrowserName(!0)},describe:function(e){if(/\sedg\//i.test(e))return{name:i.ENGINE_MAP.Blink};var t=s.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:i.ENGINE_MAP.EdgeHTML,version:t}}},{test:[/trident/i],describe:function(e){var t={name:i.ENGINE_MAP.Trident},r=s.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){return e.test(/presto/i)},describe:function(e){var t={name:i.ENGINE_MAP.Presto},r=s.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:function(e){var t=e.test(/gecko/i),r=e.test(/like gecko/i);return t&&!r},describe:function(e){var t={name:i.ENGINE_MAP.Gecko},r=s.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:i.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e){var t={name:i.ENGINE_MAP.WebKit},r=s.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return r&&(t.version=r),t}}];t.default=o,e.exports=t.default}})},e.exports=t()},99765:function(e,t,r){"use strict";let n,s;r.d(t,{N:function(){return B}});var i=r(73235),o=r(51535),a=r(7464),l=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function c(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function u(e,t){return e.name===t}function d(e){return parseInt(e.name.slice(4),10)}function f(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var h=(e,...t)=>f("Key must be ",e,...t);function p(e,t,...r){return f(`Key for the ${e} algorithm must be `,t,...r)}var m=e=>!!(0,a.b)(e)||e?.[Symbol.toStringTag]==="KeyObject";let g=["CryptoKey"];var y=r(65664);function b(e){return(0,y.Z)(e)&&"string"==typeof e.kty}var w=r(69477);let v=e=>(0,i.Jx)(e),_=e=>e?.[Symbol.toStringTag]==="KeyObject",S=async(e,t,r,n,s=!1)=>{let i=e.get(t);if(i?.[n])return i[n];let o=await (0,w.Z)({...r,alg:n});return s&&Object.freeze(t),i?i[n]=o:e.set(t,{[n]:o}),o};var E={normalizePublicKey:(e,t)=>{if(_(e)){let r=e.export({format:"jwk"});return(delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k)?v(r.k):(s||(s=new WeakMap),S(s,e,r,t))}return b(e)?e.k?(0,i.Jx)(e.k):(s||(s=new WeakMap),S(s,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(_(e)){let r=e.export({format:"jwk"});return r.k?v(r.k):(n||(n=new WeakMap),S(n,e,r,t))}return b(e)?e.k?(0,i.Jx)(e.k):(n||(n=new WeakMap),S(n,e,e,t,!0)):e}};async function A(e,t,r){if("sign"===r&&(t=await E.normalizePrivateKey(t,e)),"verify"===r&&(t=await E.normalizePublicKey(t,e)),(0,a.b)(t))return!function(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!u(e.algorithm,"HMAC"))throw c("HMAC");let r=parseInt(t.slice(2),10);if(d(e.algorithm.hash)!==r)throw c(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!u(e.algorithm,"RSASSA-PKCS1-v1_5"))throw c("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(d(e.algorithm.hash)!==r)throw c(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!u(e.algorithm,"RSA-PSS"))throw c("RSA-PSS");let r=parseInt(t.slice(2),10);if(d(e.algorithm.hash)!==r)throw c(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw c("Ed25519 or Ed448");break;case"ES256":case"ES384":case"ES512":{if(!u(e.algorithm,"ECDSA"))throw c("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw c(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw TypeError(e)}}(e,r)}(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(h(t,...g));return a.Z.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw TypeError(h(t,...g,"Uint8Array","JSON Web Key"))}let x=async(e,t,r)=>{let n=await A(e,t,"sign");return l(e,n),new Uint8Array(await a.Z.subtle.sign(function(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new o.jq(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,r))};var R=(...e)=>{let t;let r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0},O=r(48056);let k=e=>e?.[Symbol.toStringTag],P=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&t.key_ops.includes?.(r)!==!0)throw TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},C=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&b(t)){if(b(t)&&"oct"===t.kty&&"string"==typeof t.k&&P(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!m(t))throw TypeError(p(e,t,...g,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw TypeError(`${k(t)} instances for symmetric algorithms must be of type "secret"`)}},I=(e,t,r,n)=>{if(n&&b(t))switch(r){case"sign":if("oct"!==t.kty&&"string"==typeof t.d&&P(e,t,r))return;throw TypeError("JSON Web Key for this operation be a private JWK");case"verify":if("oct"!==t.kty&&void 0===t.d&&P(e,t,r))return;throw TypeError("JSON Web Key for this operation be a public JWK")}if(!m(t))throw TypeError(p(e,t,...g,n?"JSON Web Key":null));if("secret"===t.type)throw TypeError(`${k(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw TypeError(`${k(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw TypeError(`${k(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw TypeError(`${k(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw TypeError(`${k(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function T(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?C(t,r,n,e):I(t,r,n,e)}T.bind(void 0,!1);let M=T.bind(void 0,!0);var $=function(e,t,r,n,s){let i;if(void 0!==s.crit&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let a of(i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,n.crit)){if(!i.has(a))throw new o.jq(`Extension Header Parameter "${a}" is not recognized`);if(void 0===s[a])throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&void 0===n[a])throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)};class N{constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){let r;if(!this._protectedHeader&&!this._unprotectedHeader)throw new o.GW("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!R(this._protectedHeader,this._unprotectedHeader))throw new o.GW("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=$(o.GW,new Map([["b64",!0]]),t?.crit,this._protectedHeader,n),a=!0;if(s.has("b64")&&"boolean"!=typeof(a=this._protectedHeader.b64))throw new o.GW('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:l}=n;if("string"!=typeof l||!l)throw new o.GW('JWS "alg" (Algorithm) Header Parameter missing or invalid');M(l,e,"sign");let c=this._payload;a&&(c=O.g7.encode((0,i.cv)(c))),r=this._protectedHeader?O.g7.encode((0,i.cv)(JSON.stringify(this._protectedHeader))):O.g7.encode("");let u=(0,O.zo)(r,O.g7.encode("."),c),d=await x(l,e,u),f={signature:(0,i.cv)(d),payload:""};return a&&(f.payload=O.xv.decode(c)),this._unprotectedHeader&&(f.header=this._unprotectedHeader),this._protectedHeader&&(f.protected=O.xv.decode(r)),f}}class j{constructor(e){this._flattened=new N(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}var U=e=>Math.floor(e.getTime()/1e3);let D=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var L=e=>{let t;let r=D.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let n=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*n);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*n);break;case"day":case"days":case"d":t=Math.round(86400*n);break;case"week":case"weeks":case"w":t=Math.round(604800*n);break;default:t=Math.round(31557600*n)}return"-"===r[1]||"ago"===r[4]?-t:t};function q(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}class F{constructor(e={}){if(!(0,y.Z)(e))throw TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:q("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:q("setNotBefore",U(e))}:this._payload={...this._payload,nbf:U(new Date)+L(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:q("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:q("setExpirationTime",U(e))}:this._payload={...this._payload,exp:U(new Date)+L(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:U(new Date)}:e instanceof Date?this._payload={...this._payload,iat:q("setIssuedAt",U(e))}:"string"==typeof e?this._payload={...this._payload,iat:q("setIssuedAt",U(new Date)+L(e))}:this._payload={...this._payload,iat:q("setIssuedAt",e)},this}}class B extends F{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new j(O.g7.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new o.uv("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}},24049:function(e,t,r){"use strict";r.d(t,{nO:function(){return a}});var n=r(73235),s=r(69477),i=r(51535),o=r(65664);async function a(e,t){if(!(0,o.Z)(e))throw TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return(0,n.Jx)(e.k);case"RSA":if(void 0!==e.oth)throw new i.jq('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(0,s.Z)({...e,alg:t});default:throw new i.jq('Unsupported "kty" (Key Type) Parameter value')}}},48056:function(e,t,r){"use strict";r.d(t,{g7:function(){return n},xv:function(){return s},zo:function(){return i}});let n=new TextEncoder,s=new TextDecoder;function i(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}},65664:function(e,t,r){"use strict";function n(e){if(!("object"==typeof e&&null!==e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}r.d(t,{Z:function(){return n}})},73235:function(e,t,r){"use strict";r.d(t,{Jx:function(){return a},cv:function(){return i}});var n=r(48056);let s=e=>{let t=e;"string"==typeof t&&(t=n.g7.encode(t));let r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))},i=e=>s(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),o=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},a=e=>{let t=e;t instanceof Uint8Array&&(t=n.xv.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return o(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}},69477:function(e,t,r){"use strict";var n=r(7464),s=r(51535);let i=async e=>{if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new s.jq('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new s.jq('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new s.jq('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new s.jq('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),i=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,n.Z.subtle.importKey("jwk",o,...i)};t.Z=i},7464:function(e,t,r){"use strict";r.d(t,{b:function(){return n}}),t.Z=crypto;let n=e=>e instanceof CryptoKey},51535:function(e,t,r){"use strict";r.d(t,{GW:function(){return u},jq:function(){return a},uv:function(){return d}});class n extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}n.code="ERR_JOSE_GENERIC";class s extends n{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}s.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class i extends n{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}i.code="ERR_JWT_EXPIRED";class o extends n{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}o.code="ERR_JOSE_ALG_NOT_ALLOWED";class a extends n{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}a.code="ERR_JOSE_NOT_SUPPORTED";class l extends n{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}l.code="ERR_JWE_DECRYPTION_FAILED";class c extends n{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}c.code="ERR_JWE_INVALID";class u extends n{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}u.code="ERR_JWS_INVALID";class d extends n{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}d.code="ERR_JWT_INVALID";class f extends n{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}f.code="ERR_JWK_INVALID";class h extends n{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}h.code="ERR_JWKS_INVALID";class p extends n{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}p.code="ERR_JWKS_NO_MATCHING_KEY";class m extends n{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}m.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class g extends n{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}g.code="ERR_JWKS_TIMEOUT";class y extends n{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}y.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"},97538:function(e,t,r){"use strict";r.d(t,{Z:function(){return B}});var n=r(66008),s=r(7468),i=r(1188),o=r(88989),a=r(37725),l=r(46247),c=r(95106),u=r(66046),d=r(18361),f=r(99519),h=r(65329),p=r(31387),m=r(45714),g=Object.prototype.hasOwnProperty,y=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&g.call(e,"index")&&(r.index=e.index,r.input=e.input),r},b=r(40516),w=function(e,t){var r=t?(0,b.Z)(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)},v=/\w*$/,_=function(e){var t=new e.constructor(e.source,v.exec(e));return t.lastIndex=e.lastIndex,t},S=r(52175),E=S.Z?S.Z.prototype:void 0,A=E?E.valueOf:void 0,x=r(48944),R=function(e,t,r){var n=e.constructor;switch(t){case"[object ArrayBuffer]":return(0,b.Z)(e);case"[object Boolean]":case"[object Date]":return new n(+e);case"[object DataView]":return w(e,r);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return(0,x.Z)(e,r);case"[object Map]":case"[object Set]":return new n;case"[object Number]":case"[object String]":return new n(e);case"[object RegExp]":return _(e);case"[object Symbol]":return A?Object(A.call(e)):{}}},O=r(20946),k=r(67326),P=r(49462),C=r(46709),I=r(37165),T=r(51450),M=T.Z&&T.Z.isMap,$=M?(0,I.Z)(M):function(e){return(0,C.Z)(e)&&"[object Map]"==(0,m.Z)(e)},N=r(83321),j=T.Z&&T.Z.isSet,U=j?(0,I.Z)(j):function(e){return(0,C.Z)(e)&&"[object Set]"==(0,m.Z)(e)},D="[object Arguments]",L="[object Function]",q="[object Object]",F={};F[D]=F["[object Array]"]=F["[object ArrayBuffer]"]=F["[object DataView]"]=F["[object Boolean]"]=F["[object Date]"]=F["[object Float32Array]"]=F["[object Float64Array]"]=F["[object Int8Array]"]=F["[object Int16Array]"]=F["[object Int32Array]"]=F["[object Map]"]=F["[object Number]"]=F[q]=F["[object RegExp]"]=F["[object Set]"]=F["[object String]"]=F["[object Symbol]"]=F["[object Uint8Array]"]=F["[object Uint8ClampedArray]"]=F["[object Uint16Array]"]=F["[object Uint32Array]"]=!0,F["[object Error]"]=F[L]=F["[object WeakMap]"]=!1;var B=function e(t,r,g,b,w,v){var _,S=1&r,E=2&r,A=4&r;if(g&&(_=w?g(t,b,w,v):g(t)),void 0!==_)return _;if(!(0,N.Z)(t))return t;var x=(0,k.Z)(t);if(x){if(_=y(t),!S)return(0,u.Z)(t,_)}else{var C,I,T,M,j=(0,m.Z)(t),B=j==L||"[object GeneratorFunction]"==j;if((0,P.Z)(t))return(0,c.Z)(t,S);if(j==q||j==D||B&&!w){if(_=E||B?{}:(0,O.Z)(t),!S)return E?(I=(C=_)&&(0,o.Z)(t,(0,l.Z)(t),C),(0,o.Z)(t,(0,f.Z)(t),I)):(M=(T=_)&&(0,o.Z)(t,(0,a.Z)(t),T),(0,o.Z)(t,(0,d.Z)(t),M))}else{if(!F[j])return w?t:{};_=R(t,j,S)}}v||(v=new n.Z);var H=v.get(t);if(H)return H;v.set(t,_),U(t)?t.forEach(function(n){_.add(e(n,r,g,n,t,v))}):$(t)&&t.forEach(function(n,s){_.set(s,e(n,r,g,s,t,v))});var W=A?E?p.Z:h.Z:E?l.Z:a.Z,z=x?void 0:W(t);return(0,s.Z)(z||t,function(n,s){z&&(n=t[s=n]),(0,i.Z)(_,s,e(n,r,g,s,t,v))}),_}},89096:function(e,t,r){"use strict";r.d(t,{Z:function(){return c}});var n=r(57281),s=r(52175),i=r(8330),o=r(67326),a=s.Z?s.Z.isConcatSpreadable:void 0,l=function(e){return(0,o.Z)(e)||(0,i.Z)(e)||!!(a&&e&&e[a])},c=function e(t,r,s,i,o){var a=-1,c=t.length;for(s||(s=l),o||(o=[]);++a<c;){var u=t[a];r>0&&s(u)?r>1?e(u,r-1,s,i,o):(0,n.Z)(o,u):i||(o[o.length]=u)}return o}},12554:function(e,t){"use strict";t.Z=function(e,t,r){var n=-1,s=e.length;t<0&&(t=-t>s?0:s+t),(r=r>s?s:r)<0&&(r+=s),s=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(s);++n<s;)i[n]=e[n+t];return i}},59900:function(e,t,r){"use strict";var n=r(79942),s=r(52878),i=r(67686);t.Z=function(e){return(0,i.Z)((0,s.Z)(e,void 0,n.Z),e+"")}},31387:function(e,t,r){"use strict";var n=r(51502),s=r(99519),i=r(46247);t.Z=function(e){return(0,n.Z)(e,i.Z,s.Z)}},99519:function(e,t,r){"use strict";var n=r(57281),s=r(34718),i=r(18361),o=r(4628),a=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)(0,n.Z)(t,(0,i.Z)(e)),e=(0,s.Z)(e);return t}:o.Z;t.Z=a},79942:function(e,t,r){"use strict";var n=r(89096);t.Z=function(e){return(null==e?0:e.length)?(0,n.Z)(e,1):[]}},24567:function(e,t,r){"use strict";var n=r(56679),s=r(45714),i=r(8330),o=r(67326),a=r(7875),l=r(49462),c=r(97699),u=r(77170),d=Object.prototype.hasOwnProperty;t.Z=function(e){if(null==e)return!0;if((0,a.Z)(e)&&((0,o.Z)(e)||"string"==typeof e||"function"==typeof e.splice||(0,l.Z)(e)||(0,u.Z)(e)||(0,i.Z)(e)))return!e.length;var t=(0,s.Z)(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if((0,c.Z)(e))return!(0,n.Z)(e).length;for(var r in e)if(d.call(e,r))return!1;return!0}},41543:function(e,t){"use strict";t.Z=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},96623:function(e,t,r){"use strict";var n=r(20978),s=(0,r(77836).Z)(function(e,t,r){(0,n.Z)(e,t,r)});t.Z=s},31947:function(e,t,r){"use strict";r.d(t,{Z:function(){return g}});var n=r(27458),s=r(97538),i=r(24058),o=r(41543),a=r(4486),l=r(12554),c=r(46252),u=function(e,t){var r,n;return t=(0,i.Z)(t,e),r=e,null==(e=(n=t).length<2?r:(0,a.Z)(r,(0,l.Z)(n,0,-1)))||delete e[c.Z(o.Z(t))]},d=r(88989),f=r(53995),h=function(e){return(0,f.Z)(e)?void 0:e},p=r(59900),m=r(31387),g=(0,p.Z)(function(e,t){var r={};if(null==e)return r;var o=!1;t=(0,n.Z)(t,function(t){return t=(0,i.Z)(t,e),o||(o=t.length>1),t}),(0,d.Z)(e,(0,m.Z)(e),r),o&&(r=(0,s.Z)(r,7,h));for(var a=t.length;a--;)u(r,t[a]);return r})},26193:function(e,t,r){"use strict";var n=r(84780);t.Z=function(e){return e&&e.length?(0,n.Z)(e):[]}},42361:function(e,t){"use strict";self.Headers,self.Request,self.Response,self.fetch},77879:function(e,t,r){"use strict";r.d(t,{_:function(){return w}}),r(42361);var n=r(25566),s=Object.defineProperty,i=(e,t,r)=>t in e?s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,o=(e,t,r)=>(i(e,"symbol"!=typeof t?t+"":t,r),r);class a extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,a)}}class l{constructor(e,t,r){o(this,"abortController"),o(this,"itr"),o(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=r}abort(){this.abortController.abort()}async *[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw Error(e.error);if(yield e,e.done||"success"===e.status){this.doneCallback();return}}throw Error("Did not receive done or success response in stream.")}}let c=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`;if(e.headers.get("content-type")?.includes("application/json"))try{t=(await e.json()).error||t}catch(e){console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),t=await e.text()||t}catch(e){console.log("Failed to get text from error response")}throw new a(t,e.status)},u=async(e,t,r={})=>{let s={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/0.5.9 (${"undefined"!=typeof window&&window.navigator?`${window.navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:void 0!==n?`${n.arch} ${n.platform} Node.js/${n.version}`:""})`};return r.headers||(r.headers={}),r.headers={...s,...r.headers},e(t,r)},d=async(e,t)=>{let r=await u(e,t);return await c(r),r},f=async(e,t,r,n)=>{let s=null===r||"object"!=typeof r||Array.isArray(r)?r:JSON.stringify(r),i=await u(e,t,{method:"POST",body:s,signal:n?.signal,headers:n?.headers});return await c(i),i},h=async(e,t,r)=>{let n=await u(e,t,{method:"DELETE",body:JSON.stringify(r)});return await c(n),n},p=async function*(e){let t=new TextDecoder("utf-8"),r="",n=e.getReader();for(;;){let{done:e,value:s}=await n.read();if(e)break;let i=(r+=t.decode(s)).split("\n");for(let e of(r=i.pop()??"",i))try{yield JSON.parse(e)}catch(t){console.warn("invalid json: ",e)}}for(let e of r.split("\n").filter(e=>""!==e))try{yield JSON.parse(e)}catch(t){console.warn("invalid json: ",e)}},m=e=>{if(!e)return"http://127.0.0.1:11434";let t=e.includes("://");e.startsWith(":")&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let r=new URL(e),n=r.port;n||(n=t?"https:"===r.protocol?"443":"80":"11434");let s=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return s.endsWith("/")&&(s=s.slice(0,-1)),s};var g=Object.defineProperty,y=(e,t,r)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b=(e,t,r)=>(y(e,"symbol"!=typeof t?t+"":t,r),r);let w=class{constructor(e){b(this,"config"),b(this,"fetch"),b(this,"ongoingStreamedRequests",[]),this.config={host:""},e?.proxy||(this.config.host=m(e?.host??"http://127.0.0.1:11434")),this.fetch=fetch,e?.fetch!=null&&(this.fetch=e.fetch)}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let r=`${this.config.host}/api/${e}`;if(t.stream){let e=new AbortController,n=await f(this.fetch,r,t,{signal:e.signal,headers:this.config.headers});if(!n.body)throw Error("Missing body");let s=new l(e,p(n.body),()=>{let e=this.ongoingStreamedRequests.indexOf(s);e>-1&&this.ongoingStreamedRequests.splice(e,1)});return this.ongoingStreamedRequests.push(s),s}let n=await f(this.fetch,r,t,{headers:this.config.headers});return await n.json()}async encodeImage(e){if("string"!=typeof e){let t=new Uint8Array(e),r="",n=t.byteLength;for(let e=0;e<n;e++)r+=String.fromCharCode(t[e]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{name:e.model,stream:e.stream,modelfile:e.modelfile,quantize:e.quantize})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await h(this.fetch,`${this.config.host}/api/delete`,{name:e.model}),{status:"success"}}async copy(e){return await f(this.fetch,`${this.config.host}/api/copy`,{...e}),{status:"success"}}async list(){let e=await d(this.fetch,`${this.config.host}/api/tags`);return await e.json()}async show(e){let t=await f(this.fetch,`${this.config.host}/api/show`,{...e});return await t.json()}async embed(e){let t=await f(this.fetch,`${this.config.host}/api/embed`,{...e});return await t.json()}async embeddings(e){let t=await f(this.fetch,`${this.config.host}/api/embeddings`,{...e});return await t.json()}async ps(){let e=await d(this.fetch,`${this.config.host}/api/ps`);return await e.json()}};new w},27994:function(e,t,r){"use strict";let n,s,i,o,a,l,c,u,d,f;r.d(t,{ZP:function(){return ns}});var h,p,m,g,y,b,w,v,_,S,E,A,x,R,O,k,P,C,I,T,M,$,N,j,U,D,L,q,F,B,H,W,z,K,V,J,G,Z,X,Y,Q,ee,et,er,en,es,ei,eo,ea,el,ec,eu,ed,ef,eh,ep,em,eg,ey,eb,ew,ev,e_,eS,eE,eA={};r.r(eA),r.d(eA,{APIConnectionError:function(){return t_},APIConnectionTimeoutError:function(){return tS},APIError:function(){return tw},APIUserAbortError:function(){return tv},AuthenticationError:function(){return tA},BadRequestError:function(){return tE},ConflictError:function(){return tO},n:function(){return tT},InternalServerError:function(){return tC},M:function(){return tI},NotFoundError:function(){return tR},OpenAIError:function(){return tb},PermissionDeniedError:function(){return tx},RateLimitError:function(){return tP},UnprocessableEntityError:function(){return tk}});let ex="4.68.4",eR=!1;class eO{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}s||function(e,t={auto:!1}){if(eR)throw Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(s)throw Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${s}'\``);eR=t.auto,s=e.kind,i=e.fetch,e.Request,e.Response,e.Headers,o=e.FormData,e.Blob,a=e.File,l=e.ReadableStream,c=e.getMultipartRequestOptions,u=e.getDefaultAgent,d=e.fileFromPath,f=e.isFsReadStream}(function({manuallyImported:e}={}){let t,r,n,s;let i=e?"You may need to use polyfills":`Add one of these imports before your first \`import … from 'openai'\`:
- \`import 'openai/shims/node'\` (if you're running on Node)
- \`import 'openai/shims/web'\` (otherwise)
`;try{t=fetch,r=Request,n=Response,s=Headers}catch(e){throw Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${i}`)}return{kind:"web",fetch:t,Request:r,Response:n,Headers:s,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${i}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${i}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${i}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${i}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new eO(e)}),getDefaultAgent:e=>void 0,fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});var ek=r(9109).Buffer;class eP{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];let r=eP.NEWLINE_CHARS.has(t[t.length-1]||""),n=t.split(eP.NEWLINE_REGEXP);return(r&&n.pop(),1!==n.length||r)?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),r||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if(void 0!==ek){if(e instanceof ek)return e.toString();if(e instanceof Uint8Array)return ek.from(e).toString();throw new tb(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new tb(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new tb("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}eP.NEWLINE_CHARS=new Set(["\n","\r"]),eP.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class eC{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;return new eC(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(let r of eI(e,t))if(!n){if(r.data.startsWith("[DONE]")){n=!0;continue}if(null===r.event){let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if(e&&e.error)throw new tw(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("error"==r.event)throw new tw(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}},t)}static fromReadableStream(e,t){let r=!1;async function*n(){let t=new eP;for await(let r of e$(e))for(let e of t.decode(r))yield e;for(let e of t.flush())yield e}return new eC(async function*(){if(r)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let e=!1;try{for await(let t of n())!e&&t&&(yield JSON.parse(t));e=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{e||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new eC(()=>n(e),this.controller),new eC(()=>n(t),this.controller)]}toReadableStream(){let e;let t=this,r=new TextEncoder;return new l({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:n,done:s}=await e.next();if(s)return t.close();let i=r.encode(JSON.stringify(n)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}}async function*eI(e,t){if(!e.body)throw t.abort(),new tb("Attempted to iterate over a response with no body");let r=new eM,n=new eP;for await(let t of eT(e$(e.body)))for(let e of n.decode(t)){let t=r.decode(e);t&&(yield t)}for(let e of n.flush()){let t=r.decode(e);t&&(yield t)}}async function*eT(e){let t=new Uint8Array;for await(let r of e){let e;if(null==r)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?new TextEncoder().encode(r):r,s=new Uint8Array(t.length+n.length);for(s.set(t),s.set(n,t.length),t=s;-1!==(e=function(e){for(let t=0;t<e.length-2;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(t));)yield t.slice(0,e),t=t.slice(e)}t.length>0&&(yield t)}class eM{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){let r=e.indexOf(":");return -1!==r?[e.substring(0,r),":",e.substring(r+t.length)]:[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}function e$(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var eN=r(9109).Buffer;let ej=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,eU=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&eD(e),eD=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,eL=e=>eU(e)||ej(e)||f(e);async function eq(e,t,r){var n;if(eU(e=await e))return e;if(ej(e)){let n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let s=eD(n)?[await n.arrayBuffer()]:[n];return new a(s,t,r)}let s=await eF(e);if(t||(t=(eB((n=e).name)||eB(n.filename)||eB(n.path)?.split(/[\\/]/).pop())??"unknown_file"),!r?.type){let e=s[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new a(s,t,r)}async function eF(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(eD(e))t.push(await e.arrayBuffer());else if(eH(e))for await(let r of e)t.push(r);else throw Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){let t=Object.getOwnPropertyNames(e);return`[${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`);return t}let eB=e=>"string"==typeof e?e:void 0!==eN&&e instanceof eN?String(e):void 0,eH=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],eW=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],ez=async e=>{let t=await eK(e.body);return c(t,e)},eK=async e=>{let t=new o;return await Promise.all(Object.entries(e||{}).map(([e,r])=>eJ(t,e,r))),t},eV=e=>{if(eL(e))return!0;if(Array.isArray(e))return e.some(eV);if(e&&"object"==typeof e){for(let t in e)if(eV(e[t]))return!0}return!1},eJ=async(e,t,r)=>{if(void 0!==r){if(null==r)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if(eL(r)){let n=await eq(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map(r=>eJ(e,t+"[]",r)));else if("object"==typeof r)await Promise.all(Object.entries(r).map(([r,n])=>eJ(e,`${t}[${r}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var eG=r(9109).Buffer,eZ=r(25566),eX=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},eY=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function eQ(e){let{response:t}=e;if(e.options.stream)return(tf("response",t.status,t.url,t.headers,t.body),e.options.__streamClass)?e.options.__streamClass.fromSSEResponse(t,e.controller):eC.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let e=await t.json();return tf("response",t.status,t.url,t.headers,e),e0(e,t)}let n=await t.text();return tf("response",t.status,t.url,t.headers,n),n}function e0(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class e1 extends Promise{constructor(e,t=eQ){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new e1(this.responsePromise,async t=>e0(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class e2{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=to("maxRetries",t),this.timeout=to("timeout",r),this.httpAgent=n,this.fetch=s??i}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...tt(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${th()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(async r=>{let n=r&&eD(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if(void 0!==eG)return eG.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder)return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let{method:r,path:n,query:s,headers:i={}}=e,o=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:eW(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(o),l=this.buildURL(n,s);"timeout"in e&&to("timeout",e.timeout);let c=e.timeout??this.timeout,d=e.httpAgent??this.httpAgent??u(l),f=c+1e3;"number"==typeof d?.options?.timeout&&f>(d.options.timeout??0)&&(d.options.timeout=f),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let h=this.buildHeaders({options:e,headers:i,contentLength:a,retryCount:t});return{req:{method:r,...o&&{body:o},headers:h,...d&&{agent:d},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return td(i,o),td(i,t),eW(e.body)&&"node"!==s&&delete i["content-type"],void 0===tg(o,"x-stainless-retry-count")&&void 0===tg(t,"x-stainless-retry-count")&&(i["x-stainless-retry-count"]=String(n)),this.validateHeaders(i,t),i}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,r,n){return tw.generate(e,t,r,n)}request(e,t=null){return new e1(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);let{req:s,url:i,timeout:o}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:i,options:r}),tf("request",i,r,s.headers),r.signal?.aborted)throw new tv;let a=new AbortController,l=await this.fetchWithTimeout(i,s,o,a).catch(ta);if(l instanceof Error){if(r.signal?.aborted)throw new tv;if(t)return this.retryRequest(r,t);if("AbortError"===l.name)throw new tS;throw new t_({cause:l})}let c=e6(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let e=`retrying, ${t} attempts remaining`;return tf(`response (error; ${e})`,l.status,i,c),this.retryRequest(r,t,c)}let e=await l.text().catch(e=>ta(e).message),n=tr(e),s=n?void 0:e,o=t?"(error; no more retries left)":"(error; not retryable)";throw tf(`response (error; ${o})`,l.status,i,c,s),this.makeStatusError(l.status,n,s,c)}return{response:l,options:r,controller:a}}requestAPIList(e,t){return new e4(this,this.makeRequest(t,null),e)}buildURL(e,t){let r=new URL(ts(e)?e:this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return tc(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new tb(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,r,n){let{signal:s,...i}=t||{};s&&s.addEventListener("abort",()=>n.abort());let o=setTimeout(()=>n.abort(),r);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...i}).finally(()=>{clearTimeout(o)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,r){let n;let s=r?.["retry-after-ms"];if(s){let e=parseFloat(s);Number.isNaN(e)||(n=e)}let i=r?.["retry-after"];if(i&&!n){let e=parseFloat(i);n=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){let r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await ti(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${ex}`}}class e3{constructor(e,t,r,n){_.set(this,void 0),eX(this,_,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new tb("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){for(let[r,n]of[...Object.entries(t.query||{}),...e.url.searchParams.entries()])e.url.searchParams.set(r,n);t.query=void 0,t.path=e.url.toString()}return await eY(this,_,"f").requestAPIList(this.constructor,t)}async *iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async *[(_=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class e4 extends e1{constructor(e,t,r){super(t,async t=>new r(e,t.response,await eQ(t),t.options))}async *[Symbol.asyncIterator](){for await(let e of(await this))yield e}}let e6=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),e5={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},e8=e=>"object"==typeof e&&null!==e&&!tc(e)&&Object.keys(e).every(e=>tu(e5,e)),e9=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ex,"X-Stainless-OS":te(Deno.build.os),"X-Stainless-Arch":e7(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ex,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":eZ.version};if("[object process]"===Object.prototype.toString.call(void 0!==eZ?eZ:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ex,"X-Stainless-OS":te(eZ.platform),"X-Stainless-Arch":e7(eZ.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":eZ.version};let e=function(){if("undefined"==typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,s=r[3]||0;return{browser:e,version:`${t}.${n}.${s}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ex,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ex,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},e7=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",te=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown",tt=()=>n??(n=e9()),tr=e=>{try{return JSON.parse(e)}catch(e){return}},tn=RegExp("^(?:[a-z]+:)?//","i"),ts=e=>tn.test(e),ti=e=>new Promise(t=>setTimeout(t,e)),to=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new tb(`${e} must be an integer`);if(t<0)throw new tb(`${e} must be a positive integer`);return t},ta=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return Error(JSON.stringify(e))}catch{}return Error(e)},tl=e=>void 0!==eZ?eZ.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function tc(e){if(!e)return!0;for(let t in e)return!1;return!0}function tu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function td(e,t){for(let r in t){if(!tu(t,r))continue;let n=r.toLowerCase();if(!n)continue;let s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}function tf(e,...t){void 0!==eZ&&eZ?.env?.DEBUG==="true"&&console.log(`OpenAI:DEBUG:${e}`,...t)}let th=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),tp=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,tm=e=>"function"==typeof e?.get,tg=(e,t)=>{let r=t.toLowerCase();if(tm(e)){let n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,r)=>t+r.toUpperCase());for(let s of[t,r,t.toUpperCase(),n]){let t=e.get(s);if(t)return t}}for(let[n,s]of Object.entries(e))if(n.toLowerCase()===r){if(Array.isArray(s)){if(s.length<=1)return s[0];return console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]}return s}};function ty(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class tb extends Error{}class tw extends tb{constructor(e,t,r,n){super(`${tw.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t,this.code=t?.code,this.param=t?.param,this.type=t?.type}static makeMessage(e,t,r){let n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e)return new t_({message:r,cause:ta(t)});let s=t?.error;return 400===e?new tE(e,s,r,n):401===e?new tA(e,s,r,n):403===e?new tx(e,s,r,n):404===e?new tR(e,s,r,n):409===e?new tO(e,s,r,n):422===e?new tk(e,s,r,n):429===e?new tP(e,s,r,n):e>=500?new tC(e,s,r,n):new tw(e,s,r,n)}}class tv extends tw{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class t_ extends tw{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class tS extends t_{constructor({message:e}={}){super({message:e??"Request timed out."})}}class tE extends tw{constructor(){super(...arguments),this.status=400}}class tA extends tw{constructor(){super(...arguments),this.status=401}}class tx extends tw{constructor(){super(...arguments),this.status=403}}class tR extends tw{constructor(){super(...arguments),this.status=404}}class tO extends tw{constructor(){super(...arguments),this.status=409}}class tk extends tw{constructor(){super(...arguments),this.status=422}}class tP extends tw{constructor(){super(...arguments),this.status=429}}class tC extends tw{}class tI extends tb{constructor(){super("Could not parse response content as the length limit was reached")}}class tT extends tb{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}let tM="RFC3986",t$={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)};Object.prototype.hasOwnProperty;let tN=Array.isArray,tj=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();function tU(e,t){if(tN(e)){let r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}let tD=Object.prototype.hasOwnProperty,tL={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},tq=Array.isArray,tF=Array.prototype.push,tB=function(e,t){tF.apply(e,tq(t)?t:[t])},tH=Date.prototype.toISOString,tW={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,s)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===r)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let o="";for(let e=0;e<i.length;e+=1024){let t=i.length>=1024?i.slice(e,e+1024):i,r=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);if(45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===s&&(40===n||41===n)){r[r.length]=t.charAt(e);continue}if(n<128){r[r.length]=tj[n];continue}if(n<2048){r[r.length]=tj[192|n>>6]+tj[128|63&n];continue}if(n<55296||n>=57344){r[r.length]=tj[224|n>>12]+tj[128|n>>6&63]+tj[128|63&n];continue}e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=tj[240|n>>18]+tj[128|n>>12&63]+tj[128|n>>6&63]+tj[128|63&n]}o+=r.join("")}return o},encodeValuesOnly:!1,format:tM,formatter:t$[tM],indices:!1,serializeDate:e=>tH.call(e),skipNulls:!1,strictNullHandling:!1},tz={};class tK extends e3{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class tV extends e3{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){let e=this.getPaginatedItems();if(!e.length)return null;let t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class tJ{constructor(e){this._client=e}}class tG extends tJ{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}tG||(tG={});class tZ extends tJ{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}}tZ||(tZ={});class tX extends tJ{constructor(){super(...arguments),this.completions=new tZ(this._client)}}(tX||(tX={})).Completions=tZ;class tY extends tJ{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}tY||(tY={});class tQ extends tJ{create(e,t){return this._client.post("/files",ez({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return e8(e)?this.list({},e):this._client.getAPIList("/files",t0,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){let n=new Set(["processed","error","deleted"]),s=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ti(t),i=await this.retrieve(e),Date.now()-s>r)throw new tS({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}}class t0 extends tK{}(tQ||(tQ={})).FileObjectsPage=t0;class t1 extends tJ{createVariation(e,t){return this._client.post("/images/variations",ez({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ez({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}t1||(t1={});class t2 extends tJ{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}}t2||(t2={});class t3 extends tJ{create(e,t){return this._client.post("/audio/transcriptions",ez({body:e,...t}))}}t3||(t3={});class t4 extends tJ{create(e,t){return this._client.post("/audio/translations",ez({body:e,...t}))}}t4||(t4={});class t6 extends tJ{constructor(){super(...arguments),this.transcriptions=new t3(this._client),this.translations=new t4(this._client),this.speech=new t2(this._client)}}(h=t6||(t6={})).Transcriptions=t3,h.Translations=t4,h.Speech=t2;class t5 extends tJ{create(e,t){return this._client.post("/moderations",{body:e,...t})}}t5||(t5={});class t8 extends tJ{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",t9,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class t9 extends tK{}(t8||(t8={})).ModelsPage=t9;class t7 extends tJ{list(e,t={},r){return e8(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,re,{query:t,...r})}}class re extends tV{}(t7||(t7={})).FineTuningJobCheckpointsPage=re;class rt extends tJ{constructor(){super(...arguments),this.checkpoints=new t7(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return e8(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",rr,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return e8(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,rn,{query:t,...r})}}class rr extends tV{}class rn extends tV{}(p=rt||(rt={})).FineTuningJobsPage=rr,p.FineTuningJobEventsPage=rn,p.Checkpoints=t7,p.FineTuningJobCheckpointsPage=re;class rs extends tJ{constructor(){super(...arguments),this.jobs=new rt(this._client)}}(m=rs||(rs={})).Jobs=rt,m.FineTuningJobsPage=rr,m.FineTuningJobEventsPage=rn;class ri extends tJ{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return e8(e)?this.list({},e):this._client.getAPIList("/assistants",ro,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class ro extends tV{}function ra(e){return"function"==typeof e.parse}(ri||(ri={})).AssistantsPage=ro;let rl=e=>e?.role==="assistant",rc=e=>e?.role==="function",ru=e=>e?.role==="tool";var rd=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},rf=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class rh{constructor(){S.add(this),this.controller=new AbortController,E.set(this,void 0),A.set(this,()=>{}),x.set(this,()=>{}),R.set(this,void 0),O.set(this,()=>{}),k.set(this,()=>{}),P.set(this,{}),C.set(this,!1),I.set(this,!1),T.set(this,!1),M.set(this,!1),rd(this,E,new Promise((e,t)=>{rd(this,A,e,"f"),rd(this,x,t,"f")}),"f"),rd(this,R,new Promise((e,t)=>{rd(this,O,e,"f"),rd(this,k,t,"f")}),"f"),rf(this,E,"f").catch(()=>{}),rf(this,R,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},rf(this,S,"m",$).bind(this))},0)}_connected(){this.ended||(rf(this,A,"f").call(this),this._emit("connect"))}get ended(){return rf(this,C,"f")}get errored(){return rf(this,I,"f")}get aborted(){return rf(this,T,"f")}abort(){this.controller.abort()}on(e,t){return(rf(this,P,"f")[e]||(rf(this,P,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=rf(this,P,"f")[e];if(!r)return this;let n=r.findIndex(e=>e.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(rf(this,P,"f")[e]||(rf(this,P,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{rd(this,M,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)})}async done(){rd(this,M,!0,"f"),await rf(this,R,"f")}_emit(e,...t){if(rf(this,C,"f"))return;"end"===e&&(rd(this,C,!0,"f"),rf(this,O,"f").call(this));let r=rf(this,P,"f")[e];if(r&&(rf(this,P,"f")[e]=r.filter(e=>!e.once),r.forEach(({listener:e})=>e(...t))),"abort"===e){let e=t[0];rf(this,M,"f")||r?.length||Promise.reject(e),rf(this,x,"f").call(this,e),rf(this,k,"f").call(this,e),this._emit("end");return}if("error"===e){let e=t[0];rf(this,M,"f")||r?.length||Promise.reject(e),rf(this,x,"f").call(this,e),rf(this,k,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function rp(e){return e?.$brand==="auto-parseable-response-format"}function rm(e){return e?.$brand==="auto-parseable-tool"}function rg(e,t){let r=e.choices.map(e=>{var r;if("length"===e.finish_reason)throw new tI;if("content_filter"===e.finish_reason)throw new tT;return{...e,message:{...e.message,tool_calls:e.message.tool_calls?.map(e=>(function(e,t){let r=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:rm(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}})(t,e))??[],parsed:e.message.content&&!e.message.refusal?(r=e.message.content,t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(r):JSON.parse(r):null):null}}});return{...e,choices:r}}function ry(e){return!!rp(e.response_format)||(e.tools?.some(e=>rm(e)||"function"===e.type&&!0===e.function.strict)??!1)}E=new WeakMap,A=new WeakMap,x=new WeakMap,R=new WeakMap,O=new WeakMap,k=new WeakMap,P=new WeakMap,C=new WeakMap,I=new WeakMap,T=new WeakMap,M=new WeakMap,S=new WeakSet,$=function(e){if(rd(this,I,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new tv),e instanceof tv)return rd(this,T,!0,"f"),this._emit("abort",e);if(e instanceof tb)return this._emit("error",e);if(e instanceof Error){let t=new tb(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new tb(String(e)))};var rb=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class rw extends rh{constructor(){super(...arguments),N.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(rc(e)||ru(e))&&e.content)this._emit("functionCallResult",e.content);else if(rl(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(rl(e)&&e.tool_calls)for(let t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new tb("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),rb(this,N,"m",j).call(this)}async finalMessage(){return await this.done(),rb(this,N,"m",U).call(this)}async finalFunctionCall(){return await this.done(),rb(this,N,"m",D).call(this)}async finalFunctionCallResult(){return await this.done(),rb(this,N,"m",L).call(this)}async totalUsage(){return await this.done(),rb(this,N,"m",q).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=rb(this,N,"m",U).call(this);t&&this._emit("finalMessage",t);let r=rb(this,N,"m",j).call(this);r&&this._emit("finalContent",r);let n=rb(this,N,"m",D).call(this);n&&this._emit("finalFunctionCall",n);let s=rb(this,N,"m",L).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",rb(this,N,"m",q).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),rb(this,N,"m",F).call(this,t);let s=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(rg(s,t))}async _runChatCompletion(e,t,r){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){let n="function",{function_call:s="auto",stream:i,...o}=t,a="string"!=typeof s&&s?.name,{maxChatCompletions:l=10}=r||{},c={};for(let e of t.functions)c[e.name||e.function.name]=e;let u=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){let t;let i=await this._createChatCompletion(e,{...o,function_call:s,functions:u,messages:[...this.messages]},r),l=i.choices[0]?.message;if(!l)throw new tb("missing message in ChatCompletion response");if(!l.function_call)return;let{name:d,arguments:f}=l.function_call,h=c[d];if(h){if(a&&a!==d){let e=`Invalid function_call: ${JSON.stringify(d)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:n,name:d,content:e});continue}}else{let e=`Invalid function_call: ${JSON.stringify(d)}. Available options are: ${u.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:n,name:d,content:e});continue}try{t=ra(h)?await h.parse(f):f}catch(e){this._addMessage({role:n,name:d,content:e instanceof Error?e.message:String(e)});continue}let p=await h.function(t,this),m=rb(this,N,"m",B).call(this,p);if(this._addMessage({role:n,name:d,content:m}),a)return}}async _runTools(e,t,r){let n="tool",{tool_choice:s="auto",stream:i,...o}=t,a="string"!=typeof s&&s?.function?.name,{maxChatCompletions:l=10}=r||{},c=t.tools.map(e=>{if(rm(e)){if(!e.$callback)throw new tb("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(let e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);let d="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){let t=await this._createChatCompletion(e,{...o,tool_choice:s,tools:d,messages:[...this.messages]},r),i=t.choices[0]?.message;if(!i)throw new tb("missing message in ChatCompletion response");if(!i.tool_calls?.length)break;for(let e of i.tool_calls){let t;if("function"!==e.type)continue;let r=e.id,{name:s,arguments:i}=e.function,o=u[s];if(o){if(a&&a!==s){let e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:n,tool_call_id:r,content:e});continue}}else{let e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:r,content:e});continue}try{t=ra(o)?await o.parse(i):i}catch(t){let e=t instanceof Error?t.message:String(t);this._addMessage({role:n,tool_call_id:r,content:e});continue}let l=await o.function(t,this),c=rb(this,N,"m",B).call(this,l);if(this._addMessage({role:n,tool_call_id:r,content:c}),a)return}}}}N=new WeakSet,j=function(){return rb(this,N,"m",U).call(this).content??null},U=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(rl(t)){let{function_call:e,...r}=t,n={...r,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new tb("stream ended without producing a ChatCompletionMessage with role=assistant")},D=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(rl(t)&&t?.function_call)return t.function_call;if(rl(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},L=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(rc(t)&&null!=t.content||ru(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},q=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},F=function(e){if(null!=e.n&&e.n>1)throw new tb("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},B=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class rv extends rw{static runFunctions(e,t,r){let n=new rv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,s)),n}static runTools(e,t,r){let n=new rv,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,s)),n}_addMessage(e,t=!0){super._addMessage(e,t),rl(e)&&e.content&&this._emit("content",e.content)}}let r_={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,ALL:511};class rS extends Error{}class rE extends Error{}let rA=(e,t)=>{let r=e.length,n=0,s=e=>{throw new rS(`${e} at position ${n}`)},i=e=>{throw new rE(`${e} at position ${n}`)},o=()=>(d(),n>=r&&s("Unexpected end of input"),'"'===e[n])?a():"{"===e[n]?l():"["===e[n]?c():"null"===e.substring(n,n+4)||r_.NULL&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||r_.BOOL&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||r_.BOOL&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||r_.INFINITY&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||r_.MINUS_INFINITY&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||r_.NAN&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u(),a=()=>{let o=n,a=!1;for(n++;n<r&&('"'!==e[n]||a&&"\\"===e[n-1]);)a="\\"===e[n]&&!a,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(o,++n-Number(a)))}catch(e){i(String(e))}else if(r_.STR&t)try{return JSON.parse(e.substring(o,n-Number(a))+'"')}catch(t){return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},l=()=>{n++,d();let i={};try{for(;"}"!==e[n];){if(d(),n>=r&&r_.OBJ&t)return i;let s=a();d(),n++;try{let e=o();Object.defineProperty(i,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(r_.OBJ&t)return i;throw e}d(),","===e[n]&&n++}}catch(e){if(r_.OBJ&t)return i;s("Expected '}' at end of object")}return n++,i},c=()=>{n++;let r=[];try{for(;"]"!==e[n];)r.push(o()),d(),","===e[n]&&n++}catch(e){if(r_.ARR&t)return r;s("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&r_.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(r_.NUM&t)try{if("."===e[e.length-1])return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}i(String(r))}}let o=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=r||r_.NUM&t||s("Unterminated number literal");try{return JSON.parse(e.substring(o,n))}catch(r){"-"===e.substring(o,n)&&r_.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){i(String(e))}}},d=()=>{for(;n<r&&" \n\r	".includes(e[n]);)n++};return o()},rx=e=>(function(e,t=r_.ALL){if("string"!=typeof e)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return rA(e.trim(),t)})(e,r_.ALL^r_.NUM);var rR=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},rO=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class rk extends rw{constructor(e){super(),H.add(this),W.set(this,void 0),z.set(this,void 0),K.set(this,void 0),rR(this,W,e,"f"),rR(this,z,[],"f")}get currentChatCompletionSnapshot(){return rO(this,K,"f")}static fromReadableStream(e){let t=new rk(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new rk(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),rO(this,H,"m",V).call(this);let s=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});for await(let e of(this._connected(),s))rO(this,H,"m",G).call(this,e);if(s.controller.signal?.aborted)throw new tv;return this._addChatCompletion(rO(this,H,"m",Y).call(this))}async _fromReadableStream(e,t){let r;let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),rO(this,H,"m",V).call(this),this._connected();let s=eC.fromReadableStream(e,this.controller);for await(let e of s)r&&r!==e.id&&this._addChatCompletion(rO(this,H,"m",Y).call(this)),rO(this,H,"m",G).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new tv;return this._addChatCompletion(rO(this,H,"m",Y).call(this))}[(W=new WeakMap,z=new WeakMap,K=new WeakMap,H=new WeakSet,V=function(){this.ended||rR(this,K,void 0,"f")},J=function(e){let t=rO(this,z,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},rO(this,z,"f")[e.index]=t),t},G=function(e){if(this.ended)return;let t=rO(this,H,"m",ee).call(this,e);for(let r of(this._emit("chunk",e,t),e.choices)){let e=t.choices[r.index];null!=r.delta.content&&e.message?.role==="assistant"&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&e.message?.role==="assistant"&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let n=rO(this,H,"m",J).call(this,e);for(let t of(e.finish_reason&&(rO(this,H,"m",X).call(this,e),null!=n.current_tool_call_index&&rO(this,H,"m",Z).call(this,e,n.current_tool_call_index)),r.delta.tool_calls??[]))n.current_tool_call_index!==t.index&&(rO(this,H,"m",X).call(this,e),null!=n.current_tool_call_index&&rO(this,H,"m",Z).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(let t of r.delta.tool_calls??[]){let r=e.message.tool_calls?.[t.index];r?.type&&(r?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):r?.type)}}},Z=function(e,t){if(rO(this,H,"m",J).call(this,e).done_tool_calls.has(t))return;let r=e.message.tool_calls?.[t];if(!r)throw Error("no tool call snapshot");if(!r.type)throw Error("tool call snapshot missing `type`");if("function"===r.type){let e=rO(this,W,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===r.function.name);this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:rm(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},X=function(e){let t=rO(this,H,"m",J).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let r=rO(this,H,"m",Q).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Y=function(){if(this.ended)throw new tb("stream has ended, this shouldn't happen");let e=rO(this,K,"f");if(!e)throw new tb("request ended without sending any chunks");return rR(this,K,void 0,"f"),rR(this,z,[],"f"),function(e,t){var r;let{id:n,choices:s,created:i,model:o,system_fingerprint:a,...l}=e;return r={...l,id:n,choices:s.map(({message:t,finish_reason:r,index:n,logprobs:s,...i})=>{if(!r)throw new tb(`missing finish_reason for choice ${n}`);let{content:o=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new tb(`missing role for choice ${n}`);if(a){let{arguments:e,name:l}=a;if(null==e)throw new tb(`missing function_call.arguments for choice ${n}`);if(!l)throw new tb(`missing function_call.name for choice ${n}`);return{...i,message:{content:o,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}}return l?{...i,index:n,finish_reason:r,logprobs:s,message:{...c,role:u,content:o,refusal:t.refusal??null,tool_calls:l.map((t,r)=>{let{function:s,type:i,id:o,...a}=t,{arguments:l,name:c,...u}=s||{};if(null==o)throw new tb(`missing choices[${n}].tool_calls[${r}].id
${rP(e)}`);if(null==i)throw new tb(`missing choices[${n}].tool_calls[${r}].type
${rP(e)}`);if(null==c)throw new tb(`missing choices[${n}].tool_calls[${r}].function.name
${rP(e)}`);if(null==l)throw new tb(`missing choices[${n}].tool_calls[${r}].function.arguments
${rP(e)}`);return{...a,id:o,type:i,function:{...u,name:c,arguments:l}}})}}:{...i,message:{...c,content:o,role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}}),created:i,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}},t&&ry(t)?rg(r,t):{...r,choices:r.choices.map(e=>({...e,message:{...e.message,parsed:null,tool_calls:e.message.tool_calls??[]}}))}}(e,rO(this,W,"f"))},Q=function(){let e=rO(this,W,"f")?.response_format;return rp(e)?e:null},ee=function(e){var t,r,n,s;let i=rO(this,K,"f"),{choices:o,...a}=e;for(let{delta:o,finish_reason:l,index:c,logprobs:u=null,...d}of(i?Object.assign(i,a):i=rR(this,K,{...a,choices:[]},"f"),e.choices)){let e=i.choices[c];if(e||(e=i.choices[c]={finish_reason:l,index:c,message:{},logprobs:u,...d}),u){if(e.logprobs){let{content:n,refusal:s,...i}=u;Object.assign(e.logprobs,i),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),s&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},u)}if(l&&(e.finish_reason=l,rO(this,W,"f")&&ry(rO(this,W,"f")))){if("length"===l)throw new tI;if("content_filter"===l)throw new tT}if(Object.assign(e,d),!o)continue;let{content:a,refusal:f,function_call:h,role:p,tool_calls:m,...g}=o;if(Object.assign(e.message,g),f&&(e.message.refusal=(e.message.refusal||"")+f),p&&(e.message.role=p),h&&(e.message.function_call?(h.name&&(e.message.function_call.name=h.name),h.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=h.arguments)):e.message.function_call=h),a&&(e.message.content=(e.message.content||"")+a,!e.message.refusal&&rO(this,H,"m",Q).call(this)&&(e.message.parsed=rx(e.message.content))),m)for(let{index:t,id:r,type:n,function:i,...o}of(e.message.tool_calls||(e.message.tool_calls=[]),m)){let a=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(a,o),r&&(a.id=r),n&&(a.type=n),i&&(a.function??(a.function={name:i.name??"",arguments:""})),i?.name&&(a.function.name=i.name),i?.arguments&&(a.function.arguments+=i.arguments,function(e,t){if(!e)return!1;let r=e.tools?.find(e=>e.function?.name===t.function.name);return rm(r)||r?.function.strict||!1}(rO(this,W,"f"),a)&&(a.function.parsed_arguments=rx(a.function.arguments)))}}return i},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new eC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function rP(e){return JSON.stringify(e)}class rC extends rk{static fromReadableStream(e){let t=new rC(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let n=new rC(null),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,s)),n}static runTools(e,t,r){let n=new rC(t),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,s)),n}}class rI extends tJ{parse(e,t){return!function(e){for(let t of e??[]){if("function"!==t.type)throw new tb(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new tb(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>rg(t,e))}runFunctions(e,t){return e.stream?rC.runFunctions(this._client,e,t):rv.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?rC.runTools(this._client,e,t):rv.runTools(this._client,e,t)}stream(e,t){return rk.createChatCompletion(this._client,e,t)}}class rT extends tJ{constructor(){super(...arguments),this.completions=new rI(this._client)}}(rT||(rT={})).Completions=rI;var rM=function(e,t,r,n){if("a"===r&&!n)throw TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},r$=function(e,t,r,n,s){if("m"===n)throw TypeError("Private method is not writable");if("a"===n&&!s)throw TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r};class rN extends rh{constructor(){super(...arguments),et.add(this),er.set(this,[]),en.set(this,{}),es.set(this,{}),ei.set(this,void 0),eo.set(this,void 0),ea.set(this,void 0),el.set(this,void 0),ec.set(this,void 0),eu.set(this,void 0),ed.set(this,void 0),ef.set(this,void 0),eh.set(this,void 0)}[(er=new WeakMap,en=new WeakMap,es=new WeakMap,ei=new WeakMap,eo=new WeakMap,ea=new WeakMap,el=new WeakMap,ec=new WeakMap,eu=new WeakMap,ed=new WeakMap,ef=new WeakMap,eh=new WeakMap,et=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",r=>{let n=t.shift();n?n.resolve(r):e.push(r)}),this.on("end",()=>{for(let e of(r=!0,t))e.resolve(void 0);t.length=0}),this.on("abort",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),this.on("error",e=>{for(let n of(r=!0,t))n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((e,r)=>t.push({resolve:e,reject:r})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new rN;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=eC.fromReadableStream(e,this.controller);for await(let e of n)rM(this,et,"m",ep).call(this,e);if(n.controller.signal?.aborted)throw new tv;return this._addRun(rM(this,et,"m",em).call(this))}toReadableStream(){return new eC(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,s){let i=new rN;return i._run(()=>i._runToolAssistantStream(e,t,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,r,n,s){let i=s?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await e.submitToolOutputs(t,r,o,{...s,signal:this.controller.signal});for await(let e of(this._connected(),a))rM(this,et,"m",ep).call(this,e);if(a.controller.signal?.aborted)throw new tv;return this._addRun(rM(this,et,"m",em).call(this))}static createThreadAssistantStream(e,t,r){let n=new rN;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let s=new rN;return s._run(()=>s._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return rM(this,ed,"f")}currentRun(){return rM(this,ef,"f")}currentMessageSnapshot(){return rM(this,ei,"f")}currentRunStepSnapshot(){return rM(this,eh,"f")}async finalRunSteps(){return await this.done(),Object.values(rM(this,en,"f"))}async finalMessages(){return await this.done(),Object.values(rM(this,es,"f"))}async finalRun(){if(await this.done(),!rM(this,eo,"f"))throw Error("Final run was not received.");return rM(this,eo,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let s={...t,stream:!0},i=await e.createAndRun(s,{...r,signal:this.controller.signal});for await(let e of(this._connected(),i))rM(this,et,"m",ep).call(this,e);if(i.controller.signal?.aborted)throw new tv;return this._addRun(rM(this,et,"m",em).call(this))}async _createAssistantStream(e,t,r,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},o=await e.create(t,i,{...n,signal:this.controller.signal});for await(let e of(this._connected(),o))rM(this,et,"m",ep).call(this,e);if(o.controller.signal?.aborted)throw new tv;return this._addRun(rM(this,et,"m",em).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null==t||"index"===r||"type"===r){e[r]=n;continue}if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else if(ty(t)&&ty(n))t=this.accumulateDelta(t,n);else if(Array.isArray(t)&&Array.isArray(n)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...n);continue}for(let e of n){if(!ty(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let r=e.index;if(null==r)throw console.error(e),Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);let n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`);e[r]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,s){return await this._createToolAssistantStream(r,e,t,n,s)}}ep=function(e){if(!this.ended)switch(r$(this,ed,e,"f"),rM(this,et,"m",eb).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":rM(this,et,"m",eS).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":rM(this,et,"m",ey).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":rM(this,et,"m",eg).call(this,e);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier")}},em=function(){if(this.ended)throw new tb("stream has ended, this shouldn't happen");if(!rM(this,eo,"f"))throw Error("Final run has not been received");return rM(this,eo,"f")},eg=function(e){let[t,r]=rM(this,et,"m",ev).call(this,e,rM(this,ei,"f"));for(let e of(r$(this,ei,t,"f"),rM(this,es,"f")[t.id]=t,r)){let r=t.content[e.index];r?.type=="text"&&this._emit("textCreated",r.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(n&&"text"==n.type)this._emit("textDelta",e,n.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=rM(this,ea,"f")){if(rM(this,el,"f"))switch(rM(this,el,"f").type){case"text":this._emit("textDone",rM(this,el,"f").text,rM(this,ei,"f"));break;case"image_file":this._emit("imageFileDone",rM(this,el,"f").image_file,rM(this,ei,"f"))}r$(this,ea,r.index,"f")}r$(this,el,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==rM(this,ea,"f")){let t=e.data.content[rM(this,ea,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,rM(this,ei,"f"));break;case"text":this._emit("textDone",t.text,rM(this,ei,"f"))}}rM(this,ei,"f")&&this._emit("messageDone",e.data),r$(this,ei,void 0,"f")}},ey=function(e){let t=rM(this,et,"m",ew).call(this,e);switch(r$(this,eh,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(let e of r.step_details.tool_calls)e.index==rM(this,ec,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(rM(this,eu,"f")&&this._emit("toolCallDone",rM(this,eu,"f")),r$(this,ec,e.index,"f"),r$(this,eu,t.step_details.tool_calls[e.index],"f"),rM(this,eu,"f")&&this._emit("toolCallCreated",rM(this,eu,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":r$(this,eh,void 0,"f"),"tool_calls"==e.data.step_details.type&&rM(this,eu,"f")&&(this._emit("toolCallDone",rM(this,eu,"f")),r$(this,eu,void 0,"f")),this._emit("runStepDone",e.data,t)}},eb=function(e){rM(this,er,"f").push(e),this._emit("event",e)},ew=function(e){switch(e.event){case"thread.run.step.created":return rM(this,en,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=rM(this,en,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=rN.accumulateDelta(t,r.delta);rM(this,en,"f")[e.data.id]=n}return rM(this,en,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":rM(this,en,"f")[e.data.id]=e.data}if(rM(this,en,"f")[e.data.id])return rM(this,en,"f")[e.data.id];throw Error("No snapshot available")},ev=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=rM(this,et,"m",e_).call(this,e,r)}else t.content[e.index]=e,r.push(e);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},e_=function(e,t){return rN.accumulateDelta(t,e)},eS=function(e){switch(r$(this,ef,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":r$(this,eo,e.data,"f"),rM(this,eu,"f")&&(this._emit("toolCallDone",rM(this,eu,"f")),r$(this,eu,void 0,"f"))}};class rj extends tJ{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return e8(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,rU,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class rU extends tV{}(rj||(rj={})).MessagesPage=rU;class rD extends tJ{retrieve(e,t,r,n={},s){return e8(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,r={},n){return e8(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,rL,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class rL extends tV{}(rD||(rD={})).RunStepsPage=rL;class rq extends tJ{constructor(){super(...arguments),this.steps=new rD(this._client)}create(e,t,r){let{include:n,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return e8(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,rF,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return rN.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:s,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=i.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await ti(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,r){return rN.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){let s=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,s.id,n)}submitToolOutputsStream(e,t,r,n){return rN.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}}class rF extends tV{}(g=rq||(rq={})).RunsPage=rF,g.Steps=rD,g.RunStepsPage=rL;class rB extends tJ{constructor(){super(...arguments),this.runs=new rq(this._client),this.messages=new rj(this._client)}create(e={},t){return e8(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return rN.createThreadAssistantStream(e,this._client.beta.threads,t)}}(y=rB||(rB={})).Runs=rq,y.RunsPage=rF,y.Messages=rj,y.MessagesPage=rU;let rH=async e=>{let t=await Promise.allSettled(e),r=t.filter(e=>"rejected"===e.status);if(r.length){for(let e of r)console.error(e.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let e of t)"fulfilled"===e.status&&n.push(e.value);return n};class rW extends tJ{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},r){return e8(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,rz,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let s=await this.retrieve(e,t,{...r,headers:n}).withResponse(),i=s.data;switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=s.response.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await ti(o);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}}class rz extends tV{}(rW||(rW={})).VectorStoreFilesPage=rz;class rK extends tJ{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return e8(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,rz,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:s,response:i}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(s.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{let e=i.headers.get("openai-poll-after-ms");if(e){let t=parseInt(e);isNaN(t)||(o=t)}}await ti(o);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=Math.min(n?.maxConcurrency??5,t.length),i=this._client,o=t.values(),a=[...r];async function l(e){for(let t of e){let e=await i.files.create({file:t,purpose:"assistants"},n);a.push(e.id)}}let c=Array(s).fill(o).map(l);return await rH(c),await this.createAndPoll(e,{file_ids:a})}}rK||(rK={});class rV extends tJ{constructor(){super(...arguments),this.files=new rW(this._client),this.fileBatches=new rK(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return e8(e)?this.list({},e):this._client.getAPIList("/vector_stores",rJ,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class rJ extends tV{}(b=rV||(rV={})).VectorStoresPage=rJ,b.Files=rW,b.VectorStoreFilesPage=rz,b.FileBatches=rK;class rG extends tJ{constructor(){super(...arguments),this.vectorStores=new rV(this._client),this.chat=new rT(this._client),this.assistants=new ri(this._client),this.threads=new rB(this._client)}}(w=rG||(rG={})).VectorStores=rV,w.VectorStoresPage=rJ,w.Chat=rT,w.Assistants=ri,w.AssistantsPage=ro,w.Threads=rB;class rZ extends tJ{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return e8(e)?this.list({},e):this._client.getAPIList("/batches",rX,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class rX extends tV{}(rZ||(rZ={})).BatchesPage=rX;class rY extends tJ{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,ez({body:t,...r}))}}rY||(rY={});class rQ extends tJ{constructor(){super(...arguments),this.parts=new rY(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}}(rQ||(rQ={})).Parts=rY,r(25566);class r0 extends e2{constructor({baseURL:e=tl("OPENAI_BASE_URL"),apiKey:t=tl("OPENAI_API_KEY"),organization:r=tl("OPENAI_ORG_ID")??null,project:n=tl("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===t)throw new tb("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let i={apiKey:t,organization:r,project:n,...s,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&tp())throw new tb("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new tG(this),this.chat=new tX(this),this.embeddings=new tY(this),this.files=new tQ(this),this.images=new t1(this),this.audio=new t6(this),this.moderations=new t5(this),this.models=new t8(this),this.fineTuning=new rs(this),this.beta=new rG(this),this.batches=new rZ(this),this.uploads=new rQ(this),this._options=i,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return function(e,t={}){let r,n=e,s=function(e=tW){let t;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw TypeError("Encoder has to be a function.");let r=e.charset||tW.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=tM;if(void 0!==e.format){if(!tD.call(t$,e.format))throw TypeError("Unknown format option provided.");n=e.format}let s=t$[n],i=tW.filter;if(("function"==typeof e.filter||tq(e.filter))&&(i=e.filter),t=e.arrayFormat&&e.arrayFormat in tL?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":tW.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=void 0===e.allowDots?!0==!!e.encodeDotInKeys||tW.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:tW.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:tW.allowEmptyArrays,arrayFormat:t,charset:r,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:tW.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?tW.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:tW.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:tW.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:tW.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:tW.encodeValuesOnly,filter:i,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:tW.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:tW.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:tW.strictNullHandling}}(t);"function"==typeof s.filter?n=(0,s.filter)("",n):tq(s.filter)&&(r=s.filter);let i=[];if("object"!=typeof n||null===n)return"";let o=tL[s.arrayFormat],a="comma"===o&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);let l=new WeakMap;for(let e=0;e<r.length;++e){let t=r[e];s.skipNulls&&null===n[t]||tB(i,function e(t,r,n,s,i,o,a,l,c,u,d,f,h,p,m,g,y,b){var w,v;let _,S=t,E=b,A=0,x=!1;for(;void 0!==(E=E.get(tz))&&!x;){let e=E.get(t);if(A+=1,void 0!==e){if(e===A)throw RangeError("Cyclic object value");x=!0}void 0===E.get(tz)&&(A=0)}if("function"==typeof u?S=u(r,S):S instanceof Date?S=h?.(S):"comma"===n&&tq(S)&&(S=tU(S,function(e){return e instanceof Date?h?.(e):e})),null===S){if(o)return c&&!g?c(r,tW.encoder,y,"key",p):r;S=""}if("string"==typeof(w=S)||"number"==typeof w||"boolean"==typeof w||"symbol"==typeof w||"bigint"==typeof w||(v=S)&&"object"==typeof v&&v.constructor&&v.constructor.isBuffer&&v.constructor.isBuffer(v)){if(c){let e=g?r:c(r,tW.encoder,y,"key",p);return[m?.(e)+"="+m?.(c(S,tW.encoder,y,"value",p))]}return[m?.(r)+"="+m?.(String(S))]}let R=[];if(void 0===S)return R;if("comma"===n&&tq(S))g&&c&&(S=tU(S,c)),_=[{value:S.length>0?S.join(",")||null:void 0}];else if(tq(u))_=u;else{let e=Object.keys(S);_=d?e.sort(d):e}let O=l?String(r).replace(/\./g,"%2E"):String(r),k=s&&tq(S)&&1===S.length?O+"[]":O;if(i&&tq(S)&&0===S.length)return k+"[]";for(let r=0;r<_.length;++r){let w=_[r],v="object"==typeof w&&void 0!==w.value?w.value:S[w];if(a&&null===v)continue;let E=f&&l?w.replace(/\./g,"%2E"):w,x=tq(S)?"function"==typeof n?n(k,E):k:k+(f?"."+E:"["+E+"]");b.set(t,A);let O=new WeakMap;O.set(tz,b),tB(R,e(v,x,n,s,i,o,a,l,"comma"===n&&g&&tq(S)?null:c,u,d,f,h,p,m,g,y,O))}return R}(n[t],t,o,a,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,l))}let c=i.join(s.delimiter),u=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),c.length>0?u+c:""}(e,{arrayFormat:"brackets"})}}eE=r0,r0.OpenAI=eE,r0.DEFAULT_TIMEOUT=6e5,r0.OpenAIError=tb,r0.APIError=tw,r0.APIConnectionError=t_,r0.APIConnectionTimeoutError=tS,r0.APIUserAbortError=tv,r0.NotFoundError=tR,r0.ConflictError=tO,r0.RateLimitError=tP,r0.BadRequestError=tE,r0.AuthenticationError=tA,r0.InternalServerError=tC,r0.PermissionDeniedError=tx,r0.UnprocessableEntityError=tk,r0.toFile=eq,r0.fileFromPath=d;let{OpenAIError:r1,APIError:r2,APIConnectionError:r3,APIConnectionTimeoutError:r4,APIUserAbortError:r6,NotFoundError:r5,ConflictError:r8,RateLimitError:r9,BadRequestError:r7,AuthenticationError:ne,InternalServerError:nt,PermissionDeniedError:nr,UnprocessableEntityError:nn}=eA;(v=r0||(r0={})).Page=tK,v.CursorPage=tV,v.Completions=tG,v.Chat=tX,v.Embeddings=tY,v.Files=tQ,v.FileObjectsPage=t0,v.Images=t1,v.Audio=t6,v.Moderations=t5,v.Models=t8,v.ModelsPage=t9,v.FineTuning=rs,v.Beta=rG,v.Batches=rZ,v.BatchesPage=rX,v.Uploads=rQ;var ns=r0},60035:function(e,t,r){"use strict";var n=r(9109).Buffer;let s=void 0!==n,i=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,o=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,r){null==r&&null!==t&&"object"==typeof t&&(r=t,t=void 0),s&&n.isBuffer(e)&&(e=e.toString()),e&&65279===e.charCodeAt(0)&&(e=e.slice(1));let a=JSON.parse(e,t);if(null===a||"object"!=typeof a)return a;let c=r&&r.protoAction||"error",u=r&&r.constructorAction||"error";if("ignore"===c&&"ignore"===u)return a;if("ignore"!==c&&"ignore"!==u){if(!1===i.test(e)&&!1===o.test(e))return a}else if("ignore"!==c&&"ignore"===u){if(!1===i.test(e))return a}else if(!1===o.test(e))return a;return l(a,{protoAction:c,constructorAction:u,safe:r&&r.safe})}function l(e,{protoAction:t="error",constructorAction:r="error",safe:n}={}){let s=[e];for(;s.length;){let e=s;for(let i of(s=[],e)){if("ignore"!==t&&Object.prototype.hasOwnProperty.call(i,"__proto__")){if(!0===n)return null;if("error"===t)throw SyntaxError("Object contains forbidden prototype property");delete i.__proto__}if("ignore"!==r&&Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype")){if(!0===n)return null;if("error"===r)throw SyntaxError("Object contains forbidden prototype property");delete i.constructor}for(let e in i){let t=i[e];t&&"object"==typeof t&&s.push(t)}}}return e}function c(e,t,r){let n=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return a(e,t,r)}finally{Error.stackTraceLimit=n}}e.exports=c,e.exports.default=c,e.exports.parse=c,e.exports.safeParse=function(e,t){let r=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch(e){return null}finally{Error.stackTraceLimit=r}},e.exports.scan=l},34590:function(e,t,r){"use strict";r.d(t,{V8:function(){return n}});class n{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){let t,r,s,i;let o=n.hexChars,a=n.hexOut;for(i=0;i<4;i+=1)for(s=0,r=8*i,t=e[i];s<8;s+=2)a[r+1+s]=o.charAt(15&t),t>>>=4,a[r+0+s]=o.charAt(15&t),t>>>=4;return a.join("")}static _md5cycle(e,t){let r=e[0],n=e[1],s=e[2],i=e[3];r+=(n&s|~n&i)+t[0]-680876936|0,i+=((r=(r<<7|r>>>25)+n|0)&n|~r&s)+t[1]-389564586|0,s+=((i=(i<<12|i>>>20)+r|0)&r|~i&n)+t[2]+606105819|0,n+=((s=(s<<17|s>>>15)+i|0)&i|~s&r)+t[3]-1044525330|0,r+=((n=(n<<22|n>>>10)+s|0)&s|~n&i)+t[4]-176418897|0,i+=((r=(r<<7|r>>>25)+n|0)&n|~r&s)+t[5]+1200080426|0,s+=((i=(i<<12|i>>>20)+r|0)&r|~i&n)+t[6]-1473231341|0,n+=((s=(s<<17|s>>>15)+i|0)&i|~s&r)+t[7]-45705983|0,r+=((n=(n<<22|n>>>10)+s|0)&s|~n&i)+t[8]+1770035416|0,i+=((r=(r<<7|r>>>25)+n|0)&n|~r&s)+t[9]-1958414417|0,s+=((i=(i<<12|i>>>20)+r|0)&r|~i&n)+t[10]-42063|0,n+=((s=(s<<17|s>>>15)+i|0)&i|~s&r)+t[11]-1990404162|0,r+=((n=(n<<22|n>>>10)+s|0)&s|~n&i)+t[12]+1804603682|0,i+=((r=(r<<7|r>>>25)+n|0)&n|~r&s)+t[13]-40341101|0,s+=((i=(i<<12|i>>>20)+r|0)&r|~i&n)+t[14]-1502002290|0,n+=((s=(s<<17|s>>>15)+i|0)&i|~s&r)+t[15]+1236535329|0,r+=((n=(n<<22|n>>>10)+s|0)&i|s&~i)+t[1]-165796510|0,i+=((r=(r<<5|r>>>27)+n|0)&s|n&~s)+t[6]-1069501632|0,s+=((i=(i<<9|i>>>23)+r|0)&n|r&~n)+t[11]+643717713|0,n+=((s=(s<<14|s>>>18)+i|0)&r|i&~r)+t[0]-373897302|0,r+=((n=(n<<20|n>>>12)+s|0)&i|s&~i)+t[5]-701558691|0,i+=((r=(r<<5|r>>>27)+n|0)&s|n&~s)+t[10]+38016083|0,s+=((i=(i<<9|i>>>23)+r|0)&n|r&~n)+t[15]-660478335|0,n+=((s=(s<<14|s>>>18)+i|0)&r|i&~r)+t[4]-405537848|0,r+=((n=(n<<20|n>>>12)+s|0)&i|s&~i)+t[9]+568446438|0,i+=((r=(r<<5|r>>>27)+n|0)&s|n&~s)+t[14]-1019803690|0,s+=((i=(i<<9|i>>>23)+r|0)&n|r&~n)+t[3]-187363961|0,n+=((s=(s<<14|s>>>18)+i|0)&r|i&~r)+t[8]+1163531501|0,r+=((n=(n<<20|n>>>12)+s|0)&i|s&~i)+t[13]-1444681467|0,i+=((r=(r<<5|r>>>27)+n|0)&s|n&~s)+t[2]-51403784|0,s+=((i=(i<<9|i>>>23)+r|0)&n|r&~n)+t[7]+1735328473|0,n+=((s=(s<<14|s>>>18)+i|0)&r|i&~r)+t[12]-1926607734|0,r+=((n=(n<<20|n>>>12)+s|0)^s^i)+t[5]-378558|0,i+=((r=(r<<4|r>>>28)+n|0)^n^s)+t[8]-2022574463|0,s+=((i=(i<<11|i>>>21)+r|0)^r^n)+t[11]+1839030562|0,n+=((s=(s<<16|s>>>16)+i|0)^i^r)+t[14]-35309556|0,r+=((n=(n<<23|n>>>9)+s|0)^s^i)+t[1]-1530992060|0,i+=((r=(r<<4|r>>>28)+n|0)^n^s)+t[4]+1272893353|0,s+=((i=(i<<11|i>>>21)+r|0)^r^n)+t[7]-155497632|0,n+=((s=(s<<16|s>>>16)+i|0)^i^r)+t[10]-1094730640|0,r+=((n=(n<<23|n>>>9)+s|0)^s^i)+t[13]+681279174|0,i+=((r=(r<<4|r>>>28)+n|0)^n^s)+t[0]-358537222|0,s+=((i=(i<<11|i>>>21)+r|0)^r^n)+t[3]-722521979|0,n+=((s=(s<<16|s>>>16)+i|0)^i^r)+t[6]+76029189|0,r+=((n=(n<<23|n>>>9)+s|0)^s^i)+t[9]-640364487|0,i+=((r=(r<<4|r>>>28)+n|0)^n^s)+t[12]-421815835|0,s+=((i=(i<<11|i>>>21)+r|0)^r^n)+t[15]+530742520|0,n+=((s=(s<<16|s>>>16)+i|0)^i^r)+t[2]-995338651|0,n=(n<<23|n>>>9)+s|0,r+=(s^(n|~i))+t[0]-198630844|0,r=(r<<6|r>>>26)+n|0,i+=(n^(r|~s))+t[7]+1126891415|0,i=(i<<10|i>>>22)+r|0,s+=(r^(i|~n))+t[14]-1416354905|0,s=(s<<15|s>>>17)+i|0,n+=(i^(s|~r))+t[5]-57434055|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~i))+t[12]+1700485571|0,r=(r<<6|r>>>26)+n|0,i+=(n^(r|~s))+t[3]-1894986606|0,i=(i<<10|i>>>22)+r|0,s+=(r^(i|~n))+t[10]-1051523|0,s=(s<<15|s>>>17)+i|0,n+=(i^(s|~r))+t[1]-2054922799|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~i))+t[8]+1873313359|0,r=(r<<6|r>>>26)+n|0,i+=(n^(r|~s))+t[15]-30611744|0,i=(i<<10|i>>>22)+r|0,s+=(r^(i|~n))+t[6]-1560198380|0,s=(s<<15|s>>>17)+i|0,n+=(i^(s|~r))+t[13]+1309151649|0,n=(n<<21|n>>>11)+s|0,r+=(s^(n|~i))+t[4]-145523070|0,r=(r<<6|r>>>26)+n|0,i+=(n^(r|~s))+t[11]-1120210379|0,i=(i<<10|i>>>22)+r|0,s+=(r^(i|~n))+t[2]+718787259|0,s=(s<<15|s>>>17)+i|0,n+=(i^(s|~r))+t[9]-343485551|0,n=(n<<21|n>>>11)+s|0,e[0]=r+e[0]|0,e[1]=n+e[1]|0,e[2]=s+e[2]|0,e[3]=i+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(n.stateIdentity),this}appendStr(e){let t,r;let s=this._buffer8,i=this._buffer32,o=this._bufferLength;for(r=0;r<e.length;r+=1){if((t=e.charCodeAt(r))<128)s[o++]=t;else if(t<2048)s[o++]=(t>>>6)+192,s[o++]=63&t|128;else if(t<55296||t>56319)s[o++]=(t>>>12)+224,s[o++]=t>>>6&63|128,s[o++]=63&t|128;else{if((t=(t-55296)*1024+(e.charCodeAt(++r)-56320)+65536)>1114111)throw Error("Unicode standard supports code points up to U+10FFFF");s[o++]=(t>>>18)+240,s[o++]=t>>>12&63|128,s[o++]=t>>>6&63|128,s[o++]=63&t|128}o>=64&&(this._dataLength+=64,n._md5cycle(this._state,i),o-=64,i[0]=i[16])}return this._bufferLength=o,this}appendAsciiStr(e){let t;let r=this._buffer8,s=this._buffer32,i=this._bufferLength,o=0;for(;;){for(t=Math.min(e.length-o,64-i);t--;)r[i++]=e.charCodeAt(o++);if(i<64)break;this._dataLength+=64,n._md5cycle(this._state,s),i=0}return this._bufferLength=i,this}appendByteArray(e){let t;let r=this._buffer8,s=this._buffer32,i=this._bufferLength,o=0;for(;;){for(t=Math.min(e.length-o,64-i);t--;)r[i++]=e[o++];if(i<64)break;this._dataLength+=64,n._md5cycle(this._state,s),i=0}return this._bufferLength=i,this}getState(){let e=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){let t;let r=e.buffer,n=e.state,s=this._state;for(t=0,this._dataLength=e.length,this._bufferLength=e.buflen,s[0]=n[0],s[1]=n[1],s[2]=n[2],s[3]=n[3];t<r.length;t+=1)this._buffer8[t]=r.charCodeAt(t)}end(e=!1){let t=this._bufferLength,r=this._buffer8,s=this._buffer32,i=(t>>2)+1;this._dataLength+=t;let o=8*this._dataLength;if(r[t]=128,r[t+1]=r[t+2]=r[t+3]=0,s.set(n.buffer32Identity.subarray(i),i),t>55&&(n._md5cycle(this._state,s),s.set(n.buffer32Identity)),o<=4294967295)s[14]=o;else{let e=o.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;let t=parseInt(e[2],16),r=parseInt(e[1],16)||0;s[14]=t,s[15]=r}return n._md5cycle(this._state,s),e?this._state:n._hex(this._state)}}if(n.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),n.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),n.hexChars="0123456789abcdef",n.hexOut=[],n.onePassHasher=new n,"5d41402abc4b2a76b9719d911017c592"!==n.hashStr("hello"))throw Error("Md5 self test failed.")}}]);