@intelliweave/embedded 2.0.71 → 2.0.72-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,156 @@
1
- import{v4 as Me}from"uuid";function ye(l){let i=(l||"").split(`
2
- `);for(;i.length>0&&i[0].trim()=="";)i.shift();for(;i.length>0&&i[i.length-1].trim()=="";)i.pop();let e=1/0;for(let t of i){let s=t.match(/^\s*/)?.[0].length||0;e=Math.min(e,s)}return e>0&&e<1/0&&(i=i.map(t=>t.substring(e))),i.join(`
3
- `)}var De={};function C(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:De}function m(){return C().intelliweave=C().intelliweave||C().webWeaver||{},C().intelliweave}async function*ke(l){let i="",e=function*(){for(;;){let n=i.indexOf(`
4
-
5
- `);if(n==-1)break;let o=i.slice(0,n);i=i.slice(n+2);let a={},d=o.split(`
6
- `);for(let c of d){n=c.indexOf(": ");let r=c.slice(0,n),u=c.slice(n+2);n==-1&&(r=c,u=""),r&&(a[r]!==void 0?a[r]+=`
7
- `+u:a[r]=u)}yield a}},t=new TextDecoder,s=l.getReader();for(;;){let{done:n,value:o}=await s.read();if(n)break;i+=t.decode(o,{stream:!0}),yield*e()}i+=t.decode()+`
8
-
9
- `,yield*e()}function Ie(){if(m().userID)return m().userID||"";if(typeof localStorage<"u"){let l=localStorage.getItem("intelliweave.uid")||"";return l||(l=Me(),localStorage.setItem("intelliweave.uid",l),l)}else return Me()}function We(l){let i=l;if(i?.type=="object"&&i.properties)return l;let e={type:"object",properties:{},required:[]};if(l&&Array.isArray(l)){let t=l;for(let s of t)e.properties[s.name]={type:s.type||"string",description:s.description||""}}return e}var z=class z{constructor(i){this.module="IntelliWeave";this.module=i}get debugEnabled(){return z.debug?!0:typeof window<"u"&&m().debug}log(...i){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...i)}debug(...i){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...i)}info(...i){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...i)}warn(...i){console.warn(`[IntelliWeave > ${this.module}]`,...i)}error(...i){console.error(`[IntelliWeave > ${this.module}]`,...i)}timer(i,...e){let t=Date.now();return this.debug(`[${i} 0ms] Started`,...e),(...s)=>this.debug(`[${i} ${Math.floor(Date.now()-t)}ms]`,...s)}};z.debug=!1;var h=z;import{countTokens as Fe}from"gpt-tokenizer";import{countTokens as O}from"gpt-tokenizer";import{v4 as Ke}from"uuid";var J=class{constructor(){this.size=4096;this.groups=[]}createGroup(i){let e=new be;return e.id=i,this.groups.push(e),e}group(i){return this.groups.find(e=>e.id===i)}countTokens(){return this.groups.reduce((i,e)=>i+e.tokenCount,0)}removeOverflow(){let i=this.countTokens(),e=this.groups.reduce((t,s)=>t+s.weight,0);for(;i>this.size;){let t=this.groups.slice().sort((n,o)=>{let a=Math.floor(n.weight/e*this.size),d=Math.floor(o.weight/e*this.size),c=n.tokenCount-a;return o.tokenCount-d-c}),s=this.removeOneItem(t);if(!s)throw new Error("Too many items in the token window that cannot be removed.");i-=s.tokenCount}}removeOneItem(i){for(let e of i){let t=e.items.findIndex(n=>!n.cannotRemove);if(t===-1)continue;let s=e.items[t];return e.items.splice(t,1),e.tokenCount-=s.tokenCount,s}return null}},be=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
10
- `;this.itemPadding=0;this.sortFunction=(i,e)=>i.sortOrder!==e.sortOrder?i.sortOrder-e.sortOrder:i.dateAdded!==e.dateAdded?i.dateAdded-e.dateAdded:i.content.localeCompare(e.content)}setItemPadding(i){return this.itemPadding=i,this.recalculateTokens(),this}sortBy(i){return this.sortFunction=i,this.items.sort(this.sortFunction),this}setSeparator(i){return this.separator==i?this:(this.separator=i,this.recalculateTokens(),this)}setWeight(i){return this.weight=i,this}recalculateTokens(){this.tokenCount=this.items.reduce((i,e)=>(e.tokenCount=O(e.content)+O(this.separator)+this.itemPadding,i+e.tokenCount),0)}add(i){typeof i=="string"&&(i={content:i});let e=i;e.id===void 0&&(e.id=Ke());let t=this.items.find(s=>s.id===e.id);return t?(this.tokenCount-=t.tokenCount,Object.assign(t,e),e=t):this.items.push(e),e.dateAdded===void 0&&(e.dateAdded=Date.now()),e.sortOrder===void 0&&(e.sortOrder=0),e.disabled===void 0&&(e.disabled=!1),e.tokenCount=e.disabled?0:O(i.content)+O(this.separator)+this.itemPadding,this.tokenCount+=e.tokenCount,this.items.sort(this.sortFunction),e}getAllAsString(){return this.getAll().map(i=>i.content).join(this.separator)}getAll(){return this.items.filter(i=>!i.disabled)}empty(){this.items=[],this.tokenCount=0}};var W=class{constructor(i){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let i=new J;return i.createGroup("context").setSeparator(`
11
-
12
- `),i.createGroup("actions").setItemPadding(25),i.createGroup("messages").setItemPadding(10),i})();this.config=i,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}async sendMessage(i){throw new Error("Not implemented")}addUserMessage(i){throw new Error("Not implemented")}addAssistantMessage(i){throw new Error("Not implemented")}onBeforeIncomingMessage(i){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(i){return this.toolGroup.add({id:i.name,customData:i,cannotRemove:i.isContext,sortOrder:101,disabled:i.disabled,content:JSON.stringify(i)})}};import{v4 as X}from"uuid";var S=new h("ChatGPT"),H=class extends W{async sendMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e}),await this.processMessages();let s=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;return s?.role=="assistant"&&s.content||""}addAssistantMessage(i){let e={role:"assistant",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}addUserMessage(i){let e={role:"user",content:i};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(e),customData:e})}getMessages(){return this.messageGroup.items.map(i=>i.customData)}getLatestMessage(){return this.messageGroup.items.length?this.messageGroup.items[this.messageGroup.items.length-1]?.customData:void 0}async processMessages(){await this.config.onBeforeMessageProcessing?.(),S.debugEnabled&&S.debug("Process message state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(t=>t.customData),messages:this.messageGroup.items.map(t=>t.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let e=this.messageGroup.items[this.messageGroup.items.length-1]?.customData;if(e?.role=="user"||e?.role=="tool")await this.sendToAPI(),await this.processMessages();else if(e?.role=="assistant"&&e?.tool_calls?.length){for(let t of e.tool_calls)await this.processToolCall(t);await this.processMessages()}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].customData?.role=="tool";)this.messageGroup.items.shift()}async sendRequest(i){let e={};return e["Content-Type"]="application/json",this.config.apiKey&&(e.Authorization=`Bearer ${this.config.apiKey}`),await fetch(this.config.endpoint||"https://api.openai.com/v1/chat/completions",{method:"POST",headers:e,body:JSON.stringify(i)})}async sendToAPI(i){this.config.systemMessage&&this.contextGroup.add({id:"_gpt_context",cannotRemove:!0,sortOrder:0,content:this.config.systemMessage}),await this.trimMessages();let e=0;for(let a=this.messageGroup.items.length-1;a>=0;a--){let d=this.messageGroup.items[a].customData;if(d.role=="assistant"&&d.tool_calls){if(e+=1,e>=this.maxToolCallsPerMessage)throw new Error(`Exceeded the maximum tool calls per message limit of ${this.maxToolCallsPerMessage}.`)}else if(d.role=="user")break}S.debugEnabled&&S.debug("Before LLM state:",{context:this.contextGroup.getAllAsString(),tools:this.toolGroup.getAll().map(a=>a.customData),messages:this.messageGroup.items.map(a=>a.customData),tokens:{used:this.tokenWindow.countTokens(),max:this.tokenWindow.size}});let t={model:this.config.model,temperature:.2,user:this.config.userID,tools:[],stream:!!this.config.stream,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(a=>a.customData)]};for(let a of this.toolGroup.getAll()){let d=a.customData;d.description&&d.description.length>1024&&S.warn(`Tool description for "${d.name}" is too long, it will be truncated.`);let c={type:"function",function:{name:d.name,description:(d.description||"").substring(0,1024),parameters:d.params}};t.tools.push(c)}if(t.user||delete t.user,t.tools.length||delete t.tools,i)return t;let s=await this.sendRequest(t);if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();a=c.errorText||c.error?.message||c.error||a}catch{}let d=new Error(a);throw d.code=s.status,d}let n=null,o=null;if(this.config.stream){for await(let d of ke(s.body)){if(d.data=="[DONE]")break;if(!d.data)continue;let c=JSON.parse(d.data);if(o){for(let r in c.choices[0].delta)if(typeof c.choices[0].delta[r]=="string"){if(r=="role"&&o[r]==c.choices[0].delta[r])continue;o[r]=(o[r]||"")+c.choices[0].delta[r]}for(let r of c.choices[0].delta.tool_calls||[]){if(o.tool_calls||(o.tool_calls=[]),!o.tool_calls[r.index]){o.tool_calls[r.index]=r;continue}let u=o.tool_calls[r.index];u.function=u.function||{},u.function.name=(u.function.name||"")+(r.function?.name||""),u.function.arguments=(u.function.arguments||"")+(r.function?.arguments||"")}}else o={chunkID:c.id,...c.choices[0].delta};o?.content&&!o.content.startsWith("{")&&this.config.onAIMessage?.(o.content,!0)}let a=Fe(JSON.stringify(t)+JSON.stringify(o)||"");this.stats.tokensUsed+=a,S.debug(`Estimated ${a} tokens for streaming response, total used: ${this.stats.tokensUsed}`)}else n=await s.json(),this.stats.tokensUsed+=n?.usage?.total_tokens||0,S.debug(`Used ${n?.usage?.total_tokens||0} tokens, total used: ${this.stats.tokensUsed}`),o=n?.choices?.[0]?.message;if(o||(S.warn("No response block in API response."),o={role:"assistant",content:""}),o.role=="user")throw new Error("API returned a user message, which is not allowed.");this.onBeforeIncomingMessage(o),this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o}),o.content&&this.config.onAIMessage?.(o.content,!1)}async processToolCall(i){try{let t=this.toolGroup.items.find(a=>a.id==i.function.name)?.customData;if(!t)throw new Error(`Tool "${i.function.name}" not found.`);let s=JSON.parse(i.function.arguments);this.config.onAIToolStart?.(i.function.name,s);let n=await t.callback(s);typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success");let o={role:"tool",content:n,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(o),customData:o})}catch(e){S.warn(`Unable to process tool call for "${i?.function?.name}"`,e);let t={role:"tool",content:`Error: ${e.message}`,tool_call_id:i.id};this.messageGroup.add({id:"msg-"+X(),content:JSON.stringify(t),customData:t})}}};import Ye from"@anthropic-ai/sdk";import{v4 as U}from"uuid";var j=new h("AnthropicChat"),$=class extends W{addUserMessage(i){let e={role:"user",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}addAssistantMessage(i){let e={role:"assistant",content:i||""};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(e),customData:e})}async sendMessage(i){this.addUserMessage(i);let e=new Ye({apiKey:this.config.apiKey,baseURL:this.config.endpoint,dangerouslyAllowBrowser:!0}),t=!0,s="",n="";for(;t;){t=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),j.debug("Before processing state",{messages:this.messageGroup.getAll().map(p=>p.customData),tools:this.toolGroup.getAll().map(p=>p.customData),context:this.contextGroup.getAll().map(p=>p.content)});let o=this.toolGroup.getAll().map(p=>({name:p.customData?.name||"",description:p.customData?.description||"",input_schema:{type:"object",required:p.customData?.params.required||[],properties:p.customData?.params.properties||{}}})),a;if(this.config.stream){let p=e.messages.stream({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(Z=>Z.customData),tools:o,stream:!0});p.on("text",Z=>{n+=Z,this.config.onAIMessage?.(n,!0)}),a=await p.finalMessage()}else a=await e.messages.create({model:this.config.model,max_tokens:4096,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(p=>p.customData),tools:o});j.debug("Message received",a);let d=!0;Array.isArray(a.content)&&a.content.length==0&&(d=!1);let c={role:a.role,content:a.content};d&&this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(c),customData:c});let r=[];for(let p of a.content)p.type=="thinking"?j.debug(`AI is thinking: ${p.thinking}`):p.type=="text"?s+=p.text||`
13
-
14
- `:p.type=="tool_use"&&r.push(this.performToolCall(p));let u=await Promise.all(r);if(u.length>0){let p={role:"user",content:u};this.messageGroup.add({id:"msg-"+U(),content:JSON.stringify(p),customData:p}),t=!0}this.config.onAIMessage?.(s,!0),this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return s=s.trim(),this.config.onAIMessage?.(s,!1),s}async performToolCall(i){try{let e=this.toolGroup.getAll().find(s=>s.customData?.name==i.name);if(!e)throw new Error(`Tool ${i.name} not found`);this.config.onAIToolStart?.(i.name,i.input);let t=await e.customData.callback(i.input);return typeof t!="string"&&(t=JSON.stringify(t)||""),(t===""||t==="undefined")&&(t="success"),{type:"tool_result",tool_use_id:i.id,content:String(t||"")}}catch(e){return j.error(`Error performing tool call ${i.name}: ${e.message||e.toString()}`),{type:"tool_result",tool_use_id:i.id,content:`Error performing tool call ${i.name}: ${e.message||e.toString()}`}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.customData?.content?.type=="tool_result";)this.messageGroup.items.shift()}};import{v4 as we}from"uuid";import Qe from"minisearch";var Xe=l=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,removeFromMessageHistory:!0,parameters:[{name:"query",type:"string",description:"The search query"}],action:async(i,e)=>{let t=await e.knowledgeBase.search(i.query),s=e;s._lastKBsearch=i.query,s._nextRequestUseKBitems=t,e.submitAnalyticsEvent({type:"kb-search",query:i.query,results:t});let n=t.filter(a=>a.type!="action").map(a=>"id="+a.id).join(", ")||"(none)",o=t.filter(a=>a.type=="action").map(a=>"name="+a._functionID).join(", ")||"(none)";return`Search complete, context has been updated. New info entries found: ${n}. New tools available: ${o}.`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!i.url||typeof i.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(i.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return e.submitAnalyticsEvent({type:"open-url",url:i.url}),`Opened URL: ${i.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!i.path||typeof i.path!="string")throw new Error("Path parameter is required and must be a string.");let t=new URL(i.path,window.location.origin).pathname;return window.location.href=t,e.submitAnalyticsEvent({type:"change-route",path:t}),`Changed route to: ${t}`}},{id:"ui.sendEmail",type:"action",name:"Send an email using the default mail client.",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!l?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(i,e)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!e.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!i.email_address||typeof i.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!i.subject||typeof i.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!i.body||typeof i.body!="string")throw new Error("Body parameter is required and must be a string.");let t=encodeURIComponent(i.email_address),s=encodeURIComponent(i.subject),n=encodeURIComponent(i.body),o=`mailto:${t}?subject=${s}&body=${n}`;try{window.location.href=o}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return e.submitAnalyticsEvent({type:"send-email",email_address:i.email_address,subject:i.subject,body_length:i.body.length}),`Email opened in default mail client. Recipient: ${i.email_address}, Subject: ${i.subject}`}}];import{Client as Te}from"@modelcontextprotocol/sdk/client/index.js";import{StreamableHTTPClientTransport as Oe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as Je}from"@modelcontextprotocol/sdk/client/sse.js";var G={name:"@intelliweave/embedded",version:"2.0.71",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && tsx --test","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.64","@types/lodash":"^4.17.13","@types/react":"^18.3.12","@types/uuid":"^10.0.0",bestzip:"^2.2.1","cross-env":"^7.0.3","find-cache-dir":"^5.0.0",lodash:"^4.17.21","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.2.0",tsup:"^8.3.5",tsx:"^4.19.2",typedoc:"^0.27.6"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.60.0","@modelcontextprotocol/sdk":"^1.24.1","@types/json-schema":"^7.0.15","gpt-tokenizer":"^2.9.0",minisearch:"^6.3.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.0","rehype-stringify":"^10.0.0","remark-parse":"^11.0.0","remark-rehype":"^11.1.0",unified:"^11.0.4","utility-types":"^3.11.0",uuid:"^10.0.0"}};import{LoggingMessageNotificationSchema as He,ToolListChangedNotificationSchema as Ue}from"@modelcontextprotocol/sdk/types.js";var g=new h("MCPKnowledgeClient"),Q=class{constructor(i){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=i}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){g.debug("Connecting to MCP client");let i=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let e=new Te({name:G.name,version:G.version}),t=new Oe(new URL(this.config.baseURL));return await e.connect(t),g.debug("Connected with HTTP streaming mode"),e}).catch(async e=>{let t=new Te({name:G.name,version:G.version}),s=new Je(new URL(this.config.baseURL));return await t.connect(s),g.debug("Connected with SSE mode"),t});return await this.disconnect(),this.client=i,i.onerror=e=>{g.error(`MCP client error: ${e.message}`)},i.onclose=()=>{g.debug("MCP client connection closed"),this.client=void 0},i.setNotificationHandler(He,e=>{e.params.level=="critical"?g.error(`[Server] ${e.params.data}`):e.params.level=="emergency"?g.error(`[Server] ${e.params.data}`):e.params.level=="error"?g.error(`[Server] ${e.params.data}`):e.params.level=="warning"?g.warn(`[Server] ${e.params.data}`):e.params.level=="info"?g.info(`[Server] ${e.params.data}`):e.params.level=="debug"?g.debug(`[Server] ${e.params.data}`):g.log(`[Server] ${e.params.data}`)}),i.setNotificationHandler(Ue,e=>{g.debug("Tool list changed",e),this.fetchTools()}),g.debug("Fetching tools from MCP server..."),await this.fetchTools(),i}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let i=[],e;for(;;){let s=await this.client.listTools({cursor:e});e=s.nextCursor;for(let n of s.tools||[])i.push(n);if(!s?.tools?.length||!e)break}let t=[];for(let s of i){let n=!!(this.config.searchToolName&&s.name==this.config.searchToolName&&!this.config.searchToolVisible);t.push({id:s.name,name:s.name,content:s.description||"",type:"action",isContext:!0,parameters:s.inputSchema,action:o=>this.performToolCall(s.name,o),disabled:n})}g.debug(`Fetched ${i.length} tools from MCP server.`),this.tools=i,this.iwActions=t}async search(i){if(i==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let e=this.iwActions.slice(),t=await this.performSearchCall(i);return e=e.concat(t),this.lastSearchQuery=i,this.lastSearchResults=e,g.debug(`Search completed, found ${e.length} items.`),e}async performSearchCall(i){let e=[];if(!this.config.searchToolName)return e;let t=this.tools.find(n=>n.name==this.config.searchToolName);if(!t)return g.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),e;let s;if(t.inputSchema.required?.length==1){let n=t.inputSchema.required[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else if(t.inputSchema.properties&&Object.keys(t.inputSchema.properties).length==1){let n=Object.keys(t.inputSchema.properties)[0];s=await this.performToolCall(this.config.searchToolName,{[n]:i})}else s=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(s))for(let n=0;n<s.length;n++){let o=s[n];e.push({id:this.config.id+":"+this.config.searchToolName+":"+n,name:`Search result ${n+1} in ${this.config.searchToolName}`,type:"info",content:typeof o=="string"?o:JSON.stringify(o)})}else e.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)});return e}async performToolCall(i,e){await this.connect(),g.debug(`Performing tool call for ${i} with params:`,e),this.stats.toolsCalled+=1;let t=await this.client.callTool({name:i,arguments:e});if(t.isError){let s=t.content?.[0]?.text||"Unknown error";throw g.error(`Error calling tool ${i}: ${s}`),new Error(`Error calling tool ${i}: ${s}`)}if(Array.isArray(t.content)&&t.content.length==1&&t.content[0].type=="text")try{return JSON.parse(t.content[0].text)}catch{}return t.content||[]}};import{v4 as je}from"uuid";var $e=new h("Statistics"),N=[];async function f(l,i){let e={...i,event_id:je(),event_date:new Date().toISOString(),sdk_version:G.version,conversation_id:l?.conversationID||"",api_key:l?.apiKey||"",user_id:l?.userID||""};if(N.push(e),!l||(await new Promise(s=>setTimeout(s,5e3)),N.length===0))return;let t=N.slice();N.length=0;try{let s=await fetch(l.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t})});if(!s.ok)throw new Error(`Analytics submission failed: ${s.status} ${s.statusText}`)}catch(s){$e.warn("Failed to submit analytics event:",s),N.push(...t);return}}var k=new h("KnowledgeBase"),ve=1,q=class l{constructor(i){this._sources=[{id:"core.internal",query:async()=>Xe(this.ai)}];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.ai=i}registerSource(i,e){let t=i;return typeof i=="function"&&(e=i,t=`source.${ve++}`),this._sources.push({id:t,query:e}),t}removeSource(i){this._sources=this.sources.filter(e=>e.id!==i&&e.query!==i)}addEntry(i){this.manualEntries.push(i)}removeEntry(i){this.manualEntries=this.manualEntries.filter(e=>e.id!==i)}get sources(){let i=this._sources;return m().knowledgeBaseSources&&(i=i.concat(m().knowledgeBaseSources)),i=i.concat(this._windowSources),i=i.filter(e=>!e.disabled),i}async search(i){let e=Date.now();k.debug(`Searching knowledge base for: ${i}`);let t=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});t.query=i,t.entries=[],t.sources=[],typeof document<"u"&&document.dispatchEvent(t),this._windowSources=t.sources;let n=(await Promise.all(this.sources.map(async c=>{try{let r=Date.now(),u=await c.query(i);return k.debug(`Source '${c.id}' took ${Date.now()-r}ms`),u||[]}catch(r){return k.warn(`Knowledge source '${c.id}' failed:`,r),[]}}))).flat();n=n.concat(t.entries),n=n.concat(this.manualEntries),m().knowledgeBase&&(n=n.concat(m().knowledgeBase)),n=n.filter(c=>c&&!c.disabled);for(let c=0;c<n.length;c++){let r=n[c];r.id=r.id||`temp.${c}`,r._functionID=r.id.replaceAll(/[^a-zA-Z0-9_]/g,"_"),!r.action&&r.type=="tour"&&(r.action=u=>{throw new Error("This tour does not have an action. You must perform the tour content manually.")}),!r.action&&r.type=="info"&&(r.action=u=>{throw new Error("This item does not have an action. Use the content to provide information to the user instead.")})}let o=new Qe({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});o.addAll(n);let d=o.search(i).map(c=>n.find(r=>r.id==c.id));for(let c of n)c.isContext&&(d.find(r=>r.id===c.id)||d.push(c));return this.lastResults=d,f(this.ai,{event_type:"kb_search",value:d.length,value_str:"",event_properties:{search_time_ms:Date.now()-e,sources_searched:this.sources.length}}),k.debug("Found results:",d),d}getCachedEntry(i){return this.lastResults.find(e=>e.id==i||e._functionID==i)}registerSourceFromURL(i,e){e||(e=`external.${ve++}`),k.debug(`Registering remote knowledge base source: ${i}`);let t=[],s=[],n=!0,o=async(d,c)=>{k.debug(`Calling remote knowledge base action: ${d.id}`);let r={type:"action",userID:this.ai.userID,actionID:d.id,parameters:c},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let p=await u.json();return a(p.updateItems||[]),p.response},a=d=>{for(let c of d){if(!c.id){k.warn("KB item skipped since it has no ID.",c);continue}let r=t.find(u=>u.id==c.id);if(r){r.name=c.name||r.name||"",r.content=c.content||r.content||"",r.disabled=c.disabled??r.disabled,r.isContext=c.isContext??r.isContext,r.parameters=c.parameters||r.parameters||[],r.tags=c.tags||r.tags,r.type=c.type||r.type;continue}t.push({...c,action:u=>o(c,u)})}};this.registerSource(e,async d=>{if(n&&s.includes(d))return t;let c={type:"search",userID:this.ai?.userID||"",query:d},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!r.ok)throw new Error(`HTTP Error ${r.status} ${r.statusText}`);let u=await r.json();return n=!u.noCache,s.includes(d)||s.push(d),a(u.items),t})}clone(){let i=new l(this.ai);return i._sources=this._sources,i._windowSources=this._windowSources,i.manualEntries=this.manualEntries,i}registerMCPSource(i){i.id||(i.id=`external.${ve++}`);let e=new Q(i);return this.registerSource(i.id,t=>e.search(t)),e}};var ee=class{constructor(i){this.ai=i}async boolean(i){let e=await this.instruct({...i,instruction:`${i.instruction}
15
-
16
- Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(e.toLowerCase().includes("true"))return!0;if(e.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+e)}async choose(i){let e=await this.instruct({...i,instruction:`${i.instruction}
1
+ import{b as C,c as Yu,d as cb}from"./chunk-FSRPMVAS.js";var Tp=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.regexpCode=He.getEsmExportName=He.getProperty=He.safeStringify=He.stringify=He.strConcat=He.addCodeArg=He.str=He._=He.nil=He._Code=He.Name=He.IDENTIFIER=He._CodeOrName=void 0;var Ep=class{};He._CodeOrName=Ep;He.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Pa=class extends Ep{constructor(e){if(super(),!He.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};He.Name=Pa;var zn=class extends Ep{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Pa&&(r[n.str]=(r[n.str]||0)+1),r),{})}};He._Code=zn;He.nil=new zn("");function hz(t,...e){let r=[t[0]],n=0;for(;n<e.length;)T0(r,e[n]),r.push(t[++n]);return new zn(r)}He._=hz;var P0=new zn("+");function gz(t,...e){let r=[Pp(t[0])],n=0;for(;n<e.length;)r.push(P0),T0(r,e[n]),r.push(P0,Pp(t[++n]));return mV(r),new zn(r)}He.str=gz;function T0(t,e){e instanceof zn?t.push(...e._items):e instanceof Pa?t.push(e):t.push(yV(e))}He.addCodeArg=T0;function mV(t){let e=1;for(;e<t.length-1;){if(t[e]===P0){let r=hV(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function hV(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Pa||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Pa))return`"${t}${e.slice(1)}`}function gV(t,e){return e.emptyStr()?t:t.emptyStr()?e:gz`${t}${e}`}He.strConcat=gV;function yV(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Pp(Array.isArray(t)?t.join(","):t)}function _V(t){return new zn(Pp(t))}He.stringify=_V;function Pp(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}He.safeStringify=Pp;function bV(t){return typeof t=="string"&&He.IDENTIFIER.test(t)?new zn(`.${t}`):hz`[${t}]`}He.getProperty=bV;function vV(t){if(typeof t=="string"&&He.IDENTIFIER.test(t))return new zn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}He.getEsmExportName=vV;function wV(t){return new zn(t.toString())}He.regexpCode=wV});var N0=C(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.ValueScope=Gr.ValueScopeName=Gr.Scope=Gr.varKinds=Gr.UsedValueState=void 0;var Wr=Tp(),A0=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Lg;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Lg||(Gr.UsedValueState=Lg={}));Gr.varKinds={const:new Wr.Name("const"),let:new Wr.Name("let"),var:new Wr.Name("var")};var Ug=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Wr.Name?e:this.name(e)}name(e){return new Wr.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Gr.Scope=Ug;var Zg=class extends Wr.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Wr._)`.${new Wr.Name(r)}[${n}]`}};Gr.ValueScopeName=Zg;var xV=(0,Wr._)`\n`,z0=class extends Ug{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?xV:Wr.nil}}get(){return this._scope}name(e){return new Zg(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:o,itemIndex:l}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Wr._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=Wr.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Lg.Started);let u=r(l);if(u){let d=this.opts.es5?Gr.varKinds.var:Gr.varKinds.const;o=(0,Wr._)`${o}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Wr._)`${o}${u}${this.opts._n}`;else throw new A0(l);c.set(l,Lg.Completed)})}return o}};Gr.ValueScope=z0});var Le=C(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.or=Me.and=Me.not=Me.CodeGen=Me.operators=Me.varKinds=Me.ValueScopeName=Me.ValueScope=Me.Scope=Me.Name=Me.regexpCode=Me.stringify=Me.getProperty=Me.nil=Me.strConcat=Me.str=Me._=void 0;var Fe=Tp(),ni=N0(),ps=Tp();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return ps._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return ps.str}});Object.defineProperty(Me,"strConcat",{enumerable:!0,get:function(){return ps.strConcat}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return ps.nil}});Object.defineProperty(Me,"getProperty",{enumerable:!0,get:function(){return ps.getProperty}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return ps.stringify}});Object.defineProperty(Me,"regexpCode",{enumerable:!0,get:function(){return ps.regexpCode}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return ps.Name}});var Bg=N0();Object.defineProperty(Me,"Scope",{enumerable:!0,get:function(){return Bg.Scope}});Object.defineProperty(Me,"ValueScope",{enumerable:!0,get:function(){return Bg.ValueScope}});Object.defineProperty(Me,"ValueScopeName",{enumerable:!0,get:function(){return Bg.ValueScopeName}});Object.defineProperty(Me,"varKinds",{enumerable:!0,get:function(){return Bg.varKinds}});Me.operators={GT:new Fe._Code(">"),GTE:new Fe._Code(">="),LT:new Fe._Code("<"),LTE:new Fe._Code("<="),EQ:new Fe._Code("==="),NEQ:new Fe._Code("!=="),NOT:new Fe._Code("!"),OR:new Fe._Code("||"),AND:new Fe._Code("&&"),ADD:new Fe._Code("+")};var yo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},C0=class extends yo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ni.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=iu(this.rhs,e,r)),this}get names(){return this.rhs instanceof Fe._CodeOrName?this.rhs.names:{}}},Fg=class extends yo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Fe.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=iu(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Fe.Name?{}:{...this.lhs.names};return qg(e,this.rhs)}},O0=class extends Fg{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},R0=class extends yo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},M0=class extends yo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},j0=class extends yo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},D0=class extends yo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=iu(this.code,e,r),this}get names(){return this.code instanceof Fe._CodeOrName?this.code.names:{}}},Ap=class extends yo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(kV(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>za(e,r.names),{})}},_o=class extends Ap{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},L0=class extends Ap{},nu=class extends _o{};nu.kind="else";var Ta=class t extends _o{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new nu(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(yz(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=iu(this.condition,e,r),this}get names(){let e=super.names;return qg(e,this.condition),this.else&&za(e,this.else.names),e}};Ta.kind="if";var Aa=class extends _o{};Aa.kind="for";var U0=class extends Aa{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=iu(this.iteration,e,r),this}get names(){return za(super.names,this.iteration.names)}},Z0=class extends Aa{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?ni.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=qg(super.names,this.from);return qg(e,this.to)}},Vg=class extends Aa{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=iu(this.iterable,e,r),this}get names(){return za(super.names,this.iterable.names)}},zp=class extends _o{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};zp.kind="func";var Np=class extends Ap{render(e){return"return "+super.render(e)}};Np.kind="return";var F0=class extends _o{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&za(e,this.catch.names),this.finally&&za(e,this.finally.names),e}},Cp=class extends _o{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Cp.kind="catch";var Op=class extends _o{render(e){return"finally"+super.render(e)}};Op.kind="finally";var V0=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new ni.Scope({parent:e}),this._nodes=[new L0]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new C0(e,o,n)),o}const(e,r,n){return this._def(ni.varKinds.const,e,r,n)}let(e,r,n){return this._def(ni.varKinds.let,e,r,n)}var(e,r,n){return this._def(ni.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Fg(e,r,n))}add(e,r){return this._leafNode(new O0(e,Me.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Fe.nil&&this._leafNode(new D0(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Fe.addCodeArg)(r,i));return r.push("}"),new Fe._Code(r)}if(e,r,n){if(this._blockNode(new Ta(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ta(e))}else(){return this._elseNode(new nu)}endIf(){return this._endBlockNode(Ta,nu)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new U0(e),r)}forRange(e,r,n,i,o=this.opts.es5?ni.varKinds.var:ni.varKinds.let){let s=this._scope.toName(e);return this._for(new Z0(o,s,r,n),()=>i(s))}forOf(e,r,n,i=ni.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof Fe.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Fe._)`${s}.length`,a=>{this.var(o,(0,Fe._)`${s}[${a}]`),n(o)})}return this._for(new Vg("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?ni.varKinds.var:ni.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Fe._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Vg("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Aa)}label(e){return this._leafNode(new R0(e))}break(e){return this._leafNode(new M0(e))}return(e){let r=new Np;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Np)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new F0;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new Cp(o),r(o)}return n&&(this._currNode=i.finally=new Op,this.code(n)),this._endBlockNode(Cp,Op)}throw(e){return this._leafNode(new j0(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Fe.nil,n,i){return this._blockNode(new zp(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(zp)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Ta))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Me.CodeGen=V0;function za(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function qg(t,e){return e instanceof Fe._CodeOrName?za(t,e.names):t}function iu(t,e,r){if(t instanceof Fe.Name)return n(t);if(!i(t))return t;return new Fe._Code(t._items.reduce((o,s)=>(s instanceof Fe.Name&&(s=n(s)),s instanceof Fe._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof Fe._Code&&o._items.some(s=>s instanceof Fe.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function kV(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function yz(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Fe._)`!${q0(t)}`}Me.not=yz;var $V=_z(Me.operators.AND);function SV(...t){return t.reduce($V)}Me.and=SV;var IV=_z(Me.operators.OR);function EV(...t){return t.reduce(IV)}Me.or=EV;function _z(t){return(e,r)=>e===Fe.nil?r:r===Fe.nil?e:(0,Fe._)`${q0(e)} ${t} ${q0(r)}`}function q0(t){return t instanceof Fe.Name?t:(0,Fe._)`(${t})`}});var Xe=C(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.checkStrictMode=Ue.getErrorPath=Ue.Type=Ue.useFunc=Ue.setEvaluated=Ue.evaluatedPropsToName=Ue.mergeEvaluated=Ue.eachItem=Ue.unescapeJsonPointer=Ue.escapeJsonPointer=Ue.escapeFragment=Ue.unescapeFragment=Ue.schemaRefOrVal=Ue.schemaHasRulesButRef=Ue.schemaHasRules=Ue.checkUnknownRules=Ue.alwaysValidSchema=Ue.toHash=void 0;var ut=Le(),PV=Tp();function TV(t){let e={};for(let r of t)e[r]=!0;return e}Ue.toHash=TV;function AV(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(wz(t,e),!xz(e,t.self.RULES.all))}Ue.alwaysValidSchema=AV;function wz(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||Sz(t,`unknown keyword: "${o}"`)}Ue.checkUnknownRules=wz;function xz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}Ue.schemaHasRules=xz;function zV(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}Ue.schemaHasRulesButRef=zV;function NV({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ut._)`${r}`}return(0,ut._)`${t}${e}${(0,ut.getProperty)(n)}`}Ue.schemaRefOrVal=NV;function CV(t){return kz(decodeURIComponent(t))}Ue.unescapeFragment=CV;function OV(t){return encodeURIComponent(W0(t))}Ue.escapeFragment=OV;function W0(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}Ue.escapeJsonPointer=W0;function kz(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}Ue.unescapeJsonPointer=kz;function RV(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}Ue.eachItem=RV;function bz({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof ut.Name?(o instanceof ut.Name?t(i,o,s):e(i,o,s),s):o instanceof ut.Name?(e(i,s,o),o):r(o,s);return a===ut.Name&&!(c instanceof ut.Name)?n(i,c):c}}Ue.mergeEvaluated={props:bz({mergeNames:(t,e,r)=>t.if((0,ut._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ut._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ut._)`${r} || {}`).code((0,ut._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ut._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ut._)`${r} || {}`),G0(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$z}),items:bz({mergeNames:(t,e,r)=>t.if((0,ut._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ut._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ut._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ut._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $z(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ut._)`{}`);return e!==void 0&&G0(t,r,e),r}Ue.evaluatedPropsToName=$z;function G0(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ut._)`${e}${(0,ut.getProperty)(n)}`,!0))}Ue.setEvaluated=G0;var vz={};function MV(t,e){return t.scopeValue("func",{ref:e,code:vz[e.code]||(vz[e.code]=new PV._Code(e.code))})}Ue.useFunc=MV;var B0;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(B0||(Ue.Type=B0={}));function jV(t,e,r){if(t instanceof ut.Name){let n=e===B0.Num;return r?n?(0,ut._)`"[" + ${t} + "]"`:(0,ut._)`"['" + ${t} + "']"`:n?(0,ut._)`"/" + ${t}`:(0,ut._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ut.getProperty)(t).toString():"/"+W0(t)}Ue.getErrorPath=jV;function Sz(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}Ue.checkStrictMode=Sz});var bo=C(H0=>{"use strict";Object.defineProperty(H0,"__esModule",{value:!0});var xr=Le(),DV={data:new xr.Name("data"),valCxt:new xr.Name("valCxt"),instancePath:new xr.Name("instancePath"),parentData:new xr.Name("parentData"),parentDataProperty:new xr.Name("parentDataProperty"),rootData:new xr.Name("rootData"),dynamicAnchors:new xr.Name("dynamicAnchors"),vErrors:new xr.Name("vErrors"),errors:new xr.Name("errors"),this:new xr.Name("this"),self:new xr.Name("self"),scope:new xr.Name("scope"),json:new xr.Name("json"),jsonPos:new xr.Name("jsonPos"),jsonLen:new xr.Name("jsonLen"),jsonPart:new xr.Name("jsonPart")};H0.default=DV});var Rp=C(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.extendErrors=kr.resetErrorsCount=kr.reportExtraError=kr.reportError=kr.keyword$DataError=kr.keywordError=void 0;var Be=Le(),Wg=Xe(),Cr=bo();kr.keywordError={message:({keyword:t})=>(0,Be.str)`must pass "${t}" keyword validation`};kr.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Be.str)`"${t}" keyword must be ${e} ($data)`:(0,Be.str)`"${t}" keyword is invalid ($data)`};function LV(t,e=kr.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,c=Pz(t,e,r);n??(s||a)?Iz(o,c):Ez(i,(0,Be._)`[${c}]`)}kr.reportError=LV;function UV(t,e=kr.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=Pz(t,e,r);Iz(i,a),o||s||Ez(n,Cr.default.vErrors)}kr.reportExtraError=UV;function ZV(t,e){t.assign(Cr.default.errors,e),t.if((0,Be._)`${Cr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Be._)`${Cr.default.vErrors}.length`,e),()=>t.assign(Cr.default.vErrors,null)))}kr.resetErrorsCount=ZV;function FV({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Cr.default.errors,a=>{t.const(s,(0,Be._)`${Cr.default.vErrors}[${a}]`),t.if((0,Be._)`${s}.instancePath === undefined`,()=>t.assign((0,Be._)`${s}.instancePath`,(0,Be.strConcat)(Cr.default.instancePath,o.errorPath))),t.assign((0,Be._)`${s}.schemaPath`,(0,Be.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,Be._)`${s}.schema`,r),t.assign((0,Be._)`${s}.data`,n))})}kr.extendErrors=FV;function Iz(t,e){let r=t.const("err",e);t.if((0,Be._)`${Cr.default.vErrors} === null`,()=>t.assign(Cr.default.vErrors,(0,Be._)`[${r}]`),(0,Be._)`${Cr.default.vErrors}.push(${r})`),t.code((0,Be._)`${Cr.default.errors}++`)}function Ez(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,Be._)`new ${t.ValidationError}(${e})`):(r.assign((0,Be._)`${n}.errors`,e),r.return(!1))}var Na={keyword:new Be.Name("keyword"),schemaPath:new Be.Name("schemaPath"),params:new Be.Name("params"),propertyName:new Be.Name("propertyName"),message:new Be.Name("message"),schema:new Be.Name("schema"),parentSchema:new Be.Name("parentSchema")};function Pz(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Be._)`{}`:VV(t,e,r)}function VV(t,e,r={}){let{gen:n,it:i}=t,o=[qV(i,r),BV(t,r)];return WV(t,e,o),n.object(...o)}function qV({errorPath:t},{instancePath:e}){let r=e?(0,Be.str)`${t}${(0,Wg.getErrorPath)(e,Wg.Type.Str)}`:t;return[Cr.default.instancePath,(0,Be.strConcat)(Cr.default.instancePath,r)]}function BV({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,Be.str)`${e}/${t}`;return r&&(i=(0,Be.str)`${i}${(0,Wg.getErrorPath)(r,Wg.Type.Str)}`),[Na.schemaPath,i]}function WV(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Na.keyword,i],[Na.params,typeof e=="function"?e(t):e||(0,Be._)`{}`]),c.messages&&n.push([Na.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Na.schema,s],[Na.parentSchema,(0,Be._)`${u}${d}`],[Cr.default.data,o]),l&&n.push([Na.propertyName,l])}});var Az=C(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.boolOrEmptySchema=ou.topBoolOrEmptySchema=void 0;var GV=Rp(),HV=Le(),XV=bo(),KV={message:"boolean schema is false"};function JV(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Tz(t,!1):typeof r=="object"&&r.$async===!0?e.return(XV.default.data):(e.assign((0,HV._)`${n}.errors`,null),e.return(!0))}ou.topBoolOrEmptySchema=JV;function YV(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Tz(t)):r.var(e,!0)}ou.boolOrEmptySchema=YV;function Tz(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,GV.reportError)(i,KV,void 0,e)}});var X0=C(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.getRules=su.isJSONType=void 0;var QV=["string","number","integer","boolean","null","object","array"],e9=new Set(QV);function t9(t){return typeof t=="string"&&e9.has(t)}su.isJSONType=t9;function r9(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}su.getRules=r9});var K0=C(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.shouldUseRule=fs.shouldUseGroup=fs.schemaHasRulesForType=void 0;function n9({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&zz(t,n)}fs.schemaHasRulesForType=n9;function zz(t,e){return e.rules.some(r=>Nz(t,r))}fs.shouldUseGroup=zz;function Nz(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}fs.shouldUseRule=Nz});var Mp=C($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.reportTypeError=$r.checkDataTypes=$r.checkDataType=$r.coerceAndCheckDataType=$r.getJSONTypes=$r.getSchemaTypes=$r.DataType=void 0;var i9=X0(),o9=K0(),s9=Rp(),ze=Le(),Cz=Xe(),au;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(au||($r.DataType=au={}));function a9(t){let e=Oz(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}$r.getSchemaTypes=a9;function Oz(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(i9.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}$r.getJSONTypes=Oz;function c9(t,e){let{gen:r,data:n,opts:i}=t,o=l9(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,o9.schemaHasRulesForType)(t,e[0]));if(s){let a=Y0(e,n,i.strictNumbers,au.Wrong);r.if(a,()=>{o.length?u9(t,e,o):Q0(t)})}return s}$r.coerceAndCheckDataType=c9;var Rz=new Set(["string","number","integer","boolean","null"]);function l9(t,e){return e?t.filter(r=>Rz.has(r)||e==="array"&&r==="array"):[]}function u9(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,ze._)`typeof ${i}`),a=n.let("coerced",(0,ze._)`undefined`);o.coerceTypes==="array"&&n.if((0,ze._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,ze._)`${i}[0]`).assign(s,(0,ze._)`typeof ${i}`).if(Y0(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,ze._)`${a} !== undefined`);for(let l of r)(Rz.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),Q0(t),n.endIf(),n.if((0,ze._)`${a} !== undefined`,()=>{n.assign(i,a),d9(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ze._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,ze._)`"" + ${i}`).elseIf((0,ze._)`${i} === null`).assign(a,(0,ze._)`""`);return;case"number":n.elseIf((0,ze._)`${s} == "boolean" || ${i} === null
3
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,ze._)`+${i}`);return;case"integer":n.elseIf((0,ze._)`${s} === "boolean" || ${i} === null
4
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,ze._)`+${i}`);return;case"boolean":n.elseIf((0,ze._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,ze._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ze._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ze._)`${s} === "string" || ${s} === "number"
5
+ || ${s} === "boolean" || ${i} === null`).assign(a,(0,ze._)`[${i}]`)}}}function d9({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ze._)`${e} !== undefined`,()=>t.assign((0,ze._)`${e}[${r}]`,n))}function J0(t,e,r,n=au.Correct){let i=n===au.Correct?ze.operators.EQ:ze.operators.NEQ,o;switch(t){case"null":return(0,ze._)`${e} ${i} null`;case"array":o=(0,ze._)`Array.isArray(${e})`;break;case"object":o=(0,ze._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,ze._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,ze._)`typeof ${e} ${i} ${t}`}return n===au.Correct?o:(0,ze.not)(o);function s(a=ze.nil){return(0,ze.and)((0,ze._)`typeof ${e} == "number"`,a,r?(0,ze._)`isFinite(${e})`:ze.nil)}}$r.checkDataType=J0;function Y0(t,e,r,n){if(t.length===1)return J0(t[0],e,r,n);let i,o=(0,Cz.toHash)(t);if(o.array&&o.object){let s=(0,ze._)`typeof ${e} != "object"`;i=o.null?s:(0,ze._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=ze.nil;o.number&&delete o.integer;for(let s in o)i=(0,ze.and)(i,J0(s,e,r,n));return i}$r.checkDataTypes=Y0;var p9={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ze._)`{type: ${t}}`:(0,ze._)`{type: ${e}}`};function Q0(t){let e=f9(t);(0,s9.reportError)(e,p9)}$r.reportTypeError=Q0;function f9(t){let{gen:e,data:r,schema:n}=t,i=(0,Cz.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var jz=C(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});Gg.assignDefaults=void 0;var cu=Le(),m9=Xe();function h9(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)Mz(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>Mz(t,o,i.default))}Gg.assignDefaults=h9;function Mz(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,cu._)`${o}${(0,cu.getProperty)(e)}`;if(i){(0,m9.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,cu._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,cu._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,cu._)`${a} = ${(0,cu.stringify)(r)}`)}});var Nn=C(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.validateUnion=st.validateArray=st.usePattern=st.callValidateCode=st.schemaProperties=st.allSchemaProperties=st.noPropertyInData=st.propertyInData=st.isOwnProperty=st.hasPropFunc=st.reportMissingProp=st.checkMissingProp=st.checkReportMissingProp=void 0;var gt=Le(),ek=Xe(),ms=bo(),g9=Xe();function y9(t,e){let{gen:r,data:n,it:i}=t;r.if(rk(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,gt._)`${e}`},!0),t.error()})}st.checkReportMissingProp=y9;function _9({gen:t,data:e,it:{opts:r}},n,i){return(0,gt.or)(...n.map(o=>(0,gt.and)(rk(t,e,o,r.ownProperties),(0,gt._)`${i} = ${o}`)))}st.checkMissingProp=_9;function b9(t,e){t.setParams({missingProperty:e},!0),t.error()}st.reportMissingProp=b9;function Dz(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,gt._)`Object.prototype.hasOwnProperty`})}st.hasPropFunc=Dz;function tk(t,e,r){return(0,gt._)`${Dz(t)}.call(${e}, ${r})`}st.isOwnProperty=tk;function v9(t,e,r,n){let i=(0,gt._)`${e}${(0,gt.getProperty)(r)} !== undefined`;return n?(0,gt._)`${i} && ${tk(t,e,r)}`:i}st.propertyInData=v9;function rk(t,e,r,n){let i=(0,gt._)`${e}${(0,gt.getProperty)(r)} === undefined`;return n?(0,gt.or)(i,(0,gt.not)(tk(t,e,r))):i}st.noPropertyInData=rk;function Lz(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}st.allSchemaProperties=Lz;function w9(t,e){return Lz(e).filter(r=>!(0,ek.alwaysValidSchema)(t,e[r]))}st.schemaProperties=w9;function x9({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,c,l){let u=l?(0,gt._)`${t}, ${e}, ${n}${i}`:e,d=[[ms.default.instancePath,(0,gt.strConcat)(ms.default.instancePath,o)],[ms.default.parentData,s.parentData],[ms.default.parentDataProperty,s.parentDataProperty],[ms.default.rootData,ms.default.rootData]];s.opts.dynamicRef&&d.push([ms.default.dynamicAnchors,ms.default.dynamicAnchors]);let f=(0,gt._)`${u}, ${r.object(...d)}`;return c!==gt.nil?(0,gt._)`${a}.call(${c}, ${f})`:(0,gt._)`${a}(${f})`}st.callValidateCode=x9;var k9=(0,gt._)`new RegExp`;function $9({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,gt._)`${i.code==="new RegExp"?k9:(0,g9.useFunc)(t,i)}(${r}, ${n})`})}st.usePattern=$9;function S9(t){let{gen:e,data:r,keyword:n,it:i}=t,o=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(o,!0),s(()=>e.break()),o;function s(a){let c=e.const("len",(0,gt._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ek.Type.Num},o),e.if((0,gt.not)(o),a)})}}st.validateArray=S9;function I9(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ek.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,gt._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,gt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}st.validateUnion=I9});var Fz=C(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.validateKeywordUsage=Ei.validSchemaType=Ei.funcKeywordCode=Ei.macroKeywordCode=void 0;var Or=Le(),Ca=bo(),E9=Nn(),P9=Rp();function T9(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),c=Zz(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:Or.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ei.macroKeywordCode=T9;function A9(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:c}=t;N9(c,e);let l=!a&&e.compile?e.compile.call(c.self,o,s,c):e.validate,u=Zz(n,i,l),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)m(),e.modifying&&Uz(t),g(()=>t.error());else{let y=e.async?p():h();e.modifying&&Uz(t),g(()=>z9(t,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>m((0,Or._)`await `),b=>n.assign(d,!1).if((0,Or._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Or._)`${b}.errors`),()=>n.throw(b))),y}function h(){let y=(0,Or._)`${u}.errors`;return n.assign(y,null),m(Or.nil),y}function m(y=e.async?(0,Or._)`await `:Or.nil){let b=c.opts.passContext?Ca.default.this:Ca.default.self,$=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Or._)`${y}${(0,E9.callValidateCode)(t,u,b,$)}`,e.modifying)}function g(y){var b;n.if((0,Or.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Ei.funcKeywordCode=A9;function Uz(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Or._)`${n.parentData}[${n.parentDataProperty}]`))}function z9(t,e){let{gen:r}=t;r.if((0,Or._)`Array.isArray(${e})`,()=>{r.assign(Ca.default.vErrors,(0,Or._)`${Ca.default.vErrors} === null ? ${e} : ${Ca.default.vErrors}.concat(${e})`).assign(Ca.default.errors,(0,Or._)`${Ca.default.vErrors}.length`),(0,P9.extendErrors)(t)},()=>t.error())}function N9({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Zz(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Or.stringify)(r)})}function C9(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ei.validSchemaType=C9;function O9({schema:t,opts:e,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ei.validateKeywordUsage=O9});var qz=C(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.extendSubschemaMode=hs.extendSubschemaData=hs.getSubschema=void 0;var Pi=Le(),Vz=Xe();function R9(t,{keyword:e,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Pi._)`${t.schemaPath}${(0,Pi.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Pi._)`${t.schemaPath}${(0,Pi.getProperty)(e)}${(0,Pi.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Vz.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}hs.getSubschema=R9;function M9(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,Pi._)`${e.data}${(0,Pi.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Pi.str)`${l}${(0,Vz.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Pi._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let l=i instanceof Pi.Name?i:a.let("data",i,!0);c(l),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}hs.extendSubschemaData=M9;function j9(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}hs.extendSubschemaMode=j9});var jp=C((Fve,Bz)=>{"use strict";Bz.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var nk=C((Vve,Wz)=>{"use strict";var gs=Wz.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Hg(e,n,i,t,"",t)};gs.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};gs.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};gs.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};gs.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Hg(t,e,r,n,i,o,s,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,o,s,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in gs.arrayKeywords)for(var f=0;f<d.length;f++)Hg(t,e,r,d[f],i+"/"+u+"/"+f,o,i,u,n,f)}else if(u in gs.propsKeywords){if(d&&typeof d=="object")for(var p in d)Hg(t,e,r,d[p],i+"/"+u+"/"+D9(p),o,i,u,n,p)}else(u in gs.keywords||t.allKeys&&!(u in gs.skipKeywords))&&Hg(t,e,r,d,i+"/"+u,o,i,u,n)}r(n,i,o,s,a,c,l)}}function D9(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Dp=C(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.getSchemaRefs=Hr.resolveUrl=Hr.normalizeId=Hr._getFullPath=Hr.getFullPath=Hr.inlineRef=void 0;var L9=Xe(),U9=jp(),Z9=nk(),F9=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function V9(t,e=!0){return typeof t=="boolean"?!0:e===!0?!ik(t):e?Gz(t)<=e:!1}Hr.inlineRef=V9;var q9=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ik(t){for(let e in t){if(q9.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(ik)||typeof r=="object"&&ik(r))return!0}return!1}function Gz(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!F9.has(r)&&(typeof t[r]=="object"&&(0,L9.eachItem)(t[r],n=>e+=Gz(n)),e===1/0))return 1/0}return e}function Hz(t,e="",r){r!==!1&&(e=lu(e));let n=t.parse(e);return Xz(t,n)}Hr.getFullPath=Hz;function Xz(t,e){return t.serialize(e).split("#")[0]+"#"}Hr._getFullPath=Xz;var B9=/#\/?$/;function lu(t){return t?t.replace(B9,""):""}Hr.normalizeId=lu;function W9(t,e,r){return r=lu(r),t.resolve(e,r)}Hr.resolveUrl=W9;var G9=/^[a-z_][-a-z0-9._]*$/i;function H9(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=lu(t[r]||e),o={"":i},s=Hz(n,i,!1),a={},c=new Set;return Z9(t,{allKeys:!0},(d,f,p,h)=>{if(h===void 0)return;let m=s+f,g=o[h];typeof d[r]=="string"&&(g=y.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[f]=g;function y($){let R=this.opts.uriResolver.resolve;if($=lu(g?R(g,$):$),c.has($))throw u($);c.add($);let T=this.refs[$];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?l(d,T.schema,$):$!==lu(m)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=m),$}function b($){if(typeof $=="string"){if(!G9.test($))throw new Error(`invalid anchor "${$}"`);y.call(this,`#${$}`)}}}),a;function l(d,f,p){if(f!==void 0&&!U9(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Hr.getSchemaRefs=H9});var Zp=C(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.getData=ys.KeywordCxt=ys.validateFunctionCode=void 0;var eN=Az(),Kz=Mp(),sk=K0(),Xg=Mp(),X9=jz(),Up=Fz(),ok=qz(),ie=Le(),xe=bo(),K9=Dp(),vo=Xe(),Lp=Rp();function J9(t){if(nN(t)&&(iN(t),rN(t))){e5(t);return}tN(t,()=>(0,eN.topBoolOrEmptySchema)(t))}ys.validateFunctionCode=J9;function tN({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,ie._)`${xe.default.data}, ${xe.default.valCxt}`,n.$async,()=>{t.code((0,ie._)`"use strict"; ${Jz(r,i)}`),Q9(t,i),t.code(o)}):t.func(e,(0,ie._)`${xe.default.data}, ${Y9(i)}`,n.$async,()=>t.code(Jz(r,i)).code(o))}function Y9(t){return(0,ie._)`{${xe.default.instancePath}="", ${xe.default.parentData}, ${xe.default.parentDataProperty}, ${xe.default.rootData}=${xe.default.data}${t.dynamicRef?(0,ie._)`, ${xe.default.dynamicAnchors}={}`:ie.nil}}={}`}function Q9(t,e){t.if(xe.default.valCxt,()=>{t.var(xe.default.instancePath,(0,ie._)`${xe.default.valCxt}.${xe.default.instancePath}`),t.var(xe.default.parentData,(0,ie._)`${xe.default.valCxt}.${xe.default.parentData}`),t.var(xe.default.parentDataProperty,(0,ie._)`${xe.default.valCxt}.${xe.default.parentDataProperty}`),t.var(xe.default.rootData,(0,ie._)`${xe.default.valCxt}.${xe.default.rootData}`),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,ie._)`${xe.default.valCxt}.${xe.default.dynamicAnchors}`)},()=>{t.var(xe.default.instancePath,(0,ie._)`""`),t.var(xe.default.parentData,(0,ie._)`undefined`),t.var(xe.default.parentDataProperty,(0,ie._)`undefined`),t.var(xe.default.rootData,xe.default.data),e.dynamicRef&&t.var(xe.default.dynamicAnchors,(0,ie._)`{}`)})}function e5(t){let{schema:e,opts:r,gen:n}=t;tN(t,()=>{r.$comment&&e.$comment&&sN(t),o5(t),n.let(xe.default.vErrors,null),n.let(xe.default.errors,0),r.unevaluated&&t5(t),oN(t),c5(t)})}function t5(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ie._)`${r}.evaluated`),e.if((0,ie._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ie._)`${t.evaluated}.props`,(0,ie._)`undefined`)),e.if((0,ie._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ie._)`${t.evaluated}.items`,(0,ie._)`undefined`))}function Jz(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ie._)`/*# sourceURL=${r} */`:ie.nil}function r5(t,e){if(nN(t)&&(iN(t),rN(t))){n5(t,e);return}(0,eN.boolOrEmptySchema)(t,e)}function rN({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function nN(t){return typeof t.schema!="boolean"}function n5(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&sN(t),s5(t),a5(t);let o=n.const("_errs",xe.default.errors);oN(t,o),n.var(e,(0,ie._)`${o} === ${xe.default.errors}`)}function iN(t){(0,vo.checkUnknownRules)(t),i5(t)}function oN(t,e){if(t.opts.jtd)return Yz(t,[],!1,e);let r=(0,Kz.getSchemaTypes)(t.schema),n=(0,Kz.coerceAndCheckDataType)(t,r);Yz(t,r,!n,e)}function i5(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,vo.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function o5(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,vo.checkStrictMode)(t,"default is ignored in the schema root")}function s5(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,K9.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function a5(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sN({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,ie._)`${xe.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,ie.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,ie._)`${xe.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function c5(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,ie._)`${xe.default.errors} === 0`,()=>e.return(xe.default.data),()=>e.throw((0,ie._)`new ${i}(${xe.default.vErrors})`)):(e.assign((0,ie._)`${n}.errors`,xe.default.vErrors),o.unevaluated&&l5(t),e.return((0,ie._)`${xe.default.errors} === 0`))}function l5({gen:t,evaluated:e,props:r,items:n}){r instanceof ie.Name&&t.assign((0,ie._)`${e}.props`,r),n instanceof ie.Name&&t.assign((0,ie._)`${e}.items`,n)}function Yz(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,vo.schemaHasRulesButRef)(o,u))){i.block(()=>cN(t,"$ref",u.all.$ref.definition));return}c.jtd||u5(t,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,sk.shouldUseGroup)(o,f)&&(f.type?(i.if((0,Xg.checkDataType)(f.type,s,c.strictNumbers)),Qz(t,f),e.length===1&&e[0]===f.type&&r&&(i.else(),(0,Xg.reportTypeError)(t)),i.endIf()):Qz(t,f),a||i.if((0,ie._)`${xe.default.errors} === ${n||0}`))}}function Qz(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,X9.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,sk.shouldUseRule)(n,o)&&cN(t,o.keyword,o.definition,e.type)})}function u5(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(d5(t,e),t.opts.allowUnionTypes||p5(t,e),f5(t,t.dataTypes))}function d5(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{aN(t.dataTypes,r)||ak(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),h5(t,e)}}function p5(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ak(t,"use allowUnionTypes to allow union type keyword")}function f5(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,sk.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>m5(e,s))&&ak(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function m5(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function aN(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function h5(t,e){let r=[];for(let n of t.dataTypes)aN(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ak(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,vo.checkStrictMode)(t,e,t.opts.strictTypes)}var Kg=class{constructor(e,r,n){if((0,Up.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,vo.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",lN(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Up.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",xe.default.errors))}result(e,r,n){this.failResult((0,ie.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ie.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,ie._)`${r} !== undefined && (${(0,ie.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Lp.reportExtraError:Lp.reportError)(this,this.def.error,r)}$dataError(){(0,Lp.reportError)(this,this.def.$dataError||Lp.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Lp.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=ie.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=ie.nil,r=ie.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,ie.or)((0,ie._)`${i} === undefined`,r)),e!==ie.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==ie.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,ie.or)(s(),a());function s(){if(n.length){if(!(r instanceof ie.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,ie._)`${(0,Xg.checkDataTypes)(c,r,o.opts.strictNumbers,Xg.DataType.Wrong)}`}return ie.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,ie._)`!${c}(${r})`}return ie.nil}}subschema(e,r){let n=(0,ok.getSubschema)(this.it,e);(0,ok.extendSubschemaData)(n,this.it,e),(0,ok.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return r5(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=vo.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=vo.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,ie.Name)),!0}};ys.KeywordCxt=Kg;function cN(t,e,r,n){let i=new Kg(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,Up.funcKeywordCode)(i,r):"macro"in r?(0,Up.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,Up.funcKeywordCode)(i,r)}var g5=/^\/(?:[^~]|~0|~1)*$/,y5=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lN(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return xe.default.rootData;if(t[0]==="/"){if(!g5.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=xe.default.rootData}else{let l=y5.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let l of a)l&&(o=(0,ie._)`${o}${(0,ie.getProperty)((0,vo.unescapeJsonPointer)(l))}`,s=(0,ie._)`${s} && ${o}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}ys.getData=lN});var Jg=C(lk=>{"use strict";Object.defineProperty(lk,"__esModule",{value:!0});var ck=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};lk.default=ck});var Fp=C(pk=>{"use strict";Object.defineProperty(pk,"__esModule",{value:!0});var uk=Dp(),dk=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,uk.resolveUrl)(e,r,n),this.missingSchema=(0,uk.normalizeId)((0,uk.getFullPath)(e,this.missingRef))}};pk.default=dk});var Qg=C(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.resolveSchema=Cn.getCompilingSchema=Cn.resolveRef=Cn.compileSchema=Cn.SchemaEnv=void 0;var ii=Le(),_5=Jg(),Oa=bo(),oi=Dp(),uN=Xe(),b5=Zp(),uu=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,oi.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Cn.SchemaEnv=uu;function mk(t){let e=dN.call(this,t);if(e)return e;let r=(0,oi.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new ii.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:_5.default,code:(0,ii._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Oa.default.data,parentData:Oa.default.parentData,parentDataProperty:Oa.default.parentDataProperty,dataNames:[Oa.default.data],dataPathArr:[ii.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ii.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ii.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ii._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,b5.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Oa.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Oa.default.self}`,`${Oa.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof ii.Name?void 0:h,items:m instanceof ii.Name?void 0:m,dynamicProps:h instanceof ii.Name,dynamicItems:m instanceof ii.Name},p.source&&(p.source.evaluated=(0,ii.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Cn.compileSchema=mk;function v5(t,e,r){var n;r=(0,oi.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=k5.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new uu({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=w5.call(this,o)}Cn.resolveRef=v5;function w5(t){return(0,oi.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:mk.call(this,t)}function dN(t){for(let e of this._compilations)if(x5(e,t))return e}Cn.getCompilingSchema=dN;function x5(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function k5(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Yg.call(this,t,e)}function Yg(t,e){let r=this.opts.uriResolver.parse(e),n=(0,oi._getFullPath)(this.opts.uriResolver,r),i=(0,oi.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return fk.call(this,r,t);let o=(0,oi.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Yg.call(this,t,s);return typeof a?.schema!="object"?void 0:fk.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||mk.call(this,s),o===(0,oi.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,oi.resolveUrl)(this.opts.uriResolver,i,l)),new uu({schema:a,schemaId:c,root:t,baseId:i})}return fk.call(this,r,s)}}Cn.resolveSchema=Yg;var $5=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function fk(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,uN.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!$5.has(a)&&l&&(e=(0,oi.resolveUrl)(this.opts.uriResolver,e,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,uN.schemaHasRulesButRef)(r,this.RULES)){let a=(0,oi.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Yg.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new uu({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var pN=C((Xve,S5)=>{S5.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var gk=C((Kve,gN)=>{"use strict";var I5=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mN=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function hk(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var E5=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fN(t){return t.length=0,!0}function P5(t,e,r){if(t.length){let n=hk(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function T5(t){let e=0,r={error:!1,address:"",zone:""},n=[],i=[],o=!1,s=!1,a=P5;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(o===!0&&(s=!0),!a(i,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,r))break;a=fN}else{i.push(l);continue}}return i.length&&(a===fN?r.zone=i.join(""):s?n.push(i.join("")):n.push(hk(i))),r.address=n.join(""),r}function hN(t){if(A5(t,":")<2)return{host:t,isIPV6:!1};let e=T5(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function A5(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function z5(t){let e=t,r=[],n=-1,i=0;for(;i=e.length;){if(i===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(i===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(i===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function N5(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function C5(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!mN(r)){let n=hN(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}gN.exports={nonSimpleDomain:E5,recomposeAuthority:C5,normalizeComponentEncoding:N5,removeDotSegments:z5,isIPv4:mN,isUUID:I5,normalizeIPv6:hN,stringArrayToHexStripped:hk}});var wN=C((Jve,vN)=>{"use strict";var{isUUID:O5}=gk(),R5=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,M5=["http","https","ws","wss","urn","urn:uuid"];function j5(t){return M5.indexOf(t)!==-1}function yk(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function yN(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function _N(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function D5(t){return t.secure=yk(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function L5(t){if((t.port===(yk(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function U5(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(R5);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let i=`${n}:${e.nid||t.nid}`,o=_k(i);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Z5(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),i=`${r}:${e.nid||n}`,o=_k(i);o&&(t=o.serialize(t,e));let s=t,a=t.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function F5(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!O5(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function V5(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var bN={scheme:"http",domainHost:!0,parse:yN,serialize:_N},q5={scheme:"https",domainHost:bN.domainHost,parse:yN,serialize:_N},ey={scheme:"ws",domainHost:!0,parse:D5,serialize:L5},B5={scheme:"wss",domainHost:ey.domainHost,parse:ey.parse,serialize:ey.serialize},W5={scheme:"urn",parse:U5,serialize:Z5,skipNormalize:!0},G5={scheme:"urn:uuid",parse:F5,serialize:V5,skipNormalize:!0},ty={http:bN,https:q5,ws:ey,wss:B5,urn:W5,"urn:uuid":G5};Object.setPrototypeOf(ty,null);function _k(t){return t&&(ty[t]||ty[t.toLowerCase()])||void 0}vN.exports={wsIsSecure:yk,SCHEMES:ty,isValidSchemeName:j5,getSchemeHandler:_k}});var $N=C((Yve,ny)=>{"use strict";var{normalizeIPv6:H5,removeDotSegments:Vp,recomposeAuthority:X5,normalizeComponentEncoding:ry,isIPv4:K5,nonSimpleDomain:J5}=gk(),{SCHEMES:Y5,getSchemeHandler:xN}=wN();function Q5(t,e){return typeof t=="string"?t=Ti(wo(t,e),e):typeof t=="object"&&(t=wo(Ti(t,e),e)),t}function eq(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=kN(wo(t,n),wo(e,n),n,!0);return n.skipEscape=!0,Ti(i,n)}function kN(t,e,r,n){let i={};return n||(t=wo(Ti(t,r),r),e=wo(Ti(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Vp(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Vp(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Vp(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?i.path="/"+e.path:t.path?i.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Vp(i.path)),i.query=e.query):(i.path=t.path,e.query!==void 0?i.query=e.query:i.query=t.query),i.userinfo=t.userinfo,i.host=t.host,i.port=t.port),i.scheme=t.scheme),i.fragment=e.fragment,i}function tq(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ti(ry(wo(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ti(ry(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ti(ry(wo(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ti(ry(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ti(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),i=[],o=xN(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let s=X5(r);if(s!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(s),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=Vp(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var rq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function wo(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(rq);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(K5(n.host)===!1){let c=H5(n.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=xN(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&i===!1&&J5(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var bk={SCHEMES:Y5,normalize:Q5,resolve:eq,resolveComponent:kN,equal:tq,serialize:Ti,parse:wo};ny.exports=bk;ny.exports.default=bk;ny.exports.fastUri=bk});var IN=C(vk=>{"use strict";Object.defineProperty(vk,"__esModule",{value:!0});var SN=$N();SN.code='require("ajv/dist/runtime/uri").default';vk.default=SN});var ON=C(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.CodeGen=pr.Name=pr.nil=pr.stringify=pr.str=pr._=pr.KeywordCxt=void 0;var nq=Zp();Object.defineProperty(pr,"KeywordCxt",{enumerable:!0,get:function(){return nq.KeywordCxt}});var du=Le();Object.defineProperty(pr,"_",{enumerable:!0,get:function(){return du._}});Object.defineProperty(pr,"str",{enumerable:!0,get:function(){return du.str}});Object.defineProperty(pr,"stringify",{enumerable:!0,get:function(){return du.stringify}});Object.defineProperty(pr,"nil",{enumerable:!0,get:function(){return du.nil}});Object.defineProperty(pr,"Name",{enumerable:!0,get:function(){return du.Name}});Object.defineProperty(pr,"CodeGen",{enumerable:!0,get:function(){return du.CodeGen}});var iq=Jg(),zN=Fp(),oq=X0(),qp=Qg(),sq=Le(),Bp=Dp(),iy=Mp(),xk=Xe(),EN=pN(),aq=IN(),NN=(t,e)=>new RegExp(t,e);NN.code="new RegExp";var cq=["removeAdditional","useDefaults","coerceTypes"],lq=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uq={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},dq={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},PN=200;function pq(t){var e,r,n,i,o,s,a,c,l,u,d,f,p,h,m,g,y,b,$,R,T,P,F,ce,te;let H=t.strict,_e=(e=t.code)===null||e===void 0?void 0:e.optimize,he=_e===!0||_e===void 0?1:_e||0,Y=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:NN,pe=(i=t.uriResolver)!==null&&i!==void 0?i:aq.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:H)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:H)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:H)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:H)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:H)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:he,regExp:Y}:{optimize:he,regExp:Y},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:PN,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:PN,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=t.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(F=t.validateFormats)!==null&&F!==void 0?F:!0,unicodeRegExp:(ce=t.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(te=t.int32range)!==null&&te!==void 0?te:!0,uriResolver:pe}}var Wp=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...pq(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new sq.ValueScope({scope:{},prefixes:lq,es5:r,lines:n}),this.logger=_q(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,oq.getRules)(),TN.call(this,uq,e,"NOT SUPPORTED"),TN.call(this,dq,e,"DEPRECATED","warn"),this._metaOpts=gq.call(this),e.formats&&mq.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&hq.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),fq.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=EN;n==="id"&&(i={...EN},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,r);async function i(u,d){await o.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof zN.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Bp.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(e){let r;for(;typeof(r=AN.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new qp.SchemaEnv({schema:{},schemaId:n});if(r=qp.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=AN.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Bp.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(vq.call(this,n,r),!r)return(0,xk.eachItem)(n,o=>wk.call(this,o)),this;xq.call(this,r);let i={...r,type:(0,iy.getJSONTypes)(r.type),schemaType:(0,iy.getJSONTypes)(r.schemaType)};return(0,xk.eachItem)(n,i.type.length===0?o=>wk.call(this,o,i):o=>i.type.forEach(s=>wk.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=CN(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Bp.normalizeId)(s||n);let l=Bp.getSchemaRefs.call(this,e,n);return c=new qp.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):qp.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{qp.compileSchema.call(this,e)}finally{this.opts=r}}};Wp.ValidationError=iq.default;Wp.MissingRefError=zN.default;pr.default=Wp;function TN(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function AN(t){return t=(0,Bp.normalizeId)(t),this.schemas[t]||this.refs[t]}function fq(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function mq(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function hq(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function gq(){let t={...this.opts};for(let e of cq)delete t[e];return t}var yq={log(){},warn(){},error(){}};function _q(t){if(t===!1)return yq;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var bq=/^[a-z_$][a-z0-9_$:-]*$/i;function vq(t,e){let{RULES:r}=this;if((0,xk.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!bq.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function wk(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,iy.getJSONTypes)(e.type),schemaType:(0,iy.getJSONTypes)(e.schemaType)}};e.before?wq.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function wq(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function xq(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=CN(e)),t.validateSchema=this.compile(e,!0))}var kq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function CN(t){return{anyOf:[t,kq]}}});var RN=C(kk=>{"use strict";Object.defineProperty(kk,"__esModule",{value:!0});var $q={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};kk.default=$q});var LN=C(Ra=>{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.callRef=Ra.getValidate=void 0;var Sq=Fp(),MN=Nn(),Xr=Le(),pu=bo(),jN=Qg(),oy=Xe(),Iq={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&i===l.baseId)return d();let u=jN.resolveRef.call(c,l,i,r);if(u===void 0)throw new Sq.default(n.opts.uriResolver,i,r);if(u instanceof jN.SchemaEnv)return f(u);return p(u);function d(){if(o===l)return sy(t,s,o,o.$async);let h=e.scopeValue("root",{ref:l});return sy(t,(0,Xr._)`${h}.validate`,l,l.$async)}function f(h){let m=DN(t,h);sy(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Xr.stringify)(h)}:{ref:h}),g=e.name("valid"),y=t.subschema({schema:h,dataTypes:[],schemaPath:Xr.nil,topSchemaRef:m,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function DN(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Xr._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ra.getValidate=DN;function sy(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:c}=o,l=c.passContext?pu.default.this:Xr.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,Xr._)`await ${(0,MN.callValidateCode)(t,e,l)}`),p(e),s||i.assign(h,!0)},m=>{i.if((0,Xr._)`!(${m} instanceof ${o.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(h,!1)}),t.ok(h)}function d(){t.result((0,MN.callValidateCode)(t,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,Xr._)`${h}.errors`;i.assign(pu.default.vErrors,(0,Xr._)`${pu.default.vErrors} === null ? ${m} : ${pu.default.vErrors}.concat(${m})`),i.assign(pu.default.errors,(0,Xr._)`${pu.default.vErrors}.length`)}function p(h){var m;if(!o.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=oy.mergeEvaluated.props(i,g.props,o.props));else{let y=i.var("props",(0,Xr._)`${h}.evaluated.props`);o.props=oy.mergeEvaluated.props(i,y,o.props,Xr.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=oy.mergeEvaluated.items(i,g.items,o.items));else{let y=i.var("items",(0,Xr._)`${h}.evaluated.items`);o.items=oy.mergeEvaluated.items(i,y,o.items,Xr.Name)}}}Ra.callRef=sy;Ra.default=Iq});var UN=C($k=>{"use strict";Object.defineProperty($k,"__esModule",{value:!0});var Eq=RN(),Pq=LN(),Tq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Eq.default,Pq.default];$k.default=Tq});var ZN=C(Sk=>{"use strict";Object.defineProperty(Sk,"__esModule",{value:!0});var ay=Le(),_s=ay.operators,cy={maximum:{okStr:"<=",ok:_s.LTE,fail:_s.GT},minimum:{okStr:">=",ok:_s.GTE,fail:_s.LT},exclusiveMaximum:{okStr:"<",ok:_s.LT,fail:_s.GTE},exclusiveMinimum:{okStr:">",ok:_s.GT,fail:_s.LTE}},Aq={message:({keyword:t,schemaCode:e})=>(0,ay.str)`must be ${cy[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ay._)`{comparison: ${cy[t].okStr}, limit: ${e}}`},zq={keyword:Object.keys(cy),type:"number",schemaType:"number",$data:!0,error:Aq,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ay._)`${r} ${cy[e].fail} ${n} || isNaN(${r})`)}};Sk.default=zq});var FN=C(Ik=>{"use strict";Object.defineProperty(Ik,"__esModule",{value:!0});var Gp=Le(),Nq={message:({schemaCode:t})=>(0,Gp.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Gp._)`{multipleOf: ${t}}`},Cq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Nq,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,Gp._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Gp._)`${s} !== parseInt(${s})`;t.fail$data((0,Gp._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ik.default=Cq});var qN=C(Ek=>{"use strict";Object.defineProperty(Ek,"__esModule",{value:!0});function VN(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}Ek.default=VN;VN.code='require("ajv/dist/runtime/ucs2length").default'});var BN=C(Pk=>{"use strict";Object.defineProperty(Pk,"__esModule",{value:!0});var Ma=Le(),Oq=Xe(),Rq=qN(),Mq={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ma.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ma._)`{limit: ${t}}`},jq={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Mq,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Ma.operators.GT:Ma.operators.LT,s=i.opts.unicode===!1?(0,Ma._)`${r}.length`:(0,Ma._)`${(0,Oq.useFunc)(t.gen,Rq.default)}(${r})`;t.fail$data((0,Ma._)`${s} ${o} ${n}`)}};Pk.default=jq});var WN=C(Tk=>{"use strict";Object.defineProperty(Tk,"__esModule",{value:!0});var Dq=Nn(),ly=Le(),Lq={message:({schemaCode:t})=>(0,ly.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ly._)`{pattern: ${t}}`},Uq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Lq,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,ly._)`(new RegExp(${i}, ${s}))`:(0,Dq.usePattern)(t,n);t.fail$data((0,ly._)`!${a}.test(${e})`)}};Tk.default=Uq});var GN=C(Ak=>{"use strict";Object.defineProperty(Ak,"__esModule",{value:!0});var Hp=Le(),Zq={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Hp.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Hp._)`{limit: ${t}}`},Fq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Zq,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?Hp.operators.GT:Hp.operators.LT;t.fail$data((0,Hp._)`Object.keys(${r}).length ${i} ${n}`)}};Ak.default=Fq});var HN=C(zk=>{"use strict";Object.defineProperty(zk,"__esModule",{value:!0});var Xp=Nn(),Kp=Le(),Vq=Xe(),qq={message:({params:{missingProperty:t}})=>(0,Kp.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Kp._)`{missingProperty: ${t}}`},Bq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qq,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,Vq.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||o)t.block$data(Kp.nil,d);else for(let p of r)(0,Xp.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||o){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,Xp.checkMissingProp)(t,r,p)),(0,Xp.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,Xp.noPropertyInData)(e,i,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,Xp.propertyInData)(e,i,p,a.ownProperties)),e.if((0,Kp.not)(h),()=>{t.error(),e.break()})},Kp.nil)}}};zk.default=Bq});var XN=C(Nk=>{"use strict";Object.defineProperty(Nk,"__esModule",{value:!0});var Jp=Le(),Wq={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Jp.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Jp._)`{limit: ${t}}`},Gq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Wq,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?Jp.operators.GT:Jp.operators.LT;t.fail$data((0,Jp._)`${r}.length ${i} ${n}`)}};Nk.default=Gq});var uy=C(Ck=>{"use strict";Object.defineProperty(Ck,"__esModule",{value:!0});var KN=jp();KN.code='require("ajv/dist/runtime/equal").default';Ck.default=KN});var JN=C(Rk=>{"use strict";Object.defineProperty(Rk,"__esModule",{value:!0});var Ok=Mp(),fr=Le(),Hq=Xe(),Xq=uy(),Kq={message:({params:{i:t,j:e}})=>(0,fr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,fr._)`{i: ${t}, j: ${e}}`},Jq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Kq,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let c=e.let("valid"),l=o.items?(0,Ok.getSchemaTypes)(o.items):[];t.block$data(c,u,(0,fr._)`${s} === false`),t.ok(c);function u(){let h=e.let("i",(0,fr._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,fr._)`${h} > 1`,()=>(d()?f:p)(h,m))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let g=e.name("item"),y=(0,Ok.checkDataTypes)(l,g,a.opts.strictNumbers,Ok.DataType.Wrong),b=e.const("indices",(0,fr._)`{}`);e.for((0,fr._)`;${h}--;`,()=>{e.let(g,(0,fr._)`${r}[${h}]`),e.if(y,(0,fr._)`continue`),l.length>1&&e.if((0,fr._)`typeof ${g} == "string"`,(0,fr._)`${g} += "_"`),e.if((0,fr._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(m,(0,fr._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,fr._)`${b}[${g}] = ${h}`)})}function p(h,m){let g=(0,Hq.useFunc)(e,Xq.default),y=e.name("outer");e.label(y).for((0,fr._)`;${h}--;`,()=>e.for((0,fr._)`${m} = ${h}; ${m}--;`,()=>e.if((0,fr._)`${g}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Rk.default=Jq});var YN=C(jk=>{"use strict";Object.defineProperty(jk,"__esModule",{value:!0});var Mk=Le(),Yq=Xe(),Qq=uy(),e3={message:"must be equal to constant",params:({schemaCode:t})=>(0,Mk._)`{allowedValue: ${t}}`},t3={keyword:"const",$data:!0,error:e3,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Mk._)`!${(0,Yq.useFunc)(e,Qq.default)}(${r}, ${i})`):t.fail((0,Mk._)`${o} !== ${r}`)}};jk.default=t3});var QN=C(Dk=>{"use strict";Object.defineProperty(Dk,"__esModule",{value:!0});var Yp=Le(),r3=Xe(),n3=uy(),i3={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Yp._)`{allowedValues: ${t}}`},o3={keyword:"enum",schemaType:"array",$data:!0,error:i3,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,r3.useFunc)(e,n3.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",o);u=(0,Yp.or)(...i.map((h,m)=>f(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,p=>e.if((0,Yp._)`${l()}(${r}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,Yp._)`${l()}(${r}, ${p}[${h}])`:(0,Yp._)`${r} === ${m}`}}};Dk.default=o3});var eC=C(Lk=>{"use strict";Object.defineProperty(Lk,"__esModule",{value:!0});var s3=ZN(),a3=FN(),c3=BN(),l3=WN(),u3=GN(),d3=HN(),p3=XN(),f3=JN(),m3=YN(),h3=QN(),g3=[s3.default,a3.default,c3.default,l3.default,u3.default,d3.default,p3.default,f3.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},m3.default,h3.default];Lk.default=g3});var Zk=C(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.validateAdditionalItems=void 0;var ja=Le(),Uk=Xe(),y3={message:({params:{len:t}})=>(0,ja.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ja._)`{limit: ${t}}`},_3={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:y3,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Uk.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}tC(t,n)}};function tC(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,ja._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ja._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Uk.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,ja._)`${a} <= ${e.length}`);r.if((0,ja.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:Uk.Type.Num},l),s.allErrors||r.if((0,ja.not)(l),()=>r.break())})}}Qp.validateAdditionalItems=tC;Qp.default=_3});var Fk=C(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});ef.validateTuple=void 0;var rC=Le(),dy=Xe(),b3=Nn(),v3={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return nC(t,"additionalItems",e);r.items=!0,!(0,dy.alwaysValidSchema)(r,e)&&t.ok((0,b3.validateArray)(t))}};function nC(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=dy.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,rC._)`${o}.length`);r.forEach((d,f)=>{(0,dy.alwaysValidSchema)(a,d)||(n.if((0,rC._)`${l} > ${f}`,()=>t.subschema({keyword:s,schemaProp:f,dataProp:f},c)),t.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let g=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,dy.checkStrictMode)(a,g,f.strictTuples)}}}ef.validateTuple=nC;ef.default=v3});var iC=C(Vk=>{"use strict";Object.defineProperty(Vk,"__esModule",{value:!0});var w3=Fk(),x3={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,w3.validateTuple)(t,"items")};Vk.default=x3});var sC=C(qk=>{"use strict";Object.defineProperty(qk,"__esModule",{value:!0});var oC=Le(),k3=Xe(),$3=Nn(),S3=Zk(),I3={message:({params:{len:t}})=>(0,oC.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,oC._)`{limit: ${t}}`},E3={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:I3,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,k3.alwaysValidSchema)(n,e)&&(i?(0,S3.validateAdditionalItems)(t,i):t.ok((0,$3.validateArray)(t)))}};qk.default=E3});var aC=C(Bk=>{"use strict";Object.defineProperty(Bk,"__esModule",{value:!0});var On=Le(),py=Xe(),P3={message:({params:{min:t,max:e}})=>e===void 0?(0,On.str)`must contain at least ${t} valid item(s)`:(0,On.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,On._)`{minContains: ${t}}`:(0,On._)`{minContains: ${t}, maxContains: ${e}}`},T3={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:P3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:c,maxContains:l}=n;o.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,On._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,py.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,py.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,py.alwaysValidSchema)(o,r)){let m=(0,On._)`${u} >= ${s}`;a!==void 0&&(m=(0,On._)`${m} && ${u} <= ${a}`),t.pass(m);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,On._)`${i}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>h(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:py.Type.Num,compositeRule:!0},m),g()})}function h(m){e.code((0,On._)`${m}++`),a===void 0?e.if((0,On._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,On._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,On._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Bk.default=T3});var uC=C(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.validateSchemaDeps=Ai.validatePropertyDeps=Ai.error=void 0;var Wk=Le(),A3=Xe(),tf=Nn();Ai.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Wk.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Wk._)`{property: ${t},
6
+ missingProperty: ${n},
7
+ depsCount: ${e},
8
+ deps: ${r}}`};var z3={keyword:"dependencies",type:"object",schemaType:"object",error:Ai.error,code(t){let[e,r]=N3(t);cC(t,e),lC(t,r)}};function N3({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function cC(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,tf.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of a)(0,tf.checkReportMissingProp)(t,l)}):(r.if((0,Wk._)`${c} && (${(0,tf.checkMissingProp)(t,a,o)})`),(0,tf.reportMissingProp)(t,o),r.else())}}Ai.validatePropertyDeps=cC;function lC(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,A3.alwaysValidSchema)(o,e[a])||(r.if((0,tf.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}Ai.validateSchemaDeps=lC;Ai.default=z3});var pC=C(Gk=>{"use strict";Object.defineProperty(Gk,"__esModule",{value:!0});var dC=Le(),C3=Xe(),O3={message:"property name must be valid",params:({params:t})=>(0,dC._)`{propertyName: ${t.propertyName}}`},R3={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:O3,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,C3.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,dC.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};Gk.default=R3});var Xk=C(Hk=>{"use strict";Object.defineProperty(Hk,"__esModule",{value:!0});var fy=Nn(),si=Le(),M3=bo(),my=Xe(),j3={message:"must NOT have additional properties",params:({params:t})=>(0,si._)`{additionalProperty: ${t.additionalProperty}}`},D3={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:j3,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,my.alwaysValidSchema)(s,r))return;let l=(0,fy.allSchemaProperties)(n.properties),u=(0,fy.allSchemaProperties)(n.patternProperties);d(),t.ok((0,si._)`${o} === ${M3.default.errors}`);function d(){e.forIn("key",i,g=>{!l.length&&!u.length?h(g):e.if(f(g),()=>h(g))})}function f(g){let y;if(l.length>8){let b=(0,my.schemaRefOrVal)(s,n.properties,"properties");y=(0,fy.isOwnProperty)(e,b,g)}else l.length?y=(0,si.or)(...l.map(b=>(0,si._)`${g} === ${b}`)):y=si.nil;return u.length&&(y=(0,si.or)(y,...u.map(b=>(0,si._)`${(0,fy.usePattern)(t,b)}.test(${g})`))),(0,si.not)(y)}function p(g){e.code((0,si._)`delete ${i}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,my.alwaysValidSchema)(s,r)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,si.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,si.not)(y),()=>e.break()))}}function m(g,y,b){let $={keyword:"additionalProperties",dataProp:g,dataPropType:my.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,y)}}};Hk.default=D3});var hC=C(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0});var L3=Zp(),fC=Nn(),Kk=Xe(),mC=Xk(),U3={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&mC.default.code(new L3.KeywordCxt(o,mC.default,"additionalProperties"));let s=(0,fC.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=Kk.mergeEvaluated.props(e,(0,Kk.toHash)(s),o.props));let a=s.filter(d=>!(0,Kk.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,fC.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Jk.default=U3});var bC=C(Yk=>{"use strict";Object.defineProperty(Yk,"__esModule",{value:!0});var gC=Nn(),hy=Le(),yC=Xe(),_C=Xe(),Z3={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,gC.allSchemaProperties)(r),c=a.filter(m=>(0,yC.alwaysValidSchema)(o,r[m]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof hy.Name)&&(o.props=(0,_C.evaluatedPropsToName)(e,o.props));let{props:d}=o;f();function f(){for(let m of a)l&&p(m),o.allErrors?h(m):(e.var(u,!0),h(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,yC.checkStrictMode)(o,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,g=>{e.if((0,hy._)`${(0,gC.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:_C.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,hy._)`${d}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,hy.not)(u),()=>e.break())})})}}};Yk.default=Z3});var vC=C(Qk=>{"use strict";Object.defineProperty(Qk,"__esModule",{value:!0});var F3=Xe(),V3={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,F3.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Qk.default=V3});var wC=C(e$=>{"use strict";Object.defineProperty(e$,"__esModule",{value:!0});var q3=Nn(),B3={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:q3.validateUnion,error:{message:"must match a schema in anyOf"}};e$.default=B3});var xC=C(t$=>{"use strict";Object.defineProperty(t$,"__esModule",{value:!0});var gy=Le(),W3=Xe(),G3={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gy._)`{passingSchemas: ${t.passing}}`},H3={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:G3,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){o.forEach((u,d)=>{let f;(0,W3.alwaysValidSchema)(i,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,gy._)`${c} && ${s}`).assign(s,!1).assign(a,(0,gy._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),f&&t.mergeEvaluated(f,gy.Name)})})}}};t$.default=H3});var kC=C(r$=>{"use strict";Object.defineProperty(r$,"__esModule",{value:!0});var X3=Xe(),K3={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,X3.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};r$.default=K3});var IC=C(n$=>{"use strict";Object.defineProperty(n$,"__esModule",{value:!0});var yy=Le(),SC=Xe(),J3={message:({params:t})=>(0,yy.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yy._)`{failingKeyword: ${t.ifClause}}`},Y3={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:J3,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,SC.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=$C(n,"then"),o=$C(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,yy.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let f=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(f,s),d?e.assign(d,(0,yy._)`${u}`):t.setParams({ifClause:u})}}}};function $C(t,e){let r=t.schema[e];return r!==void 0&&!(0,SC.alwaysValidSchema)(t,r)}n$.default=Y3});var EC=C(i$=>{"use strict";Object.defineProperty(i$,"__esModule",{value:!0});var Q3=Xe(),eB={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Q3.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};i$.default=eB});var PC=C(o$=>{"use strict";Object.defineProperty(o$,"__esModule",{value:!0});var tB=Zk(),rB=iC(),nB=Fk(),iB=sC(),oB=aC(),sB=uC(),aB=pC(),cB=Xk(),lB=hC(),uB=bC(),dB=vC(),pB=wC(),fB=xC(),mB=kC(),hB=IC(),gB=EC();function yB(t=!1){let e=[dB.default,pB.default,fB.default,mB.default,hB.default,gB.default,aB.default,cB.default,sB.default,lB.default,uB.default];return t?e.push(rB.default,iB.default):e.push(tB.default,nB.default),e.push(oB.default),e}o$.default=yB});var TC=C(s$=>{"use strict";Object.defineProperty(s$,"__esModule",{value:!0});var Rt=Le(),_B={message:({schemaCode:t})=>(0,Rt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Rt._)`{format: ${t}}`},bB={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:_B,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=r.const("fDef",(0,Rt._)`${h}[${s}]`),g=r.let("fType"),y=r.let("format");r.if((0,Rt._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,Rt._)`${m}.type || "string"`).assign(y,(0,Rt._)`${m}.validate`),()=>r.assign(g,(0,Rt._)`"string"`).assign(y,m)),t.fail$data((0,Rt.or)(b(),$()));function b(){return c.strictSchema===!1?Rt.nil:(0,Rt._)`${s} && !${y}`}function $(){let R=u.$async?(0,Rt._)`(${m}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Rt._)`${y}(${n})`,T=(0,Rt._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${n}))`;return(0,Rt._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function p(){let h=d.formats[o];if(!h){b();return}if(h===!0)return;let[m,g,y]=$(h);m===e&&t.pass(R());function b(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function $(T){let P=T instanceof RegExp?(0,Rt.regexpCode)(T):c.code.formats?(0,Rt._)`${c.code.formats}${(0,Rt.getProperty)(o)}`:void 0,F=r.scopeValue("formats",{key:o,ref:T,code:P});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Rt._)`${F}.validate`]:["string",T,F]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Rt._)`await ${y}(${n})`}return typeof g=="function"?(0,Rt._)`${y}(${n})`:(0,Rt._)`${y}.test(${n})`}}}};s$.default=bB});var AC=C(a$=>{"use strict";Object.defineProperty(a$,"__esModule",{value:!0});var vB=TC(),wB=[vB.default];a$.default=wB});var zC=C(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.contentVocabulary=fu.metadataVocabulary=void 0;fu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var CC=C(c$=>{"use strict";Object.defineProperty(c$,"__esModule",{value:!0});var xB=UN(),kB=eC(),$B=PC(),SB=AC(),NC=zC(),IB=[xB.default,kB.default,(0,$B.default)(),SB.default,NC.metadataVocabulary,NC.contentVocabulary];c$.default=IB});var RC=C(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});_y.DiscrError=void 0;var OC;(function(t){t.Tag="tag",t.Mapping="mapping"})(OC||(_y.DiscrError=OC={}))});var jC=C(u$=>{"use strict";Object.defineProperty(u$,"__esModule",{value:!0});var mu=Le(),l$=RC(),MC=Qg(),EB=Fp(),PB=Xe(),TB={message:({params:{discrError:t,tagName:e}})=>t===l$.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,mu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},AB={keyword:"discriminator",type:"object",schemaType:"object",error:TB,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,mu._)`${r}${(0,mu.getProperty)(a)}`);e.if((0,mu._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:l$.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,mu._)`${l} === ${h}`),e.assign(c,d(p[h]));e.else(),t.error(!1,{discrError:l$.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,mu.Name),h}function f(){var p;let h={},m=y(i),g=!0;for(let R=0;R<s.length;R++){let T=s[R];if(T?.$ref&&!(0,PB.schemaHasRulesButRef)(T,o.self.RULES)){let F=T.$ref;if(T=MC.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,F),T instanceof MC.SchemaEnv&&(T=T.schema),T===void 0)throw new EB.default(o.opts.uriResolver,o.baseId,F)}let P=(p=T?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(T)),b(P,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return h;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function b(R,T){if(R.const)$(R.const,T);else if(R.enum)for(let P of R.enum)$(P,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(R,T){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=T}}}};u$.default=AB});var DC=C((Uwe,zB)=>{zB.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var UC=C((yt,d$)=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.MissingRefError=yt.ValidationError=yt.CodeGen=yt.Name=yt.nil=yt.stringify=yt.str=yt._=yt.KeywordCxt=yt.Ajv=void 0;var NB=ON(),CB=CC(),OB=jC(),LC=DC(),RB=["/properties"],by="http://json-schema.org/draft-07/schema",hu=class extends NB.default{_addVocabularies(){super._addVocabularies(),CB.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(OB.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(LC,RB):LC;this.addMetaSchema(e,by,!1),this.refs["http://json-schema.org/schema"]=by}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(by)?by:void 0)}};yt.Ajv=hu;d$.exports=yt=hu;d$.exports.Ajv=hu;Object.defineProperty(yt,"__esModule",{value:!0});yt.default=hu;var MB=Zp();Object.defineProperty(yt,"KeywordCxt",{enumerable:!0,get:function(){return MB.KeywordCxt}});var gu=Le();Object.defineProperty(yt,"_",{enumerable:!0,get:function(){return gu._}});Object.defineProperty(yt,"str",{enumerable:!0,get:function(){return gu.str}});Object.defineProperty(yt,"stringify",{enumerable:!0,get:function(){return gu.stringify}});Object.defineProperty(yt,"nil",{enumerable:!0,get:function(){return gu.nil}});Object.defineProperty(yt,"Name",{enumerable:!0,get:function(){return gu.Name}});Object.defineProperty(yt,"CodeGen",{enumerable:!0,get:function(){return gu.CodeGen}});var jB=Jg();Object.defineProperty(yt,"ValidationError",{enumerable:!0,get:function(){return jB.default}});var DB=Fp();Object.defineProperty(yt,"MissingRefError",{enumerable:!0,get:function(){return DB.default}})});var HC=C(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.formatNames=Ni.fastFormats=Ni.fullFormats=void 0;function zi(t,e){return{validate:t,compare:e}}Ni.fullFormats={date:zi(qC,h$),time:zi(f$(!0),g$),"date-time":zi(ZC(!0),WC),"iso-time":zi(f$(),BC),"iso-date-time":zi(ZC(),GC),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:qB,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:JB,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:BB,int32:{type:"number",validate:HB},int64:{type:"number",validate:XB},float:{type:"number",validate:VC},double:{type:"number",validate:VC},password:!0,binary:!0};Ni.fastFormats={...Ni.fullFormats,date:zi(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,h$),time:zi(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,g$),"date-time":zi(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,WC),"iso-time":zi(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,BC),"iso-date-time":zi(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,GC),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ni.formatNames=Object.keys(Ni.fullFormats);function LB(t){return t%4===0&&(t%100!==0||t%400===0)}var UB=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ZB=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qC(t){let e=UB.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&LB(r)?29:ZB[n])}function h$(t,e){if(t&&e)return t>e?1:t<e?-1:0}var p$=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function f$(t){return function(r){let n=p$.exec(r);if(!n)return!1;let i=+n[1],o=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(i<=23&&o<=59&&s<60)return!0;let d=o-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&s<61}}function g$(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function BC(t,e){if(!(t&&e))return;let r=p$.exec(t),n=p$.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var m$=/t|\s/i;function ZC(t){let e=f$(t);return function(n){let i=n.split(m$);return i.length===2&&qC(i[0])&&e(i[1])}}function WC(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function GC(t,e){if(!(t&&e))return;let[r,n]=t.split(m$),[i,o]=e.split(m$),s=h$(r,i);if(s!==void 0)return s||g$(n,o)}var FB=/\/|:/,VB=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function qB(t){return FB.test(t)&&VB.test(t)}var FC=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function BB(t){return FC.lastIndex=0,FC.test(t)}var WB=-(2**31),GB=2**31-1;function HB(t){return Number.isInteger(t)&&t<=GB&&t>=WB}function XB(t){return Number.isInteger(t)}function VC(){return!0}var KB=/[^\\]\\Z/;function JB(t){if(KB.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var of=C(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.regexpCode=Ke.getEsmExportName=Ke.getProperty=Ke.safeStringify=Ke.stringify=Ke.strConcat=Ke.addCodeArg=Ke.str=Ke._=Ke.nil=Ke._Code=Ke.Name=Ke.IDENTIFIER=Ke._CodeOrName=void 0;var rf=class{};Ke._CodeOrName=rf;Ke.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Da=class extends rf{constructor(e){if(super(),!Ke.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ke.Name=Da;var Rn=class extends rf{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Da&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ke._Code=Rn;Ke.nil=new Rn("");function XC(t,...e){let r=[t[0]],n=0;for(;n<e.length;)_$(r,e[n]),r.push(t[++n]);return new Rn(r)}Ke._=XC;var y$=new Rn("+");function KC(t,...e){let r=[nf(t[0])],n=0;for(;n<e.length;)r.push(y$),_$(r,e[n]),r.push(y$,nf(t[++n]));return YB(r),new Rn(r)}Ke.str=KC;function _$(t,e){e instanceof Rn?t.push(...e._items):e instanceof Da?t.push(e):t.push(tW(e))}Ke.addCodeArg=_$;function YB(t){let e=1;for(;e<t.length-1;){if(t[e]===y$){let r=QB(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function QB(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Da||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Da))return`"${t}${e.slice(1)}`}function eW(t,e){return e.emptyStr()?t:t.emptyStr()?e:KC`${t}${e}`}Ke.strConcat=eW;function tW(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:nf(Array.isArray(t)?t.join(","):t)}function rW(t){return new Rn(nf(t))}Ke.stringify=rW;function nf(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ke.safeStringify=nf;function nW(t){return typeof t=="string"&&Ke.IDENTIFIER.test(t)?new Rn(`.${t}`):XC`[${t}]`}Ke.getProperty=nW;function iW(t){if(typeof t=="string"&&Ke.IDENTIFIER.test(t))return new Rn(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Ke.getEsmExportName=iW;function oW(t){return new Rn(t.toString())}Ke.regexpCode=oW});var x$=C(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.ValueScope=Rr.ValueScopeName=Rr.Scope=Rr.varKinds=Rr.UsedValueState=void 0;var Kr=of(),b$=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},v$;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(v$=Rr.UsedValueState||(Rr.UsedValueState={}));Rr.varKinds={const:new Kr.Name("const"),let:new Kr.Name("let"),var:new Kr.Name("var")};var vy=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Kr.Name?e:this.name(e)}name(e){return new Kr.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Rr.Scope=vy;var wy=class extends Kr.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Kr._)`.${new Kr.Name(r)}[${n}]`}};Rr.ValueScopeName=wy;var sW=(0,Kr._)`\n`,w$=class extends vy{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sW:Kr.nil}}get(){return this._scope}name(e){return new wy(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let u=a.get(s);if(u)return u}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),l=c.length;return c[l]=r.ref,i.setValue(r,{property:o,itemIndex:l}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Kr._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=Kr.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,v$.Started);let u=r(l);if(u){let d=this.opts.es5?Rr.varKinds.var:Rr.varKinds.const;o=(0,Kr._)`${o}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))o=(0,Kr._)`${o}${u}${this.opts._n}`;else throw new b$(l);c.set(l,v$.Completed)})}return o}};Rr.ValueScope=w$});var Oe=C(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.or=je.and=je.not=je.CodeGen=je.operators=je.varKinds=je.ValueScopeName=je.ValueScope=je.Scope=je.Name=je.regexpCode=je.stringify=je.getProperty=je.nil=je.strConcat=je.str=je._=void 0;var Ve=of(),ai=x$(),bs=of();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return bs._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return bs.str}});Object.defineProperty(je,"strConcat",{enumerable:!0,get:function(){return bs.strConcat}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return bs.nil}});Object.defineProperty(je,"getProperty",{enumerable:!0,get:function(){return bs.getProperty}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return bs.stringify}});Object.defineProperty(je,"regexpCode",{enumerable:!0,get:function(){return bs.regexpCode}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return bs.Name}});var Sy=x$();Object.defineProperty(je,"Scope",{enumerable:!0,get:function(){return Sy.Scope}});Object.defineProperty(je,"ValueScope",{enumerable:!0,get:function(){return Sy.ValueScope}});Object.defineProperty(je,"ValueScopeName",{enumerable:!0,get:function(){return Sy.ValueScopeName}});Object.defineProperty(je,"varKinds",{enumerable:!0,get:function(){return Sy.varKinds}});je.operators={GT:new Ve._Code(">"),GTE:new Ve._Code(">="),LT:new Ve._Code("<"),LTE:new Ve._Code("<="),EQ:new Ve._Code("==="),NEQ:new Ve._Code("!=="),NOT:new Ve._Code("!"),OR:new Ve._Code("||"),AND:new Ve._Code("&&"),ADD:new Ve._Code("+")};var xo=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},k$=class extends xo{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ai.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=_u(this.rhs,e,r)),this}get names(){return this.rhs instanceof Ve._CodeOrName?this.rhs.names:{}}},xy=class extends xo{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Ve.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=_u(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Ve.Name?{}:{...this.lhs.names};return $y(e,this.rhs)}},$$=class extends xy{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},S$=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},I$=class extends xo{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},E$=class extends xo{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},P$=class extends xo{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=_u(this.code,e,r),this}get names(){return this.code instanceof Ve._CodeOrName?this.code.names:{}}},sf=class extends xo{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(aW(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Za(e,r.names),{})}},ko=class extends sf{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},T$=class extends sf{},yu=class extends ko{};yu.kind="else";var La=class t extends ko{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new yu(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(JC(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=_u(this.condition,e,r),this}get names(){let e=super.names;return $y(e,this.condition),this.else&&Za(e,this.else.names),e}};La.kind="if";var Ua=class extends ko{};Ua.kind="for";var A$=class extends Ua{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=_u(this.iteration,e,r),this}get names(){return Za(super.names,this.iteration.names)}},z$=class extends Ua{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?ai.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=$y(super.names,this.from);return $y(e,this.to)}},ky=class extends Ua{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=_u(this.iterable,e,r),this}get names(){return Za(super.names,this.iterable.names)}},af=class extends ko{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};af.kind="func";var cf=class extends sf{render(e){return"return "+super.render(e)}};cf.kind="return";var N$=class extends ko{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Za(e,this.catch.names),this.finally&&Za(e,this.finally.names),e}},lf=class extends ko{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};lf.kind="catch";var uf=class extends ko{render(e){return"finally"+super.render(e)}};uf.kind="finally";var C$=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
9
+ `:""},this._extScope=e,this._scope=new ai.Scope({parent:e}),this._nodes=[new T$]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new k$(e,o,n)),o}const(e,r,n){return this._def(ai.varKinds.const,e,r,n)}let(e,r,n){return this._def(ai.varKinds.let,e,r,n)}var(e,r,n){return this._def(ai.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new xy(e,r,n))}add(e,r){return this._leafNode(new $$(e,je.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Ve.nil&&this._leafNode(new P$(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Ve.addCodeArg)(r,i));return r.push("}"),new Ve._Code(r)}if(e,r,n){if(this._blockNode(new La(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new La(e))}else(){return this._elseNode(new yu)}endIf(){return this._endBlockNode(La,yu)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new A$(e),r)}forRange(e,r,n,i,o=this.opts.es5?ai.varKinds.var:ai.varKinds.let){let s=this._scope.toName(e);return this._for(new z$(o,s,r,n),()=>i(s))}forOf(e,r,n,i=ai.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof Ve.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Ve._)`${s}.length`,a=>{this.var(o,(0,Ve._)`${s}[${a}]`),n(o)})}return this._for(new ky("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?ai.varKinds.var:ai.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Ve._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new ky("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Ua)}label(e){return this._leafNode(new S$(e))}break(e){return this._leafNode(new I$(e))}return(e){let r=new cf;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(cf)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new N$;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new lf(o),r(o)}return n&&(this._currNode=i.finally=new uf,this.code(n)),this._endBlockNode(lf,uf)}throw(e){return this._leafNode(new E$(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Ve.nil,n,i){return this._blockNode(new af(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(af)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof La))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};je.CodeGen=C$;function Za(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function $y(t,e){return e instanceof Ve._CodeOrName?Za(t,e.names):t}function _u(t,e,r){if(t instanceof Ve.Name)return n(t);if(!i(t))return t;return new Ve._Code(t._items.reduce((o,s)=>(s instanceof Ve.Name&&(s=n(s)),s instanceof Ve._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof Ve._Code&&o._items.some(s=>s instanceof Ve.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function aW(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function JC(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Ve._)`!${O$(t)}`}je.not=JC;var cW=YC(je.operators.AND);function lW(...t){return t.reduce(cW)}je.and=lW;var uW=YC(je.operators.OR);function dW(...t){return t.reduce(uW)}je.or=dW;function YC(t){return(e,r)=>e===Ve.nil?r:r===Ve.nil?e:(0,Ve._)`${O$(e)} ${t} ${O$(r)}`}function O$(t){return t instanceof Ve.Name?t:(0,Ve._)`(${t})`}});var Je=C(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.checkStrictMode=De.getErrorPath=De.Type=De.useFunc=De.setEvaluated=De.evaluatedPropsToName=De.mergeEvaluated=De.eachItem=De.unescapeJsonPointer=De.escapeJsonPointer=De.escapeFragment=De.unescapeFragment=De.schemaRefOrVal=De.schemaHasRulesButRef=De.schemaHasRules=De.checkUnknownRules=De.alwaysValidSchema=De.toHash=void 0;var dt=Oe(),pW=of();function fW(t){let e={};for(let r of t)e[r]=!0;return e}De.toHash=fW;function mW(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(tO(t,e),!rO(e,t.self.RULES.all))}De.alwaysValidSchema=mW;function tO(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||sO(t,`unknown keyword: "${o}"`)}De.checkUnknownRules=tO;function rO(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}De.schemaHasRules=rO;function hW(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}De.schemaHasRulesButRef=hW;function gW({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,dt._)`${r}`}return(0,dt._)`${t}${e}${(0,dt.getProperty)(n)}`}De.schemaRefOrVal=gW;function yW(t){return nO(decodeURIComponent(t))}De.unescapeFragment=yW;function _W(t){return encodeURIComponent(R$(t))}De.escapeFragment=_W;function R$(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}De.escapeJsonPointer=R$;function nO(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}De.unescapeJsonPointer=nO;function bW(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}De.eachItem=bW;function QC({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof dt.Name?(o instanceof dt.Name?t(i,o,s):e(i,o,s),s):o instanceof dt.Name?(e(i,s,o),o):r(o,s);return a===dt.Name&&!(c instanceof dt.Name)?n(i,c):c}}De.mergeEvaluated={props:QC({mergeNames:(t,e,r)=>t.if((0,dt._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,dt._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,dt._)`${r} || {}`).code((0,dt._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,dt._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,dt._)`${r} || {}`),M$(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:iO}),items:QC({mergeNames:(t,e,r)=>t.if((0,dt._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,dt._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,dt._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,dt._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function iO(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,dt._)`{}`);return e!==void 0&&M$(t,r,e),r}De.evaluatedPropsToName=iO;function M$(t,e,r){Object.keys(r).forEach(n=>t.assign((0,dt._)`${e}${(0,dt.getProperty)(n)}`,!0))}De.setEvaluated=M$;var eO={};function vW(t,e){return t.scopeValue("func",{ref:e,code:eO[e.code]||(eO[e.code]=new pW._Code(e.code))})}De.useFunc=vW;var oO;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(oO=De.Type||(De.Type={}));function wW(t,e,r){if(t instanceof dt.Name){let n=e===oO.Num;return r?n?(0,dt._)`"[" + ${t} + "]"`:(0,dt._)`"['" + ${t} + "']"`:n?(0,dt._)`"/" + ${t}`:(0,dt._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,dt.getProperty)(t).toString():"/"+R$(t)}De.getErrorPath=wW;function sO(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}De.checkStrictMode=sO});var $o=C(j$=>{"use strict";Object.defineProperty(j$,"__esModule",{value:!0});var Sr=Oe(),xW={data:new Sr.Name("data"),valCxt:new Sr.Name("valCxt"),instancePath:new Sr.Name("instancePath"),parentData:new Sr.Name("parentData"),parentDataProperty:new Sr.Name("parentDataProperty"),rootData:new Sr.Name("rootData"),dynamicAnchors:new Sr.Name("dynamicAnchors"),vErrors:new Sr.Name("vErrors"),errors:new Sr.Name("errors"),this:new Sr.Name("this"),self:new Sr.Name("self"),scope:new Sr.Name("scope"),json:new Sr.Name("json"),jsonPos:new Sr.Name("jsonPos"),jsonLen:new Sr.Name("jsonLen"),jsonPart:new Sr.Name("jsonPart")};j$.default=xW});var df=C(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.extendErrors=Ir.resetErrorsCount=Ir.reportExtraError=Ir.reportError=Ir.keyword$DataError=Ir.keywordError=void 0;var We=Oe(),Iy=Je(),Mr=$o();Ir.keywordError={message:({keyword:t})=>(0,We.str)`must pass "${t}" keyword validation`};Ir.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,We.str)`"${t}" keyword must be ${e} ($data)`:(0,We.str)`"${t}" keyword is invalid ($data)`};function kW(t,e=Ir.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,c=lO(t,e,r);n??(s||a)?aO(o,c):cO(i,(0,We._)`[${c}]`)}Ir.reportError=kW;function $W(t,e=Ir.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=lO(t,e,r);aO(i,a),o||s||cO(n,Mr.default.vErrors)}Ir.reportExtraError=$W;function SW(t,e){t.assign(Mr.default.errors,e),t.if((0,We._)`${Mr.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,We._)`${Mr.default.vErrors}.length`,e),()=>t.assign(Mr.default.vErrors,null)))}Ir.resetErrorsCount=SW;function IW({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Mr.default.errors,a=>{t.const(s,(0,We._)`${Mr.default.vErrors}[${a}]`),t.if((0,We._)`${s}.instancePath === undefined`,()=>t.assign((0,We._)`${s}.instancePath`,(0,We.strConcat)(Mr.default.instancePath,o.errorPath))),t.assign((0,We._)`${s}.schemaPath`,(0,We.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,We._)`${s}.schema`,r),t.assign((0,We._)`${s}.data`,n))})}Ir.extendErrors=IW;function aO(t,e){let r=t.const("err",e);t.if((0,We._)`${Mr.default.vErrors} === null`,()=>t.assign(Mr.default.vErrors,(0,We._)`[${r}]`),(0,We._)`${Mr.default.vErrors}.push(${r})`),t.code((0,We._)`${Mr.default.errors}++`)}function cO(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,We._)`new ${t.ValidationError}(${e})`):(r.assign((0,We._)`${n}.errors`,e),r.return(!1))}var Fa={keyword:new We.Name("keyword"),schemaPath:new We.Name("schemaPath"),params:new We.Name("params"),propertyName:new We.Name("propertyName"),message:new We.Name("message"),schema:new We.Name("schema"),parentSchema:new We.Name("parentSchema")};function lO(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,We._)`{}`:EW(t,e,r)}function EW(t,e,r={}){let{gen:n,it:i}=t,o=[PW(i,r),TW(t,r)];return AW(t,e,o),n.object(...o)}function PW({errorPath:t},{instancePath:e}){let r=e?(0,We.str)`${t}${(0,Iy.getErrorPath)(e,Iy.Type.Str)}`:t;return[Mr.default.instancePath,(0,We.strConcat)(Mr.default.instancePath,r)]}function TW({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,We.str)`${e}/${t}`;return r&&(i=(0,We.str)`${i}${(0,Iy.getErrorPath)(r,Iy.Type.Str)}`),[Fa.schemaPath,i]}function AW(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([Fa.keyword,i],[Fa.params,typeof e=="function"?e(t):e||(0,We._)`{}`]),c.messages&&n.push([Fa.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Fa.schema,s],[Fa.parentSchema,(0,We._)`${u}${d}`],[Mr.default.data,o]),l&&n.push([Fa.propertyName,l])}});var dO=C(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.boolOrEmptySchema=bu.topBoolOrEmptySchema=void 0;var zW=df(),NW=Oe(),CW=$o(),OW={message:"boolean schema is false"};function RW(t){let{gen:e,schema:r,validateName:n}=t;r===!1?uO(t,!1):typeof r=="object"&&r.$async===!0?e.return(CW.default.data):(e.assign((0,NW._)`${n}.errors`,null),e.return(!0))}bu.topBoolOrEmptySchema=RW;function MW(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),uO(t)):r.var(e,!0)}bu.boolOrEmptySchema=MW;function uO(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,zW.reportError)(i,OW,void 0,e)}});var D$=C(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.getRules=vu.isJSONType=void 0;var jW=["string","number","integer","boolean","null","object","array"],DW=new Set(jW);function LW(t){return typeof t=="string"&&DW.has(t)}vu.isJSONType=LW;function UW(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vu.getRules=UW});var L$=C(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.shouldUseRule=vs.shouldUseGroup=vs.schemaHasRulesForType=void 0;function ZW({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&pO(t,n)}vs.schemaHasRulesForType=ZW;function pO(t,e){return e.rules.some(r=>fO(t,r))}vs.shouldUseGroup=pO;function fO(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}vs.shouldUseRule=fO});var ff=C(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.reportTypeError=mr.checkDataTypes=mr.checkDataType=mr.coerceAndCheckDataType=mr.getJSONTypes=mr.getSchemaTypes=mr.DataType=void 0;var FW=D$(),VW=L$(),qW=df(),Ne=Oe(),mO=Je(),pf;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(pf=mr.DataType||(mr.DataType={}));function BW(t){let e=hO(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}mr.getSchemaTypes=BW;function hO(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(FW.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}mr.getJSONTypes=hO;function WW(t,e){let{gen:r,data:n,opts:i}=t,o=GW(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,VW.schemaHasRulesForType)(t,e[0]));if(s){let a=Z$(e,n,i.strictNumbers,pf.Wrong);r.if(a,()=>{o.length?HW(t,e,o):F$(t)})}return s}mr.coerceAndCheckDataType=WW;var gO=new Set(["string","number","integer","boolean","null"]);function GW(t,e){return e?t.filter(r=>gO.has(r)||e==="array"&&r==="array"):[]}function HW(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,Ne._)`typeof ${i}`),a=n.let("coerced",(0,Ne._)`undefined`);o.coerceTypes==="array"&&n.if((0,Ne._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,Ne._)`${i}[0]`).assign(s,(0,Ne._)`typeof ${i}`).if(Z$(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,Ne._)`${a} !== undefined`);for(let l of r)(gO.has(l)||l==="array"&&o.coerceTypes==="array")&&c(l);n.else(),F$(t),n.endIf(),n.if((0,Ne._)`${a} !== undefined`,()=>{n.assign(i,a),XW(t,a)});function c(l){switch(l){case"string":n.elseIf((0,Ne._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,Ne._)`"" + ${i}`).elseIf((0,Ne._)`${i} === null`).assign(a,(0,Ne._)`""`);return;case"number":n.elseIf((0,Ne._)`${s} == "boolean" || ${i} === null
10
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,Ne._)`+${i}`);return;case"integer":n.elseIf((0,Ne._)`${s} === "boolean" || ${i} === null
11
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,Ne._)`+${i}`);return;case"boolean":n.elseIf((0,Ne._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,Ne._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Ne._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Ne._)`${s} === "string" || ${s} === "number"
12
+ || ${s} === "boolean" || ${i} === null`).assign(a,(0,Ne._)`[${i}]`)}}}function XW({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Ne._)`${e} !== undefined`,()=>t.assign((0,Ne._)`${e}[${r}]`,n))}function U$(t,e,r,n=pf.Correct){let i=n===pf.Correct?Ne.operators.EQ:Ne.operators.NEQ,o;switch(t){case"null":return(0,Ne._)`${e} ${i} null`;case"array":o=(0,Ne._)`Array.isArray(${e})`;break;case"object":o=(0,Ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,Ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,Ne._)`typeof ${e} ${i} ${t}`}return n===pf.Correct?o:(0,Ne.not)(o);function s(a=Ne.nil){return(0,Ne.and)((0,Ne._)`typeof ${e} == "number"`,a,r?(0,Ne._)`isFinite(${e})`:Ne.nil)}}mr.checkDataType=U$;function Z$(t,e,r,n){if(t.length===1)return U$(t[0],e,r,n);let i,o=(0,mO.toHash)(t);if(o.array&&o.object){let s=(0,Ne._)`typeof ${e} != "object"`;i=o.null?s:(0,Ne._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else i=Ne.nil;o.number&&delete o.integer;for(let s in o)i=(0,Ne.and)(i,U$(s,e,r,n));return i}mr.checkDataTypes=Z$;var KW={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Ne._)`{type: ${t}}`:(0,Ne._)`{type: ${e}}`};function F$(t){let e=JW(t);(0,qW.reportError)(e,KW)}mr.reportTypeError=F$;function JW(t){let{gen:e,data:r,schema:n}=t,i=(0,mO.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var _O=C(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});Ey.assignDefaults=void 0;var wu=Oe(),YW=Je();function QW(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)yO(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,o)=>yO(t,o,i.default))}Ey.assignDefaults=QW;function yO(t,e,r){let{gen:n,compositeRule:i,data:o,opts:s}=t;if(r===void 0)return;let a=(0,wu._)`${o}${(0,wu.getProperty)(e)}`;if(i){(0,YW.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,wu._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,wu._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,wu._)`${a} = ${(0,wu.stringify)(r)}`)}});var Mn=C(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.validateUnion=at.validateArray=at.usePattern=at.callValidateCode=at.schemaProperties=at.allSchemaProperties=at.noPropertyInData=at.propertyInData=at.isOwnProperty=at.hasPropFunc=at.reportMissingProp=at.checkMissingProp=at.checkReportMissingProp=void 0;var _t=Oe(),V$=Je(),ws=$o(),eG=Je();function tG(t,e){let{gen:r,data:n,it:i}=t;r.if(B$(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_t._)`${e}`},!0),t.error()})}at.checkReportMissingProp=tG;function rG({gen:t,data:e,it:{opts:r}},n,i){return(0,_t.or)(...n.map(o=>(0,_t.and)(B$(t,e,o,r.ownProperties),(0,_t._)`${i} = ${o}`)))}at.checkMissingProp=rG;function nG(t,e){t.setParams({missingProperty:e},!0),t.error()}at.reportMissingProp=nG;function bO(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_t._)`Object.prototype.hasOwnProperty`})}at.hasPropFunc=bO;function q$(t,e,r){return(0,_t._)`${bO(t)}.call(${e}, ${r})`}at.isOwnProperty=q$;function iG(t,e,r,n){let i=(0,_t._)`${e}${(0,_t.getProperty)(r)} !== undefined`;return n?(0,_t._)`${i} && ${q$(t,e,r)}`:i}at.propertyInData=iG;function B$(t,e,r,n){let i=(0,_t._)`${e}${(0,_t.getProperty)(r)} === undefined`;return n?(0,_t.or)(i,(0,_t.not)(q$(t,e,r))):i}at.noPropertyInData=B$;function vO(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}at.allSchemaProperties=vO;function oG(t,e){return vO(e).filter(r=>!(0,V$.alwaysValidSchema)(t,e[r]))}at.schemaProperties=oG;function sG({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},a,c,l){let u=l?(0,_t._)`${t}, ${e}, ${n}${i}`:e,d=[[ws.default.instancePath,(0,_t.strConcat)(ws.default.instancePath,o)],[ws.default.parentData,s.parentData],[ws.default.parentDataProperty,s.parentDataProperty],[ws.default.rootData,ws.default.rootData]];s.opts.dynamicRef&&d.push([ws.default.dynamicAnchors,ws.default.dynamicAnchors]);let f=(0,_t._)`${u}, ${r.object(...d)}`;return c!==_t.nil?(0,_t._)`${a}.call(${c}, ${f})`:(0,_t._)`${a}(${f})`}at.callValidateCode=sG;var aG=(0,_t._)`new RegExp`;function cG({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,o=i(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,_t._)`${i.code==="new RegExp"?aG:(0,eG.useFunc)(t,i)}(${r}, ${n})`})}at.usePattern=cG;function lG(t){let{gen:e,data:r,keyword:n,it:i}=t,o=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(o,!0),s(()=>e.break()),o;function s(a){let c=e.const("len",(0,_t._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:V$.Type.Num},o),e.if((0,_t.not)(o),a)})}}at.validateArray=lG;function uG(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,V$.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,_t._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,_t.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}at.validateUnion=uG});var kO=C(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.validateKeywordUsage=Ci.validSchemaType=Ci.funcKeywordCode=Ci.macroKeywordCode=void 0;var jr=Oe(),Va=$o(),dG=Mn(),pG=df();function fG(t,e){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=t,a=e.macro.call(s.self,i,o,s),c=xO(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:jr.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ci.macroKeywordCode=fG;function mG(t,e){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:a,it:c}=t;gG(c,e);let l=!a&&e.compile?e.compile.call(c.self,o,s,c):e.validate,u=xO(n,i,l),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)m(),e.modifying&&wO(t),g(()=>t.error());else{let y=e.async?p():h();e.modifying&&wO(t),g(()=>hG(t,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>m((0,jr._)`await `),b=>n.assign(d,!1).if((0,jr._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,jr._)`${b}.errors`),()=>n.throw(b))),y}function h(){let y=(0,jr._)`${u}.errors`;return n.assign(y,null),m(jr.nil),y}function m(y=e.async?(0,jr._)`await `:jr.nil){let b=c.opts.passContext?Va.default.this:Va.default.self,$=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,jr._)`${y}${(0,dG.callValidateCode)(t,u,b,$)}`,e.modifying)}function g(y){var b;n.if((0,jr.not)((b=e.valid)!==null&&b!==void 0?b:d),y)}}Ci.funcKeywordCode=mG;function wO(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,jr._)`${n.parentData}[${n.parentDataProperty}]`))}function hG(t,e){let{gen:r}=t;r.if((0,jr._)`Array.isArray(${e})`,()=>{r.assign(Va.default.vErrors,(0,jr._)`${Va.default.vErrors} === null ? ${e} : ${Va.default.vErrors}.concat(${e})`).assign(Va.default.errors,(0,jr._)`${Va.default.vErrors}.length`),(0,pG.extendErrors)(t)},()=>t.error())}function gG({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function xO(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,jr.stringify)(r)})}function yG(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ci.validSchemaType=yG;function _G({schema:t,opts:e,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ci.validateKeywordUsage=_G});var SO=C(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.extendSubschemaMode=xs.extendSubschemaData=xs.getSubschema=void 0;var Oi=Oe(),$O=Je();function bG(t,{keyword:e,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Oi._)`${t.schemaPath}${(0,Oi.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Oi._)`${t.schemaPath}${(0,Oi.getProperty)(e)}${(0,Oi.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$O.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}xs.getSubschema=bG;function vG(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,Oi._)`${e.data}${(0,Oi.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Oi.str)`${l}${(0,$O.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Oi._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(i!==void 0){let l=i instanceof Oi.Name?i:a.let("data",i,!0);c(l),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}xs.extendSubschemaData=vG;function wG(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}xs.extendSubschemaMode=wG});var mf=C(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.getSchemaRefs=Jr.resolveUrl=Jr.normalizeId=Jr._getFullPath=Jr.getFullPath=Jr.inlineRef=void 0;var xG=Je(),kG=jp(),$G=nk(),SG=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function IG(t,e=!0){return typeof t=="boolean"?!0:e===!0?!W$(t):e?IO(t)<=e:!1}Jr.inlineRef=IG;var EG=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function W$(t){for(let e in t){if(EG.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(W$)||typeof r=="object"&&W$(r))return!0}return!1}function IO(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!SG.has(r)&&(typeof t[r]=="object"&&(0,xG.eachItem)(t[r],n=>e+=IO(n)),e===1/0))return 1/0}return e}function EO(t,e="",r){r!==!1&&(e=xu(e));let n=t.parse(e);return PO(t,n)}Jr.getFullPath=EO;function PO(t,e){return t.serialize(e).split("#")[0]+"#"}Jr._getFullPath=PO;var PG=/#\/?$/;function xu(t){return t?t.replace(PG,""):""}Jr.normalizeId=xu;function TG(t,e,r){return r=xu(r),t.resolve(e,r)}Jr.resolveUrl=TG;var AG=/^[a-z_][-a-z0-9._]*$/i;function zG(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=xu(t[r]||e),o={"":i},s=EO(n,i,!1),a={},c=new Set;return $G(t,{allKeys:!0},(d,f,p,h)=>{if(h===void 0)return;let m=s+f,g=o[h];typeof d[r]=="string"&&(g=y.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[f]=g;function y($){let R=this.opts.uriResolver.resolve;if($=xu(g?R(g,$):$),c.has($))throw u($);c.add($);let T=this.refs[$];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?l(d,T.schema,$):$!==xu(m)&&($[0]==="#"?(l(d,a[$],$),a[$]=d):this.refs[$]=m),$}function b($){if(typeof $=="string"){if(!AG.test($))throw new Error(`invalid anchor "${$}"`);y.call(this,`#${$}`)}}}),a;function l(d,f,p){if(f!==void 0&&!kG(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Jr.getSchemaRefs=zG});var yf=C(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.getData=ks.KeywordCxt=ks.validateFunctionCode=void 0;var CO=dO(),TO=ff(),H$=L$(),Py=ff(),NG=_O(),gf=kO(),G$=SO(),oe=Oe(),ke=$o(),CG=mf(),So=Je(),hf=df();function OG(t){if(MO(t)&&(jO(t),RO(t))){jG(t);return}OO(t,()=>(0,CO.topBoolOrEmptySchema)(t))}ks.validateFunctionCode=OG;function OO({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},o){i.code.es5?t.func(e,(0,oe._)`${ke.default.data}, ${ke.default.valCxt}`,n.$async,()=>{t.code((0,oe._)`"use strict"; ${AO(r,i)}`),MG(t,i),t.code(o)}):t.func(e,(0,oe._)`${ke.default.data}, ${RG(i)}`,n.$async,()=>t.code(AO(r,i)).code(o))}function RG(t){return(0,oe._)`{${ke.default.instancePath}="", ${ke.default.parentData}, ${ke.default.parentDataProperty}, ${ke.default.rootData}=${ke.default.data}${t.dynamicRef?(0,oe._)`, ${ke.default.dynamicAnchors}={}`:oe.nil}}={}`}function MG(t,e){t.if(ke.default.valCxt,()=>{t.var(ke.default.instancePath,(0,oe._)`${ke.default.valCxt}.${ke.default.instancePath}`),t.var(ke.default.parentData,(0,oe._)`${ke.default.valCxt}.${ke.default.parentData}`),t.var(ke.default.parentDataProperty,(0,oe._)`${ke.default.valCxt}.${ke.default.parentDataProperty}`),t.var(ke.default.rootData,(0,oe._)`${ke.default.valCxt}.${ke.default.rootData}`),e.dynamicRef&&t.var(ke.default.dynamicAnchors,(0,oe._)`${ke.default.valCxt}.${ke.default.dynamicAnchors}`)},()=>{t.var(ke.default.instancePath,(0,oe._)`""`),t.var(ke.default.parentData,(0,oe._)`undefined`),t.var(ke.default.parentDataProperty,(0,oe._)`undefined`),t.var(ke.default.rootData,ke.default.data),e.dynamicRef&&t.var(ke.default.dynamicAnchors,(0,oe._)`{}`)})}function jG(t){let{schema:e,opts:r,gen:n}=t;OO(t,()=>{r.$comment&&e.$comment&&LO(t),FG(t),n.let(ke.default.vErrors,null),n.let(ke.default.errors,0),r.unevaluated&&DG(t),DO(t),BG(t)})}function DG(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,oe._)`${r}.evaluated`),e.if((0,oe._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,oe._)`${t.evaluated}.props`,(0,oe._)`undefined`)),e.if((0,oe._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,oe._)`${t.evaluated}.items`,(0,oe._)`undefined`))}function AO(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,oe._)`/*# sourceURL=${r} */`:oe.nil}function LG(t,e){if(MO(t)&&(jO(t),RO(t))){UG(t,e);return}(0,CO.boolOrEmptySchema)(t,e)}function RO({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function MO(t){return typeof t.schema!="boolean"}function UG(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&LO(t),VG(t),qG(t);let o=n.const("_errs",ke.default.errors);DO(t,o),n.var(e,(0,oe._)`${o} === ${ke.default.errors}`)}function jO(t){(0,So.checkUnknownRules)(t),ZG(t)}function DO(t,e){if(t.opts.jtd)return zO(t,[],!1,e);let r=(0,TO.getSchemaTypes)(t.schema),n=(0,TO.coerceAndCheckDataType)(t,r);zO(t,r,!n,e)}function ZG(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,So.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function FG(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,So.checkStrictMode)(t,"default is ignored in the schema root")}function VG(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,CG.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function qG(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function LO({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)t.code((0,oe._)`${ke.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,oe.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,oe._)`${ke.default.self}.opts.$comment(${o}, ${s}, ${a}.schema)`)}}function BG(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=t;r.$async?e.if((0,oe._)`${ke.default.errors} === 0`,()=>e.return(ke.default.data),()=>e.throw((0,oe._)`new ${i}(${ke.default.vErrors})`)):(e.assign((0,oe._)`${n}.errors`,ke.default.vErrors),o.unevaluated&&WG(t),e.return((0,oe._)`${ke.default.errors} === 0`))}function WG({gen:t,evaluated:e,props:r,items:n}){r instanceof oe.Name&&t.assign((0,oe._)`${e}.props`,r),n instanceof oe.Name&&t.assign((0,oe._)`${e}.items`,n)}function zO(t,e,r,n){let{gen:i,schema:o,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,So.schemaHasRulesButRef)(o,u))){i.block(()=>ZO(t,"$ref",u.all.$ref.definition));return}c.jtd||GG(t,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,H$.shouldUseGroup)(o,f)&&(f.type?(i.if((0,Py.checkDataType)(f.type,s,c.strictNumbers)),NO(t,f),e.length===1&&e[0]===f.type&&r&&(i.else(),(0,Py.reportTypeError)(t)),i.endIf()):NO(t,f),a||i.if((0,oe._)`${ke.default.errors} === ${n||0}`))}}function NO(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,NG.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,H$.shouldUseRule)(n,o)&&ZO(t,o.keyword,o.definition,e.type)})}function GG(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(HG(t,e),t.opts.allowUnionTypes||XG(t,e),KG(t,t.dataTypes))}function HG(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{UO(t.dataTypes,r)||X$(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),YG(t,e)}}function XG(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&X$(t,"use allowUnionTypes to allow union type keyword")}function KG(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,H$.shouldUseRule)(t.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>JG(e,s))&&X$(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function JG(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function UO(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function YG(t,e){let r=[];for(let n of t.dataTypes)UO(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function X$(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,So.checkStrictMode)(t,e,t.opts.strictTypes)}var Ty=class{constructor(e,r,n){if((0,gf.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,So.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",FO(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,gf.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ke.default.errors))}result(e,r,n){this.failResult((0,oe.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,oe.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,oe._)`${r} !== undefined && (${(0,oe.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?hf.reportExtraError:hf.reportError)(this,this.def.error,r)}$dataError(){(0,hf.reportError)(this,this.def.$dataError||hf.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,hf.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=oe.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=oe.nil,r=oe.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,oe.or)((0,oe._)`${i} === undefined`,r)),e!==oe.nil&&n.assign(e,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==oe.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,oe.or)(s(),a());function s(){if(n.length){if(!(r instanceof oe.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,oe._)`${(0,Py.checkDataTypes)(c,r,o.opts.strictNumbers,Py.DataType.Wrong)}`}return oe.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,oe._)`!${c}(${r})`}return oe.nil}}subschema(e,r){let n=(0,G$.getSubschema)(this.it,e);(0,G$.extendSubschemaData)(n,this.it,e),(0,G$.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return LG(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=So.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=So.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,oe.Name)),!0}};ks.KeywordCxt=Ty;function ZO(t,e,r,n){let i=new Ty(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,gf.funcKeywordCode)(i,r):"macro"in r?(0,gf.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,gf.funcKeywordCode)(i,r)}var QG=/^\/(?:[^~]|~0|~1)*$/,eH=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function FO(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,o;if(t==="")return ke.default.rootData;if(t[0]==="/"){if(!QG.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,o=ke.default.rootData}else{let l=eH.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(o=r[e-u],!i)return o}let s=o,a=i.split("/");for(let l of a)l&&(o=(0,oe._)`${o}${(0,oe.getProperty)((0,So.unescapeJsonPointer)(l))}`,s=(0,oe._)`${s} && ${o}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}ks.getData=FO});var Ay=C(J$=>{"use strict";Object.defineProperty(J$,"__esModule",{value:!0});var K$=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};J$.default=K$});var zy=C(eS=>{"use strict";Object.defineProperty(eS,"__esModule",{value:!0});var Y$=mf(),Q$=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Y$.resolveUrl)(e,r,n),this.missingSchema=(0,Y$.normalizeId)((0,Y$.getFullPath)(e,this.missingRef))}};eS.default=Q$});var Cy=C(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.resolveSchema=jn.getCompilingSchema=jn.resolveRef=jn.compileSchema=jn.SchemaEnv=void 0;var ci=Oe(),tH=Ay(),qa=$o(),li=mf(),VO=Je(),rH=yf(),ku=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,li.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};jn.SchemaEnv=ku;function rS(t){let e=qO.call(this,t);if(e)return e;let r=(0,li.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new ci.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),a;t.$async&&(a=s.scopeValue("Error",{ref:tH.default,code:(0,ci._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:qa.default.data,parentData:qa.default.parentData,parentDataProperty:qa.default.parentDataProperty,dataNames:[qa.default.data],dataPathArr:[ci.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ci.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ci.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ci._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,rH.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(qa.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${qa.default.self}`,`${qa.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:m}=l;p.evaluated={props:h instanceof ci.Name?void 0:h,items:m instanceof ci.Name?void 0:m,dynamicProps:h instanceof ci.Name,dynamicItems:m instanceof ci.Name},p.source&&(p.source.evaluated=(0,ci.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}jn.compileSchema=rS;function nH(t,e,r){var n;r=(0,li.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let o=sH.call(this,t,r);if(o===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(o=new ku({schema:s,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=iH.call(this,o)}jn.resolveRef=nH;function iH(t){return(0,li.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:rS.call(this,t)}function qO(t){for(let e of this._compilations)if(oH(e,t))return e}jn.getCompilingSchema=qO;function oH(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function sH(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ny.call(this,t,e)}function Ny(t,e){let r=this.opts.uriResolver.parse(e),n=(0,li._getFullPath)(this.opts.uriResolver,r),i=(0,li.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return tS.call(this,r,t);let o=(0,li.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let a=Ny.call(this,t,s);return typeof a?.schema!="object"?void 0:tS.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||rS.call(this,s),o===(0,li.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,li.resolveUrl)(this.opts.uriResolver,i,l)),new ku({schema:a,schemaId:c,root:t,baseId:i})}return tS.call(this,r,s)}}jn.resolveSchema=Ny;var aH=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tS(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,VO.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!aH.has(a)&&l&&(e=(0,li.resolveUrl)(this.opts.uriResolver,e,l))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,VO.schemaHasRulesButRef)(r,this.RULES)){let a=(0,li.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Ny.call(this,n,a)}let{schemaId:s}=this.opts;if(o=o||new ku({schema:r,schemaId:s,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var BO=C((axe,cH)=>{cH.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var GO=C((Oy,WO)=>{"use strict";(function(t,e){typeof Oy=="object"&&typeof WO<"u"?e(Oy):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Oy,(function(t){"use strict";function e(){for(var v=arguments.length,_=Array(v),S=0;S<v;S++)_[S]=arguments[S];if(_.length>1){_[0]=_[0].slice(0,-1);for(var A=_.length-1,N=1;N<A;++N)_[N]=_[N].slice(1,-1);return _[A]=_[A].slice(1),_.join("")}else return _[0]}function r(v){return"(?:"+v+")"}function n(v){return v===void 0?"undefined":v===null?"null":Object.prototype.toString.call(v).split(" ").pop().split("]").shift().toLowerCase()}function i(v){return v.toUpperCase()}function o(v){return v!=null?v instanceof Array?v:typeof v.length!="number"||v.split||v.setInterval||v.call?[v]:Array.prototype.slice.call(v):[]}function s(v,_){var S=v;if(_)for(var A in _)S[A]=_[A];return S}function a(v){var _="[A-Za-z]",S="[\\x0D]",A="[0-9]",N="[\\x22]",J=e(A,"[A-Fa-f]"),Ae="[\\x0A]",Ge="[\\x20]",tt=r(r("%[EFef]"+J+"%"+J+J+"%"+J+J)+"|"+r("%[89A-Fa-f]"+J+"%"+J+J)+"|"+r("%"+J+J)),Ft="[\\:\\/\\?\\#\\[\\]\\@]",qe="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",It=e(Ft,qe),Vt=v?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",vt=v?"[\\uE000-\\uF8FF]":"[]",Ye=e(_,A,"[\\-\\.\\_\\~]",Vt),Et=r(_+e(_,A,"[\\+\\-\\.]")+"*"),it=r(r(tt+"|"+e(Ye,qe,"[\\:]"))+"*"),Ms=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("[1-9]"+A)+"|"+A),nn=r(r("25[0-5]")+"|"+r("2[0-4]"+A)+"|"+r("1"+A+A)+"|"+r("0?[1-9]"+A)+"|0?0?"+A),kn=r(nn+"\\."+nn+"\\."+nn+"\\."+nn),ct=r(J+"{1,4}"),on=r(r(ct+"\\:"+ct)+"|"+kn),$n=r(r(ct+"\\:")+"{6}"+on),mi=r("\\:\\:"+r(ct+"\\:")+"{5}"+on),js=r(r(ct)+"?\\:\\:"+r(ct+"\\:")+"{4}"+on),Zi=r(r(r(ct+"\\:")+"{0,1}"+ct)+"?\\:\\:"+r(ct+"\\:")+"{3}"+on),Gu=r(r(r(ct+"\\:")+"{0,2}"+ct)+"?\\:\\:"+r(ct+"\\:")+"{2}"+on),Pm=r(r(r(ct+"\\:")+"{0,3}"+ct)+"?\\:\\:"+ct+"\\:"+on),Tm=r(r(r(ct+"\\:")+"{0,4}"+ct)+"?\\:\\:"+on),cc=r(r(r(ct+"\\:")+"{0,5}"+ct)+"?\\:\\:"+ct),lc=r(r(r(ct+"\\:")+"{0,6}"+ct)+"?\\:\\:"),Fi=r([$n,mi,js,Zi,Gu,Pm,Tm,cc,lc].join("|")),uc=r(r(Ye+"|"+tt)+"+"),sb=r(Fi+"\\%25"+uc),Ds=r(Fi+r("\\%25|\\%(?!"+J+"{2})")+uc),u4=r("[vV]"+J+"+\\."+e(Ye,qe,"[\\:]")+"+"),d4=r("\\["+r(Ds+"|"+Fi+"|"+u4)+"\\]"),bE=r(r(tt+"|"+e(Ye,qe))+"*"),Hu=r(d4+"|"+kn+"(?!"+bE+")|"+bE),Xu=r(A+"*"),vE=r(r(it+"@")+"?"+Hu+r("\\:"+Xu)+"?"),Ku=r(tt+"|"+e(Ye,qe,"[\\:\\@]")),p4=r(Ku+"*"),wE=r(Ku+"+"),f4=r(r(tt+"|"+e(Ye,qe,"[\\@]"))+"+"),Vi=r(r("\\/"+p4)+"*"),dc=r("\\/"+r(wE+Vi)+"?"),ab=r(f4+Vi),Am=r(wE+Vi),pc="(?!"+Ku+")",oQ=r(Vi+"|"+dc+"|"+ab+"|"+Am+"|"+pc),fc=r(r(Ku+"|"+e("[\\/\\?]",vt))+"*"),Ju=r(r(Ku+"|[\\/\\?]")+"*"),xE=r(r("\\/\\/"+vE+Vi)+"|"+dc+"|"+Am+"|"+pc),m4=r(Et+"\\:"+xE+r("\\?"+fc)+"?"+r("\\#"+Ju)+"?"),h4=r(r("\\/\\/"+vE+Vi)+"|"+dc+"|"+ab+"|"+pc),g4=r(h4+r("\\?"+fc)+"?"+r("\\#"+Ju)+"?"),sQ=r(m4+"|"+g4),aQ=r(Et+"\\:"+xE+r("\\?"+fc)+"?"),cQ="^("+Et+")\\:"+r(r("\\/\\/("+r("("+it+")@")+"?("+Hu+")"+r("\\:("+Xu+")")+"?)")+"?("+Vi+"|"+dc+"|"+Am+"|"+pc+")")+r("\\?("+fc+")")+"?"+r("\\#("+Ju+")")+"?$",lQ="^(){0}"+r(r("\\/\\/("+r("("+it+")@")+"?("+Hu+")"+r("\\:("+Xu+")")+"?)")+"?("+Vi+"|"+dc+"|"+ab+"|"+pc+")")+r("\\?("+fc+")")+"?"+r("\\#("+Ju+")")+"?$",uQ="^("+Et+")\\:"+r(r("\\/\\/("+r("("+it+")@")+"?("+Hu+")"+r("\\:("+Xu+")")+"?)")+"?("+Vi+"|"+dc+"|"+Am+"|"+pc+")")+r("\\?("+fc+")")+"?$",dQ="^"+r("\\#("+Ju+")")+"?$",pQ="^"+r("("+it+")@")+"?("+Hu+")"+r("\\:("+Xu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",_,A,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ye,qe),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ye,qe),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ye,qe),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ye,qe),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ye,qe,"[\\:\\@\\/\\?]",vt),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ye,qe,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ye,qe),"g"),UNRESERVED:new RegExp(Ye,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ye,It),"g"),PCT_ENCODED:new RegExp(tt,"g"),IPV4ADDRESS:new RegExp("^("+kn+")$"),IPV6ADDRESS:new RegExp("^\\[?("+Fi+")"+r(r("\\%25|\\%(?!"+J+"{2})")+"("+uc+")")+"?\\]?$")}}var c=a(!1),l=a(!0),u=(function(){function v(_,S){var A=[],N=!0,J=!1,Ae=void 0;try{for(var Ge=_[Symbol.iterator](),tt;!(N=(tt=Ge.next()).done)&&(A.push(tt.value),!(S&&A.length===S));N=!0);}catch(Ft){J=!0,Ae=Ft}finally{try{!N&&Ge.return&&Ge.return()}finally{if(J)throw Ae}}return A}return function(_,S){if(Array.isArray(_))return _;if(Symbol.iterator in Object(_))return v(_,S);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),d=function(v){if(Array.isArray(v)){for(var _=0,S=Array(v.length);_<v.length;_++)S[_]=v[_];return S}else return Array.from(v)},f=2147483647,p=36,h=1,m=26,g=38,y=700,b=72,$=128,R="-",T=/^xn--/,P=/[^\0-\x7E]/,F=/[\x2E\u3002\uFF0E\uFF61]/g,ce={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},te=p-h,H=Math.floor,_e=String.fromCharCode;function he(v){throw new RangeError(ce[v])}function Y(v,_){for(var S=[],A=v.length;A--;)S[A]=_(v[A]);return S}function pe(v,_){var S=v.split("@"),A="";S.length>1&&(A=S[0]+"@",v=S[1]),v=v.replace(F,".");var N=v.split("."),J=Y(N,_).join(".");return A+J}function fe(v){for(var _=[],S=0,A=v.length;S<A;){var N=v.charCodeAt(S++);if(N>=55296&&N<=56319&&S<A){var J=v.charCodeAt(S++);(J&64512)==56320?_.push(((N&1023)<<10)+(J&1023)+65536):(_.push(N),S--)}else _.push(N)}return _}var bt=function(_){return String.fromCodePoint.apply(String,d(_))},Nt=function(_){return _-48<10?_-22:_-65<26?_-65:_-97<26?_-97:p},Ur=function(_,S){return _+22+75*(_<26)-((S!=0)<<5)},tn=function(_,S,A){var N=0;for(_=A?H(_/y):_>>1,_+=H(_/S);_>te*m>>1;N+=p)_=H(_/te);return H(N+(te+1)*_/(_+g))},w=function(_){var S=[],A=_.length,N=0,J=$,Ae=b,Ge=_.lastIndexOf(R);Ge<0&&(Ge=0);for(var tt=0;tt<Ge;++tt)_.charCodeAt(tt)>=128&&he("not-basic"),S.push(_.charCodeAt(tt));for(var Ft=Ge>0?Ge+1:0;Ft<A;){for(var qe=N,It=1,Vt=p;;Vt+=p){Ft>=A&&he("invalid-input");var vt=Nt(_.charCodeAt(Ft++));(vt>=p||vt>H((f-N)/It))&&he("overflow"),N+=vt*It;var Ye=Vt<=Ae?h:Vt>=Ae+m?m:Vt-Ae;if(vt<Ye)break;var Et=p-Ye;It>H(f/Et)&&he("overflow"),It*=Et}var it=S.length+1;Ae=tn(N-qe,it,qe==0),H(N/it)>f-J&&he("overflow"),J+=H(N/it),N%=it,S.splice(N++,0,J)}return String.fromCodePoint.apply(String,S)},Ar=function(_){var S=[];_=fe(_);var A=_.length,N=$,J=0,Ae=b,Ge=!0,tt=!1,Ft=void 0;try{for(var qe=_[Symbol.iterator](),It;!(Ge=(It=qe.next()).done);Ge=!0){var Vt=It.value;Vt<128&&S.push(_e(Vt))}}catch(Ds){tt=!0,Ft=Ds}finally{try{!Ge&&qe.return&&qe.return()}finally{if(tt)throw Ft}}var vt=S.length,Ye=vt;for(vt&&S.push(R);Ye<A;){var Et=f,it=!0,Ms=!1,nn=void 0;try{for(var kn=_[Symbol.iterator](),ct;!(it=(ct=kn.next()).done);it=!0){var on=ct.value;on>=N&&on<Et&&(Et=on)}}catch(Ds){Ms=!0,nn=Ds}finally{try{!it&&kn.return&&kn.return()}finally{if(Ms)throw nn}}var $n=Ye+1;Et-N>H((f-J)/$n)&&he("overflow"),J+=(Et-N)*$n,N=Et;var mi=!0,js=!1,Zi=void 0;try{for(var Gu=_[Symbol.iterator](),Pm;!(mi=(Pm=Gu.next()).done);mi=!0){var Tm=Pm.value;if(Tm<N&&++J>f&&he("overflow"),Tm==N){for(var cc=J,lc=p;;lc+=p){var Fi=lc<=Ae?h:lc>=Ae+m?m:lc-Ae;if(cc<Fi)break;var uc=cc-Fi,sb=p-Fi;S.push(_e(Ur(Fi+uc%sb,0))),cc=H(uc/sb)}S.push(_e(Ur(cc,0))),Ae=tn(J,$n,Ye==vt),J=0,++Ye}}}catch(Ds){js=!0,Zi=Ds}finally{try{!mi&&Gu.return&&Gu.return()}finally{if(js)throw Zi}}++J,++N}return S.join("")},Vn=function(_){return pe(_,function(S){return T.test(S)?w(S.slice(4).toLowerCase()):S})},k=function(_){return pe(_,function(S){return P.test(S)?"xn--"+Ar(S):S})},Ut={version:"2.1.0",ucs2:{decode:fe,encode:bt},decode:w,encode:Ar,toASCII:k,toUnicode:Vn},Zt={};function Zr(v){var _=v.charCodeAt(0),S=void 0;return _<16?S="%0"+_.toString(16).toUpperCase():_<128?S="%"+_.toString(16).toUpperCase():_<2048?S="%"+(_>>6|192).toString(16).toUpperCase()+"%"+(_&63|128).toString(16).toUpperCase():S="%"+(_>>12|224).toString(16).toUpperCase()+"%"+(_>>6&63|128).toString(16).toUpperCase()+"%"+(_&63|128).toString(16).toUpperCase(),S}function qn(v){for(var _="",S=0,A=v.length;S<A;){var N=parseInt(v.substr(S+1,2),16);if(N<128)_+=String.fromCharCode(N),S+=3;else if(N>=194&&N<224){if(A-S>=6){var J=parseInt(v.substr(S+4,2),16);_+=String.fromCharCode((N&31)<<6|J&63)}else _+=v.substr(S,6);S+=6}else if(N>=224){if(A-S>=9){var Ae=parseInt(v.substr(S+4,2),16),Ge=parseInt(v.substr(S+7,2),16);_+=String.fromCharCode((N&15)<<12|(Ae&63)<<6|Ge&63)}else _+=v.substr(S,9);S+=9}else _+=v.substr(S,3),S+=3}return _}function Ct(v,_){function S(A){var N=qn(A);return N.match(_.UNRESERVED)?N:A}return v.scheme&&(v.scheme=String(v.scheme).replace(_.PCT_ENCODED,S).toLowerCase().replace(_.NOT_SCHEME,"")),v.userinfo!==void 0&&(v.userinfo=String(v.userinfo).replace(_.PCT_ENCODED,S).replace(_.NOT_USERINFO,Zr).replace(_.PCT_ENCODED,i)),v.host!==void 0&&(v.host=String(v.host).replace(_.PCT_ENCODED,S).toLowerCase().replace(_.NOT_HOST,Zr).replace(_.PCT_ENCODED,i)),v.path!==void 0&&(v.path=String(v.path).replace(_.PCT_ENCODED,S).replace(v.scheme?_.NOT_PATH:_.NOT_PATH_NOSCHEME,Zr).replace(_.PCT_ENCODED,i)),v.query!==void 0&&(v.query=String(v.query).replace(_.PCT_ENCODED,S).replace(_.NOT_QUERY,Zr).replace(_.PCT_ENCODED,i)),v.fragment!==void 0&&(v.fragment=String(v.fragment).replace(_.PCT_ENCODED,S).replace(_.NOT_FRAGMENT,Zr).replace(_.PCT_ENCODED,i)),v}function Li(v){return v.replace(/^0*(.*)/,"$1")||"0"}function Fr(v,_){var S=v.match(_.IPV4ADDRESS)||[],A=u(S,2),N=A[1];return N?N.split(".").map(Li).join("."):v}function Ui(v,_){var S=v.match(_.IPV6ADDRESS)||[],A=u(S,3),N=A[1],J=A[2];if(N){for(var Ae=N.toLowerCase().split("::").reverse(),Ge=u(Ae,2),tt=Ge[0],Ft=Ge[1],qe=Ft?Ft.split(":").map(Li):[],It=tt.split(":").map(Li),Vt=_.IPV4ADDRESS.test(It[It.length-1]),vt=Vt?7:8,Ye=It.length-vt,Et=Array(vt),it=0;it<vt;++it)Et[it]=qe[it]||It[Ye+it]||"";Vt&&(Et[vt-1]=Fr(Et[vt-1],_));var Ms=Et.reduce(function($n,mi,js){if(!mi||mi==="0"){var Zi=$n[$n.length-1];Zi&&Zi.index+Zi.length===js?Zi.length++:$n.push({index:js,length:1})}return $n},[]),nn=Ms.sort(function($n,mi){return mi.length-$n.length})[0],kn=void 0;if(nn&&nn.length>1){var ct=Et.slice(0,nn.index),on=Et.slice(nn.index+nn.length);kn=ct.join(":")+"::"+on.join(":")}else kn=Et.join(":");return J&&(kn+="%"+J),kn}else return v}var zo=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,qu="".match(/(){0}/)[1]===void 0;function vn(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S={},A=_.iri!==!1?l:c;_.reference==="suffix"&&(v=(_.scheme?_.scheme+":":"")+"//"+v);var N=v.match(zo);if(N){qu?(S.scheme=N[1],S.userinfo=N[3],S.host=N[4],S.port=parseInt(N[5],10),S.path=N[6]||"",S.query=N[7],S.fragment=N[8],isNaN(S.port)&&(S.port=N[5])):(S.scheme=N[1]||void 0,S.userinfo=v.indexOf("@")!==-1?N[3]:void 0,S.host=v.indexOf("//")!==-1?N[4]:void 0,S.port=parseInt(N[5],10),S.path=N[6]||"",S.query=v.indexOf("?")!==-1?N[7]:void 0,S.fragment=v.indexOf("#")!==-1?N[8]:void 0,isNaN(S.port)&&(S.port=v.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?N[4]:void 0)),S.host&&(S.host=Ui(Fr(S.host,A),A)),S.scheme===void 0&&S.userinfo===void 0&&S.host===void 0&&S.port===void 0&&!S.path&&S.query===void 0?S.reference="same-document":S.scheme===void 0?S.reference="relative":S.fragment===void 0?S.reference="absolute":S.reference="uri",_.reference&&_.reference!=="suffix"&&_.reference!==S.reference&&(S.error=S.error||"URI is not a "+_.reference+" reference.");var J=Zt[(_.scheme||S.scheme||"").toLowerCase()];if(!_.unicodeSupport&&(!J||!J.unicodeSupport)){if(S.host&&(_.domainHost||J&&J.domainHost))try{S.host=Ut.toASCII(S.host.replace(A.PCT_ENCODED,qn).toLowerCase())}catch(Ae){S.error=S.error||"Host's domain name can not be converted to ASCII via punycode: "+Ae}Ct(S,c)}else Ct(S,A);J&&J.parse&&J.parse(S,_)}else S.error=S.error||"URI can not be parsed.";return S}function $m(v,_){var S=_.iri!==!1?l:c,A=[];return v.userinfo!==void 0&&(A.push(v.userinfo),A.push("@")),v.host!==void 0&&A.push(Ui(Fr(String(v.host),S),S).replace(S.IPV6ADDRESS,function(N,J,Ae){return"["+J+(Ae?"%25"+Ae:"")+"]"})),(typeof v.port=="number"||typeof v.port=="string")&&(A.push(":"),A.push(String(v.port))),A.length?A.join(""):void 0}var Bu=/^\.\.?\//,Sm=/^\/\.(\/|$)/,Wu=/^\/\.\.(\/|$)/,Im=/^\/?(?:.|\n)*?(?=\/|$)/;function No(v){for(var _=[];v.length;)if(v.match(Bu))v=v.replace(Bu,"");else if(v.match(Sm))v=v.replace(Sm,"/");else if(v.match(Wu))v=v.replace(Wu,"/"),_.pop();else if(v==="."||v==="..")v="";else{var S=v.match(Im);if(S){var A=S[0];v=v.slice(A.length),_.push(A)}else throw new Error("Unexpected dot segment condition")}return _.join("")}function wn(v){var _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},S=_.iri?l:c,A=[],N=Zt[(_.scheme||v.scheme||"").toLowerCase()];if(N&&N.serialize&&N.serialize(v,_),v.host&&!S.IPV6ADDRESS.test(v.host)){if(_.domainHost||N&&N.domainHost)try{v.host=_.iri?Ut.toUnicode(v.host):Ut.toASCII(v.host.replace(S.PCT_ENCODED,qn).toLowerCase())}catch(Ge){v.error=v.error||"Host's domain name can not be converted to "+(_.iri?"Unicode":"ASCII")+" via punycode: "+Ge}}Ct(v,S),_.reference!=="suffix"&&v.scheme&&(A.push(v.scheme),A.push(":"));var J=$m(v,_);if(J!==void 0&&(_.reference!=="suffix"&&A.push("//"),A.push(J),v.path&&v.path.charAt(0)!=="/"&&A.push("/")),v.path!==void 0){var Ae=v.path;!_.absolutePath&&(!N||!N.absolutePath)&&(Ae=No(Ae)),J===void 0&&(Ae=Ae.replace(/^\/\//,"/%2F")),A.push(Ae)}return v.query!==void 0&&(A.push("?"),A.push(v.query)),v.fragment!==void 0&&(A.push("#"),A.push(v.fragment)),A.join("")}function Em(v,_){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},A=arguments[3],N={};return A||(v=vn(wn(v,S),S),_=vn(wn(_,S),S)),S=S||{},!S.tolerant&&_.scheme?(N.scheme=_.scheme,N.userinfo=_.userinfo,N.host=_.host,N.port=_.port,N.path=No(_.path||""),N.query=_.query):(_.userinfo!==void 0||_.host!==void 0||_.port!==void 0?(N.userinfo=_.userinfo,N.host=_.host,N.port=_.port,N.path=No(_.path||""),N.query=_.query):(_.path?(_.path.charAt(0)==="/"?N.path=No(_.path):((v.userinfo!==void 0||v.host!==void 0||v.port!==void 0)&&!v.path?N.path="/"+_.path:v.path?N.path=v.path.slice(0,v.path.lastIndexOf("/")+1)+_.path:N.path=_.path,N.path=No(N.path)),N.query=_.query):(N.path=v.path,_.query!==void 0?N.query=_.query:N.query=v.query),N.userinfo=v.userinfo,N.host=v.host,N.port=v.port),N.scheme=v.scheme),N.fragment=_.fragment,N}function nb(v,_,S){var A=s({scheme:"null"},S);return wn(Em(vn(v,A),vn(_,A),A,!0),A)}function ib(v,_){return typeof v=="string"?v=wn(vn(v,_),_):n(v)==="object"&&(v=vn(wn(v,_),_)),v}function j(v,_,S){return typeof v=="string"?v=wn(vn(v,S),S):n(v)==="object"&&(v=wn(v,S)),typeof _=="string"?_=wn(vn(_,S),S):n(_)==="object"&&(_=wn(_,S)),v===_}function V(v,_){return v&&v.toString().replace(!_||!_.iri?c.ESCAPE:l.ESCAPE,Zr)}function le(v,_){return v&&v.toString().replace(!_||!_.iri?c.PCT_ENCODED:l.PCT_ENCODED,qn)}var Te={scheme:"http",domainHost:!0,parse:function(_,S){return _.host||(_.error=_.error||"HTTP URIs must have a host."),_},serialize:function(_,S){var A=String(_.scheme).toLowerCase()==="https";return(_.port===(A?443:80)||_.port==="")&&(_.port=void 0),_.path||(_.path="/"),_}},et={scheme:"https",domainHost:Te.domainHost,parse:Te.parse,serialize:Te.serialize};function Vr(v){return typeof v.secure=="boolean"?v.secure:String(v.scheme).toLowerCase()==="wss"}var rn={scheme:"ws",domainHost:!0,parse:function(_,S){var A=_;return A.secure=Vr(A),A.resourceName=(A.path||"/")+(A.query?"?"+A.query:""),A.path=void 0,A.query=void 0,A},serialize:function(_,S){if((_.port===(Vr(_)?443:80)||_.port==="")&&(_.port=void 0),typeof _.secure=="boolean"&&(_.scheme=_.secure?"wss":"ws",_.secure=void 0),_.resourceName){var A=_.resourceName.split("?"),N=u(A,2),J=N[0],Ae=N[1];_.path=J&&J!=="/"?J:void 0,_.query=Ae,_.resourceName=void 0}return _.fragment=void 0,_}},xn={scheme:"wss",domainHost:rn.domainHost,parse:rn.parse,serialize:rn.serialize},Os={},Rs=!0,_r="[A-Za-z0-9\\-\\.\\_\\~"+(Rs?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",nr="[0-9A-Fa-f]",Bn=r(r("%[EFef]"+nr+"%"+nr+nr+"%"+nr+nr)+"|"+r("%[89A-Fa-f]"+nr+"%"+nr+nr)+"|"+r("%"+nr+nr)),t4="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",r4="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",n4=e(r4,'[\\"\\\\]'),i4="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",o4=new RegExp(_r,"g"),ac=new RegExp(Bn,"g"),s4=new RegExp(e("[^]",t4,"[\\.]",'[\\"]',n4),"g"),hE=new RegExp(e("[^]",_r,i4),"g"),a4=hE;function ob(v){var _=qn(v);return _.match(o4)?_:v}var gE={scheme:"mailto",parse:function(_,S){var A=_,N=A.to=A.path?A.path.split(","):[];if(A.path=void 0,A.query){for(var J=!1,Ae={},Ge=A.query.split("&"),tt=0,Ft=Ge.length;tt<Ft;++tt){var qe=Ge[tt].split("=");switch(qe[0]){case"to":for(var It=qe[1].split(","),Vt=0,vt=It.length;Vt<vt;++Vt)N.push(It[Vt]);break;case"subject":A.subject=le(qe[1],S);break;case"body":A.body=le(qe[1],S);break;default:J=!0,Ae[le(qe[0],S)]=le(qe[1],S);break}}J&&(A.headers=Ae)}A.query=void 0;for(var Ye=0,Et=N.length;Ye<Et;++Ye){var it=N[Ye].split("@");if(it[0]=le(it[0]),S.unicodeSupport)it[1]=le(it[1],S).toLowerCase();else try{it[1]=Ut.toASCII(le(it[1],S).toLowerCase())}catch(Ms){A.error=A.error||"Email address's domain name can not be converted to ASCII via punycode: "+Ms}N[Ye]=it.join("@")}return A},serialize:function(_,S){var A=_,N=o(_.to);if(N){for(var J=0,Ae=N.length;J<Ae;++J){var Ge=String(N[J]),tt=Ge.lastIndexOf("@"),Ft=Ge.slice(0,tt).replace(ac,ob).replace(ac,i).replace(s4,Zr),qe=Ge.slice(tt+1);try{qe=S.iri?Ut.toUnicode(qe):Ut.toASCII(le(qe,S).toLowerCase())}catch(Ye){A.error=A.error||"Email address's domain name can not be converted to "+(S.iri?"Unicode":"ASCII")+" via punycode: "+Ye}N[J]=Ft+"@"+qe}A.path=N.join(",")}var It=_.headers=_.headers||{};_.subject&&(It.subject=_.subject),_.body&&(It.body=_.body);var Vt=[];for(var vt in It)It[vt]!==Os[vt]&&Vt.push(vt.replace(ac,ob).replace(ac,i).replace(hE,Zr)+"="+It[vt].replace(ac,ob).replace(ac,i).replace(a4,Zr));return Vt.length&&(A.query=Vt.join("&")),A}},c4=/^([^\:]+)\:(.*)/,yE={scheme:"urn",parse:function(_,S){var A=_.path&&_.path.match(c4),N=_;if(A){var J=S.scheme||N.scheme||"urn",Ae=A[1].toLowerCase(),Ge=A[2],tt=J+":"+(S.nid||Ae),Ft=Zt[tt];N.nid=Ae,N.nss=Ge,N.path=void 0,Ft&&(N=Ft.parse(N,S))}else N.error=N.error||"URN can not be parsed.";return N},serialize:function(_,S){var A=S.scheme||_.scheme||"urn",N=_.nid,J=A+":"+(S.nid||N),Ae=Zt[J];Ae&&(_=Ae.serialize(_,S));var Ge=_,tt=_.nss;return Ge.path=(N||S.nid)+":"+tt,Ge}},l4=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,_E={scheme:"urn:uuid",parse:function(_,S){var A=_;return A.uuid=A.nss,A.nss=void 0,!S.tolerant&&(!A.uuid||!A.uuid.match(l4))&&(A.error=A.error||"UUID is not valid."),A},serialize:function(_,S){var A=_;return A.nss=(_.uuid||"").toLowerCase(),A}};Zt[Te.scheme]=Te,Zt[et.scheme]=et,Zt[rn.scheme]=rn,Zt[xn.scheme]=xn,Zt[gE.scheme]=gE,Zt[yE.scheme]=yE,Zt[_E.scheme]=_E,t.SCHEMES=Zt,t.pctEncChar=Zr,t.pctDecChars=qn,t.parse=vn,t.removeDotSegments=No,t.serialize=wn,t.resolveComponents=Em,t.resolve=nb,t.normalize=ib,t.equal=j,t.escapeComponent=V,t.unescapeComponent=le,Object.defineProperty(t,"__esModule",{value:!0})}))});var XO=C(nS=>{"use strict";Object.defineProperty(nS,"__esModule",{value:!0});var HO=GO();HO.code='require("ajv/dist/runtime/uri").default';nS.default=HO});var nR=C(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.CodeGen=hr.Name=hr.nil=hr.stringify=hr.str=hr._=hr.KeywordCxt=void 0;var lH=yf();Object.defineProperty(hr,"KeywordCxt",{enumerable:!0,get:function(){return lH.KeywordCxt}});var $u=Oe();Object.defineProperty(hr,"_",{enumerable:!0,get:function(){return $u._}});Object.defineProperty(hr,"str",{enumerable:!0,get:function(){return $u.str}});Object.defineProperty(hr,"stringify",{enumerable:!0,get:function(){return $u.stringify}});Object.defineProperty(hr,"nil",{enumerable:!0,get:function(){return $u.nil}});Object.defineProperty(hr,"Name",{enumerable:!0,get:function(){return $u.Name}});Object.defineProperty(hr,"CodeGen",{enumerable:!0,get:function(){return $u.CodeGen}});var uH=Ay(),eR=zy(),dH=D$(),_f=Cy(),pH=Oe(),bf=mf(),Ry=ff(),oS=Je(),KO=BO(),fH=XO(),tR=(t,e)=>new RegExp(t,e);tR.code="new RegExp";var mH=["removeAdditional","useDefaults","coerceTypes"],hH=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),gH={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},yH={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},JO=200;function _H(t){var e,r,n,i,o,s,a,c,l,u,d,f,p,h,m,g,y,b,$,R,T,P,F,ce,te;let H=t.strict,_e=(e=t.code)===null||e===void 0?void 0:e.optimize,he=_e===!0||_e===void 0?1:_e||0,Y=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:tR,pe=(i=t.uriResolver)!==null&&i!==void 0?i:fH.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:H)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:H)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:H)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:H)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:H)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:he,regExp:Y}:{optimize:he,regExp:Y},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:JO,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:JO,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:($=t.inlineRefs)!==null&&$!==void 0?$:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(F=t.validateFormats)!==null&&F!==void 0?F:!0,unicodeRegExp:(ce=t.unicodeRegExp)!==null&&ce!==void 0?ce:!0,int32range:(te=t.int32range)!==null&&te!==void 0?te:!0,uriResolver:pe}}var vf=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,..._H(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new pH.ValueScope({scope:{},prefixes:hH,es5:r,lines:n}),this.logger=$H(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,dH.getRules)(),YO.call(this,gH,e,"NOT SUPPORTED"),YO.call(this,yH,e,"DEPRECATED","warn"),this._metaOpts=xH.call(this),e.formats&&vH.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wH.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),bH.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=KO;n==="id"&&(i={...KO},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,r);async function i(u,d){await o.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||s.call(this,f)}async function o(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof eR.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,i);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,bf.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(e){let r;for(;typeof(r=QO.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new _f.SchemaEnv({schema:{},schemaId:n});if(r=_f.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=QO.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,bf.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(IH.call(this,n,r),!r)return(0,oS.eachItem)(n,o=>iS.call(this,o)),this;PH.call(this,r);let i={...r,type:(0,Ry.getJSONTypes)(r.type),schemaType:(0,Ry.getJSONTypes)(r.schemaType)};return(0,oS.eachItem)(n,i.type.length===0?o=>iS.call(this,o,i):o=>i.type.forEach(s=>iS.call(this,o,i,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let o=i.split("/").slice(1),s=e;for(let a of o)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=rR(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,bf.normalizeId)(s||n);let l=bf.getSchemaRefs.call(this,e,n);return c=new _f.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):_f.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{_f.compileSchema.call(this,e)}finally{this.opts=r}}};hr.default=vf;vf.ValidationError=uH.default;vf.MissingRefError=eR.default;function YO(t,e,r,n="error"){for(let i in t){let o=i;o in e&&this.logger[n](`${r}: option ${i}. ${t[o]}`)}}function QO(t){return t=(0,bf.normalizeId)(t),this.schemas[t]||this.refs[t]}function bH(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function vH(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wH(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function xH(){let t={...this.opts};for(let e of mH)delete t[e];return t}var kH={log(){},warn(){},error(){}};function $H(t){if(t===!1)return kH;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var SH=/^[a-z_$][a-z0-9_$:-]*$/i;function IH(t,e){let{RULES:r}=this;if((0,oS.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!SH.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function iS(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ry.getJSONTypes)(e.type),schemaType:(0,Ry.getJSONTypes)(e.schemaType)}};e.before?EH.call(this,s,a,e.before):s.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function EH(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function PH(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rR(e)),t.validateSchema=this.compile(e,!0))}var TH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rR(t){return{anyOf:[t,TH]}}});var iR=C(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});var AH={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sS.default=AH});var cR=C(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.callRef=Ba.getValidate=void 0;var zH=zy(),oR=Mn(),Yr=Oe(),Su=$o(),sR=Cy(),My=Je(),NH={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:o,validateName:s,opts:a,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&i===l.baseId)return d();let u=sR.resolveRef.call(c,l,i,r);if(u===void 0)throw new zH.default(n.opts.uriResolver,i,r);if(u instanceof sR.SchemaEnv)return f(u);return p(u);function d(){if(o===l)return jy(t,s,o,o.$async);let h=e.scopeValue("root",{ref:l});return jy(t,(0,Yr._)`${h}.validate`,l,l.$async)}function f(h){let m=aR(t,h);jy(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Yr.stringify)(h)}:{ref:h}),g=e.name("valid"),y=t.subschema({schema:h,dataTypes:[],schemaPath:Yr.nil,topSchemaRef:m,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function aR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Yr._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ba.getValidate=aR;function jy(t,e,r,n){let{gen:i,it:o}=t,{allErrors:s,schemaEnv:a,opts:c}=o,l=c.passContext?Su.default.this:Yr.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=i.let("valid");i.try(()=>{i.code((0,Yr._)`await ${(0,oR.callValidateCode)(t,e,l)}`),p(e),s||i.assign(h,!0)},m=>{i.if((0,Yr._)`!(${m} instanceof ${o.ValidationError})`,()=>i.throw(m)),f(m),s||i.assign(h,!1)}),t.ok(h)}function d(){t.result((0,oR.callValidateCode)(t,e,l),()=>p(e),()=>f(e))}function f(h){let m=(0,Yr._)`${h}.errors`;i.assign(Su.default.vErrors,(0,Yr._)`${Su.default.vErrors} === null ? ${m} : ${Su.default.vErrors}.concat(${m})`),i.assign(Su.default.errors,(0,Yr._)`${Su.default.vErrors}.length`)}function p(h){var m;if(!o.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=My.mergeEvaluated.props(i,g.props,o.props));else{let y=i.var("props",(0,Yr._)`${h}.evaluated.props`);o.props=My.mergeEvaluated.props(i,y,o.props,Yr.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=My.mergeEvaluated.items(i,g.items,o.items));else{let y=i.var("items",(0,Yr._)`${h}.evaluated.items`);o.items=My.mergeEvaluated.items(i,y,o.items,Yr.Name)}}}Ba.callRef=jy;Ba.default=NH});var lR=C(aS=>{"use strict";Object.defineProperty(aS,"__esModule",{value:!0});var CH=iR(),OH=cR(),RH=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CH.default,OH.default];aS.default=RH});var uR=C(cS=>{"use strict";Object.defineProperty(cS,"__esModule",{value:!0});var Dy=Oe(),$s=Dy.operators,Ly={maximum:{okStr:"<=",ok:$s.LTE,fail:$s.GT},minimum:{okStr:">=",ok:$s.GTE,fail:$s.LT},exclusiveMaximum:{okStr:"<",ok:$s.LT,fail:$s.GTE},exclusiveMinimum:{okStr:">",ok:$s.GT,fail:$s.LTE}},MH={message:({keyword:t,schemaCode:e})=>(0,Dy.str)`must be ${Ly[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Dy._)`{comparison: ${Ly[t].okStr}, limit: ${e}}`},jH={keyword:Object.keys(Ly),type:"number",schemaType:"number",$data:!0,error:MH,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Dy._)`${r} ${Ly[e].fail} ${n} || isNaN(${r})`)}};cS.default=jH});var dR=C(lS=>{"use strict";Object.defineProperty(lS,"__esModule",{value:!0});var wf=Oe(),DH={message:({schemaCode:t})=>(0,wf.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,wf._)`{multipleOf: ${t}}`},LH={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:DH,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,o=i.opts.multipleOfPrecision,s=e.let("res"),a=o?(0,wf._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,wf._)`${s} !== parseInt(${s})`;t.fail$data((0,wf._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};lS.default=LH});var fR=C(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});function pR(t){let e=t.length,r=0,n=0,i;for(;n<e;)r++,i=t.charCodeAt(n++),i>=55296&&i<=56319&&n<e&&(i=t.charCodeAt(n),(i&64512)===56320&&n++);return r}uS.default=pR;pR.code='require("ajv/dist/runtime/ucs2length").default'});var mR=C(dS=>{"use strict";Object.defineProperty(dS,"__esModule",{value:!0});var Wa=Oe(),UH=Je(),ZH=fR(),FH={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wa.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wa._)`{limit: ${t}}`},VH={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:FH,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,o=e==="maxLength"?Wa.operators.GT:Wa.operators.LT,s=i.opts.unicode===!1?(0,Wa._)`${r}.length`:(0,Wa._)`${(0,UH.useFunc)(t.gen,ZH.default)}(${r})`;t.fail$data((0,Wa._)`${s} ${o} ${n}`)}};dS.default=VH});var hR=C(pS=>{"use strict";Object.defineProperty(pS,"__esModule",{value:!0});var qH=Mn(),Uy=Oe(),BH={message:({schemaCode:t})=>(0,Uy.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Uy._)`{pattern: ${t}}`},WH={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:BH,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:o}=t,s=o.opts.unicodeRegExp?"u":"",a=r?(0,Uy._)`(new RegExp(${i}, ${s}))`:(0,qH.usePattern)(t,n);t.fail$data((0,Uy._)`!${a}.test(${e})`)}};pS.default=WH});var gR=C(fS=>{"use strict";Object.defineProperty(fS,"__esModule",{value:!0});var xf=Oe(),GH={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,xf.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,xf._)`{limit: ${t}}`},HH={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?xf.operators.GT:xf.operators.LT;t.fail$data((0,xf._)`Object.keys(${r}).length ${i} ${n}`)}};fS.default=HH});var yR=C(mS=>{"use strict";Object.defineProperty(mS,"__esModule",{value:!0});var kf=Mn(),$f=Oe(),XH=Je(),KH={message:({params:{missingProperty:t}})=>(0,$f.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,$f._)`{missingProperty: ${t}}`},JH={keyword:"required",type:"object",schemaType:"array",$data:!0,error:KH,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:o,it:s}=t,{opts:a}=s;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,XH.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||o)t.block$data($f.nil,d);else for(let p of r)(0,kf.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||o){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,kf.checkMissingProp)(t,r,p)),(0,kf.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,kf.noPropertyInData)(e,i,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,kf.propertyInData)(e,i,p,a.ownProperties)),e.if((0,$f.not)(h),()=>{t.error(),e.break()})},$f.nil)}}};mS.default=JH});var _R=C(hS=>{"use strict";Object.defineProperty(hS,"__esModule",{value:!0});var Sf=Oe(),YH={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Sf.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Sf._)`{limit: ${t}}`},QH={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:YH,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?Sf.operators.GT:Sf.operators.LT;t.fail$data((0,Sf._)`${r}.length ${i} ${n}`)}};hS.default=QH});var Zy=C(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});var bR=jp();bR.code='require("ajv/dist/runtime/equal").default';gS.default=bR});var vR=C(_S=>{"use strict";Object.defineProperty(_S,"__esModule",{value:!0});var yS=ff(),gr=Oe(),eX=Je(),tX=Zy(),rX={message:({params:{i:t,j:e}})=>(0,gr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,gr._)`{i: ${t}, j: ${e}}`},nX={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rX,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:a}=t;if(!n&&!i)return;let c=e.let("valid"),l=o.items?(0,yS.getSchemaTypes)(o.items):[];t.block$data(c,u,(0,gr._)`${s} === false`),t.ok(c);function u(){let h=e.let("i",(0,gr._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,gr._)`${h} > 1`,()=>(d()?f:p)(h,m))}function d(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function f(h,m){let g=e.name("item"),y=(0,yS.checkDataTypes)(l,g,a.opts.strictNumbers,yS.DataType.Wrong),b=e.const("indices",(0,gr._)`{}`);e.for((0,gr._)`;${h}--;`,()=>{e.let(g,(0,gr._)`${r}[${h}]`),e.if(y,(0,gr._)`continue`),l.length>1&&e.if((0,gr._)`typeof ${g} == "string"`,(0,gr._)`${g} += "_"`),e.if((0,gr._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(m,(0,gr._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,gr._)`${b}[${g}] = ${h}`)})}function p(h,m){let g=(0,eX.useFunc)(e,tX.default),y=e.name("outer");e.label(y).for((0,gr._)`;${h}--;`,()=>e.for((0,gr._)`${m} = ${h}; ${m}--;`,()=>e.if((0,gr._)`${g}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};_S.default=nX});var wR=C(vS=>{"use strict";Object.defineProperty(vS,"__esModule",{value:!0});var bS=Oe(),iX=Je(),oX=Zy(),sX={message:"must be equal to constant",params:({schemaCode:t})=>(0,bS._)`{allowedValue: ${t}}`},aX={keyword:"const",$data:!0,error:sX,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,bS._)`!${(0,iX.useFunc)(e,oX.default)}(${r}, ${i})`):t.fail((0,bS._)`${o} !== ${r}`)}};vS.default=aX});var xR=C(wS=>{"use strict";Object.defineProperty(wS,"__esModule",{value:!0});var If=Oe(),cX=Je(),lX=Zy(),uX={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,If._)`{allowedValues: ${t}}`},dX={keyword:"enum",schemaType:"array",$data:!0,error:uX,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:o,it:s}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,cX.useFunc)(e,lX.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",o);u=(0,If.or)(...i.map((h,m)=>f(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",o,p=>e.if((0,If._)`${l()}(${r}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,h){let m=i[h];return typeof m=="object"&&m!==null?(0,If._)`${l()}(${r}, ${p}[${h}])`:(0,If._)`${r} === ${m}`}}};wS.default=dX});var kR=C(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});var pX=uR(),fX=dR(),mX=mR(),hX=hR(),gX=gR(),yX=yR(),_X=_R(),bX=vR(),vX=wR(),wX=xR(),xX=[pX.default,fX.default,mX.default,hX.default,gX.default,yX.default,_X.default,bX.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},vX.default,wX.default];xS.default=xX});var $S=C(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});Ef.validateAdditionalItems=void 0;var Ga=Oe(),kS=Je(),kX={message:({params:{len:t}})=>(0,Ga.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ga._)`{limit: ${t}}`},$X={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:kX,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,kS.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}$R(t,n)}};function $R(t,e){let{gen:r,schema:n,data:i,keyword:o,it:s}=t;s.items=!0;let a=r.const("len",(0,Ga._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ga._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,kS.alwaysValidSchema)(s,n)){let l=r.var("valid",(0,Ga._)`${a} <= ${e.length}`);r.if((0,Ga.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:kS.Type.Num},l),s.allErrors||r.if((0,Ga.not)(l),()=>r.break())})}}Ef.validateAdditionalItems=$R;Ef.default=$X});var SS=C(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});Pf.validateTuple=void 0;var SR=Oe(),Fy=Je(),SX=Mn(),IX={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return IR(t,"additionalItems",e);r.items=!0,!(0,Fy.alwaysValidSchema)(r,e)&&t.ok((0,SX.validateArray)(t))}};function IR(t,e,r=t.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:a}=t;u(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Fy.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,SR._)`${o}.length`);r.forEach((d,f)=>{(0,Fy.alwaysValidSchema)(a,d)||(n.if((0,SR._)`${l} > ${f}`,()=>t.subschema({keyword:s,schemaProp:f,dataProp:f},c)),t.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(f.strictTuples&&!m){let g=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Fy.checkStrictMode)(a,g,f.strictTuples)}}}Pf.validateTuple=IR;Pf.default=IX});var ER=C(IS=>{"use strict";Object.defineProperty(IS,"__esModule",{value:!0});var EX=SS(),PX={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,EX.validateTuple)(t,"items")};IS.default=PX});var TR=C(ES=>{"use strict";Object.defineProperty(ES,"__esModule",{value:!0});var PR=Oe(),TX=Je(),AX=Mn(),zX=$S(),NX={message:({params:{len:t}})=>(0,PR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,PR._)`{limit: ${t}}`},CX={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:NX,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,TX.alwaysValidSchema)(n,e)&&(i?(0,zX.validateAdditionalItems)(t,i):t.ok((0,AX.validateArray)(t)))}};ES.default=CX});var AR=C(PS=>{"use strict";Object.defineProperty(PS,"__esModule",{value:!0});var Dn=Oe(),Vy=Je(),OX={message:({params:{min:t,max:e}})=>e===void 0?(0,Dn.str)`must contain at least ${t} valid item(s)`:(0,Dn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Dn._)`{minContains: ${t}}`:(0,Dn._)`{minContains: ${t}, maxContains: ${e}}`},RX={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OX,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t,s,a,{minContains:c,maxContains:l}=n;o.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Dn._)`${i}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Vy.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Vy.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Vy.alwaysValidSchema)(o,r)){let m=(0,Dn._)`${u} >= ${s}`;a!==void 0&&(m=(0,Dn._)`${m} && ${u} <= ${a}`),t.pass(m);return}o.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Dn._)`${i}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>h(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Vy.Type.Num,compositeRule:!0},m),g()})}function h(m){e.code((0,Dn._)`${m}++`),a===void 0?e.if((0,Dn._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Dn._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Dn._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};PS.default=RX});var CR=C(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.validateSchemaDeps=Ri.validatePropertyDeps=Ri.error=void 0;var TS=Oe(),MX=Je(),Tf=Mn();Ri.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,TS.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,TS._)`{property: ${t},
13
+ missingProperty: ${n},
14
+ depsCount: ${e},
15
+ deps: ${r}}`};var jX={keyword:"dependencies",type:"object",schemaType:"object",error:Ri.error,code(t){let[e,r]=DX(t);zR(t,e),NR(t,r)}};function DX({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function zR(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Tf.propertyInData)(r,n,s,i.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(c,()=>{for(let l of a)(0,Tf.checkReportMissingProp)(t,l)}):(r.if((0,TS._)`${c} && (${(0,Tf.checkMissingProp)(t,a,o)})`),(0,Tf.reportMissingProp)(t,o),r.else())}}Ri.validatePropertyDeps=zR;function NR(t,e=t.schema){let{gen:r,data:n,keyword:i,it:o}=t,s=r.name("valid");for(let a in e)(0,MX.alwaysValidSchema)(o,e[a])||(r.if((0,Tf.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:i,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}Ri.validateSchemaDeps=NR;Ri.default=jX});var RR=C(AS=>{"use strict";Object.defineProperty(AS,"__esModule",{value:!0});var OR=Oe(),LX=Je(),UX={message:"property name must be valid",params:({params:t})=>(0,OR._)`{propertyName: ${t.propertyName}}`},ZX={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:UX,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,LX.alwaysValidSchema)(i,r))return;let o=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,OR.not)(o),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(o)}};AS.default=ZX});var NS=C(zS=>{"use strict";Object.defineProperty(zS,"__esModule",{value:!0});var qy=Mn(),ui=Oe(),FX=$o(),By=Je(),VX={message:"must NOT have additional properties",params:({params:t})=>(0,ui._)`{additionalProperty: ${t.additionalProperty}}`},qX={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:VX,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,By.alwaysValidSchema)(s,r))return;let l=(0,qy.allSchemaProperties)(n.properties),u=(0,qy.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ui._)`${o} === ${FX.default.errors}`);function d(){e.forIn("key",i,g=>{!l.length&&!u.length?h(g):e.if(f(g),()=>h(g))})}function f(g){let y;if(l.length>8){let b=(0,By.schemaRefOrVal)(s,n.properties,"properties");y=(0,qy.isOwnProperty)(e,b,g)}else l.length?y=(0,ui.or)(...l.map(b=>(0,ui._)`${g} === ${b}`)):y=ui.nil;return u.length&&(y=(0,ui.or)(y,...u.map(b=>(0,ui._)`${(0,qy.usePattern)(t,b)}.test(${g})`))),(0,ui.not)(y)}function p(g){e.code((0,ui._)`delete ${i}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,By.alwaysValidSchema)(s,r)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,ui.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,ui.not)(y),()=>e.break()))}}function m(g,y,b){let $={keyword:"additionalProperties",dataProp:g,dataPropType:By.Type.Str};b===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema($,y)}}};zS.default=qX});var DR=C(OS=>{"use strict";Object.defineProperty(OS,"__esModule",{value:!0});var BX=yf(),MR=Mn(),CS=Je(),jR=NS(),WX={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&jR.default.code(new BX.KeywordCxt(o,jR.default,"additionalProperties"));let s=(0,MR.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=CS.mergeEvaluated.props(e,(0,CS.toHash)(s),o.props));let a=s.filter(d=>!(0,CS.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,MR.propertyInData)(e,i,d,o.opts.ownProperties)),u(d),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};OS.default=WX});var FR=C(RS=>{"use strict";Object.defineProperty(RS,"__esModule",{value:!0});var LR=Mn(),Wy=Oe(),UR=Je(),ZR=Je(),GX={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:o}=t,{opts:s}=o,a=(0,LR.allSchemaProperties)(r),c=a.filter(m=>(0,UR.alwaysValidSchema)(o,r[m]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&i.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Wy.Name)&&(o.props=(0,ZR.evaluatedPropsToName)(e,o.props));let{props:d}=o;f();function f(){for(let m of a)l&&p(m),o.allErrors?h(m):(e.var(u,!0),h(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,UR.checkStrictMode)(o,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,g=>{e.if((0,Wy._)`${(0,LR.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:ZR.Type.Str},u),o.opts.unevaluated&&d!==!0?e.assign((0,Wy._)`${d}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,Wy.not)(u),()=>e.break())})})}}};RS.default=GX});var VR=C(MS=>{"use strict";Object.defineProperty(MS,"__esModule",{value:!0});var HX=Je(),XX={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,HX.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};MS.default=XX});var qR=C(jS=>{"use strict";Object.defineProperty(jS,"__esModule",{value:!0});var KX=Mn(),JX={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:KX.validateUnion,error:{message:"must match a schema in anyOf"}};jS.default=JX});var BR=C(DS=>{"use strict";Object.defineProperty(DS,"__esModule",{value:!0});var Gy=Oe(),YX=Je(),QX={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Gy._)`{passingSchemas: ${t.passing}}`},eK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:QX,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){o.forEach((u,d)=>{let f;(0,YX.alwaysValidSchema)(i,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Gy._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Gy._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Gy.Name)})})}}};DS.default=eK});var WR=C(LS=>{"use strict";Object.defineProperty(LS,"__esModule",{value:!0});var tK=Je(),rK={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((o,s)=>{if((0,tK.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:s},i);t.ok(i),t.mergeEvaluated(a)})}};LS.default=rK});var XR=C(US=>{"use strict";Object.defineProperty(US,"__esModule",{value:!0});var Hy=Oe(),HR=Je(),nK={message:({params:t})=>(0,Hy.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Hy._)`{failingKeyword: ${t.ifClause}}`},iK={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nK,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,HR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=GR(n,"then"),o=GR(n,"else");if(!i&&!o)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),i&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,Hy.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let f=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(f,s),d?e.assign(d,(0,Hy._)`${u}`):t.setParams({ifClause:u})}}}};function GR(t,e){let r=t.schema[e];return r!==void 0&&!(0,HR.alwaysValidSchema)(t,r)}US.default=iK});var KR=C(ZS=>{"use strict";Object.defineProperty(ZS,"__esModule",{value:!0});var oK=Je(),sK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,oK.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ZS.default=sK});var JR=C(FS=>{"use strict";Object.defineProperty(FS,"__esModule",{value:!0});var aK=$S(),cK=ER(),lK=SS(),uK=TR(),dK=AR(),pK=CR(),fK=RR(),mK=NS(),hK=DR(),gK=FR(),yK=VR(),_K=qR(),bK=BR(),vK=WR(),wK=XR(),xK=KR();function kK(t=!1){let e=[yK.default,_K.default,bK.default,vK.default,wK.default,xK.default,fK.default,mK.default,pK.default,hK.default,gK.default];return t?e.push(cK.default,uK.default):e.push(aK.default,lK.default),e.push(dK.default),e}FS.default=kK});var YR=C(VS=>{"use strict";Object.defineProperty(VS,"__esModule",{value:!0});var Mt=Oe(),$K={message:({schemaCode:t})=>(0,Mt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Mt._)`{format: ${t}}`},SK={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$K,code(t,e){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=r.const("fDef",(0,Mt._)`${h}[${s}]`),g=r.let("fType"),y=r.let("format");r.if((0,Mt._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,Mt._)`${m}.type || "string"`).assign(y,(0,Mt._)`${m}.validate`),()=>r.assign(g,(0,Mt._)`"string"`).assign(y,m)),t.fail$data((0,Mt.or)(b(),$()));function b(){return c.strictSchema===!1?Mt.nil:(0,Mt._)`${s} && !${y}`}function $(){let R=u.$async?(0,Mt._)`(${m}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Mt._)`${y}(${n})`,T=(0,Mt._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${n}))`;return(0,Mt._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function p(){let h=d.formats[o];if(!h){b();return}if(h===!0)return;let[m,g,y]=$(h);m===e&&t.pass(R());function b(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function $(T){let P=T instanceof RegExp?(0,Mt.regexpCode)(T):c.code.formats?(0,Mt._)`${c.code.formats}${(0,Mt.getProperty)(o)}`:void 0,F=r.scopeValue("formats",{key:o,ref:T,code:P});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Mt._)`${F}.validate`]:["string",T,F]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Mt._)`await ${y}(${n})`}return typeof g=="function"?(0,Mt._)`${y}(${n})`:(0,Mt._)`${y}.test(${n})`}}}};VS.default=SK});var QR=C(qS=>{"use strict";Object.defineProperty(qS,"__esModule",{value:!0});var IK=YR(),EK=[IK.default];qS.default=EK});var eM=C(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.contentVocabulary=Iu.metadataVocabulary=void 0;Iu.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Iu.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rM=C(BS=>{"use strict";Object.defineProperty(BS,"__esModule",{value:!0});var PK=lR(),TK=kR(),AK=JR(),zK=QR(),tM=eM(),NK=[PK.default,TK.default,(0,AK.default)(),zK.default,tM.metadataVocabulary,tM.contentVocabulary];BS.default=NK});var nM=C(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});Af.DiscrError=void 0;var CK;(function(t){t.Tag="tag",t.Mapping="mapping"})(CK=Af.DiscrError||(Af.DiscrError={}))});var oM=C(GS=>{"use strict";Object.defineProperty(GS,"__esModule",{value:!0});var Eu=Oe(),WS=nM(),iM=Cy(),OK=Je(),RK={message:({params:{discrError:t,tagName:e}})=>t===WS.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Eu._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},MK={keyword:"discriminator",type:"object",schemaType:"object",error:RK,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:o}=t,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Eu._)`${r}${(0,Eu.getProperty)(a)}`);e.if((0,Eu._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:WS.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Eu._)`${l} === ${h}`),e.assign(c,d(p[h]));e.else(),t.error(!1,{discrError:WS.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,Eu.Name),h}function f(){var p;let h={},m=y(i),g=!0;for(let R=0;R<s.length;R++){let T=s[R];T?.$ref&&!(0,OK.schemaHasRulesButRef)(T,o.self.RULES)&&(T=iM.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,T?.$ref),T instanceof iM.SchemaEnv&&(T=T.schema));let P=(p=T?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(T)),b(P,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return h;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function b(R,T){if(R.const)$(R.const,T);else if(R.enum)for(let P of R.enum)$(P,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(R,T){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=T}}}};GS.default=MK});var sM=C((Xxe,jK)=>{jK.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var lM=C((At,cM)=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.MissingRefError=At.ValidationError=At.CodeGen=At.Name=At.nil=At.stringify=At.str=At._=At.KeywordCxt=void 0;var DK=nR(),LK=rM(),UK=oM(),aM=sM(),ZK=["/properties"],Xy="http://json-schema.org/draft-07/schema",Ky=class extends DK.default{_addVocabularies(){super._addVocabularies(),LK.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(UK.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(aM,ZK):aM;this.addMetaSchema(e,Xy,!1),this.refs["http://json-schema.org/schema"]=Xy}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xy)?Xy:void 0)}};cM.exports=At=Ky;Object.defineProperty(At,"__esModule",{value:!0});At.default=Ky;var FK=yf();Object.defineProperty(At,"KeywordCxt",{enumerable:!0,get:function(){return FK.KeywordCxt}});var Pu=Oe();Object.defineProperty(At,"_",{enumerable:!0,get:function(){return Pu._}});Object.defineProperty(At,"str",{enumerable:!0,get:function(){return Pu.str}});Object.defineProperty(At,"stringify",{enumerable:!0,get:function(){return Pu.stringify}});Object.defineProperty(At,"nil",{enumerable:!0,get:function(){return Pu.nil}});Object.defineProperty(At,"Name",{enumerable:!0,get:function(){return Pu.Name}});Object.defineProperty(At,"CodeGen",{enumerable:!0,get:function(){return Pu.CodeGen}});var VK=Ay();Object.defineProperty(At,"ValidationError",{enumerable:!0,get:function(){return VK.default}});var qK=zy();Object.defineProperty(At,"MissingRefError",{enumerable:!0,get:function(){return qK.default}})});var uM=C(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.formatLimitDefinition=void 0;var BK=lM(),di=Oe(),Ss=di.operators,Jy={formatMaximum:{okStr:"<=",ok:Ss.LTE,fail:Ss.GT},formatMinimum:{okStr:">=",ok:Ss.GTE,fail:Ss.LT},formatExclusiveMaximum:{okStr:"<",ok:Ss.LT,fail:Ss.GTE},formatExclusiveMinimum:{okStr:">",ok:Ss.GT,fail:Ss.LTE}},WK={message:({keyword:t,schemaCode:e})=>(0,di.str)`should be ${Jy[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,di._)`{comparison: ${Jy[t].okStr}, limit: ${e}}`};Tu.formatLimitDefinition={keyword:Object.keys(Jy),type:"string",schemaType:"string",$data:!0,error:WK,code(t){let{gen:e,data:r,schemaCode:n,keyword:i,it:o}=t,{opts:s,self:a}=o;if(!s.validateFormats)return;let c=new BK.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,di._)`${f}[${c.schemaCode}]`);t.fail$data((0,di.or)((0,di._)`typeof ${p} != "object"`,(0,di._)`${p} instanceof RegExp`,(0,di._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,di._)`${s.code.formats}${(0,di.getProperty)(f)}`:void 0});t.fail$data(d(h))}function d(f){return(0,di._)`${f}.compare(${r}, ${n}) ${Jy[i].fail} 0`}},dependencies:["format"]};var GK=t=>(t.addKeyword(Tu.formatLimitDefinition),t);Tu.default=GK});var mM=C((zf,fM)=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var Au=HC(),HK=uM(),HS=Oe(),dM=new HS.Name("fullFormats"),XK=new HS.Name("fastFormats"),XS=(t,e={keywords:!0})=>{if(Array.isArray(e))return pM(t,e,Au.fullFormats,dM),t;let[r,n]=e.mode==="fast"?[Au.fastFormats,XK]:[Au.fullFormats,dM],i=e.formats||Au.formatNames;return pM(t,i,r,n),e.keywords&&(0,HK.default)(t),t};XS.get=(t,e="full")=>{let n=(e==="fast"?Au.fastFormats:Au.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function pM(t,e,r,n){var i,o;(i=(o=t.opts.code).formats)!==null&&i!==void 0||(o.formats=(0,HS._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)t.addFormat(s,r[s])}fM.exports=zf=XS;Object.defineProperty(zf,"__esModule",{value:!0});zf.default=XS});var FD=C((rze,ZD)=>{"use strict";var Z_=Object.prototype.hasOwnProperty,UD=Object.prototype.toString,OD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,MD=function(e){return typeof Array.isArray=="function"?Array.isArray(e):UD.call(e)==="[object Array]"},jD=function(e){if(!e||UD.call(e)!=="[object Object]")return!1;var r=Z_.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Z_.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!r&&!n)return!1;var i;for(i in e);return typeof i>"u"||Z_.call(e,i)},DD=function(e,r){OD&&r.name==="__proto__"?OD(e,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0}):e[r.name]=r.newValue},LD=function(e,r){if(r==="__proto__")if(Z_.call(e,r)){if(RD)return RD(e,r).value}else return;return e[r]};ZD.exports=function t(){var e,r,n,i,o,s,a=arguments[0],c=1,l=arguments.length,u=!1;for(typeof a=="boolean"&&(u=a,a=arguments[1]||{},c=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});c<l;++c)if(e=arguments[c],e!=null)for(r in e)n=LD(a,r),i=LD(e,r),a!==i&&(u&&i&&(jD(i)||(o=MD(i)))?(o?(o=!1,s=n&&MD(n)?n:[]):s=n&&jD(n)?n:{},DD(a,{name:r,newValue:t(u,s,i)})):typeof i<"u"&&DD(a,{name:r,newValue:i}));return a}});function se(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function I(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var lb=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return lb=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Qu(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ed=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var X=class extends Error{},Bt=class t extends X{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Co({message:n,cause:ed(r)});let o=r?.error;return e===400?new mc(e,o,n,i):e===401?new hc(e,o,n,i):e===403?new gc(e,o,n,i):e===404?new yc(e,o,n,i):e===409?new _c(e,o,n,i):e===422?new bc(e,o,n,i):e===429?new vc(e,o,n,i):e>=500?new wc(e,o,n,i):new t(e,o,n,i)}},qt=class extends Bt{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Co=class extends Bt{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Oo=class extends Co{constructor({message:e}={}){super({message:e??"Request timed out."})}},mc=class extends Bt{},hc=class extends Bt{},gc=class extends Bt{},yc=class extends Bt{},_c=class extends Bt{},bc=class extends Bt{},vc=class extends Bt{},wc=class extends Bt{},xc=class extends X{constructor(){super("Could not parse response content as the length limit was reached")}},kc=class extends X{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},hi=class extends Error{constructor(e){super(e)}};var _4=/^[a-z][a-z0-9+.-]*:/i,kE=t=>_4.test(t),br=t=>(br=Array.isArray,br(t)),ub=br;function db(t){return typeof t!="object"?{}:t??{}}function $E(t){if(!t)return!0;for(let e in t)return!1;return!0}function SE(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function td(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var IE=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new X(`${t} must be an integer`);if(e<0)throw new X(`${t} must be a positive integer`);return e};var EE=t=>{try{return JSON.parse(t)}catch{return}};var gi=t=>new Promise(e=>setTimeout(e,t));var Ro="6.22.0";var zE=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function b4(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var v4=()=>{let t=b4();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ro,"X-Stainless-OS":TE(Deno.build.os),"X-Stainless-Arch":PE(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ro,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ro,"X-Stainless-OS":TE(globalThis.process.platform??"unknown"),"X-Stainless-Arch":PE(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=w4();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ro,"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":Ro,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function w4(){if(typeof navigator>"u"||!navigator)return null;let t=[{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/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var PE=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",TE=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),AE,NE=()=>AE??(AE=v4());function CE(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pb(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function zm(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return pb({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function fb(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function OE(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var RE=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Nm="RFC3986",mb=t=>String(t),Cm={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:mb},hb="RFC1738";var Om=(t,e)=>(Om=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Om(t,e)),yi=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var gb=1024,ME=(t,e,r,n,i)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<o.length;a+=gb){let c=o.length>=gb?o.slice(a,a+gb):o,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===hb&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=yi[d];continue}if(d<2048){l[l.length]=yi[192|d>>6]+yi[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=yi[224|d>>12]+yi[128|d>>6&63]+yi[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=yi[240|d>>18]+yi[128|d>>12&63]+yi[128|d>>6&63]+yi[128|d&63]}s+=l.join("")}return s};function jE(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function yb(t,e){if(br(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var LE={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},UE=function(t,e){Array.prototype.push.apply(t,br(e)?e:[e])},DE,Wt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ME,encodeValuesOnly:!1,format:Nm,formatter:mb,indices:!1,serializeDate(t){return(DE??(DE=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function $4(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var _b={};function ZE(t,e,r,n,i,o,s,a,c,l,u,d,f,p,h,m,g,y){let b=t,$=y,R=0,T=!1;for(;($=$.get(_b))!==void 0&&!T;){let H=$.get(t);if(R+=1,typeof H<"u"){if(H===R)throw new RangeError("Cyclic object value");T=!0}typeof $.get(_b)>"u"&&(R=0)}if(typeof l=="function"?b=l(e,b):b instanceof Date?b=f?.(b):r==="comma"&&br(b)&&(b=yb(b,function(H){return H instanceof Date?f?.(H):H})),b===null){if(o)return c&&!m?c(e,Wt.encoder,g,"key",p):e;b=""}if($4(b)||jE(b)){if(c){let H=m?e:c(e,Wt.encoder,g,"key",p);return[h?.(H)+"="+h?.(c(b,Wt.encoder,g,"value",p))]}return[h?.(e)+"="+h?.(String(b))]}let P=[];if(typeof b>"u")return P;let F;if(r==="comma"&&br(b))m&&c&&(b=yb(b,c)),F=[{value:b.length>0?b.join(",")||null:void 0}];else if(br(l))F=l;else{let H=Object.keys(b);F=u?H.sort(u):H}let ce=a?String(e).replace(/\./g,"%2E"):String(e),te=n&&br(b)&&b.length===1?ce+"[]":ce;if(i&&br(b)&&b.length===0)return te+"[]";for(let H=0;H<F.length;++H){let _e=F[H],he=typeof _e=="object"&&typeof _e.value<"u"?_e.value:b[_e];if(s&&he===null)continue;let Y=d&&a?_e.replace(/\./g,"%2E"):_e,pe=br(b)?typeof r=="function"?r(te,Y):te:te+(d?"."+Y:"["+Y+"]");y.set(t,R);let fe=new WeakMap;fe.set(_b,y),UE(P,ZE(he,pe,r,n,i,o,s,a,r==="comma"&&m&&br(b)?null:c,l,u,d,f,p,h,m,g,fe))}return P}function S4(t=Wt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||Wt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Nm;if(typeof t.format<"u"){if(!Om(Cm,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Cm[r],i=Wt.filter;(typeof t.filter=="function"||br(t.filter))&&(i=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in LE?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=Wt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Wt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Wt.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Wt.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Wt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Wt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Wt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Wt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Wt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Wt.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Wt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Wt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Wt.strictNullHandling}}function bb(t,e={}){let r=t,n=S4(e),i,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):br(n.filter)&&(o=n.filter,i=o);let s=[];if(typeof r!="object"||r===null)return"";let a=LE[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let l=new WeakMap;for(let f=0;f<i.length;++f){let p=i[f];n.skipNulls&&r[p]===null||UE(s,ZE(r[p],p,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let u=s.join(n.delimiter),d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function qE(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var FE;function $c(t){let e;return(FE??(e=new globalThis.TextEncoder,FE=e.encode.bind(e)))(t)}var VE;function vb(t){let e;return(VE??(e=new globalThis.TextDecoder,VE=e.decode.bind(e)))(t)}var sn,an,Ls=class{constructor(){sn.set(this,void 0),an.set(this,void 0),se(this,sn,new Uint8Array,"f"),se(this,an,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?$c(e):e;se(this,sn,qE([I(this,sn,"f"),r]),"f");let n=[],i;for(;(i=E4(I(this,sn,"f"),I(this,an,"f")))!=null;){if(i.carriage&&I(this,an,"f")==null){se(this,an,i.index,"f");continue}if(I(this,an,"f")!=null&&(i.index!==I(this,an,"f")+1||i.carriage)){n.push(vb(I(this,sn,"f").subarray(0,I(this,an,"f")-1))),se(this,sn,I(this,sn,"f").subarray(I(this,an,"f")),"f"),se(this,an,null,"f");continue}let o=I(this,an,"f")!==null?i.preceding-1:i.preceding,s=vb(I(this,sn,"f").subarray(0,o));n.push(s),se(this,sn,I(this,sn,"f").subarray(i.index),"f"),se(this,an,null,"f")}return n}flush(){return I(this,sn,"f").length?this.decode(`
16
+ `):[]}};sn=new WeakMap,an=new WeakMap;Ls.NEWLINE_CHARS=new Set([`
17
+ `,"\r"]);Ls.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function E4(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function BE(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Mm={off:0,error:200,warn:300,info:400,debug:500},wb=(t,e,r)=>{if(t){if(SE(Mm,t))return t;Ot(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Mm))}`)}};function rd(){}function Rm(t,e,r){return!e||Mm[t]>Mm[r]?rd:e[t].bind(e)}var P4={error:rd,warn:rd,info:rd,debug:rd},WE=new WeakMap;function Ot(t){let e=t.logger,r=t.logLevel??"off";if(!e)return P4;let n=WE.get(e);if(n&&n[0]===r)return n[1];let i={error:Rm("error",e,r),warn:Rm("warn",e,r),info:Rm("info",e,r),debug:Rm("debug",e,r)};return WE.set(e,[r,i]),i}var qi=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var nd,_i=class t{constructor(e,r,n){this.iterator=e,nd.set(this,void 0),this.controller=r,se(this,nd,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?Ot(n):console;async function*s(){if(i)throw new X("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of T4(e,r))if(!a){if(c.data.startsWith("[DONE]")){a=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let l;try{l=JSON.parse(c.data)}catch(u){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),u}if(l&&l.error)throw new Bt(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(c.data)}catch(u){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),u}if(c.event=="error")throw new Bt(void 0,l.error,l.message,void 0);yield{event:c.event,data:l}}}a=!0}catch(c){if(Qu(c))return;throw c}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new Ls,c=fb(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*s(){if(i)throw new X("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Qu(c))return;throw c}finally{a||r.abort()}}return new t(s,r,n)}[(nd=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,I(this,nd,"f")),new t(()=>i(r),this.controller,I(this,nd,"f"))]}toReadableStream(){let e=this,r;return pb({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=$c(JSON.stringify(i)+`
18
+ `);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*T4(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new X("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new X("Attempted to iterate over a response with no body");let r=new xb,n=new Ls,i=fb(t.body);for await(let o of A4(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*A4(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?$c(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=BE(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var xb=class{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 o={event:this.event,data:this.data.join(`
19
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=z4(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function z4(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function jm(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return Ot(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):_i.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return kb(f,r)}return await r.text()})();return Ot(t).debug(`[${n}] response parsed`,qi({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function kb(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var id,Us=class t extends Promise{constructor(e,r,n=jm){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,id.set(this,void 0),se(this,id,e,"f")}_thenUnwrap(e){return new t(I(this,id,"f"),this.responsePromise,async(r,n)=>kb(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(I(this,id,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};id=new WeakMap;var Dm,od=class{constructor(e,r,n,i){Dm.set(this,void 0),se(this,Dm,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new X("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await I(this,Dm,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Dm=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},sd=class extends Us{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await jm(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},bi=class extends od{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},$e=class extends od{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...db(this.options.query),after:r}}:null}},Bi=class extends od{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...db(this.options.query),after:e}}:null}};var Ib=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Sc(t,e,r){return Ib(),new File(t,e??"unknown_file",r)}function ad(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Lm=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Wi=async(t,e)=>$b(t.body)?{...t,body:await HE(t.body,e)}:t,Wn=async(t,e)=>({...t,body:await HE(t.body,e)}),GE=new WeakMap;function C4(t){let e=typeof t=="function"?t:t.fetch,r=GE.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return GE.set(e,n),n}var HE=async(t,e)=>{if(!await C4(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,i])=>Sb(r,n,i))),r},XE=t=>t instanceof Blob&&"name"in t,O4=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Lm(t)||XE(t)),$b=t=>{if(O4(t))return!0;if(Array.isArray(t))return t.some($b);if(t&&typeof t=="object"){for(let e in t)if($b(t[e]))return!0}return!1},Sb=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Sc([await r.blob()],ad(r)));else if(Lm(r))t.append(e,Sc([await new Response(zm(r)).blob()],ad(r)));else if(XE(r))t.append(e,r,ad(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Sb(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,i])=>Sb(t,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var KE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",R4=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&KE(t),M4=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Um(t,e,r){if(Ib(),t=await t,R4(t))return t instanceof File?t:Sc([await t.arrayBuffer()],t.name);if(M4(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Sc(await Eb(i),e,r)}let n=await Eb(t);if(e||(e=ad(t)),!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return Sc(n,e,r)}async function Eb(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(KE(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Lm(t))for await(let r of t)e.push(...await Eb(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${j4(t)}`)}return e}function j4(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var M=class{constructor(e){this._client=e}};function YE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var JE=Object.freeze(Object.create(null)),L4=(t=YE)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,f)=>{/[?#]/.test(d)&&(i=!0);let p=n[f],h=(i?encodeURIComponent:t)(""+p);return f!==n.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??JE)??JE)?.toString)&&(h=p+"",o.push({start:u.length+d.length,length:h.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===n.length?"":h)},""),a=s.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((f,p)=>{let h=" ".repeat(p.start-u),m="^".repeat(p.length);return u=p.start+p.length,f+h+m},"");throw new X(`Path parameters result in path with invalid segments:
20
+ ${o.map(f=>f.error).join(`
21
+ `)}
22
+ ${s}
23
+ ${d}`)}return s},z=L4(YE);var Zs=class extends M{list(e,r={},n){return this._client.getAPIList(z`/chat/completions/${e}/messages`,$e,{query:r,...n})}};function cd(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ld(t){return t?.$brand==="auto-parseable-response-format"}function Fs(t){return t?.$brand==="auto-parseable-tool"}function QE(t,e){return!e||!Pb(e)?{...t,choices:t.choices.map(r=>(t1(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:ud(t,e)}function ud(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new xc;if(n.finish_reason==="content_filter")throw new kc;return t1(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>V4(e,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?F4(e,n.message.content):null}}});return{...t,choices:r}}function F4(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function V4(t,e){let r=t.tools?.find(n=>cd(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Fs(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function e1(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>cd(n)&&n.function?.name===e.function.name);return cd(r)&&(Fs(r)||r?.function.strict||!1)}function Pb(t){return ld(t.response_format)?!0:t.tools?.some(e=>Fs(e)||e.type==="function"&&e.function.strict===!0)??!1}function t1(t){for(let e of t||[])if(e.type!=="function")throw new X(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function r1(t){for(let e of t??[]){if(e.type!=="function")throw new X(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new X(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Ic=t=>t?.role==="assistant",Tb=t=>t?.role==="tool";var Ab,Zm,Fm,dd,pd,Vm,fd,Gi,md,qm,Bm,Ec,n1,Mo=class{constructor(){Ab.add(this),this.controller=new AbortController,Zm.set(this,void 0),Fm.set(this,()=>{}),dd.set(this,()=>{}),pd.set(this,void 0),Vm.set(this,()=>{}),fd.set(this,()=>{}),Gi.set(this,{}),md.set(this,!1),qm.set(this,!1),Bm.set(this,!1),Ec.set(this,!1),se(this,Zm,new Promise((e,r)=>{se(this,Fm,e,"f"),se(this,dd,r,"f")}),"f"),se(this,pd,new Promise((e,r)=>{se(this,Vm,e,"f"),se(this,fd,r,"f")}),"f"),I(this,Zm,"f").catch(()=>{}),I(this,pd,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},I(this,Ab,"m",n1).bind(this))},0)}_connected(){this.ended||(I(this,Fm,"f").call(this),this._emit("connect"))}get ended(){return I(this,md,"f")}get errored(){return I(this,qm,"f")}get aborted(){return I(this,Bm,"f")}abort(){this.controller.abort()}on(e,r){return(I(this,Gi,"f")[e]||(I(this,Gi,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=I(this,Gi,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(I(this,Gi,"f")[e]||(I(this,Gi,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{se(this,Ec,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){se(this,Ec,!0,"f"),await I(this,pd,"f")}_emit(e,...r){if(I(this,md,"f"))return;e==="end"&&(se(this,md,!0,"f"),I(this,Vm,"f").call(this));let n=I(this,Gi,"f")[e];if(n&&(I(this,Gi,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!I(this,Ec,"f")&&!n?.length&&Promise.reject(i),I(this,dd,"f").call(this,i),I(this,fd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!I(this,Ec,"f")&&!n?.length&&Promise.reject(i),I(this,dd,"f").call(this,i),I(this,fd,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Zm=new WeakMap,Fm=new WeakMap,dd=new WeakMap,pd=new WeakMap,Vm=new WeakMap,fd=new WeakMap,Gi=new WeakMap,md=new WeakMap,qm=new WeakMap,Bm=new WeakMap,Ec=new WeakMap,Ab=new WeakSet,n1=function(e){if(se(this,qm,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new qt),e instanceof qt)return se(this,Bm,!0,"f"),this._emit("abort",e);if(e instanceof X)return this._emit("error",e);if(e instanceof Error){let r=new X(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new X(String(e)))};function i1(t){return typeof t.parse=="function"}var zr,zb,Wm,Nb,Cb,Ob,o1,s1,q4=10,Pc=class extends Mo{constructor(){super(...arguments),zr.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Tb(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ic(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new X("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),I(this,zr,"m",zb).call(this)}async finalMessage(){return await this.done(),I(this,zr,"m",Wm).call(this)}async finalFunctionToolCall(){return await this.done(),I(this,zr,"m",Nb).call(this)}async finalFunctionToolCallResult(){return await this.done(),I(this,zr,"m",Cb).call(this)}async totalUsage(){return await this.done(),I(this,zr,"m",Ob).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=I(this,zr,"m",Wm).call(this);r&&this._emit("finalMessage",r);let n=I(this,zr,"m",zb).call(this);n&&this._emit("finalContent",n);let i=I(this,zr,"m",Nb).call(this);i&&this._emit("finalFunctionToolCall",i);let o=I(this,zr,"m",Cb).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",I(this,zr,"m",Ob).call(this))}async _createChatCompletion(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),I(this,zr,"m",o1).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ud(o,r))}async _runChatCompletion(e,r,n){for(let i of r.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){let i="tool",{tool_choice:o="auto",stream:s,...a}=r,c=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:l=q4}=n||{},u=r.tools.map(p=>{if(Fs(p)){if(!p.$callback)throw new X("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),d={};for(let p of u)p.type==="function"&&(d[p.function.name||p.function.function.name]=p.function);let f="tools"in r?u.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(let p of r.messages)this._addMessage(p,!1);for(let p=0;p<l;++p){let m=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!m)throw new X("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(let g of m.tool_calls){if(g.type!=="function")continue;let y=g.id,{name:b,arguments:$}=g.function,R=d[b];if(R){if(c&&c!==b){let ce=`Invalid tool_call: ${JSON.stringify(b)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,tool_call_id:y,content:ce});continue}}else{let ce=`Invalid tool_call: ${JSON.stringify(b)}. Available options are: ${Object.keys(d).map(te=>JSON.stringify(te)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:y,content:ce});continue}let T;try{T=i1(R)?await R.parse($):$}catch(ce){let te=ce instanceof Error?ce.message:String(ce);this._addMessage({role:i,tool_call_id:y,content:te});continue}let P=await R.function(T,this),F=I(this,zr,"m",s1).call(this,P);if(this._addMessage({role:i,tool_call_id:y,content:F}),c)return}}}};zr=new WeakSet,zb=function(){return I(this,zr,"m",Wm).call(this).content??null},Wm=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Ic(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new X("stream ended without producing a ChatCompletionMessage with role=assistant")},Nb=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Ic(r)&&r?.tool_calls?.length)return r.tool_calls.filter(n=>n.type==="function").at(-1)?.function}},Cb=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Tb(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===r.tool_call_id)))return r.content}},Ob=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},o1=function(e){if(e.n!=null&&e.n>1)throw new X("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},s1=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var hd=class t extends Pc{static runTools(e,r,n){let i=new t,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}_addMessage(e,r=!0){super._addMessage(e,r),Ic(e)&&e.content&&this._emit("content",e.content)}};var Kt={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Rb=class extends Error{},Mb=class extends Error{};function B4(t,e=Kt.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return W4(t.trim(),e)}var W4=(t,e)=>{let r=t.length,n=0,i=f=>{throw new Rb(`${f} at position ${n}`)},o=f=>{throw new Mb(`${f} at position ${n}`)},s=()=>(d(),n>=r&&i("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||Kt.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||Kt.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||Kt.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||Kt.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||Kt.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||Kt.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):u()),a=()=>{let f=n,p=!1;for(n++;n<r&&(t[n]!=='"'||p&&t[n-1]==="\\");)p=t[n]==="\\"?!p:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(f,++n-Number(p)))}catch(h){o(String(h))}else if(Kt.STR&e)try{return JSON.parse(t.substring(f,n-Number(p))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},c=()=>{n++,d();let f={};try{for(;t[n]!=="}";){if(d(),n>=r&&Kt.OBJ&e)return f;let p=a();d(),n++;try{let h=s();Object.defineProperty(f,p,{value:h,writable:!0,enumerable:!0,configurable:!0})}catch(h){if(Kt.OBJ&e)return f;throw h}d(),t[n]===","&&n++}}catch{if(Kt.OBJ&e)return f;i("Expected '}' at end of object")}return n++,f},l=()=>{n++;let f=[];try{for(;t[n]!=="]";)f.push(s()),d(),t[n]===","&&n++}catch{if(Kt.ARR&e)return f;i("Expected ']' at end of array")}return n++,f},u=()=>{if(n===0){t==="-"&&Kt.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t)}catch(p){if(Kt.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(p))}}let f=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(Kt.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(t.substring(f,n))}catch{t.substring(f,n)==="-"&&Kt.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(h){o(String(h))}}},d=()=>{for(;n<r&&`
24
+ \r `.includes(t[n]);)n++};return s()},jb=t=>B4(t,Kt.ALL^Kt.NUM);var Gt,Hi,Tc,jo,Db,Gm,Lb,Ub,Zb,Hm,Fb,a1,Vs=class t extends Pc{constructor(e){super(),Gt.add(this),Hi.set(this,void 0),Tc.set(this,void 0),jo.set(this,void 0),se(this,Hi,e,"f"),se(this,Tc,[],"f")}get currentChatCompletionSnapshot(){return I(this,jo,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let i=new t(r);return i._run(()=>i._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,r,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),I(this,Gt,"m",Db).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let s of o)I(this,Gt,"m",Lb).call(this,s);if(o.controller.signal?.aborted)throw new qt;return this._addChatCompletion(I(this,Gt,"m",Hm).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),I(this,Gt,"m",Db).call(this),this._connected();let i=_i.fromReadableStream(e,this.controller),o;for await(let s of i)o&&o!==s.id&&this._addChatCompletion(I(this,Gt,"m",Hm).call(this)),I(this,Gt,"m",Lb).call(this,s),o=s.id;if(i.controller.signal?.aborted)throw new qt;return this._addChatCompletion(I(this,Gt,"m",Hm).call(this))}[(Hi=new WeakMap,Tc=new WeakMap,jo=new WeakMap,Gt=new WeakSet,Db=function(){this.ended||se(this,jo,void 0,"f")},Gm=function(r){let n=I(this,Tc,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},I(this,Tc,"f")[r.index]=n,n)},Lb=function(r){if(this.ended)return;let n=I(this,Gt,"m",a1).call(this,r);this._emit("chunk",r,n);for(let i of r.choices){let o=n.choices[i.index];i.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",i.delta.content,o.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),i.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:o.message.refusal}),i.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:o.logprobs?.content??[]}),i.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let s=I(this,Gt,"m",Gm).call(this,o);o.finish_reason&&(I(this,Gt,"m",Zb).call(this,o),s.current_tool_call_index!=null&&I(this,Gt,"m",Ub).call(this,o,s.current_tool_call_index));for(let a of i.delta.tool_calls??[])s.current_tool_call_index!==a.index&&(I(this,Gt,"m",Zb).call(this,o),s.current_tool_call_index!=null&&I(this,Gt,"m",Ub).call(this,o,s.current_tool_call_index)),s.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let c=o.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},Ub=function(r,n){if(I(this,Gt,"m",Gm).call(this,r).done_tool_calls.has(n))return;let o=r.message.tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let s=I(this,Hi,"f")?.tools?.find(a=>cd(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:Fs(s)?s.$parseRaw(o.function.arguments):s?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Zb=function(r){let n=I(this,Gt,"m",Gm).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=I(this,Gt,"m",Fb).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Hm=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");let r=I(this,jo,"f");if(!r)throw new X("request ended without sending any chunks");return se(this,jo,void 0,"f"),se(this,Tc,[],"f"),G4(r,I(this,Hi,"f"))},Fb=function(){let r=I(this,Hi,"f")?.response_format;return ld(r)?r:null},a1=function(r){var n,i,o,s;let a=I(this,jo,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=se(this,jo,{...l,choices:[]},"f");for(let{delta:u,finish_reason:d,index:f,logprobs:p=null,...h}of r.choices){let m=a.choices[f];if(m||(m=a.choices[f]={finish_reason:d,index:f,message:{},logprobs:p,...h}),p)if(!m.logprobs)m.logprobs=Object.assign({},p);else{let{content:P,refusal:F,...ce}=p;Object.assign(m.logprobs,ce),P&&((n=m.logprobs).content??(n.content=[]),m.logprobs.content.push(...P)),F&&((i=m.logprobs).refusal??(i.refusal=[]),m.logprobs.refusal.push(...F))}if(d&&(m.finish_reason=d,I(this,Hi,"f")&&Pb(I(this,Hi,"f")))){if(d==="length")throw new xc;if(d==="content_filter")throw new kc}if(Object.assign(m,h),!u)continue;let{content:g,refusal:y,function_call:b,role:$,tool_calls:R,...T}=u;if(Object.assign(m.message,T),y&&(m.message.refusal=(m.message.refusal||"")+y),$&&(m.message.role=$),b&&(m.message.function_call?(b.name&&(m.message.function_call.name=b.name),b.arguments&&((o=m.message.function_call).arguments??(o.arguments=""),m.message.function_call.arguments+=b.arguments)):m.message.function_call=b),g&&(m.message.content=(m.message.content||"")+g,!m.message.refusal&&I(this,Gt,"m",Fb).call(this)&&(m.message.parsed=jb(m.message.content))),R){m.message.tool_calls||(m.message.tool_calls=[]);for(let{index:P,id:F,type:ce,function:te,...H}of R){let _e=(s=m.message.tool_calls)[P]??(s[P]={});Object.assign(_e,H),F&&(_e.id=F),ce&&(_e.type=ce),te&&(_e.function??(_e.function={name:te.name??"",arguments:""})),te?.name&&(_e.function.name=te.name),te?.arguments&&(_e.function.arguments+=te.arguments,e1(I(this,Hi,"f"),_e)&&(_e.function.parsed_arguments=jb(_e.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new _i(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function G4(t,e){let{id:r,choices:n,created:i,model:o,system_fingerprint:s,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:u,index:d,logprobs:f,...p})=>{if(!u)throw new X(`missing finish_reason for choice ${d}`);let{content:h=null,function_call:m,tool_calls:g,...y}=l,b=l.role;if(!b)throw new X(`missing role for choice ${d}`);if(m){let{arguments:$,name:R}=m;if($==null)throw new X(`missing function_call.arguments for choice ${d}`);if(!R)throw new X(`missing function_call.name for choice ${d}`);return{...p,message:{content:h,function_call:{arguments:$,name:R},role:b,refusal:l.refusal??null},finish_reason:u,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:u,logprobs:f,message:{...y,role:b,content:h,refusal:l.refusal??null,tool_calls:g.map(($,R)=>{let{function:T,type:P,id:F,...ce}=$,{arguments:te,name:H,..._e}=T||{};if(F==null)throw new X(`missing choices[${d}].tool_calls[${R}].id
25
+ ${Xm(t)}`);if(P==null)throw new X(`missing choices[${d}].tool_calls[${R}].type
26
+ ${Xm(t)}`);if(H==null)throw new X(`missing choices[${d}].tool_calls[${R}].function.name
27
+ ${Xm(t)}`);if(te==null)throw new X(`missing choices[${d}].tool_calls[${R}].function.arguments
28
+ ${Xm(t)}`);return{...ce,id:F,type:P,function:{..._e,name:H,arguments:te}}})}}:{...p,message:{...y,content:h,role:b,refusal:l.refusal??null},finish_reason:u,index:d,logprobs:f}}),created:i,model:o,object:"chat.completion",...s?{system_fingerprint:s}:{}};return QE(c,e)}function Xm(t){return JSON.stringify(t)}var gd=class t extends Vs{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let i=new t(r),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,r,o)),i}};var Xi=class extends M{constructor(){super(...arguments),this.messages=new Zs(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1})}retrieve(e,r){return this._client.get(z`/chat/completions/${e}`,r)}update(e,r,n){return this._client.post(z`/chat/completions/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/chat/completions",$e,{query:e,...r})}delete(e,r){return this._client.delete(z`/chat/completions/${e}`,r)}parse(e,r){return r1(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>ud(n,e))}runTools(e,r){return e.stream?gd.runTools(this._client,e,r):hd.runTools(this._client,e,r)}stream(e,r){return Vs.createChatCompletion(this._client,e,r)}};Xi.Messages=Zs;var Do=class extends M{constructor(){super(...arguments),this.completions=new Xi(this._client)}};Do.Completions=Xi;var c1=Symbol("brand.privateNullableHeaders");function*X4(t){if(!t)return;if(c1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():ub(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=ub(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var U=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of X4(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[c1]:!0,values:e,nulls:r}};var Ac=class extends M{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:U([{Accept:"application/octet-stream"},r?.headers]),__binaryResponse:!0})}};var zc=class extends M{create(e,r){return this._client.post("/audio/transcriptions",Wn({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Nc=class extends M{create(e,r){return this._client.post("/audio/translations",Wn({body:e,...r,__metadata:{model:e.model}},this._client))}};var vi=class extends M{constructor(){super(...arguments),this.transcriptions=new zc(this._client),this.translations=new Nc(this._client),this.speech=new Ac(this._client)}};vi.Transcriptions=zc;vi.Translations=Nc;vi.Speech=Ac;var qs=class extends M{create(e,r){return this._client.post("/batches",{body:e,...r})}retrieve(e,r){return this._client.get(z`/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/batches",$e,{query:e,...r})}cancel(e,r){return this._client.post(z`/batches/${e}/cancel`,r)}};var Cc=class extends M{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(z`/assistants/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(z`/assistants/${e}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/assistants",$e,{query:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(z`/assistants/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Oc=class extends M{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Rc=class extends M{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Lo=class extends M{constructor(){super(...arguments),this.sessions=new Oc(this._client),this.transcriptionSessions=new Rc(this._client)}};Lo.Sessions=Oc;Lo.TranscriptionSessions=Rc;var Mc=class extends M{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}cancel(e,r){return this._client.post(z`/chatkit/sessions/${e}/cancel`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var jc=class extends M{retrieve(e,r){return this._client.get(z`/chatkit/threads/${e}`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}list(e={},r){return this._client.getAPIList("/chatkit/threads",Bi,{query:e,...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}delete(e,r){return this._client.delete(z`/chatkit/threads/${e}`,{...r,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}listItems(e,r={},n){return this._client.getAPIList(z`/chatkit/threads/${e}/items`,Bi,{query:r,...n,headers:U([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var Uo=class extends M{constructor(){super(...arguments),this.sessions=new Mc(this._client),this.threads=new jc(this._client)}};Uo.Sessions=Mc;Uo.Threads=jc;var Dc=class extends M{create(e,r,n){return this._client.post(z`/threads/${e}/messages`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(z`/threads/${i}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(z`/threads/${i}/messages/${e}`,{body:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(z`/threads/${e}/messages`,$e,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{thread_id:i}=r;return this._client.delete(z`/threads/${i}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Lc=class extends M{retrieve(e,r,n){let{thread_id:i,run_id:o,...s}=r;return this._client.get(z`/threads/${i}/runs/${o}/steps/${e}`,{query:s,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r,n){let{thread_id:i,...o}=r;return this._client.getAPIList(z`/threads/${i}/runs/${e}/steps`,$e,{query:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var l1=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var Zo=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var ir,Ws,Vb,wi,Km,Gn,Gs,Uc,Bs,Qm,cn,Jm,Ym,bd,yd,_d,u1,d1,p1,f1,m1,h1,g1,Ki=class extends Mo{constructor(){super(...arguments),ir.add(this),Vb.set(this,[]),wi.set(this,{}),Km.set(this,{}),Gn.set(this,void 0),Gs.set(this,void 0),Uc.set(this,void 0),Bs.set(this,void 0),Qm.set(this,void 0),cn.set(this,void 0),Jm.set(this,void 0),Ym.set(this,void 0),bd.set(this,void 0)}[(Vb=new WeakMap,wi=new WeakMap,Km=new WeakMap,Gn=new WeakMap,Gs=new WeakMap,Uc=new WeakMap,Bs=new WeakMap,Qm=new WeakMap,cn=new WeakMap,Jm=new WeakMap,Ym=new WeakMap,bd=new WeakMap,ir=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new Ws;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=_i.fromReadableStream(e,this.controller);for await(let o of i)I(this,ir,"m",yd).call(this,o);if(i.controller.signal?.aborted)throw new qt;return this._addRun(I(this,ir,"m",_d).call(this))}toReadableStream(){return new _i(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,i){let o=new Ws;return o._run(()=>o._runToolAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.submitToolOutputs(r,s,{...i,signal:this.controller.signal});this._connected();for await(let c of a)I(this,ir,"m",yd).call(this,c);if(a.controller.signal?.aborted)throw new qt;return this._addRun(I(this,ir,"m",_d).call(this))}static createThreadAssistantStream(e,r,n){let i=new Ws;return i._run(()=>i._threadAssistantStream(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,r,n,i){let o=new Ws;return o._run(()=>o._runAssistantStream(e,r,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return I(this,Jm,"f")}currentRun(){return I(this,Ym,"f")}currentMessageSnapshot(){return I(this,Gn,"f")}currentRunStepSnapshot(){return I(this,bd,"f")}async finalRunSteps(){return await this.done(),Object.values(I(this,wi,"f"))}async finalMessages(){return await this.done(),Object.values(I(this,Km,"f"))}async finalRun(){if(await this.done(),!I(this,Gs,"f"))throw Error("Final run was not received.");return I(this,Gs,"f")}async _createThreadAssistantStream(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},s=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let a of s)I(this,ir,"m",yd).call(this,a);if(s.controller.signal?.aborted)throw new qt;return this._addRun(I(this,ir,"m",_d).call(this))}async _createAssistantStream(e,r,n,i){let o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let s={...n,stream:!0},a=await e.create(r,s,{...i,signal:this.controller.signal});this._connected();for await(let c of a)I(this,ir,"m",yd).call(this,c);if(a.controller.signal?.aborted)throw new qt;return this._addRun(I(this,ir,"m",_d).call(this))}static accumulateDelta(e,r){for(let[n,i]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let o=e[n];if(o==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof o=="string"&&typeof i=="string")o+=i;else if(typeof o=="number"&&typeof i=="number")o+=i;else if(td(o)&&td(i))o=this.accumulateDelta(o,i);else if(Array.isArray(o)&&Array.isArray(i)){if(o.every(s=>typeof s=="string"||typeof s=="number")){o.push(...i);continue}for(let s of i){if(!td(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let a=s.index;if(a==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(s):o[a]=this.accumulateDelta(c,s)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,i){return await this._createAssistantStream(r,e,n,i)}async _runToolAssistantStream(e,r,n,i){return await this._createToolAssistantStream(r,e,n,i)}};Ws=Ki,yd=function(e){if(!this.ended)switch(se(this,Jm,e,"f"),I(this,ir,"m",p1).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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":I(this,ir,"m",g1).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":I(this,ir,"m",d1).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":I(this,ir,"m",u1).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},_d=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");if(!I(this,Gs,"f"))throw Error("Final run has not been received");return I(this,Gs,"f")},u1=function(e){let[r,n]=I(this,ir,"m",m1).call(this,e,I(this,Gn,"f"));se(this,Gn,r,"f"),I(this,Km,"f")[r.id]=r;for(let i of n){let o=r.content[i.index];o?.type=="text"&&this._emit("textCreated",o.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,r),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let o=i.text,s=r.content[i.index];if(s&&s.type=="text")this._emit("textDelta",o,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=I(this,Uc,"f")){if(I(this,Bs,"f"))switch(I(this,Bs,"f").type){case"text":this._emit("textDone",I(this,Bs,"f").text,I(this,Gn,"f"));break;case"image_file":this._emit("imageFileDone",I(this,Bs,"f").image_file,I(this,Gn,"f"));break}se(this,Uc,i.index,"f")}se(this,Bs,r.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(I(this,Uc,"f")!==void 0){let i=e.data.content[I(this,Uc,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,I(this,Gn,"f"));break;case"text":this._emit("textDone",i.text,I(this,Gn,"f"));break}}I(this,Gn,"f")&&this._emit("messageDone",e.data),se(this,Gn,void 0,"f")}},d1=function(e){let r=I(this,ir,"m",f1).call(this,e);switch(se(this,bd,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==I(this,Qm,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(I(this,cn,"f")&&this._emit("toolCallDone",I(this,cn,"f")),se(this,Qm,o.index,"f"),se(this,cn,r.step_details.tool_calls[o.index],"f"),I(this,cn,"f")&&this._emit("toolCallCreated",I(this,cn,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":se(this,bd,void 0,"f"),e.data.step_details.type=="tool_calls"&&I(this,cn,"f")&&(this._emit("toolCallDone",I(this,cn,"f")),se(this,cn,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},p1=function(e){I(this,Vb,"f").push(e),this._emit("event",e)},f1=function(e){switch(e.event){case"thread.run.step.created":return I(this,wi,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=I(this,wi,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=Ws.accumulateDelta(r,n.delta);I(this,wi,"f")[e.data.id]=i}return I(this,wi,"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":I(this,wi,"f")[e.data.id]=e.data;break}if(I(this,wi,"f")[e.data.id])return I(this,wi,"f")[e.data.id];throw new Error("No snapshot available")},m1=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let o of i.delta.content)if(o.index in r.content){let s=r.content[o.index];r.content[o.index]=I(this,ir,"m",h1).call(this,o,s)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},h1=function(e,r){return Ws.accumulateDelta(r,e)},g1=function(e){switch(se(this,Ym,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;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":case"thread.run.incomplete":se(this,Gs,e.data,"f"),I(this,cn,"f")&&(this._emit("toolCallDone",I(this,cn,"f")),se(this,cn,void 0,"f"));break;case"thread.run.cancelling":break}};var Hs=class extends M{constructor(){super(...arguments),this.steps=new Lc(this._client)}create(e,r,n){let{include:i,...o}=r;return this._client.post(z`/threads/${e}/runs`,{query:{include:i},body:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}retrieve(e,r,n){let{thread_id:i}=r;return this._client.get(z`/threads/${i}/runs/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{thread_id:i,...o}=r;return this._client.post(z`/threads/${i}/runs/${e}`,{body:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(z`/threads/${e}/runs`,$e,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{thread_id:i}=r;return this._client.post(z`/threads/${i}/runs/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,r,n){return Ki.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(e,r,{...n,headers:{...n?.headers,...i}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await gi(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,n){return Ki.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){let{thread_id:i,...o}=r;return this._client.post(z`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:r.stream??!1})}async submitToolOutputsAndPoll(e,r,n){let i=await this.submitToolOutputs(e,r,n);return await this.poll(i.id,r,n)}submitToolOutputsStream(e,r,n){return Ki.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};Hs.Steps=Lc;var Fo=class extends M{constructor(){super(...arguments),this.runs=new Hs(this._client),this.messages=new Dc(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(z`/threads/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(z`/threads/${e}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r){return this._client.delete(z`/threads/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Ki.createThreadAssistantStream(e,this._client.beta.threads,r)}};Fo.Runs=Hs;Fo.Messages=Dc;var Hn=class extends M{constructor(){super(...arguments),this.realtime=new Lo(this._client),this.chatkit=new Uo(this._client),this.assistants=new Cc(this._client),this.threads=new Fo(this._client)}};Hn.Realtime=Lo;Hn.ChatKit=Uo;Hn.Assistants=Cc;Hn.Threads=Fo;var Xs=class extends M{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1})}};var Zc=class extends M{retrieve(e,r,n){let{container_id:i}=r;return this._client.get(z`/containers/${i}/files/${e}/content`,{...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var Ks=class extends M{constructor(){super(...arguments),this.content=new Zc(this._client)}create(e,r,n){return this._client.post(z`/containers/${e}/files`,Wi({body:r,...n},this._client))}retrieve(e,r,n){let{container_id:i}=r;return this._client.get(z`/containers/${i}/files/${e}`,n)}list(e,r={},n){return this._client.getAPIList(z`/containers/${e}/files`,$e,{query:r,...n})}delete(e,r,n){let{container_id:i}=r;return this._client.delete(z`/containers/${i}/files/${e}`,{...n,headers:U([{Accept:"*/*"},n?.headers])})}};Ks.Content=Zc;var Vo=class extends M{constructor(){super(...arguments),this.files=new Ks(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r})}retrieve(e,r){return this._client.get(z`/containers/${e}`,r)}list(e={},r){return this._client.getAPIList("/containers",$e,{query:e,...r})}delete(e,r){return this._client.delete(z`/containers/${e}`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}};Vo.Files=Ks;var Fc=class extends M{create(e,r,n){let{include:i,...o}=r;return this._client.post(z`/conversations/${e}/items`,{query:{include:i},body:o,...n})}retrieve(e,r,n){let{conversation_id:i,...o}=r;return this._client.get(z`/conversations/${i}/items/${e}`,{query:o,...n})}list(e,r={},n){return this._client.getAPIList(z`/conversations/${e}/items`,Bi,{query:r,...n})}delete(e,r,n){let{conversation_id:i}=r;return this._client.delete(z`/conversations/${i}/items/${e}`,n)}};var qo=class extends M{constructor(){super(...arguments),this.items=new Fc(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r})}retrieve(e,r){return this._client.get(z`/conversations/${e}`,r)}update(e,r,n){return this._client.post(z`/conversations/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(z`/conversations/${e}`,r)}};qo.Items=Fc;var Js=class extends M{create(e,r){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&Ot(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:i},...r});return n?o:(Ot(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(s=>(s&&s.data&&s.data.forEach(a=>{let c=a.embedding;a.embedding=l1(c)}),s)))}};var Vc=class extends M{retrieve(e,r,n){let{eval_id:i,run_id:o}=r;return this._client.get(z`/evals/${i}/runs/${o}/output_items/${e}`,n)}list(e,r,n){let{eval_id:i,...o}=r;return this._client.getAPIList(z`/evals/${i}/runs/${e}/output_items`,$e,{query:o,...n})}};var Ys=class extends M{constructor(){super(...arguments),this.outputItems=new Vc(this._client)}create(e,r,n){return this._client.post(z`/evals/${e}/runs`,{body:r,...n})}retrieve(e,r,n){let{eval_id:i}=r;return this._client.get(z`/evals/${i}/runs/${e}`,n)}list(e,r={},n){return this._client.getAPIList(z`/evals/${e}/runs`,$e,{query:r,...n})}delete(e,r,n){let{eval_id:i}=r;return this._client.delete(z`/evals/${i}/runs/${e}`,n)}cancel(e,r,n){let{eval_id:i}=r;return this._client.post(z`/evals/${i}/runs/${e}`,n)}};Ys.OutputItems=Vc;var Bo=class extends M{constructor(){super(...arguments),this.runs=new Ys(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r})}retrieve(e,r){return this._client.get(z`/evals/${e}`,r)}update(e,r,n){return this._client.post(z`/evals/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/evals",$e,{query:e,...r})}delete(e,r){return this._client.delete(z`/evals/${e}`,r)}};Bo.Runs=Ys;var Qs=class extends M{create(e,r){return this._client.post("/files",Wn({body:e,...r},this._client))}retrieve(e,r){return this._client.get(z`/files/${e}`,r)}list(e={},r){return this._client.getAPIList("/files",$e,{query:e,...r})}delete(e,r){return this._client.delete(z`/files/${e}`,r)}content(e,r){return this._client.get(z`/files/${e}/content`,{...r,headers:U([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),o=Date.now(),s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await gi(r),s=await this.retrieve(e),Date.now()-o>n)throw new Oo({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return s}};var qc=class extends M{};var Bc=class extends M{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r})}};var ea=class extends M{constructor(){super(...arguments),this.graders=new Bc(this._client)}};ea.Graders=Bc;var Wc=class extends M{create(e,r,n){return this._client.getAPIList(z`/fine_tuning/checkpoints/${e}/permissions`,bi,{body:r,method:"post",...n})}retrieve(e,r={},n){return this._client.get(z`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n})}delete(e,r,n){let{fine_tuned_model_checkpoint:i}=r;return this._client.delete(z`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var ta=class extends M{constructor(){super(...arguments),this.permissions=new Wc(this._client)}};ta.Permissions=Wc;var Gc=class extends M{list(e,r={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/checkpoints`,$e,{query:r,...n})}};var ra=class extends M{constructor(){super(...arguments),this.checkpoints=new Gc(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r})}retrieve(e,r){return this._client.get(z`/fine_tuning/jobs/${e}`,r)}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",$e,{query:e,...r})}cancel(e,r){return this._client.post(z`/fine_tuning/jobs/${e}/cancel`,r)}listEvents(e,r={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/events`,$e,{query:r,...n})}pause(e,r){return this._client.post(z`/fine_tuning/jobs/${e}/pause`,r)}resume(e,r){return this._client.post(z`/fine_tuning/jobs/${e}/resume`,r)}};ra.Checkpoints=Gc;var Xn=class extends M{constructor(){super(...arguments),this.methods=new qc(this._client),this.jobs=new ra(this._client),this.checkpoints=new ta(this._client),this.alpha=new ea(this._client)}};Xn.Methods=qc;Xn.Jobs=ra;Xn.Checkpoints=ta;Xn.Alpha=ea;var Hc=class extends M{};var Wo=class extends M{constructor(){super(...arguments),this.graderModels=new Hc(this._client)}};Wo.GraderModels=Hc;var na=class extends M{createVariation(e,r){return this._client.post("/images/variations",Wn({body:e,...r},this._client))}edit(e,r){return this._client.post("/images/edits",Wn({body:e,...r,stream:e.stream??!1},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1})}};var ia=class extends M{retrieve(e,r){return this._client.get(z`/models/${e}`,r)}list(e){return this._client.getAPIList("/models",bi,e)}delete(e,r){return this._client.delete(z`/models/${e}`,r)}};var oa=class extends M{create(e,r){return this._client.post("/moderations",{body:e,...r})}};var Xc=class extends M{accept(e,r,n){return this._client.post(z`/realtime/calls/${e}/accept`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}hangup(e,r){return this._client.post(z`/realtime/calls/${e}/hangup`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}refer(e,r,n){return this._client.post(z`/realtime/calls/${e}/refer`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}reject(e,r={},n){return this._client.post(z`/realtime/calls/${e}/reject`,{body:r,...n,headers:U([{Accept:"*/*"},n?.headers])})}};var Kc=class extends M{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r})}};var Ji=class extends M{constructor(){super(...arguments),this.clientSecrets=new Kc(this._client),this.calls=new Xc(this._client)}};Ji.ClientSecrets=Kc;Ji.Calls=Xc;function y1(t,e){return!e||!I2(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:qb(t,e)}function qb(t,e){let r=t.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:T2(e,i)};if(i.type==="message"){let o=i.content.map(s=>s.type==="output_text"?{...s,parsed:S2(e,s.text)}:s);return{...i,content:o}}return i}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||eh(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let o of i.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function S2(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function I2(t){return!!ld(t.text?.format)}function E2(t){return t?.$brand==="auto-parseable-tool"}function P2(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function T2(t,e){let r=P2(t.tools??[],e.name);return{...e,...e,parsed_arguments:E2(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function eh(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Jc,th,Go,rh,_1,b1,v1,w1,nh=class t extends Mo{constructor(e){super(),Jc.add(this),th.set(this,void 0),Go.set(this,void 0),rh.set(this,void 0),se(this,th,e,"f")}static createResponse(e,r,n){let i=new t(r);return i._run(()=>i._createOrRetrieveResponse(e,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,r,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),I(this,Jc,"m",_1).call(this);let o,s=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),s=r.starting_after??null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of o)I(this,Jc,"m",b1).call(this,a,s);if(o.controller.signal?.aborted)throw new qt;return I(this,Jc,"m",v1).call(this)}[(th=new WeakMap,Go=new WeakMap,rh=new WeakMap,Jc=new WeakSet,_1=function(){this.ended||se(this,Go,void 0,"f")},b1=function(r,n){if(this.ended)return;let i=(s,a)=>{(n==null||a.sequence_number>n)&&this._emit(s,a)},o=I(this,Jc,"m",w1).call(this,r);switch(i("event",r),r.type){case"response.output_text.delta":{let s=o.output[r.output_index];if(!s)throw new X(`missing output at index ${r.output_index}`);if(s.type==="message"){let a=s.content[r.content_index];if(!a)throw new X(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new X(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let s=o.output[r.output_index];if(!s)throw new X(`missing output at index ${r.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...r,snapshot:s.arguments});break}default:i(r.type,r);break}},v1=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");let r=I(this,Go,"f");if(!r)throw new X("request ended without sending any events");se(this,Go,void 0,"f");let n=A2(r,I(this,th,"f"));return se(this,rh,n,"f"),n},w1=function(r){let n=I(this,Go,"f");if(!n){if(r.type!=="response.created")throw new X(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=se(this,Go,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let i=n.output[r.output_index];if(!i)throw new X(`missing output at index ${r.output_index}`);let o=i.type,s=r.part;o==="message"&&s.type!=="reasoning_text"?i.content.push(s):o==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{let i=n.output[r.output_index];if(!i)throw new X(`missing output at index ${r.output_index}`);if(i.type==="message"){let o=i.content[r.content_index];if(!o)throw new X(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new X(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let i=n.output[r.output_index];if(!i)throw new X(`missing output at index ${r.output_index}`);i.type==="function_call"&&(i.arguments+=r.delta);break}case"response.reasoning_text.delta":{let i=n.output[r.output_index];if(!i)throw new X(`missing output at index ${r.output_index}`);if(i.type==="reasoning"){let o=i.content?.[r.content_index];if(!o)throw new X(`missing content at index ${r.content_index}`);if(o.type!=="reasoning_text")throw new X(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=r.delta}break}case"response.completed":{se(this,Go,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=I(this,rh,"f");if(!e)throw new X("stream ended without producing a ChatCompletion");return e}};function A2(t,e){return y1(t,e)}var Yc=class extends M{list(e,r={},n){return this._client.getAPIList(z`/responses/${e}/input_items`,$e,{query:r,...n})}};var Qc=class extends M{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r})}};var Yi=class extends M{constructor(){super(...arguments),this.inputItems=new Yc(this._client),this.inputTokens=new Qc(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&eh(n),n))}retrieve(e,r={},n){return this._client.get(z`/responses/${e}`,{query:r,...n,stream:r?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&eh(i),i))}delete(e,r){return this._client.delete(z`/responses/${e}`,{...r,headers:U([{Accept:"*/*"},r?.headers])})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>qb(n,e))}stream(e,r){return nh.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(z`/responses/${e}/cancel`,r)}compact(e,r){return this._client.post("/responses/compact",{body:e,...r})}};Yi.InputItems=Yc;Yi.InputTokens=Qc;var el=class extends M{retrieve(e,r){return this._client.get(z`/skills/${e}/content`,{...r,headers:U([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var tl=class extends M{retrieve(e,r,n){let{skill_id:i}=r;return this._client.get(z`/skills/${i}/versions/${e}/content`,{...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var sa=class extends M{constructor(){super(...arguments),this.content=new tl(this._client)}create(e,r={},n){return this._client.post(z`/skills/${e}/versions`,Wi({body:r,...n},this._client))}retrieve(e,r,n){let{skill_id:i}=r;return this._client.get(z`/skills/${i}/versions/${e}`,n)}list(e,r={},n){return this._client.getAPIList(z`/skills/${e}/versions`,$e,{query:r,...n})}delete(e,r,n){let{skill_id:i}=r;return this._client.delete(z`/skills/${i}/versions/${e}`,n)}};sa.Content=tl;var Qi=class extends M{constructor(){super(...arguments),this.content=new el(this._client),this.versions=new sa(this._client)}create(e={},r){return this._client.post("/skills",Wi({body:e,...r},this._client))}retrieve(e,r){return this._client.get(z`/skills/${e}`,r)}update(e,r,n){return this._client.post(z`/skills/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/skills",$e,{query:e,...r})}delete(e,r){return this._client.delete(z`/skills/${e}`,r)}};Qi.Content=el;Qi.Versions=sa;var rl=class extends M{create(e,r,n){return this._client.post(z`/uploads/${e}/parts`,Wn({body:r,...n},this._client))}};var Ho=class extends M{constructor(){super(...arguments),this.parts=new rl(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r})}cancel(e,r){return this._client.post(z`/uploads/${e}/cancel`,r)}complete(e,r,n){return this._client.post(z`/uploads/${e}/complete`,{body:r,...n})}};Ho.Parts=rl;var x1=async t=>{let e=await Promise.allSettled(t),r=e.filter(i=>i.status==="rejected");if(r.length){for(let i of r)console.error(i.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var nl=class extends M{create(e,r,n){return this._client.post(z`/vector_stores/${e}/file_batches`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(z`/vector_stores/${i}/file_batches/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,r,n){let{vector_store_id:i}=r;return this._client.post(z`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r);return await this.poll(e,i.id,n)}listFiles(e,r,n){let{vector_store_id:i,...o}=r;return this._client.getAPIList(z`/vector_stores/${i}/file_batches/${e}/files`,$e,{query:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:s}=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await gi(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},i){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=i?.maxConcurrency??5,s=Math.min(o,r.length),a=this._client,c=r.values(),l=[...n];async function u(f){for(let p of f){let h=await a.files.create({file:p,purpose:"assistants"},i);l.push(h.id)}}let d=Array(s).fill(c).map(u);return await x1(d),await this.createAndPoll(e,{file_ids:l})}};var il=class extends M{create(e,r,n){return this._client.post(z`/vector_stores/${e}/files`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,r,n){let{vector_store_id:i}=r;return this._client.get(z`/vector_stores/${i}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,r,n){let{vector_store_id:i,...o}=r;return this._client.post(z`/vector_stores/${i}/files/${e}`,{body:o,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,r={},n){return this._client.getAPIList(z`/vector_stores/${e}/files`,$e,{query:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,r,n){let{vector_store_id:i}=r;return this._client.delete(z`/vector_stores/${i}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,r,n){let i=await this.create(e,r,n);return await this.poll(e,i.id,n)}async poll(e,r,n){let i=U([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...n,headers:i}).withResponse(),s=o.data;switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.response.headers.get("openai-poll-after-ms");if(c){let l=parseInt(c);isNaN(l)||(a=l)}}await gi(a);break;case"failed":case"completed":return s}}}async upload(e,r,n){let i=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,r,n){let i=await this.upload(e,r,n);return await this.poll(e,i.id,n)}content(e,r,n){let{vector_store_id:i}=r;return this._client.getAPIList(z`/vector_stores/${i}/files/${e}/content`,bi,{...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var eo=class extends M{constructor(){super(...arguments),this.files=new il(this._client),this.fileBatches=new nl(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,r){return this._client.get(z`/vector_stores/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,r,n){return this._client.post(z`/vector_stores/${e}`,{body:r,...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},r){return this._client.getAPIList("/vector_stores",$e,{query:e,...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,r){return this._client.delete(z`/vector_stores/${e}`,{...r,headers:U([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}search(e,r,n){return this._client.getAPIList(z`/vector_stores/${e}/search`,bi,{body:r,method:"post",...n,headers:U([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};eo.Files=il;eo.FileBatches=nl;var aa=class extends M{create(e,r){return this._client.post("/videos",Wi({body:e,...r},this._client))}retrieve(e,r){return this._client.get(z`/videos/${e}`,r)}list(e={},r){return this._client.getAPIList("/videos",Bi,{query:e,...r})}delete(e,r){return this._client.delete(z`/videos/${e}`,r)}downloadContent(e,r={},n){return this._client.get(z`/videos/${e}/content`,{query:r,...n,headers:U([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,r,n){return this._client.post(z`/videos/${e}/remix`,Wi({body:r,...n},this._client))}};var ol,k1,ih,ca=class extends M{constructor(){super(...arguments),ol.add(this)}async unwrap(e,r,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,r,n,i),JSON.parse(e)}async verifySignature(e,r,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");I(this,ol,"m",k1).call(this,n);let o=U([r]).values,s=I(this,ol,"m",ih).call(this,o,"webhook-signature"),a=I(this,ol,"m",ih).call(this,o,"webhook-timestamp"),c=I(this,ol,"m",ih).call(this,o,"webhook-id"),l=parseInt(a,10);if(isNaN(l))throw new hi("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new hi("Webhook timestamp is too old");if(l>u+i)throw new hi("Webhook timestamp is too new");let d=s.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),f=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),p=c?`${c}.${a}.${e}`:`${a}.${e}`,h=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let m of d)try{let g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",h,g,new TextEncoder().encode(p)))return}catch{continue}throw new hi("The given webhook signature does not match the expected signature")}};ol=new WeakSet,k1=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},ih=function(e,r){if(!e)throw new Error("Headers are required");let n=e.get(r);if(n==null)throw new Error(`Missing required header: ${r}`);return n};var Bb,Wb,oh,$1,be=class{constructor({baseURL:e=Zo("OPENAI_BASE_URL"),apiKey:r=Zo("OPENAI_API_KEY"),organization:n=Zo("OPENAI_ORG_ID")??null,project:i=Zo("OPENAI_PROJECT_ID")??null,webhookSecret:o=Zo("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(Bb.add(this),oh.set(this,void 0),this.completions=new Xs(this),this.chat=new Do(this),this.embeddings=new Js(this),this.files=new Qs(this),this.images=new na(this),this.audio=new vi(this),this.moderations=new oa(this),this.models=new ia(this),this.fineTuning=new Xn(this),this.graders=new Wo(this),this.vectorStores=new eo(this),this.webhooks=new ca(this),this.beta=new Hn(this),this.batches=new qs(this),this.uploads=new Ho(this),this.responses=new Yi(this),this.realtime=new Ji(this),this.conversations=new qo(this),this.evals=new Bo(this),this.containers=new Vo(this),this.skills=new Qi(this),this.videos=new aa(this),r===void 0)throw new X("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:r,organization:n,project:i,webhookSecret:o,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&zE())throw new X(`It looks like you're running in a browser-like environment.
29
+
30
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
31
+ If you understand the risks and have appropriate mitigations in place,
32
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
33
+
34
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
35
+
36
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
37
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Wb.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=wb(a.logLevel,"ClientOptions.logLevel",this)??wb(Zo("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??CE(),se(this,oh,RE,"f"),this._options=a,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return bb(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ro}`}defaultIdempotencyKey(){return`stainless-node-retry-${lb()}`}makeStatusError(e,r,n,i){return Bt.generate(e,r,n,i)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof X?n:new X(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new X(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let i=!I(this,Bb,"m",$1).call(this)&&n||this.baseURL,o=kE(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return $E(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new Us(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:c}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Ot(this).debug(`[${l}] sending request`,qi({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new qt;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(ed),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new qt;let b=Qu(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Ot(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Ot(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,qi({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new Oo:new Co({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${u}${m}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let F=`retrying, ${r} attempts remaining`;return await OE(p.body),Ot(this).info(`${g} - ${F}`),Ot(this).debug(`[${l}] response error (${F})`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let b=y?"error; no more retries left":"error; not retryable";Ot(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>ed(F).message),R=EE($),T=R?void 0:$;throw Ot(this).debug(`[${l}] response error (${b})`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,T,p.headers)}return Ot(this).info(g),Ot(this).debug(`[${l}] response start`,qi({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new sd(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{},c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let c=parseFloat(s);Number.isNaN(c)||(o=c)}let a=i?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await gi(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,c=this.buildURL(o,s,a);"timeout"in n&&IE("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=U([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...NE(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=U([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:zm(e)}:I(this,oh,"f").call(this,{body:e,headers:n})}};Wb=be,oh=new WeakMap,Bb=new WeakSet,$1=function(){return this.baseURL!=="https://api.openai.com/v1"};be.OpenAI=Wb;be.DEFAULT_TIMEOUT=6e5;be.OpenAIError=X;be.APIError=Bt;be.APIConnectionError=Co;be.APIConnectionTimeoutError=Oo;be.APIUserAbortError=qt;be.NotFoundError=yc;be.ConflictError=_c;be.RateLimitError=vc;be.BadRequestError=mc;be.AuthenticationError=hc;be.InternalServerError=wc;be.PermissionDeniedError=gc;be.UnprocessableEntityError=bc;be.InvalidWebhookSignatureError=hi;be.toFile=Um;be.Completions=Xs;be.Chat=Do;be.Embeddings=Js;be.Files=Qs;be.Images=na;be.Audio=vi;be.Moderations=oa;be.Models=ia;be.FineTuning=Xn;be.Graders=Wo;be.VectorStores=eo;be.Webhooks=ca;be.Beta=Hn;be.Batches=qs;be.Uploads=Ho;be.Responses=Yi;be.Realtime=Ji;be.Conversations=qo;be.Evals=Bo;be.Containers=Vo;be.Skills=Qi;be.Videos=aa;var or=[];for(let t=0;t<256;++t)or.push((t+256).toString(16).slice(1));function S1(t,e=0){return(or[t[e+0]]+or[t[e+1]]+or[t[e+2]]+or[t[e+3]]+"-"+or[t[e+4]]+or[t[e+5]]+"-"+or[t[e+6]]+or[t[e+7]]+"-"+or[t[e+8]]+or[t[e+9]]+"-"+or[t[e+10]]+or[t[e+11]]+or[t[e+12]]+or[t[e+13]]+or[t[e+14]]+or[t[e+15]]).toLowerCase()}var Gb,U2=new Uint8Array(16);function Hb(){if(!Gb){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Gb=crypto.getRandomValues.bind(crypto)}return Gb(U2)}var Z2=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Xb={randomUUID:Z2};function F2(t,e,r){t=t||{};let n=t.random??t.rng?.()??Hb();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return S1(n)}function V2(t,e,r){return Xb.randomUUID&&!e&&!t?Xb.randomUUID():F2(t,e,r)}var sr=V2;var Xo=class{constructor(){this.size=4096;this.groups=[]}createGroup(e){let r=new Kb;return r.id=e,this.groups.push(r),r}group(e){return this.groups.find(r=>r.id===e)}static countTokensInText(e){return e==null?e="":typeof e=="number"?e=e+"":typeof e!="string"&&(e=JSON.stringify(e)),Math.ceil(e.length/3)}countTokens(){return this.groups.reduce((e,r)=>e+r.tokenCount,0)}removeOverflow(){let e=this.countTokens(),r=this.groups.reduce((n,i)=>n+i.weight,0);for(;e>this.size;){let n=this.groups.slice().sort((o,s)=>{let a=Math.floor(o.weight/r*this.size),c=Math.floor(s.weight/r*this.size),l=o.tokenCount-a;return s.tokenCount-c-l}),i=this.removeOneItem(n);if(!i)throw new Error("Too many items in the token window that cannot be removed.");e-=i.tokenCount}}removeOneItem(e){for(let r of e){let n=r.items.findIndex(o=>!o.cannotRemove);if(n===-1)continue;let i=r.items[n];return r.items.splice(n,1),r.tokenCount-=i.tokenCount,i}return null}},Kb=class{constructor(){this.id="";this.items=[];this.weight=1;this.tokenCount=0;this.separator=`
38
+ `;this.itemPadding=0;this.sortFunction=(e,r)=>e.sortOrder!==r.sortOrder?e.sortOrder-r.sortOrder:e.dateAdded!==r.dateAdded?e.dateAdded-r.dateAdded:0}setItemPadding(e){return this.itemPadding=e,this.recalculateTokens(),this}sortBy(e){return this.sortFunction=e,this.items.sort(this.sortFunction),this}setSeparator(e){return this.separator==e?this:(this.separator=e,this.recalculateTokens(),this)}setWeight(e){return this.weight=e,this}recalculateTokens(){this.tokenCount=this.items.reduce((e,r)=>(r.tokenCount=Xo.countTokensInText(typeof r.data=="string"?r.data:JSON.stringify(r.data))+Xo.countTokensInText(this.separator)+this.itemPadding,e+r.tokenCount),0)}add(e){typeof e=="string"&&(e={source:"user",data:e});let r=e;r.id===void 0&&(r.id=sr()),!r.sections?.length&&typeof r.data=="string"?r.text=r.data:r.text=r.sections?.map(i=>{if(i.type==="text")return i.text||"";if(i.type==="tool_call")return`[Tool Call: ${i.toolKbName||i.toolName}] `;if(i.type==="tool_result"&&i.toolErrorResponse)return`[Tool Error: ${i.toolErrorResponse}] `}).filter(i=>!!i).join(`
39
+
40
+ `)||"";let n=this.items.find(i=>i.id===r.id);return n?(this.tokenCount-=n.tokenCount,Object.assign(n,r),r=n):this.items.push(r),r.dateAdded===void 0&&(r.dateAdded=Date.now()),r.sortOrder===void 0&&(r.sortOrder=0),r.disabled===void 0&&(r.disabled=!1),r.source===void 0&&(r.source="user"),r.sections===void 0&&(r.sections=[]),r.tokenCount=r.disabled?0:Xo.countTokensInText(typeof e.data=="string"?e.data:JSON.stringify(e.data))+Xo.countTokensInText(this.separator)+this.itemPadding,this.tokenCount+=r.tokenCount,this.items.sort(this.sortFunction),r}getAllAsString(){return this.getAll().map(e=>e.text).join(this.separator)}getAll(){return this.items.filter(e=>!e.disabled)}empty(){this.items=[],this.tokenCount=0}};function sh(t){let e=(t||"").split(`
41
+ `);for(;e.length>0&&e[0].trim()=="";)e.shift();for(;e.length>0&&e[e.length-1].trim()=="";)e.pop();let r=1/0;for(let n of e){let i=n.match(/^\s*/)?.[0].length||0;r=Math.min(r,i)}return r>0&&r<1/0&&(e=e.map(n=>n.substring(r))),e.join(`
42
+ `)}var q2={};function Ko(){return typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:q2}function ht(){return Ko().intelliweave=Ko().intelliweave||Ko().webWeaver||{},Ko().intelliweave}function I1(){if(ht().userID)return ht().userID||"";if(typeof localStorage<"u"&&localStorage.getItem&&localStorage.setItem){let t=localStorage.getItem("intelliweave.uid")||"";return t||(t=sr(),localStorage.setItem("intelliweave.uid",t),t)}else return sr()}function E1(t){let e=t;if(e?.type=="object"&&e.properties)return t;let r={type:"object",properties:{},required:[]};if(t&&Array.isArray(t)){let n=t;for(let i of n)r.properties[i.name]={type:i.type||"string",description:i.description||""}}return r}var ah=class ah{constructor(e){this.module="IntelliWeave";this.module=e}get debugEnabled(){return ah.debug?!0:typeof window<"u"&&ht().debug}log(...e){this.debugEnabled&&console.log(`[IntelliWeave > ${this.module}]`,...e)}debug(...e){this.debugEnabled&&console.debug(`[IntelliWeave > ${this.module}]`,...e)}info(...e){this.debugEnabled&&console.info(`[IntelliWeave > ${this.module}]`,...e)}warn(...e){console.warn(`[IntelliWeave > ${this.module}]`,...e)}error(...e){console.error(`[IntelliWeave > ${this.module}]`,...e)}timer(e,...r){let n=Date.now();return this.debug(`[${e} 0ms] Started`,...r),(...i)=>this.debug(`[${e} ${Math.floor(Date.now()-n)}ms]`,...i)}};ah.debug=!1;var Ce=ah;var P1=new Ce("ChatBase"),sl=class{constructor(e){this.id="";this.metadata={};this.maxToolCallsPerMessage=10;this.stats={tokensUsed:0};this.tokenWindow=(()=>{let e=new Xo;return e.createGroup("context").setSeparator(`
43
+
44
+ `),e.createGroup("actions").setItemPadding(25),e.createGroup("messages").setItemPadding(10),e})();this.config=e,this.tokenWindow.size=this.config.maxTokens||16e3}get contextGroup(){return this.tokenWindow.group("context")}get toolGroup(){return this.tokenWindow.group("actions")}get messageGroup(){return this.tokenWindow.group("messages")}getBaseURL(){if(!this.config.endpoint)return;let e=this.config.endpoint;return e.endsWith("/chat/completions")&&(e=e.substring(0,e.length-17)),e}async sendMessage(e,r){throw new Error("Not implemented")}addUserMessage(e){throw new Error("Not implemented")}addAssistantMessage(e){throw new Error("Not implemented")}addTextMessage(e,r,n){this.messageGroup.add({id:"msg-"+sr(),source:r,data:n,sections:[{type:"text",text:e}]})}onBeforeIncomingMessage(e){}resetConversation(){this.messageGroup.empty(),this.toolGroup.empty(),this.contextGroup.empty()}async trimMessages(){this.tokenWindow.removeOverflow()}registerTool(e){return this.toolGroup.add({id:e.name,data:e,cannotRemove:!e.canRemove,sortOrder:101,disabled:!!e.kbItem?.disabled})}findToolBySafeName(e){return this.toolGroup.getAll().find(r=>r.id==e||r.data?.kbItem?.name==e)?.data}async executeTool(e,r){if(!e)throw new Error("Tool not found");P1.debug(`Executing tool '${e.name}'`,r,e),this.config.onAIToolStart?.(e.kbItem?.name||e.name,r);let n;try{n=await e.callback(r)}catch(i){throw P1.error(`Error executing tool '${e.name}'`,i),i}return typeof n!="string"&&(n=JSON.stringify(n)||""),(n===""||n==="undefined")&&(n="success"),n}};var Jb=new Ce("ChatGPT"),ch=class extends sl{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}createOpenAIClient(){return new be({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0})}async sendMessage(e,r){this.addUserMessage(e);let n=this.createOpenAIClient(),i=!0,o=[];for(;i;){let s="msg-"+sr();i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),Jb.debug("Before processing state",{messages:this.messageGroup.getAll().map(d=>d.data),tools:this.toolGroup.getAll().map(d=>d.data),context:this.contextGroup.getAll().map(d=>d.text)});let a=this.toolGroup.getAll().filter(d=>!!d?.data).map(d=>({type:"function",function:{name:d.data.name,description:d.data.description||"",parameters:{type:"object",...d.data?.params}}})),c,l;if(this.config.stream){let d=n.chat.completions.stream({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(f=>f.data)],tools:a,stream:!0,parallel_tool_calls:!0,stream_options:{include_usage:!0}});for await(let f of d){let p=d.currentChatCompletionSnapshot?.choices?.[0]?.message;if(!p)continue;let h=this.parseMessageBlock(s,p,void 0,!0);this.config.onAIMessage?.([...o,h],!0),r?.([...o,h])}c=await d.finalMessage(),l=await d.totalUsage()}else{let d=await n.chat.completions.create({model:this.config.model,messages:[{role:"system",content:this.contextGroup.getAllAsString()},...this.messageGroup.getAll().map(f=>f.data)],tools:a,parallel_tool_calls:!0});c=d.choices[0].message,l=d.usage}c.role=="assistant"&&!c.content&&!c.tool_calls?.length&&(c.content=""),Jb.debug("Message received",c);let u=this.messageGroup.add(this.parseMessageBlock(s,c,l,!1));o.push(u),await Promise.all((c.tool_calls||[]).map(async d=>{if(d.type!="function")return;let f=this.findToolBySafeName(d.function.name);try{let p=null;try{p=d.function.arguments?JSON.parse(d.function.arguments):null}catch(g){throw new Error(`The AI provided invalid JSON arguments for tool call ${d.function.name}: ${g.message}`)}let h=await this.executeTool(f,p),m=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:f?.kbItem?.id,toolKbName:f?.kbItem?.name,toolSuccessResponse:h,toolCallInstanceID:d.id,toolCallHiddenInUI:f?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:h}});o.push(m)}catch(p){let h=p?.message||"An unknown error occurred",m=this.messageGroup.add({source:"user",sections:[{type:"tool_result",toolName:d.function.name,toolKbID:f?.kbItem?.id,toolKbName:f?.kbItem?.name,toolErrorResponse:h,toolCallInstanceID:d.id,toolCallHiddenInUI:f?.kbItem?.hideActionInUI}],data:{role:"tool",tool_call_id:d.id,content:`Error performing tool call ${d.function.name}: ${h}`}});o.push(m)}i=!0,this.config.onAIMessage?.(o,!0),r?.(o)})),this.stats.tokensUsed+=l?.total_tokens||0}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e,r,n,i){let o=[];r.reasoning&&o.push({type:"thinking",text:r.reasoning});for(let s of r.tool_calls||[]){if(s.type!="function")continue;let a=this.findToolBySafeName(s.function.name),c=null;if(s.function.arguments)try{c=JSON.parse(s.function.arguments)}catch(l){i||Jb.error(`Failed to parse tool parameters for tool call ${s.function.name}:`,l)}o.push({type:"tool_call",toolName:s.function.name,toolKbID:a?.kbItem?.id,toolKbName:a?.kbItem?.name,toolCallInstanceID:s.id,toolCallHiddenInUI:a?.kbItem?.hideActionInUI,toolParameters:c})}return typeof r.content=="string"&&o.push({type:"text",text:r.content||""}),{id:e,data:r,sections:o,source:"assistant",streamingInProgress:i,usage:{inputTokens:n?.prompt_tokens||0,outputTokens:n?.completion_tokens||0,cachedInputTokens:0,totalTokens:(n?.prompt_tokens||0)+(n?.completion_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items.length&&this.messageGroup.items[0].data?.role=="tool";)this.messageGroup.items.shift()}};function B(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r}function E(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Yb=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Yb=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function to(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var vd=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var ee=class extends Error{},Jt=class t extends ee{constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("request-id"),this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new Jo({message:n,cause:vd(r)});let o=r;return e===400?new ll(e,o,n,i):e===401?new ul(e,o,n,i):e===403?new dl(e,o,n,i):e===404?new pl(e,o,n,i):e===409?new fl(e,o,n,i):e===422?new ml(e,o,n,i):e===429?new hl(e,o,n,i):e>=500?new gl(e,o,n,i):new t(e,o,n,i)}},ar=class extends Jt{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Jo=class extends Jt{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},cl=class extends Jo{constructor({message:e}={}){super({message:e??"Request timed out."})}},ll=class extends Jt{},ul=class extends Jt{},dl=class extends Jt{},pl=class extends Jt{},fl=class extends Jt{},ml=class extends Jt{},hl=class extends Jt{},gl=class extends Jt{};var W2=/^[a-z][a-z0-9+.-]*:/i,T1=t=>W2.test(t),Qb=t=>(Qb=Array.isArray,Qb(t)),ev=Qb;function lh(t){return typeof t!="object"?{}:t??{}}function A1(t){if(!t)return!0;for(let e in t)return!1;return!0}function z1(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var N1=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ee(`${t} must be an integer`);if(e<0)throw new ee(`${t} must be a positive integer`);return e};var uh=t=>{try{return JSON.parse(t)}catch{return}};var C1=t=>new Promise(e=>setTimeout(e,t));var Yo="0.74.0";var j1=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function G2(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var H2=()=>{let t=G2();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yo,"X-Stainless-OS":R1(Deno.build.os),"X-Stainless-Arch":O1(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yo,"X-Stainless-OS":R1(globalThis.process.platform??"unknown"),"X-Stainless-Arch":O1(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=X2();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Yo,"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":Yo,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function X2(){if(typeof navigator>"u"||!navigator)return null;let t=[{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/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var O1=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",R1=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),M1,D1=()=>M1??(M1=H2());function L1(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function tv(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function dh(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return tv({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}function wd(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function U1(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Z1=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function q1(t){let e=0;for(let i of t)e+=i.length;let r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}var F1;function xd(t){let e;return(F1??(e=new globalThis.TextEncoder,F1=e.encode.bind(e)))(t)}var V1;function rv(t){let e;return(V1??(e=new globalThis.TextDecoder,V1=e.decode.bind(e)))(t)}var ln,un,ro=class{constructor(){ln.set(this,void 0),un.set(this,void 0),B(this,ln,new Uint8Array,"f"),B(this,un,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?xd(e):e;B(this,ln,q1([E(this,ln,"f"),r]),"f");let n=[],i;for(;(i=Y2(E(this,ln,"f"),E(this,un,"f")))!=null;){if(i.carriage&&E(this,un,"f")==null){B(this,un,i.index,"f");continue}if(E(this,un,"f")!=null&&(i.index!==E(this,un,"f")+1||i.carriage)){n.push(rv(E(this,ln,"f").subarray(0,E(this,un,"f")-1))),B(this,ln,E(this,ln,"f").subarray(E(this,un,"f")),"f"),B(this,un,null,"f");continue}let o=E(this,un,"f")!==null?i.preceding-1:i.preceding,s=rv(E(this,ln,"f").subarray(0,o));n.push(s),B(this,ln,E(this,ln,"f").subarray(i.index),"f"),B(this,un,null,"f")}return n}flush(){return E(this,ln,"f").length?this.decode(`
45
+ `):[]}};ln=new WeakMap,un=new WeakMap;ro.NEWLINE_CHARS=new Set([`
46
+ `,"\r"]);ro.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Y2(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function B1(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var fh={off:0,error:200,warn:300,info:400,debug:500},nv=(t,e,r)=>{if(t){if(z1(fh,t))return t;Yt(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(fh))}`)}};function kd(){}function ph(t,e,r){return!e||fh[t]>fh[r]?kd:e[t].bind(e)}var Q2={error:kd,warn:kd,info:kd,debug:kd},W1=new WeakMap;function Yt(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Q2;let n=W1.get(e);if(n&&n[0]===r)return n[1];let i={error:ph("error",e,r),warn:ph("warn",e,r),info:ph("info",e,r),debug:ph("debug",e,r)};return W1.set(e,[r,i]),i}var no=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var $d,xi=class t{constructor(e,r,n){this.iterator=e,$d.set(this,void 0),this.controller=r,B(this,$d,n,"f")}static fromSSEResponse(e,r,n){let i=!1,o=n?Yt(n):console;async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of eL(e,r)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(l){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),l}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop")try{yield JSON.parse(c.data)}catch(l){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),l}if(c.event!=="ping"&&c.event==="error")throw new Jt(void 0,uh(c.data)??c.data,void 0,e.headers)}a=!0}catch(c){if(to(c))return;throw c}finally{a||r.abort()}}return new t(s,r,n)}static fromReadableStream(e,r,n){let i=!1;async function*o(){let a=new ro,c=wd(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*s(){if(i)throw new ee("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(to(c))return;throw c}finally{a||r.abort()}}return new t(s,r,n)}[($d=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),r.push(s)}return o.shift()}});return[new t(()=>i(e),this.controller,E(this,$d,"f")),new t(()=>i(r),this.controller,E(this,$d,"f"))]}toReadableStream(){let e=this,r;return tv({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await r.next();if(o)return n.close();let s=xd(JSON.stringify(i)+`
47
+ `);n.enqueue(s)}catch(i){n.error(i)}},async cancel(){await r.return?.()}})}};async function*eL(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ee("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ee("Attempted to iterate over a response with no body");let r=new iv,n=new ro,i=wd(t.body);for await(let o of tL(i))for(let s of n.decode(o)){let a=r.decode(s);a&&(yield a)}for(let o of n.flush()){let s=r.decode(o);s&&(yield s)}}async function*tL(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?xd(r):r,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=B1(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var iv=class{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 o={event:this.event,data:this.data.join(`
48
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,i]=rL(e,":");return i.startsWith(" ")&&(i=i.substring(1)),r==="event"?this.event=i:r==="data"&&this.data.push(i),null}};function rL(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function mh(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:o}=e,s=await(async()=>{if(e.options.stream)return Yt(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):xi.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let f=await r.json();return ov(f,r)}return await r.text()})();return Yt(t).debug(`[${n}] response parsed`,no({retryOfRequestLogID:i,url:r.url,status:r.status,body:s,durationMs:Date.now()-o})),s}function ov(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Sd,la=class t extends Promise{constructor(e,r,n=mh){super(i=>{i(null)}),this.responsePromise=r,this.parseResponse=n,Sd.set(this,void 0),B(this,Sd,e,"f")}_thenUnwrap(e){return new t(E(this,Sd,"f"),this.responsePromise,async(r,n)=>ov(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(E(this,Sd,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Sd=new WeakMap;var hh,gh=class{constructor(e,r,n,i){hh.set(this,void 0),B(this,hh,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new ee("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await E(this,hh,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(hh=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Id=class extends la{constructor(e,r,n){super(e,r,async(i,o)=>new n(i,o.response,await mh(i,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Sn=class extends gh{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...lh(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...lh(this.options.query),after_id:e}}:null}};var yl=class extends gh{constructor(e,r,n,i){super(e,r,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...lh(this.options.query),page:e}}:null}};var av=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ua(t,e,r){return av(),new File(t,e??"unknown_file",r)}function Ed(t,e){let r=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?r.split(/[\\/]/).pop()||void 0:r}var cv=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var _l=async(t,e,r=!0)=>({...t,body:await oL(t.body,e,r)}),G1=new WeakMap;function iL(t){let e=typeof t=="function"?t:t.fetch,r=G1.get(e);if(r)return r;let n=(async()=>{try{let i="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new i(o).text()}catch{return!0}})();return G1.set(e,n),n}var oL=async(t,e,r=!0)=>{if(!await iL(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([i,o])=>sv(n,i,o,r))),n},sL=t=>t instanceof Blob&&"name"in t;var sv=async(t,e,r,n)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let i={},o=r.headers.get("Content-Type");o&&(i={type:o}),t.append(e,ua([await r.blob()],Ed(r,n),i))}else if(cv(r))t.append(e,ua([await new Response(dh(r)).blob()],Ed(r,n)));else if(sL(r))t.append(e,ua([r],Ed(r,n),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(i=>sv(t,e+"[]",i,n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([i,o])=>sv(t,`${e}[${i}]`,o,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var H1=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",aL=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&H1(t),cL=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function yh(t,e,r){if(av(),t=await t,e||(e=Ed(t,!0)),aL(t))return t instanceof File&&e==null&&r==null?t:ua([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...r});if(cL(t)){let i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),ua(await lv(i),e,r)}let n=await lv(t);if(!r?.type){let i=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof i=="string"&&(r={...r,type:i})}return ua(n,e,r)}async function lv(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(H1(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(cv(t))for await(let r of t)e.push(...await lv(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${lL(t)}`)}return e}function lL(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var wt=class{constructor(e){this._client=e}};var X1=Symbol.for("brand.privateNullableHeaders");function*dL(t){if(!t)return;if(X1 in t){let{values:n,nulls:i}=t;yield*n.entries();for(let o of i)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():ev(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=ev(n[1])?n[1]:[n[1]],s=!1;for(let a of o)a!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,a])}}var ve=t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[o,s]of dL(n)){let a=o.toLowerCase();i.has(a)||(e.delete(o),i.add(a)),s===null?(e.delete(o),r.add(a)):(e.append(o,s),r.delete(a))}}return{[X1]:!0,values:e,nulls:r}};var Pd=Symbol("anthropic.sdk.stainlessHelper");function _h(t){return typeof t=="object"&&t!==null&&Pd in t}function uv(t,e){let r=new Set;if(t)for(let n of t)_h(n)&&r.add(n[Pd]);if(e){for(let n of e)if(_h(n)&&r.add(n[Pd]),Array.isArray(n.content))for(let i of n.content)_h(i)&&r.add(i[Pd])}return Array.from(r)}function bh(t,e){let r=uv(t,e);return r.length===0?{}:{"x-stainless-helper":r.join(", ")}}function K1(t){return _h(t)?{"x-stainless-helper":t[Pd]}:{}}function Y1(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var J1=Object.freeze(Object.create(null)),pL=(t=Y1)=>function(r,...n){if(r.length===1)return r[0];let i=!1,o=[],s=r.reduce((u,d,f)=>{/[?#]/.test(d)&&(i=!0);let p=n[f],h=(i?encodeURIComponent:t)(""+p);return f!==n.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??J1)??J1)?.toString)&&(h=p+"",o.push({start:u.length+d.length,length:h.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===n.length?"":h)},""),a=s.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((u,d)=>u.start-d.start),o.length>0){let u=0,d=o.reduce((f,p)=>{let h=" ".repeat(p.start-u),m="^".repeat(p.length);return u=p.start+p.length,f+h+m},"");throw new ee(`Path parameters result in path with invalid segments:
49
+ ${o.map(f=>f.error).join(`
50
+ `)}
51
+ ${s}
52
+ ${d}`)}return s},xt=pL(Y1);var bl=class extends wt{list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/files",Sn,{query:i,...r,headers:ve([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(xt`/v1/files/${e}`,{...n,headers:ve([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/files/${e}/content`,{...n,headers:ve([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/files/${e}`,{...n,headers:ve([{"anthropic-beta":[...i??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...i}=e;return this._client.post("/v1/files",_l({body:i,...r,headers:ve([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},K1(i.file),r?.headers])},this._client))}};var vl=class extends wt{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/models/${e}?beta=true`,{...n,headers:ve([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models?beta=true",Sn,{query:i,...r,headers:ve([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var vh={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Q1(t){return t?.output_format??t?.output_config?.format}function dv(t,e,r){let n=Q1(e);return!e||!("parse"in(n??{}))?{...t,content:t.content.map(i=>{if(i.type==="text"){let o=Object.defineProperty({...i},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(o,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return i}),parsed_output:null}:pv(t,e,r)}function pv(t,e,r){let n=null,i=t.content.map(o=>{if(o.type==="text"){let s=hL(e,o.text);n===null&&(n=s);let a=Object.defineProperty({...o},"parsed_output",{value:s,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return r.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),s},enumerable:!1})}return o});return{...t,content:i,parsed_output:n}}function hL(t,e){let r=Q1(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(n){throw new ee(`Failed to parse structured output: ${n}`)}}var gL=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e++;continue}if(n==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(n===":"){r.push({type:"separator",value:":"}),e++;continue}if(n===","){r.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",c=!1;for(n=t[++e];n!=='"';){if(e===t.length){c=!0;break}if(n==="\\"){if(e++,e===t.length){c=!0;break}a+=n+t[e],n=t[++e]}else a+=n,n=t[++e]}n=t[++e],c||r.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=t[++e]);n&&o.test(n)||n===".";)a+=n,n=t[++e];r.push({type:"number",value:a});continue}let s=/[a-z]/i;if(n&&s.test(n)){let a="";for(;n&&s.test(n)&&e!==t.length;)a+=n,n=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},wl=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),wl(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),wl(t);case"string":let n=t[t.length-2];if(n?.type==="delimiter")return t=t.slice(0,t.length-1),wl(t);if(n?.type==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),wl(t);break;case"delimiter":return t=t.slice(0,t.length-1),wl(t);break}return t},yL=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},_L=t=>{let e="";return t.map(r=>{r.type==="string"?e+='"'+r.value+'"':e+=r.value}),e},wh=t=>JSON.parse(_L(yL(wl(gL(t)))));var In,Qo,xl,Td,xh,Ad,zd,kh,Nd,io,Cd,$h,Sh,da,Ih,Eh,Od,fv,eP,Ph,mv,hv,gv,tP,rP="__json_buf";function nP(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Th=class t{constructor(e,r){In.add(this),this.messages=[],this.receivedMessages=[],Qo.set(this,void 0),xl.set(this,null),this.controller=new AbortController,Td.set(this,void 0),xh.set(this,()=>{}),Ad.set(this,()=>{}),zd.set(this,void 0),kh.set(this,()=>{}),Nd.set(this,()=>{}),io.set(this,{}),Cd.set(this,!1),$h.set(this,!1),Sh.set(this,!1),da.set(this,!1),Ih.set(this,void 0),Eh.set(this,void 0),Od.set(this,void 0),Ph.set(this,n=>{if(B(this,$h,!0,"f"),to(n)&&(n=new ar),n instanceof ar)return B(this,Sh,!0,"f"),this._emit("abort",n);if(n instanceof ee)return this._emit("error",n);if(n instanceof Error){let i=new ee(n.message);return i.cause=n,this._emit("error",i)}return this._emit("error",new ee(String(n)))}),B(this,Td,new Promise((n,i)=>{B(this,xh,n,"f"),B(this,Ad,i,"f")}),"f"),B(this,zd,new Promise((n,i)=>{B(this,kh,n,"f"),B(this,Nd,i,"f")}),"f"),E(this,Td,"f").catch(()=>{}),E(this,zd,"f").catch(()=>{}),B(this,xl,e,"f"),B(this,Od,r?.logger??console,"f")}get response(){return E(this,Ih,"f")}get request_id(){return E(this,Eh,"f")}async withResponse(){B(this,da,!0,"f");let e=await E(this,Td,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n,{logger:i}={}){let o=new t(r,{logger:i});for(let s of r.messages)o._addMessageParam(s);return B(o,xl,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},E(this,Ph,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{E(this,In,"m",mv).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let c of a)E(this,In,"m",hv).call(this,c);if(a.controller.signal?.aborted)throw new ar;E(this,In,"m",gv).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(B(this,Ih,e,"f"),B(this,Eh,e?.headers.get("request-id"),"f"),E(this,xh,"f").call(this,e),this._emit("connect"))}get ended(){return E(this,Cd,"f")}get errored(){return E(this,$h,"f")}get aborted(){return E(this,Sh,"f")}abort(){this.controller.abort()}on(e,r){return(E(this,io,"f")[e]||(E(this,io,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=E(this,io,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(E(this,io,"f")[e]||(E(this,io,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{B(this,da,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){B(this,da,!0,"f"),await E(this,zd,"f")}get currentMessage(){return E(this,Qo,"f")}async finalMessage(){return await this.done(),E(this,In,"m",fv).call(this)}async finalText(){return await this.done(),E(this,In,"m",eP).call(this)}_emit(e,...r){if(E(this,Cd,"f"))return;e==="end"&&(B(this,Cd,!0,"f"),E(this,kh,"f").call(this));let n=E(this,io,"f")[e];if(n&&(E(this,io,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!E(this,da,"f")&&!n?.length&&Promise.reject(i),E(this,Ad,"f").call(this,i),E(this,Nd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!E(this,da,"f")&&!n?.length&&Promise.reject(i),E(this,Ad,"f").call(this,i),E(this,Nd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",E(this,In,"m",fv).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{E(this,In,"m",mv).call(this),this._connected(null);let o=xi.fromReadableStream(e,this.controller);for await(let s of o)E(this,In,"m",hv).call(this,s);if(o.controller.signal?.aborted)throw new ar;E(this,In,"m",gv).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(Qo=new WeakMap,xl=new WeakMap,Td=new WeakMap,xh=new WeakMap,Ad=new WeakMap,zd=new WeakMap,kh=new WeakMap,Nd=new WeakMap,io=new WeakMap,Cd=new WeakMap,$h=new WeakMap,Sh=new WeakMap,da=new WeakMap,Ih=new WeakMap,Eh=new WeakMap,Od=new WeakMap,Ph=new WeakMap,In=new WeakSet,fv=function(){if(this.receivedMessages.length===0)throw new ee("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},eP=function(){if(this.receivedMessages.length===0)throw new ee("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new ee("stream ended without producing a content block with type=text");return r.join(" ")},mv=function(){this.ended||B(this,Qo,void 0,"f")},hv=function(r){if(this.ended)return;let n=E(this,In,"m",tP).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{nP(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}case"compaction_delta":{i.type==="compaction"&&i.content&&this._emit("compaction",i.content);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(dv(n,E(this,xl,"f"),{logger:E(this,Od,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{B(this,Qo,n,"f");break}case"content_block_start":case"message_delta":break}},gv=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=E(this,Qo,"f");if(!r)throw new ee("request ended without sending any chunks");return B(this,Qo,void 0,"f"),dv(r,E(this,xl,"f"),{logger:E(this,Od,"f")})},tP=function(r){let n=E(this,Qo,"f");if(r.type==="message_start"){if(n)throw new ee(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new ee(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.container=r.delta.container,n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,n.context_management=r.context_management,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),r.usage.iterations!=null&&(n.usage.iterations=r.usage.iterations),n;case"content_block_start":return n.content.push(r.content_block),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&nP(i)){let o=i[rP]||"";o+=r.delta.partial_json;let s={...i};if(Object.defineProperty(s,rP,{value:o,enumerable:!1,writable:!0}),o)try{s.input=wh(o)}catch(a){let c=new ee(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${o}`);E(this,Ph,"f").call(this,c)}n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}case"compaction_delta":{i?.type==="compaction"&&(n.content[r.index]={...i,content:(i.content||"")+r.delta.content});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new xi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var pa=class extends Error{constructor(e){let r=typeof e=="string"?e:e.map(n=>n.type==="text"?n.text:`[${n.type}]`).join(" ");super(r),this.name="ToolError",this.content=e}};var iP=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
53
+ 1. Task Overview
54
+ The user's core request and success criteria
55
+ Any clarifications or constraints they specified
56
+ 2. Current State
57
+ What has been completed so far
58
+ Files created, modified, or analyzed (with paths if relevant)
59
+ Key outputs or artifacts produced
60
+ 3. Important Discoveries
61
+ Technical constraints or requirements uncovered
62
+ Decisions made and their rationale
63
+ Errors encountered and how they were resolved
64
+ What approaches were tried that didn't work (and why)
65
+ 4. Next Steps
66
+ Specific actions needed to complete the task
67
+ Any blockers or open questions to resolve
68
+ Priority order if multiple steps remain
69
+ 5. Context to Preserve
70
+ User preferences or style requirements
71
+ Domain-specific details that aren't obvious
72
+ Any promises made to the user
73
+ Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
74
+ Wrap your summary in <summary></summary> tags.`;var Rd,kl,fa,Ht,Md,dn,oo,es,jd,oP,yv;function sP(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}}var $l=class{constructor(e,r,n){Rd.add(this),this.client=e,kl.set(this,!1),fa.set(this,!1),Ht.set(this,void 0),Md.set(this,void 0),dn.set(this,void 0),oo.set(this,void 0),es.set(this,void 0),jd.set(this,0),B(this,Ht,{params:{...r,messages:structuredClone(r.messages)}},"f");let o=["BetaToolRunner",...uv(r.tools,r.messages)].join(", ");B(this,Md,{...n,headers:ve([{"x-stainless-helper":o},n?.headers])},"f"),B(this,es,sP(),"f")}async*[(kl=new WeakMap,fa=new WeakMap,Ht=new WeakMap,Md=new WeakMap,dn=new WeakMap,oo=new WeakMap,es=new WeakMap,jd=new WeakMap,Rd=new WeakSet,oP=async function(){let r=E(this,Ht,"f").params.compactionControl;if(!r||!r.enabled)return!1;let n=0;if(E(this,dn,"f")!==void 0)try{let l=await E(this,dn,"f");n=l.usage.input_tokens+(l.usage.cache_creation_input_tokens??0)+(l.usage.cache_read_input_tokens??0)+l.usage.output_tokens}catch{return!1}let i=r.contextTokenThreshold??1e5;if(n<i)return!1;let o=r.model??E(this,Ht,"f").params.model,s=r.summaryPrompt??iP,a=E(this,Ht,"f").params.messages;if(a[a.length-1].role==="assistant"){let l=a[a.length-1];if(Array.isArray(l.content)){let u=l.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():l.content=u}}let c=await this.client.beta.messages.create({model:o,messages:[...a,{role:"user",content:[{type:"text",text:s}]}],max_tokens:E(this,Ht,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(c.content[0]?.type!=="text")throw new ee("Expected text response for compaction");return E(this,Ht,"f").params.messages=[{role:"user",content:c.content}],!0},Symbol.asyncIterator)](){var e;if(E(this,kl,"f"))throw new ee("Cannot iterate over a consumed stream");B(this,kl,!0,"f"),B(this,fa,!0,"f"),B(this,oo,void 0,"f");try{for(;;){let r;try{if(E(this,Ht,"f").params.max_iterations&&E(this,jd,"f")>=E(this,Ht,"f").params.max_iterations)break;B(this,fa,!1,"f"),B(this,oo,void 0,"f"),B(this,jd,(e=E(this,jd,"f"),e++,e),"f"),B(this,dn,void 0,"f");let{max_iterations:n,compactionControl:i,...o}=E(this,Ht,"f").params;if(o.stream?(r=this.client.beta.messages.stream({...o},E(this,Md,"f")),B(this,dn,r.finalMessage(),"f"),E(this,dn,"f").catch(()=>{}),yield r):(B(this,dn,this.client.beta.messages.create({...o,stream:!1},E(this,Md,"f")),"f"),yield E(this,dn,"f")),!await E(this,Rd,"m",oP).call(this)){if(!E(this,fa,"f")){let{role:c,content:l}=await E(this,dn,"f");E(this,Ht,"f").params.messages.push({role:c,content:l})}let a=await E(this,Rd,"m",yv).call(this,E(this,Ht,"f").params.messages.at(-1));if(a)E(this,Ht,"f").params.messages.push(a);else if(!E(this,fa,"f"))break}}finally{r&&r.abort()}}if(!E(this,dn,"f"))throw new ee("ToolRunner concluded without a message from the server");E(this,es,"f").resolve(await E(this,dn,"f"))}catch(r){throw B(this,kl,!1,"f"),E(this,es,"f").promise.catch(()=>{}),E(this,es,"f").reject(r),B(this,es,sP(),"f"),r}}setMessagesParams(e){typeof e=="function"?E(this,Ht,"f").params=e(E(this,Ht,"f").params):E(this,Ht,"f").params=e,B(this,fa,!0,"f"),B(this,oo,void 0,"f")}async generateToolResponse(){let e=await E(this,dn,"f")??this.params.messages.at(-1);return e?E(this,Rd,"m",yv).call(this,e):null}done(){return E(this,es,"f").promise}async runUntilDone(){if(!E(this,kl,"f"))for await(let e of this);return this.done()}get params(){return E(this,Ht,"f").params}pushMessages(...e){this.setMessagesParams(r=>({...r,messages:[...r.messages,...e]}))}then(e,r){return this.runUntilDone().then(e,r)}};yv=async function(e){return E(this,oo,"f")!==void 0?E(this,oo,"f"):(B(this,oo,vL(E(this,Ht,"f").params,e),"f"),E(this,oo,"f"))};async function vL(t,e=t.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(i=>i.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async i=>{let o=t.tools.find(s=>("name"in s?s.name:s.mcp_server_name)===i.name);if(!o||!("run"in o))return{type:"tool_result",tool_use_id:i.id,content:`Error: Tool '${i.name}' not found`,is_error:!0};try{let s=i.input;"parse"in o&&o.parse&&(s=o.parse(s));let a=await o.run(s);return{type:"tool_result",tool_use_id:i.id,content:a}}catch(s){return{type:"tool_result",tool_use_id:i.id,content:s instanceof pa?s.content:`Error: ${s instanceof Error?s.message:String(s)}`,is_error:!0}}}))}}var Sl=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new ro;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ee("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ee("Attempted to iterate over a response with no body");return new t(wd(e.body),r)}};var Il=class extends wt{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...r,headers:ve([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/messages/batches/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Sn,{query:i,...r,headers:ve([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(xt`/v1/messages/batches/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:i}=r??{};return this._client.post(xt`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:ve([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let i=await this.retrieve(e);if(!i.results_url)throw new ee(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);let{betas:o}=r??{};return this._client.get(i.results_url,{...n,headers:ve([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>Sl.fromResponse(a.response,a.controller))}};var aP={"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","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},xL=["claude-opus-4-6"],so=class extends wt{constructor(){super(...arguments),this.batches=new Il(this._client)}create(e,r){let n=cP(e),{betas:i,...o}=n;o.model in aP&&console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${aP[o.model]}
75
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),o.model in xL&&o.thinking&&o.thinking.type==="enabled"&&console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let s=this._client._options.timeout;if(!o.stream&&s==null){let c=vh[o.model]??void 0;s=this._client.calculateNonstreamingTimeout(o.max_tokens,c)}let a=bh(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:s??6e5,...r,headers:ve([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},a,r?.headers]),stream:n.stream??!1})}parse(e,r){return r={...r,headers:ve([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},r?.headers])},this.create(e,r).then(n=>pv(n,e,{logger:this._client.logger??console}))}stream(e,r){return Th.createMessage(this,e,r)}countTokens(e,r){let n=cP(e),{betas:i,...o}=n;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:ve([{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new $l(this._client,e,r)}};function cP(t){if(!t.output_format)return t;if(t.output_config?.format)throw new ee("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...r}=t;return{...r,output_config:{...t.output_config,format:e}}}so.Batches=Il;so.BetaToolRunner=$l;so.ToolError=pa;var El=class extends wt{create(e,r={},n){let{betas:i,...o}=r??{};return this._client.post(xt`/v1/skills/${e}/versions?beta=true`,_l({body:o,...n,headers:ve([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])},this._client))}retrieve(e,r,n){let{skill_id:i,betas:o}=r;return this._client.get(xt`/v1/skills/${i}/versions/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e,r={},n){let{betas:i,...o}=r??{};return this._client.getAPIList(xt`/v1/skills/${e}/versions?beta=true`,yl,{query:o,...n,headers:ve([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,r,n){let{skill_id:i,betas:o}=r;return this._client.delete(xt`/v1/skills/${i}/versions/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},n?.headers])})}};var ma=class extends wt{constructor(){super(...arguments),this.versions=new El(this._client)}create(e={},r){let{betas:n,...i}=e??{};return this._client.post("/v1/skills?beta=true",_l({body:i,...r,headers:ve([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])},this._client,!1))}retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/skills/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/skills?beta=true",yl,{query:i,...r,headers:ve([{"anthropic-beta":[...n??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,r={},n){let{betas:i}=r??{};return this._client.delete(xt`/v1/skills/${e}?beta=true`,{...n,headers:ve([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},n?.headers])})}};ma.Versions=El;var Kn=class extends wt{constructor(){super(...arguments),this.models=new vl(this._client),this.messages=new so(this._client),this.files=new bl(this._client),this.skills=new ma(this._client)}};Kn.Models=vl;Kn.Messages=so;Kn.Files=bl;Kn.Skills=ma;var ha=class extends wt{create(e,r){let{betas:n,...i}=e;return this._client.post("/v1/complete",{body:i,timeout:this._client._options.timeout??6e5,...r,headers:ve([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}};function lP(t){return t?.output_config?.format}function _v(t,e,r){let n=lP(e);return!e||!("parse"in(n??{}))?{...t,content:t.content.map(i=>i.type==="text"?Object.defineProperty({...i},"parsed_output",{value:null,enumerable:!1}):i),parsed_output:null}:bv(t,e,r)}function bv(t,e,r){let n=null,i=t.content.map(o=>{if(o.type==="text"){let s=IL(e,o.text);return n===null&&(n=s),Object.defineProperty({...o},"parsed_output",{value:s,enumerable:!1})}return o});return{...t,content:i,parsed_output:n}}function IL(t,e){let r=lP(t);if(r?.type!=="json_schema")return null;try{return"parse"in r?r.parse(e):JSON.parse(e)}catch(n){throw new ee(`Failed to parse structured output: ${n}`)}}var En,ts,Pl,Dd,Ah,Ld,Ud,zh,Zd,ao,Fd,Nh,Ch,ga,Oh,Rh,Vd,vv,uP,wv,xv,kv,$v,dP,pP="__json_buf";function fP(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Mh=class t{constructor(e,r){En.add(this),this.messages=[],this.receivedMessages=[],ts.set(this,void 0),Pl.set(this,null),this.controller=new AbortController,Dd.set(this,void 0),Ah.set(this,()=>{}),Ld.set(this,()=>{}),Ud.set(this,void 0),zh.set(this,()=>{}),Zd.set(this,()=>{}),ao.set(this,{}),Fd.set(this,!1),Nh.set(this,!1),Ch.set(this,!1),ga.set(this,!1),Oh.set(this,void 0),Rh.set(this,void 0),Vd.set(this,void 0),wv.set(this,n=>{if(B(this,Nh,!0,"f"),to(n)&&(n=new ar),n instanceof ar)return B(this,Ch,!0,"f"),this._emit("abort",n);if(n instanceof ee)return this._emit("error",n);if(n instanceof Error){let i=new ee(n.message);return i.cause=n,this._emit("error",i)}return this._emit("error",new ee(String(n)))}),B(this,Dd,new Promise((n,i)=>{B(this,Ah,n,"f"),B(this,Ld,i,"f")}),"f"),B(this,Ud,new Promise((n,i)=>{B(this,zh,n,"f"),B(this,Zd,i,"f")}),"f"),E(this,Dd,"f").catch(()=>{}),E(this,Ud,"f").catch(()=>{}),B(this,Pl,e,"f"),B(this,Vd,r?.logger??console,"f")}get response(){return E(this,Oh,"f")}get request_id(){return E(this,Rh,"f")}async withResponse(){B(this,ga,!0,"f");let e=await E(this,Dd,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n,{logger:i}={}){let o=new t(r,{logger:i});for(let s of r.messages)o._addMessageParam(s);return B(o,Pl,{...r,stream:!0},"f"),o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},E(this,wv,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let i=n?.signal,o;i&&(i.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),i.addEventListener("abort",o));try{E(this,En,"m",xv).call(this);let{response:s,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(s);for await(let c of a)E(this,En,"m",kv).call(this,c);if(a.controller.signal?.aborted)throw new ar;E(this,En,"m",$v).call(this)}finally{i&&o&&i.removeEventListener("abort",o)}}_connected(e){this.ended||(B(this,Oh,e,"f"),B(this,Rh,e?.headers.get("request-id"),"f"),E(this,Ah,"f").call(this,e),this._emit("connect"))}get ended(){return E(this,Fd,"f")}get errored(){return E(this,Nh,"f")}get aborted(){return E(this,Ch,"f")}abort(){this.controller.abort()}on(e,r){return(E(this,ao,"f")[e]||(E(this,ao,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=E(this,ao,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===r);return i>=0&&n.splice(i,1),this}once(e,r){return(E(this,ao,"f")[e]||(E(this,ao,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{B(this,ga,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){B(this,ga,!0,"f"),await E(this,Ud,"f")}get currentMessage(){return E(this,ts,"f")}async finalMessage(){return await this.done(),E(this,En,"m",vv).call(this)}async finalText(){return await this.done(),E(this,En,"m",uP).call(this)}_emit(e,...r){if(E(this,Fd,"f"))return;e==="end"&&(B(this,Fd,!0,"f"),E(this,zh,"f").call(this));let n=E(this,ao,"f")[e];if(n&&(E(this,ao,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...r))),e==="abort"){let i=r[0];!E(this,ga,"f")&&!n?.length&&Promise.reject(i),E(this,Ld,"f").call(this,i),E(this,Zd,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=r[0];!E(this,ga,"f")&&!n?.length&&Promise.reject(i),E(this,Ld,"f").call(this,i),E(this,Zd,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",E(this,En,"m",vv).call(this))}async _fromReadableStream(e,r){let n=r?.signal,i;n&&(n.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),n.addEventListener("abort",i));try{E(this,En,"m",xv).call(this),this._connected(null);let o=xi.fromReadableStream(e,this.controller);for await(let s of o)E(this,En,"m",kv).call(this,s);if(o.controller.signal?.aborted)throw new ar;E(this,En,"m",$v).call(this)}finally{n&&i&&n.removeEventListener("abort",i)}}[(ts=new WeakMap,Pl=new WeakMap,Dd=new WeakMap,Ah=new WeakMap,Ld=new WeakMap,Ud=new WeakMap,zh=new WeakMap,Zd=new WeakMap,ao=new WeakMap,Fd=new WeakMap,Nh=new WeakMap,Ch=new WeakMap,ga=new WeakMap,Oh=new WeakMap,Rh=new WeakMap,Vd=new WeakMap,wv=new WeakMap,En=new WeakSet,vv=function(){if(this.receivedMessages.length===0)throw new ee("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},uP=function(){if(this.receivedMessages.length===0)throw new ee("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new ee("stream ended without producing a content block with type=text");return r.join(" ")},xv=function(){this.ended||B(this,ts,void 0,"f")},kv=function(r){if(this.ended)return;let n=E(this,En,"m",dP).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let i=n.content.at(-1);switch(r.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",r.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",r.delta.citation,i.citations??[]);break}case"input_json_delta":{fP(i)&&i.input&&this._emit("inputJson",r.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",r.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(_v(n,E(this,Pl,"f"),{logger:E(this,Vd,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{B(this,ts,n,"f");break}case"content_block_start":case"message_delta":break}},$v=function(){if(this.ended)throw new ee("stream has ended, this shouldn't happen");let r=E(this,ts,"f");if(!r)throw new ee("request ended without sending any chunks");return B(this,ts,void 0,"f"),_v(r,E(this,Pl,"f"),{logger:E(this,Vd,"f")})},dP=function(r){let n=E(this,ts,"f");if(r.type==="message_start"){if(n)throw new ee(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new ee(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push({...r.content_block}),n;case"content_block_delta":{let i=n.content.at(r.index);switch(r.delta.type){case"text_delta":{i?.type==="text"&&(n.content[r.index]={...i,text:(i.text||"")+r.delta.text});break}case"citations_delta":{i?.type==="text"&&(n.content[r.index]={...i,citations:[...i.citations??[],r.delta.citation]});break}case"input_json_delta":{if(i&&fP(i)){let o=i[pP]||"";o+=r.delta.partial_json;let s={...i};Object.defineProperty(s,pP,{value:o,enumerable:!1,writable:!0}),o&&(s.input=wh(o)),n.content[r.index]=s}break}case"thinking_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,thinking:i.thinking+r.delta.thinking});break}case"signature_delta":{i?.type==="thinking"&&(n.content[r.index]={...i,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",i=>{let o=r.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of r)i.resolve(void 0);r.length=0}),this.on("abort",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),this.on("error",i=>{n=!0;for(let o of r)o.reject(i);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>r.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new xi(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Tl=class extends wt{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(xt`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",Sn,{query:e,...r})}delete(e,r){return this._client.delete(xt`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(xt`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new ee(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:ve([{Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,o)=>Sl.fromResponse(o.response,o.controller))}};var rs=class extends wt{constructor(){super(...arguments),this.batches=new Tl(this._client)}create(e,r){e.model in mP&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${mP[e.model]}
76
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),e.model in PL&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let n=this._client._options.timeout;if(!e.stream&&n==null){let o=vh[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}let i=bh(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,headers:ve([i,r?.headers]),stream:e.stream??!1})}parse(e,r){return this.create(e,r).then(n=>bv(n,e,{logger:this._client.logger??console}))}stream(e,r){return Mh.createMessage(this,e,r,{logger:this._client.logger??console})}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},mP={"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","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026"},PL=["claude-opus-4-6"];rs.Batches=Tl;var ya=class extends wt{retrieve(e,r={},n){let{betas:i}=r??{};return this._client.get(xt`/v1/models/${e}`,{...n,headers:ve([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...i}=e??{};return this._client.getAPIList("/v1/models",Sn,{query:i,...r,headers:ve([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}};var qd=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var Sv,Iv,jh,hP,gP="\\n\\nHuman:",yP="\\n\\nAssistant:",Pt=class{constructor({baseURL:e=qd("ANTHROPIC_BASE_URL"),apiKey:r=qd("ANTHROPIC_API_KEY")??null,authToken:n=qd("ANTHROPIC_AUTH_TOKEN")??null,...i}={}){Sv.add(this),jh.set(this,void 0);let o={apiKey:r,authToken:n,...i,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&j1())throw new ee(`It looks like you're running in a browser-like environment.
77
+
78
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
79
+ If you understand the risks and have appropriate mitigations in place,
80
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
81
+
82
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
83
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Iv.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s="warn";this.logLevel=s,this.logLevel=nv(o.logLevel,"ClientOptions.logLevel",this)??nv(qd("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??L1(),B(this,jh,Z1,"f"),this._options=o,this.apiKey=typeof r=="string"?r:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new 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')}async authHeaders(e){return ve([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ve([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return ve([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new ee(`Cannot stringify type ${typeof n}; 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("&")}getUserAgent(){return`${this.constructor.name}/JS ${Yo}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yb()}`}makeStatusError(e,r,n,i){return Jt.generate(e,r,n,i)}buildURL(e,r,n){let i=!E(this,Sv,"m",hP).call(this)&&n||this.baseURL,o=T1(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return A1(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new la(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,o=i.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(i);let{req:s,url:a,timeout:c}=await this.buildRequest(i,{retryCount:o-r});await this.prepareRequest(s,{url:a,options:i});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Yt(this).debug(`[${l}] sending request`,no({retryOfRequestLogID:n,method:i.method,url:a,options:i,headers:s.headers})),i.signal?.aborted)throw new ar;let f=new AbortController,p=await this.fetchWithTimeout(a,s,c,f).catch(vd),h=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new ar;let b=to(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),this.retryRequest(i,r,n??l);throw Yt(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Yt(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,no({retryOfRequestLogID:n,url:a,durationMs:h-d,message:p.message})),b?new cl:new Jo({cause:p})}let m=[...p.headers.entries()].filter(([y])=>y==="request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${u}${m}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${h-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let F=`retrying, ${r} attempts remaining`;return await U1(p.body),Yt(this).info(`${g} - ${F}`),Yt(this).debug(`[${l}] response error (${F})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),this.retryRequest(i,r,n??l,p.headers)}let b=y?"error; no more retries left":"error; not retryable";Yt(this).info(`${g} - ${b}`);let $=await p.text().catch(F=>vd(F).message),R=uh($),T=R?void 0:$;throw Yt(this).debug(`[${l}] response error (${b})`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(p.status,R,T,p.headers)}return Yt(this).info(g),Yt(this).debug(`[${l}] response start`,no({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:h-d})),{response:p,options:i,controller:f,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Id(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:o,method:s,...a}=r||{},c=this._makeAbort(i);o&&o.addEventListener("abort",c,{once:!0});let l=setTimeout(c,n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let o,s=i?.get("retry-after-ms");if(s){let c=parseFloat(s);Number.isNaN(c)||(o=c)}let a=i?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await C1(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new ee("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:o,query:s,defaultBaseURL:a}=n,c=this.buildURL(o,s,a);"timeout"in n&&N1("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:u}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:r});return{req:{method:i,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let s=ve([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...D1(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=ve([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:dh(e)}:E(this,jh,"f").call(this,{body:e,headers:n})}};Iv=Pt,jh=new WeakMap,Sv=new WeakSet,hP=function(){return this.baseURL!=="https://api.anthropic.com"};Pt.Anthropic=Iv;Pt.HUMAN_PROMPT=gP;Pt.AI_PROMPT=yP;Pt.DEFAULT_TIMEOUT=6e5;Pt.AnthropicError=ee;Pt.APIError=Jt;Pt.APIConnectionError=Jo;Pt.APIConnectionTimeoutError=cl;Pt.APIUserAbortError=ar;Pt.NotFoundError=pl;Pt.ConflictError=fl;Pt.RateLimitError=hl;Pt.BadRequestError=ll;Pt.AuthenticationError=ul;Pt.InternalServerError=gl;Pt.PermissionDeniedError=dl;Pt.UnprocessableEntityError=ml;Pt.toFile=yh;var ki=class extends Pt{constructor(){super(...arguments),this.completions=new ha(this),this.messages=new rs(this),this.models=new ya(this),this.beta=new Kn(this)}};ki.Completions=ha;ki.Messages=rs;ki.Models=ya;ki.Beta=Kn;var _P=new Ce("AnthropicChat"),Dh=class extends sl{addUserMessage(e){this.addTextMessage(e,"user",{role:"user",content:e||""})}addAssistantMessage(e){this.addTextMessage(e,"assistant",{role:"assistant",content:e||""})}async sendMessage(e,r){this.addUserMessage(e);let n=new ki({apiKey:this.config.apiKey,baseURL:this.getBaseURL(),dangerouslyAllowBrowser:!0}),i=!0,o=[];for(;i;){i=!1,await this.config.onBeforeMessageProcessing?.(),await this.trimMessages(),_P.debug("Before processing state",{messages:this.messageGroup.getAll().map(u=>u.data),tools:this.toolGroup.getAll().map(u=>u.data),context:this.contextGroup.getAll().map(u=>u.text)});let s=this.toolGroup.getAll().map(u=>({name:u.data?.name||"",description:u.data?.description||"",input_schema:{...u.data?.params,type:"object"}})),a;if(this.config.stream){let u=n.messages.stream({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.getAll().map(d=>d.data),tools:s,stream:!0});u.on("streamEvent",(d,f)=>{let p=this.parseMessageBlock(f,!0);this.config.onAIMessage?.([...o,p],!0),r?.([...o,p])});try{a=await u.finalMessage()}catch(d){throw d?.error?.error?.message?d.error.error:d}}else try{a=await n.messages.create({model:this.config.model,max_tokens:16e3,system:this.contextGroup.getAllAsString(),messages:this.messageGroup.items.map(u=>u.data),tools:s})}catch(u){throw u?.error?.error?.message?u.error.error:u}if(_P.debug("Message received",a),a.content?.length){let u=this.messageGroup.add(this.parseMessageBlock(a,!1));o.push(u)}let c=[],l=[];if(await Promise.all(a.content.map(async u=>{if(u.type!="tool_use")return;let d=this.findToolBySafeName(u.name);try{let f=await this.executeTool(d,u.input);l.push({type:"tool_result",tool_use_id:u.id,content:f}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolSuccessResponse:f,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}catch(f){let p=f?.message||"An unknown error occurred";l.push({type:"tool_result",tool_use_id:u.id,content:`Error performing tool call ${u.name}: ${p}`}),c.push({type:"tool_result",toolKbID:d?.kbItem?.id,toolKbName:d?.kbItem?.name,toolName:u.name,toolErrorResponse:p,toolCallInstanceID:u.id,toolCallHiddenInUI:d?.kbItem?.hideActionInUI})}})),l.length>0){let u=this.messageGroup.add({id:"msg-"+sr(),sections:c,data:{role:"user",content:l}});o.push(u),i=!0,this.config.onAIMessage?.(o,!0),r?.(o)}this.stats.tokensUsed+=a.usage.input_tokens+a.usage.output_tokens}return this.config.onAIMessage?.(o,!1),r?.(o),o}parseMessageBlock(e,r){let n=[];for(let i of e.content)if(i.type=="thinking")n.push({type:"thinking",text:i.thinking||""});else if(i.type=="text")n.push({type:"text",text:i.text||""});else if(i.type=="tool_use"){let o=this.findToolBySafeName(i.name);n.push({type:"tool_call",toolName:i.name,toolKbID:o?.kbItem?.id,toolKbName:o?.kbItem?.name,toolParameters:i.input,toolCallInstanceID:i.id,toolCallHiddenInUI:o?.kbItem?.hideActionInUI})}return{id:e.id,data:{role:e.role,content:e.content},sections:n,source:"assistant",streamingInProgress:r,usage:{inputTokens:e.usage?.input_tokens||0,outputTokens:e.usage?.output_tokens||0,cachedInputTokens:e.usage?.cache_read_input_tokens||0,totalTokens:(e.usage?.input_tokens||0)+(e.usage?.output_tokens||0)}}}async trimMessages(){for(await super.trimMessages();this.messageGroup.items[0]?.data?.content?.type=="tool_result";)this.messageGroup.items.shift()}};var AL="ENTRIES",kP="KEYS",$P="VALUES";var Bd=class{constructor(e,r){let n=e._tree,i=Array.from(n.keys());this.set=e,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:r}=Al(this._path);if(Al(r)==="")return{done:!1,value:this.result()};let n=e.get(Al(r));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=Al(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>Al(e)).filter(e=>e!=="").join("")}value(){return Al(this._path).node.get("")}result(){switch(this._type){case $P:return this.value();case kP:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},Al=t=>t[t.length-1],zL=(t,e,r)=>{let n=new Map;if(e===void 0)return n;let i=e.length+1,o=i+r,s=new Uint8Array(o*i).fill(r+1);for(let a=0;a<i;++a)s[a]=a;for(let a=1;a<o;++a)s[a*i]=a;return SP(t,e,r,n,s,1,i,""),n},SP=(t,e,r,n,i,o,s,a)=>{let c=o*s;e:for(let l of t.keys())if(l===""){let u=i[c-1];u<=r&&n.set(a,[t.get(l),u])}else{let u=o;for(let d=0;d<l.length;++d,++u){let f=l[d],p=s*u,h=p-s,m=i[p],g=Math.max(0,u-r-1),y=Math.min(s-1,u+r);for(let b=g;b<y;++b){let $=f!==e[b],R=i[h+b]+ +$,T=i[h+b+1]+1,P=i[p+b]+1,F=i[p+b+1]=Math.min(R,T,P);F<m&&(m=F)}if(m>r)continue e}SP(t.get(l),e,r,n,i,u,s,a+l)}},Wd=class t{constructor(e=new Map,r=""){this._size=void 0,this._tree=e,this._prefix=r}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[r,n]=Zh(this._tree,e.slice(this._prefix.length));if(r===void 0){let[i,o]=Ov(n);for(let s of i.keys())if(s!==""&&s.startsWith(o)){let a=new Map;return a.set(s.slice(o.length),i.get(s)),new t(a,e)}}return new t(r,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,NL(this._tree,e)}entries(){return new Bd(this,AL)}forEach(e){for(let[r,n]of this)e(r,n,this)}fuzzyGet(e,r){return zL(this._tree,e,r)}get(e){let r=zv(this._tree,e);return r!==void 0?r.get(""):void 0}has(e){let r=zv(this._tree,e);return r!==void 0&&r.has("")}keys(){return new Bd(this,kP)}set(e,r){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,Ev(this._tree,e).set("",r),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e);return n.set("",r(n.get(""))),this}fetch(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Ev(this._tree,e),i=n.get("");return i===void 0&&n.set("",i=r()),i}values(){return new Bd(this,$P)}[Symbol.iterator](){return this.entries()}static from(e){let r=new t;for(let[n,i]of e)r.set(n,i);return r}static fromObject(e){return t.from(Object.entries(e))}},Zh=(t,e,r=[])=>{if(e.length===0||t==null)return[t,r];for(let n of t.keys())if(n!==""&&e.startsWith(n))return r.push([t,n]),Zh(t.get(n),e.slice(n.length),r);return r.push([t,e]),Zh(void 0,"",r)},zv=(t,e)=>{if(e.length===0||t==null)return t;for(let r of t.keys())if(r!==""&&e.startsWith(r))return zv(t.get(r),e.slice(r.length))},Ev=(t,e)=>{let r=e.length;e:for(let n=0;t&&n<r;){for(let o of t.keys())if(o!==""&&e[n]===o[0]){let s=Math.min(r-n,o.length),a=1;for(;a<s&&e[n+a]===o[a];)++a;let c=t.get(o);if(a===o.length)t=c;else{let l=new Map;l.set(o.slice(a),c),t.set(e.slice(n,n+a),l),t.delete(o),t=l}n+=a;continue e}let i=new Map;return t.set(e.slice(n),i),i}return t},NL=(t,e)=>{let[r,n]=Zh(t,e);if(r!==void 0){if(r.delete(""),r.size===0)IP(n);else if(r.size===1){let[i,o]=r.entries().next().value;EP(n,i,o)}}},IP=t=>{if(t.length===0)return;let[e,r]=Ov(t);if(e.delete(r),e.size===0)IP(t.slice(0,-1));else if(e.size===1){let[n,i]=e.entries().next().value;n!==""&&EP(t.slice(0,-1),n,i)}},EP=(t,e,r)=>{if(t.length===0)return;let[n,i]=Ov(t);n.set(i+e,r),n.delete(i)},Ov=t=>t[t.length-1],Rv="or",PP="and",CL="and_not",Gd=class t{constructor(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let r=e.autoVacuum==null||e.autoVacuum===!0?Av:e.autoVacuum;this._options={...Tv,...e,autoVacuum:r,searchOptions:{...bP,...e.searchOptions||{}},autoSuggestOptions:{...DL,...e.autoSuggestOptions||{}}},this._index=new Wd,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Cv,this.addFields(this._options.fields)}add(e){let{extractField:r,stringifyField:n,tokenize:i,processTerm:o,fields:s,idField:a}=this._options,c=r(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(c))throw new Error(`MiniSearch: duplicate ID ${c}`);let l=this.addDocumentId(c);this.saveStoredFields(l,e);for(let u of s){let d=r(e,u);if(d==null)continue;let f=i(n(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.addFieldLength(l,p,this._documentCount-1,h);for(let m of f){let g=o(m,u);if(Array.isArray(g))for(let y of g)this.addTerm(p,l,y);else g&&this.addTerm(p,l,g)}}}addAll(e){for(let r of e)this.add(r)}addAllAsync(e,r={}){let{chunkSize:n=10}=r,i={chunk:[],promise:Promise.resolve()},{chunk:o,promise:s}=e.reduce(({chunk:a,promise:c},l,u)=>(a.push(l),(u+1)%n===0?{chunk:[],promise:c.then(()=>new Promise(d=>setTimeout(d,0))).then(()=>this.addAll(a))}:{chunk:a,promise:c}),i);return s.then(()=>this.addAll(o))}remove(e){let{tokenize:r,processTerm:n,extractField:i,stringifyField:o,fields:s,idField:a}=this._options,c=i(e,a);if(c==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);let l=this._idToShortId.get(c);if(l==null)throw new Error(`MiniSearch: cannot remove document with ID ${c}: it is not in the index`);for(let u of s){let d=i(e,u);if(d==null)continue;let f=r(o(d,u),u),p=this._fieldIds[u],h=new Set(f).size;this.removeFieldLength(l,p,this._documentCount,h);for(let m of f){let g=n(m,u);if(Array.isArray(g))for(let y of g)this.removeTerm(p,l,y);else g&&this.removeTerm(p,l,g)}}this._storedFields.delete(l),this._documentIds.delete(l),this._idToShortId.delete(c),this._fieldLength.delete(l),this._documentCount-=1}removeAll(e){if(e)for(let r of e)this.remove(r);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Wd,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(e){let r=this._idToShortId.get(e);if(r==null)throw new Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach((n,i)=>{this.removeFieldLength(r,i,this._documentCount,n)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:r,batchSize:n,batchWait:i}=this._options.autoVacuum;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:r,minDirtFactor:e})}discardAll(e){let r=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let n of e)this.discard(n)}finally{this._options.autoVacuum=r}this.maybeAutoVacuum()}replace(e){let{idField:r,extractField:n}=this._options,i=n(e,r);this.discard(i),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,r){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let n=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Cv,this.performVacuuming(e,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,r){let n=this._dirtCount;if(this.vacuumConditionsMet(r)){let i=e.batchSize||Nv.batchSize,o=e.batchWait||Nv.batchWait,s=1;for(let[a,c]of this._index){for(let[l,u]of c)for(let[d]of u)this._documentIds.has(d)||(u.size<=1?c.delete(l):u.delete(d));this._index.get(a).size===0&&this._index.delete(a),s%i===0&&await new Promise(l=>setTimeout(l,o)),s+=1}this._dirtCount-=n}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:r,minDirtFactor:n}=e;return r=r||Av.minDirtCount,n=n||Av.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let r=this._idToShortId.get(e);if(r!=null)return this._storedFields.get(r)}search(e,r={}){let{searchOptions:n}=this._options,i={...n,...r},o=this.executeQuery(e,r),s=[];for(let[a,{score:c,terms:l,match:u}]of o){let d=l.length||1,f={id:this._documentIds.get(a),score:c*d,terms:Object.keys(u),queryTerms:l,match:u};Object.assign(f,this._storedFields.get(a)),(i.filter==null||i.filter(f))&&s.push(f)}return e===t.wildcard&&i.boostDocument==null||s.sort(wP),s}autoSuggest(e,r={}){r={...this._options.autoSuggestOptions,...r};let n=new Map;for(let{score:o,terms:s}of this.search(e,r)){let a=s.join(" "),c=n.get(a);c!=null?(c.score+=o,c.count+=1):n.set(a,{score:o,terms:s,count:1})}let i=[];for(let[o,{score:s,terms:a,count:c}]of n)i.push({suggestion:o,terms:a,score:s/c});return i.sort(wP),i}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),r)}static async loadJSONAsync(e,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(e),r)}static getDefault(e){if(Tv.hasOwnProperty(e))return Pv(Tv,e);throw new Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=Lh(i),c._fieldLength=Lh(o),c._storedFields=Lh(s);for(let[l,u]of c._documentIds)c._idToShortId.set(u,l);for(let[l,u]of n){let d=new Map;for(let f of Object.keys(u)){let p=u[f];a===1&&(p=p.ds),d.set(parseInt(f,10),Lh(p))}c._index.set(l,d)}return c}static async loadJSAsync(e,r){let{index:n,documentIds:i,fieldLength:o,storedFields:s,serializationVersion:a}=e,c=this.instantiateMiniSearch(e,r);c._documentIds=await Uh(i),c._fieldLength=await Uh(o),c._storedFields=await Uh(s);for(let[u,d]of c._documentIds)c._idToShortId.set(d,u);let l=0;for(let[u,d]of n){let f=new Map;for(let p of Object.keys(d)){let h=d[p];a===1&&(h=h.ds),f.set(parseInt(p,10),await Uh(h))}++l%1e3===0&&await TP(0),c._index.set(u,f)}return c}static instantiateMiniSearch(e,r){let{documentCount:n,nextId:i,fieldIds:o,averageFieldLength:s,dirtCount:a,serializationVersion:c}=e;if(c!==1&&c!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let l=new t(r);return l._documentCount=n,l._nextId=i,l._idToShortId=new Map,l._fieldIds=o,l._avgFieldLength=s,l._dirtCount=a||0,l._index=new Wd,l}executeQuery(e,r={}){if(e===t.wildcard)return this.executeWildcardQuery(r);if(typeof e!="string"){let f={...r,...e,queries:void 0},p=e.queries.map(h=>this.executeQuery(h,f));return this.combineResults(p,f.combineWith)}let{tokenize:n,processTerm:i,searchOptions:o}=this._options,s={tokenize:n,processTerm:i,...o,...r},{tokenize:a,processTerm:c}=s,d=a(e).flatMap(f=>c(f)).filter(f=>!!f).map(jL(s)).map(f=>this.executeQuerySpec(f,s));return this.combineResults(d,s.combineWith)}executeQuerySpec(e,r){let n={...this._options.searchOptions,...r},i=(n.fields||this._options.fields).reduce((m,g)=>({...m,[g]:Pv(n.boost,g)||1}),{}),{boostDocument:o,weights:s,maxFuzzy:a,bm25:c}=n,{fuzzy:l,prefix:u}={...bP.weights,...s},d=this._index.get(e.term),f=this.termResults(e.term,e.term,1,e.termBoost,d,i,o,c),p,h;if(e.prefix&&(p=this._index.atPrefix(e.term)),e.fuzzy){let m=e.fuzzy===!0?.2:e.fuzzy,g=m<1?Math.min(a,Math.round(e.term.length*m)):m;g&&(h=this._index.fuzzyGet(e.term,g))}if(p)for(let[m,g]of p){let y=m.length-e.term.length;if(!y)continue;h?.delete(m);let b=u*m.length/(m.length+.3*y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}if(h)for(let m of h.keys()){let[g,y]=h.get(m);if(!y)continue;let b=l*m.length/(m.length+y);this.termResults(e.term,m,b,e.termBoost,g,i,o,c,f)}return f}executeWildcardQuery(e){let r=new Map,n={...this._options.searchOptions,...e};for(let[i,o]of this._documentIds){let s=n.boostDocument?n.boostDocument(o,"",this._storedFields.get(i)):1;r.set(i,{score:s,terms:[],match:{}})}return r}combineResults(e,r=Rv){if(e.length===0)return new Map;let n=r.toLowerCase(),i=OL[n];if(!i)throw new Error(`Invalid combination operator: ${r}`);return e.reduce(i)||new Map}toJSON(){let e=[];for(let[r,n]of this._index){let i={};for(let[o,s]of n)i[o]=Object.fromEntries(s);e.push([r,i])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:e,serializationVersion:2}}termResults(e,r,n,i,o,s,a,c,l=new Map){if(o==null)return l;for(let u of Object.keys(s)){let d=s[u],f=this._fieldIds[u],p=o.get(f);if(p==null)continue;let h=p.size,m=this._avgFieldLength[f];for(let g of p.keys()){if(!this._documentIds.has(g)){this.removeTerm(f,g,r),h-=1;continue}let y=a?a(this._documentIds.get(g),r,this._storedFields.get(g)):1;if(!y)continue;let b=p.get(g),$=this._fieldLength.get(g)[f],R=ML(b,h,this._documentCount,$,m,c),T=n*i*d*y*R,P=l.get(g);if(P){P.score+=T,LL(P.terms,e);let F=Pv(P.match,r);F?F.push(u):P.match[r]=[u]}else l.set(g,{score:T,terms:[e],match:{[r]:[u]}})}}return l}addTerm(e,r,n){let i=this._index.fetch(n,xP),o=i.get(e);if(o==null)o=new Map,o.set(r,1),i.set(e,o);else{let s=o.get(r);o.set(r,(s||0)+1)}}removeTerm(e,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,e,n);return}let i=this._index.fetch(n,xP),o=i.get(e);o==null||o.get(r)==null?this.warnDocumentChanged(r,e,n):o.get(r)<=1?o.size<=1?i.delete(e):o.delete(r):o.set(r,o.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)}warnDocumentChanged(e,r,n){for(let i of Object.keys(this._fieldIds))if(this._fieldIds[i]===r){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${n}" was not present in field "${i}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(e){let r=this._nextId;return this._idToShortId.set(e,r),this._documentIds.set(r,e),this._documentCount+=1,this._nextId+=1,r}addFields(e){for(let r=0;r<e.length;r++)this._fieldIds[e[r]]=r}addFieldLength(e,r,n,i){let o=this._fieldLength.get(e);o==null&&this._fieldLength.set(e,o=[]),o[r]=i;let a=(this._avgFieldLength[r]||0)*n+i;this._avgFieldLength[r]=a/(n+1)}removeFieldLength(e,r,n,i){if(n===1){this._avgFieldLength[r]=0;return}let o=this._avgFieldLength[r]*n-i;this._avgFieldLength[r]=o/(n-1)}saveStoredFields(e,r){let{storeFields:n,extractField:i}=this._options;if(n==null||n.length===0)return;let o=this._storedFields.get(e);o==null&&this._storedFields.set(e,o={});for(let s of n){let a=i(r,s);a!==void 0&&(o[s]=a)}}};Gd.wildcard=Symbol("*");var Pv=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,OL={[Rv]:(t,e)=>{for(let r of e.keys()){let n=t.get(r);if(n==null)t.set(r,e.get(r));else{let{score:i,terms:o,match:s}=e.get(r);n.score=n.score+i,n.match=Object.assign(n.match,s),vP(n.terms,o)}}return t},[PP]:(t,e)=>{let r=new Map;for(let n of e.keys()){let i=t.get(n);if(i==null)continue;let{score:o,terms:s,match:a}=e.get(n);vP(i.terms,s),r.set(n,{score:i.score+o,terms:i.terms,match:Object.assign(i.match,a)})}return r},[CL]:(t,e)=>{for(let r of e.keys())t.delete(r);return t}},RL={k:1.2,b:.7,d:.5},ML=(t,e,r,n,i,o)=>{let{k:s,b:a,d:c}=o;return Math.log(1+(r-e+.5)/(e+.5))*(c+t*(s+1)/(t+s*(1-a+a*n/i)))},jL=t=>(e,r,n)=>{let i=typeof t.fuzzy=="function"?t.fuzzy(e,r,n):t.fuzzy||!1,o=typeof t.prefix=="function"?t.prefix(e,r,n):t.prefix===!0,s=typeof t.boostTerm=="function"?t.boostTerm(e,r,n):1;return{term:e,fuzzy:i,prefix:o,termBoost:s}},Tv={idField:"id",extractField:(t,e)=>t[e],stringifyField:(t,e)=>t.toString(),tokenize:t=>t.split(UL),processTerm:t=>t.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(t,e)=>{typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},bP={combineWith:Rv,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:RL},DL={combineWith:PP,prefix:(t,e,r)=>e===r.length-1},Nv={batchSize:1e3,batchWait:10},Cv={minDirtFactor:.1,minDirtCount:20},Av={...Nv,...Cv},LL=(t,e)=>{t.includes(e)||t.push(e)},vP=(t,e)=>{for(let r of e)t.includes(r)||t.push(r)},wP=({score:t},{score:e})=>e-t,xP=()=>new Map,Lh=t=>{let e=new Map;for(let r of Object.keys(t))e.set(parseInt(r,10),t[r]);return e},Uh=async t=>{let e=new Map,r=0;for(let n of Object.keys(t))e.set(parseInt(n,10),t[n]),++r%1e3===0&&await TP(0);return e},TP=t=>new Promise(e=>setTimeout(e,t)),UL=/[\n\r\p{Z}\p{P}]+/u;var AP=t=>[{id:"search",type:"action",name:"Search the knowledge base.",content:"Search the knowledge base for information, actions, tools, tours, UI elements, etc. Use this on EVERY request if you don't have information. If the user asks for personal information, use this. If the user asks you to do something, use this to find the tool you need.",isContext:!0,hideActionInUI:"after-complete",parameters:[{name:"query",type:"string",description:"The search query"}],action:async(e,r)=>{let n=await r.knowledgeBase.search(e.query),i=r;i._lastKBsearch=e.query,i._nextRequestUseKBitems=n;let o=n.filter(a=>a.type!="action").map(a=>"- "+a.name).join(`
84
+ `)||"- (none)",s=n.filter(a=>a.type=="action").map(a=>"- "+a._functionID).join(`
85
+ `)||"- (none)";return`Search complete, context has been updated.
86
+ New information found:
87
+ ${o}
88
+
89
+ New tools available:
90
+ ${s}`}},{id:"ui.openURL",type:"action",name:"Open a URL in a new tab.",tags:"open, url, website, navigate, visit, go to, new tab, browser",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowOpenNewTab,content:"Opens the specified URL in a new tab. Use this when the user asks to open a website, visit a URL, go to a page, or navigate to a specific website. Only available when allowOpenNewTab flag is enabled.",parameters:[{name:"url",type:"string",description:"The URL to open in a new tab"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowOpenNewTab)throw new Error("Open New Tab action is not enabled for this persona.");if(!e.url||typeof e.url!="string")throw new Error("URL parameter is required and must be a string.");if(!window.open(e.url,"_blank"))throw new Error("Window blocked by popup blocker. Please allow popups for this site.");return`Opened URL: ${e.url}`}},{id:"ui.changeRoute",type:"action",name:"Change the current page route.",tags:"navigate, route, path, page, go to, change page, routing, navigation",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowChangeRoute,content:"Changes the current page route to the specified path. Use this when the user asks to navigate to a different page, go to a specific section, or change the current page route. Only available when allowChangeRoute flag is enabled.",parameters:[{name:"path",type:"string",description:'The path to navigate to (e.g., "/home", "/dashboard")'}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowChangeRoute)throw new Error("Change Route action is not enabled for this persona.");if(!e.path||typeof e.path!="string")throw new Error("Path parameter is required and must be a string.");let n=new URL(e.path,window.location.origin).pathname;return window.location.href=n,`Changed route to: ${n}`}},{id:"ui.sendEmail",type:"action",name:"Send an email",tags:"email, send, mail, compose, message, contact, mailto",isContext:!0,disabled:typeof window>"u"||!t?.flags?.allowSendEmail,content:"Sends an email using the user's default mail client by opening a mailto: link. Use this when the user asks to send an email, compose a message, or contact someone via email. Only available when allowSendEmail flag is enabled.",parameters:[{name:"email_address",type:"string",description:"The recipient email address"},{name:"subject",type:"string",description:"The email subject line"},{name:"body",type:"string",description:"The email body content"}],action:(e,r)=>{if(typeof window>"u")throw new Error("This action is only available in browser environments.");if(!r.flags.allowSendEmail)throw new Error("Send Email action is not enabled for this persona.");if(!e.email_address||typeof e.email_address!="string")throw new Error("Email address parameter is required and must be a string.");if(!e.subject||typeof e.subject!="string")throw new Error("Subject parameter is required and must be a string.");if(!e.body||typeof e.body!="string")throw new Error("Body parameter is required and must be a string.");let n=encodeURIComponent(e.email_address),i=encodeURIComponent(e.subject),o=encodeURIComponent(e.body),s=`mailto:${n}?subject=${i}&body=${o}`;try{window.location.href=s}catch(a){throw new Error(`Failed to open email client: ${a instanceof Error?a.message:String(a)}`)}return`Email opened in default mail client. Recipient: ${e.email_address}, Subject: ${e.subject}`}}];var Ze;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Ze||(Ze={}));var zP;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(zP||(zP={}));var K=Ze.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),co=t=>{switch(typeof t){case"undefined":return K.undefined;case"string":return K.string;case"number":return Number.isNaN(t)?K.nan:K.number;case"boolean":return K.boolean;case"function":return K.function;case"bigint":return K.bigint;case"symbol":return K.symbol;case"object":return Array.isArray(t)?K.array:t===null?K.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?K.promise:typeof Map<"u"&&t instanceof Map?K.map:typeof Set<"u"&&t instanceof Set?K.set:typeof Date<"u"&&t instanceof Date?K.date:K.object;default:return K.unknown}};var D=Ze.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var pn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let l=s.path[c];c===s.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(s))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ze.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};pn.create=t=>new pn(t);var ZL=(t,e)=>{let r;switch(t.code){case D.invalid_type:t.received===K.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case D.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ze.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ze.joinValues(t.keys,", ")}`;break;case D.invalid_union:r="Invalid input";break;case D.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ze.joinValues(t.options)}`;break;case D.invalid_enum_value:r=`Invalid enum value. Expected ${Ze.joinValues(t.options)}, received '${t.received}'`;break;case D.invalid_arguments:r="Invalid function arguments";break;case D.invalid_return_type:r="Invalid function return type";break;case D.invalid_date:r="Invalid date";break;case D.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ze.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case D.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case D.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case D.custom:r="Invalid input";break;case D.invalid_intersection_types:r="Intersection results could not be merged";break;case D.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case D.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ze.assertNever(t)}return{message:r}},ns=ZL;var FL=ns;function Hd(){return FL}var Fh=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}};function G(t,e){let r=Hd(),n=Fh({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ns?void 0:ns].filter(i=>!!i)});t.common.issues.push(n)}var vr=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return me;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return me;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},me=Object.freeze({status:"aborted"}),zl=t=>({status:"dirty",value:t}),Nr=t=>({status:"valid",value:t}),Mv=t=>t.status==="aborted",jv=t=>t.status==="dirty",_a=t=>t.status==="valid",Xd=t=>typeof Promise<"u"&&t instanceof Promise;var re;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(re||(re={}));var Pn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},NP=(t,e)=>{if(_a(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new pn(t.common.issues);return this._error=r,this._error}}};function Pe(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Re=class{get description(){return this._def.description}_getType(e){return co(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:co(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vr,ctx:{common:e.parent.common,data:e.data,parsedType:co(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Xd(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:co(e)},i=this._parseSync({data:e,path:n.path,parent:n});return NP(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:co(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return _a(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>_a(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:co(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Xd(i)?i:Promise.resolve(i));return NP(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:D.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Yn({schema:this,typeName:de.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Jn.create(this,this._def)}nullable(){return po.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return os.create(this)}promise(){return ba.create(this,this._def)}or(e){return Ml.create([this,e],this._def)}and(e){return jl.create(this,e,this._def)}transform(e){return new Yn({...Pe(this._def),schema:this,typeName:de.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Fl({...Pe(this._def),innerType:this,defaultValue:r,typeName:de.ZodDefault})}brand(){return new Vh({typeName:de.ZodBranded,type:this,...Pe(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vl({...Pe(this._def),innerType:this,catchValue:r,typeName:de.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return qh.create(this,e)}readonly(){return ql.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},VL=/^c[^\s-]{8,}$/i,qL=/^[0-9a-z]+$/,BL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WL=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,GL=/^[a-z0-9_-]{21}$/i,HL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,XL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,KL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dv,YL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,QL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,eU=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,tU=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rU=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nU=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,CP="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",iU=new RegExp(`^${CP}$`);function OP(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function oU(t){return new RegExp(`^${OP(t)}$`)}function sU(t){let e=`${CP}T${OP(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function aU(t,e){return!!((e==="v4"||!e)&&YL.test(t)||(e==="v6"||!e)&&eU.test(t))}function cU(t,e){if(!HL.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function lU(t,e){return!!((e==="v4"||!e)&&QL.test(t)||(e==="v6"||!e)&&tU.test(t))}var Cl=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==K.string){let o=this._getOrReturnCtx(e);return G(o,{code:D.invalid_type,expected:K.string,received:o.parsedType}),me}let n=new vr,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),G(i,{code:D.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),G(i,{code:D.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?G(i,{code:D.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&G(i,{code:D.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")KL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"email",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Dv||(Dv=new RegExp(JL,"u")),Dv.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"emoji",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")WL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"uuid",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")GL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"nanoid",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")VL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"cuid",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")qL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"cuid2",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")BL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"ulid",code:D.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),G(i,{validation:"url",code:D.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"regex",code:D.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?sU(o).test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?iU.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?oU(o).test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{code:D.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?XL.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"duration",code:D.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?aU(e.data,o.version)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"ip",code:D.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?cU(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"jwt",code:D.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?lU(e.data,o.version)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"cidr",code:D.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?rU.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"base64",code:D.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?nU.test(e.data)||(i=this._getOrReturnCtx(e,i),G(i,{validation:"base64url",code:D.invalid_string,message:o.message}),n.dirty()):Ze.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:D.invalid_string,...re.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...re.errToObj(e)})}url(e){return this._addCheck({kind:"url",...re.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...re.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...re.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...re.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...re.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...re.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...re.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...re.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...re.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...re.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...re.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...re.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...re.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...re.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...re.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...re.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...re.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...re.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...re.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...re.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...re.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...re.errToObj(r)})}nonempty(e){return this.min(1,re.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Cl.create=t=>new Cl({checks:[],typeName:de.ZodString,coerce:t?.coerce??!1,...Pe(t)});function uU(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var Kd=class t extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==K.number){let o=this._getOrReturnCtx(e);return G(o,{code:D.invalid_type,expected:K.number,received:o.parsedType}),me}let n,i=new vr;for(let o of this._def.checks)o.kind==="int"?Ze.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:D.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?uU(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:D.not_finite,message:o.message}),i.dirty()):Ze.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,re.toString(r))}gt(e,r){return this.setLimit("min",e,!1,re.toString(r))}lte(e,r){return this.setLimit("max",e,!0,re.toString(r))}lt(e,r){return this.setLimit("max",e,!1,re.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:re.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:re.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:re.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:re.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:re.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:re.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:re.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ze.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Kd.create=t=>new Kd({checks:[],typeName:de.ZodNumber,coerce:t?.coerce||!1,...Pe(t)});var Jd=class t extends Re{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==K.bigint)return this._getInvalidInput(e);let n,i=new vr;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),G(n,{code:D.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Ze.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return G(r,{code:D.invalid_type,expected:K.bigint,received:r.parsedType}),me}gte(e,r){return this.setLimit("min",e,!0,re.toString(r))}gt(e,r){return this.setLimit("min",e,!1,re.toString(r))}lte(e,r){return this.setLimit("max",e,!0,re.toString(r))}lt(e,r){return this.setLimit("max",e,!1,re.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:re.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:re.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:re.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Jd.create=t=>new Jd({checks:[],typeName:de.ZodBigInt,coerce:t?.coerce??!1,...Pe(t)});var Yd=class extends Re{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==K.boolean){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.boolean,received:n.parsedType}),me}return Nr(e.data)}};Yd.create=t=>new Yd({typeName:de.ZodBoolean,coerce:t?.coerce||!1,...Pe(t)});var Qd=class t extends Re{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==K.date){let o=this._getOrReturnCtx(e);return G(o,{code:D.invalid_type,expected:K.date,received:o.parsedType}),me}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return G(o,{code:D.invalid_date}),me}let n=new vr,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),G(i,{code:D.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),G(i,{code:D.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Ze.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:re.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:re.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Qd.create=t=>new Qd({checks:[],coerce:t?.coerce||!1,typeName:de.ZodDate,...Pe(t)});var ep=class extends Re{_parse(e){if(this._getType(e)!==K.symbol){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.symbol,received:n.parsedType}),me}return Nr(e.data)}};ep.create=t=>new ep({typeName:de.ZodSymbol,...Pe(t)});var Ol=class extends Re{_parse(e){if(this._getType(e)!==K.undefined){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.undefined,received:n.parsedType}),me}return Nr(e.data)}};Ol.create=t=>new Ol({typeName:de.ZodUndefined,...Pe(t)});var Rl=class extends Re{_parse(e){if(this._getType(e)!==K.null){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.null,received:n.parsedType}),me}return Nr(e.data)}};Rl.create=t=>new Rl({typeName:de.ZodNull,...Pe(t)});var tp=class extends Re{constructor(){super(...arguments),this._any=!0}_parse(e){return Nr(e.data)}};tp.create=t=>new tp({typeName:de.ZodAny,...Pe(t)});var is=class extends Re{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Nr(e.data)}};is.create=t=>new is({typeName:de.ZodUnknown,...Pe(t)});var $i=class extends Re{_parse(e){let r=this._getOrReturnCtx(e);return G(r,{code:D.invalid_type,expected:K.never,received:r.parsedType}),me}};$i.create=t=>new $i({typeName:de.ZodNever,...Pe(t)});var rp=class extends Re{_parse(e){if(this._getType(e)!==K.undefined){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.void,received:n.parsedType}),me}return Nr(e.data)}};rp.create=t=>new rp({typeName:de.ZodVoid,...Pe(t)});var os=class t extends Re{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==K.array)return G(r,{code:D.invalid_type,expected:K.array,received:r.parsedType}),me;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(G(r,{code:s?D.too_big:D.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(G(r,{code:D.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(G(r,{code:D.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new Pn(r,s,r.path,a)))).then(s=>vr.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Pn(r,s,r.path,a)));return vr.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:re.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:re.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:re.toString(r)}})}nonempty(e){return this.min(1,e)}};os.create=(t,e)=>new os({type:t,minLength:null,maxLength:null,exactLength:null,typeName:de.ZodArray,...Pe(e)});function Nl(t){if(t instanceof fn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Jn.create(Nl(n))}return new fn({...t._def,shape:()=>e})}else return t instanceof os?new os({...t._def,type:Nl(t.element)}):t instanceof Jn?Jn.create(Nl(t.unwrap())):t instanceof po?po.create(Nl(t.unwrap())):t instanceof uo?uo.create(t.items.map(e=>Nl(e))):t}var fn=class t extends Re{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=Ze.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==K.object){let l=this._getOrReturnCtx(e);return G(l,{code:D.invalid_type,expected:K.object,received:l.parsedType}),me}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof $i&&this._def.unknownKeys==="strip"))for(let l in i.data)s.includes(l)||a.push(l);let c=[];for(let l of s){let u=o[l],d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Pn(i,d,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof $i){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")a.length>0&&(G(i,{code:D.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Pn(i,d,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,f=await u.value;l.push({key:d,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>vr.mergeObjectSync(n,l)):vr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return re.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:re.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:de.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ze.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ze.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Nl(this)}partial(e){let r={};for(let n of Ze.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ze.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Jn;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return RP(Ze.objectKeys(this.shape))}};fn.create=(t,e)=>new fn({shape:()=>t,unknownKeys:"strip",catchall:$i.create(),typeName:de.ZodObject,...Pe(e)});fn.strictCreate=(t,e)=>new fn({shape:()=>t,unknownKeys:"strict",catchall:$i.create(),typeName:de.ZodObject,...Pe(e)});fn.lazycreate=(t,e)=>new fn({shape:t,unknownKeys:"strip",catchall:$i.create(),typeName:de.ZodObject,...Pe(e)});var Ml=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new pn(a.ctx.common.issues));return G(r,{code:D.invalid_union,unionErrors:s}),me}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new pn(c));return G(r,{code:D.invalid_union,unionErrors:a}),me}}get options(){return this._def.options}};Ml.create=(t,e)=>new Ml({options:t,typeName:de.ZodUnion,...Pe(e)});var lo=t=>t instanceof Dl?lo(t.schema):t instanceof Yn?lo(t.innerType()):t instanceof Ll?[t.value]:t instanceof Ul?t.options:t instanceof Zl?Ze.objectValues(t.enum):t instanceof Fl?lo(t._def.innerType):t instanceof Ol?[void 0]:t instanceof Rl?[null]:t instanceof Jn?[void 0,...lo(t.unwrap())]:t instanceof po?[null,...lo(t.unwrap())]:t instanceof Vh||t instanceof ql?lo(t.unwrap()):t instanceof Vl?lo(t._def.innerType):[],Lv=class t extends Re{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==K.object)return G(r,{code:D.invalid_type,expected:K.object,received:r.parsedType}),me;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(G(r,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),me)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let s=lo(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:de.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Pe(n)})}};function Uv(t,e){let r=co(t),n=co(e);if(t===e)return{valid:!0,data:t};if(r===K.object&&n===K.object){let i=Ze.objectKeys(e),o=Ze.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let c=Uv(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===K.array&&n===K.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],c=Uv(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===K.date&&n===K.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var jl=class extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,s)=>{if(Mv(o)||Mv(s))return me;let a=Uv(o.value,s.value);return a.valid?((jv(o)||jv(s))&&r.dirty(),{status:r.value,value:a.data}):(G(n,{code:D.invalid_intersection_types}),me)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};jl.create=(t,e,r)=>new jl({left:t,right:e,typeName:de.ZodIntersection,...Pe(r)});var uo=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==K.array)return G(n,{code:D.invalid_type,expected:K.array,received:n.parsedType}),me;if(n.data.length<this._def.items.length)return G(n,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),me;!this._def.rest&&n.data.length>this._def.items.length&&(G(n,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Pn(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>vr.mergeArray(r,s)):vr.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};uo.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new uo({items:t,typeName:de.ZodTuple,rest:null,...Pe(e)})};var Zv=class t extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==K.object)return G(n,{code:D.invalid_type,expected:K.object,received:n.parsedType}),me;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Pn(n,a,n.path,a)),value:s._parse(new Pn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?vr.mergeObjectAsync(r,i):vr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Re?new t({keyType:e,valueType:r,typeName:de.ZodRecord,...Pe(n)}):new t({keyType:Cl.create(),valueType:e,typeName:de.ZodRecord,...Pe(r)})}},np=class extends Re{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==K.map)return G(n,{code:D.invalid_type,expected:K.map,received:n.parsedType}),me;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],l)=>({key:i._parse(new Pn(n,a,n.path,[l,"key"])),value:o._parse(new Pn(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return me;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return me;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};np.create=(t,e,r)=>new np({valueType:e,keyType:t,typeName:de.ZodMap,...Pe(r)});var ip=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==K.set)return G(n,{code:D.invalid_type,expected:K.set,received:n.parsedType}),me;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(G(n,{code:D.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(G(n,{code:D.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let l=new Set;for(let u of c){if(u.status==="aborted")return me;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>o._parse(new Pn(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:re.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:re.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ip.create=(t,e)=>new ip({valueType:t,minSize:null,maxSize:null,typeName:de.ZodSet,...Pe(e)});var Fv=class t extends Re{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==K.function)return G(r,{code:D.invalid_type,expected:K.function,received:r.parsedType}),me;function n(a,c){return Fh({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hd(),ns].filter(l=>!!l),issueData:{code:D.invalid_arguments,argumentsError:c}})}function i(a,c){return Fh({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Hd(),ns].filter(l=>!!l),issueData:{code:D.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof ba){let a=this;return Nr(async function(...c){let l=new pn([]),u=await a._def.args.parseAsync(c,o).catch(p=>{throw l.addIssue(n(c,p)),l}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(p=>{throw l.addIssue(i(d,p)),l})})}else{let a=this;return Nr(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new pn([n(c,l.error)]);let u=Reflect.apply(s,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new pn([i(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:uo.create(e).rest(is.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||uo.create([]).rest(is.create()),returns:r||is.create(),typeName:de.ZodFunction,...Pe(n)})}},Dl=class extends Re{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Dl.create=(t,e)=>new Dl({getter:t,typeName:de.ZodLazy,...Pe(e)});var Ll=class extends Re{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return G(r,{received:r.data,code:D.invalid_literal,expected:this._def.value}),me}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ll.create=(t,e)=>new Ll({value:t,typeName:de.ZodLiteral,...Pe(e)});function RP(t,e){return new Ul({values:t,typeName:de.ZodEnum,...Pe(e)})}var Ul=class t extends Re{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return G(r,{expected:Ze.joinValues(n),received:r.parsedType,code:D.invalid_type}),me}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return G(r,{received:r.data,code:D.invalid_enum_value,options:n}),me}return Nr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Ul.create=RP;var Zl=class extends Re{_parse(e){let r=Ze.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==K.string&&n.parsedType!==K.number){let i=Ze.objectValues(r);return G(n,{expected:Ze.joinValues(i),received:n.parsedType,code:D.invalid_type}),me}if(this._cache||(this._cache=new Set(Ze.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ze.objectValues(r);return G(n,{received:n.data,code:D.invalid_enum_value,options:i}),me}return Nr(e.data)}get enum(){return this._def.values}};Zl.create=(t,e)=>new Zl({values:t,typeName:de.ZodNativeEnum,...Pe(e)});var ba=class extends Re{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==K.promise&&r.common.async===!1)return G(r,{code:D.invalid_type,expected:K.promise,received:r.parsedType}),me;let n=r.parsedType===K.promise?r.data:Promise.resolve(r.data);return Nr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ba.create=(t,e)=>new ba({type:t,typeName:de.ZodPromise,...Pe(e)});var Yn=class extends Re{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===de.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{G(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return me;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?me:c.status==="dirty"?zl(c.value):r.value==="dirty"?zl(c.value):c});{if(r.value==="aborted")return me;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?me:a.status==="dirty"?zl(a.value):r.value==="dirty"?zl(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?me:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?me:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_a(s))return me;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>_a(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):me);Ze.assertNever(i)}};Yn.create=(t,e,r)=>new Yn({schema:t,typeName:de.ZodEffects,effect:e,...Pe(r)});Yn.createWithPreprocess=(t,e,r)=>new Yn({schema:e,effect:{type:"preprocess",transform:t},typeName:de.ZodEffects,...Pe(r)});var Jn=class extends Re{_parse(e){return this._getType(e)===K.undefined?Nr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Jn.create=(t,e)=>new Jn({innerType:t,typeName:de.ZodOptional,...Pe(e)});var po=class extends Re{_parse(e){return this._getType(e)===K.null?Nr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};po.create=(t,e)=>new po({innerType:t,typeName:de.ZodNullable,...Pe(e)});var Fl=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===K.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Fl.create=(t,e)=>new Fl({innerType:t,typeName:de.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Pe(e)});var Vl=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xd(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new pn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vl.create=(t,e)=>new Vl({innerType:t,typeName:de.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Pe(e)});var op=class extends Re{_parse(e){if(this._getType(e)!==K.nan){let n=this._getOrReturnCtx(e);return G(n,{code:D.invalid_type,expected:K.nan,received:n.parsedType}),me}return{status:"valid",value:e.data}}};op.create=t=>new op({typeName:de.ZodNaN,...Pe(t)});var Vh=class extends Re{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},qh=class t extends Re{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?me:o.status==="dirty"?(r.dirty(),zl(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?me:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:de.ZodPipeline})}},ql=class extends Re{_parse(e){let r=this._def.innerType._parse(e),n=i=>(_a(i)&&(i.value=Object.freeze(i.value)),i);return Xd(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};ql.create=(t,e)=>new ql({innerType:t,typeName:de.ZodReadonly,...Pe(e)});var Zde={object:fn.lazycreate},de;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(de||(de={}));var Fde=Cl.create,Vde=Kd.create,qde=op.create,Bde=Jd.create,Wde=Yd.create,Gde=Qd.create,Hde=ep.create,Xde=Ol.create,Kde=Rl.create,Jde=tp.create,Yde=is.create,Qde=$i.create,epe=rp.create,tpe=os.create,dU=fn.create,rpe=fn.strictCreate,npe=Ml.create,ipe=Lv.create,ope=jl.create,spe=uo.create,ape=Zv.create,cpe=np.create,lpe=ip.create,upe=Fv.create,dpe=Dl.create,ppe=Ll.create,fpe=Ul.create,mpe=Zl.create,hpe=ba.create,gpe=Yn.create,ype=Jn.create,_pe=po.create,bpe=Yn.createWithPreprocess,vpe=qh.create;var Wh=Object.freeze({status:"aborted"});function O(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:t});function s(a){var c;let l=r?.Parent?new o:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Si=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bl=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},Bh={};function wr(t){return t&&Object.assign(Bh,t),Bh}var Z={};Yu(Z,{BIGINT_FORMAT_RANGES:()=>LP,Class:()=>qv,NUMBER_FORMAT_RANGES:()=>Kv,aborted:()=>ls,allowsEval:()=>Gv,assert:()=>_U,assertEqual:()=>mU,assertIs:()=>gU,assertNever:()=>yU,assertNotEqual:()=>hU,assignProp:()=>ss,base64ToUint8Array:()=>ZP,base64urlToUint8Array:()=>RU,cached:()=>Gl,captureStackTrace:()=>Xh,cleanEnum:()=>OU,cleanRegex:()=>cp,clone:()=>qr,cloneDef:()=>vU,createTransparentProxy:()=>IU,defineLazy:()=>ot,esc:()=>Hh,escapeRegex:()=>Ii,extend:()=>TU,finalizeIssue:()=>Qn,floatSafeRemainder:()=>Bv,getElementAtPath:()=>wU,getEnumValues:()=>Gh,getLengthableOrigin:()=>lp,getParsedType:()=>SU,getSizableOrigin:()=>UP,hexToUint8Array:()=>jU,isObject:()=>va,isPlainObject:()=>cs,issue:()=>Hl,joinValues:()=>ge,jsonStringifyReplacer:()=>Wl,merge:()=>zU,mergeDefs:()=>as,normalizeParams:()=>ae,nullish:()=>ap,numKeys:()=>$U,objectClone:()=>bU,omit:()=>PU,optionalKeys:()=>Xv,partial:()=>NU,pick:()=>EU,prefixIssues:()=>fo,primitiveTypes:()=>DP,promiseAllObject:()=>xU,propertyKeyTypes:()=>Hv,randomString:()=>kU,required:()=>CU,safeExtend:()=>AU,shallowClone:()=>jP,slugify:()=>Wv,stringifyPrimitive:()=>ye,uint8ArrayToBase64:()=>FP,uint8ArrayToBase64url:()=>MU,uint8ArrayToHex:()=>DU,unwrapMessage:()=>sp});function mU(t){return t}function hU(t){return t}function gU(t){}function yU(t){throw new Error}function _U(t){}function Gh(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function ge(t,e="|"){return t.map(r=>ye(r)).join(e)}function Wl(t,e){return typeof e=="bigint"?e.toString():e}function Gl(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ap(t){return t==null}function cp(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Bv(t,e){let r=(t.toString().split(".")[1]||"").length,n=e.toString(),i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(i=Number.parseInt(c[1]))}let o=r>i?r:i,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}var MP=Symbol("evaluating");function ot(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==MP)return n===void 0&&(n=MP,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function bU(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function ss(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function as(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function vU(t){return as(t._zod.def)}function wU(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function xU(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let o=0;o<e.length;o++)i[e[o]]=n[o];return i})}function kU(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Hh(t){return JSON.stringify(t)}function Wv(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Xh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function va(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Gv=Gl(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function cs(t){if(va(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(va(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function jP(t){return cs(t)?{...t}:Array.isArray(t)?[...t]:t}function $U(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var SU=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Hv=new Set(["string","number","symbol"]),DP=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ii(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function IU(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,o){return e??(e=t()),Reflect.set(e,n,i,o)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function ye(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Xv(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Kv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},LP={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function EU(t,e){let r=t._zod.def,n=as(t._zod.def,{get shape(){let i={};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(i[o]=r.shape[o])}return ss(this,"shape",i),i},checks:[]});return qr(t,n)}function PU(t,e){let r=t._zod.def,n=as(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete i[o]}return ss(this,"shape",i),i},checks:[]});return qr(t,n)}function TU(t,e){if(!cs(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let i=as(t._zod.def,{get shape(){let o={...t._zod.def.shape,...e};return ss(this,"shape",o),o},checks:[]});return qr(t,i)}function AU(t,e){if(!cs(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ss(this,"shape",n),n},checks:t._zod.def.checks};return qr(t,r)}function zU(t,e){let r=as(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return ss(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return qr(t,r)}function NU(t,e,r){let n=as(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:i[s]}):i[s])}else for(let s in i)o[s]=t?new t({type:"optional",innerType:i[s]}):i[s];return ss(this,"shape",o),o},checks:[]});return qr(e,n)}function CU(t,e,r){let n=as(e._zod.def,{get shape(){let i=e._zod.def.shape,o={...i};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new t({type:"nonoptional",innerType:i[s]});return ss(this,"shape",o),o},checks:[]});return qr(e,n)}function ls(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function fo(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function sp(t){return typeof t=="string"?t:t?.message}function Qn(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=sp(t.inst?._zod.def?.error?.(t))??sp(e?.error?.(t))??sp(r.customError?.(t))??sp(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function UP(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function lp(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Hl(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function OU(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ZP(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function FP(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function RU(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return ZP(e+r)}function MU(t){return FP(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function jU(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function DU(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var qv=class{constructor(...e){}};var VP=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Wl,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Kh=O("$ZodError",VP),Jv=O("$ZodError",VP,{Parent:Error});function Jh(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Yh(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>n({issues:s}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)r._errors.push(e(o));else{let s=r,a=0;for(;a<o.path.length;){let c=o.path[a];a===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(e(o))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return n(t),r}var Qh=t=>(e,r,n,i)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Si;if(s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>Qn(c,o,wr())));throw Xh(a,i?.callee),a}return s.value};var eg=t=>async(e,r,n,i)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??t)(s.issues.map(c=>Qn(c,o,wr())));throw Xh(a,i?.callee),a}return s.value};var up=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Si;return o.issues.length?{success:!1,error:new(t??Kh)(o.issues.map(s=>Qn(s,i,wr())))}:{success:!0,data:o.value}},Xl=up(Jv),dp=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>Qn(s,i,wr())))}:{success:!0,data:o.value}},pp=dp(Jv),qP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Qh(t)(e,r,i)};var BP=t=>(e,r,n)=>Qh(t)(e,r,n);var WP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return eg(t)(e,r,i)};var GP=t=>async(e,r,n)=>eg(t)(e,r,n);var HP=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return up(t)(e,r,i)};var XP=t=>(e,r,n)=>up(t)(e,r,n);var KP=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return dp(t)(e,r,i)};var JP=t=>async(e,r,n)=>dp(t)(e,r,n);var YP=/^[cC][^\s-]{8,}$/,QP=/^[0-9a-z]+$/,eT=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tT=/^[0-9a-vA-V]{20}$/,rT=/^[A-Za-z0-9]{27}$/,nT=/^[a-zA-Z0-9_-]{21}$/,iT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oT=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Yv=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var sT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var UU="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function aT(){return new RegExp(UU,"u")}var cT=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var uT=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,dT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,pT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qv=/^[A-Za-z0-9_-]*$/;var fT=/^\+(?:[0-9]){6,14}[0-9]$/,mT="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",hT=new RegExp(`^${mT}$`);function gT(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yT(t){return new RegExp(`^${gT(t)}$`)}function _T(t){let e=gT({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${mT}T(?:${n})$`)}var bT=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},vT=/^-?\d+n?$/,wT=/^-?\d+$/,xT=/^-?\d+(?:\.\d+)?/,kT=/^(?:true|false)$/i,$T=/^null$/i;var ST=/^[^A-Z]*$/,IT=/^[^a-z]*$/;var Qt=O("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ET={number:"number",bigint:"bigint",object:"date"},ew=O("$ZodCheckLessThan",(t,e)=>{Qt.init(t,e);let r=ET[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),tw=O("$ZodCheckGreaterThan",(t,e)=>{Qt.init(t,e);let r=ET[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,o=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),PT=O("$ZodCheckMultipleOf",(t,e)=>{Qt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Bv(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),TT=O("$ZodCheckNumberFormat",(t,e)=>{Qt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,o]=Kv[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=i,a.maximum=o,r&&(a.pattern=wT)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}});var AT=O("$ZodCheckMaxLength",(t,e)=>{var r;Qt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ap(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let i=n.value;if(i.length<=e.maximum)return;let s=lp(i);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),zT=O("$ZodCheckMinLength",(t,e)=>{var r;Qt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ap(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let s=lp(i);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),NT=O("$ZodCheckLengthEquals",(t,e)=>{var r;Qt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!ap(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,o=i.length;if(o===e.length)return;let s=lp(i),a=o>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),fp=O("$ZodCheckStringFormat",(t,e)=>{var r,n;Qt.init(t,e),t._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),CT=O("$ZodCheckRegex",(t,e)=>{fp.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),OT=O("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ST),fp.init(t,e)}),RT=O("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=IT),fp.init(t,e)}),MT=O("$ZodCheckIncludes",(t,e)=>{Qt.init(t,e);let r=Ii(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),jT=O("$ZodCheckStartsWith",(t,e)=>{Qt.init(t,e);let r=new RegExp(`^${Ii(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),DT=O("$ZodCheckEndsWith",(t,e)=>{Qt.init(t,e);let r=new RegExp(`.*${Ii(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var LT=O("$ZodCheckOverwrite",(t,e)=>{Qt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var tg=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
91
+ `).filter(s=>s),i=Math.min(...n.map(s=>s.length-s.trimStart().length)),o=n.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,i.join(`
92
+ `))}};var ZT={major:4,minor:1,patch:13};var rt=O("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ZT;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let o of i._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(s,a,c)=>{let l=ls(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&c?.async===!1)throw new Si;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=ls(s,f)))});else{if(s.issues.length===f)continue;l||(l=ls(s,f))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(ls(s))return s.aborted=!0,s;let l=i(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Si;return l.then(u=>t._zod.parse(u,c))}return t._zod.parse(l,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let l=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>o(u,s,a)):o(l,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Si;return c.then(l=>i(l,n,a))}return i(c,n,a)}}t["~standard"]={validate:i=>{try{let o=Xl(t,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return pp(t,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),Kl=O("$ZodString",(t,e)=>{rt.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??bT(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),pt=O("$ZodStringFormat",(t,e)=>{fp.init(t,e),Kl.init(t,e)}),nw=O("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=oT),pt.init(t,e)}),iw=O("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Yv(n))}else e.pattern??(e.pattern=Yv());pt.init(t,e)}),ow=O("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=sT),pt.init(t,e)}),sw=O("$ZodURL",(t,e)=>{pt.init(t,e),t._zod.check=r=>{try{let n=r.value.trim(),i=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),aw=O("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=aT()),pt.init(t,e)}),cw=O("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=nT),pt.init(t,e)}),lw=O("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=YP),pt.init(t,e)}),uw=O("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=QP),pt.init(t,e)}),dw=O("$ZodULID",(t,e)=>{e.pattern??(e.pattern=eT),pt.init(t,e)}),pw=O("$ZodXID",(t,e)=>{e.pattern??(e.pattern=tT),pt.init(t,e)}),fw=O("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=rT),pt.init(t,e)}),mw=O("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=_T(e)),pt.init(t,e)}),hw=O("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=hT),pt.init(t,e)}),gw=O("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=yT(e)),pt.init(t,e)}),yw=O("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=iT),pt.init(t,e)}),_w=O("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=cT),pt.init(t,e),t._zod.bag.format="ipv4"}),bw=O("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=lT),pt.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var vw=O("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=uT),pt.init(t,e)}),ww=O("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=dT),pt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,o]=n;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function YT(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var xw=O("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=pT),pt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{YT(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function ZU(t){if(!Qv.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return YT(r)}var kw=O("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Qv),pt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{ZU(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),$w=O("$ZodE164",(t,e)=>{e.pattern??(e.pattern=fT),pt.init(t,e)});function FU(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}var Sw=O("$ZodJWT",(t,e)=>{pt.init(t,e),t._zod.check=r=>{FU(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var ig=O("$ZodNumber",(t,e)=>{rt.init(t,e),t._zod.pattern=t._zod.bag.pattern??xT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...o?{received:o}:{}}),r}}),Iw=O("$ZodNumberFormat",(t,e)=>{TT.init(t,e),ig.init(t,e)}),og=O("$ZodBoolean",(t,e)=>{rt.init(t,e),t._zod.pattern=kT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),Ew=O("$ZodBigInt",(t,e)=>{rt.init(t,e),t._zod.pattern=vT,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var Pw=O("$ZodNull",(t,e)=>{rt.init(t,e),t._zod.pattern=$T,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}}),Tw=O("$ZodAny",(t,e)=>{rt.init(t,e),t._zod.parse=r=>r}),Aw=O("$ZodUnknown",(t,e)=>{rt.init(t,e),t._zod.parse=r=>r}),zw=O("$ZodNever",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Nw=O("$ZodDate",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:t}),r}});function FT(t,e,r){t.issues.length&&e.issues.push(...fo(r,t.issues)),e.value[r]=t.value}var Cw=O("$ZodArray",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(l=>FT(l,r,s))):FT(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function ng(t,e,r,n){t.issues.length&&e.issues.push(...fo(r,t.issues)),t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function QT(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Xv(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function eA(t,e,r,n,i,o){let s=[],a=i.keySet,c=i.catchall._zod,l=c.def.type;for(let u in e){if(a.has(u))continue;if(l==="never"){s.push(u);continue}let d=c.run({value:e[u],issues:[]},n);d instanceof Promise?t.push(d.then(f=>ng(f,r,u,e))):ng(d,r,u,e)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),t.length?Promise.all(t).then(()=>r):r}var tA=O("$ZodObject",(t,e)=>{if(rt.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Gl(()=>QT(e));ot(t._zod,"propValues",()=>{let a=e.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let i=va,o=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!i(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let h=d[f]._zod.run({value:l[f],issues:[]},c);h instanceof Promise?u.push(h.then(m=>ng(m,a,f,l))):ng(h,a,f,l)}return o?eA(u,l,a,c,n.value,t):u.length?Promise.all(u).then(()=>a):a}}),rA=O("$ZodObjectJIT",(t,e)=>{tA.init(t,e);let r=t._zod.parse,n=Gl(()=>QT(e)),i=f=>{let p=new tg(["shape","payload","ctx"]),h=n.value,m=$=>{let R=Hh($);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let $ of h.keys)g[$]=`key_${y++}`;p.write("const newResult = {};");for(let $ of h.keys){let R=g[$],T=Hh($);p.write(`const ${R} = ${m($)};`),p.write(`
93
+ if (${R}.issues.length) {
94
+ payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
95
+ ...iss,
96
+ path: iss.path ? [${T}, ...iss.path] : [${T}]
97
+ })));
98
+ }
99
+
100
+
101
+ if (${R}.value === undefined) {
102
+ if (${T} in input) {
103
+ newResult[${T}] = undefined;
104
+ }
105
+ } else {
106
+ newResult[${T}] = ${R}.value;
107
+ }
108
+
109
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return($,R)=>b(f,$,R)},o,s=va,a=!Bh.jitless,l=a&&Gv.value,u=e.catchall,d;t._zod.parse=(f,p)=>{d??(d=n.value);let h=f.value;return s(h)?a&&l&&p?.async===!1&&p.jitless!==!0?(o||(o=i(e.shape)),f=o(f,p),u?eA([],h,f,p,d,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function VT(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;let i=t.filter(o=>!ls(o));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Qn(s,n,wr())))}),e)}var sg=O("$ZodUnion",(t,e)=>{rt.init(t,e),ot(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),ot(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),ot(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),ot(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>cp(o.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1,a=[];for(let c of e.options){let l=c._zod.run({value:i.value,issues:[]},o);if(l instanceof Promise)a.push(l),s=!0;else{if(l.issues.length===0)return l;a.push(l)}}return s?Promise.all(a).then(c=>VT(c,i,t,o)):VT(a,i,t,o)}}),Ow=O("$ZodDiscriminatedUnion",(t,e)=>{sg.init(t,e);let r=t._zod.parse;ot(t._zod,"propValues",()=>{let i={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(s)){i[a]||(i[a]=new Set);for(let l of c)i[a].add(l)}}return i});let n=Gl(()=>{let i=e.options,o=new Map;for(let s of i){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let c of a){if(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,s)}}return o});t._zod.parse=(i,o)=>{let s=i.value;if(!va(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),i;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(i,o):e.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:t}),i)}}),Rw=O("$ZodIntersection",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,o=e.left._zod.run({value:i,issues:[]},n),s=e.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([c,l])=>qT(r,c,l)):qT(r,o,s)}});function rw(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(cs(t)&&cs(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),i={...t,...e};for(let o of n){let s=rw(t[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=e[n],s=rw(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function qT(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ls(t))return t;let n=rw(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Mw=O("$ZodRecord",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!cs(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let o=[],s=e.keyType._zod.values;if(s){r.value={};let a=new Set;for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){a.add(typeof l=="number"?l.toString():l);let u=e.valueType._zod.run({value:i[l],issues:[]},n);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&r.issues.push(...fo(l,d.issues)),r.value[l]=d.value})):(u.issues.length&&r.issues.push(...fo(l,u.issues)),r.value[l]=u.value)}let c;for(let l in i)a.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(u=>Qn(u,n,wr())),input:a,path:[a],inst:t}),r.value[c.value]=c.value;continue}let l=e.valueType._zod.run({value:i[a],issues:[]},n);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&r.issues.push(...fo(a,u.issues)),r.value[c.value]=u.value})):(l.issues.length&&r.issues.push(...fo(a,l.issues)),r.value[c.value]=l.value)}}return o.length?Promise.all(o).then(()=>r):r}});var jw=O("$ZodEnum",(t,e)=>{rt.init(t,e);let r=Gh(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>Hv.has(typeof i)).map(i=>typeof i=="string"?Ii(i):i.toString()).join("|")})$`),t._zod.parse=(i,o)=>{let s=i.value;return n.has(s)||i.issues.push({code:"invalid_value",values:r,input:s,inst:t}),i}}),Dw=O("$ZodLiteral",(t,e)=>{if(rt.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Ii(n):n?Ii(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var Lw=O("$ZodTransform",(t,e)=>{rt.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Bl(t.constructor.name);let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new Si;return r.value=i,r}});function BT(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var Uw=O("$ZodOptional",(t,e)=>{rt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ot(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ot(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${cp(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>BT(o,r.value)):BT(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Zw=O("$ZodNullable",(t,e)=>{rt.init(t,e),ot(t._zod,"optin",()=>e.innerType._zod.optin),ot(t._zod,"optout",()=>e.innerType._zod.optout),ot(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${cp(r.source)}|null)$`):void 0}),ot(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Fw=O("$ZodDefault",(t,e)=>{rt.init(t,e),t._zod.optin="optional",ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>WT(o,e)):WT(i,e)}});function WT(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Vw=O("$ZodPrefault",(t,e)=>{rt.init(t,e),t._zod.optin="optional",ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),qw=O("$ZodNonOptional",(t,e)=>{rt.init(t,e),ot(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>GT(o,t)):GT(i,t)}});function GT(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Bw=O("$ZodCatch",(t,e)=>{rt.init(t,e),ot(t._zod,"optin",()=>e.innerType._zod.optin),ot(t._zod,"optout",()=>e.innerType._zod.optout),ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Qn(s,n,wr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(o=>Qn(o,n,wr()))},input:r.value}),r.issues=[]),r)}});var Ww=O("$ZodPipe",(t,e)=>{rt.init(t,e),ot(t._zod,"values",()=>e.in._zod.values),ot(t._zod,"optin",()=>e.in._zod.optin),ot(t._zod,"optout",()=>e.out._zod.optout),ot(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=e.out._zod.run(r,n);return o instanceof Promise?o.then(s=>rg(s,e.in,n)):rg(o,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>rg(o,e.out,n)):rg(i,e.out,n)}});function rg(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var Gw=O("$ZodReadonly",(t,e)=>{rt.init(t,e),ot(t._zod,"propValues",()=>e.innerType._zod.propValues),ot(t._zod,"values",()=>e.innerType._zod.values),ot(t._zod,"optin",()=>e.innerType?._zod?.optin),ot(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(HT):HT(i)}});function HT(t){return t.value=Object.freeze(t.value),t}var Hw=O("$ZodCustom",(t,e)=>{Qt.init(t,e),rt.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(o=>XT(o,r,n,t));XT(i,r,n,t)}});function XT(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(Hl(i))}}var qU=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},BU=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${qU(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ye(n.values[0])}`:`Invalid option: expected one of ${ge(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ge(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Xw(){return{localeError:BU()}}var nA;var ag=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Jw(){return new ag}(nA=globalThis).__zod_globalRegistry??(nA.__zod_globalRegistry=Jw());var mo=globalThis.__zod_globalRegistry;function Yw(t,e){return new t({type:"string",...ae(e)})}function Qw(t,e){return new t({type:"string",coerce:!0,...ae(e)})}function ex(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function cg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function tx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function rx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function nx(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function ix(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function lg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function ox(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function sx(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function ax(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function cx(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function lx(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function ux(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function dx(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function px(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function fx(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function mx(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function hx(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function gx(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function yx(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function _x(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function bx(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function vx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function wx(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function xx(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function kx(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function $x(t,e){return new t({type:"number",checks:[],...ae(e)})}function Sx(t,e){return new t({type:"number",coerce:!0,checks:[],...ae(e)})}function Ix(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function Ex(t,e){return new t({type:"boolean",...ae(e)})}function Px(t,e){return new t({type:"boolean",coerce:!0,...ae(e)})}function Tx(t,e){return new t({type:"bigint",coerce:!0,...ae(e)})}function Ax(t,e){return new t({type:"null",...ae(e)})}function zx(t){return new t({type:"any"})}function Nx(t){return new t({type:"unknown"})}function Cx(t,e){return new t({type:"never",...ae(e)})}function Ox(t,e){return new t({type:"date",coerce:!0,...ae(e)})}function xa(t,e){return new ew({check:"less_than",...ae(e),value:t,inclusive:!1})}function ei(t,e){return new ew({check:"less_than",...ae(e),value:t,inclusive:!0})}function ka(t,e){return new tw({check:"greater_than",...ae(e),value:t,inclusive:!1})}function mn(t,e){return new tw({check:"greater_than",...ae(e),value:t,inclusive:!0})}function Jl(t,e){return new PT({check:"multiple_of",...ae(e),value:t})}function mp(t,e){return new AT({check:"max_length",...ae(e),maximum:t})}function $a(t,e){return new zT({check:"min_length",...ae(e),minimum:t})}function hp(t,e){return new NT({check:"length_equals",...ae(e),length:t})}function ug(t,e){return new CT({check:"string_format",format:"regex",...ae(e),pattern:t})}function dg(t){return new OT({check:"string_format",format:"lowercase",...ae(t)})}function pg(t){return new RT({check:"string_format",format:"uppercase",...ae(t)})}function fg(t,e){return new MT({check:"string_format",format:"includes",...ae(e),includes:t})}function mg(t,e){return new jT({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function hg(t,e){return new DT({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function ho(t){return new LT({check:"overwrite",tx:t})}function gg(t){return ho(e=>e.normalize(t))}function yg(){return ho(t=>t.trim())}function _g(){return ho(t=>t.toLowerCase())}function bg(){return ho(t=>t.toUpperCase())}function Rx(){return ho(t=>Wv(t))}function oA(t,e,r){return new t({type:"array",element:e,...ae(r)})}function Mx(t,e,r){let n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function jx(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}function Dx(t){let e=XU(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Hl(n,r.value,e._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),r.issues.push(Hl(i))}},t(r.value,r)));return e}function XU(t,e){let r=new Qt({check:"custom",...ae(e)});return r._zod.check=t,r}function Yl(t){return!!t._zod}function ri(t,e){return Yl(t)?Xl(t,e):t.safeParse(e)}function vg(t){if(!t)return;let e;if(Yl(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function mA(t){if(Yl(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var gp={};Yu(gp,{ZodISODate:()=>Zx,ZodISODateTime:()=>Lx,ZodISODuration:()=>Bx,ZodISOTime:()=>Vx,date:()=>Fx,datetime:()=>Ux,duration:()=>Wx,time:()=>qx});var Lx=O("ZodISODateTime",(t,e)=>{mw.init(t,e),kt.init(t,e)});function Ux(t){return vx(Lx,t)}var Zx=O("ZodISODate",(t,e)=>{hw.init(t,e),kt.init(t,e)});function Fx(t){return wx(Zx,t)}var Vx=O("ZodISOTime",(t,e)=>{gw.init(t,e),kt.init(t,e)});function qx(t){return xx(Vx,t)}var Bx=O("ZodISODuration",(t,e)=>{yw.init(t,e),kt.init(t,e)});function Wx(t){return kx(Bx,t)}var gA=(t,e)=>{Kh.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Yh(t,r)},flatten:{value:r=>Jh(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Wl,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Wl,2)}},isEmpty:{get(){return t.issues.length===0}}})},_ge=O("ZodError",gA),hn=O("ZodError",gA,{Parent:Error});var yA=Qh(hn),_A=eg(hn),bA=up(hn),vA=dp(hn),wA=qP(hn),xA=BP(hn),kA=WP(hn),$A=GP(hn),SA=HP(hn),IA=XP(hn),EA=KP(hn),PA=JP(hn);var ft=O("ZodType",(t,e)=>(rt.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(Z.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),t.clone=(r,n)=>qr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>yA(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bA(t,r,n),t.parseAsync=async(r,n)=>_A(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>vA(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>wA(t,r,n),t.decode=(r,n)=>xA(t,r,n),t.encodeAsync=async(r,n)=>kA(t,r,n),t.decodeAsync=async(r,n)=>$A(t,r,n),t.safeEncode=(r,n)=>SA(t,r,n),t.safeDecode=(r,n)=>IA(t,r,n),t.safeEncodeAsync=async(r,n)=>EA(t,r,n),t.safeDecodeAsync=async(r,n)=>PA(t,r,n),t.refine=(r,n)=>t.check(z6(r,n)),t.superRefine=r=>t.check(N6(r)),t.overwrite=r=>t.check(ho(r)),t.optional=()=>Tt(t),t.nullable=()=>zA(t),t.nullish=()=>Tt(zA(t)),t.nonoptional=r=>S6(t,r),t.array=()=>q(t),t.or=r=>mt([t,r]),t.and=r=>kg(t,r),t.transform=r=>Hx(t,UA(r)),t.default=r=>x6(t,r),t.prefault=r=>$6(t,r),t.catch=r=>E6(t,r),t.pipe=r=>Hx(t,r),t.readonly=()=>A6(t),t.describe=r=>{let n=t.clone();return mo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return mo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return mo.get(t);let n=t.clone();return mo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),NA=O("_ZodString",(t,e)=>{Kl.init(t,e),ft.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(ug(...n)),t.includes=(...n)=>t.check(fg(...n)),t.startsWith=(...n)=>t.check(mg(...n)),t.endsWith=(...n)=>t.check(hg(...n)),t.min=(...n)=>t.check($a(...n)),t.max=(...n)=>t.check(mp(...n)),t.length=(...n)=>t.check(hp(...n)),t.nonempty=(...n)=>t.check($a(1,...n)),t.lowercase=n=>t.check(dg(n)),t.uppercase=n=>t.check(pg(n)),t.trim=()=>t.check(yg()),t.normalize=(...n)=>t.check(gg(...n)),t.toLowerCase=()=>t.check(_g()),t.toUpperCase=()=>t.check(bg()),t.slugify=()=>t.check(Rx())}),Xx=O("ZodString",(t,e)=>{Kl.init(t,e),NA.init(t,e),t.email=r=>t.check(ex(WZ,r)),t.url=r=>t.check(lg(CA,r)),t.jwt=r=>t.check(bx(a6,r)),t.emoji=r=>t.check(ox(GZ,r)),t.guid=r=>t.check(cg(TA,r)),t.uuid=r=>t.check(tx(wg,r)),t.uuidv4=r=>t.check(rx(wg,r)),t.uuidv6=r=>t.check(nx(wg,r)),t.uuidv7=r=>t.check(ix(wg,r)),t.nanoid=r=>t.check(sx(HZ,r)),t.guid=r=>t.check(cg(TA,r)),t.cuid=r=>t.check(ax(XZ,r)),t.cuid2=r=>t.check(cx(KZ,r)),t.ulid=r=>t.check(lx(JZ,r)),t.base64=r=>t.check(gx(i6,r)),t.base64url=r=>t.check(yx(o6,r)),t.xid=r=>t.check(ux(YZ,r)),t.ksuid=r=>t.check(dx(QZ,r)),t.ipv4=r=>t.check(px(e6,r)),t.ipv6=r=>t.check(fx(t6,r)),t.cidrv4=r=>t.check(mx(r6,r)),t.cidrv6=r=>t.check(hx(n6,r)),t.e164=r=>t.check(_x(s6,r)),t.datetime=r=>t.check(Ux(r)),t.date=r=>t.check(Fx(r)),t.time=r=>t.check(qx(r)),t.duration=r=>t.check(Wx(r))});function x(t){return Yw(Xx,t)}var kt=O("ZodStringFormat",(t,e)=>{pt.init(t,e),NA.init(t,e)}),WZ=O("ZodEmail",(t,e)=>{ow.init(t,e),kt.init(t,e)});var TA=O("ZodGUID",(t,e)=>{nw.init(t,e),kt.init(t,e)});var wg=O("ZodUUID",(t,e)=>{iw.init(t,e),kt.init(t,e)});var CA=O("ZodURL",(t,e)=>{sw.init(t,e),kt.init(t,e)});function OA(t){return lg(CA,t)}var GZ=O("ZodEmoji",(t,e)=>{aw.init(t,e),kt.init(t,e)});var HZ=O("ZodNanoID",(t,e)=>{cw.init(t,e),kt.init(t,e)});var XZ=O("ZodCUID",(t,e)=>{lw.init(t,e),kt.init(t,e)});var KZ=O("ZodCUID2",(t,e)=>{uw.init(t,e),kt.init(t,e)});var JZ=O("ZodULID",(t,e)=>{dw.init(t,e),kt.init(t,e)});var YZ=O("ZodXID",(t,e)=>{pw.init(t,e),kt.init(t,e)});var QZ=O("ZodKSUID",(t,e)=>{fw.init(t,e),kt.init(t,e)});var e6=O("ZodIPv4",(t,e)=>{_w.init(t,e),kt.init(t,e)});var t6=O("ZodIPv6",(t,e)=>{bw.init(t,e),kt.init(t,e)});var r6=O("ZodCIDRv4",(t,e)=>{vw.init(t,e),kt.init(t,e)});var n6=O("ZodCIDRv6",(t,e)=>{ww.init(t,e),kt.init(t,e)});var i6=O("ZodBase64",(t,e)=>{xw.init(t,e),kt.init(t,e)});var o6=O("ZodBase64URL",(t,e)=>{kw.init(t,e),kt.init(t,e)});var s6=O("ZodE164",(t,e)=>{$w.init(t,e),kt.init(t,e)});var a6=O("ZodJWT",(t,e)=>{Sw.init(t,e),kt.init(t,e)});var xg=O("ZodNumber",(t,e)=>{ig.init(t,e),ft.init(t,e),t.gt=(n,i)=>t.check(ka(n,i)),t.gte=(n,i)=>t.check(mn(n,i)),t.min=(n,i)=>t.check(mn(n,i)),t.lt=(n,i)=>t.check(xa(n,i)),t.lte=(n,i)=>t.check(ei(n,i)),t.max=(n,i)=>t.check(ei(n,i)),t.int=n=>t.check(AA(n)),t.safe=n=>t.check(AA(n)),t.positive=n=>t.check(ka(0,n)),t.nonnegative=n=>t.check(mn(0,n)),t.negative=n=>t.check(xa(0,n)),t.nonpositive=n=>t.check(ei(0,n)),t.multipleOf=(n,i)=>t.check(Jl(n,i)),t.step=(n,i)=>t.check(Jl(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Qe(t){return $x(xg,t)}var c6=O("ZodNumberFormat",(t,e)=>{Iw.init(t,e),xg.init(t,e)});function AA(t){return Ix(c6,t)}var Kx=O("ZodBoolean",(t,e)=>{og.init(t,e),ft.init(t,e)});function lt(t){return Ex(Kx,t)}var RA=O("ZodBigInt",(t,e)=>{Ew.init(t,e),ft.init(t,e),t.gte=(n,i)=>t.check(mn(n,i)),t.min=(n,i)=>t.check(mn(n,i)),t.gt=(n,i)=>t.check(ka(n,i)),t.gte=(n,i)=>t.check(mn(n,i)),t.min=(n,i)=>t.check(mn(n,i)),t.lt=(n,i)=>t.check(xa(n,i)),t.lte=(n,i)=>t.check(ei(n,i)),t.max=(n,i)=>t.check(ei(n,i)),t.positive=n=>t.check(ka(BigInt(0),n)),t.negative=n=>t.check(xa(BigInt(0),n)),t.nonpositive=n=>t.check(ei(BigInt(0),n)),t.nonnegative=n=>t.check(mn(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(Jl(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var l6=O("ZodNull",(t,e)=>{Pw.init(t,e),ft.init(t,e)});function Jx(t){return Ax(l6,t)}var u6=O("ZodAny",(t,e)=>{Tw.init(t,e),ft.init(t,e)});function MA(){return zx(u6)}var d6=O("ZodUnknown",(t,e)=>{Aw.init(t,e),ft.init(t,e)});function $t(){return Nx(d6)}var p6=O("ZodNever",(t,e)=>{zw.init(t,e),ft.init(t,e)});function f6(t){return Cx(p6,t)}var jA=O("ZodDate",(t,e)=>{Nw.init(t,e),ft.init(t,e),t.min=(n,i)=>t.check(mn(n,i)),t.max=(n,i)=>t.check(ei(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var m6=O("ZodArray",(t,e)=>{Cw.init(t,e),ft.init(t,e),t.element=e.element,t.min=(r,n)=>t.check($a(r,n)),t.nonempty=r=>t.check($a(1,r)),t.max=(r,n)=>t.check(mp(r,n)),t.length=(r,n)=>t.check(hp(r,n)),t.unwrap=()=>t.element});function q(t,e){return oA(m6,t,e)}var DA=O("ZodObject",(t,e)=>{rA.init(t,e),ft.init(t,e),Z.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Br(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:$t()}),t.loose=()=>t.clone({...t._zod.def,catchall:$t()}),t.strict=()=>t.clone({...t._zod.def,catchall:f6()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Z.extend(t,r),t.safeExtend=r=>Z.safeExtend(t,r),t.merge=r=>Z.merge(t,r),t.pick=r=>Z.pick(t,r),t.omit=r=>Z.omit(t,r),t.partial=(...r)=>Z.partial(ZA,t,r[0]),t.required=(...r)=>Z.required(FA,t,r[0])});function W(t,e){let r={type:"object",shape:t??{},...Z.normalizeParams(e)};return new DA(r)}function Xt(t,e){return new DA({type:"object",shape:t,catchall:$t(),...Z.normalizeParams(e)})}var LA=O("ZodUnion",(t,e)=>{sg.init(t,e),ft.init(t,e),t.options=e.options});function mt(t,e){return new LA({type:"union",options:t,...Z.normalizeParams(e)})}var h6=O("ZodDiscriminatedUnion",(t,e)=>{LA.init(t,e),Ow.init(t,e)});function Yx(t,e,r){return new h6({type:"union",options:e,discriminator:t,...Z.normalizeParams(r)})}var g6=O("ZodIntersection",(t,e)=>{Rw.init(t,e),ft.init(t,e)});function kg(t,e){return new g6({type:"intersection",left:t,right:e})}var y6=O("ZodRecord",(t,e)=>{Mw.init(t,e),ft.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function St(t,e,r){return new y6({type:"record",keyType:t,valueType:e,...Z.normalizeParams(r)})}var Gx=O("ZodEnum",(t,e)=>{jw.init(t,e),ft.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Gx({...e,checks:[],...Z.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Gx({...e,checks:[],...Z.normalizeParams(i),entries:o})}});function Br(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Gx({type:"enum",entries:r,...Z.normalizeParams(e)})}var _6=O("ZodLiteral",(t,e)=>{Dw.init(t,e),ft.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ne(t,e){return new _6({type:"literal",values:Array.isArray(t)?t:[t],...Z.normalizeParams(e)})}var b6=O("ZodTransform",(t,e)=>{Lw.init(t,e),ft.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Bl(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(Z.issue(o,r.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(Z.issue(s))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r)):(r.value=i,r)}});function UA(t){return new b6({type:"transform",transform:t})}var ZA=O("ZodOptional",(t,e)=>{Uw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Tt(t){return new ZA({type:"optional",innerType:t})}var v6=O("ZodNullable",(t,e)=>{Zw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType});function zA(t){return new v6({type:"nullable",innerType:t})}var w6=O("ZodDefault",(t,e)=>{Fw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function x6(t,e){return new w6({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Z.shallowClone(e)}})}var k6=O("ZodPrefault",(t,e)=>{Vw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $6(t,e){return new k6({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Z.shallowClone(e)}})}var FA=O("ZodNonOptional",(t,e)=>{qw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType});function S6(t,e){return new FA({type:"nonoptional",innerType:t,...Z.normalizeParams(e)})}var I6=O("ZodCatch",(t,e)=>{Bw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function E6(t,e){return new I6({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var P6=O("ZodPipe",(t,e)=>{Ww.init(t,e),ft.init(t,e),t.in=e.in,t.out=e.out});function Hx(t,e){return new P6({type:"pipe",in:t,out:e})}var T6=O("ZodReadonly",(t,e)=>{Gw.init(t,e),ft.init(t,e),t.unwrap=()=>t._zod.def.innerType});function A6(t){return new T6({type:"readonly",innerType:t})}var VA=O("ZodCustom",(t,e)=>{Hw.init(t,e),ft.init(t,e)});function qA(t,e){return Mx(VA,t??(()=>!0),e)}function z6(t,e={}){return jx(VA,t,e)}function N6(t){return Dx(t)}function Qx(t,e){return Hx(UA(t),e)}var WA={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var BA;BA||(BA={});var $g={};Yu($g,{bigint:()=>M6,boolean:()=>R6,date:()=>j6,number:()=>O6,string:()=>C6});function C6(t){return Qw(Xx,t)}function O6(t){return Sx(xg,t)}function R6(t){return Px(Kx,t)}function M6(t){return Tx(RA,t)}function j6(t){return Ox(jA,t)}wr(Xw());var eu="2025-11-25";var HA=[eu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],us="io.modelcontextprotocol/related-task",Ig="2.0",cr=qA(t=>t!==null&&(typeof t=="object"||typeof t=="function")),XA=mt([x(),Qe().int()]),KA=x(),Dge=Xt({ttl:mt([Qe(),Jx()]).optional(),pollInterval:Qe().optional()}),L6=W({ttl:Qe().optional()}),U6=W({taskId:x()}),t0=Xt({progressToken:XA.optional(),[us]:U6.optional()}),gn=W({_meta:t0.optional()}),yp=gn.extend({task:L6.optional()}),JA=t=>yp.safeParse(t).success,lr=W({method:x(),params:gn.loose().optional()}),Tn=W({_meta:t0.optional()}),An=W({method:x(),params:Tn.loose().optional()}),ur=Xt({_meta:t0.optional()}),Eg=mt([x(),Qe().int()]),YA=W({jsonrpc:ne(Ig),id:Eg,...lr.shape}).strict(),_p=t=>YA.safeParse(t).success,QA=W({jsonrpc:ne(Ig),...An.shape}).strict(),ez=t=>QA.safeParse(t).success,r0=W({jsonrpc:ne(Ig),id:Eg,result:ur}).strict(),Sa=t=>r0.safeParse(t).success;var we;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(we||(we={}));var n0=W({jsonrpc:ne(Ig),id:Eg.optional(),error:W({code:Qe().int(),message:x(),data:$t().optional()})}).strict();var tz=t=>n0.safeParse(t).success;var Pg=mt([YA,QA,r0,n0]),Lge=mt([r0,n0]),Ia=ur.strict(),Z6=Tn.extend({requestId:Eg.optional(),reason:x().optional()}),Tg=An.extend({method:ne("notifications/cancelled"),params:Z6}),F6=W({src:x(),mimeType:x().optional(),sizes:q(x()).optional(),theme:Br(["light","dark"]).optional()}),bp=W({icons:q(F6).optional()}),Ql=W({name:x(),title:x().optional()}),rz=Ql.extend({...Ql.shape,...bp.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),V6=kg(W({applyDefaults:lt().optional()}),St(x(),$t())),q6=Qx(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,kg(W({form:V6.optional(),url:cr.optional()}),St(x(),$t()).optional())),B6=Xt({list:cr.optional(),cancel:cr.optional(),requests:Xt({sampling:Xt({createMessage:cr.optional()}).optional(),elicitation:Xt({create:cr.optional()}).optional()}).optional()}),W6=Xt({list:cr.optional(),cancel:cr.optional(),requests:Xt({tools:Xt({call:cr.optional()}).optional()}).optional()}),G6=W({experimental:St(x(),cr).optional(),sampling:W({context:cr.optional(),tools:cr.optional()}).optional(),elicitation:q6.optional(),roots:W({listChanged:lt().optional()}).optional(),tasks:B6.optional()}),H6=gn.extend({protocolVersion:x(),capabilities:G6,clientInfo:rz}),X6=lr.extend({method:ne("initialize"),params:H6});var K6=W({experimental:St(x(),cr).optional(),logging:cr.optional(),completions:cr.optional(),prompts:W({listChanged:lt().optional()}).optional(),resources:W({subscribe:lt().optional(),listChanged:lt().optional()}).optional(),tools:W({listChanged:lt().optional()}).optional(),tasks:W6.optional()}),i0=ur.extend({protocolVersion:x(),capabilities:K6,serverInfo:rz,instructions:x().optional()}),nz=An.extend({method:ne("notifications/initialized"),params:Tn.optional()}),iz=t=>nz.safeParse(t).success,Ag=lr.extend({method:ne("ping"),params:gn.optional()}),J6=W({progress:Qe(),total:Tt(Qe()),message:Tt(x())}),Y6=W({...Tn.shape,...J6.shape,progressToken:XA}),zg=An.extend({method:ne("notifications/progress"),params:Y6}),Q6=gn.extend({cursor:KA.optional()}),vp=lr.extend({params:Q6.optional()}),wp=ur.extend({nextCursor:KA.optional()}),eF=Br(["working","input_required","completed","failed","cancelled"]),xp=W({taskId:x(),status:eF,ttl:mt([Qe(),Jx()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:Tt(Qe()),statusMessage:Tt(x())}),Ea=ur.extend({task:xp}),tF=Tn.merge(xp),kp=An.extend({method:ne("notifications/tasks/status"),params:tF}),Ng=lr.extend({method:ne("tasks/get"),params:gn.extend({taskId:x()})}),Cg=ur.merge(xp),Og=lr.extend({method:ne("tasks/result"),params:gn.extend({taskId:x()})}),Uge=ur.loose(),Rg=vp.extend({method:ne("tasks/list")}),Mg=wp.extend({tasks:q(xp)}),jg=lr.extend({method:ne("tasks/cancel"),params:gn.extend({taskId:x()})}),oz=ur.merge(xp),sz=W({uri:x(),mimeType:Tt(x()),_meta:St(x(),$t()).optional()}),az=sz.extend({text:x()}),o0=x().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),cz=sz.extend({blob:o0}),$p=Br(["user","assistant"]),tu=W({audience:q($p).optional(),priority:Qe().min(0).max(1).optional(),lastModified:gp.datetime({offset:!0}).optional()}),lz=W({...Ql.shape,...bp.shape,uri:x(),description:Tt(x()),mimeType:Tt(x()),annotations:tu.optional(),_meta:Tt(Xt({}))}),rF=W({...Ql.shape,...bp.shape,uriTemplate:x(),description:Tt(x()),mimeType:Tt(x()),annotations:tu.optional(),_meta:Tt(Xt({}))}),nF=vp.extend({method:ne("resources/list")}),s0=wp.extend({resources:q(lz)}),iF=vp.extend({method:ne("resources/templates/list")}),a0=wp.extend({resourceTemplates:q(rF)}),c0=gn.extend({uri:x()}),oF=c0,sF=lr.extend({method:ne("resources/read"),params:oF}),l0=ur.extend({contents:q(mt([az,cz]))}),u0=An.extend({method:ne("notifications/resources/list_changed"),params:Tn.optional()}),aF=c0,cF=lr.extend({method:ne("resources/subscribe"),params:aF}),lF=c0,uF=lr.extend({method:ne("resources/unsubscribe"),params:lF}),dF=Tn.extend({uri:x()}),pF=An.extend({method:ne("notifications/resources/updated"),params:dF}),fF=W({name:x(),description:Tt(x()),required:Tt(lt())}),mF=W({...Ql.shape,...bp.shape,description:Tt(x()),arguments:Tt(q(fF)),_meta:Tt(Xt({}))}),hF=vp.extend({method:ne("prompts/list")}),d0=wp.extend({prompts:q(mF)}),gF=gn.extend({name:x(),arguments:St(x(),x()).optional()}),yF=lr.extend({method:ne("prompts/get"),params:gF}),p0=W({type:ne("text"),text:x(),annotations:tu.optional(),_meta:St(x(),$t()).optional()}),f0=W({type:ne("image"),data:o0,mimeType:x(),annotations:tu.optional(),_meta:St(x(),$t()).optional()}),m0=W({type:ne("audio"),data:o0,mimeType:x(),annotations:tu.optional(),_meta:St(x(),$t()).optional()}),_F=W({type:ne("tool_use"),name:x(),id:x(),input:St(x(),$t()),_meta:St(x(),$t()).optional()}),bF=W({type:ne("resource"),resource:mt([az,cz]),annotations:tu.optional(),_meta:St(x(),$t()).optional()}),vF=lz.extend({type:ne("resource_link")}),h0=mt([p0,f0,m0,vF,bF]),wF=W({role:$p,content:h0}),g0=ur.extend({description:x().optional(),messages:q(wF)}),y0=An.extend({method:ne("notifications/prompts/list_changed"),params:Tn.optional()}),xF=W({title:x().optional(),readOnlyHint:lt().optional(),destructiveHint:lt().optional(),idempotentHint:lt().optional(),openWorldHint:lt().optional()}),kF=W({taskSupport:Br(["required","optional","forbidden"]).optional()}),uz=W({...Ql.shape,...bp.shape,description:x().optional(),inputSchema:W({type:ne("object"),properties:St(x(),cr).optional(),required:q(x()).optional()}).catchall($t()),outputSchema:W({type:ne("object"),properties:St(x(),cr).optional(),required:q(x()).optional()}).catchall($t()).optional(),annotations:xF.optional(),execution:kF.optional(),_meta:St(x(),$t()).optional()}),$F=vp.extend({method:ne("tools/list")}),_0=wp.extend({tools:q(uz)}),ru=ur.extend({content:q(h0).default([]),structuredContent:St(x(),$t()).optional(),isError:lt().optional()}),Zge=ru.or(ur.extend({toolResult:$t()})),SF=yp.extend({name:x(),arguments:St(x(),$t()).optional()}),IF=lr.extend({method:ne("tools/call"),params:SF}),Sp=An.extend({method:ne("notifications/tools/list_changed"),params:Tn.optional()}),dz=W({autoRefresh:lt().default(!0),debounceMs:Qe().int().nonnegative().default(300)}),pz=Br(["debug","info","notice","warning","error","critical","alert","emergency"]),EF=gn.extend({level:pz}),PF=lr.extend({method:ne("logging/setLevel"),params:EF}),TF=Tn.extend({level:pz,logger:x().optional(),data:$t()}),b0=An.extend({method:ne("notifications/message"),params:TF}),AF=W({name:x().optional()}),zF=W({hints:q(AF).optional(),costPriority:Qe().min(0).max(1).optional(),speedPriority:Qe().min(0).max(1).optional(),intelligencePriority:Qe().min(0).max(1).optional()}),NF=W({mode:Br(["auto","required","none"]).optional()}),CF=W({type:ne("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:q(h0).default([]),structuredContent:W({}).loose().optional(),isError:lt().optional(),_meta:St(x(),$t()).optional()}),OF=Yx("type",[p0,f0,m0]),Sg=Yx("type",[p0,f0,m0,_F,CF]),RF=W({role:$p,content:mt([Sg,q(Sg)]),_meta:St(x(),$t()).optional()}),MF=yp.extend({messages:q(RF),modelPreferences:zF.optional(),systemPrompt:x().optional(),includeContext:Br(["none","thisServer","allServers"]).optional(),temperature:Qe().optional(),maxTokens:Qe().int(),stopSequences:q(x()).optional(),metadata:cr.optional(),tools:q(uz).optional(),toolChoice:NF.optional()}),v0=lr.extend({method:ne("sampling/createMessage"),params:MF}),w0=ur.extend({model:x(),stopReason:Tt(Br(["endTurn","stopSequence","maxTokens"]).or(x())),role:$p,content:OF}),x0=ur.extend({model:x(),stopReason:Tt(Br(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:$p,content:mt([Sg,q(Sg)])}),jF=W({type:ne("boolean"),title:x().optional(),description:x().optional(),default:lt().optional()}),DF=W({type:ne("string"),title:x().optional(),description:x().optional(),minLength:Qe().optional(),maxLength:Qe().optional(),format:Br(["email","uri","date","date-time"]).optional(),default:x().optional()}),LF=W({type:Br(["number","integer"]),title:x().optional(),description:x().optional(),minimum:Qe().optional(),maximum:Qe().optional(),default:Qe().optional()}),UF=W({type:ne("string"),title:x().optional(),description:x().optional(),enum:q(x()),default:x().optional()}),ZF=W({type:ne("string"),title:x().optional(),description:x().optional(),oneOf:q(W({const:x(),title:x()})),default:x().optional()}),FF=W({type:ne("string"),title:x().optional(),description:x().optional(),enum:q(x()),enumNames:q(x()).optional(),default:x().optional()}),VF=mt([UF,ZF]),qF=W({type:ne("array"),title:x().optional(),description:x().optional(),minItems:Qe().optional(),maxItems:Qe().optional(),items:W({type:ne("string"),enum:q(x())}),default:q(x()).optional()}),BF=W({type:ne("array"),title:x().optional(),description:x().optional(),minItems:Qe().optional(),maxItems:Qe().optional(),items:W({anyOf:q(W({const:x(),title:x()}))}),default:q(x()).optional()}),WF=mt([qF,BF]),GF=mt([FF,VF,WF]),HF=mt([GF,jF,DF,LF]),XF=yp.extend({mode:ne("form").optional(),message:x(),requestedSchema:W({type:ne("object"),properties:St(x(),HF),required:q(x()).optional()})}),KF=yp.extend({mode:ne("url"),message:x(),elicitationId:x(),url:x().url()}),JF=mt([XF,KF]),k0=lr.extend({method:ne("elicitation/create"),params:JF}),YF=Tn.extend({elicitationId:x()}),QF=An.extend({method:ne("notifications/elicitation/complete"),params:YF}),$0=ur.extend({action:Br(["accept","decline","cancel"]),content:Qx(t=>t===null?void 0:t,St(x(),mt([x(),Qe(),lt(),q(x())])).optional())}),eV=W({type:ne("ref/resource"),uri:x()});var tV=W({type:ne("ref/prompt"),name:x()}),rV=gn.extend({ref:mt([tV,eV]),argument:W({name:x(),value:x()}),context:W({arguments:St(x(),x()).optional()}).optional()}),nV=lr.extend({method:ne("completion/complete"),params:rV});var S0=ur.extend({completion:Xt({values:q(x()).max(100),total:Tt(Qe().int()),hasMore:Tt(lt())})}),iV=W({uri:x().startsWith("file://"),name:x().optional(),_meta:St(x(),$t()).optional()}),oV=lr.extend({method:ne("roots/list"),params:gn.optional()}),sV=ur.extend({roots:q(iV)}),aV=An.extend({method:ne("notifications/roots/list_changed"),params:Tn.optional()}),Fge=mt([Ag,X6,nV,PF,yF,hF,nF,iF,sF,cF,uF,IF,$F,Ng,Og,Rg,jg]),Vge=mt([Tg,zg,nz,aV,kp]),qge=mt([Ia,w0,x0,$0,sV,Cg,Mg,Ea]),Bge=mt([Ag,v0,k0,oV,Ng,Og,Rg,jg]),Wge=mt([Tg,zg,b0,pF,u0,Sp,y0,kp,QF]),Gge=mt([Ia,i0,S0,g0,d0,s0,a0,l0,ru,_0,Cg,Mg,Ea]),ue=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===we.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new e0(i.elicitations,r)}return new t(e,r,n)}},e0=class extends ue{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(we.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ds(t){return t==="completed"||t==="failed"||t==="cancelled"}var Eye=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function I0(t){let r=vg(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=mA(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function E0(t,e){let r=ri(t,e);if(!r.success)throw r.error;return r.data}var fV=6e4,Dg=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Tg,r=>{this._oncancel(r)}),this.setNotificationHandler(zg,r=>{this._onprogress(r)}),this.setRequestHandler(Ag,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ng,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ue(we.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Og,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let d=c,f=new ue(d.error.code,d.error.message,d.error.data);u(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new ue(we.InvalidParams,`Task not found: ${o}`);if(!ds(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(ds(s.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[us]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Rg,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new ue(we.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(jg,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ue(we.InvalidParams,`Task not found: ${r.params.taskId}`);if(ds(i.status))throw new ue(we.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ue(we.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof ue?i:new ue(we.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ue.fromError(we.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{i?.(o,s),Sa(o)||tz(o)?this._onresponse(o):_p(o)?this._onrequest(o,s):ez(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=ue.fromError(we.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,o=e.params?._meta?.[us]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:we.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(u).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=JA(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:s.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(s.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(u,d)},sendRequest:async(u,d,f)=>{if(s.signal.aborted)throw new ue(we.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let h=p.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,d,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(s.signal.aborted)return;let d={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async u=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:we.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),s(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Sa(e))n(e);else{let s=new ue(e.error.code,e.error.message,e.error.data);n(s)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Sa(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),Sa(e))i(e);else{let s=ue.fromError(e.error.code,e.error.message,e.error.data);i(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof ue?s:new ue(we.InternalError,String(s))}}return}let o;try{let s=await this.request(e,Ea,n);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new ue(we.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},ds(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new ue(we.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ue(we.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof ue?s:new ue(we.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let d=b=>{u(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[us]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let $=b instanceof ue?b:new ue(we.RequestTimeout,String(b));u($)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let $=ri(r,b.result);$.success?l($.data):u($.error)}catch($){u($)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??fV,g=()=>h(ue.fromError(we.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let b=$=>{let R=this._responseHandlers.get(f);R?R($):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch($=>{this._cleanupTimeout(f),u($)})}else this._transport.send(p,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cg,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Mg,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},oz,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[us]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[us]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[us]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=I0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let s=E0(e,i);return Promise.resolve(r(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=I0(e);this._notificationHandlers.set(n,i=>{let o=E0(e,i);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&_p(i.message)){let o=i.message.id,s=this._requestResolvers.get(o);s?(s(new ue(we.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new ue(we.InvalidRequest,"Request cancelled"));return}let s=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(s),o(new ue(we.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new ue(we.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,s)=>{await n.storeTaskResult(i,o,s,r);let a=await n.getTask(i,r);if(a){let c=kp.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ds(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,s)=>{let a=await n.getTask(i,r);if(!a)throw new ue(we.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(ds(a.status))throw new ue(we.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,s,r);let c=await n.getTask(i,r);if(c){let l=kp.parse({method:"notifications/tasks/status",params:c});await this.notification(l),ds(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function fz(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function mz(t,e){let r={...t};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let s=r[i];fz(s)&&fz(o)?r[i]={...s,...o}:r[i]=o}return r}var hM=cb(UC(),1),gM=cb(mM(),1);function KK(){let t=new hM.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,gM.default)(t),t}var Yy=class{constructor(e){this._ajv=e??KK()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Qy=class{constructor(e){this._client=e}async*callToolStream(e,r=ru,n){let i=this._client,o={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},s=i.requestStream({method:"tools/call",params:e},r,o),a=i.getToolOutputValidator(e.name);for await(let c of s){if(c.type==="result"&&a){let l=c.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new ue(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{let u=a(l.structuredContent);if(!u.valid){yield{type:"error",error:new ue(we.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ue){yield{type:"error",error:u};return}yield{type:"error",error:new ue(we.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function yM(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function _M(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function e_(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let o=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(r[i]=o.default),r[i]!==void 0&&e_(o,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&e_(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&e_(r,e)}}function JK(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var t_=class extends Dg{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Yy,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Sp,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",y0,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",u0,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Qy(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mz(this._capabilities,e)}setRequestHandler(e,r){let i=vg(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let o;if(Yl(i)){let a=i;o=a._zod?.def?.value??a.value}else{let a=i;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");let s=o;if(s==="elicitation/create"){let a=async(c,l)=>{let u=ri(k0,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new ue(we.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=u.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=JK(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new ue(we.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new ue(we.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,l));if(d.task){let b=ri(Ea,h);if(!b.success){let $=b.error instanceof Error?b.error.message:String(b.error);throw new ue(we.InvalidParams,`Invalid task creation result: ${$}`)}return b.data}let m=ri($0,h);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new ue(we.InvalidParams,`Invalid elicitation result: ${b}`)}let g=m.data,y=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{e_(y,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(s==="sampling/createMessage"){let a=async(c,l)=>{let u=ri(v0,c);if(!u.success){let g=u.error instanceof Error?u.error.message:String(u.error);throw new ue(we.InvalidParams,`Invalid sampling request: ${g}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let g=ri(Ea,f);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new ue(we.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}let h=d.tools||d.toolChoice?x0:w0,m=ri(h,f);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new ue(we.InvalidParams,`Invalid sampling result: ${g}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:eu,capabilities:this._capabilities,clientInfo:this._clientInfo}},i0,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!HA.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){yM(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&_M(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ia,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},S0,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Ia,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},g0,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},d0,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},s0,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},a0,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},l0,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Ia,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Ia,r)}async callTool(e,r=ru,n){if(this.isToolTaskRequired(e.name))throw new ue(we.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),o=this.getToolOutputValidator(e.name);if(o){if(!i.structuredContent&&!i.isError)throw new ue(we.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let s=o(i.structuredContent);if(!s.valid)throw new ue(we.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof ue?s:new ue(we.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return i}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let i=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,i)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},_0,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let o=dz.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=o.data,{onChanged:c}=n,l=async()=>{if(!s){c(null,null);return}try{let d=await i();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},u=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let f=setTimeout(l,a);this._listChangedDebounceTimers.set(e,f)}else l()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function r_(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function bM(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...r_(e.headers),...r_(n.headers)}:e.headers};return t(r,i)}:t}var KS;KS=globalThis.crypto;async function YK(t){return(await KS).getRandomValues(new Uint8Array(t))}async function QK(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r="",n=await YK(t);for(let i=0;i<t;i++){let o=n[i]%e.length;r+=e[o]}return r}async function eJ(t){return await QK(t)}async function tJ(t){let e=await(await KS).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function JS(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await eJ(t),r=await tJ(e);return{code_verifier:e,code_challenge:r}}var yr=OA().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:WA.custom,message:"URL must be parseable",fatal:!0}),Wh}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),wM=Xt({resource:x().url(),authorization_servers:q(yr).optional(),jwks_uri:x().url().optional(),scopes_supported:q(x()).optional(),bearer_methods_supported:q(x()).optional(),resource_signing_alg_values_supported:q(x()).optional(),resource_name:x().optional(),resource_documentation:x().optional(),resource_policy_uri:x().url().optional(),resource_tos_uri:x().url().optional(),tls_client_certificate_bound_access_tokens:lt().optional(),authorization_details_types_supported:q(x()).optional(),dpop_signing_alg_values_supported:q(x()).optional(),dpop_bound_access_tokens_required:lt().optional()}),YS=Xt({issuer:x(),authorization_endpoint:yr,token_endpoint:yr,registration_endpoint:yr.optional(),scopes_supported:q(x()).optional(),response_types_supported:q(x()),response_modes_supported:q(x()).optional(),grant_types_supported:q(x()).optional(),token_endpoint_auth_methods_supported:q(x()).optional(),token_endpoint_auth_signing_alg_values_supported:q(x()).optional(),service_documentation:yr.optional(),revocation_endpoint:yr.optional(),revocation_endpoint_auth_methods_supported:q(x()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(x()).optional(),introspection_endpoint:x().optional(),introspection_endpoint_auth_methods_supported:q(x()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(x()).optional(),code_challenge_methods_supported:q(x()).optional(),client_id_metadata_document_supported:lt().optional()}),rJ=Xt({issuer:x(),authorization_endpoint:yr,token_endpoint:yr,userinfo_endpoint:yr.optional(),jwks_uri:yr,registration_endpoint:yr.optional(),scopes_supported:q(x()).optional(),response_types_supported:q(x()),response_modes_supported:q(x()).optional(),grant_types_supported:q(x()).optional(),acr_values_supported:q(x()).optional(),subject_types_supported:q(x()),id_token_signing_alg_values_supported:q(x()),id_token_encryption_alg_values_supported:q(x()).optional(),id_token_encryption_enc_values_supported:q(x()).optional(),userinfo_signing_alg_values_supported:q(x()).optional(),userinfo_encryption_alg_values_supported:q(x()).optional(),userinfo_encryption_enc_values_supported:q(x()).optional(),request_object_signing_alg_values_supported:q(x()).optional(),request_object_encryption_alg_values_supported:q(x()).optional(),request_object_encryption_enc_values_supported:q(x()).optional(),token_endpoint_auth_methods_supported:q(x()).optional(),token_endpoint_auth_signing_alg_values_supported:q(x()).optional(),display_values_supported:q(x()).optional(),claim_types_supported:q(x()).optional(),claims_supported:q(x()).optional(),service_documentation:x().optional(),claims_locales_supported:q(x()).optional(),ui_locales_supported:q(x()).optional(),claims_parameter_supported:lt().optional(),request_parameter_supported:lt().optional(),request_uri_parameter_supported:lt().optional(),require_request_uri_registration:lt().optional(),op_policy_uri:yr.optional(),op_tos_uri:yr.optional(),client_id_metadata_document_supported:lt().optional()}),xM=W({...rJ.shape,...YS.pick({code_challenge_methods_supported:!0}).shape}),kM=W({access_token:x(),id_token:x().optional(),token_type:x(),expires_in:$g.number().optional(),scope:x().optional(),refresh_token:x().optional()}).strip(),$M=W({error:x(),error_description:x().optional(),error_uri:x().optional()}),vM=yr.optional().or(ne("").transform(()=>{})),nJ=W({redirect_uris:q(yr),token_endpoint_auth_method:x().optional(),grant_types:q(x()).optional(),response_types:q(x()).optional(),client_name:x().optional(),client_uri:yr.optional(),logo_uri:vM,scope:x().optional(),contacts:q(x()).optional(),tos_uri:vM,policy_uri:x().optional(),jwks_uri:yr.optional(),jwks:MA().optional(),software_id:x().optional(),software_version:x().optional(),software_statement:x().optional()}).strip(),iJ=W({client_id:x(),client_secret:x().optional(),client_id_issued_at:Qe().optional(),client_secret_expires_at:Qe().optional()}).strip(),SM=nJ.merge(iJ),u0e=W({error:x(),error_description:x().optional()}).strip(),d0e=W({token:x(),token_type_hint:x().optional()}).strip();function IM(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function EM({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}var jt=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Nf=class extends jt{};Nf.errorCode="invalid_request";var Ha=class extends jt{};Ha.errorCode="invalid_client";var Xa=class extends jt{};Xa.errorCode="invalid_grant";var Ka=class extends jt{};Ka.errorCode="unauthorized_client";var Cf=class extends jt{};Cf.errorCode="unsupported_grant_type";var Of=class extends jt{};Of.errorCode="invalid_scope";var Rf=class extends jt{};Rf.errorCode="access_denied";var Io=class extends jt{};Io.errorCode="server_error";var Mf=class extends jt{};Mf.errorCode="temporarily_unavailable";var jf=class extends jt{};jf.errorCode="unsupported_response_type";var Df=class extends jt{};Df.errorCode="unsupported_token_type";var Lf=class extends jt{};Lf.errorCode="invalid_token";var Uf=class extends jt{};Uf.errorCode="method_not_allowed";var Zf=class extends jt{};Zf.errorCode="too_many_requests";var Ja=class extends jt{};Ja.errorCode="invalid_client_metadata";var Ff=class extends jt{};Ff.errorCode="insufficient_scope";var Vf=class extends jt{};Vf.errorCode="invalid_target";var PM={[Nf.errorCode]:Nf,[Ha.errorCode]:Ha,[Xa.errorCode]:Xa,[Ka.errorCode]:Ka,[Cf.errorCode]:Cf,[Of.errorCode]:Of,[Rf.errorCode]:Rf,[Io.errorCode]:Io,[Mf.errorCode]:Mf,[jf.errorCode]:jf,[Df.errorCode]:Df,[Lf.errorCode]:Lf,[Uf.errorCode]:Uf,[Zf.errorCode]:Zf,[Ja.errorCode]:Ja,[Ff.errorCode]:Ff,[Vf.errorCode]:Vf};var Eo=class extends Error{constructor(e){super(e??"Unauthorized")}};function oJ(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var QS="code",eI="S256";function sJ(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&oJ(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function aJ(t,e,r,n){let{client_id:i,client_secret:o}=e;switch(t){case"client_secret_basic":cJ(i,o,r);return;case"client_secret_post":lJ(i,o,n);return;case"none":uJ(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function cJ(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function lJ(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function uJ(t,e){e.set("client_id",t)}async function AM(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=$M.parse(JSON.parse(r)),{error:i,error_description:o,error_uri:s}=n,a=PM[i]||Io;return new a(o||"",s)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Io(i)}}async function qf(t,e){try{return await tI(t,e)}catch(r){if(r instanceof Ha||r instanceof Ka)return await t.invalidateCredentials?.("all"),await tI(t,e);if(r instanceof Xa)return await t.invalidateCredentials?.("tokens"),await tI(t,e);throw r}}async function tI(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){let s,a;try{s=await fJ(e,{resourceMetadataUrl:i},o),s.authorization_servers&&s.authorization_servers.length>0&&(a=s.authorization_servers[0])}catch{}a||(a=new URL("/",e));let c=await pJ(e,t,s),l=await _J(a,{fetchFn:o}),u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let g=l?.client_id_metadata_document_supported===!0,y=t.clientMetadataUrl;if(y&&!dJ(y))throw new Ja(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${y}`);if(g&&y)u={client_id:y},await t.saveClientInformation?.(u);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let $=await kJ(a,{metadata:l,clientMetadata:t.clientMetadata,fetchFn:o});await t.saveClientInformation($),u=$}}let d=!t.redirectUrl;if(r!==void 0||d){let g=await xJ(t,a,{metadata:l,resource:c,authorizationCode:r,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}let f=await t.tokens();if(f?.refresh_token)try{let g=await wJ(a,{metadata:l,clientInformation:u,refreshToken:f.refresh_token,resource:c,addClientAuthentication:t.addClientAuthentication,fetchFn:o});return await t.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof jt)||g instanceof Io))throw g}let p=t.state?await t.state():void 0,{authorizationUrl:h,codeVerifier:m}=await bJ(a,{metadata:l,clientInformation:u,state:p,redirectUrl:t.redirectUrl,scope:n||s?.scopes_supported?.join(" ")||t.clientMetadata.scope,resource:c});return await t.saveCodeVerifier(m),await t.redirectToAuthorization(h),"REDIRECT"}function dJ(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function pJ(t,e,r){let n=IM(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!EM({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function nI(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let i=rI(t,"resource_metadata")||void 0,o;if(i)try{o=new URL(i)}catch{}let s=rI(t,"scope")||void 0,a=rI(t,"error")||void 0;return{resourceMetadataUrl:o,scope:s,error:a}}function rI(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function fJ(t,e,r=fetch){let n=await gJ(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return wM.parse(await n.json())}async function iI(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?iI(t,void 0,r):void 0;throw n}}function mJ(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function TM(t,e,r=fetch){return await iI(t,{"MCP-Protocol-Version":e},r)}function hJ(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function gJ(t,e,r,n){let i=new URL(t),o=n?.protocolVersion??eu,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let c=mJ(e,i.pathname);s=new URL(c,n?.metadataServerUrl??i),s.search=i.search}let a=await TM(s,o,r);if(!n?.metadataUrl&&hJ(a,i.pathname)){let c=new URL(`/.well-known/${e}`,i);a=await TM(c,o,r)}return a}function yJ(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function _J(t,{fetchFn:e=fetch,protocolVersion:r=eu}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=yJ(t);for(let{url:o,type:s}of i){let a=await iI(o,n,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`)}return s==="oauth"?YS.parse(await a.json()):xM.parse(await a.json())}}}async function bJ(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(QS))throw new Error(`Incompatible auth server: does not support response type ${QS}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(eI))throw new Error(`Incompatible auth server: does not support code challenge method ${eI}`)}else a=new URL("/authorize",t);let c=await JS(),l=c.code_verifier,u=c.code_challenge;return a.searchParams.set("response_type",QS),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",eI),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:l}}function vJ(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function zM(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:i,resource:o,fetchFn:s}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",o.href),i)await i(c,r,a,e);else if(n){let u=e?.token_endpoint_auth_methods_supported??[],d=sJ(n,u);aJ(d,n,c,r)}let l=await(s??fetch)(a,{method:"POST",headers:c,body:r});if(!l.ok)throw await AM(l);return kM.parse(await l.json())}async function wJ(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await zM(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:o,resource:i,fetchFn:s});return{refresh_token:n,...c}}async function xJ(t,e,{metadata:r,resource:n,authorizationCode:i,fetchFn:o}={}){let s=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(s)),!a){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await t.codeVerifier();a=vJ(i,l,t.redirectUrl)}let c=await t.clientInformation();return zM(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:o})}async function kJ(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let o=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw await AM(o);return SM.parse(await o.json())}var n_=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function oI(t){}function NM(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=oI,onError:r=oI,onRetry:n=oI,onComment:i}=t,o="",s=!0,a,c="",l="";function u(m){let g=s?m.replace(/^\xEF\xBB\xBF/,""):m,[y,b]=$J(`${o}${g}`);for(let $ of y)d($);o=b,s=!1}function d(m){if(m===""){p();return}if(m.startsWith(":")){i&&i(m.slice(m.startsWith(": ")?2:1));return}let g=m.indexOf(":");if(g!==-1){let y=m.slice(0,g),b=m[g+1]===" "?2:1,$=m.slice(g+b);f(y,$,m);return}f(m,"",m)}function f(m,g,y){switch(m){case"event":l=g;break;case"data":c=`${c}${g}
110
+ `;break;case"id":a=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new n_(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:y}));break;default:r(new n_(`Unknown field "${m.length>20?`${m.slice(0,20)}\u2026`:m}"`,{type:"unknown-field",field:m,value:g,line:y}));break}}function p(){c.length>0&&e({id:a,event:l||void 0,data:c.endsWith(`
111
+ `)?c.slice(0,-1):c}),a=void 0,c="",l=""}function h(m={}){o&&m.consume&&d(o),s=!0,a=void 0,c="",l="",o=""}return{feed:u,reset:h}}function $J(t){let e=[],r="",n=0;for(;n<t.length;){let i=t.indexOf("\r",n),o=t.indexOf(`
112
+ `,n),s=-1;if(i!==-1&&o!==-1?s=Math.min(i,o):i!==-1?s=i:o!==-1&&(s=o),s===-1){r=t.slice(n);break}else{let a=t.slice(n,s);e.push(a),n=s+1,t[n-1]==="\r"&&t[n]===`
113
+ `&&n++}}return[e,r]}var i_=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let i;super({start(o){i=NM({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:r,onComment:n})},transform(o){i.feed(o)}})}};var SJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Is=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},o_=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=bM(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??SJ}async _authThenStart(){if(!this._authProvider)throw new Eo("No auth provider");let e;try{e=await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new Eo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=r_(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let i=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Is(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,i=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),i)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let i=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},i)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:i,replayMessageId:o}=r,s,a=!1,c=!1;(async()=>{try{let u=e.pipeThrough(new TextDecoderStream).pipeThrough(new i_({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await u.read();if(h)break;if(p.id&&(s=p.id,a=!0,i?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Pg.parse(JSON.parse(p.data));Sa(m)&&(c=!0,o!==void 0&&(m.id=o)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:i,replayMessageId:o},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Eo("No auth provider");if(await qf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:i}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:_p(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Is(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:p,scope:h}=nI(a);if(this._resourceMetadataUrl=p,this._scope=h,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Eo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:p,scope:h,error:m}=nI(a);if(m==="insufficient_scope"){let g=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Is(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),p&&(this._resourceMetadataUrl=p),this._lastUpscopingHeader=g??void 0,await qf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Eo;return this.send(e)}}throw new Is(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),iz(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let u=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type");if(u)if(d?.includes("text/event-stream"))this._handleSseStream(a.body,{onresumptiontoken:i},!1);else if(d?.includes("application/json")){let f=await a.json(),p=Array.isArray(f)?f.map(h=>Pg.parse(h)):[Pg.parse(f)];for(let h of p)this.onmessage?.(h)}else throw await a.body?.cancel(),new Is(-1,`Unexpected content type: ${d}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Is(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var Es={name:"@intelliweave/embedded",version:"2.0.72-beta.10",description:"Integrate IntelliWeave into your app or website.",main:"./dist/webpack/index.js",types:"./dist/webpack/index.d.ts",type:"module",exports:{".":"./dist/webpack/index.js","./component":"./dist/component/component.js","./node":"./dist/node/node.js","./react":"./dist/react/react.js","./webpack":"./dist/webpack/index.js"},scripts:{build:"npm run build:lib && npm run build:docs","build:lib":"tsx build.ts","build:dev":"cross-env DEVELOPMENT=1 npm run build","build:docs":"typedoc src/index.mts --out dist/docs/",deploy:'npm run build && gsutil cp ./dist/web-weaver.min.js gs://metapress-cdn/web-weaver.min.js && gcloud compute url-maps invalidate-cdn-cache mp-cdn-loadbalancer --project="mp-backend-api" --path "/web-weaver.min.js" --async',"start:server":"cd server && npm run start","deploy:server":"cd server && npm run deploy","llm:build":"cd llm-server && docker build -t web-weaver-llm .","llm:start":"npm run llm:build && docker run -it --rm -p 8000:80 --gpus=all web-weaver-llm","llm:deploy.docker":"npm run llm:build && gcloud auth configure-docker us-central1-docker.pkg.dev && docker tag web-weaver-llm us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm && docker push us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm","llm:deploy":'npm run llm:deploy.docker && gcloud run deploy web-weaver-llm --project=ydangle-web-companion --image=us-central1-docker.pkg.dev/ydangle-web-companion/docker-artifacts/web-weaver-llm --allow-unauthenticated --region=us-central1 --description="Web Weaver LLM" --concurrency=2 --min-instances=0 --timeout=5m --memory=16Gi --cpu=8',prepack:"npm run build",test:"npm run build && vitest run","test:local":"IW_API_URL=http://localhost:3000/api npm run test"},keywords:["web","weaver","ai","assistant","chat"],author:"jjv360",license:"UNLICENSED",devDependencies:{"@types/audioworklet":"^0.0.95","@types/lodash":"^4.17.23","@types/react":"^18.3.12",bestzip:"^2.2.1","cross-env":"^10.1.0","find-cache-dir":"^6.0.0",lodash:"^4.17.23","onnxruntime-web":"^1.20.0",react:"^18.3.1","replace-in-file":"^8.4.0",tsup:"^8.5.1",tsx:"^4.21.0",typedoc:"^0.28.17",vitest:"^4.0.18"},peerDependencies:{"onnxruntime-web":"^1.20.0",react:"^18 || ^19"},dependencies:{"@anthropic-ai/sdk":"^0.74.0","@modelcontextprotocol/sdk":"^1.26.0","@types/json-schema":"^7.0.15",minisearch:"^7.2.0",openai:"^6.22.0","rehype-document":"^7.0.3","rehype-external-links":"^3.0.0","rehype-format":"^5.0.1","rehype-stringify":"^10.0.1","remark-parse":"^11.0.0","remark-rehype":"^11.1.2",unified:"^11.0.5","utility-types":"^3.11.0",uuid:"^13.0.0"}};var er=new Ce("MCPKnowledgeClient"),EJ="https://intelliweave-mcp-proxy-828827766277.us-central1.run.app",s_=class{constructor(e){this.tools=[];this.iwActions=[];this.stats={toolsCalled:0};this.lastSearchQuery="";this.lastSearchResults=[];this.config=e}async connect(){return this.client?this.client:this.connectionPromise?await this.connectionPromise:(this.connectionPromise=this.connectInternal(),this.connectionPromise.finally(()=>{this.connectionPromise=void 0}),await this.connectionPromise)}async connectInternal(){er.debug("Connecting to MCP client");let e=this.config.connect?await this.config.connect():await Promise.resolve().then(async()=>{let r=new URL(this.config.baseURL),n={};this.config.headers&&(n={...n,...this.config.headers}),this.config.proxy?.enabled&&(n["Mcp-Target-Url"]=r.toString(),n["IntelliWeave-Api-Key"]=this.config.proxy.apiKey||"",r=new URL(this.config.proxy.url||EJ));let i=new t_({name:Es.name,version:Es.version}),o=new o_(r,{requestInit:{headers:n}});return await i.connect(o),er.debug("Connected with HTTP streaming mode"),i});return await this.disconnect(),this.client=e,e.onerror=r=>{er.error(`MCP client error: ${r.message}`)},e.onclose=()=>{er.debug("MCP client connection closed"),this.client=void 0},e.setNotificationHandler(b0,r=>{r.params.level=="critical"?er.error(`[Server] ${r.params.data}`):r.params.level=="emergency"?er.error(`[Server] ${r.params.data}`):r.params.level=="error"?er.error(`[Server] ${r.params.data}`):r.params.level=="warning"?er.warn(`[Server] ${r.params.data}`):r.params.level=="info"?er.info(`[Server] ${r.params.data}`):r.params.level=="debug"?er.debug(`[Server] ${r.params.data}`):er.log(`[Server] ${r.params.data}`)}),e.setNotificationHandler(Sp,r=>{er.debug("Tool list changed",r),this.fetchTools()}),er.debug("Fetching tools from MCP server..."),await this.fetchTools(),e}async disconnect(){await this.client?.close(),this.client=void 0,this.tools=[],this.iwActions=[]}async fetchTools(){let e=[],r;for(;;){let i=await this.client.listTools({cursor:r});r=i.nextCursor;for(let o of i.tools||[])e.push(o);if(!i?.tools?.length||!r)break}let n=[];for(let i of e){let o=!!(this.config.searchToolName&&i.name==this.config.searchToolName&&!this.config.searchToolVisible);n.push({id:i.name,name:i.name,content:i.description||"",type:"action",isContext:!0,parameters:i.inputSchema,action:s=>this.performToolCall(i.name,s),disabled:o})}er.debug(`Fetched ${e.length} tools from MCP server.`),this.tools=e,this.iwActions=n}async search(e){if(e==this.lastSearchQuery)return this.lastSearchResults;await this.connect();let r=this.iwActions.slice(),n=await this.performSearchCall(e);return r=r.concat(n),this.lastSearchQuery=e,this.lastSearchResults=r,er.debug(`Search completed, found ${r.length} items.`),r}async performSearchCall(e){let r=[];if(!this.config.searchToolName)return r;let n=this.tools.find(o=>o.name==this.config.searchToolName);if(!n)return er.warn(`Search function ${this.config.searchToolName} not found on the MCP server.`),r;let i;if(n.inputSchema.required?.length==1){let o=n.inputSchema.required[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else if(n.inputSchema.properties&&Object.keys(n.inputSchema.properties).length==1){let o=Object.keys(n.inputSchema.properties)[0];i=await this.performToolCall(this.config.searchToolName,{[o]:e})}else i=await this.performToolCall(this.config.searchToolName,{});if(Array.isArray(i))for(let o=0;o<i.length;o++){let s=i[o];r.push({id:this.config.id+":"+this.config.searchToolName+":"+o,name:`Search result ${o+1} in ${this.config.searchToolName}`,type:"info",content:typeof s=="string"?s:JSON.stringify(s)})}else r.push({id:this.config.id+":"+this.config.searchToolName+":result",name:`Search result in ${this.config.searchToolName}`,type:"info",content:typeof i=="string"?i:JSON.stringify(i)});return r}async performToolCall(e,r){await this.connect(),er.debug(`Performing tool call for ${e} with params:`,r),this.stats.toolsCalled+=1;let n=await this.client.callTool({name:e,arguments:r});if(n.isError){let i=n.content?.[0]?.text||"Unknown error";throw er.error(`Error calling tool ${e}: ${i}`),new Error(`Error calling tool ${e}: ${i}`)}if(Array.isArray(n.content)&&n.content.length==1&&n.content[0].type=="text")try{return JSON.parse(n.content[0].text)}catch{}return n.content||[]}};var PJ=new Ce("Statistics"),Bf=[];async function Dr(t,e){let r={...e,event_id:sr(),event_date:new Date().toISOString(),sdk_version:Es.version,conversation_id:t?.conversationID||"",api_key:t?.apiKey||"",user_id:t?.userID||""};if(Bf.push(r),!t||(await new Promise(i=>setTimeout(i,5e3)),Bf.length===0))return;let n=Bf.slice();Bf.length=0;try{let i=await fetch(t.hubAPI+"/analytics/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:n})});if(!i.ok)throw new Error(`Analytics submission failed: ${i.status} ${i.statusText}`)}catch(i){PJ.warn("Failed to submit analytics event:",i),Bf.push(...n);return}}var Ya=new Ce("KnowledgeBase"),sI=1,a_=class t{constructor(e){this._sources=[];this._windowSources=[];this.lastResults=[];this.manualEntries=[];this.allowWindowSources=!0;this.allowGlobalConfigSources=!0;this.ai=e,this.ensureInternalKnowledge()}ensureInternalKnowledge(){this._sources=this._sources.filter(e=>e.id!=="core.internal"),this._sources.push({id:"core.internal",query:async()=>AP(this.ai)})}reset(){this._windowSources=[],this.manualEntries=[],this.lastResults=[],this._sources=[],this.ensureInternalKnowledge()}registerSource(e,r){let n=e;return typeof e=="function"&&(r=e,n=`source.${sI++}`),this._sources.push({id:n,query:r}),n}removeSource(e){this._sources=this.sources.filter(r=>r.id!==e&&r.query!==e)}addEntry(e){this.manualEntries.push(e)}removeEntry(e){this.manualEntries=this.manualEntries.filter(r=>r.id!==e)}get sources(){let e=this._sources;return this.allowGlobalConfigSources&&ht().knowledgeBaseSources&&(e=e.concat(ht().knowledgeBaseSources)),this.allowWindowSources&&typeof document<"u"&&(e=e.concat(this._windowSources)),e=e.filter(r=>!r.disabled),e}async search(e){Ya.debug(`Searching knowledge base for: ${e}`);let r=Date.now(),n=new Event("webweaver_kb_search",{bubbles:!0,cancelable:!0});n.query=e,n.entries=[],n.sources=[],this.allowWindowSources&&typeof document<"u"?(document.dispatchEvent(n),this._windowSources=n.sources):this._windowSources=[];let o=(await Promise.all(this.sources.map(async l=>{try{let u=Date.now(),d=await l.query(e);return Ya.debug(`Source '${l.id}' took ${Date.now()-u}ms`),d||[]}catch(u){return Ya.warn(`Knowledge source '${l.id}' failed:`,u),[]}}))).flat();o=o.concat(n.entries),o=o.concat(this.manualEntries),this.allowGlobalConfigSources&&ht().knowledgeBase&&(o=o.concat(ht().knowledgeBase)),o=o.filter(l=>l&&!l.disabled);for(let l=0;l<o.length;l++){let u=o[l];u.id=u.id||`temp.${l}`,u._functionID=u.id.replaceAll(/[^a-zA-Z0-9_]/g,"_")}let s=new Gd({fields:["id","type","name","content","tags"],storeFields:[],searchOptions:{boost:{name:3,tags:2},fuzzy:.2}});s.addAll(o);let c=s.search(e).map(l=>o.find(u=>u.id==l.id));for(let l of o)l.isContext&&(c.find(u=>u.id===l.id)||c.push(l));return this.lastResults=c,Dr(this.ai,{event_type:"kb_search",value:c.length,value_str:"",event_properties:{search_time_ms:Date.now()-r,sources_searched:this.sources.length}}),Ya.debug("Found results:",c),c}getCachedEntry(e){return this.lastResults.find(r=>r.id==e||r._functionID==e)}registerSourceFromURL(e,r){r||(r=`external.${sI++}`),Ya.debug(`Registering remote knowledge base source: ${e}`);let n=[],i=[],o=!0,s=async(c,l)=>{Ya.debug(`Calling remote knowledge base action: ${c.id}`);let u={type:"action",userID:this.ai.userID,actionID:c.id,parameters:l},d=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok)throw new Error(`HTTP Error ${d.status} ${d.statusText}`);let f=await d.json();return a(f.updateItems||[]),f.response},a=c=>{for(let l of c){if(!l.id){Ya.warn("KB item skipped since it has no ID.",l);continue}let u=n.find(d=>d.id==l.id);if(u){u.name=l.name||u.name||"",u.content=l.content||u.content||"",u.disabled=l.disabled??u.disabled,u.isContext=l.isContext??u.isContext,u.parameters=l.parameters||u.parameters||[],u.tags=l.tags||u.tags,u.type=l.type||u.type;continue}n.push({...l,action:d=>s(l,d)})}};this.registerSource(r,async c=>{if(o&&i.includes(c))return n;let l={type:"search",userID:this.ai?.userID||"",query:c},u=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok)throw new Error(`HTTP Error ${u.status} ${u.statusText}`);let d=await u.json();return o=!d.noCache,i.includes(c)||i.push(c),a(d.items),n})}clone(){let e=new t(this.ai);return e._sources=this._sources,e._windowSources=this._windowSources,e.manualEntries=this.manualEntries,e.ensureInternalKnowledge(),e}registerMCPSource(e){e.id||(e.id=`external.${sI++}`);let r=new s_(e);return this.registerSource(e.id,n=>r.search(n)),r}};var c_=class{constructor(e){this.ai=e}async boolean(e){let r=await this.instruct({...e,instruction:`${e.instruction}
114
+
115
+ Return only the text "true" or "false" to indicate the answer to the question. Do not include any additional text or explanations.`});if(r.toLowerCase().includes("true"))return!0;if(r.toLowerCase().includes("false"))return!1;throw new Error("The AI did not give a boolean answer: "+r)}async choose(e){let r=await this.instruct({...e,instruction:`${e.instruction}
17
116
 
18
117
  Reply only with one of the following options:
19
- ${i.options.map(t=>`- "${t}"`).join(`
118
+ ${e.options.map(n=>`- "${n}"`).join(`
20
119
  `)}
21
120
 
22
- Do not include any additional text or explanations.`});return i.options.includes(e)?e:i.options.find(t=>e.toLowerCase().includes(t.toLowerCase()))}async extract(i){let e=`
23
- You will receive some data. Extraction instructions: ${i.instruction}
121
+ Do not include any additional text or explanations.`});return e.options.includes(r)?r:e.options.find(n=>r.toLowerCase().includes(n.toLowerCase()))}async extract(e){let r=`
122
+ You will receive some data. Extraction instructions: ${e.instruction}
24
123
 
25
- ${i.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
124
+ ${e.allowMultiple?"Return a JSONL string only, one JSON object on each line.":"Return a valid JSON object only."}
26
125
 
27
126
  Objects should have the following keys:
28
- ${i.extractions.map(s=>`- ${s.name} (${s.type}): ${s.description||"No description provided."}`).join(`
127
+ ${e.extractions.map(i=>`- ${i.name} (${i.type}): ${i.description||"No description provided."}`).join(`
29
128
  `)}
30
- `,t=await this.instruct({...i,instruction:e});if(t=t.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),i.allowMultiple){let s=t.split(`
31
- `).map(o=>o.trim()).filter(o=>!!o.trim()),n=[];for(let o of s)try{n.push(JSON.parse(o))}catch(a){console.error("Failed to parse line as JSON:",o,a.message)}return n}else return[JSON.parse(t.trim())]}async generateMarkdown(i){return this.instruct({...i,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(i){let e=this.ai.clone();return e.resetConversation(),e.getContextPrefix=async()=>i.instruction,i.callback&&e.addEventListener("output",t=>{i.callback(t.detail.message)}),i.allowKB||(e.knowledgeBase._sources=[]),await e.sendMessage(typeof i.data=="string"?i.data:JSON.stringify(i.data))||""}};var v=new h("Main"),Ee=new Set,I=class I extends EventTarget{constructor(){super(...arguments);this.conversationID=we();this.knowledgeBase=new q(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new ee(this);this.userID=Ie();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this._lastTrackedTokens=0}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:I.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(e){if(this.apiKey=e,!e)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{v.debug("Loading configuration...");let t=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})});if(!t.ok)throw new Error(`Failed to load configuration: ${t.status} ${t.statusText}`);try{this.config=await t.json(),v.debug("Config loaded successfully:",this.config),this.config&&v.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(s){v.error("Failed to parse JSON response:",s);try{let n=await t.clone().text();v.error("Raw response that failed parsing:",n)}catch{v.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${s}`)}})(),(async()=>{try{let t=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!t.ok)throw new Error(`Failed to load VAD model: ${t.status} ${t.statusText}`);this.vadModel=await t.blob()}catch(t){v.warn(`Failed to load VAD model, some features will be unavailable. ${t.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let t of this.config.knowledge||[])t.url&&t.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:t.id,searchToolName:t.mcpSearchToolName,baseURL:t.url}):t.url&&this.knowledgeBase.registerSourceFromURL(t.url);for(let t of this.config.knowledge||[])t.entries?.length&&this.knowledgeBase.registerSource(t.id,()=>t.entries||[]);if(this.config.mcpServers)for(let t of this.config.mcpServers)this.knowledgeBase.registerMCPSource(t);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this.config}catch(t){throw v.warn("Failed to load:",t),this.error=t,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:t}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:t}})),t}}setModel(e){let t=this.models.find(n=>n.id==e);if(!t)throw new Error(`Model with ID "${e}" not found.`);let s={...t.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(n,o)=>{let a=this.knowledgeBase.getCachedEntry(n);this.onAIToolStart?.(a?.id||n,o)}};t.config.providerID==="anthropic"?this.currentModel=new $(s):this.currentModel=new H(s),this.currentModel.id=t.id,this.currentModel.metadata=t}async getContextPrefix(){let e=m().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof e=="function"&&(e=await e()),e}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let e=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let t=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,content:t}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,content:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,content:`# Knowledge Database
32
- You have access to a database of knowledge base items. These include "info" type items which provide information and "tour" type items which contain instructions you should follow (only do one item at a time).${e.length==0?`
33
-
34
- (no items found)`:""}`});for(let n of e)if(n.type=="info"||n.type=="tour"||n.type=="input-event"){let o=ye(typeof n.content=="function"?n.content():n.content);this.currentModel.contextGroup.add({id:n.id,customData:n,cannotRemove:n.isContext,sortOrder:101,disabled:n.disabled,content:`## ${n.type}: ${n.name}
35
- ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeof n.content=="function"?n.content():n.content),params:We(n.parameters||[{name:"value",type:"string",description:"Input"}]),removeFromMessageHistory:!!n.removeFromMessageHistory,callback:a=>this.toolRunKBAction(n,a),kb:n};this.currentModel.registerTool(o)}else continue;let s=this.currentModel.contextGroup.getAllAsString();this._lastSystemMsg!=s&&(this._lastSystemMsg=s,this.submitAnalyticsEvent({type:"system-msg",txt:s}))}processIncomingMessage(e,t){if(!t){let s=this.currentModel?.stats?.tokensUsed||0,n=s-(this._lastTrackedTokens||0);this._lastTrackedTokens=s,f(this,{event_type:"message_receive",value:n,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:s}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isChunk:t,message:e}})),this.onAIMessage?.(e,!!t)}async sendMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)return v.warn("Cannot send message while another message is being processed."),null;this.isProcessing=!0;try{this._messageStartTime=Date.now(),Ee.has(this.conversationID)||(Ee.add(this.conversationID),f(this,{event_type:"session_start"})),this._lastTrackedTokens=this.currentModel?.stats?.tokensUsed||0,f(this,{event_type:"message_send",value_str:"",event_properties:{message_length:e.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:e}})),this.submitAnalyticsEvent({type:"message",role:"user",message:e,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()});let t=await this.currentModel.sendMessage(e);return t&&typeof t=="string"&&t.trim().length>0&&this.submitAnalyticsEvent({type:"message",role:"assistant",message:t,conversationID:this.conversationID,apiKey:this.apiKey,personaID:this.config?.id,date:Date.now()}),t}finally{this.isProcessing=!1}}async toolRunKBAction(e,t){let s=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:e,input:t,ai:this}}));let n=await e.action(t,this),o=Date.now()-s;return f(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,result:n}})),n}catch(n){let o=Date.now()-s;throw f(this,{event_type:"tool_call",value_str:e.id||"",event_properties:{tool_args:t,execution_time_ms:o,success:!1,error_message:n.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:e,input:t,ai:this,error:n}})),n}}submitAnalyticsEvent(e){m().analytics===!1||this.config?.analytics===!1||fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(t=>{v.debug("Failed to submit analytics event:",t)})}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=we(),this._lastSystemMsg="")}insertAssistantMessage(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(e)}exportState(){return{type:"intelliweave/state/v1",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll().map(e=>e.customData)}}importState(e){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(e?.type!="intelliweave/state/v1")throw new Error(`Invalid state type: ${e.type}`);this.conversationID=e.conversationID;for(let t of e.messages)this.currentModel.messageGroup.add({id:we(),content:JSON.stringify(t),customData:t})}clone(){let e=new I;return e.apiKey=this.apiKey,e.config=this.config,e.models=this.models,this.config?.id&&e.setModel(this.config.id),e.audio=this.audio,e.vadModel=this.vadModel,e.userID=this.userID,e.knowledgeBase=this.knowledgeBase.clone(),e}};I.version=G.version,I.builtInActionsVersion="1.0.0",v.debug("\u{1F6A8}\u{1F6A8}\u{1F6A8} NEW SDK BUILD LOADED - Built-in Actions Version:",I.builtInActionsVersion);var T=I;var y=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(e={},t=""){this.register();let s=document.createElement(this.tagName);for(let n in e)s.setAttribute(n,e[n]);return s.onBeforeCreate(),s.innerHTML=t,s}static add(e={},t=""){this.register();let s=n=>n.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(e).map(n=>`${n}="${s(e[n]+"")}"`).join(" ")}>${t}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(e,t,s){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(e,t)=>this.getAttribute(t.toString())||"",set:(e,t,s)=>(this.getAttribute(t.toString())===s||(s?this.setAttribute(t.toString(),s):this.removeAttribute(t.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(e,t)=>this._state[t],set:(e,t,s)=>(this._state[t]=s,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(e){return!!this.root?.getElementById(e)}child(e){let t=this.root?.getElementById(e);if(!t)throw new Error(`Child with ID ${e} not found`);return t}};y.observedAttributes=[],y.tagName="",y._isRegistered=!1;var Re='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var Ve='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Le='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var _=class extends y{constructor(){super(...arguments);this.html=()=>`
129
+ `,n=await this.instruct({...e,instruction:r});if(n=n.replace(/```jsonl/g,"").replace(/```json/g,"").replace(/```/g,""),e.allowMultiple){let i=n.split(`
130
+ `).map(s=>s.trim()).filter(s=>!!s.trim()),o=[];for(let s of i)try{o.push(JSON.parse(s))}catch(a){console.error("Failed to parse line as JSON:",s,a.message)}return o}else return[JSON.parse(n.trim())]}async generateMarkdown(e){return this.instruct({...e,instruction:"Generate a Markdown document based on the input text. Always include a header on every response. Give long detailed answers with many paragraphs, and explain concepts step by step."})}async instruct(e){let r=this.ai.clone();return r.resetConversation(),r.getContextPrefix=async()=>e.instruction,e.callback&&r.addEventListener("output",n=>{e.callback(n.detail.message)}),e.allowKB||(r.knowledgeBase._sources=[]),await r.sendMessage(typeof e.data=="string"?e.data:JSON.stringify(e.data)).then(n=>n.text())}};var zu=class{constructor(e){this.messages=e}text(){return this.messages?.flatMap(e=>e.sections)?.filter(e=>e?.type=="text")?.map(e=>e?.text||"")?.filter(e=>!!e)?.join(`
131
+
132
+ `)?.trim()||""}tokenUsage(){return{cachedInputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.cachedInputTokens||0),0)||0,inputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.inputTokens||0),0)||0,outputTokens:this.messages?.reduce((e,r)=>e+(r.usage?.outputTokens||0),0)||0,totalTokens:this.messages?.reduce((e,r)=>e+(r.usage?.totalTokens||0),0)||0}}sections(){return this.messages?.flatMap(e=>e.sections||[])||[]}toolCalls(){return this.messages?.flatMap(e=>e.sections?.filter(r=>r.type=="tool_call")||[])||[]}toolResult(e){return this.messages?.map(r=>r.sections?.find(n=>n.type=="tool_result"&&n.toolCallInstanceID==e)).filter(r=>!!r)[0]||null}};var l_=class{constructor(e){this.subagents=[];this.cachedSubagents={};this.ai=e}register(e){if(this.subagents.find(r=>r.id==e.id))throw new Error(`Sub-agent with ID ${e.id} already exists`);this.subagents.push(e),this.ai.knowledgeBase.registerSource("subagent:"+e.id,r=>[{type:"action",id:"ask:"+e.id,name:`Ask ${e.name||"subagent"}`,content:e.usageInstructions||`Use this tool to ask ${e.name||"subagent"} a question.`,isContext:!0,parameters:[{type:"string",name:"query",description:"The question to ask the subagent"}],action:async(n,i)=>await this.runQuery(e,n.query)}])}remove(e){this.subagents=this.subagents.filter(r=>r.id!=e),this.ai.knowledgeBase.removeSource("subagent:"+e)}async runQuery(e,r){let n=e.apiKey||this.ai.apiKey,i=this.cachedSubagents[n];return i||(i=new Nu,await i.load(n,e.config),this.cachedSubagents[n]=i),i=i.clone(),i.knowledgeBase.allowGlobalConfigSources=!1,i.knowledgeBase.allowWindowSources=!1,e.clearExistingKnowledge&&i.knowledgeBase.reset(),e.knowledge&&i.knowledgeBase.registerSource(e.knowledge),e.onAgentLoaded&&await e.onAgentLoaded(i),(await i.sendMessage(r)).text()}};var Ln=new Ce("Main"),CM=new Set,Qa=class Qa extends EventTarget{constructor(){super(...arguments);this.conversationID=sr();this.knowledgeBase=new a_(this);this.subAgents=new l_(this);this._lastKBsearch="";this.models=[];this.audio=null;this.apiKey="";this.logic=new c_(this);this.userID=I1();this.hubAPI="https://intelliweave.ai/api";this._lastSystemMsg="";this.isProcessing=!1;this.activeAnalyticsPromises=[]}get loaded(){return!!(this.config&&this.currentModel)}get flags(){return this.config?.flags||{}}getBuiltInActionsInfo(){return{version:Qa.builtInActionsVersion,availableActions:["ui.openURL - Open URLs in new tabs","ui.changeRoute - Change page routes","ui.sendEmail - Send emails via mailto links","search - Search knowledge base"],enabledFlags:this.flags}}async load(r,n){if(this.apiKey=r,!r)throw new Error("API key is required to load the AI.");try{await Promise.all([(async()=>{Ln.debug("Loading configuration...");let i=await fetch(this.hubAPI+"/config/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r})});if(!i.ok)throw new Error(`Failed to load configuration: ${i.status} ${i.statusText}`);try{this.config=await i.json(),Ln.debug("Config loaded successfully:",this.config),n&&(this.config={...this.config,...n}),this.config&&Ln.debug("UI Properties - logo:",this.config.logo,"background:",this.config.background,"textColor:",this.config.textColor)}catch(o){Ln.error("Failed to parse JSON response:",o);try{let s=await i.clone().text();Ln.error("Raw response that failed parsing:",s)}catch{Ln.error("Could not get raw response text either")}throw new Error(`Failed to parse configuration: ${o}`)}})(),(async()=>{try{let i=await fetch("https://cdn.intelliweave.ai/models/silero_vad_3.onnx");if(!i.ok)throw new Error(`Failed to load VAD model: ${i.status} ${i.statusText}`);this.vadModel=await i.blob()}catch(i){Ln.warn(`Failed to load VAD model, some features will be unavailable. ${i.message}`)}})()]),this.models=[{id:this.config.id,config:this.config.model}],this.setModel(this.config.id);for(let i of this.config.knowledge||[])i.url&&i.backendType=="mcp"?this.knowledgeBase.registerMCPSource({id:i.id,searchToolName:i.mcpSearchToolName,baseURL:i.url}):i.url&&this.knowledgeBase.registerSourceFromURL(i.url);for(let i of this.config.knowledge||[])i.entries?.length&&this.knowledgeBase.registerSource(i.id,()=>i.entries||[]);if(this.config.mcpServers)for(let i of this.config.mcpServers)this.knowledgeBase.registerMCPSource(i);for(let i of this.config.subagents||[])this.subAgents.register(i);return this.resetConversation(),this.dispatchEvent(new CustomEvent("load",{detail:{ai:this}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_loaded",{detail:{ai:this}})),this}catch(i){throw Ln.warn("Failed to load:",i),this.error=i,this.dispatchEvent(new CustomEvent("error",{detail:{ai:this,error:i}})),typeof window<"u"&&window.dispatchEvent(new CustomEvent("webweaver_error",{detail:{ai:this,error:i}})),i}}setModel(r){let n=this.models.find(o=>o.id==r);if(!n)throw new Error(`Model with ID "${r}" not found.`);let i={...n.config,stream:!0,systemMessage:"",onBeforeMessageProcessing:this.onBeforeMessageProcessing.bind(this),onAIMessage:this.processIncomingMessage.bind(this),onAIToolStart:(o,s)=>{let a=this.knowledgeBase.getCachedEntry(o);this.onAIToolStart?.(a?.id||o,s)}};this.config?.onCreateProvider?this.currentModel=this.config.onCreateProvider(i):n.config.providerID==="anthropic"?this.currentModel=new Dh(i):this.currentModel=new ch(i),this.currentModel.id=n.id,this.currentModel.metadata=n}async getContextPrefix(){let r=ht().pageSummary||`You are ${this.config?.name||"IntelliWeave"}. ${this.config?.instructions||"Speak in short sentences."}`;return typeof r=="function"&&(r=await r()),r}async onBeforeMessageProcessing(){this._lastKBsearch||(this._lastKBsearch="__intelliweaveblanksearchforcontextitems__");let r=this._nextRequestUseKBitems||await this.knowledgeBase.search(this._lastKBsearch);this._nextRequestUseKBitems=void 0;let n=await this.getContextPrefix();this.currentModel.contextGroup.add({id:"_iw_main",sortOrder:1,cannotRemove:!0,data:n}),this.currentModel.contextGroup.add({id:"_iw_kb_only_rule",sortOrder:2,cannotRemove:!0,disabled:!this.flags.onlyUseKnowledgeBase,data:"Important rule: Only use knowledge from your knowledge base to answer questions, do not speak about anything that is not included in your knowledge base."}),this.currentModel.contextGroup.add({id:"_iw_kb_rag",sortOrder:99,cannotRemove:!0,data:sh(`
133
+ # RAG search
134
+ Use the \`search\` tool proactively as much as possible to find missing information or tools.
135
+ Use the \`search\` tool when you are unsure about specific details or actions to take.
136
+ Use the \`search\` tool if you are unable to complete the user's request.
137
+ If you're about to say "I don't have access..." or "I can't..." use the \`search\` tool first.
138
+ `)}),this.currentModel.contextGroup.add({id:"_iw_kb_description",sortOrder:100,cannotRemove:!0,data:`# Knowledge Database${r.length==0?`
139
+
140
+ (no items found)`:""}`});for(let i of r)if(i.type=="info"||i.type=="tour"||i.type=="input-event"){let o=sh(i.content),s=!0;if(i.attachments?.length)for(let a of i.attachments)a.url&&(s&&(o+=`
141
+
142
+ \`\`\`yaml
143
+ attachments:
144
+ `,s=!1),o+=`- name: "${a.name||""}"
145
+ mimetype: "${a.mimeType||""}"
146
+ url: "${a.url}"
147
+ `);s||(o+="```\n"),this.currentModel.contextGroup.add({id:i.id,data:`## ${i.type}: ${i.name}
148
+ ${o}`,cannotRemove:i.isContext,sortOrder:101,disabled:typeof i.disabled=="function"?i.disabled(this):i.disabled})}else if(i.type=="action"){let o={name:i._functionID,description:sh(i.content),params:E1(i.parameters||[{name:"value",type:"string",description:"Input"}]),callback:s=>this.toolRunKBAction(i,s),canRemove:!i.isContext,kbItem:i};this.currentModel.registerTool(o)}else continue}processIncomingMessage(r,n){if(!n){let i=this.currentModel?.stats?.tokensUsed||0,o=r.reduce((s,a)=>s+(a.usage?.totalTokens||0),0);Dr(this,{event_type:"message_receive",value:o,value_str:"",event_properties:{response_time_ms:Date.now()-(this._messageStartTime||Date.now()),is_streaming:!1,is_chunk:!1,total_tokens:i}})}this.dispatchEvent(new CustomEvent("output",{detail:{ai:this,isPartial:n,messages:r}})),this.onAIMessage?.(r,!!n)}async sendMessage(r,n){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(this.isProcessing)throw new Error("Cannot send message while another message is being processed.");this.isProcessing=!0;try{this._messageStartTime=Date.now(),CM.has(this.conversationID)||(CM.add(this.conversationID),Dr(this,{event_type:"session_start"})),Dr(this,{event_type:"message_send",value_str:"",event_properties:{message_length:r.length,is_voice_input:!!this.audio?.speechRecognition?.isRunning}}),this.dispatchEvent(new CustomEvent("input",{detail:{ai:this,message:r}})),this.submitAnalyticsEvent({type:"message",role:"user",message:r});let i=Date.now(),o=await this.currentModel.sendMessage(r),s=new zu(o);(this._voiceTracker||Ln.debug.bind(Ln))(`LLM response took ${Date.now()-i}ms`);let c=this.currentModel.contextGroup.getAllAsString();c+=`
149
+
150
+ === TOOLS ===
151
+
152
+ `+this.currentModel.toolGroup.getAll().map(l=>"- "+l.data?.name).join(`
153
+ `),this._lastSystemMsg!=c&&(this._lastSystemMsg=c,this.submitAnalyticsEvent({type:"system-msg",txt:c}));for(let l of o)for(let u of l.sections||[])if(u.type=="text")this.submitAnalyticsEvent({type:"message",role:"assistant",message:u.text||""});else if(u.type=="thinking")this.submitAnalyticsEvent({type:"thinking",role:"assistant",message:u.text||""});else if(u.type=="tool_call"){let d=s.toolResult(u.toolCallInstanceID);this.submitAnalyticsEvent({type:"action",role:"assistant",action:u.toolKbID||"",actionName:u.toolKbName||"",value:u.toolParameters,result:d?.toolErrorResponse||d?.toolSuccessResponse,isError:!!d?.toolErrorResponse})}else u.type=="tool_result"||this.submitAnalyticsEvent({type:"other",role:"assistant"});return s}finally{this.isProcessing=!1}}async toolRunKBAction(r,n){let i=Date.now();try{this.dispatchEvent(new CustomEvent("toolstart",{detail:{knowledgeBaseEntry:r,input:n,ai:this}}));let o=await r.action(n,this),s=Date.now()-i;return Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!0}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,result:o}})),o}catch(o){let s=Date.now()-i;throw Dr(this,{event_type:"tool_call",value_str:r.id||"",event_properties:{tool_args:n,execution_time_ms:s,success:!1,error_message:o.message}}),this.dispatchEvent(new CustomEvent("tool",{detail:{knowledgeBaseEntry:r,input:n,ai:this,error:o}})),o}}submitAnalyticsEvent(r){if(ht().analytics===!1||this.config?.analytics===!1)return;let n=fetch(this.hubAPI+"/analytics/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,apiKey:this.apiKey,time:Date.now(),conversationID:this.conversationID,personaID:this.config?.id})}).catch(i=>{Ln.debug("Failed to submit analytics event:",i)});this.activeAnalyticsPromises.push(n),n.finally(()=>{this.activeAnalyticsPromises=this.activeAnalyticsPromises.filter(i=>i!==n)})}async waitForAnalytics(){this.activeAnalyticsPromises.length!==0&&(await Promise.all(this.activeAnalyticsPromises),this.activeAnalyticsPromises.length>0&&await this.waitForAnalytics())}resetConversation(){this.currentModel&&(this.currentModel.resetConversation(),this._lastKBsearch="",this._nextRequestUseKBitems=void 0,this.conversationID=sr(),this._lastSystemMsg="")}insertAssistantMessage(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");this.currentModel.addAssistantMessage(r)}exportState(){return{type:"intelliweave/state/v2",conversationID:this.conversationID,messages:this.currentModel?.messageGroup.getAll()}}importState(r){if(!this.currentModel)throw new Error("No model selected. Please call load() first.");if(r?.type!="intelliweave/state/v2")throw new Error(`Invalid state type: ${r.type}`);this.conversationID=r.conversationID;for(let n of r.messages)this.currentModel.messageGroup.add(n)}clone(){let r=new Qa;return r.apiKey=this.apiKey,r.config=this.config,r.models=this.models,this.config?.id&&r.setModel(this.config.id),r.audio=this.audio,r.vadModel=this.vadModel,r.userID=this.userID,r.knowledgeBase=this.knowledgeBase.clone(),r}get messages(){return this.currentModel?.messageGroup.items||[]}};Qa.version=Es.version,Qa.builtInActionsVersion="1.0.0",Ln.debug(`Loaded: version=${Es.version} builtInActionsVersion=${Qa.builtInActionsVersion}`);var Nu=Qa;var yn=class extends HTMLElement{constructor(){super(...arguments);this._state={}}get root(){return this._shadow}static register(){this._isRegistered||(this._isRegistered=!0,this.tagName||(this.tagName="anonymous-component-"+this.name.toLowerCase().replace(/[^a-z0-9-]/g,"-")+"--"+Math.random().toString(36).substring(2)),window.customElements.define(this.tagName,this))}static create(r={},n=""){this.register();let i=document.createElement(this.tagName);for(let o in r)i.setAttribute(o,r[o]);return i.onBeforeCreate(),i.innerHTML=n,i}static add(r={},n=""){this.register();let i=o=>o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;");return`<${this.tagName} ${Object.keys(r).map(o=>`${o}="${i(r[o]+"")}"`).join(" ")}>${n}</${this.tagName}>`}static createElement(){return this.register(),document.createElement(this.tagName)}connectedCallback(){this._shadow||(this._shadow=this.attachShadow({mode:"closed"}),this._shadow.innerHTML=this.html(),this.onCreate()),this.onUpdate()}disconnectedCallback(){this._shadow=void 0,this.onDestroy()}html(){return""}onBeforeCreate(){}onCreate(){}onUpdate(){}onDestroy(){}attributeChangedCallback(r,n,i){this._shadow&&this.onUpdate()}get attr(){return this._attrProxy?this._attrProxy:(this._attrProxy=new Proxy({},{get:(r,n)=>this.getAttribute(n.toString())||"",set:(r,n,i)=>(this.getAttribute(n.toString())===i||(i?this.setAttribute(n.toString(),i):this.removeAttribute(n.toString()),this._shadow&&this.onUpdate()),!0)}),this._attrProxy)}get state(){return this._stateProxy?this._stateProxy:(this._stateProxy=new Proxy({},{get:(r,n)=>this._state[n],set:(r,n,i)=>(this._state[n]=i,this._shadow&&this.onUpdate(),!0)}),this._stateProxy)}hasChild(r){return!!this.root?.getElementById(r)}child(r){let n=this.root?.getElementById(r);if(!n)throw new Error(`Child with ID ${r} not found`);return n}};yn.observedAttributes=[],yn.tagName="",yn._isRegistered=!1;var OM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" width="200" height="200" style="shape-rendering: auto; display: block; " xmlns:xlink="http://www.w3.org/1999/xlink"><g><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="0.5s" calcMode="spline" keyTimes="0;1" values="10;0" keySplines="0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="fill" repeatCount="indefinite" dur="2s" calcMode="discrete" keyTimes="0;0.25;0.5;0.75;1" values="%23797979;%23797979;%23797979;%23797979;%23797979" begin="0s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="0s"></animate>%0A</circle><circle cx="50" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-0.5s"></animate>%0A</circle><circle cx="84" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1s"></animate>%0A</circle><circle cx="16" cy="50" r="10" fill="%23797979">%0A <animate attributeName="r" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="0;0;10;10;10" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A <animate attributeName="cx" repeatCount="indefinite" dur="2s" calcMode="spline" keyTimes="0;0.25;0.5;0.75;1" values="16;16;16;50;84" keySplines="0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1" begin="-1.5s"></animate>%0A</circle><g></g></g><!-- [ldio] generated by https://loading.io --></svg>';var RM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 475.085 475.085" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M237.541 328.897c25.128 0 46.632-8.946 64.523-26.83 17.888-17.884 26.833-39.399 26.833-64.525V91.365c0-25.126-8.938-46.632-26.833-64.525C284.173 8.951 262.669 0 237.541 0c-25.125 0-46.632 8.951-64.524 26.84-17.893 17.89-26.838 39.399-26.838 64.525v146.177c0 25.125 8.949 46.641 26.838 64.525 17.889 17.884 39.399 26.83 64.524 26.83z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path><path d="M396.563 188.15c-3.606-3.617-7.898-5.426-12.847-5.426-4.944 0-9.226 1.809-12.847 5.426-3.613 3.616-5.421 7.898-5.421 12.845v36.547c0 35.214-12.518 65.333-37.548 90.362-25.022 25.03-55.145 37.545-90.36 37.545-35.214 0-65.334-12.515-90.365-37.545-25.028-25.022-37.541-55.147-37.541-90.362v-36.547c0-4.947-1.809-9.229-5.424-12.845-3.617-3.617-7.895-5.426-12.847-5.426s-9.235 1.809-12.85 5.426c-3.618 3.616-5.426 7.898-5.426 12.845v36.547c0 42.065 14.04 78.659 42.112 109.776 28.073 31.118 62.762 48.961 104.068 53.526v37.691h-73.089c-4.949 0-9.231 1.811-12.847 5.428-3.617 3.614-5.426 7.898-5.426 12.847 0 4.941 1.809 9.233 5.426 12.847 3.616 3.614 7.898 5.428 12.847 5.428h182.719c4.948 0 9.236-1.813 12.847-5.428 3.621-3.613 5.431-7.905 5.431-12.847 0-4.948-1.81-9.232-5.431-12.847-3.61-3.617-7.898-5.428-12.847-5.428h-73.08v-37.691c41.299-4.565 75.985-22.408 104.061-53.526 28.076-31.117 42.12-67.711 42.12-109.776v-36.547c0-4.946-1.813-9.225-5.435-12.845z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var MM='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" x="0" y="0" viewBox="0 0 448.075 448.075" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><g><path d="M352.021 16.075c0-6.08-3.52-11.84-8.96-14.4-5.76-2.88-12.16-1.92-16.96 1.92l-141.76 112.96 167.68 167.68zM443.349 420.747l-416-416c-6.24-6.24-16.384-6.24-22.624 0s-6.24 16.384 0 22.624l100.672 100.704h-9.376c-9.92 0-18.56 4.48-24.32 11.52-4.8 5.44-7.68 12.8-7.68 20.48v128c0 17.6 14.4 32 32 32h74.24l155.84 124.48c2.88 2.24 6.4 3.52 9.92 3.52 2.24 0 4.8-.64 7.04-1.6 5.44-2.56 8.96-8.32 8.96-14.4v-57.376l68.672 68.672c3.136 3.136 7.232 4.704 11.328 4.704s8.192-1.568 11.328-4.672c6.24-6.272 6.24-16.384 0-22.656z" fill="%23ffffff" opacity="1" data-original="%23000000" class=""></path></g></svg>';var Wf=class extends yn{constructor(){super(...arguments);this.html=()=>`
36
154
 
37
155
  <!-- Styling -->
38
156
  <style>
@@ -40,7 +158,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
40
158
  :host {
41
159
  width: 100%;
42
160
  height: 44px;
43
- background-color: rgba(0, 0, 0, 0.1);
161
+ background-color: var(--intelliweave-interaction-bg, rgba(0, 0, 0, 0.1));
44
162
  border-top: 1px solid rgba(255, 255, 255, 0.1);
45
163
  display: flex;
46
164
  align-items: center;
@@ -49,6 +167,11 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
49
167
  color: var(--intelliweave-text-color, white);
50
168
  }
51
169
 
170
+ /** Remove top border in fullscreen UI */
171
+ :host([layout="fullscreen"]) {
172
+ border-top: none;
173
+ }
174
+
52
175
  :host input {
53
176
  flex: 1 1 1px;
54
177
  border: none;
@@ -58,6 +181,10 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
58
181
  color: var(--intelliweave-text-color, white);
59
182
  padding: 10px 16px 10px 10px;
60
183
  }
184
+ :host input::placeholder {
185
+ color: var(--intelliweave-text-color, white);
186
+ opacity: 0.7;
187
+ }
61
188
 
62
189
  :host #llm-button {
63
190
  flex: 0 0 auto;
@@ -71,8 +198,39 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
71
198
  border: 1px solid rgba(255, 255, 255, 0.2);
72
199
  }
73
200
 
201
+ :host #send-button {
202
+ flex: 0 0 auto;
203
+ width: 34px;
204
+ height: 34px;
205
+ margin: 0 4px 0 0;
206
+ border-radius: 8px;
207
+ background-color: var(--intelliweave-persona-bg, var(--intelliweave-background, #4a6572));
208
+ border: none;
209
+ cursor: pointer;
210
+ display: flex;
211
+ align-items: center;
212
+ justify-content: center;
213
+ transition: opacity 0.15s ease;
214
+ }
215
+ :host #send-button svg {
216
+ width: 18px;
217
+ height: 18px;
218
+ fill: var(--intelliweave-text-color, white);
219
+ }
220
+
221
+ /** Remove send button background in widget UI */
222
+ :host([layout="widget"]) #send-button {
223
+ background-color: transparent;
224
+ opacity: 0.5;
225
+ }
226
+
227
+ /** Send button hover */
228
+ :host #send-button:hover {
229
+ opacity: 0.85;
230
+ }
231
+
74
232
  :host #loader {
75
- background-image: url('${Re}');
233
+ background-image: url('${OM}');
76
234
  background-size: 64px 64px;
77
235
  background-position: center;
78
236
  background-repeat: no-repeat;
@@ -95,7 +253,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
95
253
  }
96
254
 
97
255
  :host #microphone-button {
98
- background-image: url('${Ve}');
256
+ background-image: url('${RM}');
99
257
  z-index: 2;
100
258
  margin-right: -10px;
101
259
  }
@@ -119,7 +277,7 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
119
277
  }
120
278
 
121
279
  :host #cancel-speech-button {
122
- background-image: url('${Le}');
280
+ background-image: url('${MM}');
123
281
  z-index: 2;
124
282
  }
125
283
 
@@ -140,10 +298,17 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
140
298
  <!-- LLM button -->
141
299
  <div id='llm-button'>LLM</div>
142
300
 
301
+ <!-- Send button -->
302
+ <button id='send-button' type='button' aria-label='Send message'>
303
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
304
+ <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
305
+ </svg>
306
+ </button>
307
+
143
308
  <!-- Loader bar -->
144
309
  <div id='loader'></div>
145
310
 
146
- `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",e=>this.onInputKeyPress(e),{capture:!0}),this.child("input-field").addEventListener("keydown",e=>e.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",e=>this.onLLMButtonClick(e)),this.child("microphone-button").addEventListener("click",e=>this.onMicButtonClick(e)),this.child("cancel-speech-button").addEventListener("click",e=>this.onCancelSpeechButtonClick(e))}connectAI(e){this.ai=e,this.ai.audio?.speechRecognition.addEventListener("speech",t=>this.onSpeechEvent(t)),this.ai.audio?.speechRecognition.addEventListener("start",t=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",t=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",t=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let e=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;e&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!e&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(t=>t.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(e){if(e.stopPropagation(),e.key!="Enter")return;let t=this.child("input-field"),s=t.value?.trim();t.value="",s&&this.dispatchEvent(new CustomEvent("input-message",{detail:s}))}onLLMButtonClick(e){e.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onMicButtonClick(e){e.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let e="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(e="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(e="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(e="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(e="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(e="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(e="rgba(0, 255, 0, 0.5)");let t=this.ai?.audio?.speechRecognition.volumeLevel||0,s=30,n=6,o=Math.round(t*(s-n)+n),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${o}px/2); left: 0px; width: 6px; height: ${o}px; background-color: ${e}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let e=0;e<this.voiceAnimationPieces.length;e++){let t=this.voiceAnimationPieces[e];t.posX+=2,t.style.transform=`translate(${t.posX}px, 0px)`,!(t.posX<400)&&(this.voiceAnimationPieces.splice(e--,1),t.remove())}}}onSpeechEvent(e){this.attr.loading||e.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:e.detail.transcript}))}onCancelSpeechButtonClick(e){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};_.observedAttributes=["loading","llmName","llmButtonVisible","textColor"];var Be='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var D=class extends y{constructor(){super(...arguments);this.html=()=>`
311
+ `;this._wasLoading=!1;this.voiceAnimationPieces=[];this._micAnimFrameCounter=0}onCreate(){this.child("input-field").addEventListener("keypress",r=>this.onInputKeyPress(r),{capture:!0}),this.child("input-field").addEventListener("keydown",r=>r.stopPropagation(),{capture:!0}),this.child("llm-button").addEventListener("click",r=>this.onLLMButtonClick(r)),this.child("send-button").addEventListener("click",r=>this.onSendButtonClick(r)),this.child("microphone-button").addEventListener("click",r=>this.onMicButtonClick(r)),this.child("cancel-speech-button").addEventListener("click",r=>this.onCancelSpeechButtonClick(r))}connectAI(r){this.ai=r,this.ai.audio?.speechRecognition.addEventListener("speech",n=>this.onSpeechEvent(n)),this.ai.audio?.speechRecognition.addEventListener("start",n=>this.onUpdate()),this.ai.audio?.speechRecognition.addEventListener("end",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechstart",n=>this.onUpdate()),this.ai.audio?.speechOutput.addEventListener("speechend",n=>this.onUpdate()),this.onUpdate()}onUpdate(){this.attr.textColor&&document.documentElement.style.setProperty("--intelliweave-text-color",this.attr.textColor),this.child("input-field").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("llm-button").style.display=this.attr.loading||!this.attr.llmButtonVisible||this.state.micActiv?"none":"",this.child("llm-button").innerText=this.attr.llmName||"LLM",this.child("send-button").style.display=this.attr.loading||this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("loader").style.display=this.attr.loading?"block":"",this.child("microphone-button").style.display=!this.ai?.audio?.speechRecognition?.isSupported||this.attr.loading&&!this.ai?.audio?.speechRecognition.isRunning?"none":"",this.child("cancel-speech-button").style.display="none",this.ai?.audio?.speechRecognition.isRunning&&this.ai?.audio?.speechOutput.isSpeaking&&(this.child("microphone-button").style.display="none",this.child("cancel-speech-button").style.display=""),!this.attr.loading&&this._wasLoading&&this.child("input-field").focus(),this._wasLoading=this.attr.loading,this.child("microphone-button-bg").classList.toggle("active",!!this.ai?.audio?.speechRecognition.isRunning);let r=this.ai?.audio?.speechRecognition.isRunning&&!this.attr.loading;r&&!this.micStateAnimationTimer?this.micStateAnimationTimer=setInterval(()=>this.onMicAnimation(),1e3/60):!r&&this.micStateAnimationTimer&&(this.voiceAnimationPieces.forEach(n=>n.remove()),this.voiceAnimationPieces=[],clearInterval(this.micStateAnimationTimer),this.micStateAnimationTimer=void 0)}onInputKeyPress(r){if(r.stopPropagation(),r.key!="Enter")return;let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onLLMButtonClick(r){r.preventDefault(),this.dispatchEvent(new CustomEvent("llm-button-click"))}onSendButtonClick(r){r.preventDefault();let n=this.child("input-field"),i=n.value?.trim();n.value="",i&&this.dispatchEvent(new CustomEvent("input-message",{detail:i}))}onMicButtonClick(r){r.preventDefault(),this.ai.audio?.speechRecognition.isRunning?this.ai.audio?.speechRecognition.stop():this.ai.audio?.speechRecognition.start()}onMicAnimation(){if(!this.attr.loading){if(this._micAnimFrameCounter++,this._micAnimFrameCounter%5==0){let r="rgba(140, 170, 200, 0.5)";this.ai?.audio?.speechRecognition.voiceDetection?.isModelLoaded||(r="rgba(255, 0, 0, 0.5)"),this.ai?.audio?.speechRecognition.voiceDetection?.isTranscribing&&(r="rgba(96, 66, 245, 0.9)"),this.ai?.audio?.speechRecognition.wordsCurrentlyBeingSpoken&&(r="rgba(0, 128, 255, 0.9)"),this.ai?.audio?.speechRecognition.voiceDetection?.isVoicePossiblyEnding&&(r="rgba(0, 128, 255, 0.5)"),this.ai?.isProcessing&&(r="rgba(255, 255, 0, 0.5)"),this.ai?.audio?.speechOutput.isSpeaking&&(r="rgba(0, 255, 0, 0.5)");let n=this.ai?.audio?.speechRecognition.volumeLevel||0,i=30,o=6,s=Math.round(n*(i-o)+o),a=document.createElement("div");a.posX=50,a.style.cssText=`position: absolute; top: calc(50% - ${s}px/2); left: 0px; width: 6px; height: ${s}px; background-color: ${r}; border-radius: 3px; pointer-events: none; `,this.root?.appendChild(a),this.voiceAnimationPieces.push(a)}for(let r=0;r<this.voiceAnimationPieces.length;r++){let n=this.voiceAnimationPieces[r];n.posX+=2,n.style.transform=`translate(${n.posX}px, 0px)`,!(n.posX<400)&&(this.voiceAnimationPieces.splice(r--,1),n.remove())}}}onSpeechEvent(r){this.attr.loading||r.detail.isFinal&&this.dispatchEvent(new CustomEvent("input-message",{detail:r.detail.transcript}))}onCancelSpeechButtonClick(r){this.ai.audio?.speechOutput.interrupt(),this.onUpdate()}};Wf.observedAttributes=["loading","llmName","llmButtonVisible","textColor","layout"];var jM='data:image/svg+xml,<svg id="eLjt8NmVnoY1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 300 300" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" project-id="defaf4a7213e40159eb368f9622a2af1" export-id="e0405e7e1d4a45c0a08fbbedb06a02a8" cached="false"><defs><radialGradient id="eLjt8NmVnoY6-fill" cx="0" cy="0" r="1" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-58.520001 292.985 -172.197 -34.394001 203.907 57.158)"><stop id="eLjt8NmVnoY6-fill-0" offset="0%" stop-color="%232b3d43"/><stop id="eLjt8NmVnoY6-fill-1" offset="33%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-2" offset="58%" stop-color="%23328897"/><stop id="eLjt8NmVnoY6-fill-3" offset="100%" stop-color="%237ebf96"/></radialGradient><radialGradient id="eLjt8NmVnoY7-fill" cx="0" cy="0" r="1.112049" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(182.129 -94.016999 94.016999 182.129 43.4553 184.626)"><stop id="eLjt8NmVnoY7-fill-0" offset="0%" stop-color="%233f2d2d"/><stop id="eLjt8NmVnoY7-fill-1" offset="28%" stop-color="%23c83b35"/><stop id="eLjt8NmVnoY7-fill-2" offset="81%" stop-color="%23f69153"/><stop id="eLjt8NmVnoY7-fill-3" offset="100%" stop-color="%23ffe388"/></radialGradient><radialGradient id="eLjt8NmVnoY9-fill" cx="0" cy="0" r="593.59" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-0.196117 0.98058 -0.578542 -0.115709 406.499077 117.274778)"><stop id="eLjt8NmVnoY9-fill-0" offset="0%" stop-color="%23252d3a"/><stop id="eLjt8NmVnoY9-fill-1" offset="60%" stop-color="%23c50"/><stop id="eLjt8NmVnoY9-fill-2" offset="100%" stop-color="%23fddc85"/></radialGradient><radialGradient id="eLjt8NmVnoY10-fill" cx="0" cy="0" r="454.77" spreadMethod="pad" gradientUnits="userSpaceOnUse" gradientTransform="translate(87.33 340.7)"><stop id="eLjt8NmVnoY10-fill-0" offset="0%" stop-color="%23002936"/><stop id="eLjt8NmVnoY10-fill-1" offset="44%" stop-color="%23007aa1"/><stop id="eLjt8NmVnoY10-fill-2" offset="67%" stop-color="%2326ab7f"/><stop id="eLjt8NmVnoY10-fill-3" offset="100%" stop-color="%2395e0c8"/></radialGradient></defs><g transform="matrix(.339855 0 0 0.339855 65.056641 64.89012)"><path d="M337.93,111.85c17.31-4.12,30.6-2.15,38.55,5.96c12.9,13.16,10.13,41.58-7.64,77.95-34.66,70.98-116.01,153.37-181.35,183.6-4.15,1.92-8.16,3.6-12.02,5.03l.05.18C83.95,418.36,13.7,365.53,1.49,278.27C15.34,403.24,121.28,500.43,249.94,500.43c138.07,0,250-111.93,250-250c0-9.8-.58-19.46-1.68-28.96-12-82.27-75.81-133.5-160.33-109.62Z" fill="url(%23eLjt8NmVnoY9-fill)"/><path d="M249.94,0.43c-138.07,0-250,111.93-250,250c0,9.41.54,18.69,1.55,27.84C13.7,365.54,83.95,418.36,175.52,384.58l-.05-.18c-11.22,4.17-21.17,6.24-29.61,6.24-9.59,0-17.18-2.67-22.44-8.03-12.9-13.19-10.13-41.61,7.64-77.98c18.26-37.41,49.51-77.98,84.51-112.41c31.45-32.33,62.2-54.66,91.14-68.47.16-.08.34-.16.49-.23c1.74-.85,3.47-1.68,5.18-2.49c9.22-4.27,17.77-7.33,25.54-9.17c84.52-23.88,148.33,27.35,160.33,109.62C483.91,97.04,378.22,0.43,249.94,0.43Z" fill="url(%23eLjt8NmVnoY10-fill)"/><path d="M337.93,111.85c-7.77,1.84-16.32,4.9-25.54,9.17-1.71.8-3.45,1.63-5.18,2.49-.16.08-.34.16-.49.23-28.94,13.81-59.69,36.14-91.14,68.47-35,34.43-66.24,75-84.51,112.41-17.77,36.37-20.54,64.79-7.64,77.98c5.26,5.36,12.85,8.03,22.44,8.03c8.45,0,18.39-2.07,29.61-6.24c3.86-1.42,7.88-3.11,12.02-5.03c65.34-30.23,146.68-112.62,181.35-183.6c17.77-36.37,20.54-64.79,7.64-77.95-7.95-8.11-21.24-10.08-38.55-5.96h-.01Z" fill="%23252d3a"/></g></svg>%0D%0A';var Gf=class extends yn{constructor(){super(...arguments);this.html=()=>`
147
312
 
148
313
  <!-- Styling -->
149
314
  <style>
@@ -196,7 +361,32 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
196
361
  <!-- Logo -->
197
362
  <img id='root' />
198
363
 
199
- `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let e=this.child("root");if(!e)return;let t=this.attr.logo||Be;this._lastLogoSrc!=t&&(this._lastLogoSrc=t,e.src=t);let s=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(s){let n=window.visualViewport?.offsetTop||0,o=window.visualViewport?.offsetLeft||0,a=s.getBoundingClientRect();if(!a)return;e.classList.add("focused-mode"),e.style.width="128px",e.style.height="128px",e.style.left=Math.round(a.x+a.width/2-128/2+o)+"px",e.style.top=Math.round(a.y+a.height/2-128/2+n)+"px"}else e.classList.remove("focused-mode"),e.style.width="",e.style.height="",e.style.left="",e.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};D.observedAttributes=["logo","focusID"];import dt from"rehype-external-links";import ht from"rehype-format";import ut from"rehype-stringify";import pt from"remark-parse";import mt from"remark-rehype";import{unified as gt}from"unified";var K=class extends y{constructor(){super(...arguments);this.html=()=>`
364
+ `;this._lastLogoSrc=""}onCreate(){this.layoutUpdateTimer=setInterval(()=>this.onUpdate(),100)}onDestroy(){clearInterval(this.layoutUpdateTimer)}onUpdate(){let r=this.child("root");if(!r)return;let n=this.attr.logo||jM;this._lastLogoSrc!=n&&(this._lastLogoSrc=n,r.src=n);let i=this.attr.focusID?document.getElementById(this.attr.focusID):null;if(i){let o=window.visualViewport?.offsetTop||0,s=window.visualViewport?.offsetLeft||0,a=i.getBoundingClientRect();if(!a)return;r.classList.add("focused-mode"),r.style.width="128px",r.style.height="128px",r.style.left=Math.round(a.x+a.width/2-128/2+s)+"px",r.style.top=Math.round(a.y+a.height/2-128/2+o)+"px"}else r.classList.remove("focused-mode"),r.style.width="",r.style.height="",r.style.left="",r.style.top=""}refreshLayout(){setTimeout(()=>this.onUpdate(),100)}};Gf.observedAttributes=["logo","focusID"];var DM=typeof self=="object"?self:globalThis,CJ=(t,e)=>{let r=(i,o)=>(t.set(o,i),i),n=i=>{if(t.has(i))return t.get(i);let[o,s]=e[i];switch(o){case 0:case-1:return r(s,i);case 1:{let a=r([],i);for(let c of s)a.push(n(c));return a}case 2:{let a=r({},i);for(let[c,l]of s)a[n(c)]=n(l);return a}case 3:return r(new Date(s),i);case 4:{let{source:a,flags:c}=s;return r(new RegExp(a,c),i)}case 5:{let a=r(new Map,i);for(let[c,l]of s)a.set(n(c),n(l));return a}case 6:{let a=r(new Set,i);for(let c of s)a.add(n(c));return a}case 7:{let{name:a,message:c}=s;return r(new DM[a](c),i)}case 8:return r(BigInt(s),i);case"BigInt":return r(Object(BigInt(s)),i)}return r(new DM[o](s),i)};return n},uI=t=>CJ(new Map,t)(0);var Cu="",{toString:OJ}={},{keys:RJ}=Object,Jf=t=>{let e=typeof t;if(e!=="object"||!t)return[0,e];let r=OJ.call(t).slice(8,-1);switch(r){case"Array":return[1,Cu];case"Object":return[2,Cu];case"Date":return[3,Cu];case"RegExp":return[4,Cu];case"Map":return[5,Cu];case"Set":return[6,Cu]}return r.includes("Array")?[1,r]:r.includes("Error")?[7,r]:[2,r]},m_=([t,e])=>t===0&&(e==="function"||e==="symbol"),MJ=(t,e,r,n)=>{let i=(s,a)=>{let c=n.push(s)-1;return r.set(a,c),c},o=s=>{if(r.has(s))return r.get(s);let[a,c]=Jf(s);switch(a){case 0:{let u=s;switch(c){case"bigint":a=8,u=s.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return i([-1],s)}return i([a,u],s)}case 1:{if(c)return i([c,[...s]],s);let u=[],d=i([a,u],s);for(let f of s)u.push(o(f));return d}case 2:{if(c)switch(c){case"BigInt":return i([c,s.toString()],s);case"Boolean":case"Number":case"String":return i([c,s.valueOf()],s)}if(e&&"toJSON"in s)return o(s.toJSON());let u=[],d=i([a,u],s);for(let f of RJ(s))(t||!m_(Jf(s[f])))&&u.push([o(f),o(s[f])]);return d}case 3:return i([a,s.toISOString()],s);case 4:{let{source:u,flags:d}=s;return i([a,{source:u,flags:d}],s)}case 5:{let u=[],d=i([a,u],s);for(let[f,p]of s)(t||!(m_(Jf(f))||m_(Jf(p))))&&u.push([o(f),o(p)]);return d}case 6:{let u=[],d=i([a,u],s);for(let f of s)(t||!m_(Jf(f)))&&u.push(o(f));return d}}let{message:l}=s;return i([a,{name:c,message:l}],s)};return o},dI=(t,{json:e,lossy:r}={})=>{let n=[];return MJ(!(e||r),!!e,new Map,n)(t),n};var Mi=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?uI(dI(t,e)):structuredClone(t):(t,e)=>uI(dI(t,e));var Yf=(function(t,e,r,n,i){let o=ji(e);if(r!=null&&(typeof r!="number"||r<0||r===Number.POSITIVE_INFINITY))throw new Error("Expected positive finite `index`");if(n!=null&&(!n.type||!n.children))throw new Error("Expected valid `parent`");if(r==null!=(n==null))throw new Error("Expected both `index` and `parent`");return LM(t)?o.call(i,t,r,n):!1}),ji=(function(t){if(t==null)return LJ;if(typeof t=="string")return DJ(t);if(typeof t=="object")return jJ(t);if(typeof t=="function")return pI(t);throw new Error("Expected function, string, or array as `test`")});function jJ(t){let e=[],r=-1;for(;++r<t.length;)e[r]=ji(t[r]);return pI(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function DJ(t){return pI(e);function e(r){return r.tagName===t}}function pI(t){return e;function e(r,n,i){return!!(LM(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function LJ(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="element"&&"tagName"in t&&typeof t.tagName=="string")}function LM(t){return t!==null&&typeof t=="object"&&"type"in t&&"tagName"in t}var UJ=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,ZJ=/^[a-zA-Z]:\\/;function fI(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return ZJ.test(t)?!1:UJ.test(t)}function UM(t){let e=String(t||"").trim();return e?e.split(/[ \t\n\r\f]+/g):[]}function ZM(t){return t.join(" ").trim()}var Ou=(function(t){if(t==null)return BJ;if(typeof t=="function")return h_(t);if(typeof t=="object")return Array.isArray(t)?FJ(t):VJ(t);if(typeof t=="string")return qJ(t);throw new Error("Expected function, string, or object as test")});function FJ(t){let e=[],r=-1;for(;++r<t.length;)e[r]=Ou(t[r]);return h_(n);function n(...i){let o=-1;for(;++o<e.length;)if(e[o].apply(this,i))return!0;return!1}}function VJ(t){let e=t;return h_(r);function r(n){let i=n,o;for(o in t)if(i[o]!==e[o])return!1;return!0}}function qJ(t){return h_(e);function e(r){return r&&r.type===t}}function h_(t){return e;function e(r,n,i){return!!(WJ(r)&&t.call(this,r,typeof n=="number"?n:void 0,i||void 0))}}function BJ(){return!0}function WJ(t){return t!==null&&typeof t=="object"&&"type"in t}var FM=[],mI=!0,g_=!1,Qf="skip";function em(t,e,r,n){let i;typeof e=="function"&&typeof r!="function"?(n=r,r=e):i=e;let o=Ou(i),s=n?-1:1;a(t,void 0,[])();function a(c,l,u){let d=c&&typeof c=="object"?c:{};if(typeof d.type=="string"){let p=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(c.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=FM,h,m,g;if((!e||o(c,l,u[u.length-1]||void 0))&&(p=GJ(r(c,u)),p[0]===g_))return p;if("children"in c&&c.children){let y=c;if(y.children&&p[0]!==Qf)for(m=(n?y.children.length:-1)+s,g=u.concat(y);m>-1&&m<y.children.length;){let b=y.children[m];if(h=a(b,m,g)(),h[0]===g_)return h;m=typeof h[1]=="number"?h[1]:m+s}}return p}}}function GJ(t){return Array.isArray(t)?t:typeof t=="number"?[mI,t]:t==null?FM:[t]}function tm(t,e,r,n){let i,o,s;typeof e=="function"&&typeof r!="function"?(o=void 0,s=e,i=r):(o=e,s=r,i=n),em(t,o,a,i);function a(c,l){let u=l[l.length-1],d=u?u.children.indexOf(c):void 0;return s(c,d,u)}}var HJ=["http","https"],XJ=["nofollow"],KJ={};function nm(t){let e=t||KJ,r=e.protocols||HJ,n=ji(e.test);return function(i){tm(i,"element",function(o,s,a){if(o.tagName==="a"&&typeof o.properties.href=="string"&&n(o,s,a)){let c=o.properties.href;if(fI(c)?r.includes(c.slice(0,c.indexOf(":"))):c.startsWith("//")){let l=rm(e.content,o),u=l&&!Array.isArray(l)?[l]:l,d=rm(e.rel,o)||XJ,f=typeof d=="string"?UM(d):d,p=rm(e.target,o),h=rm(e.properties,o);if(h&&Object.assign(o.properties,Mi(h)),f.length>0&&(o.properties.rel=[...f]),p&&(o.properties.target=p),u){let m=rm(e.contentProperties,o)||{};o.children.push({type:"element",tagName:"span",properties:Mi(m),children:Mi(u)})}}}})}}function rm(t,e){return typeof t=="function"?t(e):t}var ec=ji(function(t){return t.tagName==="audio"||t.tagName==="canvas"||t.tagName==="embed"||t.tagName==="iframe"||t.tagName==="img"||t.tagName==="math"||t.tagName==="object"||t.tagName==="picture"||t.tagName==="svg"||t.tagName==="video"});var JJ=/[ \t\n\f\r]/g;function _n(t){return typeof t=="object"?t.type==="text"?VM(t.value):!1:VM(t)}function VM(t){return t.replace(JJ,"")===""}var qM=["address","article","aside","blockquote","body","br","caption","center","col","colgroup","dd","dialog","dir","div","dl","dt","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","legend","li","li","listing","main","menu","nav","ol","optgroup","option","p","plaintext","pre","section","summary","table","tbody","td","td","tfoot","th","th","thead","tr","ul","wbr","xmp"];var BM=["button","input","select","textarea"];var WM=["area","base","basefont","dialog","datalist","head","link","meta","noembed","noframes","param","rp","script","source","style","template","track","title"];var YJ={},hI=Ou(["comment","doctype"]);function gI(t,e){HM(t,{collapse:o8((e||YJ).newlines?n8:i8),whitespace:"normal"})}function HM(t,e){if("children"in t){let r={...e};return(t.type==="root"||JM(t))&&(r.before=!0,r.after=!0),r.whitespace=s8(t,e),e8(t,r)}if(t.type==="text"){if(e.whitespace==="normal")return QJ(t,e);e.whitespace==="nowrap"&&(t.value=e.collapse(t.value))}return{ignore:hI(t),stripAtStart:!1,remove:!1}}function QJ(t,e){let r=e.collapse(t.value),n={ignore:!1,stripAtStart:!1,remove:!1},i=0,o=r.length;return e.before&&GM(r.charAt(0))&&i++,i!==o&&GM(r.charAt(o-1))&&(e.after?o--:n.stripAtStart=!0),i===o?n.remove=!0:t.value=r.slice(i,o),n}function e8(t,e){let r=e.before,n=e.after,i=t.children,o=i.length,s=-1;for(;++s<o;){let a=HM(i[s],{...e,after:XM(i,s,n),before:r});a.remove?(i.splice(s,1),s--,o--):a.ignore||(r=a.stripAtStart),KM(i[s])&&(r=!1)}return{ignore:!1,stripAtStart:!!(r||n),remove:!1}}function XM(t,e,r){for(;++e<t.length;){let n=t[e],i=t8(n);if(i===void 0&&"children"in n&&!r8(n)&&(i=XM(n.children,-1)),typeof i=="boolean")return i}return r}function t8(t){if(t.type==="element"){if(KM(t))return!1;if(JM(t))return!0}else if(t.type==="text"){if(!_n(t))return!1}else if(!hI(t))return!1}function KM(t){return ec(t)||Yf(t,BM)}function JM(t){return Yf(t,qM)}function r8(t){return!!(t.type==="element"&&t.properties.hidden)||hI(t)||Yf(t,WM)}function GM(t){return t===" "||t===`
365
+ `}function n8(t){let e=/\r?\n|\r/.exec(t);return e?e[0]:" "}function i8(){return" "}function o8(t){return e;function e(r){return String(r).replace(/[\t\n\v\f\r ]+/g,t)}}function s8(t,e){if("tagName"in t&&t.properties)switch(t.tagName){case"listing":case"plaintext":case"script":case"style":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return t.properties.wrap?"pre-wrap":"pre";case"td":case"th":return t.properties.noWrap?"nowrap":e.whitespace;case"textarea":return"pre-wrap";default:}return e.whitespace}var a8={}.hasOwnProperty;function yI(t,e){let r=t.type==="element"&&a8.call(t.properties,e)&&t.properties[e];return r!=null&&r!==!1}var c8=new Set(["pingback","prefetch","stylesheet"]);function _I(t){if(t.type!=="element"||t.tagName!=="link")return!1;if(t.properties.itemProp)return!0;let e=t.properties.rel,r=-1;if(!Array.isArray(e)||e.length===0)return!1;for(;++r<e.length;)if(!c8.has(String(e[r])))return!1;return!0}var l8=ji(["a","abbr","area","b","bdi","bdo","br","button","cite","code","data","datalist","del","dfn","em","i","input","ins","kbd","keygen","label","map","mark","meter","noscript","output","progress","q","ruby","s","samp","script","select","small","span","strong","sub","sup","template","textarea","time","u","var","wbr"]),u8=ji("meta");function bI(t){return!!(t.type==="text"||l8(t)||ec(t)||_I(t)||u8(t)&&yI(t,"itemProp"))}var vI=["pre","script","style","textarea"];var d8={};function xI(t,e){let r=e||d8,n={blanks:r.blanks||[],head:!1,indentInitial:r.indentInitial!==!1,indent:typeof r.indent=="number"?" ".repeat(r.indent):typeof r.indent=="string"?r.indent:" "};gI(t,{newlines:!0}),em(t,i);function i(s,a){if(!("children"in s))return;if(s.type==="element"&&s.tagName==="head"&&(n.head=!0),n.head&&s.type==="element"&&s.tagName==="body"&&(n.head=!1),s.type==="element"&&vI.includes(s.tagName))return Qf;if(s.children.length===0||!wI(n,s))return;let c=a.length;n.indentInitial||c--;let l=!1;for(let f of s.children)(f.type==="comment"||f.type==="text")&&(f.value.includes(`
366
+ `)&&(l=!0),f.value=f.value.replace(/ *\n/g,"$&"+n.indent.repeat(c)));let u=[],d;for(let f of s.children)(wI(n,f)||l&&!d)&&(o(u,c,f),l=!0),d=f,u.push(f);d&&(l||wI(n,d))&&(_n(d)&&(u.pop(),d=u[u.length-1]),o(u,c-1)),s.children=u}function o(s,a,c){let l=s[s.length-1],u=l&&_n(l)?s[s.length-2]:l,d=(YM(n,u)&&YM(n,c)?`
367
+
368
+ `:`
369
+ `)+n.indent.repeat(Math.max(a,0));l&&l.type==="text"?l.value=_n(l)?d:l.value+d:s.push({type:"text",value:d})}}function YM(t,e){return!!(e&&e.type==="element"&&t.blanks.length>0&&t.blanks.includes(e.tagName))}function wI(t,e){return e.type==="root"||(e.type==="element"?t.head||e.tagName==="script"||ec(e)||!bI(e):!1)}function im(t){return function(e){xI(e,t)}}var QM=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];var Po=class{constructor(e,r,n){this.property=e,this.normal=r,n&&(this.space=n)}};Po.prototype.property={};Po.prototype.normal={};Po.prototype.space=null;function kI(t,e){let r={},n={},i=-1;for(;++i<t.length;)Object.assign(r,t[i].property),Object.assign(n,t[i].normal);return new Po(r,n,e)}function om(t){return t.toLowerCase()}var Er=class{constructor(e,r){this.property=e,this.attribute=r}};Er.prototype.space=null;Er.prototype.boolean=!1;Er.prototype.booleanish=!1;Er.prototype.overloadedBoolean=!1;Er.prototype.number=!1;Er.prototype.commaSeparated=!1;Er.prototype.spaceSeparated=!1;Er.prototype.commaOrSpaceSeparated=!1;Er.prototype.mustUseProperty=!1;Er.prototype.defined=!1;var sm={};Yu(sm,{boolean:()=>Se,booleanish:()=>zt,commaOrSpaceSeparated:()=>Qr,commaSeparated:()=>Ps,number:()=>L,overloadedBoolean:()=>$I,spaceSeparated:()=>nt});var p8=0,Se=tc(),zt=tc(),$I=tc(),L=tc(),nt=tc(),Ps=tc(),Qr=tc();function tc(){return 2**++p8}var SI=Object.keys(sm),rc=class extends Er{constructor(e,r,n,i){let o=-1;if(super(e,r),ej(this,"space",i),typeof n=="number")for(;++o<SI.length;){let s=SI[o];ej(this,SI[o],(n&sm[s])===sm[s])}}};rc.prototype.defined=!0;function ej(t,e,r){r&&(t[e]=r)}var f8={}.hasOwnProperty;function Un(t){let e={},r={},n;for(n in t.properties)if(f8.call(t.properties,n)){let i=t.properties[n],o=new rc(n,t.transform(t.attributes||{},n),i,t.space);t.mustUseProperty&&t.mustUseProperty.includes(n)&&(o.mustUseProperty=!0),e[n]=o,r[om(n)]=n,r[om(o.attribute)]=n}return new Po(e,r,t.space)}var II=Un({space:"xlink",transform(t,e){return"xlink:"+e.slice(5).toLowerCase()},properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null}});var EI=Un({space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()},properties:{xmlLang:null,xmlBase:null,xmlSpace:null}});function y_(t,e){return e in t?t[e]:e}function __(t,e){return y_(t,e.toLowerCase())}var PI=Un({space:"xmlns",attributes:{xmlnsxlink:"xmlns:xlink"},transform:__,properties:{xmlns:null,xmlnsXLink:null}});var TI=Un({transform(t,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()},properties:{ariaActiveDescendant:null,ariaAtomic:zt,ariaAutoComplete:null,ariaBusy:zt,ariaChecked:zt,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:nt,ariaCurrent:null,ariaDescribedBy:nt,ariaDetails:null,ariaDisabled:zt,ariaDropEffect:nt,ariaErrorMessage:null,ariaExpanded:zt,ariaFlowTo:nt,ariaGrabbed:zt,ariaHasPopup:null,ariaHidden:zt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:nt,ariaLevel:L,ariaLive:null,ariaModal:zt,ariaMultiLine:zt,ariaMultiSelectable:zt,ariaOrientation:null,ariaOwns:nt,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:zt,ariaReadOnly:zt,ariaRelevant:null,ariaRequired:zt,ariaRoleDescription:nt,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:zt,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null}});var tj=Un({space:"html",attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},transform:__,mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ps,acceptCharset:nt,accessKey:nt,action:null,allow:null,allowFullScreen:Se,allowPaymentRequest:Se,allowUserMedia:Se,alt:null,as:null,async:Se,autoCapitalize:null,autoComplete:nt,autoFocus:Se,autoPlay:Se,blocking:nt,capture:null,charSet:null,checked:Se,cite:null,className:nt,cols:L,colSpan:null,content:null,contentEditable:zt,controls:Se,controlsList:nt,coords:L|Ps,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Se,defer:Se,dir:null,dirName:null,disabled:Se,download:$I,draggable:zt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Se,formTarget:null,headers:nt,height:L,hidden:Se,high:L,href:null,hrefLang:null,htmlFor:nt,httpEquiv:nt,id:null,imageSizes:null,imageSrcSet:null,inert:Se,inputMode:null,integrity:null,is:null,isMap:Se,itemId:null,itemProp:nt,itemRef:nt,itemScope:Se,itemType:nt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Se,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:Se,muted:Se,name:null,nonce:null,noModule:Se,noValidate:Se,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Se,optimum:L,pattern:null,ping:nt,placeholder:null,playsInline:Se,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Se,referrerPolicy:null,rel:nt,required:Se,reversed:Se,rows:L,rowSpan:L,sandbox:nt,scope:null,scoped:Se,seamless:Se,selected:Se,shadowRootClonable:Se,shadowRootDelegatesFocus:Se,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:zt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:Se,useMap:null,value:zt,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:nt,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Se,declare:Se,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:Se,noHref:Se,noShade:Se,noWrap:Se,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:zt,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Se,disableRemotePlayback:Se,prefix:null,property:null,results:L,security:null,unselectable:null}});var rj=Un({space:"svg",attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},transform:y_,properties:{about:Qr,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:nt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:Se,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ps,g2:Ps,glyphName:Ps,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:Qr,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:nt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Qr,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Qr,rev:Qr,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Qr,requiredFeatures:Qr,requiredFonts:Qr,requiredFormats:Qr,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:Qr,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Qr,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Qr,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null}});var m8=/^data[-\w.:]+$/i,nj=/-[a-z]/g,h8=/[A-Z]/g;function AI(t,e){let r=om(e),n=e,i=Er;if(r in t.normal)return t.property[t.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&m8.test(e)){if(e.charAt(4)==="-"){let o=e.slice(5).replace(nj,y8);n="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=e.slice(4);if(!nj.test(o)){let s=o.replace(h8,g8);s.charAt(0)!=="-"&&(s="-"+s),e="data"+s}}i=rc}return new i(n,e)}function g8(t){return"-"+t.toLowerCase()}function y8(t){return t.charAt(1).toUpperCase()}var ij=kI([EI,II,PI,TI,tj],"html"),b_=kI([EI,II,PI,TI,rj],"svg");var oj={}.hasOwnProperty;function sj(t,e){let r=e||{};function n(i,...o){let s=n.invalid,a=n.handlers;if(i&&oj.call(i,t)){let c=String(i[t]);s=oj.call(a,c)?a[c]:n.unknown}if(s)return s.call(this,i,...o)}return n.handlers=r.handlers||{},n.invalid=r.invalid,n.unknown=r.unknown,n}var _8=/["&'<>`]/g,b8=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,v8=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,w8=/[|\\{}()[\]^$+*?.]/g,aj=new WeakMap;function cj(t,e){if(t=t.replace(e.subset?x8(e.subset):_8,n),e.subset||e.escapeOnly)return t;return t.replace(b8,r).replace(v8,n);function r(i,o,s){return e.format((i.charCodeAt(0)-55296)*1024+i.charCodeAt(1)-56320+65536,s.charCodeAt(o+2),e)}function n(i,o,s){return e.format(i.charCodeAt(0),s.charCodeAt(o+1),e)}}function x8(t){let e=aj.get(t);return e||(e=k8(t),aj.set(t,e)),e}function k8(t){let e=[],r=-1;for(;++r<t.length;)e.push(t[r].replace(w8,"\\$&"));return new RegExp("(?:"+e.join("|")+")","g")}var $8=/[\dA-Fa-f]/;function lj(t,e,r){let n="&#x"+t.toString(16).toUpperCase();return r&&e&&!$8.test(String.fromCharCode(e))?n:n+";"}var S8=/\d/;function uj(t,e,r){let n="&#"+String(t);return r&&e&&!S8.test(String.fromCharCode(e))?n:n+";"}var dj=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"];var v_={nbsp:"\xA0",iexcl:"\xA1",cent:"\xA2",pound:"\xA3",curren:"\xA4",yen:"\xA5",brvbar:"\xA6",sect:"\xA7",uml:"\xA8",copy:"\xA9",ordf:"\xAA",laquo:"\xAB",not:"\xAC",shy:"\xAD",reg:"\xAE",macr:"\xAF",deg:"\xB0",plusmn:"\xB1",sup2:"\xB2",sup3:"\xB3",acute:"\xB4",micro:"\xB5",para:"\xB6",middot:"\xB7",cedil:"\xB8",sup1:"\xB9",ordm:"\xBA",raquo:"\xBB",frac14:"\xBC",frac12:"\xBD",frac34:"\xBE",iquest:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acirc:"\xC2",Atilde:"\xC3",Auml:"\xC4",Aring:"\xC5",AElig:"\xC6",Ccedil:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecirc:"\xCA",Euml:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icirc:"\xCE",Iuml:"\xCF",ETH:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocirc:"\xD4",Otilde:"\xD5",Ouml:"\xD6",times:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucirc:"\xDB",Uuml:"\xDC",Yacute:"\xDD",THORN:"\xDE",szlig:"\xDF",agrave:"\xE0",aacute:"\xE1",acirc:"\xE2",atilde:"\xE3",auml:"\xE4",aring:"\xE5",aelig:"\xE6",ccedil:"\xE7",egrave:"\xE8",eacute:"\xE9",ecirc:"\xEA",euml:"\xEB",igrave:"\xEC",iacute:"\xED",icirc:"\xEE",iuml:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocirc:"\xF4",otilde:"\xF5",ouml:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucirc:"\xFB",uuml:"\xFC",yacute:"\xFD",thorn:"\xFE",yuml:"\xFF",fnof:"\u0192",Alpha:"\u0391",Beta:"\u0392",Gamma:"\u0393",Delta:"\u0394",Epsilon:"\u0395",Zeta:"\u0396",Eta:"\u0397",Theta:"\u0398",Iota:"\u0399",Kappa:"\u039A",Lambda:"\u039B",Mu:"\u039C",Nu:"\u039D",Xi:"\u039E",Omicron:"\u039F",Pi:"\u03A0",Rho:"\u03A1",Sigma:"\u03A3",Tau:"\u03A4",Upsilon:"\u03A5",Phi:"\u03A6",Chi:"\u03A7",Psi:"\u03A8",Omega:"\u03A9",alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",rho:"\u03C1",sigmaf:"\u03C2",sigma:"\u03C3",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",thetasym:"\u03D1",upsih:"\u03D2",piv:"\u03D6",bull:"\u2022",hellip:"\u2026",prime:"\u2032",Prime:"\u2033",oline:"\u203E",frasl:"\u2044",weierp:"\u2118",image:"\u2111",real:"\u211C",trade:"\u2122",alefsym:"\u2135",larr:"\u2190",uarr:"\u2191",rarr:"\u2192",darr:"\u2193",harr:"\u2194",crarr:"\u21B5",lArr:"\u21D0",uArr:"\u21D1",rArr:"\u21D2",dArr:"\u21D3",hArr:"\u21D4",forall:"\u2200",part:"\u2202",exist:"\u2203",empty:"\u2205",nabla:"\u2207",isin:"\u2208",notin:"\u2209",ni:"\u220B",prod:"\u220F",sum:"\u2211",minus:"\u2212",lowast:"\u2217",radic:"\u221A",prop:"\u221D",infin:"\u221E",ang:"\u2220",and:"\u2227",or:"\u2228",cap:"\u2229",cup:"\u222A",int:"\u222B",there4:"\u2234",sim:"\u223C",cong:"\u2245",asymp:"\u2248",ne:"\u2260",equiv:"\u2261",le:"\u2264",ge:"\u2265",sub:"\u2282",sup:"\u2283",nsub:"\u2284",sube:"\u2286",supe:"\u2287",oplus:"\u2295",otimes:"\u2297",perp:"\u22A5",sdot:"\u22C5",lceil:"\u2308",rceil:"\u2309",lfloor:"\u230A",rfloor:"\u230B",lang:"\u2329",rang:"\u232A",loz:"\u25CA",spades:"\u2660",clubs:"\u2663",hearts:"\u2665",diams:"\u2666",quot:'"',amp:"&",lt:"<",gt:">",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var pj=["cent","copy","divide","gt","lt","not","para","times"];var fj={}.hasOwnProperty,zI={},w_;for(w_ in v_)fj.call(v_,w_)&&(zI[v_[w_]]=w_);var I8=/[^\dA-Za-z]/;function mj(t,e,r,n){let i=String.fromCharCode(t);if(fj.call(zI,i)){let o=zI[i],s="&"+o;return r&&dj.includes(o)&&!pj.includes(o)&&(!n||e&&e!==61&&I8.test(String.fromCharCode(e)))?s:s+";"}return""}function hj(t,e,r){let n=lj(t,e,r.omitOptionalSemicolons),i;if((r.useNamedReferences||r.useShortestReferences)&&(i=mj(t,e,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!i)&&r.useShortestReferences){let o=uj(t,e,r.omitOptionalSemicolons);o.length<n.length&&(n=o)}return i&&(!r.useShortestReferences||i.length<n.length)?i:n}function To(t,e){return cj(t,Object.assign({format:hj},e))}var E8=/^>|^->|<!--|-->|--!>|<!-$/g,P8=[">"],T8=["<",">"];function gj(t,e,r,n){return n.settings.bogusComments?"<?"+To(t.value,Object.assign({},n.settings.characterReferences,{subset:P8}))+">":"<!--"+t.value.replace(E8,i)+"-->";function i(o){return To(o,Object.assign({},n.settings.characterReferences,{subset:T8}))}}function yj(t,e,r,n){return"<!"+(n.settings.upperDoctype?"DOCTYPE":"doctype")+(n.settings.tightDoctype?"":" ")+"html>"}function NI(t,e){let r=String(t);if(typeof e!="string")throw new TypeError("Expected character");let n=0,i=r.indexOf(e);for(;i!==-1;)n++,i=r.indexOf(e,i+e.length);return n}function _j(t,e){let r=e||{};return(t[t.length-1]===""?[...t,""]:t).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}var Dt=bj(1),CI=bj(-1),A8=[];function bj(t){return e;function e(r,n,i){let o=r?r.children:A8,s=(n||0)+t,a=o[s];if(!i)for(;a&&_n(a);)s+=t,a=o[s];return a}}var z8={}.hasOwnProperty;function x_(t){return e;function e(r,n,i){return z8.call(t,r.tagName)&&t[r.tagName](r,n,i)}}var am=x_({body:C8,caption:OI,colgroup:OI,dd:j8,dt:M8,head:OI,html:N8,li:R8,optgroup:D8,option:L8,p:O8,rp:vj,rt:vj,tbody:Z8,td:wj,tfoot:F8,th:wj,thead:U8,tr:V8});function OI(t,e,r){let n=Dt(r,e,!0);return!n||n.type!=="comment"&&!(n.type==="text"&&_n(n.value.charAt(0)))}function N8(t,e,r){let n=Dt(r,e);return!n||n.type!=="comment"}function C8(t,e,r){let n=Dt(r,e);return!n||n.type!=="comment"}function O8(t,e,r){let n=Dt(r,e);return n?n.type==="element"&&(n.tagName==="address"||n.tagName==="article"||n.tagName==="aside"||n.tagName==="blockquote"||n.tagName==="details"||n.tagName==="div"||n.tagName==="dl"||n.tagName==="fieldset"||n.tagName==="figcaption"||n.tagName==="figure"||n.tagName==="footer"||n.tagName==="form"||n.tagName==="h1"||n.tagName==="h2"||n.tagName==="h3"||n.tagName==="h4"||n.tagName==="h5"||n.tagName==="h6"||n.tagName==="header"||n.tagName==="hgroup"||n.tagName==="hr"||n.tagName==="main"||n.tagName==="menu"||n.tagName==="nav"||n.tagName==="ol"||n.tagName==="p"||n.tagName==="pre"||n.tagName==="section"||n.tagName==="table"||n.tagName==="ul"):!r||!(r.type==="element"&&(r.tagName==="a"||r.tagName==="audio"||r.tagName==="del"||r.tagName==="ins"||r.tagName==="map"||r.tagName==="noscript"||r.tagName==="video"))}function R8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&n.tagName==="li"}function M8(t,e,r){let n=Dt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd"))}function j8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&(n.tagName==="dt"||n.tagName==="dd")}function vj(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&(n.tagName==="rp"||n.tagName==="rt")}function D8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&n.tagName==="optgroup"}function L8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&(n.tagName==="option"||n.tagName==="optgroup")}function U8(t,e,r){let n=Dt(r,e);return!!(n&&n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot"))}function Z8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&(n.tagName==="tbody"||n.tagName==="tfoot")}function F8(t,e,r){return!Dt(r,e)}function V8(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&n.tagName==="tr"}function wj(t,e,r){let n=Dt(r,e);return!n||n.type==="element"&&(n.tagName==="td"||n.tagName==="th")}var xj=x_({body:W8,colgroup:G8,head:B8,html:q8,tbody:H8});function q8(t){let e=Dt(t,-1);return!e||e.type!=="comment"}function B8(t){let e=t.children,r=[],n=-1;for(;++n<e.length;){let i=e[n];if(i.type==="element"&&(i.tagName==="title"||i.tagName==="base")){if(r.includes(i.tagName))return!1;r.push(i.tagName)}}return e.length>0}function W8(t){let e=Dt(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&_n(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function G8(t,e,r){let n=CI(r,e),i=Dt(t,-1,!0);return r&&n&&n.type==="element"&&n.tagName==="colgroup"&&am(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="col")}function H8(t,e,r){let n=CI(r,e),i=Dt(t,-1);return r&&n&&n.type==="element"&&(n.tagName==="thead"||n.tagName==="tbody")&&am(n,r.children.indexOf(n),r)?!1:!!(i&&i.type==="element"&&i.tagName==="tr")}var k_={name:[[`
370
+ \f\r &/=>`.split(""),`
371
+ \f\r "&'/=>\``.split("")],[`\0
372
+ \f\r "&'/<=>`.split(""),`\0
373
+ \f\r "&'/<=>\``.split("")]],unquoted:[[`
374
+ \f\r &>`.split(""),`\0
375
+ \f\r "&'<=>\``.split("")],[`\0
376
+ \f\r "&'<=>\``.split(""),`\0
377
+ \f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function kj(t,e,r,n){let i=n.schema,o=i.space==="svg"?!1:n.settings.omitOptionalTags,s=i.space==="svg"?n.settings.closeEmptyElements:n.settings.voids.includes(t.tagName.toLowerCase()),a=[],c;i.space==="html"&&t.tagName==="svg"&&(n.schema=b_);let l=X8(n,t.properties),u=n.all(i.space==="html"&&t.tagName==="template"?t.content:t);return n.schema=i,u&&(s=!1),(l||!o||!xj(t,e,r))&&(a.push("<",t.tagName,l?" "+l:""),s&&(i.space==="svg"||n.settings.closeSelfClosing)&&(c=l.charAt(l.length-1),(!n.settings.tightSelfClosing||c==="/"||c&&c!=='"'&&c!=="'")&&a.push(" "),a.push("/")),a.push(">")),a.push(u),!s&&(!o||!am(t,e,r))&&a.push("</"+t.tagName+">"),a.join("")}function X8(t,e){let r=[],n=-1,i;if(e){for(i in e)if(e[i]!==null&&e[i]!==void 0){let o=K8(t,i,e[i]);o&&r.push(o)}}for(;++n<r.length;){let o=t.settings.tightAttributes?r[n].charAt(r[n].length-1):void 0;n!==r.length-1&&o!=='"'&&o!=="'"&&(r[n]+=" ")}return r.join("")}function K8(t,e,r){let n=AI(t.schema,e),i=t.settings.allowParseErrors&&t.schema.space==="html"?0:1,o=t.settings.allowDangerousCharacters?0:1,s=t.quote,a;if(n.overloadedBoolean&&(r===n.attribute||r==="")?r=!0:(n.boolean||n.overloadedBoolean&&typeof r!="string")&&(r=!!r),r==null||r===!1||typeof r=="number"&&Number.isNaN(r))return"";let c=To(n.attribute,Object.assign({},t.settings.characterReferences,{subset:k_.name[i][o]}));return r===!0||(r=Array.isArray(r)?(n.commaSeparated?_j:ZM)(r,{padLeft:!t.settings.tightCommaSeparatedLists}):String(r),t.settings.collapseEmptyAttributes&&!r)?c:(t.settings.preferUnquoted&&(a=To(r,Object.assign({},t.settings.characterReferences,{attribute:!0,subset:k_.unquoted[i][o]}))),a!==r&&(t.settings.quoteSmart&&NI(r,s)>NI(r,t.alternative)&&(s=t.alternative),a=s+To(r,Object.assign({},t.settings.characterReferences,{subset:(s==="'"?k_.single:k_.double)[i][o],attribute:!0}))+s),c+(a&&"="+a))}var J8=["<","&"];function $_(t,e,r,n){return r&&r.type==="element"&&(r.tagName==="script"||r.tagName==="style")?t.value:To(t.value,Object.assign({},n.settings.characterReferences,{subset:J8}))}function $j(t,e,r,n){return n.settings.allowDangerousHtml?t.value:$_(t,e,r,n)}function Sj(t,e,r,n){return n.all(t)}var Ij=sj("type",{invalid:Y8,unknown:Q8,handlers:{comment:gj,doctype:yj,element:kj,raw:$j,root:Sj,text:$_}});function Y8(t){throw new Error("Expected node, not `"+t+"`")}function Q8(t){let e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}var eY={},tY={},rY=[];function RI(t,e){let r=e||eY,n=r.quote||'"',i=n==='"'?"'":'"';if(n!=='"'&&n!=="'")throw new Error("Invalid quote `"+n+"`, expected `'` or `\"`");return{one:nY,all:iY,settings:{omitOptionalTags:r.omitOptionalTags||!1,allowParseErrors:r.allowParseErrors||!1,allowDangerousCharacters:r.allowDangerousCharacters||!1,quoteSmart:r.quoteSmart||!1,preferUnquoted:r.preferUnquoted||!1,tightAttributes:r.tightAttributes||!1,upperDoctype:r.upperDoctype||!1,tightDoctype:r.tightDoctype||!1,bogusComments:r.bogusComments||!1,tightCommaSeparatedLists:r.tightCommaSeparatedLists||!1,tightSelfClosing:r.tightSelfClosing||!1,collapseEmptyAttributes:r.collapseEmptyAttributes||!1,allowDangerousHtml:r.allowDangerousHtml||!1,voids:r.voids||QM,characterReferences:r.characterReferences||tY,closeSelfClosing:r.closeSelfClosing||!1,closeEmptyElements:r.closeEmptyElements||!1},schema:r.space==="svg"?b_:ij,quote:n,alternative:i}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function nY(t,e,r){return Ij(t,e,r,this)}function iY(t){let e=[],r=t&&t.children||rY,n=-1;for(;++n<r.length;)e[n]=this.one(r[n],n,t);return e.join("")}function cm(t){let e=this,r={...e.data("settings"),...t};e.compiler=n;function n(i){return RI(i,r)}}var oY={};function MI(t,e){let r=e||oY,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,i=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Pj(t,n,i)}function Pj(t,e,r){if(sY(t)){if("value"in t)return t.type==="html"&&!r?"":t.value;if(e&&"alt"in t&&t.alt)return t.alt;if("children"in t)return Ej(t.children,e,r)}return Array.isArray(t)?Ej(t,e,r):""}function Ej(t,e,r){let n=[],i=-1;for(;++i<t.length;)n[i]=Pj(t[i],e,r);return n.join("")}function sY(t){return!!(t&&typeof t=="object")}var Tj=document.createElement("i");function Ru(t){let e="&"+t+";";Tj.innerHTML=e;let r=Tj.textContent;return r.charCodeAt(r.length-1)===59&&t!=="semi"||r===e?!1:r}function Pr(t,e,r,n){let i=t.length,o=0,s;if(e<0?e=-e>i?0:i+e:e=e>i?i:e,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(e,r),t.splice(...s);else for(r&&t.splice(e,r);o<n.length;)s=n.slice(o,o+1e4),s.unshift(e,0),t.splice(...s),o+=1e4,e+=1e4}function Lr(t,e){return t.length>0?(Pr(t,t.length,0,e),t):e}var Aj={}.hasOwnProperty;function zj(t){let e={},r=-1;for(;++r<t.length;)aY(e,t[r]);return e}function aY(t,e){let r;for(r in e){let i=(Aj.call(t,r)?t[r]:void 0)||(t[r]={}),o=e[r],s;if(o)for(s in o){Aj.call(i,s)||(i[s]=[]);let a=o[s];cY(i[s],Array.isArray(a)?a:a?[a]:[])}}}function cY(t,e){let r=-1,n=[];for(;++r<e.length;)(e[r].add==="after"?t:n).push(e[r]);Pr(t,0,0,n)}function S_(t,e){let r=Number.parseInt(t,e);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"\uFFFD":String.fromCodePoint(r)}function Ao(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}var bn=Ts(/[A-Za-z]/),tr=Ts(/[\dA-Za-z]/),Nj=Ts(/[#-'*+\--9=?A-Z^-~]/);function lm(t){return t!==null&&(t<32||t===127)}var um=Ts(/\d/),Cj=Ts(/[\dA-Fa-f]/),Oj=Ts(/[!-/:-@[-`{-~]/);function Q(t){return t!==null&&t<-2}function Lt(t){return t!==null&&(t<0||t===32)}function Ie(t){return t===-2||t===-1||t===32}var Rj=Ts(/\p{P}|\p{S}/u),Mj=Ts(/\s/);function Ts(t){return e;function e(r){return r!==null&&r>-1&&t.test(String.fromCharCode(r))}}function Zn(t){let e=[],r=-1,n=0,i=0;for(;++r<t.length;){let o=t.charCodeAt(r),s="";if(o===37&&tr(t.charCodeAt(r+1))&&tr(t.charCodeAt(r+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(s=String.fromCharCode(o));else if(o>55295&&o<57344){let a=t.charCodeAt(r+1);o<56320&&a>56319&&a<57344?(s=String.fromCharCode(o,a),i=1):s="\uFFFD"}else s=String.fromCharCode(o);s&&(e.push(t.slice(n,r),encodeURIComponent(s)),n=r+i+1,s=""),i&&(r+=i,i=0)}return e.join("")+t.slice(n)}function Ee(t,e,r,n){let i=n?n-1:Number.POSITIVE_INFINITY,o=0;return s;function s(c){return Ie(c)?(t.enter(r),a(c)):e(c)}function a(c){return Ie(c)&&o++<i?(t.consume(c),a):(t.exit(r),e(c))}}var jj={tokenize:lY};function lY(t){let e=t.attempt(this.parser.constructs.contentInitial,n,i),r;return e;function n(a){if(a===null){t.consume(a);return}return t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),Ee(t,e,"linePrefix")}function i(a){return t.enter("paragraph"),o(a)}function o(a){let c=t.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=c),r=c,s(a)}function s(a){if(a===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(a);return}return Q(a)?(t.consume(a),t.exit("chunkText"),o):(t.consume(a),s)}}var Lj={tokenize:uY},Dj={tokenize:dY};function uY(t){let e=this,r=[],n=0,i,o,s;return a;function a($){if(n<r.length){let R=r[n];return e.containerState=R[1],t.attempt(R[0].continuation,c,l)($)}return l($)}function c($){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,i&&b();let R=e.events.length,T=R,P;for(;T--;)if(e.events[T][0]==="exit"&&e.events[T][1].type==="chunkFlow"){P=e.events[T][1].end;break}y(n);let F=R;for(;F<e.events.length;)e.events[F][1].end=Object.assign({},P),F++;return Pr(e.events,T+1,0,e.events.slice(R)),e.events.length=F,l($)}return a($)}function l($){if(n===r.length){if(!i)return f($);if(i.currentConstruct&&i.currentConstruct.concrete)return h($);e.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return e.containerState={},t.check(Dj,u,d)($)}function u($){return i&&b(),y(n),f($)}function d($){return e.parser.lazy[e.now().line]=n!==r.length,s=e.now().offset,h($)}function f($){return e.containerState={},t.attempt(Dj,p,h)($)}function p($){return n++,r.push([e.currentConstruct,e.containerState]),f($)}function h($){if($===null){i&&b(),y(0),t.consume($);return}return i=i||e.parser.flow(e.now()),t.enter("chunkFlow",{contentType:"flow",previous:o,_tokenizer:i}),m($)}function m($){if($===null){g(t.exit("chunkFlow"),!0),y(0),t.consume($);return}return Q($)?(t.consume($),g(t.exit("chunkFlow")),n=0,e.interrupt=void 0,a):(t.consume($),m)}function g($,R){let T=e.sliceStream($);if(R&&T.push(null),$.previous=o,o&&(o.next=$),o=$,i.defineSkip($.start),i.write(T),e.parser.lazy[$.start.line]){let P=i.events.length;for(;P--;)if(i.events[P][1].start.offset<s&&(!i.events[P][1].end||i.events[P][1].end.offset>s))return;let F=e.events.length,ce=F,te,H;for(;ce--;)if(e.events[ce][0]==="exit"&&e.events[ce][1].type==="chunkFlow"){if(te){H=e.events[ce][1].end;break}te=!0}for(y(n),P=F;P<e.events.length;)e.events[P][1].end=Object.assign({},H),P++;Pr(e.events,ce+1,0,e.events.slice(F)),e.events.length=P}}function y($){let R=r.length;for(;R-- >$;){let T=r[R];e.containerState=T[1],T[0].exit.call(e,t)}r.length=$}function b(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function dY(t,e,r){return Ee(t,t.attempt(this.parser.constructs.document,e,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function jI(t){if(t===null||Lt(t)||Mj(t))return 1;if(Rj(t))return 2}function Mu(t,e,r){let n=[],i=-1;for(;++i<t.length;){let o=t[i].resolveAll;o&&!n.includes(o)&&(e=o(e,r),n.push(o))}return e}var dm={name:"attention",tokenize:fY,resolveAll:pY};function pY(t,e){let r=-1,n,i,o,s,a,c,l,u;for(;++r<t.length;)if(t[r][0]==="enter"&&t[r][1].type==="attentionSequence"&&t[r][1]._close){for(n=r;n--;)if(t[n][0]==="exit"&&t[n][1].type==="attentionSequence"&&t[n][1]._open&&e.sliceSerialize(t[n][1]).charCodeAt(0)===e.sliceSerialize(t[r][1]).charCodeAt(0)){if((t[n][1]._close||t[r][1]._open)&&(t[r][1].end.offset-t[r][1].start.offset)%3&&!((t[n][1].end.offset-t[n][1].start.offset+t[r][1].end.offset-t[r][1].start.offset)%3))continue;c=t[n][1].end.offset-t[n][1].start.offset>1&&t[r][1].end.offset-t[r][1].start.offset>1?2:1;let d=Object.assign({},t[n][1].end),f=Object.assign({},t[r][1].start);Uj(d,-c),Uj(f,c),s={type:c>1?"strongSequence":"emphasisSequence",start:d,end:Object.assign({},t[n][1].end)},a={type:c>1?"strongSequence":"emphasisSequence",start:Object.assign({},t[r][1].start),end:f},o={type:c>1?"strongText":"emphasisText",start:Object.assign({},t[n][1].end),end:Object.assign({},t[r][1].start)},i={type:c>1?"strong":"emphasis",start:Object.assign({},s.start),end:Object.assign({},a.end)},t[n][1].end=Object.assign({},s.start),t[r][1].start=Object.assign({},a.end),l=[],t[n][1].end.offset-t[n][1].start.offset&&(l=Lr(l,[["enter",t[n][1],e],["exit",t[n][1],e]])),l=Lr(l,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),l=Lr(l,Mu(e.parser.constructs.insideSpan.null,t.slice(n+1,r),e)),l=Lr(l,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[r][1].end.offset-t[r][1].start.offset?(u=2,l=Lr(l,[["enter",t[r][1],e],["exit",t[r][1],e]])):u=0,Pr(t,n-1,r-n+3,l),r=n+l.length-u-2;break}}for(r=-1;++r<t.length;)t[r][1].type==="attentionSequence"&&(t[r][1].type="data");return t}function fY(t,e){let r=this.parser.constructs.attentionMarkers.null,n=this.previous,i=jI(n),o;return s;function s(c){return o=c,t.enter("attentionSequence"),a(c)}function a(c){if(c===o)return t.consume(c),a;let l=t.exit("attentionSequence"),u=jI(c),d=!u||u===2&&i||r.includes(c),f=!i||i===2&&u||r.includes(n);return l._open=!!(o===42?d:d&&(i||!f)),l._close=!!(o===42?f:f&&(u||!d)),e(c)}}function Uj(t,e){t.column+=e,t.offset+=e,t._bufferIndex+=e}var DI={name:"autolink",tokenize:mY};function mY(t,e,r){let n=0;return i;function i(p){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),o}function o(p){return bn(p)?(t.consume(p),s):p===64?r(p):l(p)}function s(p){return p===43||p===45||p===46||tr(p)?(n=1,a(p)):l(p)}function a(p){return p===58?(t.consume(p),n=0,c):(p===43||p===45||p===46||tr(p))&&n++<32?(t.consume(p),a):(n=0,l(p))}function c(p){return p===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),e):p===null||p===32||p===60||lm(p)?r(p):(t.consume(p),c)}function l(p){return p===64?(t.consume(p),u):Nj(p)?(t.consume(p),l):r(p)}function u(p){return tr(p)?d(p):r(p)}function d(p){return p===46?(t.consume(p),n=0,u):p===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),e):f(p)}function f(p){if((p===45||tr(p))&&n++<63){let h=p===45?f:d;return t.consume(p),h}return r(p)}}var As={tokenize:hY,partial:!0};function hY(t,e,r){return n;function n(o){return Ie(o)?Ee(t,i,"linePrefix")(o):i(o)}function i(o){return o===null||Q(o)?e(o):r(o)}}var I_={name:"blockQuote",tokenize:gY,continuation:{tokenize:yY},exit:_Y};function gY(t,e,r){let n=this;return i;function i(s){if(s===62){let a=n.containerState;return a.open||(t.enter("blockQuote",{_container:!0}),a.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(s),t.exit("blockQuoteMarker"),o}return r(s)}function o(s){return Ie(s)?(t.enter("blockQuotePrefixWhitespace"),t.consume(s),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),e):(t.exit("blockQuotePrefix"),e(s))}}function yY(t,e,r){let n=this;return i;function i(s){return Ie(s)?Ee(t,o,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):o(s)}function o(s){return t.attempt(I_,e,r)(s)}}function _Y(t){t.exit("blockQuote")}var E_={name:"characterEscape",tokenize:bY};function bY(t,e,r){return n;function n(o){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(o),t.exit("escapeMarker"),i}function i(o){return Oj(o)?(t.enter("characterEscapeValue"),t.consume(o),t.exit("characterEscapeValue"),t.exit("characterEscape"),e):r(o)}}var P_={name:"characterReference",tokenize:vY};function vY(t,e,r){let n=this,i=0,o,s;return a;function a(d){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),c}function c(d){return d===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(d),t.exit("characterReferenceMarkerNumeric"),l):(t.enter("characterReferenceValue"),o=31,s=tr,u(d))}function l(d){return d===88||d===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(d),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),o=6,s=Cj,u):(t.enter("characterReferenceValue"),o=7,s=um,u(d))}function u(d){if(d===59&&i){let f=t.exit("characterReferenceValue");return s===tr&&!Ru(n.sliceSerialize(f))?r(d):(t.enter("characterReferenceMarker"),t.consume(d),t.exit("characterReferenceMarker"),t.exit("characterReference"),e)}return s(d)&&i++<o?(t.consume(d),u):r(d)}}var Zj={tokenize:xY,partial:!0},T_={name:"codeFenced",tokenize:wY,concrete:!0};function wY(t,e,r){let n=this,i={tokenize:T,partial:!0},o=0,s=0,a;return c;function c(P){return l(P)}function l(P){let F=n.events[n.events.length-1];return o=F&&F[1].type==="linePrefix"?F[2].sliceSerialize(F[1],!0).length:0,a=P,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(P)}function u(P){return P===a?(s++,t.consume(P),u):s<3?r(P):(t.exit("codeFencedFenceSequence"),Ie(P)?Ee(t,d,"whitespace")(P):d(P))}function d(P){return P===null||Q(P)?(t.exit("codeFencedFence"),n.interrupt?e(P):t.check(Zj,m,R)(P)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),f(P))}function f(P){return P===null||Q(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),d(P)):Ie(P)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ee(t,p,"whitespace")(P)):P===96&&P===a?r(P):(t.consume(P),f)}function p(P){return P===null||Q(P)?d(P):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),h(P))}function h(P){return P===null||Q(P)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),d(P)):P===96&&P===a?r(P):(t.consume(P),h)}function m(P){return t.attempt(i,R,g)(P)}function g(P){return t.enter("lineEnding"),t.consume(P),t.exit("lineEnding"),y}function y(P){return o>0&&Ie(P)?Ee(t,b,"linePrefix",o+1)(P):b(P)}function b(P){return P===null||Q(P)?t.check(Zj,m,R)(P):(t.enter("codeFlowValue"),$(P))}function $(P){return P===null||Q(P)?(t.exit("codeFlowValue"),b(P)):(t.consume(P),$)}function R(P){return t.exit("codeFenced"),e(P)}function T(P,F,ce){let te=0;return H;function H(fe){return P.enter("lineEnding"),P.consume(fe),P.exit("lineEnding"),_e}function _e(fe){return P.enter("codeFencedFence"),Ie(fe)?Ee(P,he,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(fe):he(fe)}function he(fe){return fe===a?(P.enter("codeFencedFenceSequence"),Y(fe)):ce(fe)}function Y(fe){return fe===a?(te++,P.consume(fe),Y):te>=s?(P.exit("codeFencedFenceSequence"),Ie(fe)?Ee(P,pe,"whitespace")(fe):pe(fe)):ce(fe)}function pe(fe){return fe===null||Q(fe)?(P.exit("codeFencedFence"),F(fe)):ce(fe)}}}function xY(t,e,r){let n=this;return i;function i(s){return s===null?r(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}var pm={name:"codeIndented",tokenize:$Y},kY={tokenize:SY,partial:!0};function $Y(t,e,r){let n=this;return i;function i(l){return t.enter("codeIndented"),Ee(t,o,"linePrefix",5)(l)}function o(l){let u=n.events[n.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?s(l):r(l)}function s(l){return l===null?c(l):Q(l)?t.attempt(kY,s,c)(l):(t.enter("codeFlowValue"),a(l))}function a(l){return l===null||Q(l)?(t.exit("codeFlowValue"),s(l)):(t.consume(l),a)}function c(l){return t.exit("codeIndented"),e(l)}}function SY(t,e,r){let n=this;return i;function i(s){return n.parser.lazy[n.now().line]?r(s):Q(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):Ee(t,o,"linePrefix",5)(s)}function o(s){let a=n.events[n.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):Q(s)?i(s):r(s)}}var LI={name:"codeText",tokenize:PY,resolve:IY,previous:EY};function IY(t){let e=t.length-4,r=3,n,i;if((t[r][1].type==="lineEnding"||t[r][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(n=r;++n<e;)if(t[n][1].type==="codeTextData"){t[r][1].type="codeTextPadding",t[e][1].type="codeTextPadding",r+=2,e-=2;break}}for(n=r-1,e++;++n<=e;)i===void 0?n!==e&&t[n][1].type!=="lineEnding"&&(i=n):(n===e||t[n][1].type==="lineEnding")&&(t[i][1].type="codeTextData",n!==i+2&&(t[i][1].end=t[n-1][1].end,t.splice(i+2,n-i-2),e-=n-i-2,n=i+2),i=void 0);return t}function EY(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function PY(t,e,r){let n=this,i=0,o,s;return a;function a(f){return t.enter("codeText"),t.enter("codeTextSequence"),c(f)}function c(f){return f===96?(t.consume(f),i++,c):(t.exit("codeTextSequence"),l(f))}function l(f){return f===null?r(f):f===32?(t.enter("space"),t.consume(f),t.exit("space"),l):f===96?(s=t.enter("codeTextSequence"),o=0,d(f)):Q(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),l):(t.enter("codeTextData"),u(f))}function u(f){return f===null||f===32||f===96||Q(f)?(t.exit("codeTextData"),l(f)):(t.consume(f),u)}function d(f){return f===96?(t.consume(f),o++,d):o===i?(t.exit("codeTextSequence"),t.exit("codeText"),e(f)):(s.type="codeTextData",u(f))}}var A_=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,r){let n=r??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,r,n){let i=r||0;this.setCursor(Math.trunc(e));let o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&fm(this.left,n),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),fm(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),fm(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){let r=this.left.splice(e,Number.POSITIVE_INFINITY);fm(this.right,r.reverse())}else{let r=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);fm(this.left,r.reverse())}}};function fm(t,e){let r=0;if(e.length<1e4)t.push(...e);else for(;r<e.length;)t.push(...e.slice(r,r+1e4)),r+=1e4}function z_(t){let e={},r=-1,n,i,o,s,a,c,l,u=new A_(t);for(;++r<u.length;){for(;r in e;)r=e[r];if(n=u.get(r),r&&n[1].type==="chunkFlow"&&u.get(r-1)[1].type==="listItemPrefix"&&(c=n[1]._tokenizer.events,o=0,o<c.length&&c[o][1].type==="lineEndingBlank"&&(o+=2),o<c.length&&c[o][1].type==="content"))for(;++o<c.length&&c[o][1].type!=="content";)c[o][1].type==="chunkText"&&(c[o][1]._isInFirstContentOfListItem=!0,o++);if(n[0]==="enter")n[1].contentType&&(Object.assign(e,TY(u,r)),r=e[r],l=!0);else if(n[1]._container){for(o=r,i=void 0;o--&&(s=u.get(o),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank");)s[0]==="enter"&&(i&&(u.get(i)[1].type="lineEndingBlank"),s[1].type="lineEnding",i=o);i&&(n[1].end=Object.assign({},u.get(i)[1].start),a=u.slice(i,r),a.unshift(n),u.splice(i,r-i+1,a))}}return Pr(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!l}function TY(t,e){let r=t.get(e)[1],n=t.get(e)[2],i=e-1,o=[],s=r._tokenizer||n.parser[r.contentType](r.start),a=s.events,c=[],l={},u,d,f=-1,p=r,h=0,m=0,g=[m];for(;p;){for(;t.get(++i)[1]!==p;);o.push(i),p._tokenizer||(u=n.sliceStream(p),p.next||u.push(null),d&&s.defineSkip(p.start),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(u),p._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=r;++f<a.length;)a[f][0]==="exit"&&a[f-1][0]==="enter"&&a[f][1].type===a[f-1][1].type&&a[f][1].start.line!==a[f][1].end.line&&(m=f+1,g.push(m),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(s.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),f=g.length;f--;){let y=a.slice(g[f],g[f+1]),b=o.pop();c.push([b,b+y.length-1]),t.splice(b,2,y)}for(c.reverse(),f=-1;++f<c.length;)l[h+c[f][0]]=h+c[f][1],h+=c[f][1]-c[f][0]-1;return l}var UI={tokenize:NY,resolve:zY},AY={tokenize:CY,partial:!0};function zY(t){return z_(t),t}function NY(t,e){let r;return n;function n(a){return t.enter("content"),r=t.enter("chunkContent",{contentType:"content"}),i(a)}function i(a){return a===null?o(a):Q(a)?t.check(AY,s,o)(a):(t.consume(a),i)}function o(a){return t.exit("chunkContent"),t.exit("content"),e(a)}function s(a){return t.consume(a),t.exit("chunkContent"),r.next=t.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,i}}function CY(t,e,r){let n=this;return i;function i(s){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),Ee(t,o,"linePrefix")}function o(s){if(s===null||Q(s))return r(s);let a=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):t.interrupt(n.parser.constructs.flow,r,e)(s)}}function N_(t,e,r,n,i,o,s,a,c){let l=c||Number.POSITIVE_INFINITY,u=0;return d;function d(y){return y===60?(t.enter(n),t.enter(i),t.enter(o),t.consume(y),t.exit(o),f):y===null||y===32||y===41||lm(y)?r(y):(t.enter(n),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),m(y))}function f(y){return y===62?(t.enter(o),t.consume(y),t.exit(o),t.exit(i),t.exit(n),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(a),f(y)):y===null||y===60||Q(y)?r(y):(t.consume(y),y===92?h:p)}function h(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function m(y){return!u&&(y===null||y===41||Lt(y))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(n),e(y)):u<l&&y===40?(t.consume(y),u++,m):y===41?(t.consume(y),u--,m):y===null||y===32||y===40||lm(y)?r(y):(t.consume(y),y===92?g:m)}function g(y){return y===40||y===41||y===92?(t.consume(y),m):m(y)}}function C_(t,e,r,n,i,o){let s=this,a=0,c;return l;function l(p){return t.enter(n),t.enter(i),t.consume(p),t.exit(i),t.enter(o),u}function u(p){return a>999||p===null||p===91||p===93&&!c||p===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?r(p):p===93?(t.exit(o),t.enter(i),t.consume(p),t.exit(i),t.exit(n),e):Q(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),d(p))}function d(p){return p===null||p===91||p===93||Q(p)||a++>999?(t.exit("chunkString"),u(p)):(t.consume(p),c||(c=!Ie(p)),p===92?f:d)}function f(p){return p===91||p===92||p===93?(t.consume(p),a++,d):d(p)}}function O_(t,e,r,n,i,o){let s;return a;function a(f){return f===34||f===39||f===40?(t.enter(n),t.enter(i),t.consume(f),t.exit(i),s=f===40?41:f,c):r(f)}function c(f){return f===s?(t.enter(i),t.consume(f),t.exit(i),t.exit(n),e):(t.enter(o),l(f))}function l(f){return f===s?(t.exit(o),c(s)):f===null?r(f):Q(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),Ee(t,l,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(f))}function u(f){return f===s||f===null||Q(f)?(t.exit("chunkString"),l(f)):(t.consume(f),f===92?d:u)}function d(f){return f===s||f===92?(t.consume(f),u):u(f)}}function nc(t,e){let r;return n;function n(i){return Q(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),r=!0,n):Ie(i)?Ee(t,n,r?"linePrefix":"lineSuffix")(i):e(i)}}var ZI={name:"definition",tokenize:RY},OY={tokenize:MY,partial:!0};function RY(t,e,r){let n=this,i;return o;function o(p){return t.enter("definition"),s(p)}function s(p){return C_.call(n,t,a,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function a(p){return i=Ao(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),c):r(p)}function c(p){return Lt(p)?nc(t,l)(p):l(p)}function l(p){return N_(t,u,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(OY,d,d)(p)}function d(p){return Ie(p)?Ee(t,f,"whitespace")(p):f(p)}function f(p){return p===null||Q(p)?(t.exit("definition"),n.parser.defined.push(i),e(p)):r(p)}}function MY(t,e,r){return n;function n(a){return Lt(a)?nc(t,i)(a):r(a)}function i(a){return O_(t,o,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return Ie(a)?Ee(t,s,"whitespace")(a):s(a)}function s(a){return a===null||Q(a)?e(a):r(a)}}var FI={name:"hardBreakEscape",tokenize:jY};function jY(t,e,r){return n;function n(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return Q(o)?(t.exit("hardBreakEscape"),e(o)):r(o)}}var VI={name:"headingAtx",tokenize:LY,resolve:DY};function DY(t,e){let r=t.length-2,n=3,i,o;return t[n][1].type==="whitespace"&&(n+=2),r-2>n&&t[r][1].type==="whitespace"&&(r-=2),t[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&t[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(i={type:"atxHeadingText",start:t[n][1].start,end:t[r][1].end},o={type:"chunkText",start:t[n][1].start,end:t[r][1].end,contentType:"text"},Pr(t,n,r-n+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function LY(t,e,r){let n=0;return i;function i(u){return t.enter("atxHeading"),o(u)}function o(u){return t.enter("atxHeadingSequence"),s(u)}function s(u){return u===35&&n++<6?(t.consume(u),s):u===null||Lt(u)?(t.exit("atxHeadingSequence"),a(u)):r(u)}function a(u){return u===35?(t.enter("atxHeadingSequence"),c(u)):u===null||Q(u)?(t.exit("atxHeading"),e(u)):Ie(u)?Ee(t,a,"whitespace")(u):(t.enter("atxHeadingText"),l(u))}function c(u){return u===35?(t.consume(u),c):(t.exit("atxHeadingSequence"),a(u))}function l(u){return u===null||u===35||Lt(u)?(t.exit("atxHeadingText"),a(u)):(t.consume(u),l)}}var Fj=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],qI=["pre","script","style","textarea"];var BI={name:"htmlFlow",tokenize:VY,resolveTo:FY,concrete:!0},UY={tokenize:BY,partial:!0},ZY={tokenize:qY,partial:!0};function FY(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function VY(t,e,r){let n=this,i,o,s,a,c;return l;function l(k){return u(k)}function u(k){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(k),d}function d(k){return k===33?(t.consume(k),f):k===47?(t.consume(k),o=!0,m):k===63?(t.consume(k),i=3,n.interrupt?e:w):bn(k)?(t.consume(k),s=String.fromCharCode(k),g):r(k)}function f(k){return k===45?(t.consume(k),i=2,p):k===91?(t.consume(k),i=5,a=0,h):bn(k)?(t.consume(k),i=4,n.interrupt?e:w):r(k)}function p(k){return k===45?(t.consume(k),n.interrupt?e:w):r(k)}function h(k){let Ut="CDATA[";return k===Ut.charCodeAt(a++)?(t.consume(k),a===Ut.length?n.interrupt?e:he:h):r(k)}function m(k){return bn(k)?(t.consume(k),s=String.fromCharCode(k),g):r(k)}function g(k){if(k===null||k===47||k===62||Lt(k)){let Ut=k===47,Zt=s.toLowerCase();return!Ut&&!o&&qI.includes(Zt)?(i=1,n.interrupt?e(k):he(k)):Fj.includes(s.toLowerCase())?(i=6,Ut?(t.consume(k),y):n.interrupt?e(k):he(k)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):o?b(k):$(k))}return k===45||tr(k)?(t.consume(k),s+=String.fromCharCode(k),g):r(k)}function y(k){return k===62?(t.consume(k),n.interrupt?e:he):r(k)}function b(k){return Ie(k)?(t.consume(k),b):H(k)}function $(k){return k===47?(t.consume(k),H):k===58||k===95||bn(k)?(t.consume(k),R):Ie(k)?(t.consume(k),$):H(k)}function R(k){return k===45||k===46||k===58||k===95||tr(k)?(t.consume(k),R):T(k)}function T(k){return k===61?(t.consume(k),P):Ie(k)?(t.consume(k),T):$(k)}function P(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(t.consume(k),c=k,F):Ie(k)?(t.consume(k),P):ce(k)}function F(k){return k===c?(t.consume(k),c=null,te):k===null||Q(k)?r(k):(t.consume(k),F)}function ce(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Lt(k)?T(k):(t.consume(k),ce)}function te(k){return k===47||k===62||Ie(k)?$(k):r(k)}function H(k){return k===62?(t.consume(k),_e):r(k)}function _e(k){return k===null||Q(k)?he(k):Ie(k)?(t.consume(k),_e):r(k)}function he(k){return k===45&&i===2?(t.consume(k),bt):k===60&&i===1?(t.consume(k),Nt):k===62&&i===4?(t.consume(k),Ar):k===63&&i===3?(t.consume(k),w):k===93&&i===5?(t.consume(k),tn):Q(k)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(UY,Vn,Y)(k)):k===null||Q(k)?(t.exit("htmlFlowData"),Y(k)):(t.consume(k),he)}function Y(k){return t.check(ZY,pe,Vn)(k)}function pe(k){return t.enter("lineEnding"),t.consume(k),t.exit("lineEnding"),fe}function fe(k){return k===null||Q(k)?Y(k):(t.enter("htmlFlowData"),he(k))}function bt(k){return k===45?(t.consume(k),w):he(k)}function Nt(k){return k===47?(t.consume(k),s="",Ur):he(k)}function Ur(k){if(k===62){let Ut=s.toLowerCase();return qI.includes(Ut)?(t.consume(k),Ar):he(k)}return bn(k)&&s.length<8?(t.consume(k),s+=String.fromCharCode(k),Ur):he(k)}function tn(k){return k===93?(t.consume(k),w):he(k)}function w(k){return k===62?(t.consume(k),Ar):k===45&&i===2?(t.consume(k),w):he(k)}function Ar(k){return k===null||Q(k)?(t.exit("htmlFlowData"),Vn(k)):(t.consume(k),Ar)}function Vn(k){return t.exit("htmlFlow"),e(k)}}function qY(t,e,r){let n=this;return i;function i(s){return Q(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):r(s)}function o(s){return n.parser.lazy[n.now().line]?r(s):e(s)}}function BY(t,e,r){return n;function n(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(As,e,r)}}var WI={name:"htmlText",tokenize:WY};function WY(t,e,r){let n=this,i,o,s;return a;function a(w){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(w),c}function c(w){return w===33?(t.consume(w),l):w===47?(t.consume(w),T):w===63?(t.consume(w),$):bn(w)?(t.consume(w),ce):r(w)}function l(w){return w===45?(t.consume(w),u):w===91?(t.consume(w),o=0,h):bn(w)?(t.consume(w),b):r(w)}function u(w){return w===45?(t.consume(w),p):r(w)}function d(w){return w===null?r(w):w===45?(t.consume(w),f):Q(w)?(s=d,Nt(w)):(t.consume(w),d)}function f(w){return w===45?(t.consume(w),p):d(w)}function p(w){return w===62?bt(w):w===45?f(w):d(w)}function h(w){let Ar="CDATA[";return w===Ar.charCodeAt(o++)?(t.consume(w),o===Ar.length?m:h):r(w)}function m(w){return w===null?r(w):w===93?(t.consume(w),g):Q(w)?(s=m,Nt(w)):(t.consume(w),m)}function g(w){return w===93?(t.consume(w),y):m(w)}function y(w){return w===62?bt(w):w===93?(t.consume(w),y):m(w)}function b(w){return w===null||w===62?bt(w):Q(w)?(s=b,Nt(w)):(t.consume(w),b)}function $(w){return w===null?r(w):w===63?(t.consume(w),R):Q(w)?(s=$,Nt(w)):(t.consume(w),$)}function R(w){return w===62?bt(w):$(w)}function T(w){return bn(w)?(t.consume(w),P):r(w)}function P(w){return w===45||tr(w)?(t.consume(w),P):F(w)}function F(w){return Q(w)?(s=F,Nt(w)):Ie(w)?(t.consume(w),F):bt(w)}function ce(w){return w===45||tr(w)?(t.consume(w),ce):w===47||w===62||Lt(w)?te(w):r(w)}function te(w){return w===47?(t.consume(w),bt):w===58||w===95||bn(w)?(t.consume(w),H):Q(w)?(s=te,Nt(w)):Ie(w)?(t.consume(w),te):bt(w)}function H(w){return w===45||w===46||w===58||w===95||tr(w)?(t.consume(w),H):_e(w)}function _e(w){return w===61?(t.consume(w),he):Q(w)?(s=_e,Nt(w)):Ie(w)?(t.consume(w),_e):te(w)}function he(w){return w===null||w===60||w===61||w===62||w===96?r(w):w===34||w===39?(t.consume(w),i=w,Y):Q(w)?(s=he,Nt(w)):Ie(w)?(t.consume(w),he):(t.consume(w),pe)}function Y(w){return w===i?(t.consume(w),i=void 0,fe):w===null?r(w):Q(w)?(s=Y,Nt(w)):(t.consume(w),Y)}function pe(w){return w===null||w===34||w===39||w===60||w===61||w===96?r(w):w===47||w===62||Lt(w)?te(w):(t.consume(w),pe)}function fe(w){return w===47||w===62||Lt(w)?te(w):r(w)}function bt(w){return w===62?(t.consume(w),t.exit("htmlTextData"),t.exit("htmlText"),e):r(w)}function Nt(w){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),Ur}function Ur(w){return Ie(w)?Ee(t,tn,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(w):tn(w)}function tn(w){return t.enter("htmlTextData"),s(w)}}var ic={name:"labelEnd",tokenize:YY,resolveTo:JY,resolveAll:KY},GY={tokenize:QY},HY={tokenize:e7},XY={tokenize:t7};function KY(t){let e=-1;for(;++e<t.length;){let r=t[e][1];(r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd")&&(t.splice(e+1,r.type==="labelImage"?4:2),r.type="data",e++)}return t}function JY(t,e){let r=t.length,n=0,i,o,s,a;for(;r--;)if(i=t[r][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;t[r][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(s){if(t[r][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=r,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(s=r);let c={type:t[o][1].type==="labelLink"?"link":"image",start:Object.assign({},t[o][1].start),end:Object.assign({},t[t.length-1][1].end)},l={type:"label",start:Object.assign({},t[o][1].start),end:Object.assign({},t[s][1].end)},u={type:"labelText",start:Object.assign({},t[o+n+2][1].end),end:Object.assign({},t[s-2][1].start)};return a=[["enter",c,e],["enter",l,e]],a=Lr(a,t.slice(o+1,o+n+3)),a=Lr(a,[["enter",u,e]]),a=Lr(a,Mu(e.parser.constructs.insideSpan.null,t.slice(o+n+4,s-3),e)),a=Lr(a,[["exit",u,e],t[s-2],t[s-1],["exit",l,e]]),a=Lr(a,t.slice(s+1)),a=Lr(a,[["exit",c,e]]),Pr(t,o,t.length,a),t}function YY(t,e,r){let n=this,i=n.events.length,o,s;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){o=n.events[i][1];break}return a;function a(f){return o?o._inactive?d(f):(s=n.parser.defined.includes(Ao(n.sliceSerialize({start:o.end,end:n.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(f),t.exit("labelMarker"),t.exit("labelEnd"),c):r(f)}function c(f){return f===40?t.attempt(GY,u,s?u:d)(f):f===91?t.attempt(HY,u,s?l:d)(f):s?u(f):d(f)}function l(f){return t.attempt(XY,u,d)(f)}function u(f){return e(f)}function d(f){return o._balanced=!0,r(f)}}function QY(t,e,r){return n;function n(d){return t.enter("resource"),t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),i}function i(d){return Lt(d)?nc(t,o)(d):o(d)}function o(d){return d===41?u(d):N_(t,s,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(d)}function s(d){return Lt(d)?nc(t,c)(d):u(d)}function a(d){return r(d)}function c(d){return d===34||d===39||d===40?O_(t,l,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(d):u(d)}function l(d){return Lt(d)?nc(t,u)(d):u(d)}function u(d){return d===41?(t.enter("resourceMarker"),t.consume(d),t.exit("resourceMarker"),t.exit("resource"),e):r(d)}}function e7(t,e,r){let n=this;return i;function i(a){return C_.call(n,t,o,s,"reference","referenceMarker","referenceString")(a)}function o(a){return n.parser.defined.includes(Ao(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(a):r(a)}function s(a){return r(a)}}function t7(t,e,r){return n;function n(o){return t.enter("reference"),t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),i}function i(o){return o===93?(t.enter("referenceMarker"),t.consume(o),t.exit("referenceMarker"),t.exit("reference"),e):r(o)}}var GI={name:"labelStartImage",tokenize:r7,resolveAll:ic.resolveAll};function r7(t,e,r){let n=this;return i;function i(a){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(a),t.exit("labelImageMarker"),o}function o(a){return a===91?(t.enter("labelMarker"),t.consume(a),t.exit("labelMarker"),t.exit("labelImage"),s):r(a)}function s(a){return a===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(a):e(a)}}var HI={name:"labelStartLink",tokenize:n7,resolveAll:ic.resolveAll};function n7(t,e,r){let n=this;return i;function i(s){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(s),t.exit("labelMarker"),t.exit("labelLink"),o}function o(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):e(s)}}var mm={name:"lineEnding",tokenize:i7};function i7(t,e){return r;function r(n){return t.enter("lineEnding"),t.consume(n),t.exit("lineEnding"),Ee(t,e,"linePrefix")}}var oc={name:"thematicBreak",tokenize:o7};function o7(t,e,r){let n=0,i;return o;function o(l){return t.enter("thematicBreak"),s(l)}function s(l){return i=l,a(l)}function a(l){return l===i?(t.enter("thematicBreakSequence"),c(l)):n>=3&&(l===null||Q(l))?(t.exit("thematicBreak"),e(l)):r(l)}function c(l){return l===i?(t.consume(l),n++,c):(t.exit("thematicBreakSequence"),Ie(l)?Ee(t,a,"whitespace")(l):a(l))}}var Tr={name:"list",tokenize:c7,continuation:{tokenize:l7},exit:d7},s7={tokenize:p7,partial:!0},a7={tokenize:u7,partial:!0};function c7(t,e,r){let n=this,i=n.events[n.events.length-1],o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(p){let h=n.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(h==="listUnordered"?!n.containerState.marker||p===n.containerState.marker:um(p)){if(n.containerState.type||(n.containerState.type=h,t.enter(h,{_container:!0})),h==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(oc,r,l)(p):l(p);if(!n.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),c(p)}return r(p)}function c(p){return um(p)&&++s<10?(t.consume(p),c):(!n.interrupt||s<2)&&(n.containerState.marker?p===n.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),l(p)):r(p)}function l(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||p,t.check(As,n.interrupt?r:u,t.attempt(s7,f,d))}function u(p){return n.containerState.initialBlankLine=!0,o++,f(p)}function d(p){return Ie(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),f):r(p)}function f(p){return n.containerState.size=o+n.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(p)}}function l7(t,e,r){let n=this;return n.containerState._closeFlow=void 0,t.check(As,i,o);function i(a){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,Ee(t,e,"listItemIndent",n.containerState.size+1)(a)}function o(a){return n.containerState.furtherBlankLines||!Ie(a)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(a)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,t.attempt(a7,e,s)(a))}function s(a){return n.containerState._closeFlow=!0,n.interrupt=void 0,Ee(t,t.attempt(Tr,e,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function u7(t,e,r){let n=this;return Ee(t,i,"listItemIndent",n.containerState.size+1);function i(o){let s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?e(o):r(o)}}function d7(t){t.exit(this.containerState.type)}function p7(t,e,r){let n=this;return Ee(t,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){let s=n.events[n.events.length-1];return!Ie(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):r(o)}}var R_={name:"setextUnderline",tokenize:m7,resolveTo:f7};function f7(t,e){let r=t.length,n,i,o;for(;r--;)if(t[r][0]==="enter"){if(t[r][1].type==="content"){n=r;break}t[r][1].type==="paragraph"&&(i=r)}else t[r][1].type==="content"&&t.splice(r,1),!o&&t[r][1].type==="definition"&&(o=r);let s={type:"setextHeading",start:Object.assign({},t[i][1].start),end:Object.assign({},t[t.length-1][1].end)};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[n][1],e]),t[n][1].end=Object.assign({},t[o][1].end)):t[n][1]=s,t.push(["exit",s,e]),t}function m7(t,e,r){let n=this,i;return o;function o(l){let u=n.events.length,d;for(;u--;)if(n.events[u][1].type!=="lineEnding"&&n.events[u][1].type!=="linePrefix"&&n.events[u][1].type!=="content"){d=n.events[u][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||d)?(t.enter("setextHeadingLine"),i=l,s(l)):r(l)}function s(l){return t.enter("setextHeadingLineSequence"),a(l)}function a(l){return l===i?(t.consume(l),a):(t.exit("setextHeadingLineSequence"),Ie(l)?Ee(t,c,"lineSuffix")(l):c(l))}function c(l){return l===null||Q(l)?(t.exit("setextHeadingLine"),e(l)):r(l)}}var Vj={tokenize:h7};function h7(t){let e=this,r=t.attempt(As,n,t.attempt(this.parser.constructs.flowInitial,i,Ee(t,t.attempt(this.parser.constructs.flow,i,t.attempt(UI,i)),"linePrefix")));return r;function n(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,r}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,r}}var qj={resolveAll:Hj()},Bj=Gj("string"),Wj=Gj("text");function Gj(t){return{tokenize:e,resolveAll:Hj(t==="text"?g7:void 0)};function e(r){let n=this,i=this.parser.constructs[t],o=r.attempt(i,s,a);return s;function s(u){return l(u)?o(u):a(u)}function a(u){if(u===null){r.consume(u);return}return r.enter("data"),r.consume(u),c}function c(u){return l(u)?(r.exit("data"),o(u)):(r.consume(u),c)}function l(u){if(u===null)return!0;let d=i[u],f=-1;if(d)for(;++f<d.length;){let p=d[f];if(!p.previous||p.previous.call(n,n.previous))return!0}return!1}}}function Hj(t){return e;function e(r,n){let i=-1,o;for(;++i<=r.length;)o===void 0?r[i]&&r[i][1].type==="data"&&(o=i,i++):(!r[i]||r[i][1].type!=="data")&&(i!==o+2&&(r[o][1].end=r[i-1][1].end,r.splice(o+2,i-o-2),i=o+2),o=void 0);return t?t(r,n):r}}function g7(t,e){let r=0;for(;++r<=t.length;)if((r===t.length||t[r][1].type==="lineEnding")&&t[r-1][1].type==="data"){let n=t[r-1][1],i=e.sliceStream(n),o=i.length,s=-1,a=0,c;for(;o--;){let l=i[o];if(typeof l=="string"){for(s=l.length;l.charCodeAt(s-1)===32;)a++,s--;if(s)break;s=-1}else if(l===-2)c=!0,a++;else if(l!==-1){o++;break}}if(a){let l={type:r===t.length||c||a<2?"lineSuffix":"hardBreakTrailing",start:{line:n.end.line,column:n.end.column-a,offset:n.end.offset-a,_index:n.start._index+o,_bufferIndex:o?s:n.start._bufferIndex+s},end:Object.assign({},n.end)};n.end=Object.assign({},l.start),n.start.offset===n.end.offset?Object.assign(n,l):(t.splice(r,0,["enter",l,e],["exit",l,e]),r+=2)}r++}return t}function Xj(t,e,r){let n=Object.assign(r?Object.assign({},r):{line:1,column:1,offset:0},{_index:0,_bufferIndex:-1}),i={},o=[],s=[],a=[],c=!0,l={consume:R,enter:T,exit:P,attempt:te(F),check:te(ce),interrupt:te(ce,{interrupt:!0})},u={previous:null,code:null,containerState:{},events:[],parser:t,sliceStream:m,sliceSerialize:h,now:g,defineSkip:y,write:p},d=e.tokenize.call(u,l),f;return e.resolveAll&&o.push(e),u;function p(Y){return s=Lr(s,Y),b(),s[s.length-1]!==null?[]:(H(e,0),u.events=Mu(o,u.events,u),u.events)}function h(Y,pe){return _7(m(Y),pe)}function m(Y){return y7(s,Y)}function g(){let{line:Y,column:pe,offset:fe,_index:bt,_bufferIndex:Nt}=n;return{line:Y,column:pe,offset:fe,_index:bt,_bufferIndex:Nt}}function y(Y){i[Y.line]=Y.column,he()}function b(){let Y;for(;n._index<s.length;){let pe=s[n._index];if(typeof pe=="string")for(Y=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===Y&&n._bufferIndex<pe.length;)$(pe.charCodeAt(n._bufferIndex));else $(pe)}}function $(Y){c=void 0,f=Y,d=d(Y)}function R(Y){Q(Y)?(n.line++,n.column=1,n.offset+=Y===-3?2:1,he()):Y!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=Y,c=!0}function T(Y,pe){let fe=pe||{};return fe.type=Y,fe.start=g(),u.events.push(["enter",fe,u]),a.push(fe),fe}function P(Y){let pe=a.pop();return pe.end=g(),u.events.push(["exit",pe,u]),pe}function F(Y,pe){H(Y,pe.from)}function ce(Y,pe){pe.restore()}function te(Y,pe){return fe;function fe(bt,Nt,Ur){let tn,w,Ar,Vn;return Array.isArray(bt)?Ut(bt):"tokenize"in bt?Ut([bt]):k(bt);function k(Ct){return Li;function Li(Fr){let Ui=Fr!==null&&Ct[Fr],zo=Fr!==null&&Ct.null,qu=[...Array.isArray(Ui)?Ui:Ui?[Ui]:[],...Array.isArray(zo)?zo:zo?[zo]:[]];return Ut(qu)(Fr)}}function Ut(Ct){return tn=Ct,w=0,Ct.length===0?Ur:Zt(Ct[w])}function Zt(Ct){return Li;function Li(Fr){return Vn=_e(),Ar=Ct,Ct.partial||(u.currentConstruct=Ct),Ct.name&&u.parser.constructs.disable.null.includes(Ct.name)?qn(Fr):Ct.tokenize.call(pe?Object.assign(Object.create(u),pe):u,l,Zr,qn)(Fr)}}function Zr(Ct){return c=!0,Y(Ar,Vn),Nt}function qn(Ct){return c=!0,Vn.restore(),++w<tn.length?Zt(tn[w]):Ur}}}function H(Y,pe){Y.resolveAll&&!o.includes(Y)&&o.push(Y),Y.resolve&&Pr(u.events,pe,u.events.length-pe,Y.resolve(u.events.slice(pe),u)),Y.resolveTo&&(u.events=Y.resolveTo(u.events,u))}function _e(){let Y=g(),pe=u.previous,fe=u.currentConstruct,bt=u.events.length,Nt=Array.from(a);return{restore:Ur,from:bt};function Ur(){n=Y,u.previous=pe,u.currentConstruct=fe,u.events.length=bt,a=Nt,he()}}function he(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function y7(t,e){let r=e.start._index,n=e.start._bufferIndex,i=e.end._index,o=e.end._bufferIndex,s;if(r===i)s=[t[r].slice(n,o)];else{if(s=t.slice(r,i),n>-1){let a=s[0];typeof a=="string"?s[0]=a.slice(n):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function _7(t,e){let r=-1,n=[],i;for(;++r<t.length;){let o=t[r],s;if(typeof o=="string")s=o;else switch(o){case-5:{s="\r";break}case-4:{s=`
378
+ `;break}case-3:{s=`\r
379
+ `;break}case-2:{s=e?" ":" ";break}case-1:{if(!e&&i)continue;s=" ";break}default:s=String.fromCharCode(o)}i=o===-2,n.push(s)}return n.join("")}var XI={};Yu(XI,{attentionMarkers:()=>I7,contentInitial:()=>v7,disable:()=>E7,document:()=>b7,flow:()=>x7,flowInitial:()=>w7,insideSpan:()=>S7,string:()=>k7,text:()=>$7});var b7={42:Tr,43:Tr,45:Tr,48:Tr,49:Tr,50:Tr,51:Tr,52:Tr,53:Tr,54:Tr,55:Tr,56:Tr,57:Tr,62:I_},v7={91:ZI},w7={[-2]:pm,[-1]:pm,32:pm},x7={35:VI,42:oc,45:[R_,oc],60:BI,61:R_,95:oc,96:T_,126:T_},k7={38:P_,92:E_},$7={[-5]:mm,[-4]:mm,[-3]:mm,33:GI,38:P_,42:dm,60:[DI,WI],91:HI,92:[FI,E_],93:ic,95:dm,96:LI},S7={null:[dm,qj]},I7={null:[42,95]},E7={null:[]};function KI(t){let r=zj([XI,...(t||{}).extensions||[]]),n={defined:[],lazy:{},constructs:r,content:i(jj),document:i(Lj),flow:i(Vj),string:i(Bj),text:i(Wj)};return n;function i(o){return s;function s(a){return Xj(n,o,a)}}}function JI(t){for(;!z_(t););return t}var Kj=/[\0\t\n\r]/g;function YI(){let t=1,e="",r=!0,n;return i;function i(o,s,a){let c=[],l,u,d,f,p;for(o=e+(typeof o=="string"?o.toString():new TextDecoder(s||void 0).decode(o)),d=0,e="",r&&(o.charCodeAt(0)===65279&&d++,r=void 0);d<o.length;){if(Kj.lastIndex=d,l=Kj.exec(o),f=l&&l.index!==void 0?l.index:o.length,p=o.charCodeAt(f),!l){e=o.slice(d);break}if(p===10&&d===f&&n)c.push(-3),n=void 0;else switch(n&&(c.push(-5),n=void 0),d<f&&(c.push(o.slice(d,f)),t+=f-d),p){case 0:{c.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,c.push(-2);t++<u;)c.push(-1);break}case 10:{c.push(-4),t=1;break}default:n=!0,t=1}d=f+1}return a&&(n&&c.push(-5),e&&c.push(e),c.push(null)),c}}var P7=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Jj(t){return t.replace(P7,T7)}function T7(t,e,r){if(e)return e;if(r.charCodeAt(0)===35){let i=r.charCodeAt(1),o=i===120||i===88;return S_(r.slice(o?2:1),o?16:10)}return Ru(r)||t}function zs(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Yj(t.position):"start"in t||"end"in t?Yj(t):"line"in t||"column"in t?QI(t):""}function QI(t){return Qj(t&&t.line)+":"+Qj(t&&t.column)}function Yj(t){return QI(t&&t.start)+"-"+QI(t&&t.end)}function Qj(t){return t&&typeof t=="number"?t:1}var tD={}.hasOwnProperty;function eE(t,e,r){return typeof e!="string"&&(r=e,e=void 0),A7(r)(JI(KI(r).document().write(YI()(t,e,!0))))}function A7(t){let e={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Wu),autolinkProtocol:te,autolinkEmail:te,atxHeading:o(vn),blockQuote:o(Li),characterEscape:te,characterReference:te,codeFenced:o(Fr),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:o(Fr,s),codeText:o(Ui,s),codeTextData:te,data:te,codeFlowValue:te,definition:o(zo),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:o(qu),hardBreakEscape:o($m),hardBreakTrailing:o($m),htmlFlow:o(Bu,s),htmlFlowData:te,htmlText:o(Bu,s),htmlTextData:te,image:o(Sm),label:s,link:o(Wu),listItem:o(No),listItemValue:f,listOrdered:o(Im,d),listUnordered:o(Im),paragraph:o(wn),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:o(vn),strong:o(Em),thematicBreak:o(ib)},exit:{atxHeading:c(),atxHeadingSequence:T,autolink:c(),autolinkEmail:Ct,autolinkProtocol:qn,blockQuote:c(),characterEscapeValue:H,characterReferenceMarkerHexadecimal:Zt,characterReferenceMarkerNumeric:Zt,characterReferenceValue:Zr,codeFenced:c(g),codeFencedFence:m,codeFencedFenceInfo:p,codeFencedFenceMeta:h,codeFlowValue:H,codeIndented:c(y),codeText:c(fe),codeTextData:H,data:H,definition:c(),definitionDestinationString:R,definitionLabelString:b,definitionTitleString:$,emphasis:c(),hardBreakEscape:c(he),hardBreakTrailing:c(he),htmlFlow:c(Y),htmlFlowData:H,htmlText:c(pe),htmlTextData:H,image:c(Nt),label:tn,labelText:Ur,lineEnding:_e,link:c(bt),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:Ut,resourceDestinationString:w,resourceTitleString:Ar,resource:Vn,setextHeading:c(ce),setextHeadingLineSequence:F,setextHeadingText:P,strong:c(),thematicBreak:c()}};rD(e,(t||{}).mdastExtensions||[]);let r={};return n;function n(j){let V={type:"root",children:[]},le={stack:[V],tokenStack:[],config:e,enter:a,exit:l,buffer:s,resume:u,data:r},Te=[],et=-1;for(;++et<j.length;)if(j[et][1].type==="listOrdered"||j[et][1].type==="listUnordered")if(j[et][0]==="enter")Te.push(et);else{let Vr=Te.pop();et=i(j,Vr,et)}for(et=-1;++et<j.length;){let Vr=e[j[et][0]];tD.call(Vr,j[et][1].type)&&Vr[j[et][1].type].call(Object.assign({sliceSerialize:j[et][2].sliceSerialize},le),j[et][1])}if(le.tokenStack.length>0){let Vr=le.tokenStack[le.tokenStack.length-1];(Vr[1]||eD).call(le,void 0,Vr[0])}for(V.position={start:Ns(j.length>0?j[0][1].start:{line:1,column:1,offset:0}),end:Ns(j.length>0?j[j.length-2][1].end:{line:1,column:1,offset:0})},et=-1;++et<e.transforms.length;)V=e.transforms[et](V)||V;return V}function i(j,V,le){let Te=V-1,et=-1,Vr=!1,rn,xn,Os,Rs;for(;++Te<=le;){let _r=j[Te];switch(_r[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{_r[0]==="enter"?et++:et--,Rs=void 0;break}case"lineEndingBlank":{_r[0]==="enter"&&(rn&&!Rs&&!et&&!Os&&(Os=Te),Rs=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Rs=void 0}if(!et&&_r[0]==="enter"&&_r[1].type==="listItemPrefix"||et===-1&&_r[0]==="exit"&&(_r[1].type==="listUnordered"||_r[1].type==="listOrdered")){if(rn){let nr=Te;for(xn=void 0;nr--;){let Bn=j[nr];if(Bn[1].type==="lineEnding"||Bn[1].type==="lineEndingBlank"){if(Bn[0]==="exit")continue;xn&&(j[xn][1].type="lineEndingBlank",Vr=!0),Bn[1].type="lineEnding",xn=nr}else if(!(Bn[1].type==="linePrefix"||Bn[1].type==="blockQuotePrefix"||Bn[1].type==="blockQuotePrefixWhitespace"||Bn[1].type==="blockQuoteMarker"||Bn[1].type==="listItemIndent"))break}Os&&(!xn||Os<xn)&&(rn._spread=!0),rn.end=Object.assign({},xn?j[xn][1].start:_r[1].end),j.splice(xn||Te,0,["exit",rn,_r[2]]),Te++,le++}if(_r[1].type==="listItemPrefix"){let nr={type:"listItem",_spread:!1,start:Object.assign({},_r[1].start),end:void 0};rn=nr,j.splice(Te,0,["enter",nr,_r[2]]),Te++,le++,Os=void 0,Rs=!0}}}return j[V][1]._spread=Vr,le}function o(j,V){return le;function le(Te){a.call(this,j(Te),Te),V&&V.call(this,Te)}}function s(){this.stack.push({type:"fragment",children:[]})}function a(j,V,le){this.stack[this.stack.length-1].children.push(j),this.stack.push(j),this.tokenStack.push([V,le]),j.position={start:Ns(V.start),end:void 0}}function c(j){return V;function V(le){j&&j.call(this,le),l.call(this,le)}}function l(j,V){let le=this.stack.pop(),Te=this.tokenStack.pop();if(Te)Te[0].type!==j.type&&(V?V.call(this,j,Te[0]):(Te[1]||eD).call(this,j,Te[0]));else throw new Error("Cannot close `"+j.type+"` ("+zs({start:j.start,end:j.end})+"): it\u2019s not open");le.position.end=Ns(j.end)}function u(){return MI(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(j){if(this.data.expectingFirstListItemValue){let V=this.stack[this.stack.length-2];V.start=Number.parseInt(this.sliceSerialize(j),10),this.data.expectingFirstListItemValue=void 0}}function p(){let j=this.resume(),V=this.stack[this.stack.length-1];V.lang=j}function h(){let j=this.resume(),V=this.stack[this.stack.length-1];V.meta=j}function m(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){let j=this.resume(),V=this.stack[this.stack.length-1];V.value=j.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){let j=this.resume(),V=this.stack[this.stack.length-1];V.value=j.replace(/(\r?\n|\r)$/g,"")}function b(j){let V=this.resume(),le=this.stack[this.stack.length-1];le.label=V,le.identifier=Ao(this.sliceSerialize(j)).toLowerCase()}function $(){let j=this.resume(),V=this.stack[this.stack.length-1];V.title=j}function R(){let j=this.resume(),V=this.stack[this.stack.length-1];V.url=j}function T(j){let V=this.stack[this.stack.length-1];if(!V.depth){let le=this.sliceSerialize(j).length;V.depth=le}}function P(){this.data.setextHeadingSlurpLineEnding=!0}function F(j){let V=this.stack[this.stack.length-1];V.depth=this.sliceSerialize(j).codePointAt(0)===61?1:2}function ce(){this.data.setextHeadingSlurpLineEnding=void 0}function te(j){let le=this.stack[this.stack.length-1].children,Te=le[le.length-1];(!Te||Te.type!=="text")&&(Te=nb(),Te.position={start:Ns(j.start),end:void 0},le.push(Te)),this.stack.push(Te)}function H(j){let V=this.stack.pop();V.value+=this.sliceSerialize(j),V.position.end=Ns(j.end)}function _e(j){let V=this.stack[this.stack.length-1];if(this.data.atHardBreak){let le=V.children[V.children.length-1];le.position.end=Ns(j.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&e.canContainEols.includes(V.type)&&(te.call(this,j),H.call(this,j))}function he(){this.data.atHardBreak=!0}function Y(){let j=this.resume(),V=this.stack[this.stack.length-1];V.value=j}function pe(){let j=this.resume(),V=this.stack[this.stack.length-1];V.value=j}function fe(){let j=this.resume(),V=this.stack[this.stack.length-1];V.value=j}function bt(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let V=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=V,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function Nt(){let j=this.stack[this.stack.length-1];if(this.data.inReference){let V=this.data.referenceType||"shortcut";j.type+="Reference",j.referenceType=V,delete j.url,delete j.title}else delete j.identifier,delete j.label;this.data.referenceType=void 0}function Ur(j){let V=this.sliceSerialize(j),le=this.stack[this.stack.length-2];le.label=Jj(V),le.identifier=Ao(V).toLowerCase()}function tn(){let j=this.stack[this.stack.length-1],V=this.resume(),le=this.stack[this.stack.length-1];if(this.data.inReference=!0,le.type==="link"){let Te=j.children;le.children=Te}else le.alt=V}function w(){let j=this.resume(),V=this.stack[this.stack.length-1];V.url=j}function Ar(){let j=this.resume(),V=this.stack[this.stack.length-1];V.title=j}function Vn(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function Ut(j){let V=this.resume(),le=this.stack[this.stack.length-1];le.label=V,le.identifier=Ao(this.sliceSerialize(j)).toLowerCase(),this.data.referenceType="full"}function Zt(j){this.data.characterReferenceType=j.type}function Zr(j){let V=this.sliceSerialize(j),le=this.data.characterReferenceType,Te;le?(Te=S_(V,le==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Te=Ru(V);let et=this.stack.pop();et.value+=Te,et.position.end=Ns(j.end)}function qn(j){H.call(this,j);let V=this.stack[this.stack.length-1];V.url=this.sliceSerialize(j)}function Ct(j){H.call(this,j);let V=this.stack[this.stack.length-1];V.url="mailto:"+this.sliceSerialize(j)}function Li(){return{type:"blockquote",children:[]}}function Fr(){return{type:"code",lang:null,meta:null,value:""}}function Ui(){return{type:"inlineCode",value:""}}function zo(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function qu(){return{type:"emphasis",children:[]}}function vn(){return{type:"heading",depth:0,children:[]}}function $m(){return{type:"break"}}function Bu(){return{type:"html",value:""}}function Sm(){return{type:"image",title:null,url:"",alt:null}}function Wu(){return{type:"link",title:null,url:"",children:[]}}function Im(j){return{type:"list",ordered:j.type==="listOrdered",start:null,spread:j._spread,children:[]}}function No(j){return{type:"listItem",spread:j._spread,checked:null,children:[]}}function wn(){return{type:"paragraph",children:[]}}function Em(){return{type:"strong",children:[]}}function nb(){return{type:"text",value:""}}function ib(){return{type:"thematicBreak"}}}function Ns(t){return{line:t.line,column:t.column,offset:t.offset}}function rD(t,e){let r=-1;for(;++r<e.length;){let n=e[r];Array.isArray(n)?rD(t,n):z7(t,n)}}function z7(t,e){let r;for(r in e)if(tD.call(e,r))switch(r){case"canContainEols":{let n=e[r];n&&t[r].push(...n);break}case"transforms":{let n=e[r];n&&t[r].push(...n);break}case"enter":case"exit":{let n=e[r];n&&Object.assign(t[r],n);break}}}function eD(t,e){throw t?new Error("Cannot close `"+t.type+"` ("+zs({start:t.start,end:t.end})+"): a different token (`"+e.type+"`, "+zs({start:e.start,end:e.end})+") is open"):new Error("Cannot close document, a token (`"+e.type+"`, "+zs({start:e.start,end:e.end})+") is still open")}function hm(t){let e=this;e.parser=r;function r(n){return eE(n,{...e.data("settings"),...t,extensions:e.data("micromarkExtensions")||[],mdastExtensions:e.data("fromMarkdownExtensions")||[]})}}function nD(t,e){let r={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(e),!0)};return t.patch(e,r),t.applyData(e,r)}function iD(t,e){let r={type:"element",tagName:"br",properties:{},children:[]};return t.patch(e,r),[t.applyData(e,r),{type:"text",value:`
380
+ `}]}function oD(t,e){let r=e.value?e.value+`
381
+ `:"",n={};e.lang&&(n.className=["language-"+e.lang]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return e.meta&&(i.data={meta:e.meta}),t.patch(e,i),i=t.applyData(e,i),i={type:"element",tagName:"pre",properties:{},children:[i]},t.patch(e,i),i}function sD(t,e){let r={type:"element",tagName:"del",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function aD(t,e){let r={type:"element",tagName:"em",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function cD(t,e){let r=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=String(e.identifier).toUpperCase(),i=Zn(n.toLowerCase()),o=t.footnoteOrder.indexOf(n),s,a=t.footnoteCounts.get(n);a===void 0?(a=0,t.footnoteOrder.push(n),s=t.footnoteOrder.length):s=o+1,a+=1,t.footnoteCounts.set(n,a);let c={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+i,id:r+"fnref-"+i+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};t.patch(e,c);let l={type:"element",tagName:"sup",properties:{},children:[c]};return t.patch(e,l),t.applyData(e,l)}function lD(t,e){let r={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function uD(t,e){if(t.options.allowDangerousHtml){let r={type:"raw",value:e.value};return t.patch(e,r),t.applyData(e,r)}}function M_(t,e){let r=e.referenceType,n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+n}];let i=t.all(e),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});let s=i[i.length-1];return s&&s.type==="text"?s.value+=n:i.push({type:"text",value:n}),i}function dD(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return M_(t,e);let i={src:Zn(n.url||""),alt:e.alt};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"img",properties:i,children:[]};return t.patch(e,o),t.applyData(e,o)}function pD(t,e){let r={src:Zn(e.url)};e.alt!==null&&e.alt!==void 0&&(r.alt=e.alt),e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"img",properties:r,children:[]};return t.patch(e,n),t.applyData(e,n)}function fD(t,e){let r={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,r);let n={type:"element",tagName:"code",properties:{},children:[r]};return t.patch(e,n),t.applyData(e,n)}function mD(t,e){let r=String(e.identifier).toUpperCase(),n=t.definitionById.get(r);if(!n)return M_(t,e);let i={href:Zn(n.url||"")};n.title!==null&&n.title!==void 0&&(i.title=n.title);let o={type:"element",tagName:"a",properties:i,children:t.all(e)};return t.patch(e,o),t.applyData(e,o)}function hD(t,e){let r={href:Zn(e.url)};e.title!==null&&e.title!==void 0&&(r.title=e.title);let n={type:"element",tagName:"a",properties:r,children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function gD(t,e,r){let n=t.all(e),i=r?N7(r):yD(e),o={},s=[];if(typeof e.checked=="boolean"){let u=n[0],d;u&&u.type==="element"&&u.tagName==="p"?d=u:(d={type:"element",tagName:"p",properties:{},children:[]},n.unshift(d)),d.children.length>0&&d.children.unshift({type:"text",value:" "}),d.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let a=-1;for(;++a<n.length;){let u=n[a];(i||a!==0||u.type!=="element"||u.tagName!=="p")&&s.push({type:"text",value:`
382
+ `}),u.type==="element"&&u.tagName==="p"&&!i?s.push(...u.children):s.push(u)}let c=n[n.length-1];c&&(i||c.type!=="element"||c.tagName!=="p")&&s.push({type:"text",value:`
383
+ `});let l={type:"element",tagName:"li",properties:o,children:s};return t.patch(e,l),t.applyData(e,l)}function N7(t){let e=!1;if(t.type==="list"){e=t.spread||!1;let r=t.children,n=-1;for(;!e&&++n<r.length;)e=yD(r[n])}return e}function yD(t){let e=t.spread;return e??t.children.length>1}function _D(t,e){let r={},n=t.all(e),i=-1;for(typeof e.start=="number"&&e.start!==1&&(r.start=e.start);++i<n.length;){let s=n[i];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}let o={type:"element",tagName:e.ordered?"ol":"ul",properties:r,children:t.wrap(n,!0)};return t.patch(e,o),t.applyData(e,o)}function bD(t,e){let r={type:"element",tagName:"p",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function vD(t,e){let r={type:"root",children:t.wrap(t.all(e))};return t.patch(e,r),t.applyData(e,r)}function wD(t,e){let r={type:"element",tagName:"strong",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}var j_=xD("end"),D_=xD("start");function xD(t){return e;function e(r){let n=r&&r.position&&r.position[t]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function tE(t){let e=D_(t),r=j_(t);if(e&&r)return{start:e,end:r}}function kD(t,e){let r=t.all(e),n=r.shift(),i=[];if(n){let s={type:"element",tagName:"thead",properties:{},children:t.wrap([n],!0)};t.patch(e.children[0],s),i.push(s)}if(r.length>0){let s={type:"element",tagName:"tbody",properties:{},children:t.wrap(r,!0)},a=D_(e.children[1]),c=j_(e.children[e.children.length-1]);a&&c&&(s.position={start:a,end:c}),i.push(s)}let o={type:"element",tagName:"table",properties:{},children:t.wrap(i,!0)};return t.patch(e,o),t.applyData(e,o)}function $D(t,e,r){let n=r?r.children:void 0,o=(n?n.indexOf(e):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,a=s?s.length:e.children.length,c=-1,l=[];for(;++c<a;){let d=e.children[c],f={},p=s?s[c]:void 0;p&&(f.align=p);let h={type:"element",tagName:o,properties:f,children:[]};d&&(h.children=t.all(d),t.patch(d,h),h=t.applyData(d,h)),l.push(h)}let u={type:"element",tagName:"tr",properties:{},children:t.wrap(l,!0)};return t.patch(e,u),t.applyData(e,u)}function SD(t,e){let r={type:"element",tagName:"td",properties:{},children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function ED(t){let e=String(t),r=/\r?\n|\r/g,n=r.exec(e),i=0,o=[];for(;n;)o.push(ID(e.slice(i,n.index),i>0,!0),n[0]),i=n.index+n[0].length,n=r.exec(e);return o.push(ID(e.slice(i),i>0,!1)),o.join("")}function ID(t,e,r){let n=0,i=t.length;if(e){let o=t.codePointAt(n);for(;o===9||o===32;)n++,o=t.codePointAt(n)}if(r){let o=t.codePointAt(i-1);for(;o===9||o===32;)i--,o=t.codePointAt(i-1)}return i>n?t.slice(n,i):""}function PD(t,e){let r={type:"text",value:ED(String(e.value))};return t.patch(e,r),t.applyData(e,r)}function TD(t,e){let r={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,r),t.applyData(e,r)}var AD={blockquote:nD,break:iD,code:oD,delete:sD,emphasis:aD,footnoteReference:cD,heading:lD,html:uD,imageReference:dD,image:pD,inlineCode:fD,linkReference:mD,link:hD,listItem:gD,list:_D,paragraph:bD,root:vD,strong:wD,table:kD,tableCell:SD,tableRow:$D,text:PD,thematicBreak:TD,toml:L_,yaml:L_,definition:L_,footnoteDefinition:L_};function L_(){}function C7(t,e){let r=[{type:"text",value:"\u21A9"}];return e>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),r}function O7(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function zD(t){let e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",r=t.options.footnoteBackContent||C7,n=t.options.footnoteBackLabel||O7,i=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",s=t.options.footnoteLabelProperties||{className:["sr-only"]},a=[],c=-1;for(;++c<t.footnoteOrder.length;){let l=t.footnoteById.get(t.footnoteOrder[c]);if(!l)continue;let u=t.all(l),d=String(l.identifier).toUpperCase(),f=Zn(d.toLowerCase()),p=0,h=[],m=t.footnoteCounts.get(d);for(;m!==void 0&&++p<=m;){h.length>0&&h.push({type:"text",value:" "});let b=typeof r=="string"?r:r(c,p);typeof b=="string"&&(b={type:"text",value:b}),h.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(c,p),className:["data-footnote-backref"]},children:Array.isArray(b)?b:[b]})}let g=u[u.length-1];if(g&&g.type==="element"&&g.tagName==="p"){let b=g.children[g.children.length-1];b&&b.type==="text"?b.value+=" ":g.children.push({type:"text",value:" "}),g.children.push(...h)}else u.push(...h);let y={type:"element",tagName:"li",properties:{id:e+"fn-"+f},children:t.wrap(u,!0)};t.patch(l,y),a.push(y)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Mi(s),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:`
384
+ `},{type:"element",tagName:"ol",properties:{},children:t.wrap(a,!0)},{type:"text",value:`
385
+ `}]}}var rE={}.hasOwnProperty,R7={};function CD(t,e){let r=e||R7,n=new Map,i=new Map,o=new Map,s={...AD,...r.handlers},a={all:l,applyData:j7,definitionById:n,footnoteById:i,footnoteCounts:o,footnoteOrder:[],handlers:s,one:c,options:r,patch:M7,wrap:L7};return tm(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){let d=u.type==="definition"?n:i,f=String(u.identifier).toUpperCase();d.has(f)||d.set(f,u)}}),a;function c(u,d){let f=u.type,p=a.handlers[f];if(rE.call(a.handlers,f)&&p)return p(a,u,d);if(a.options.passThrough&&a.options.passThrough.includes(f)){if("children"in u){let{children:m,...g}=u,y=Mi(g);return y.children=a.all(u),y}return Mi(u)}return(a.options.unknownHandler||D7)(a,u,d)}function l(u){let d=[];if("children"in u){let f=u.children,p=-1;for(;++p<f.length;){let h=a.one(f[p],u);if(h){if(p&&f[p-1].type==="break"&&(!Array.isArray(h)&&h.type==="text"&&(h.value=ND(h.value)),!Array.isArray(h)&&h.type==="element")){let m=h.children[0];m&&m.type==="text"&&(m.value=ND(m.value))}Array.isArray(h)?d.push(...h):d.push(h)}}}return d}}function M7(t,e){t.position&&(e.position=tE(t))}function j7(t,e){let r=e;if(t&&t.data){let n=t.data.hName,i=t.data.hChildren,o=t.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{let s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&o&&Object.assign(r.properties,Mi(o)),"children"in r&&r.children&&i!==null&&i!==void 0&&(r.children=i)}return r}function D7(t,e){let r=e.data||{},n="value"in e&&!(rE.call(r,"hProperties")||rE.call(r,"hChildren"))?{type:"text",value:e.value}:{type:"element",tagName:"div",properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function L7(t,e){let r=[],n=-1;for(e&&r.push({type:"text",value:`
386
+ `});++n<t.length;)n&&r.push({type:"text",value:`
387
+ `}),r.push(t[n]);return e&&t.length>0&&r.push({type:"text",value:`
388
+ `}),r}function ND(t){let e=0,r=t.charCodeAt(e);for(;r===9||r===32;)e++,r=t.charCodeAt(e);return t.slice(e)}function U_(t,e){let r=CD(t,e),n=r.one(t,void 0),i=zD(r),o=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return i&&("children"in o,o.children.push({type:"text",value:`
389
+ `},i)),o}function gm(t,e){return t&&"run"in t?async function(r,n){let i=U_(r,{file:n,...e});await t.run(i,n)}:function(r,n){return U_(r,{file:n,...t||e})}}function nE(t){if(t)throw t}var V_=cb(FD(),1);function ym(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function iE(){let t=[],e={run:r,use:n};return e;function r(...i){let o=-1,s=i.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);a(null,...i);function a(c,...l){let u=t[++o],d=-1;if(c){s(c);return}for(;++d<i.length;)(l[d]===null||l[d]===void 0)&&(l[d]=i[d]);i=l,u?VD(u,a)(...l):s(null,...l)}}function n(i){if(typeof i!="function")throw new TypeError("Expected `middelware` to be a function, not "+i);return t.push(i),e}}function VD(t,e){let r;return n;function n(...s){let a=t.length>s.length,c;a&&s.push(i);try{c=t.apply(this,s)}catch(l){let u=l;if(a&&r)throw u;return i(u)}a||(c&&c.then&&typeof c.then=="function"?c.then(o,i):c instanceof Error?i(c):o(c))}function i(s,...a){r||(r=!0,e(s,...a))}function o(s){i(null,s)}}var rr=class extends Error{constructor(e,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let i="",o={},s=!1;if(r&&("line"in r&&"column"in r?o={place:r}:"start"in r&&"end"in r?o={place:r}:"type"in r?o={ancestors:[r],place:r.position}:o={...r}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof n=="string"){let c=n.indexOf(":");c===-1?o.ruleId=n:(o.source=n.slice(0,c),o.ruleId=n.slice(c+1))}if(!o.place&&o.ancestors&&o.ancestors){let c=o.ancestors[o.ancestors.length-1];c&&(o.place=c.position)}let a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file,this.message=i,this.line=a?a.line:void 0,this.name=zs(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual,this.expected,this.note,this.url}};rr.prototype.file="";rr.prototype.name="";rr.prototype.reason="";rr.prototype.message="";rr.prototype.stack="";rr.prototype.column=void 0;rr.prototype.line=void 0;rr.prototype.ancestors=void 0;rr.prototype.cause=void 0;rr.prototype.fatal=void 0;rr.prototype.place=void 0;rr.prototype.ruleId=void 0;rr.prototype.source=void 0;var pi={basename:U7,dirname:Z7,extname:F7,join:V7,sep:"/"};function U7(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');_m(t);let r=0,n=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else n<0&&(o=!0,n=i+1);return n<0?"":t.slice(r,n)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){r=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(n=i):(a=-1,n=s));return r===n?n=s:n<0&&(n=t.length),t.slice(r,n)}function Z7(t){if(_m(t),t.length===0)return".";let e=-1,r=t.length,n;for(;--r;)if(t.codePointAt(r)===47){if(n){e=r;break}}else n||(n=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function F7(t){_m(t);let e=t.length,r=-1,n=0,i=-1,o=0,s;for(;e--;){let a=t.codePointAt(e);if(a===47){if(s){n=e+1;break}continue}r<0&&(s=!0,r=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||r<0||o===0||o===1&&i===r-1&&i===n+1?"":t.slice(i,r)}function V7(...t){let e=-1,r;for(;++e<t.length;)_m(t[e]),t[e]&&(r=r===void 0?t[e]:r+"/"+t[e]);return r===void 0?".":q7(r)}function q7(t){_m(t);let e=t.codePointAt(0)===47,r=B7(t,!e);return r.length===0&&!e&&(r="."),r.length>0&&t.codePointAt(t.length-1)===47&&(r+="/"),e?"/"+r:r}function B7(t,e){let r="",n=0,i=-1,o=0,s=-1,a,c;for(;++s<=t.length;){if(s<t.length)a=t.codePointAt(s);else{if(a===47)break;a=47}if(a===47){if(!(i===s-1||o===1))if(i!==s-1&&o===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(c=r.lastIndexOf("/"),c!==r.length-1){c<0?(r="",n=0):(r=r.slice(0,c),n=r.length-1-r.lastIndexOf("/")),i=s,o=0;continue}}else if(r.length>0){r="",n=0,i=s,o=0;continue}}e&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+t.slice(i+1,s):r=t.slice(i+1,s),n=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return r}function _m(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}var qD={cwd:W7};function W7(){return"/"}function ju(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function BD(t){if(typeof t=="string")t=new URL(t);else if(!ju(t)){let e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){let e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return G7(t)}function G7(t){if(t.hostname!==""){let n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}let e=t.pathname,r=-1;for(;++r<e.length;)if(e.codePointAt(r)===37&&e.codePointAt(r+1)===50){let n=e.codePointAt(r+2);if(n===70||n===102){let i=new TypeError("File URL path must not include encoded / characters");throw i.code="ERR_INVALID_FILE_URL_PATH",i}}return decodeURIComponent(e)}var oE=["history","path","basename","stem","extname","dirname"],bm=class{constructor(e){let r;e?ju(e)?r={path:e}:typeof e=="string"||H7(e)?r={value:e}:r=e:r={},this.cwd=qD.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<oE.length;){let o=oE[n];o in r&&r[o]!==void 0&&r[o]!==null&&(this[o]=o==="history"?[...r[o]]:r[o])}let i;for(i in r)oE.includes(i)||(this[i]=r[i])}get basename(){return typeof this.path=="string"?pi.basename(this.path):void 0}set basename(e){aE(e,"basename"),sE(e,"basename"),this.path=pi.join(this.dirname||"",e)}get dirname(){return typeof this.path=="string"?pi.dirname(this.path):void 0}set dirname(e){WD(this.basename,"dirname"),this.path=pi.join(e||"",this.basename)}get extname(){return typeof this.path=="string"?pi.extname(this.path):void 0}set extname(e){if(sE(e,"extname"),WD(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=pi.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){ju(e)&&(e=BD(e)),aE(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path=="string"?pi.basename(this.path,this.extname):void 0}set stem(e){aE(e,"stem"),sE(e,"stem"),this.path=pi.join(this.dirname||"",e+(this.extname||""))}fail(e,r,n){let i=this.message(e,r,n);throw i.fatal=!0,i}info(e,r,n){let i=this.message(e,r,n);return i.fatal=void 0,i}message(e,r,n){let i=new rr(e,r,n);return this.path&&(i.name=this.path+":"+i.name,i.file=this.path),i.fatal=!1,this.messages.push(i),i}toString(e){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(e||void 0).decode(this.value)}};function sE(t,e){if(t&&t.includes(pi.sep))throw new Error("`"+e+"` cannot be a path: did not expect `"+pi.sep+"`")}function aE(t,e){if(!t)throw new Error("`"+e+"` cannot be empty")}function WD(t,e){if(!t)throw new Error("Setting `"+e+"` requires `path` to be set too")}function H7(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var GD=(function(t){let n=this.constructor.prototype,i=n[t],o=function(){return i.apply(o,arguments)};return Object.setPrototypeOf(o,n),o});var X7={}.hasOwnProperty,dE=class t extends GD{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=iE()}copy(){let e=new t,r=-1;for(;++r<this.attachers.length;){let n=this.attachers[r];e.use(...n)}return e.data((0,V_.default)(!0,{},this.namespace)),e}data(e,r){return typeof e=="string"?arguments.length===2?(uE("data",this.frozen),this.namespace[e]=r,this):X7.call(this.namespace,e)&&this.namespace[e]||void 0:e?(uE("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;let e=this;for(;++this.freezeIndex<this.attachers.length;){let[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);let i=r.call(e,...n);typeof i=="function"&&this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();let r=F_(e),n=this.parser||this.Parser;return cE("parse",n),n(String(r),r)}process(e,r){let n=this;return this.freeze(),cE("process",this.parser||this.Parser),lE("process",this.compiler||this.Compiler),r?i(void 0,r):new Promise(i);function i(o,s){let a=F_(e),c=n.parse(a);n.run(c,a,function(u,d,f){if(u||!d||!f)return l(u);let p=d,h=n.stringify(p,f);J7(h)?f.value=h:f.result=h,l(u,f)});function l(u,d){u||!d?s(u):o?o(d):r(void 0,d)}}}processSync(e){let r=!1,n;return this.freeze(),cE("processSync",this.parser||this.Parser),lE("processSync",this.compiler||this.Compiler),this.process(e,i),XD("processSync","process",r),n;function i(o,s){r=!0,nE(o),n=s}}run(e,r,n){HD(e),this.freeze();let i=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?o(void 0,n):new Promise(o);function o(s,a){let c=F_(r);i.run(e,c,l);function l(u,d,f){let p=d||e;u?a(u):s?s(p):n(void 0,p,f)}}}runSync(e,r){let n=!1,i;return this.run(e,r,o),XD("runSync","run",n),i;function o(s,a){nE(s),i=a,n=!0}}stringify(e,r){this.freeze();let n=F_(r),i=this.compiler||this.Compiler;return lE("stringify",i),HD(e),i(e,n)}use(e,...r){let n=this.attachers,i=this.namespace;if(uE("use",this.frozen),e!=null)if(typeof e=="function")c(e,r);else if(typeof e=="object")Array.isArray(e)?a(e):s(e);else throw new TypeError("Expected usable value, not `"+e+"`");return this;function o(l){if(typeof l=="function")c(l,[]);else if(typeof l=="object")if(Array.isArray(l)){let[u,...d]=l;c(u,d)}else s(l);else throw new TypeError("Expected usable value, not `"+l+"`")}function s(l){if(!("plugins"in l)&&!("settings"in l))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(l.plugins),l.settings&&(i.settings=(0,V_.default)(!0,i.settings,l.settings))}function a(l){let u=-1;if(l!=null)if(Array.isArray(l))for(;++u<l.length;){let d=l[u];o(d)}else throw new TypeError("Expected a list of plugins, not `"+l+"`")}function c(l,u){let d=-1,f=-1;for(;++d<n.length;)if(n[d][0]===l){f=d;break}if(f===-1)n.push([l,...u]);else if(u.length>0){let[p,...h]=u,m=n[f][1];ym(m)&&ym(p)&&(p=(0,V_.default)(!0,m,p)),n[f]=[l,p,...h]}}}},q_=new dE().freeze();function cE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function lE(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function uE(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function HD(t){if(!ym(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function XD(t,e,r){if(!r)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function F_(t){return K7(t)?t:new bm(t)}function K7(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function J7(t){return typeof t=="string"||Y7(t)}function Y7(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}var vm=class extends yn{constructor(){super(...arguments);this.html=()=>`
200
390
 
201
391
  <!-- Styling -->
202
392
  <style>
@@ -279,15 +469,24 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
279
469
  <div id='llm-selector-list'></div>
280
470
  </div>
281
471
 
282
- `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let e=this.child("llm-selector-list");for(;e.lastChild;)e.lastChild.remove();for(let t of this.state.items||[]){let s=document.createElement("div");s.className="llm-selector-item"+(t.id==this.state.selectedID?" selected":""),s.innerHTML=`
283
- <div class='llm-selector-item-icon' style="background-image: url('${t.icon}'); "></div>
284
- <div class='llm-selector-item-name'>${t.name}</div>
285
- <div class='llm-selector-item-provider'>${t.provider}</div>
286
- `,s.addEventListener("click",n=>{this.dispatchEvent(new CustomEvent("select",{detail:t.id}))}),e.appendChild(s)}}};K.observedAttributes=["open"];var E=new h("ONNXModel"),w=class l{constructor(i){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=i,E.debug(`Model input parameters: ${i.inputNames.join(", ")}`),E.debug(`Model output parameters: ${i.outputNames.join(", ")}`)}static isSupported(){return!!l.lib}static async load(i){if(!l.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(E.debug("Loading ONNX runtime"),this.onnx=await l.lib()),E.debug(`Loading model: ${i}`);let e=await this.onnx.InferenceSession.create(i);return new l(e)}makeTensor(i,e,t=0){let s=1;for(let o of e)s*=o;let n;if(i=="float32")n=new l.onnx.Tensor(new Float32Array(s),e);else if(i=="int8")n=new l.onnx.Tensor(new Int8Array(s),e);else if(i=="int16")n=new l.onnx.Tensor(new Int16Array(s),e);else if(i=="int32")n=new l.onnx.Tensor(new Int32Array(s),e);else if(i=="int64")n=new l.onnx.Tensor(new BigInt64Array(s),e);else if(i=="uint8")n=new l.onnx.Tensor(new Uint8Array(s),e);else if(i=="uint16")n=new l.onnx.Tensor(new Uint16Array(s),e);else if(i=="uint32")n=new l.onnx.Tensor(new Uint32Array(s),e);else if(i=="uint64")n=new l.onnx.Tensor(new BigUint64Array(s),e);else throw new Error(`Invalid type: ${i}`);return t!==0&&(i=="int64"||i=="uint64")?n.data.fill(BigInt(t)):t!==0&&n.data.fill(t),n}registerConstant(i,e){if(!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);return this.constantTensors[i]=e,e}makeConstant(i,e,t,s=0){return this.registerConstant(i,this.makeTensor(e,t,s))}registerState(i,e,t){if(e||(e=i),!this.session.inputNames.includes(i))throw new Error(`Model does not have an input named: ${i}`);if(!this.session.outputNames.includes(e))throw new Error(`Model does not have an output named: ${e}`);return this.stateTensors[i]={outputName:e,tensor:t},t}makeState(i,e,t,s,n=0){return this.registerState(i,e,this.makeTensor(t,s,n))}async run(i={}){if(this._runActive&&this.ignoreIfBusy)return E.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let e in this.stateTensors)i[e]=this.stateTensors[e].tensor;for(let e in this.constantTensors)i[e]=this.constantTensors[e];try{let e=await this.session.run(i);for(let t in this.stateTensors){let s=e[this.stateTensors[t].outputName];this.stateTensors[t].tensor=s}return e}finally{this._runActive=!1}}resetState(){E.debug("Resetting state tensors");for(let i in this.stateTensors)this.stateTensors[i].tensor.data.fill(0)}};var Pe="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var nt=new h("PCMPlayerNode"),R=class extends AudioWorkletNode{constructor(e,t,s){super(e,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!s||s!="int16"&&s!="float32")throw new Error(`Invalid format: ${s}`);this.sampleRate=t,this.format=s,this.port.onmessage=n=>this.onWorkletMessage(n),this.port.postMessage({action:"start",inputSampleRate:t,outputSampleRate:e.sampleRate,format:s})}static async registerModule(e){await e.audioWorklet.addModule(Pe)}feed(e){this.port.postMessage({action:"data",buffer:e.buffer},[e.buffer])}async play(e){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(t=>this._playPromiseResolve=t),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:e}}));try{let t=e.getReader();for(;!this.isCancelled;){let{done:s,value:n}=await t.read();if(s||!n)break;this.feed(n)}}catch(t){nt.warn("Stream error:",t),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:e,error:t}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(e){e.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var te=new h("SpeechOutput"),Ae=.5,ot=.8,ie=class extends EventTarget{constructor(e){super();this.maxVolumeHeard=0;this.ai=e,this.ai.addEventListener("output",t=>this.onTextOutputFromAI(t)),this.ai.audio?.speechRecognition.addEventListener("speechstart",t=>this.interrupt()),this.ai.knowledgeBase.registerSource(()=>[{id:"system.voice",type:"info",name:"Voice active",isContext:!0,disabled:!1,content:"Text-to-speech is active. The user can hear your voice."}])}onTextOutputFromAI(e){e.detail.isChunk||this.ai?.audio?.speechRecognition.isRunning&&this.speak(e.detail.message)}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}async speak(e){if(!this.ai?.config?.voice?.providerID)return te.warn("No voice provider configured");let t=`speech-${at++}`;await this.ai.audio.beginAccess(t);try{await this._speakWithLock(e)}finally{this.ai.audio.endAccess(t)}}async _speakWithLock(e){let t=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:e}});if(this.dispatchEvent(t),e=t.detail.message,t.defaultPrevented||!e)return;this.interrupt(),this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=ot);let s=this.ai?._voiceTracker||te.timer(`${this.ai.config.voice.providerID} voice`);s(`Speak: ${e}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let n=new R(this.ai.audio.context,24e3,"int16");this.currentPlayer=n,n.connect(this.analyserNode),n.addEventListener("end",a=>{let d=a;s(`PCM stream ${d.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==n&&!d.detail.interrupted&&(this.currentPlayer=void 0,this.onSpeechEnd())});let o;if(this.ai.config.voice.providerID=="openai")o=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:e,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});else if(this.ai.config.voice.providerID=="elevenlabs")o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${this.ai.config.voice.voiceID}?output_format=pcm_24000`,{method:"POST",headers:{"xi-api-key":`${this.ai.config.voice.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({text:e})});else{te.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}if(s(`Received response ${o.status} ${o.statusText}`),!o.ok){te.warn(`Failed to generate voice sample: ${o.status} ${o.statusText}`);return}this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:e}})),s("Playing PCM stream"),await n.play(o.body),s("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(!this.currentPlayerVolume)return;let e=this.currentPlayerVolume,t=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Ae);let s=400;e.gain.linearRampToValueAtTime(0,s/1e3),await new Promise(n=>setTimeout(n,s+250)),e.disconnect(),t?.stop(),t?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=Ae)}},at=1;function se(l,i){let e=i.reduce((d,c)=>d+c.byteLength,0),t=new DataView(new ArrayBuffer(44));t.setUint8(0,82),t.setUint8(1,73),t.setUint8(2,70),t.setUint8(3,70),t.setUint32(4,44+e,!0),t.setUint8(8,87),t.setUint8(9,65),t.setUint8(10,86),t.setUint8(11,69);let s=1,n=32,o=s*n/8,a=l*o;return t.setUint8(12,102),t.setUint8(13,109),t.setUint8(14,116),t.setUint8(15,32),t.setUint32(16,16,!0),t.setUint16(20,3,!0),t.setUint16(22,s,!0),t.setUint32(24,l,!0),t.setUint32(28,a,!0),t.setUint16(32,o,!0),t.setUint16(34,n,!0),t.setUint8(36,100),t.setUint8(37,97),t.setUint8(38,116),t.setUint8(39,97),t.setUint32(40,e,!0),new File([t,...i],"audio.wav",{type:"audio/wav"})}var Ne="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var V=class extends AudioWorkletNode{constructor(e,t,s,n){super(e,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=s;let o=["int16","int64","float32"];if(!t||t<=0)throw new Error(`Invalid sample rate: ${t}`);if(!o.includes(s))throw new Error(`Invalid format ${s}, must be one of: ${o.join(", ")}`);if(!n||n<=0)throw new Error(`Invalid buffer size: ${n}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:e.sampleRate,outputSampleRate:t,format:s,bufferSize:n})}static async registerModule(e){await e.audioWorklet.addModule(Ne)}onWorkletMessage(e){if(e.data.action=="data"){let t=null;if(this.format=="int16"&&(t=new Int16Array(e.data.buffer)),this.format=="int64"&&(t=new BigInt64Array(e.data.buffer)),this.format=="float32"&&(t=new Float32Array(e.data.buffer)),!t)throw new Error(`Invalid format: ${this.format}`);this.onData(t),this.dispatchEvent(new CustomEvent("data",{detail:{data:t}}))}}onData(e){}};var xe=16e3,ne=256,L=8,F=new h("VoiceDetectionNode"),Y=class Y extends V{constructor(e){super(e,xe,"float32",ne*L);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!Y.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return xe}get numberOfSamples(){return ne}get numberOfSampleChunks(){return L}get outputBufferSize(){return ne*L}get isModelLoaded(){return!!this.vad}async loadModel(){F.debug("Loading VAD model"),this.vad=await w.load(Y.vadModelURL),this.vad.ignoreIfBusy=!0,F.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],xe),this.vad.makeState("h","hn","float32",[2,L,64]),this.vad.makeState("c","cn","float32",[2,L,64])}async onData(e){if(this.vad)try{let t=await this.vad.run({input:new w.onnx.Tensor(e,[L,ne])});if(!t)return;this.currentProbability=0;for(let o=0;o<t.output.data.length;o++)t.output.data[o]>this.currentProbability&&(this.currentProbability=t.output.data[o]);let s=this.isVoiceActive?this.sentivityEnd:this.sensitivity,n=this.currentProbability>s;if(!n&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=n,n&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),F.debug("Started speaking")):n?this.lastVoiceActiveDate=Date.now():!n&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!n&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),F.debug("Stopped speaking after timeout")),!n){let o=Date.now();o>this.nextVadReset&&(this.nextVadReset=o+5e3,this.vad.resetState())}}catch(t){F.error("VAD failed:",t)}}onSpeechStart(){}onSpeechEnd(){}};Y.vadModelURL="";var B=Y;var _e=new h("VoiceChunkOutputNode"),P=class extends B{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((e,t)=>e+t.length,0)/8e3}async onData(e){if(await super.onData(e),this.isVoiceActive&&!this._voiceRecording){_e.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let t of this.buffers)this.recordedBuffers.push(t),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:t,isFinal:!1}})),this.onVoiceChunk(t);this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!1}})),this.onVoiceChunk(e);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(e),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:e,isFinal:!0}})),this.onVoiceChunk(e),this._voiceRecording=!1;let t=this.recordedBuffers.reduce((s,n)=>s+n.length,0);_e.debug(`Voice complete, recorded ${(t/8e3).toFixed(2)} seconds of audio, ${t*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(e);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(e){}onVoiceEnd(e){}};var oe=new h("OpenAITranscriptionNode"),ae=class extends P{constructor(e,t){super(e);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=t}async onVoiceEnd(e){let t=oe.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...e);let s=se(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let n="";try{let o=new FormData;o.append("file",s),o.append("model","whisper-1"),o.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);t("Response received"),n=await a.text(),t("Content received: "+n),this.lastRequestAbortController=void 0}catch(o){oe.error(`Failed to transcribe speech: ${o.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!n)return oe.debug("Transcription complete, but no text was found");oe.debug(`Transcription: ${n}`),this.onVoiceTranscription(n),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n}}))}onVoiceTranscription(e){}};var re=class extends WebSocket{constructor(e){super(e);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(e){this.readyState==WebSocket.OPEN?super.send(e):this.pendingData.push(e)}_onOpen(){for(let e of this.pendingData)super.send(e);this.pendingData=[]}};var x=new h("IntelliWeaveTranscriptionNode"),lt="wss://speech.intelliweave.ai/api/v1/transcribe",ce=class ce extends P{constructor(e,t){super(e);this.apiAddress=lt;this.apiKey="";this.isTranscribing=!1;this.apiKey=t}async onVoiceChunk(e){this.isTranscribing=!0,this.ws?this.ws.send(e):(x.debug("Opening WebSocket connection"),this.ws=new re(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(e.buffer),this.ws.onopen=()=>{x.debug("WebSocket connection opened")},this.ws.addEventListener("message",s=>{let n=JSON.parse(s.data);if(n.error)return x.warn("Error: "+n.error);if(n.type!="transcription")return x.warn("Invalid response type",n);if(n.streaming&&!n.final)return x.debug("Partial transcription: "+n.partialText);if(this.isTranscribing=!1,!n.text.trim())return x.warn(`Empty transcription (${n.processingTime}ms)`);x.debug(`Transcription: ${n.text} (${n.processingTime}ms)`),this.onVoiceTranscription(n.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:n.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",s=>x.warn("WebSocket error")));let t=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{x.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},t)}async onVoiceEnd(e){if(this.ws?.send(JSON.stringify({type:"end"})),ce.debugExportWav){let t=se(this.sampleRate,e),s=document.createElement("a");s.href=URL.createObjectURL(t),s.download="recording.wav",s.click()}}onVoiceTranscription(e){}onSocketClose(){x.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};ce.debugExportWav=!1;var le=ce;var Se=new h("SpeechRecognition"),de=class extends EventTarget{constructor(e){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=e,this.ai.knowledgeBase.registerSource(()=>[{id:"system.microphone.enable",type:"action",name:"Enable or disable microphone",isContext:!0,content:`Starts or stops listening to input from the user through the microphone. ${this.isRunning?"Microphone access is currently enabled and you can hear the user.":"Microphone access is currently disabled."}.`,parameters:[{name:"enable",type:"boolean",description:"If true, enables the microphone. If false, disables it."}],action:async t=>{t.enable?await this.start():this.stop()}}])}get isSupported(){if(!w.lib||!this.ai?.vadModel||!C().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey))return!1}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let e=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,e.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),B.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new ae(this.ai.audio.context,this.ai.config.transcription.apiKey),e.connect(this.voiceDetection)):(this.voiceDetection=new le(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,e.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",t=>{this.ai._voiceTracker=Se.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),f(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("speechend",t=>{this.ai._voiceTracker?.("Speech ended");let s=this.recordingStartTime?Date.now()-this.recordingStartTime:0;f(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:s}}),this.dispatchEvent(new CustomEvent(t.type,{detail:t.detail}))}),this.voiceDetection.addEventListener("transcription",t=>{this.ai._voiceTracker?.(`Transcription: ${t.detail.text}`),f(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:t.detail.confidence||void 0}}),this.onTranscription(t)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(e){Se.error("Failed to start speech recognition:",e),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(e=>e.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let e=0;for(let s of this.analyserBuffer)e+=s*s;let t=Math.sqrt(e/this.analyserBuffer.length);return t>this.maxVolumeHeard&&(this.maxVolumeHeard=t),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,t/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(e){let t=e.detail.text;Se.debug("Heard:",t),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:t,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(e){throw this._skipEvents=!1,e}}}};var he=new h("AudioSystem"),A=class l{constructor(i){this.locks=[];if(!i)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=i,this.ai.audio=this,this.speechRecognition=new de(this.ai),this.speechOutput=new ie(this.ai)}static get isSupported(){return!(!w.lib||!C().AudioWorkletNode)}static async registerModules(i){await Promise.all([R.registerModule(i),V.registerModule(i)])}async beginAccess(i){he.debug(`Began access for: ${i}`),this.locks.includes(i)||this.locks.push(i),!this.context&&(he.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await l.registerModules(this.context))}endAccess(i){he.debug(`Ended access for: ${i}`),this.locks=this.locks.filter(e=>e!=i),!this.locks.length&&(he.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var Xs=new h("Stream");import Rs,{createContext as ct,useContext as Vs,useEffect as Ls,useMemo as Bs,useState as Ps}from"react";var Fs=new h("React");var Ys=ct(void 0);var b=new h("Embed"),M=class extends y{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
472
+ `}onUpdate(){this.child("llm-selector-panel").className=this.attr.open?"open":"closed";let r=this.child("llm-selector-list");for(;r.lastChild;)r.lastChild.remove();for(let n of this.state.items||[]){let i=document.createElement("div");i.className="llm-selector-item"+(n.id==this.state.selectedID?" selected":""),i.innerHTML=`
473
+ <div class='llm-selector-item-icon' style="background-image: url('${n.icon}'); "></div>
474
+ <div class='llm-selector-item-name'>${n.name}</div>
475
+ <div class='llm-selector-item-provider'>${n.provider}</div>
476
+ `,i.addEventListener("click",o=>{this.dispatchEvent(new CustomEvent("select",{detail:n.id}))}),r.appendChild(i)}}};vm.observedAttributes=["open"];var Du=new Ce("ONNXModel"),fi=class t{constructor(e){this.stateTensors={};this.constantTensors={};this._runActive=!1;this.ignoreIfBusy=!1;this.session=e,Du.debug(`Model input parameters: ${e.inputNames.join(", ")}`),Du.debug(`Model output parameters: ${e.outputNames.join(", ")}`)}static isSupported(){return!!t.lib}static async load(e){if(!t.lib)throw new Error("ONNX runtime not loaded, please set the runtime loader. Example: ONNXModel.lib = () => import('onnxruntime-web')");this.onnx||(Du.debug("Loading ONNX runtime"),this.onnx=await t.lib()),Du.debug(`Loading model: ${e}`);let r=await this.onnx.InferenceSession.create(e);return new t(r)}makeTensor(e,r,n=0){let i=1;for(let s of r)i*=s;let o;if(e=="float32")o=new t.onnx.Tensor(new Float32Array(i),r);else if(e=="int8")o=new t.onnx.Tensor(new Int8Array(i),r);else if(e=="int16")o=new t.onnx.Tensor(new Int16Array(i),r);else if(e=="int32")o=new t.onnx.Tensor(new Int32Array(i),r);else if(e=="int64")o=new t.onnx.Tensor(new BigInt64Array(i),r);else if(e=="uint8")o=new t.onnx.Tensor(new Uint8Array(i),r);else if(e=="uint16")o=new t.onnx.Tensor(new Uint16Array(i),r);else if(e=="uint32")o=new t.onnx.Tensor(new Uint32Array(i),r);else if(e=="uint64")o=new t.onnx.Tensor(new BigUint64Array(i),r);else throw new Error(`Invalid type: ${e}`);return n!==0&&(e=="int64"||e=="uint64")?o.data.fill(BigInt(n)):n!==0&&o.data.fill(n),o}registerConstant(e,r){if(!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);return this.constantTensors[e]=r,r}makeConstant(e,r,n,i=0){return this.registerConstant(e,this.makeTensor(r,n,i))}registerState(e,r,n){if(r||(r=e),!this.session.inputNames.includes(e))throw new Error(`Model does not have an input named: ${e}`);if(!this.session.outputNames.includes(r))throw new Error(`Model does not have an output named: ${r}`);return this.stateTensors[e]={outputName:r,tensor:n},n}makeState(e,r,n,i,o=0){return this.registerState(e,r,this.makeTensor(n,i,o))}async run(e={}){if(this._runActive&&this.ignoreIfBusy)return Du.debug("Ignoring run request because a previous run is still active");if(this._runActive)throw new Error("A previous run is still active");this._runActive=!0;for(let r in this.stateTensors)e[r]=this.stateTensors[r].tensor;for(let r in this.constantTensors)e[r]=this.constantTensors[r];try{let r=await this.session.run(e);for(let n in this.stateTensors){let i=r[this.stateTensors[n].outputName];this.stateTensors[n].tensor=i}return r}finally{this._runActive=!1}}resetState(){Du.debug("Resetting state tensors");for(let e in this.stateTensors)this.stateTensors[e].tensor.data.fill(0)}};var KD="data:application/javascript;base64,dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoaSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFpKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtpfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9aSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoaSx0KT0+aSt0Lmxlbmd0aCwwKX1mZWVkKGkpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChpKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQscik9PnQrci5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgaT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgaSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLHI9MDtmb3IoO3IhPXQubGVuZ3RoOyl7aWYocj50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtyfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGE9dC5sZW5ndGgtcixzPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sZj1zLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7ZjxhPyh0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCkscikscis9Zix0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChzLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrYSkscikscis9YSx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWEpfXJldHVybiB0fXBhZCgpe2xldCBpPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoaT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLHI9bmV3IHQoaSk7dGhpcy5mZWVkKHIpfX07dmFyIGQ9Y2xhc3N7Y29uc3RydWN0b3IoaSx0LHIsYSl7aWYoIWl8fCF0fHwhcil0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1pLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1yfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWEsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1pPT5pLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoaSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGkpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWksdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsaSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9aT0+e2xldCB0PWkubGVuZ3RoLHI9dGhpcy5jaGFubmVscyxhLHMsZixoLGUsbix1LG8sbDtpZih0JXIhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihhPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxzPXRoaXMucmF0aW9XZWlnaHQsZj10aGlzLmxhc3RXZWlnaHQsaD0wLGU9MCxuPTAsdT0wLG89dGhpcy5vdXRwdXRCdWZmZXI7ZjwxO2YrPXMpZm9yKGU9ZiUxLGg9MS1lLHRoaXMubGFzdFdlaWdodD1mJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpb1t1KytdPXRoaXMubGFzdE91dHB1dFtsXSpoK2lbbF0qZTtmb3IoZi09MSx0LT1yLG49TWF0aC5mbG9vcihmKSpyO3U8YSYmbjx0Oyl7Zm9yKGU9ZiUxLGg9MS1lLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKW9bdSsrXT1pW24rKGw+MD9sOjApXSpoK2lbbisocitsKV0qZTtmKz1zLG49TWF0aC5mbG9vcihmKSpyfWZvcihsPTA7bDxyOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09aVtuKytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKHUpfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWk9PntsZXQgdD1pLmxlbmd0aCxyLGEscz10aGlzLmNoYW5uZWxzLGYsaCxlLG4sdSxvLGwsbSxnO2lmKHQlcyE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKHI9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGE9W10sZj10aGlzLnJhdGlvV2VpZ2h0LGg9MCxuPTAsdT0wLG89IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsZz0wLGU9MDtlPHM7KytlKWFbZV09MDtkb3tpZihvKWZvcihoPWYsZT0wO2U8czsrK2UpYVtlXT0wO2Vsc2V7Zm9yKGg9dGhpcy5sYXN0V2VpZ2h0LGU9MDtlPHM7KytlKWFbZV09dGhpcy5sYXN0T3V0cHV0W2VdO289ITB9Zm9yKDtoPjAmJm48dDspaWYodT0xK24tZyxoPj11KXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKytdKnU7Zz1uLGgtPXV9ZWxzZXtmb3IoZT0wO2U8czsrK2UpYVtlXSs9aVtuKyhlPjA/ZTowKV0qaDtnKz1oLGg9MDticmVha31pZihoPT09MClmb3IoZT0wO2U8czsrK2UpbFttKytdPWFbZV0vZjtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9aCxlPTA7ZTxzOysrZSl0aGlzLmxhc3RPdXRwdXRbZV09YVtlXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKG48dCYmbTxyKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoaSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihpKX19O2Z1bmN0aW9uIFMocCl7bGV0IGk9cC5sZW5ndGgsdD1uZXcgRmxvYXQzMkFycmF5KGkpO2Zvcig7aS0tOyl7bGV0IHI9cFtpXTt0W2ldPXI+PTMyNzY4Py0oNjU1MzYtcikvMzI3Njg6ci8zMjc2N31yZXR1cm4gdH12YXIgeT0xMDI0KjgsQj1jbGFzcyBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3Nvcntjb25zdHJ1Y3Rvcih0KXtzdXBlcih0KTt0aGlzLmNodW5rcz1bXTt0aGlzLmNodW5rUG9zaXRpb249MDt0aGlzLmlzRW5kZWQ9ITE7dGhpcy5pc0NhbmNlbGxlZD0hMTt0aGlzLnNhbXBsZVJhdGU9MDt0aGlzLmZvcm1hdD0iaW50MTYiO3RoaXMuYnVmZmVyT2Zmc2V0PTA7dGhpcy5sYXN0UGxheWVkQnVmZmVyU2l6ZT0wO3RoaXMuX2hhc1NlbnRFbmRFdmVudD0hMTt0aGlzLnBvcnQub25tZXNzYWdlPXI9PnRoaXMub25NZXNzYWdlKHIpfW9uTWVzc2FnZSh0KXtpZih0LmRhdGEuYWN0aW9uPT0ic3RhcnQiKXRoaXMuZm9ybWF0PXQuZGF0YS5mb3JtYXQsdGhpcy5zYW1wbGVSYXRlPXQuZGF0YS5pbnB1dFNhbXBsZVJhdGUsdGhpcy5yZXNhbXBsZXI9bmV3IGQodC5kYXRhLmlucHV0U2FtcGxlUmF0ZSx0LmRhdGEub3V0cHV0U2FtcGxlUmF0ZSwxLHkpLHRoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMuaW5wdXRCdWZmZXI9bmV3IGMoVWludDhBcnJheSx5KjIpOnRoaXMuZm9ybWF0PT0iZmxvYXQzMiImJih0aGlzLmlucHV0QnVmZmVyPW5ldyBjKFVpbnQ4QXJyYXkseSo0KSk7ZWxzZSBpZih0LmRhdGEuYWN0aW9uPT0iZGF0YSIpe2xldCByPW5ldyBVaW50OEFycmF5KHQuZGF0YS5idWZmZXIpO2Zvcih0aGlzLmlucHV0QnVmZmVyLmZlZWQocik7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspdGhpcy5kcmFpbkJ1ZmZlcigpfWVsc2UgdC5kYXRhLmFjdGlvbj09ImVuZCI/KHRoaXMubGFzdFBsYXllZEJ1ZmZlclNpemUmJnRoaXMuY2h1bmtzLnB1c2gobmV3IEZsb2F0MzJBcnJheSh0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplKjIpKSx0aGlzLmlzRW5kZWQ9ITApOnQuZGF0YS5hY3Rpb249PSJjYW5jZWwiJiYodGhpcy5pc0VuZGVkPSEwLHRoaXMuaXNDYW5jZWxsZWQ9ITApfWRyYWluQnVmZmVyKCl7bGV0IHQ9dGhpcy5pbnB1dEJ1ZmZlci5kcmFpbigpO2lmKCF0KXJldHVybjtsZXQgcjtpZih0aGlzLmZvcm1hdD09ImludDE2Iil7bGV0IHM9bmV3IEludDE2QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0LHQuYnl0ZUxlbmd0aC8yKTtyPVMocyl9ZWxzZSBpZih0aGlzLmZvcm1hdD09ImZsb2F0MzIiKXI9bmV3IEZsb2F0MzJBcnJheSh0LmJ1ZmZlcix0LmJ5dGVPZmZzZXQsdC5ieXRlTGVuZ3RoLzQpO2Vsc2UgdGhyb3cgbmV3IEVycm9yKGBJbnZhbGlkIGZvcm1hdDogJHt0aGlzLmZvcm1hdH1gKTtsZXQgYT10aGlzLnJlc2FtcGxlci5yZXNhbXBsZShyKTt0aGlzLmNodW5rcy5wdXNoKGEpfW5leHRGbG9hdCgpe2lmKCF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIDA7bGV0IHQ9dGhpcy5jaHVua3NbMF1bdGhpcy5jaHVua1Bvc2l0aW9uXTtyZXR1cm4gdGhpcy5jaHVua1Bvc2l0aW9uKyssdGhpcy5jaHVua1Bvc2l0aW9uPHRoaXMuY2h1bmtzWzBdLmxlbmd0aHx8KHRoaXMuY2h1bmtzLnNoaWZ0KCksdGhpcy5jaHVua1Bvc2l0aW9uPTApLHR9cHJvY2Vzcyh0LHIsYSl7aWYodGhpcy5pc0NhbmNlbGxlZClyZXR1cm4hMTtpZih0aGlzLmlzRW5kZWQmJiF0aGlzLmNodW5rcy5sZW5ndGgpcmV0dXJuIHRoaXMuX2hhc1NlbnRFbmRFdmVudHx8KHRoaXMuX2hhc1NlbnRFbmRFdmVudD0hMCx0aGlzLnBvcnQucG9zdE1lc3NhZ2Uoe2FjdGlvbjoiZW5kIn0pKSwhMTtsZXQgcz1yWzBdPy5bMF0/Lmxlbmd0aDtpZighcylyZXR1cm4hMDt0aGlzLmxhc3RQbGF5ZWRCdWZmZXJTaXplPXM7Zm9yKGxldCBmPTA7ZjxzO2YrKyl7bGV0IGg9dGhpcy5uZXh0RmxvYXQoKTtmb3IobGV0IGU9MDtlPHIubGVuZ3RoO2UrKylmb3IobGV0IG49MDtuPHJbZV0ubGVuZ3RoO24rKylyW2VdW25dW2ZdPWh9cmV0dXJuITB9fTtyZWdpc3RlclByb2Nlc3NvcigicGNtLXBsYXllci1ub2RlIixCKTsK";var eQ=new Ce("PCMPlayerNode"),Lu=class extends AudioWorkletNode{constructor(r,n,i){super(r,"pcm-player-node",{numberOfInputs:0});this.sampleRate=0;this.format="int16";this.isCancelled=!1;if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!i||i!="int16"&&i!="float32")throw new Error(`Invalid format: ${i}`);this.sampleRate=n,this.format=i,this.port.onmessage=o=>this.onWorkletMessage(o),this.port.postMessage({action:"start",inputSampleRate:n,outputSampleRate:r.sampleRate,format:i})}static async registerModule(r){await r.audioWorklet.addModule(KD)}feed(r){this.port.postMessage({action:"data",buffer:r.buffer},[r.buffer])}async play(r){if(this.isCancelled)throw new Error("PCMPlayerNode has already been cancelled.");if(this._playPromise)throw new Error("Already playing a stream");this._playPromise=new Promise(n=>this._playPromiseResolve=n),this.dispatchEvent(new CustomEvent("start",{detail:{player:this,stream:r}}));try{let n=r.getReader();for(;!this.isCancelled;){let{done:i,value:o}=await n.read();if(i||!o)break;this.feed(o)}}catch(n){eQ.warn("Stream error:",n),this.dispatchEvent(new CustomEvent("error",{detail:{player:this,stream:r,error:n}}))}this.port.postMessage({action:"end"}),await this._playPromise}onWorkletMessage(r){r.data.action=="end"&&(this._playPromiseResolve?.(),this.dispatchEvent(new CustomEvent("end",{detail:{player:this}})))}stop(){this.isCancelled=!0,this.port.postMessage({action:"cancel"}),this._playPromiseResolve?.()}};var Fn=new Ce("ElevenLabs");function pE(t,e,r="pcm_24000"){let n=[],i=Date.now(),o=!1,s,a;return{stream:new ReadableStream({start:d=>{s=d,a=new WebSocket(`wss://api.elevenlabs.io/v1/text-to-speech/${e}/stream-input?inactivity_timeout=120&output_format=${r}`),a.addEventListener("open",()=>{Fn.debug(`[at ${Date.now()-i}ms] WebSocket connected`),a.send(JSON.stringify({text:" ","xi-api-key":t}));for(let f of n)a.send(JSON.stringify({text:f}));n.length=0}),a.addEventListener("close",()=>{Fn.debug(`[at ${Date.now()-i}ms] WebSocket closed`),s?.close(),o=!0}),a.addEventListener("message",f=>{let p=JSON.parse(f.data);if(p.final){a.close(),s?.close();return}if(Fn.debug(`[at ${Date.now()-i}ms] Message received: ${p.audio?.length||0} bytes of audio data`),!p.audio)return;let h=Uint8Array.from(atob(p.audio),m=>m.charCodeAt(0));s?.enqueue(h)})},cancel:()=>{Fn.debug(`[at ${Date.now()-i}ms] Stream cancelled`),a?.close(),o=!0}}),sendText:d=>{d&&(Fn.debug(`[at ${Date.now()-i}ms] Sending text: "${d}"`),a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:d})):n.push(d))},endText:()=>{a?.readyState===WebSocket.OPEN?a.send(JSON.stringify({text:""})):n.push("")},get isClosed(){return o}}}function JD(t,e="pcm_16000",r=16e3,n="vad"){let i=[],o=Date.now(),s=!1,a,c;return{stream:new ReadableStream({start:async p=>{a=p;let h=await fetch("https://api.elevenlabs.io/v1/single-use-token/realtime_scribe",{method:"POST",headers:{"xi-api-key":t}});if(!h.ok)throw new Error(`Failed to generate single-use token: ${h.status} ${h.statusText}`);let m=await h.json(),g=m.token;if(!g)throw new Error(`No token found in response: ${JSON.stringify(m)}`);c=new WebSocket(`wss://api.elevenlabs.io/v1/speech-to-text/realtime?token=${encodeURIComponent(g)}&audio_format=${e}&commit_strategy=${n}`),c.addEventListener("open",()=>{Fn.debug(`[at ${Date.now()-o}ms] WebSocket connected`);for(let y of i)c.send(y);i.length=0}),c.addEventListener("close",()=>{Fn.debug(`[at ${Date.now()-o}ms] WebSocket closed`),a?.close(),s=!0}),c.addEventListener("message",y=>{let b=JSON.parse(y.data);b.message_type=="committed_transcript"?(Fn.debug(`[at ${Date.now()-o}ms] Committed transcript received: "${b.text}"`),a?.enqueue(b.text)):b.error&&(Fn.warn(`[at ${Date.now()-o}ms] Error received: ${b.error}`),a?.error(new Error(b.error)),c?.close(),s=!0)})},cancel:()=>{Fn.debug(`[at ${Date.now()-o}ms] Stream cancelled`),c?.close(),s=!0}}),sendAudio:p=>{let h=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:btoa(String.fromCharCode(...new Uint8Array(p))),commit:!1,sample_rate:r});Fn.debug(`[at ${Date.now()-o}ms] Sending audio: ${p.byteLength} bytes`),c?.readyState===WebSocket.OPEN?c.send(h):i.push(h)},commit:()=>{let p=JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:r});c?.readyState===WebSocket.OPEN?c.send(p):i.push(p)},close:()=>{Fn.debug("Closing connection"),c?.close(),s=!0,setTimeout(()=>{a?.close()},1e3)},get isClosed(){return s}}}var B_=new Ce("SpeechOutput"),YD=.5,tQ=.8,W_=class extends EventTarget{constructor(r){super();this.autoSpeak=!0;this.preemptiveConnection=!0;this.processedMessages=new Set;this.maxVolumeHeard=0;this._queuedText=[];this._queueActive=!1;this.ai=r,this.ai.addEventListener("output",n=>this.onOutputFromAI(n)),this.ai.audio?.speechRecognition.addEventListener("speechstart",n=>this.interrupt())}onOutputFromAI(r){let n=r.detail.messages,i=r.detail.isPartial;if(!(!this.ai?.audio?.speechRecognition.isRunning||!this.autoSpeak)){for(let o of n)if(!o.streamingInProgress&&!(!o.id||this.processedMessages.has(o.id))){this.processedMessages.add(o.id);for(let s of o.sections||[])s.type=="text"&&s.text&&this.speak(s.text)}i||this.processedMessages.clear()}}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}async speak(r){if(!this.ai?.config?.voice?.providerID)return B_.warn("No voice provider configured");this.ai._voiceTracker?.(`Added text to queue: ${r}`),this._queuedText.push(r),this._runQueue()}async _runQueue(){if(this._queueActive)return;let r=this._queuedText.shift();if(!r)return;this._queueActive=!0;let n=`speech-${rQ++}`;try{await this.ai.audio.beginAccess(n),await this._speakWithLock(r)}finally{this._queueActive=!1,this.ai.audio.endAccess(n)}this._queuedText.length?await this._runQueue():this.onSpeechEnd()}_getElevenLabsConnection(){let r=this._elevenLabsPrecachedConnection;return(!r||r.isClosed)&&(r=pE(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),this.preemptiveConnection&&(this._elevenLabsPrecachedConnection=pE(this.ai.config.voice.apiKey,this.ai.config.voice.voiceID,"pcm_24000")),r}async _speakWithLock(r){let n=new CustomEvent("speechfilter",{detail:{ai:this.ai,message:r}});if(this.dispatchEvent(n),r=n.detail.message,n.defaultPrevented||!r)return;this.ai.audio.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=tQ);let i=this.ai?._voiceTracker||B_.timer(`${this.ai.config.voice.providerID} voice`);i(`Speak: ${r}`),this.currentPlayerVolume?.disconnect(),this.currentPlayerVolume=this.ai.audio.context.createGain(),this.currentPlayerVolume.connect(this.ai.audio.context.destination),this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,this.analyserNode.connect(this.currentPlayerVolume),this.maxVolumeHeard=0,this.analyserBuffer=new Float32Array(this.analyserNode.fftSize);let o=new Lu(this.ai.audio.context,24e3,"int16");this.currentPlayer=o,o.connect(this.analyserNode),o.addEventListener("end",c=>{let l=c;i(`PCM stream ${l.detail.interrupted?"interrupted":"ended"}`),this.currentPlayer==o&&!l.detail.interrupted&&(this.currentPlayer=void 0)});let s=Date.now(),a=null;if(this.ai.config.voice.providerID=="openai"){let c=await fetch("https://api.openai.com/v1/audio/speech",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.ai.config.voice.apiKey}`},body:JSON.stringify({model:"tts-1",input:r,voice:this.ai.config.voice.voiceID,response_format:"pcm"})});if(!c.ok){B_.warn(`Failed to generate voice sample: ${c.status} ${c.statusText}`);return}a=c.body}else if(this.ai.config.voice.providerID=="elevenlabs"){let c=this._getElevenLabsConnection();c.sendText(r),c.endText(),a=c.stream}else{B_.warn(`Unknown voice provider: ${this.ai.config.voice.providerID}`);return}i(`Received response in ${Date.now()-s}ms`),this.dispatchEvent(new CustomEvent("speechstart",{detail:{ai:this.ai,message:r}})),i("Playing PCM stream"),await o.play(a),i("Audio has ended")}get isSpeaking(){return!!this.currentPlayer}async interrupt(){if(this._queuedText=[],!this.currentPlayerVolume)return;this.ai._voiceTracker?.("Interrupted");let r=this.currentPlayerVolume,n=this.currentPlayer;this.currentPlayerVolume=void 0,this.currentPlayer=void 0,this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=YD);let i=400;r.gain.linearRampToValueAtTime(0,i/1e3),await new Promise(o=>setTimeout(o,i+250)),r.disconnect(),n?.stop(),n?.disconnect()}onSpeechEnd(){this.dispatchEvent(new CustomEvent("speechend",{detail:{ai:this.ai}})),this.ai?.audio?.speechRecognition.voiceDetection&&(this.ai.audio.speechRecognition.voiceDetection.sensitivity=YD)}},rQ=1;function G_(t,e){let r=e.reduce((c,l)=>c+l.byteLength,0),n=new DataView(new ArrayBuffer(44));n.setUint8(0,82),n.setUint8(1,73),n.setUint8(2,70),n.setUint8(3,70),n.setUint32(4,44+r,!0),n.setUint8(8,87),n.setUint8(9,65),n.setUint8(10,86),n.setUint8(11,69);let i=1,o=32,s=i*o/8,a=t*s;return n.setUint8(12,102),n.setUint8(13,109),n.setUint8(14,116),n.setUint8(15,32),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,a,!0),n.setUint16(32,s,!0),n.setUint16(34,o,!0),n.setUint8(36,100),n.setUint8(37,97),n.setUint8(38,116),n.setUint8(39,97),n.setUint32(40,r,!0),new File([n,...e],"audio.wav",{type:"audio/wav"})}var QD="data:application/javascript;base64,dmFyIGc9Y2xhc3N7Y29uc3RydWN0b3IoZSx0LGksZil7aWYoIWV8fCF0fHwhaSl0aHJvdyBuZXcgRXJyb3IoIkludmFsaWQgc2V0dGluZ3Mgc3BlY2lmaWVkIGZvciB0aGUgcmVzYW1wbGVyLiIpO3RoaXMucmVzYW1wbGVyPW51bGwsdGhpcy5mcm9tU2FtcGxlUmF0ZT1lLHRoaXMudG9TYW1wbGVSYXRlPXQsdGhpcy5jaGFubmVscz1pfHwwLHRoaXMuaW5wdXRCdWZmZXJTaXplPWYsdGhpcy5pbml0aWFsaXplKCl9aW5pdGlhbGl6ZSgpe3RoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlPyh0aGlzLnJlc2FtcGxlcj1lPT5lLHRoaXMucmF0aW9XZWlnaHQ9MSk6KHRoaXMuZnJvbVNhbXBsZVJhdGU8dGhpcy50b1NhbXBsZVJhdGU/KHRoaXMubGluZWFySW50ZXJwb2xhdGlvbigpLHRoaXMubGFzdFdlaWdodD0xKToodGhpcy5tdWx0aVRhcCgpLHRoaXMudGFpbEV4aXN0cz0hMSx0aGlzLmxhc3RXZWlnaHQ9MCksdGhpcy5pbml0aWFsaXplQnVmZmVycygpLHRoaXMucmF0aW9XZWlnaHQ9dGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLnRvU2FtcGxlUmF0ZSl9YnVmZmVyU2xpY2UoZSl7dHJ5e3JldHVybiB0aGlzLm91dHB1dEJ1ZmZlci5zdWJhcnJheSgwLGUpfWNhdGNoe3RyeXtyZXR1cm4gdGhpcy5vdXRwdXRCdWZmZXIubGVuZ3RoPWUsdGhpcy5vdXRwdXRCdWZmZXJ9Y2F0Y2h7cmV0dXJuIHRoaXMub3V0cHV0QnVmZmVyLnNsaWNlKDAsZSl9fX1pbml0aWFsaXplQnVmZmVycygpe3RoaXMub3V0cHV0QnVmZmVyU2l6ZT1NYXRoLmNlaWwodGhpcy5pbnB1dEJ1ZmZlclNpemUqdGhpcy50b1NhbXBsZVJhdGUvdGhpcy5mcm9tU2FtcGxlUmF0ZS90aGlzLmNoYW5uZWxzKjEuMDAwMDAwNDc2ODM3MTU4MikrdGhpcy5jaGFubmVscyt0aGlzLmNoYW5uZWxzO3RyeXt0aGlzLm91dHB1dEJ1ZmZlcj1uZXcgRmxvYXQzMkFycmF5KHRoaXMub3V0cHV0QnVmZmVyU2l6ZSksdGhpcy5sYXN0T3V0cHV0PW5ldyBGbG9hdDMyQXJyYXkodGhpcy5jaGFubmVscyl9Y2F0Y2h7dGhpcy5vdXRwdXRCdWZmZXI9W10sdGhpcy5sYXN0T3V0cHV0PVtdfX1saW5lYXJJbnRlcnBvbGF0aW9uKCl7dGhpcy5yZXNhbXBsZXI9ZT0+e2xldCB0PWUubGVuZ3RoLGk9dGhpcy5jaGFubmVscyxmLGgsYSxzLHIsdSxuLHAsbDtpZih0JWkhPT0wKXRocm93IG5ldyBFcnJvcigiQnVmZmVyIHdhcyBvZiBpbmNvcnJlY3Qgc2FtcGxlIGxlbmd0aC4iKTtpZih0PD0wKXJldHVybltdO2ZvcihmPXRoaXMub3V0cHV0QnVmZmVyU2l6ZSxoPXRoaXMucmF0aW9XZWlnaHQsYT10aGlzLmxhc3RXZWlnaHQscz0wLHI9MCx1PTAsbj0wLHA9dGhpcy5vdXRwdXRCdWZmZXI7YTwxO2ErPWgpZm9yKHI9YSUxLHM9MS1yLHRoaXMubGFzdFdlaWdodD1hJTEsbD0wO2w8dGhpcy5jaGFubmVsczsrK2wpcFtuKytdPXRoaXMubGFzdE91dHB1dFtsXSpzK2VbbF0qcjtmb3IoYS09MSx0LT1pLHU9TWF0aC5mbG9vcihhKSppO248ZiYmdTx0Oyl7Zm9yKHI9YSUxLHM9MS1yLGw9MDtsPHRoaXMuY2hhbm5lbHM7KytsKXBbbisrXT1lW3UrKGw+MD9sOjApXSpzK2VbdSsoaStsKV0qcjthKz1oLHU9TWF0aC5mbG9vcihhKSppfWZvcihsPTA7bDxpOysrbCl0aGlzLmxhc3RPdXRwdXRbbF09ZVt1KytdO3JldHVybiB0aGlzLmJ1ZmZlclNsaWNlKG4pfX1tdWx0aVRhcCgpe3RoaXMucmVzYW1wbGVyPWU9PntsZXQgdD1lLmxlbmd0aCxpLGYsaD10aGlzLmNoYW5uZWxzLGEscyxyLHUsbixwLGwsbSxCO2lmKHQlaCE9PTApdGhyb3cgbmV3IEVycm9yKCJCdWZmZXIgd2FzIG9mIGluY29ycmVjdCBzYW1wbGUgbGVuZ3RoLiIpO2lmKHQ8PTApcmV0dXJuW107Zm9yKGk9dGhpcy5vdXRwdXRCdWZmZXJTaXplLGY9W10sYT10aGlzLnJhdGlvV2VpZ2h0LHM9MCx1PTAsbj0wLHA9IXRoaXMudGFpbEV4aXN0cyx0aGlzLnRhaWxFeGlzdHM9ITEsbD10aGlzLm91dHB1dEJ1ZmZlcixtPTAsQj0wLHI9MDtyPGg7KytyKWZbcl09MDtkb3tpZihwKWZvcihzPWEscj0wO3I8aDsrK3IpZltyXT0wO2Vsc2V7Zm9yKHM9dGhpcy5sYXN0V2VpZ2h0LHI9MDtyPGg7KytyKWZbcl09dGhpcy5sYXN0T3V0cHV0W3JdO3A9ITB9Zm9yKDtzPjAmJnU8dDspaWYobj0xK3UtQixzPj1uKXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KytdKm47Qj11LHMtPW59ZWxzZXtmb3Iocj0wO3I8aDsrK3IpZltyXSs9ZVt1KyhyPjA/cjowKV0qcztCKz1zLHM9MDticmVha31pZihzPT09MClmb3Iocj0wO3I8aDsrK3IpbFttKytdPWZbcl0vYTtlbHNle2Zvcih0aGlzLmxhc3RXZWlnaHQ9cyxyPTA7cjxoOysrcil0aGlzLmxhc3RPdXRwdXRbcl09ZltyXTt0aGlzLnRhaWxFeGlzdHM9ITA7YnJlYWt9fXdoaWxlKHU8dCYmbTxpKTtyZXR1cm4gdGhpcy5idWZmZXJTbGljZShtKX19cmVzYW1wbGUoZSl7cmV0dXJuIHRoaXMuZnJvbVNhbXBsZVJhdGU9PXRoaXMudG9TYW1wbGVSYXRlP3RoaXMucmF0aW9XZWlnaHQ9MToodGhpcy5mcm9tU2FtcGxlUmF0ZTx0aGlzLnRvU2FtcGxlUmF0ZT90aGlzLmxhc3RXZWlnaHQ9MToodGhpcy50YWlsRXhpc3RzPSExLHRoaXMubGFzdFdlaWdodD0wKSx0aGlzLmluaXRpYWxpemVCdWZmZXJzKCksdGhpcy5yYXRpb1dlaWdodD10aGlzLmZyb21TYW1wbGVSYXRlL3RoaXMudG9TYW1wbGVSYXRlKSx0aGlzLnJlc2FtcGxlcihlKX19O2Z1bmN0aW9uIGQobyl7bGV0IGU9by5sZW5ndGgsdD1uZXcgSW50MTZBcnJheShlKTtmb3IoO2UtLTspe2xldCBpPU1hdGgubWF4KC0xLE1hdGgubWluKDEsb1tlXSkpO3RbZV09aTwwP2kqMzI3Njg6aSozMjc2N31yZXR1cm4gdH1mdW5jdGlvbiB3KG8pe2xldCBlPW8ubGVuZ3RoLHQ9bmV3IEJpZ0ludDY0QXJyYXkoZSk7Zm9yKDtlLS07KXtsZXQgaT1NYXRoLm1heCgtMSxNYXRoLm1pbigxLG9bZV0pKTt0W2VdPUJpZ0ludChNYXRoLmZsb29yKGk8MD9pKjMyNzY4OmkqMzI3NjcpKSoweDEwMDAwMDAwMDAwMG59cmV0dXJuIHR9dmFyIGM9Y2xhc3N7Y29uc3RydWN0b3IoZSx0KXt0aGlzLm91dHB1dEJ1ZmZlclNpemU9MDt0aGlzLnBhcnRpYWxCdWZmZXJzPVtdO3RoaXMucGFydGlhbEJ1ZmZlck9mZnNldD0wO2lmKCFlKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBhcnJheSBjbGFzczogJHtlfWApO2lmKCF0fHx0PD0wKXRocm93IG5ldyBFcnJvcihgSW52YWxpZCBvdXRwdXQgYnVmZmVyIHNpemU6ICR7dH1gKTt0aGlzLkFycmF5Q2xhc3M9ZSx0aGlzLm91dHB1dEJ1ZmZlclNpemU9dH1nZXQgcXVldWVkU2l6ZSgpe3JldHVybiB0aGlzLnBhcnRpYWxCdWZmZXJzLnJlZHVjZSgoZSx0KT0+ZSt0Lmxlbmd0aCwwKX1mZWVkKGUpe3RoaXMucGFydGlhbEJ1ZmZlcnMucHVzaChlKX1nZXQgY2FuRHJhaW4oKXtyZXR1cm4gdGhpcy5wYXJ0aWFsQnVmZmVycy5yZWR1Y2UoKHQsaSk9PnQraS5sZW5ndGgsMCktdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0Pj10aGlzLm91dHB1dEJ1ZmZlclNpemV9ZHJhaW4oKXtpZighdGhpcy5jYW5EcmFpbilyZXR1cm4gbnVsbDtsZXQgZT10aGlzLkFycmF5Q2xhc3MsdD1uZXcgZSh0aGlzLm91dHB1dEJ1ZmZlclNpemUpLGk9MDtmb3IoO2khPXQubGVuZ3RoOyl7aWYoaT50Lmxlbmd0aCl0aHJvdyBuZXcgRXJyb3IoYEJ1ZmZlciBvdmVyZmxvdzogJHtpfSA+ICR7dC5sZW5ndGh9YCk7bGV0IGY9dC5sZW5ndGgtaSxoPXRoaXMucGFydGlhbEJ1ZmZlcnNbMF0sYT1oLmxlbmd0aC10aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQ7YTxmPyh0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCksaSksaSs9YSx0aGlzLnBhcnRpYWxCdWZmZXJzLnNoaWZ0KCksdGhpcy5wYXJ0aWFsQnVmZmVyT2Zmc2V0PTApOih0LnNldChoLnN1YmFycmF5KHRoaXMucGFydGlhbEJ1ZmZlck9mZnNldCx0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrZiksaSksaSs9Zix0aGlzLnBhcnRpYWxCdWZmZXJPZmZzZXQrPWYpfXJldHVybiB0fXBhZCgpe2xldCBlPXRoaXMucXVldWVkU2l6ZSV0aGlzLm91dHB1dEJ1ZmZlclNpemU7aWYoZT09MClyZXR1cm47bGV0IHQ9dGhpcy5BcnJheUNsYXNzLGk9bmV3IHQoZSk7dGhpcy5mZWVkKGkpfX07dmFyIHk9Y2xhc3MgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3J7Y29uc3RydWN0b3IodCl7c3VwZXIodCk7dGhpcy5mb3JtYXQ9ImludDE2Ijt0aGlzLmlucHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSw0MDk2KTt0aGlzLnBvcnQub25tZXNzYWdlPWk9PnRoaXMub25NZXNzYWdlKGkpfW9uTWVzc2FnZSh0KXt0LmRhdGEuYWN0aW9uPT0ic3RhcnQiJiYodGhpcy5mb3JtYXQ9dC5kYXRhLmZvcm1hdCx0aGlzLnJlc2FtcGxlcj1uZXcgZyh0LmRhdGEuaW5wdXRTYW1wbGVSYXRlLHQuZGF0YS5vdXRwdXRTYW1wbGVSYXRlLDEsNDA5NiksdGhpcy5mb3JtYXQ9PSJpbnQxNiI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoSW50MTZBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXI9bmV3IGMoQmlnSW50NjRBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSk6dGhpcy5mb3JtYXQ9PSJmbG9hdDMyIiYmKHRoaXMub3V0cHV0QnVmZmVyPW5ldyBjKEZsb2F0MzJBcnJheSx0LmRhdGEuYnVmZmVyU2l6ZSkpKX1wcm9jZXNzKHQsaSxmKXtmb3IobGV0IGE9MDthPGkubGVuZ3RoO2ErKyl7bGV0IHM9TWF0aC5taW4oaVthXS5sZW5ndGgsdFswXS5sZW5ndGgpO2ZvcihsZXQgcj0wO3I8cztyKyspaVthXVtyXS5zZXQodFswXVtyXSl9aWYoIXRoaXMucmVzYW1wbGVyKXJldHVybiEwO2xldCBoPW5ldyBGbG9hdDMyQXJyYXkoaVswXVswXS5sZW5ndGgpO2ZvcihoLnNldChpWzBdWzBdKSx0aGlzLmlucHV0QnVmZmVyLmZlZWQoaCk7dGhpcy5pbnB1dEJ1ZmZlci5jYW5EcmFpbjspe2xldCBhPXRoaXMuaW5wdXRCdWZmZXIuZHJhaW4oKSxzPXRoaXMucmVzYW1wbGVyLnJlc2FtcGxlKGEpO3RoaXMuZm9ybWF0PT0iaW50MTYiP3RoaXMub3V0cHV0QnVmZmVyLmZlZWQoZChzKSk6dGhpcy5mb3JtYXQ9PSJpbnQ2NCI/dGhpcy5vdXRwdXRCdWZmZXIuZmVlZCh3KHMpKTp0aGlzLmZvcm1hdD09ImZsb2F0MzIiJiZ0aGlzLm91dHB1dEJ1ZmZlci5mZWVkKHMpfWZvcig7dGhpcy5vdXRwdXRCdWZmZXIuY2FuRHJhaW47KXtsZXQgYT10aGlzLm91dHB1dEJ1ZmZlci5kcmFpbigpO2lmKCFhKWJyZWFrO3RoaXMucG9ydC5wb3N0TWVzc2FnZSh7YWN0aW9uOiJkYXRhIixidWZmZXI6YS5idWZmZXJ9LFthLmJ1ZmZlcl0pfXJldHVybiEwfX07cmVnaXN0ZXJQcm9jZXNzb3IoInBjbS1yZWNlaXZlci1ub2RlIix5KTsK";var Uu=class extends AudioWorkletNode{constructor(r,n,i,o){super(r,"pcm-receiver-node",{numberOfInputs:1});this.format="int16";this.format=i;let s=["int16","int64","float32"];if(!n||n<=0)throw new Error(`Invalid sample rate: ${n}`);if(!s.includes(i))throw new Error(`Invalid format ${i}, must be one of: ${s.join(", ")}`);if(!o||o<=0)throw new Error(`Invalid buffer size: ${o}`);this.port.onmessage=a=>this.onWorkletMessage(a),this.port.postMessage({action:"start",inputSampleRate:r.sampleRate,outputSampleRate:n,format:i,bufferSize:o})}static async registerModule(r){await r.audioWorklet.addModule(QD)}onWorkletMessage(r){if(r.data.action=="data"){let n=null;if(this.format=="int16"&&(n=new Int16Array(r.data.buffer)),this.format=="int64"&&(n=new BigInt64Array(r.data.buffer)),this.format=="float32"&&(n=new Float32Array(r.data.buffer)),!n)throw new Error(`Invalid format: ${this.format}`);this.onData(n),this.dispatchEvent(new CustomEvent("data",{detail:{data:n}}))}}onData(r){}};var fE=16e3,H_=256,Zu=8,wm=new Ce("VoiceDetectionNode"),xm=class xm extends Uu{constructor(r){super(r,fE,"float32",H_*Zu);this.isVoiceActive=!1;this.lastVoiceActiveDate=0;this.voiceEndTimeout=50;this.sensitivity=.5;this.sentivityEnd=.2;this.nextVadReset=0;this.currentProbability=0;this._lastVoiceActive=!1;if(!xm.vadModelURL)throw new Error("VAD model url not set, please load it and set it to VoiceDetectionNode.vadModelURL");this.loadModel()}get isVoicePossiblyEnding(){return this.isVoiceActive&&this.currentProbability<this.sensitivity}get sampleRate(){return fE}get numberOfSamples(){return H_}get numberOfSampleChunks(){return Zu}get outputBufferSize(){return H_*Zu}get isModelLoaded(){return!!this.vad}async loadModel(){wm.debug("Loading VAD model"),this.vad=await fi.load(xm.vadModelURL),this.vad.ignoreIfBusy=!0,wm.debug("Model loaded"),this.vad.makeConstant("sr","int64",[1],fE),this.vad.makeState("h","hn","float32",[2,Zu,64]),this.vad.makeState("c","cn","float32",[2,Zu,64])}async onData(r){if(this.vad)try{let n=await this.vad.run({input:new fi.onnx.Tensor(r,[Zu,H_])});if(!n)return;this.currentProbability=0;for(let s=0;s<n.output.data.length;s++)n.output.data[s]>this.currentProbability&&(this.currentProbability=n.output.data[s]);let i=this.isVoiceActive?this.sentivityEnd:this.sensitivity,o=this.currentProbability>i;if(!o&&this._lastVoiceActive&&(this.nextVadReset=Date.now(),this.vad.resetState()),this._lastVoiceActive=o,o&&!this.isVoiceActive?(this.lastVoiceActiveDate=Date.now(),this.isVoiceActive=!0,this.dispatchEvent(new CustomEvent("speechstart")),this.onSpeechStart(),wm.debug("Started speaking")):o?this.lastVoiceActiveDate=Date.now():!o&&this.isVoiceActive&&Date.now()<this.lastVoiceActiveDate+this.voiceEndTimeout||!o&&this.isVoiceActive&&(this.isVoiceActive=!1,this.dispatchEvent(new CustomEvent("speechend")),this.onSpeechEnd(),wm.debug("Stopped speaking after timeout")),!o){let s=Date.now();s>this.nextVadReset&&(this.nextVadReset=s+5e3,this.vad.resetState())}}catch(n){wm.error("VAD failed:",n)}}onSpeechStart(){}onSpeechEnd(){}};xm.vadModelURL="";var Fu=xm;var e4=new Ce("VoiceChunkOutputNode"),Cs=class extends Fu{constructor(){super(...arguments);this.buffers=[];this.recordedBuffers=[];this._voiceRecording=!1;this.backBufferDurationSeconds=3}get bufferDuration(){return this.buffers.reduce((r,n)=>r+n.length,0)/8e3}async onData(r){if(await super.onData(r),this.isVoiceActive&&!this._voiceRecording){e4.debug(`Voice detected, sending ${this.buffers.length} existing chunks`),this._voiceRecording=!0;for(let n of this.buffers)this.recordedBuffers.push(n),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:n,isFinal:!1}})),this.onVoiceChunk(n);this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r),this.buffers=[]}else if(this.isVoiceActive)this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!1}})),this.onVoiceChunk(r);else if(!this.isVoiceActive&&this._voiceRecording){this.recordedBuffers.push(r),this.dispatchEvent(new CustomEvent("voicedata",{detail:{data:r,isFinal:!0}})),this.onVoiceChunk(r),this._voiceRecording=!1;let n=this.recordedBuffers.reduce((i,o)=>i+o.length,0);e4.debug(`Voice complete, recorded ${(n/8e3).toFixed(2)} seconds of audio, ${n*4/1024} KB of data`),this.dispatchEvent(new CustomEvent("voicedataend",{detail:{data:this.recordedBuffers}})),this.onVoiceEnd(this.recordedBuffers),this.recordedBuffers=[]}else for(this.buffers.push(r);this.bufferDuration>this.backBufferDurationSeconds;)this.buffers.shift()}onVoiceChunk(r){}onVoiceEnd(r){}};var X_=new Ce("OpenAITranscriptionNode"),K_=class extends Cs{constructor(r,n){super(r);this.apiKey="";this.pendingBuffers=[];this.isTranscribing=!1;this.apiKey=n}async onVoiceEnd(r){let n=X_.timer("OpenAI Transcribe");this.isTranscribing=!0,this.pendingBuffers.push(...r);let i=G_(this.sampleRate,this.pendingBuffers);this.lastRequestAbortController?.abort(),this.lastRequestAbortController=new AbortController;let o="";try{let s=new FormData;s.append("file",i),s.append("model","whisper-1"),s.append("response_format","text");let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s,signal:this.lastRequestAbortController.signal});if(!a.ok)throw new Error(`Failed to generate voice sample: ${a.status} ${a.statusText}`);n("Response received"),o=await a.text(),n("Content received: "+o),this.lastRequestAbortController=void 0}catch(s){X_.error(`Failed to transcribe speech: ${s.message}`);return}finally{this.isTranscribing=!1}if(this.pendingBuffers=[],!o)return X_.debug("Transcription complete, but no text was found");X_.debug(`Transcription: ${o}`),this.onVoiceTranscription(o),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o}}))}onVoiceTranscription(r){}};var J_=class extends WebSocket{constructor(r){super(r);this.pendingData=[];this.addEventListener("open",()=>this._onOpen())}send(r){this.readyState==WebSocket.OPEN?super.send(r):this.pendingData.push(r)}_onOpen(){for(let r of this.pendingData)super.send(r);this.pendingData=[]}};var Di=new Ce("IntelliWeaveTranscriptionNode"),iQ="wss://speech.intelliweave.ai/api/v1/transcribe",Q_=class Q_ extends Cs{constructor(r,n){super(r);this.apiAddress=iQ;this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0,this.ws?this.ws.send(r):(Di.debug("Opening WebSocket connection"),this.ws=new J_(this.apiAddress),this.ws.send(JSON.stringify({type:"hello",sampleRate:16e3,channels:1,format:"float32",apiKey:this.apiKey})),this.ws.send(r.buffer),this.ws.onopen=()=>{Di.debug("WebSocket connection opened")},this.ws.addEventListener("message",i=>{let o=JSON.parse(i.data);if(o.error)return Di.warn("Error: "+o.error);if(o.type!="transcription")return Di.warn("Invalid response type",o);if(o.streaming&&!o.final)return Di.debug("Partial transcription: "+o.partialText);if(this.isTranscribing=!1,!o.text.trim())return Di.warn(`Empty transcription (${o.processingTime}ms)`);Di.debug(`Transcription: ${o.text} (${o.processingTime}ms)`),this.onVoiceTranscription(o.text),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:o.text}}))}),this.ws.addEventListener("close",()=>this.onSocketClose()),this.ws.addEventListener("error",i=>Di.warn("WebSocket error")));let n=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Di.debug("Shutting down WebSocket connection"),this.ws?.close(),this.ws=void 0},n)}async onVoiceEnd(r){if(this.ws?.send(JSON.stringify({type:"end"})),Q_.debugExportWav){let n=G_(this.sampleRate,r),i=document.createElement("a");i.href=URL.createObjectURL(n),i.download="recording.wav",i.click()}}onVoiceTranscription(r){}onSocketClose(){Di.debug("WebSocket connection closed"),this.ws=void 0,this.isTranscribing=!1}};Q_.debugExportWav=!1;var Y_=Q_;var Vu=new Ce("ElevenLabsTranscriptionNode"),eb=class extends Cs{constructor(r,n){super(r);this.apiKey="";this.isTranscribing=!1;this.apiKey=n}async onVoiceChunk(r){this.isTranscribing=!0;let n=new Int16Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]*32767;!this.connection||this.connection.isClosed?(this.connection?.close(),this.connection=void 0,Vu.debug(`Opening connection. sampleRate: ${this.sampleRate} format=${this.format}`),this.connection=JD(this.apiKey,"pcm_"+this.sampleRate,this.sampleRate,"manual"),this.startReading(this.connection),this.connection.sendAudio(n.buffer)):this.connection.sendAudio(n.buffer);let i=1e3*60*1;this.shutdownTimer&&clearTimeout(this.shutdownTimer),this.shutdownTimer=setTimeout(()=>{Vu.debug("Shutting down WebSocket connection"),this.connection?.close(),this.connection=void 0},i)}async startReading(r){let n=r.stream.getReader();try{for(;;){let{value:i,done:o}=await n.read();if(o){Vu.debug("Stream closed");break}if(!i?.trim()){Vu.warn("Empty transcription received");continue}this.isTranscribing=!1,Vu.debug(`Transcription: ${i}`),this.onVoiceTranscription(i),this.dispatchEvent(new CustomEvent("transcription",{detail:{text:i}}))}}catch(i){Vu.error(`Failed to read transcription stream: ${i.message}`),this.connection==r&&(this.connection=void 0);return}}async onVoiceEnd(r){this.connection?.commit()}onVoiceTranscription(r){}};var mE=new Ce("SpeechRecognition"),tb=class extends EventTarget{constructor(r){super();this.isRunning=!1;this._skipEvents=!1;this.maxVolumeHeard=0;this.ai=r}get isSupported(){if(!fi.lib||!this.ai?.vadModel||!Ko().AudioWorkletNode)return!1;if(this.ai?.config?.transcription?.providerID!="intelliweave"){if(!(this.ai?.config?.transcription?.providerID=="openai"&&this.ai.config?.transcription?.apiKey)){if(!(this.ai?.config?.transcription?.providerID=="elevenlabs"&&this.ai.config?.transcription?.apiKey))return!1}}return!0}async start(){if(!this.isSupported)throw new Error("Speech recognition not supported in this persona and browser.");if(!this.isRunning){this.isRunning=!0;try{await this.ai.audio.beginAccess("speech-recognition"),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}});let r=this.ai.audio.context.createMediaStreamSource(this.micStream);this.analyserNode=this.ai.audio.context.createAnalyser(),this.analyserNode.fftSize=32,r.connect(this.analyserNode),this.analyserBuffer=new Float32Array(this.analyserNode.fftSize),Fu.vadModelURL=URL.createObjectURL(this.ai.vadModel),this.ai?.config?.transcription?.providerID=="openai"?(this.voiceDetection=new K_(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):this.ai?.config?.transcription?.providerID=="elevenlabs"?(this.voiceDetection=new eb(this.ai.audio.context,this.ai.config.transcription.apiKey),r.connect(this.voiceDetection)):(this.voiceDetection=new Y_(this.ai.audio.context,this.ai.apiKey),this.voiceDetection.apiAddress=this.ai?.config?.transcription?.url||this.voiceDetection.apiAddress,r.connect(this.voiceDetection)),this.voiceDetection.addEventListener("speechstart",n=>{this.ai._voiceTracker=mE.timer("voice interaction","Speech started"),this.recordingStartTime=Date.now(),Dr(this.ai,{event_type:"voice_start",event_properties:{audio_provider:this.ai.config?.transcription?.providerID||"intelliweave",sample_rate:16e3}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("speechend",n=>{this.ai._voiceTracker?.("Speech ended");let i=this.recordingStartTime?Date.now()-this.recordingStartTime:0;Dr(this.ai,{event_type:"voice_end",event_properties:{recording_duration_ms:i}}),this.dispatchEvent(new CustomEvent(n.type,{detail:n.detail}))}),this.voiceDetection.addEventListener("transcription",n=>{this.ai._voiceTracker?.(`Transcription: ${n.detail.text}`),Dr(this.ai,{event_type:"voice_submit",value_str:"",event_properties:{transcription_provider:this.ai.config?.transcription?.providerID||"intelliweave",confidence_score:n.detail.confidence||void 0}}),this.onTranscription(n)}),this._skipEvents||this.dispatchEvent(new CustomEvent("start",{detail:{speechRecognition:this}}))}catch(r){mE.error("Failed to start speech recognition:",r),this.stop()}}}stop(){this.isRunning&&(this.isRunning=!1,this.ai.audio.endAccess("speech-recognition"),this.voiceDetection?.disconnect(),this.voiceDetection=void 0,this.micStream?.getTracks().forEach(r=>r.stop()),this.micStream=void 0,this.analyserNode=void 0,this.analyserBuffer=void 0,this._skipEvents||this.dispatchEvent(new CustomEvent("end",{detail:{speechRecognition:this}})))}get volumeLevel(){if(!this.analyserNode||!this.analyserBuffer)return 0;this.analyserNode.getFloatTimeDomainData(this.analyserBuffer);let r=0;for(let i of this.analyserBuffer)r+=i*i;let n=Math.sqrt(r/this.analyserBuffer.length);return n>this.maxVolumeHeard&&(this.maxVolumeHeard=n),this.maxVolumeHeard*=.999,this.maxVolumeHeard<.01&&(this.maxVolumeHeard=.01),Math.min(1,Math.max(0,n/this.maxVolumeHeard))}get wordsCurrentlyBeingSpoken(){return!!this.voiceDetection?.isVoiceActive}get isTranscribing(){return!!this.voiceDetection?.isTranscribing}onTranscription(r){let n=r.detail.text;mE.debug("Heard:",n),this.dispatchEvent(new CustomEvent("speech",{detail:{transcript:n,isFinal:!0}}))}async reset(){if(this.isRunning){this._skipEvents=!0;try{this.stop(),await this.start(),this._skipEvents=!1}catch(r){throw this._skipEvents=!1,r}}}};var rb=new Ce("AudioSystem"),km=class t{constructor(e){this.locks=[];if(!e)throw new Error("AI reference is required. Please pass in the IntelliWeave instance to the constructor.");this.ai=e,this.ai.audio=this,this.speechRecognition=new tb(this.ai),this.speechOutput=new W_(this.ai)}static get isSupported(){return!(!fi.lib||!Ko().AudioWorkletNode)}static async registerModules(e){await Promise.all([Lu.registerModule(e),Uu.registerModule(e)])}async beginAccess(e){rb.debug(`Began access for: ${e}`),this.locks.includes(e)||this.locks.push(e),!this.context&&(rb.debug("Creating AudioContext"),this.context=new AudioContext({latencyHint:"interactive"}),this.context.resume(),await t.registerModules(this.context))}endAccess(e){rb.debug(`Ended access for: ${e}`),this.locks=this.locks.filter(r=>r!=e),!this.locks.length&&(rb.debug("Closing AudioContext"),this.context?.close(),this.context=void 0)}};var en=new Ce("Embed"),sc=class extends yn{constructor(){super();this.config={};this.suggestions=[];this._previousOpenState=!1;this.html=()=>`
287
477
 
288
478
  <!-- Styling -->
289
479
  <style>
290
480
 
481
+ :host {
482
+ display: block;
483
+ }
484
+ :host([layout="fullscreen"]),
485
+ :host([positioningmode="container"]) {
486
+ width: 100%;
487
+ height: 100%;
488
+ }
489
+
291
490
  #root {
292
491
  position: fixed;
293
492
  width: 64px;
@@ -322,6 +521,24 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
322
521
  max-height: calc(max(50vh, 100vh - 320px));
323
522
  overflow: visible;
324
523
  }
524
+ #root.layout-fullscreen {
525
+ position: absolute;
526
+ inset: 0;
527
+ width: 100%;
528
+ height: 100%;
529
+ max-width: none;
530
+ max-height: none;
531
+ border-radius: 0;
532
+ box-shadow: none;
533
+ background: transparent !important;
534
+ overflow: hidden;
535
+ box-sizing: border-box;
536
+ padding-bottom: calc(12px + env(safe-area-inset-bottom));
537
+ }
538
+ #root.layout-fullscreen #web-weaver-logo,
539
+ #root.layout-fullscreen #pulseanim {
540
+ display: none;
541
+ }
325
542
 
326
543
  #root #web-weaver-logo {
327
544
  position: absolute;
@@ -332,6 +549,58 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
332
549
  border-radius:50%;
333
550
  z-index:999;
334
551
  }
552
+ #root #fullscreen-header {
553
+ display: none;
554
+ width: 100%;
555
+ max-width: 860px;
556
+ padding: 12px 24px;
557
+ box-sizing: border-box;
558
+ position: absolute;
559
+ top: 0;
560
+ left: 50%;
561
+ transform: translateX(-50%);
562
+ z-index: 10;
563
+ transition: opacity 0.2s ease;
564
+ }
565
+ #root.layout-fullscreen #fullscreen-header {
566
+ display: flex;
567
+ justify-content: space-between;
568
+ align-items: center;
569
+ }
570
+ #root.layout-fullscreen #fullscreen-persona {
571
+ display: flex;
572
+ align-items: center;
573
+ gap: 10px;
574
+ font-size: 16px;
575
+ font-weight: 600;
576
+ color: #333;
577
+ }
578
+ #root.layout-fullscreen #fullscreen-logo {
579
+ width: 32px;
580
+ height: 32px;
581
+ border-radius: 8px;
582
+ object-fit: contain;
583
+ }
584
+ #root.layout-fullscreen #fullscreen-branding {
585
+ display: none;
586
+ align-items: center;
587
+ gap: 6px;
588
+ font-size: 11px;
589
+ color: #666;
590
+ text-transform: uppercase;
591
+ letter-spacing: 0.5px;
592
+ }
593
+ #root.layout-fullscreen #fullscreen-branding.visible {
594
+ display: flex;
595
+ }
596
+ #root.layout-fullscreen #fullscreen-branding .brand-label {
597
+ opacity: 0.6;
598
+ font-weight: 400;
599
+ }
600
+ #root.layout-fullscreen #fullscreen-branding .brand-name {
601
+ font-weight: 600;
602
+ color: #333;
603
+ }
335
604
 
336
605
  #root.open #web-weaver-logo {
337
606
  background-color: rgba(0,0,0,0);
@@ -353,6 +622,16 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
353
622
  border-bottom-left-radius: 16px;
354
623
  position: relative;
355
624
  }
625
+ #root.layout-fullscreen #poweredby {
626
+ background-color: transparent;
627
+ color: #111111;
628
+ border: none;
629
+ border-top: none;
630
+ width: 100%;
631
+ max-width: 720px;
632
+ margin: 0 auto;
633
+ border-radius: 0;
634
+ }
356
635
 
357
636
  #root.open #poweredby {
358
637
  display: flex; /* Show when open */
@@ -383,6 +662,15 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
383
662
  box-sizing: border-box;
384
663
  line-height: 1.3;
385
664
  }
665
+ #root.layout-fullscreen #web-weaver-embed-inner {
666
+ padding: 56px 24px 16px 24px;
667
+ display: flex;
668
+ flex-direction: column;
669
+ gap: 12px;
670
+ width: 100%;
671
+ max-width: 860px;
672
+ margin: 0 auto;
673
+ }
386
674
  #web-weaver-embed-inner::-webkit-scrollbar {
387
675
  width: 0;
388
676
  background: transparent;
@@ -393,6 +681,14 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
393
681
  text-align: center;
394
682
  font-size: 14px;
395
683
  }
684
+ #root.layout-fullscreen #web-weaver-embed-inner .introduction-message {
685
+ padding: 8px 12px;
686
+ border-radius: 14px;
687
+ background: var(--intelliweave-persona-bg-muted, rgba(32, 38, 44, 0.8));
688
+ text-align: center;
689
+ width: 100%;
690
+ box-sizing: border-box;
691
+ }
396
692
 
397
693
  #web-weaver-embed-inner .suggestion-button {
398
694
  margin: 10px 20px;
@@ -409,6 +705,17 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
409
705
  font-size: 12px;
410
706
  opacity: 0.5;
411
707
  }
708
+ #root.layout-fullscreen #web-weaver-embed-inner .input {
709
+ align-self: flex-end;
710
+ max-width: min(80%, 720px);
711
+ margin: 0 0 0 auto;
712
+ padding: 6px 12px;
713
+ border-radius: 14px;
714
+ background: var(--intelliweave-persona-bg, rgba(32, 38, 44, 0.92));
715
+ opacity: 0.9;
716
+ font-size: 14px;
717
+ color: var(--intelliweave-user-bubble-text, inherit);
718
+ }
412
719
 
413
720
  #web-weaver-embed-inner .tool {
414
721
  margin: 10px 20px 0px 20px;
@@ -420,11 +727,102 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
420
727
  margin: 6px 20px 30px 20px;
421
728
  font-size: 14px;
422
729
  }
730
+ #root.layout-fullscreen #web-weaver-embed-inner .output {
731
+ align-self: flex-start;
732
+ max-width: min(80%, 720px);
733
+ margin: 0;
734
+ padding: 6px 12px;
735
+ border-radius: 14px;
736
+ background: var(--intelliweave-assistant-bubble-bg, rgba(32, 38, 44, 0.78));
737
+ font-size: 14px;
738
+ color: var(--intelliweave-assistant-bubble-text, inherit);
739
+ }
740
+ #root.layout-fullscreen #web-weaver-embed-inner .output > * {
741
+ margin-top: 0;
742
+ margin-bottom: 0;
743
+ }
744
+ #root.layout-fullscreen #web-weaver-embed-inner .output > * + * {
745
+ margin-top: 8px;
746
+ }
423
747
 
748
+ /* Image styles for markdown-rendered images in AI responses */
749
+ #web-weaver-embed-inner .output img {
750
+ max-width: 100%;
751
+ max-height: 300px;
752
+ width: auto;
753
+ height: auto;
754
+ border-radius: 8px;
755
+ margin: 8px 0;
756
+ display: block;
757
+ object-fit: contain;
758
+ }
759
+ #root.layout-fullscreen #web-weaver-embed-inner .output img {
760
+ max-width: 100%;
761
+ max-height: 400px;
762
+ }
763
+
764
+ /** Info block */
765
+ #web-weaver-embed-inner .info-block {
766
+ display: flex;
767
+ flex-direction: row;
768
+ align-items: flex-start;
769
+ margin: 10px 20px 10px 20px;
770
+ border: 1px solid var(--intelliweave-assistant-bubble-bg, rgba(42, 48, 54, 0.78));
771
+ border-radius: 8px;
772
+ background-color: var(--intelliweave-assistant-bubble-bg, rgba(42, 48, 54, 0.78));
773
+ padding: 10px;
774
+ gap: 8px;
775
+ color: var(--intelliweave-assistant-bubble-text, inherit);
776
+ }
777
+ #web-weaver-embed-inner .info-block .info-block-icon {
778
+ width: 14px;
779
+ height: 14px;
780
+ background-size: contain;
781
+ background-position: center;
782
+ background-repeat: no-repeat;
783
+ flex: 0 0 auto;
784
+ opacity: 0.5;
785
+ }
786
+ #web-weaver-embed-inner .info-block .info-block-text {
787
+ flex: 1 1 1px;
788
+ font-size: 11px;
789
+ opacity: 0.5;
790
+ }
791
+ #web-weaver-embed-inner .info-block .info-block-text > p:first-child {
792
+ margin-top: 0px;
793
+ }
794
+ #web-weaver-embed-inner .info-block .info-block-text > p:last-child {
795
+ margin-bottom: 0px;
796
+ }
797
+
798
+ /** Info block icons */
799
+ #web-weaver-embed-inner .info-block-icon.thinking-icon {
800
+ background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB4PSIwIiB5PSIwIiB2aWV3Qm94PSIwIDAgNTEyLjAwOCA1MTIiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDUxMiA1MTIiIHhtbDpzcGFjZT0icHJlc2VydmUiIGNsYXNzPSIiPjxnPjxwYXRoIGQ9Ik04LjA5NCAxODQuMTA1YTU0Ljg3NiA1NC44NzYgMCAwIDAgMjMuMjQyIDIwLjkxYzQuNTU5IDIuMTY5IDYuNDk2IDcuNjI2IDQuMzI0IDEyLjE4OC0yLjE3MiA0LjU1OS03LjYyOSA2LjQ5Ni0xMi4xODcgNC4zMjRhNzMuMDc0IDczLjA3NCAwIDAgMS0xMC40Ny02LjE5MWMxMC4wMjggMjkuNzI2IDM3Ljg4NCA0OS43NjIgNjkuMjU5IDQ5LjgxMmguNTQ3YTk0LjM2NSA5NC4zNjUgMCAwIDEtLjM1Ni0xNS4xODdjNC4wNS00OC43NTQgNDUuMTQ1LTg2LjA1OSA5NC4wNjMtODUuMzg3aDUyLjAzYTkuMTQgOS4xNCAwIDAgMCA5LjE0Mi05LjE0YzAtMTUuMTQ5IDEyLjI4LTI3LjQzIDI3LjQzLTI3LjQzaDI3LjQyOWM1LjA1IDAgOS4xNCA0LjA5NCA5LjE0IDkuMTQ0YTkuMTQgOS4xNCAwIDAgMS05LjE0IDkuMTQxaC0yNy40M2MtNS4wNSAwLTkuMTQgNC4wOTQtOS4xNCA5LjE0NSAwIDE1LjE0OC0xMi4yODIgMjcuNDI1LTI3LjQzIDI3LjQyNWgtNTIuMDMxYy0zOS4yNzgtLjY5MS03Mi4zOTEgMjkuMTMtNzUuODA1IDY4LjI2MmE3My42MTYgNzMuNjE2IDAgMCAwIDEuNTkgMjAuNjQ1Yy4zOTQgMS44MjguODYgMy41NDYgMS4zODMgNS4yNzdhNjQuNzE1IDY0LjcxNSAwIDAgMCAyLjIxIDYuMzE2bC4yMi41MmE3My43OTQgNzMuNzk0IDAgMCAwIDQ4LjYzMiA0Mi43MjZsLjY2OC4xNzJjMS42NzIuNDQyIDMuMzcxLjgwNSA1LjA5IDEuMTI1Ljg2LjE1NyAxLjczOC4yNzQgMi42MDUuNDAzIDEuMjQ2LjE4MyAyLjQ4LjM3NSAzLjc0My40OTYgMi4yNTcuMjA3IDQuNTcuMzQ3IDYuODM1LjM0N2E3My4yODYgNzMuMjg2IDAgMCAwIDU4LjY2NS0yOS42MzIgMTI4LjExNiAxMjguMTE2IDAgMCAxLTEyLjQ1NC05LjA1MWMtMy44ODItMy4yMy00LjQxNC04Ljk5Ni0xLjE4My0xMi44OGE5LjE0IDkuMTQgMCAwIDEgMTIuODc1LTEuMTgzIDEwOS41MjEgMTA5LjUyMSAwIDAgMCA5MC44ODcgMjMuMzI1IDEwOS41MDggMTA5LjUwOCAwIDAgMCA3NS41NzgtNTUuNjFBNzMuMDg5IDczLjA4OSAwIDAgMSAzODcgMjIyLjA3NGMtMS4zOTUtNC44MjQgMS4zNjMtOS44NzUgNi4xOC0xMS4zMDQgNC44MTItMS40MzQgOS44ODIgMS4yODkgMTEuMzQ3IDYuMDkzIDcuMDg2IDI0LjAzNSAyOS41NTkgNDAuMjE1IDU0LjYwMiAzOS4zMDkgMjUuMDQzLS45MDYgNDYuMjg5LTE4LjY2OCA1MS42MTctNDMuMTUyIDUuMzMyLTI0LjQ4NS02LjYwNS00OS40Ny0yOS4wMDgtNjAuNzA0YTEwOC45OTUgMTA4Ljk5NSAwIDAgMS00LjY3MiAxNS42MjUgOS4xNDUgOS4xNDUgMCAwIDEtMTEuODQ3IDUuMTkyYy00LjcwNy0xLjgzNi03LjAzMS03LjE0NS01LjE5Ni0xMS44NDhhOTAuMTY1IDkwLjE2NSAwIDAgMCA1LjYwNi0yMy4wMDRjLjE0OC0xLjI2MS4yMzgtMi40NDEuMzI4LTMuNjU2LjE1Ni0yLjIwNy4zMDUtNC4zOTguMzA1LTYuNjIxIDAtMzkuNjQtMjUuNTk4LTc0Ljc0Mi02My4zNDQtODYuODU2YTEwNy41MjggMTA3LjUyOCAwIDAgMSA3LjY0NCAxMy42MjIgOS4xNDMgOS4xNDMgMCAxIDEtMTYuNjA1IDcuNjI1QzM3My45OCAxOS41NyAzMjQuNzQ3LTEuMDgyIDI4MC4xOTUgMTQuNjhhOTAuOTU1IDkwLjk1NSAwIDAgMC0xOS4xOTkgOS4yNSA5LjE0NyA5LjE0NyAwIDAgMS0xMi42NTYtMi42NjhjLTIuNzU4LTQuMjMtMS41NjMtOS44OTkgMi42NzItMTIuNjU3IDEuMzc5LS45MTQgMi44MjQtMS42OTkgNC4yNDItMi41MzlhNjIuNjg1IDYyLjY4NSAwIDAgMC02MC4yMzQgMy41NCA3My4wMjcgNzMuMDI3IDAgMCAxIDExLjI5MiAxMi41OTcgOS4xNDIgOS4xNDIgMCAxIDEtMTQuOTk2IDEwLjQ1NyA1NS4yMTEgNTUuMjExIDAgMCAwLTE2LjIyNi0xNS4yODVoLS4wODZjLTIzLjgtMTQuOC01NC45NTMtOS4wOS03MS45NTMgMTMuMTk1YTcxLjM3NiA3MS4zNzYgMCAwIDEgMTAuNTYyIDMuOTM4IDkuMTU1IDkuMTU1IDAgMCAxIDUuMzggNy41NDcgOS4xNSA5LjE1IDAgMCAxLTMuOTc3IDguMzcgOS4xNDcgOS4xNDcgMCAwIDEtOS4yNS41OTUgNTQuODYxIDU0Ljg2MSAwIDAgMC03Ni41OSAzNi4wMDggNzIuNDcyIDcyLjQ3MiAwIDAgMSAxNS4yMjItMy45NyA5LjE0NiA5LjE0NiAwIDEgMSAyLjU3OSAxOC4xMSA1NC40NDMgNTQuNDQzIDAgMCAwLTIzLjI2NiA5LjE0NGwtLjEyMS4xMDJjLTIzLjgxNyAxNi40NTMtMzAuNjcyIDQ4LjYyOS0xNS42MjUgNzMuMzYuMDU1LjEyOC4wNzQuMjM4LjEyOS4zMzF6bTAgMCIgZmlsbD0iI2ZmZmZmZiIgb3BhY2l0eT0iMSIgZGF0YS1vcmlnaW5hbD0iIzAwMDAwMCIgY2xhc3M9IiI+PC9wYXRoPjxwYXRoIGQ9Ik0zODguNTQ3IDM1Ni41NzRjNDcuODkgMCA4Ni44NTUtMzAuNzU0IDg2Ljg1NS02OC41N2E1NC4wMTggNTQuMDE4IDAgMCAwLTIuMzMyLTE1LjU0MyA3Mi40NyA3Mi40NyAwIDAgMS02MS44Ni0xNC40NjUgMTI4LjgxMyAxMjguODEzIDAgMCAxLTk5LjQ2NCA2MS41NTkgODYuMjggODYuMjggMCAwIDAgNTUuNzc0IDM0LjkxIDEwMS45MiAxMDEuOTIgMCAwIDAgMjEuMDI3IDIuMTF6TTI5MC43MTkgMzE5LjQxOGExMjguNDc3IDEyOC40NzcgMCAwIDEtMzcuNDA2LTkuMDcgNy4wNjUgNy4wNjUgMCAwIDEtLjk4NS0uMTkyYy0uOTE0LS4zOS0xLjgyOC0uODYtMi43NDItMS4yNjEtLjM2Ny0uMTY1LS43NjItLjI3NC0xLjEyNS0uNDVhOTAuNTY2IDkwLjU2NiAwIDAgMS0xMC42OCAxMi40NzNjLjQ5MiAxNC43NTQgMTIuNTc0IDI2LjQ3MyAyNy4zMzYgMjYuNTE2YTI4LjA1NSAyOC4wNTUgMCAwIDEgMjEuNDc3IDkuMzA0bDUyLjg4MyA2MC41NzVhMTAuMDY4IDEwLjA2OCAwIDAgMCA3LjMxMiAzLjI2MWM1LjM3MS4wMTYgOS43MzgtNC4zMiA5Ljc1OC05LjY5MXYtNDAuMzU2YTk5LjMyMiA5OS4zMjIgMCAwIDEtNjUuODI4LTUxLjEwOXptMCAwIiBmaWxsPSIjZmZmZmZmIiBvcGFjaXR5PSIxIiBkYXRhLW9yaWdpbmFsPSIjMDAwMDAwIiBjbGFzcz0iIj48L3BhdGg+PC9nPjwvc3ZnPg==");
801
+ }
802
+ #web-weaver-embed-inner .info-block-icon.tool-icon {
803
+ background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB4PSIwIiB5PSIwIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTEyIDUxMiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgY2xhc3M9IiI+PGc+PHBhdGggZD0iTTUwNy40NTggMTAwLjAyOWExNSAxNSAwIDAgMC0yNS4xMDEtNi43NDVsLTUzLjU5IDUzLjU5LTUzLjAzMy0xMC42MDYtMTAuNjA2LTUzLjAzMyA1My41OS01My41OWExNC45OTkgMTQuOTk5IDAgMCAwLTYuNzQ2LTI1LjEwMWMtNDYuNDgyLTEyLjM4Ni05Ni40MTMuOTc5LTEzMC4zMDMgMzQuODctMzcuMjY5IDM3LjI2OC00OS4xOTQgOTMuMDg2LTMxLjI4NiAxNDEuOTg4TDIzLjcyIDM4Ni40NzhDOC45MzcgMzk5Ljg1My41MjEgNDE4LjE5NC4wMjMgNDM4LjEyM2MtLjQ5OCAxOS45MyA2Ljk5MSAzOC42NjkgMjEuMDg4IDUyLjc2NkMzNC43NjggNTA0LjU0NSA1Mi43OCA1MTIgNzIuMDExIDUxMmMuNjIgMCAxLjI0My0uMDA4IDEuODY2LS4wMjMgMTkuOTI5LS40OTggMzguMjcxLTguOTE0IDUxLjY0Ni0yMy42OTdMMzMwLjU5IDI2MS42MjZhMTM0LjUyIDEzNC41MiAwIDAgMCA0Ni4yODkgOC4xODljMzUuMTYxIDAgNjkuODg4LTEzLjY2MSA5NS43MDktMzkuNDgzIDMzLjg5MS0zMy44OTEgNDcuMjUyLTgzLjgyMSAzNC44Ny0xMzAuMzAzek03NC4xNDQgNDUyLjg1NWMtOC4yODQgMC0xNS02LjcxNi0xNS0xNXM2LjcxNi0xNSAxNS0xNSAxNSA2LjcxNiAxNSAxNS02LjcxNSAxNS0xNSAxNXoiIGZpbGw9IiNmZmZmZmYiIG9wYWNpdHk9IjEiIGRhdGEtb3JpZ2luYWw9IiMwMDAwMDAiPjwvcGF0aD48L2c+PC9zdmc+");
804
+ }
805
+
424
806
  :host a, :host a:visited {
425
807
  color: rgba(128, 192, 255, 1);
426
808
  text-decoration: none;
427
809
  }
810
+ #root.layout-fullscreen #interaction-bar {
811
+ width: 100%;
812
+ max-width: 720px;
813
+ margin: 12px auto 0 auto;
814
+ border-radius: 12px;
815
+ overflow: hidden;
816
+ }
817
+ #root.layout-fullscreen #interaction-bar {
818
+ background-color: var(--intelliweave-interaction-bg, rgba(32, 38, 44, 0.9));
819
+ }
820
+ @media (max-width: 768px) {
821
+ #root.layout-fullscreen #interaction-bar {
822
+ width: calc(100% - 24px);
823
+ margin-bottom: calc(12px + env(safe-area-inset-bottom));
824
+ }
825
+ }
428
826
 
429
827
  .circle {
430
828
  width: 64px;
@@ -456,18 +854,32 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
456
854
  <div id='root' class='hidden'>
457
855
 
458
856
  <!-- Logo -->
459
- ${D.add({id:"web-weaver-logo",logo:this.attr.logo})}
857
+ ${Gf.add({id:"web-weaver-logo",logo:this.attr.logo})}
460
858
  <div id='pulseanim' class="circle pulse"></div>
461
859
 
860
+
861
+
862
+ <!-- Fullscreen header -->
863
+ <div id='fullscreen-header'>
864
+ <div id='fullscreen-persona'>
865
+ <img id='fullscreen-logo' src='' alt='' />
866
+ <span id='fullscreen-name'></span>
867
+ </div>
868
+ <div id='fullscreen-branding' class='branding-chatterly'>
869
+ <span class='brand-label'>CREATED WITH</span>
870
+ <span class='brand-name'>Chatterly</span>
871
+ </div>
872
+ </div>
873
+
462
874
  <!-- Inner container contains all the UI when the panel is open -->
463
875
  <div id='web-weaver-embed-inner'>
464
876
  </div>
465
877
 
466
878
  <!-- LLM selector panel -->
467
- ${K.add({id:"llm-selector-panel"})}
879
+ ${vm.add({id:"llm-selector-panel"})}
468
880
 
469
881
  <!-- Interaction panel -->
470
- ${_.add({id:"interaction-bar"})}
882
+ ${Wf.add({id:"interaction-bar"})}
471
883
 
472
884
 
473
885
  <!-- Powered by IW banner -->
@@ -477,4 +889,16 @@ ${o}`})}else if(n.type=="action"){let o={name:n._functionID,description:ye(typeo
477
889
 
478
890
  </div>
479
891
 
480
- `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new T,A.isSupported&&(this.ai.audio=new A(this.ai))}onCreate(){m().embed&&b.warn("Only one <web-weaver-embed> element should be on the page."),m().embed=this;let e=m();b.debug("[WebWeaverEmbed] Client config:",e),e.displayMode&&!this.attr.displayMode&&(b.debug("[WebWeaverEmbed] Setting displayMode from client config:",e.displayMode),this.attr.displayMode=e.displayMode),e.positioningMode&&!this.attr.positioningMode&&(b.debug("[WebWeaverEmbed] Setting positioningMode from client config:",e.positioningMode),this.attr.positioningMode=e.positioningMode),e.positionX&&!this.attr.positionX&&(b.debug("[WebWeaverEmbed] Setting positionX from client config:",e.positionX),this.attr.positionX=e.positionX),e.positionY&&!this.attr.positionY&&(b.debug("[WebWeaverEmbed] Setting positionY from client config:",e.positionY),this.attr.positionY=e.positionY),e.offsetX!==void 0&&!this.attr.offsetX&&(b.debug("[WebWeaverEmbed] Setting offsetX from client config:",e.offsetX),this.attr.offsetX=String(e.offsetX)),e.offsetY!==void 0&&!this.attr.offsetY&&(b.debug("[WebWeaverEmbed] Setting offsetY from client config:",e.offsetY),this.attr.offsetY=String(e.offsetY)),b.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",n=>this.onContainerClick(n)),this.child("web-weaver-logo").addEventListener("click",n=>this.onLogoClick(n)),this.child("interaction-bar").addEventListener("input-message",n=>this.processInput(n.detail)),this.child("interaction-bar").addEventListener("llm-button-click",n=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",n=>this.onLLMModelSelect(n)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.onAIToolStart=this.onAIToolStart.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:n=>(this.suggestions.push(n.text),this.ai.submitAnalyticsEvent({type:"suggest-response",text:n.text}),"Suggestion button added")});let s=this.attr.apiKey||m().apiKey;if(!s)return b.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(s).then(n=>{this.config=n,m().introductionMessage=this.config.introductionMessage,m().analytics=this.config.analytics!==void 0?!!this.config.analytics:m().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.resetConversation()}).catch(n=>{b.error("Failed to load AI configuration:",n),this.state.loading=!1;let o=this.child("web-weaver-embed-inner");o&&(o.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyConfigStylesAndAttributes(){let e=this.config,t=this.child("root");if(!t)return;let s=!1,o=this.attr.logo||e.logo;if(o&&o!==this._lastLogo){this._lastLogo=o,s=!0;let Ce=this.child("web-weaver-logo");Ce&&Ce.setAttribute("logo",o)}let d=this.attr.background||e.background;d!==this._lastBackground&&(this._lastBackground=d,s=!0,d?t.style.background=d:t.style.background="");let r=this.attr.textColor||e.textColor,u=this.child("interaction-bar");r!==this._lastTextColor&&(this._lastTextColor=r,s=!0,r?(t.style.color=r,u&&u.setAttribute("textColor",r)):(t.style.color="",u&&u.removeAttribute("textColor")));let Z=this.attr.displayMode||e.displayMode||"closed";Z!==this._lastDisplayMode&&(this._lastDisplayMode=Z,s=!0,Z==="open"&&!this.attr.open&&(this.attr.open=!0));let ue=this.attr.positioningMode||e.positioningMode||"fixed";ue!==this._lastPositioningMode&&(this._lastPositioningMode=ue,s=!0);let pe=this.attr.positionX||e.positionX||"right";pe!==this._lastPositionX&&(this._lastPositionX=pe,s=!0);let me=this.attr.positionY||e.positionY||"bottom";me!==this._lastPositionY&&(this._lastPositionY=me,s=!0);let Ge=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,ge=Ge!==void 0?Ge:e.offsetX!==void 0?e.offsetX:20;ge!==this._lastOffsetX&&(this._lastOffsetX=ge,s=!0);let Ze=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,fe=Ze!==void 0?Ze:e.offsetY!==void 0?e.offsetY:20;fe!==this._lastOffsetY&&(this._lastOffsetY=fe,s=!0),s&&b.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:o,finalBackground:t.style.background,finalTextColor:t.style.color,finalDisplayMode:Z,finalPositioningMode:ue,finalPositionX:pe,finalPositionY:me,finalOffsetX:ge,finalOffsetY:fe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),f(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let d=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;f(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:d}})}this._previousOpenState=this.attr.open,this.attr.open?this.child("root").classList.add("open"):this.child("root").classList.remove("open");let e=this.child("root"),t=this._lastPositioningMode||"fixed",s=this._lastPositionX||"right",n=this._lastPositionY||"bottom",o=this._lastOffsetX!==void 0?this._lastOffsetX:20,a=this._lastOffsetY!==void 0?this._lastOffsetY:20;t==="container"?(e.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):e.classList.remove("container-mode"),t!=="container"&&(e.style.left="",e.style.right="",e.style.top="",e.style.bottom="",s==="left"?e.style.left=o+"px":e.style.right=o+"px",n==="top"?e.style.top=a+"px":e.style.bottom=a+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((d,c)=>(c.priority||0)-(d.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){m().embed==this&&(m().embed=void 0)}onContainerClick(e){(this._lastDisplayMode||"closed")!=="open"&&(this.attr.open||(e.preventDefault(),this.attr.open=!0))}onLogoClick(e){if(e.preventDefault(),e.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{if((this._lastDisplayMode||"closed")==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let e=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;e.children.length>0;)e.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let t=document.createElement("div");t.className="introduction-message",t.innerHTML=m().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,e.appendChild(t),this.ai.insertAssistantMessage(t.innerText);for(let s of m().introductionSuggestions||[]){let n=document.createElement("div");n.className="suggestion-button",n.innerText=s,n.addEventListener("click",o=>this.onSuggestionClick(o,s)),e.appendChild(n)}}async processInput(e){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let t=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let n of Array.from(t.querySelectorAll(".suggestion-button")))n.remove();this.attr.focusID="";let s=document.createElement("div");s.className="input",s.innerText=e,t.appendChild(s),this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output",this.currentOutputElement.style.display="none",this.currentOutputElement.innerHTML="",t.appendChild(this.currentOutputElement),t.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"}),await this.ai.sendMessage(e);for(let n of this.suggestions){let o=document.createElement("div");o.className="suggestion-button",o.innerText=n,o.addEventListener("click",a=>this.onSuggestionClick(a,n)),t.appendChild(o)}t.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}catch(s){b.error("Failed to process input:",s);let n=document.createElement("div");n.className="output",n.innerText="Sorry, there was a problem getting a response. "+s.message,t.appendChild(n);let o=document.createElement("div");o.className="suggestion-button",o.innerText="Reset conversation",o.addEventListener("click",a=>this.resetConversation()),t.appendChild(o)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(e){let t=await gt().use(pt).use(mt).use(dt,{target:"_blank",rel:["noopener","noreferrer"]}).use(ht).use(ut).processSync(e);this.currentOutputElement&&(this.currentOutputElement.style.display="",this.currentOutputElement.innerHTML=t.toString("utf-8"));let s=this.child("web-weaver-embed-inner");for(let n of Array.from(s.querySelectorAll(".tool")))n.remove();s.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onAIToolStart(e,t){let s=`Running: ${e}`;e=="search"&&(s=`Searching: ${t?.query}`),e=="ui.focusElement"&&(s=`Focusing: #${t?.elementID}`),e=="ui.suggestResponse"&&(s=`Suggested response: ${t?.text}`);let n=this.child("web-weaver-embed-inner"),o=document.createElement("div");o.className="tool",o.innerText=s,n.appendChild(o),n.lastElementChild?.scrollIntoView({behavior:"instant",block:"end"})}onSuggestionClick(e,t){this.processInput(t)}onLLMModelSelect(e){e.preventDefault(),this.ai.setModel(e.detail),this.state.llmPanelOpen=!1}};M.tagName="intelliweave-embed",M.observedAttributes=["logo","focusID","open","background","textColor","displayMode","positioningMode","positionX","positionY","offsetX","offsetY"];var Pn=M;w.lib=()=>import("onnxruntime-web");M.register();export{Pn as default};
892
+ `;this._lastLogo="";this._lastBackground="";this._lastTextColor="";this._lastDisplayMode="";this._lastLayout="";this._lastPersonaName="";this._lastHeaderLogo="";this._lastPositioningMode="";this._lastPositionX="";this._lastPositionY="";this._isProcessing=!1;this.ai=new Nu,km.isSupported&&(this.ai.audio=new km(this.ai))}onCreate(){ht().embed&&en.warn("Only one <web-weaver-embed> element should be on the page."),ht().embed=this;let r=ht();en.debug("[WebWeaverEmbed] Client config:",r),r.displayMode&&!this.attr.displayMode&&(en.debug("[WebWeaverEmbed] Setting displayMode from client config:",r.displayMode),this.attr.displayMode=r.displayMode),r.layout&&!this.attr.layout&&(en.debug("[WebWeaverEmbed] Setting layout from client config:",r.layout),this.attr.layout=r.layout),r.positioningMode&&!this.attr.positioningMode&&(en.debug("[WebWeaverEmbed] Setting positioningMode from client config:",r.positioningMode),this.attr.positioningMode=r.positioningMode),r.positionX&&!this.attr.positionX&&(en.debug("[WebWeaverEmbed] Setting positionX from client config:",r.positionX),this.attr.positionX=r.positionX),r.positionY&&!this.attr.positionY&&(en.debug("[WebWeaverEmbed] Setting positionY from client config:",r.positionY),this.attr.positionY=r.positionY),r.offsetX!==void 0&&!this.attr.offsetX&&(en.debug("[WebWeaverEmbed] Setting offsetX from client config:",r.offsetX),this.attr.offsetX=String(r.offsetX)),r.offsetY!==void 0&&!this.attr.offsetY&&(en.debug("[WebWeaverEmbed] Setting offsetY from client config:",r.offsetY),this.attr.offsetY=String(r.offsetY)),en.debug("[WebWeaverEmbed] Attributes after setting:",{displayMode:this.attr.displayMode,positionX:this.attr.positionX,positionY:this.attr.positionY,offsetX:this.attr.offsetX,offsetY:this.attr.offsetY}),this.applyConfigStylesAndAttributes(),this.child("root").addEventListener("click",o=>this.onContainerClick(o)),this.child("web-weaver-logo").addEventListener("click",o=>this.onLogoClick(o)),this.child("interaction-bar").addEventListener("input-message",o=>this.processInput(o.detail)),this.child("interaction-bar").addEventListener("llm-button-click",o=>this.state.llmPanelOpen=!this.state.llmPanelOpen),this.child("llm-selector-panel").addEventListener("select",o=>this.onLLMModelSelect(o)),this.child("web-weaver-embed-inner").addEventListener("scroll",o=>this.onContentScroll(o)),this.child("interaction-bar").connectAI(this.ai),this.ai.onAIMessage=this.onAIMessage.bind(this),this.ai.knowledgeBase.addEntry({id:"ui.suggestResponse",type:"action",name:"Suggest a response",content:"Add a button with a suggested response for the user's next message. Supports multiple calls at once.",isContext:!0,hideActionInUI:"always",parameters:[{name:"text",type:"string",description:"The suggested response for the user's next message."}],action:o=>(this.suggestions.push(o.text),"Suggestion button added")}),this.ai.knowledgeBase.addEntry({id:"_iw_image_instructions",type:"info",name:"Using Images",content:`
893
+ You can display images in Markdown format, example: ![filename](url)
894
+ Image URLs must be absolute. When using an image URL from the knowledge base, include all parameters.`,isContext:!0});let i=this.attr.apiKey||ht().apiKey;if(!i)return en.warn("No API key specified, some features may be unavailable.");this.state.loading=!0,this.attr.hubAPI&&(this.ai.hubAPI=this.attr.hubAPI),this.ai.load(i).then(o=>{this.config=o.config,ht().introductionMessage||(ht().introductionMessage=this.config.introductionMessage),ht().analytics=this.config.analytics!==void 0?!!this.config.analytics:ht().analytics,this.applyConfigStylesAndAttributes(),this.child("root").classList.remove("hidden"),this.state.loading=!1,this.config.managedBy&&this.updateBrandingFor(this.config.managedBy),this.resetConversation()}).catch(o=>{en.error("Failed to load AI configuration:",o),this.state.loading=!1;let s=this.child("web-weaver-embed-inner");s&&(s.innerHTML='<div class="output" style="color: red; padding: 20px;">Error loading configuration. Please try again later.</div>')})}applyPersonaColorVariants(r,n){if(!n){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.removeProperty("--intelliweave-interaction-bg");return}let i=this.parseColorToRGB(n);if(!i){r.style.removeProperty("--intelliweave-persona-bg-muted"),r.style.removeProperty("--intelliweave-assistant-bubble-bg"),r.style.setProperty("--intelliweave-interaction-bg",n);return}let{r:o,g:s,b:a}=i;r.style.setProperty("--intelliweave-persona-bg-muted",`rgba(${o}, ${s}, ${a}, 0.65)`),r.style.setProperty("--intelliweave-assistant-bubble-bg",`rgba(${Math.round(o*.85)}, ${Math.round(s*.85)}, ${Math.round(a*.85)}, 0.85)`),r.style.setProperty("--intelliweave-interaction-bg",`rgba(${o}, ${s}, ${a}, 0.9)`)}parseColorToRGB(r){if(!r)return null;let n=r.trim();if(n.startsWith("#")){let i=n.slice(1);if(i.length===3){let o=parseInt(i[0]+i[0],16),s=parseInt(i[1]+i[1],16),a=parseInt(i[2]+i[2],16);return{r:o,g:s,b:a}}if(i.length===6){let o=parseInt(i.slice(0,2),16),s=parseInt(i.slice(2,4),16),a=parseInt(i.slice(4,6),16);return{r:o,g:s,b:a}}return null}if(n.startsWith("rgb")){let i=n.match(/rgba?\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)/i);return i?{r:Math.max(0,Math.min(255,Math.round(Number(i[1])))),g:Math.max(0,Math.min(255,Math.round(Number(i[2])))),b:Math.max(0,Math.min(255,Math.round(Number(i[3]))))}:null}return null}applyConfigStylesAndAttributes(){let r=this.config,n=this.child("root");if(!n)return;let i=!1,s=this.attr.logo||r.logo;if(s&&s!==this._lastLogo){this._lastLogo=s,i=!0;let fe=this.child("web-weaver-logo");fe&&fe.setAttribute("logo",s)}let a=this.root?.getElementById("fullscreen-logo"),c=this.root?.getElementById("fullscreen-name"),l=r.name||"";l!==this._lastPersonaName&&(this._lastPersonaName=l,c&&(c.textContent=l),i=!0),s!==this._lastHeaderLogo&&(this._lastHeaderLogo=s||"",a&&(s?(a.src=s,a.style.display=""):a.style.display="none"),i=!0);let u=this.root?.getElementById("fullscreen-header"),d=(this.attr.header||"").toLowerCase();if(u){let fe=d==="hidden"||d==="none"||d==="false";u.style.display=!fe&&(s||l)?"":"none"}let p=this.attr.background||r.background;p!==this._lastBackground&&(this._lastBackground=p,i=!0,p?(n.style.background=p,n.style.setProperty("--intelliweave-persona-bg",p),this.applyPersonaColorVariants(n,p)):(n.style.background="",n.style.removeProperty("--intelliweave-persona-bg"),this.applyPersonaColorVariants(n,void 0)));let m=this.attr.textColor||r.textColor,g=this.child("interaction-bar");m!==this._lastTextColor&&(this._lastTextColor=m,i=!0,m?(n.style.color=m,n.style.setProperty("--intelliweave-user-bubble-text",m),n.style.setProperty("--intelliweave-assistant-bubble-text",m),g&&g.setAttribute("textColor",m)):(n.style.color="",n.style.removeProperty("--intelliweave-user-bubble-text"),n.style.removeProperty("--intelliweave-assistant-bubble-text"),g&&g.removeAttribute("textColor")));let b=this.attr.displayMode||r.displayMode||"closed";b!==this._lastDisplayMode&&(this._lastDisplayMode=b,i=!0,b==="open"&&!this.attr.open&&(this.attr.open=!0));let R=this.attr.layout||r.layout||"widget";R!==this._lastLayout&&(this._lastLayout=R,i=!0);let P=this.attr.positioningMode||r.positioningMode||"fixed";P!==this._lastPositioningMode&&(this._lastPositioningMode=P,i=!0);let ce=this.attr.positionX||r.positionX||"right";ce!==this._lastPositionX&&(this._lastPositionX=ce,i=!0);let H=this.attr.positionY||r.positionY||"bottom";H!==this._lastPositionY&&(this._lastPositionY=H,i=!0);let _e=this.attr.offsetX?parseInt(this.attr.offsetX):void 0,he=_e!==void 0?_e:r.offsetX!==void 0?r.offsetX:20;he!==this._lastOffsetX&&(this._lastOffsetX=he,i=!0);let Y=this.attr.offsetY?parseInt(this.attr.offsetY):void 0,pe=Y!==void 0?Y:r.offsetY!==void 0?r.offsetY:20;pe!==this._lastOffsetY&&(this._lastOffsetY=pe,i=!0),i&&en.debug("[WebWeaverEmbed] Applied UI Styling:",{finalLogo:s,finalBackground:n.style.background,finalTextColor:n.style.color,finalDisplayMode:b,finalLayout:R,finalPositioningMode:P,finalPositionX:ce,finalPositionY:H,finalOffsetX:he,finalOffsetY:pe})}onUpdate(){if(this.applyConfigStylesAndAttributes(),this.child("web-weaver-embed-inner").style.display=this.attr.open?"":"none",this.child("interaction-bar").style.display=this.attr.open?"":"none",this.child("llm-selector-panel").attr.open=this.state.llmPanelOpen,this.child("pulseanim").style.display=this.attr.open?"none":"",this.child("poweredby").style.display=this.attr.open?"flex":"none",this.child("interaction-bar").attr.layout=this._lastLayout||"widget",this.attr.open&&!this._previousOpenState)this._uiSessionStartTime=Date.now(),Dr(this.ai,{event_type:"ui_open",event_properties:{trigger:"button_click"}});else if(!this.attr.open&&this._previousOpenState){let l=this._uiSessionStartTime?Date.now()-this._uiSessionStartTime:0;Dr(this.ai,{event_type:"ui_close",event_properties:{trigger:"button_click",session_duration_ms:l}})}this._previousOpenState=this.attr.open;let r=this.child("root");this.attr.open?r.classList.add("open"):r.classList.remove("open"),(this._lastLayout||"widget")==="fullscreen"?(r.classList.add("layout-fullscreen"),this.attr.open||(this.attr.open=!0)):r.classList.remove("layout-fullscreen");let i=this._lastPositioningMode||"fixed",o=this._lastPositionX||"right",s=this._lastPositionY||"bottom",a=this._lastOffsetX!==void 0?this._lastOffsetX:20,c=this._lastOffsetY!==void 0?this._lastOffsetY:20;i==="container"?(r.classList.add("container-mode"),this.attr.open||(this.attr.open=!0)):r.classList.remove("container-mode"),i!=="container"&&(r.style.left="",r.style.right="",r.style.top="",r.style.bottom="",o==="left"?r.style.left=a+"px":r.style.right=a+"px",s==="top"?r.style.top=c+"px":r.style.bottom=c+"px"),this.child("interaction-bar").attr.loading=this.state.loading,this.child("interaction-bar").attr.llmName=this.ai.currentModel?.metadata?.name||this.ai.currentModel?.id||"None",this.child("interaction-bar").attr.llmButtonVisible=this.ai.models.length>1,this.child("llm-selector-panel").state.items=this.ai.models.sort((l,u)=>(u.priority||0)-(l.priority||0)),this.child("llm-selector-panel").state.selectedID=this.ai.currentModel?.id}onDestroy(){ht().embed==this&&(ht().embed=void 0)}onContainerClick(r){let n=this._lastDisplayMode||"closed";(this._lastLayout||"widget")!=="fullscreen"&&n!=="open"&&(this.attr.open||(r.preventDefault(),this.attr.open=!0))}onLogoClick(r){if(r.preventDefault(),r.stopPropagation(),this.attr.focusID)this.attr.focusID="";else{let n=this._lastDisplayMode||"closed";if((this._lastLayout||"widget")==="fullscreen"||n==="open")return;this.attr.open=!this.attr.open}}open(){this.attr.open=!0}close(){this.attr.open=!1}resetConversation(){let r=this.child("web-weaver-embed-inner");for(this.state.llmPanelOpen=!1;r.children.length>0;)r.children[0].remove();this.ai.resetConversation(),this.suggestions=[];let n=document.createElement("div");n.className="introduction-message",n.innerHTML=ht().introductionMessage||`Welcome to <b>${document.title||"Web Weaver"}</b>. How can I help you?`,r.appendChild(n),this.ai.insertAssistantMessage(n.innerText);for(let i of ht().introductionSuggestions||[]){let o=document.createElement("div");o.className="suggestion-button",o.innerText=i,o.addEventListener("click",s=>this.onSuggestionClick(s,i)),r.appendChild(o)}}async processInput(r){if(this._isProcessing)return;this._isProcessing=!0,this.state.loading=!0,this.state.llmPanelOpen=!1;let n=this.child("web-weaver-embed-inner");this.suggestions=[];try{for(let a of Array.from(n.querySelectorAll(".suggestion-button")))a.remove();this.attr.focusID="";let i=document.createElement("div");i.className="input",i.innerText=r,n.appendChild(i);let o=this.currentOutputElement;this.currentOutputElement=document.createElement("div"),this.currentOutputElement.className="output-container",n.appendChild(this.currentOutputElement);let s=Math.ceil(n.clientHeight-300);s<0&&(s=0),s>600&&(s=600),o&&(o.style.minHeight=""),this.currentOutputElement.style.minHeight=s+"px",this.currentOutputElement.offsetHeight,this.currentOutputElement.scrollIntoView({behavior:"smooth",block:"start"}),await this.ai.sendMessage(r);for(let a of this.suggestions){let c=document.createElement("div");c.className="suggestion-button",c.innerText=a,c.addEventListener("click",l=>this.onSuggestionClick(l,a)),this.currentOutputElement.appendChild(c)}}catch(i){en.error("Failed to process input:",i);let o=document.createElement("div");o.className="output",o.innerText="Sorry, there was a problem getting a response. "+i.message,n.appendChild(o);let s=document.createElement("div");s.className="suggestion-button",s.innerText="Reset conversation",s.addEventListener("click",a=>this.resetConversation()),n.appendChild(s)}this.state.loading=!1,this._isProcessing=!1}async onAIMessage(r,n){let i=[];for(let o of r)for(let s=0;s<(o.sections?.length||0);s++){let a=o.sections[s],c=`msgelem-${o.id||""}_${s}_${a.type||"unknown"}`;if(c=c.replace(/[^a-zA-Z0-9-_]/g,"_"),a.type=="thinking"){if(!a.text)continue;let l=a.text||"";l.includes(`
895
+ `)&&(l=l.split(`
896
+ `)[0]),this.updateInfoElement(c,l,"thinking-icon"),i.push(c)}else if(a.type=="tool_call"){let u=new zu(r).toolResult(a.toolCallInstanceID||"");if(a.toolCallHiddenInUI!="always"){if(u?.toolErrorResponse)this.updateInfoElement(c,"**Error:** "+u.toolErrorResponse||"","tool-icon"),i.push(c);else if(!(a.toolCallHiddenInUI=="after-complete"&&u))if(a.toolKbID=="search"){let d=a.toolParameters?.query?`**Search:** ${a.toolParameters.query}`:"**Search**";this.updateInfoElement(c,d,"tool-icon"),i.push(c)}else if(a.toolKbID?.startsWith("ask:")&&a.toolParameters?.query){let d=a.toolKbID.substring(4),p=`**Ask ${this.ai.subAgents.subagents.find(h=>h.id===d)?.name||"agent"}:** ${a.toolParameters.query}`;this.updateInfoElement(c,p,"tool-icon"),i.push(c)}else this.updateInfoElement(c,a.toolKbName||"","tool-icon"),i.push(c)}}else if(a.type!="tool_result"){if(!a.text)continue;this.updateTextElement(c,a.text||""),i.push(c)}}for(let o of Array.from(this.currentOutputElement.children))i.includes(o.id)||o.remove()}updateTextElement(r,n){let i=this.currentOutputElement.querySelector(`#${r}`);i||(i=document.createElement("div"),i.id=r,i.className="output",this.currentOutputElement.appendChild(i));let o=q_().use(hm).use(gm).use(nm,{target:"_blank",rel:["noopener","noreferrer"]}).use(im).use(cm).processSync(n||"");i.innerHTML=o.toString("utf-8")}updateInfoElement(r,n,i){let o=this.currentOutputElement.querySelector(`#${r}`);o||(o=document.createElement("div"),o.id=r,o.className="info-block",o.innerHTML=`
897
+ <div class='info-block-icon'></div>
898
+ <div class='info-block-text'></div>
899
+ `,this.currentOutputElement.appendChild(o));let s=q_().use(hm).use(gm).use(nm,{target:"_blank",rel:["noopener","noreferrer"]}).use(im).use(cm).processSync(n||"");o.querySelector(".info-block-icon").className="info-block-icon "+i,o.querySelector(".info-block-text").innerHTML=s.toString("utf-8")}onSuggestionClick(r,n){this.processInput(n)}onLLMModelSelect(r){r.preventDefault(),this.ai.setModel(r.detail),this.state.llmPanelOpen=!1}onContentScroll(r){let n=this.child("fullscreen-header");if(!n)return;let i=r.target.scrollTop,o=0,s=60;if(i<=o)n.style.opacity="1",n.style.pointerEvents="";else if(i>=s)n.style.opacity="0",n.style.pointerEvents="none";else{let a=1-(i-o)/(s-o);n.style.opacity=String(a),n.style.pointerEvents=a<.5?"none":""}}updateBrandingFor(r){if(!r)return;this.root?.querySelectorAll(`.branding-${r}`)?.forEach(i=>{i.classList.add("visible")})}};sc.tagName="intelliweave-embed",sc.observedAttributes=["logo","focusID","open","background","textColor","displayMode","layout","header","positioningMode","positionX","positionY","offsetX","offsetY"];var aCe=sc;fi.lib=()=>import("./ort.bundle.min-4BREXDX3.js");sc.register();export{aCe as default};
900
+ /*! Bundled license information:
901
+
902
+ uri-js/dist/es5/uri.all.js:
903
+ (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *)
904
+ */