askii-cli 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,493 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var kh=Object.create;var ps=Object.defineProperty;var Fh=Object.getOwnPropertyDescriptor;var Ph=Object.getOwnPropertyNames;var Th=Object.getPrototypeOf,Ah=Object.prototype.hasOwnProperty;var J=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Rh=(r,e)=>{for(var t in e)ps(r,t,{get:e[t],enumerable:!0})},Ih=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ph(e))!Ah.call(r,i)&&i!==t&&ps(r,i,{get:()=>e[i],enumerable:!(n=Fh(e,i))||n.enumerable});return r};var Me=(r,e,t)=>(t=r!=null?kh(Th(r)):{},Ih(e||!r||!r.__esModule?ps(t,"default",{value:r,enumerable:!0}):t,r));var ys=J((Zn,gl)=>{(function(r,e){typeof Zn=="object"&&typeof gl<"u"?e(Zn):typeof define=="function"&&define.amd?define(["exports"],e):e(r.WHATWGFetch={})})(Zn,(function(r){"use strict";var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},t={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};function n(w){return w&&DataView.prototype.isPrototypeOf(w)}if(t.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(w){return w&&i.indexOf(Object.prototype.toString.call(w))>-1};function a(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function l(w){return typeof w!="string"&&(w=String(w)),w}function c(w){var C={next:function(){var P=w.shift();return{done:P===void 0,value:P}}};return t.iterable&&(C[Symbol.iterator]=function(){return C}),C}function u(w){this.map={},w instanceof u?w.forEach(function(C,P){this.append(P,C)},this):Array.isArray(w)?w.forEach(function(C){if(C.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+C.length);this.append(C[0],C[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(C){this.append(C,w[C])},this)}u.prototype.append=function(w,C){w=a(w),C=l(C);var P=this.map[w];this.map[w]=P?P+", "+C:C},u.prototype.delete=function(w){delete this.map[a(w)]},u.prototype.get=function(w){return w=a(w),this.has(w)?this.map[w]:null},u.prototype.has=function(w){return this.map.hasOwnProperty(a(w))},u.prototype.set=function(w,C){this.map[a(w)]=l(C)},u.prototype.forEach=function(w,C){for(var P in this.map)this.map.hasOwnProperty(P)&&w.call(C,this.map[P],P,this)},u.prototype.keys=function(){var w=[];return this.forEach(function(C,P){w.push(P)}),c(w)},u.prototype.values=function(){var w=[];return this.forEach(function(C){w.push(C)}),c(w)},u.prototype.entries=function(){var w=[];return this.forEach(function(C,P){w.push([P,C])}),c(w)},t.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function h(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function f(w){return new Promise(function(C,P){w.onload=function(){C(w.result)},w.onerror=function(){P(w.error)}})}function d(w){var C=new FileReader,P=f(C);return C.readAsArrayBuffer(w),P}function p(w){var C=new FileReader,P=f(C),U=/charset=([A-Za-z0-9_-]+)/.exec(w.type),Z=U?U[1]:"utf-8";return C.readAsText(w,Z),P}function m(w){for(var C=new Uint8Array(w),P=new Array(C.length),U=0;U<C.length;U++)P[U]=String.fromCharCode(C[U]);return P.join("")}function g(w){if(w.slice)return w.slice(0);var C=new Uint8Array(w.byteLength);return C.set(new Uint8Array(w)),C.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:t.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:t.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():t.arrayBuffer&&t.blob&&n(w)?(this._bodyArrayBuffer=g(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):t.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||o(w))?this._bodyArrayBuffer=g(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var w=h(this);if(w)return w;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var w=h(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(t.blob)return this.blob().then(d);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=h(this);if(w)return w;if(this._bodyBlob)return p(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(m(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},t.formData&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}var y=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function D(w){var C=w.toUpperCase();return y.indexOf(C)>-1?C:w}function v(w,C){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');C=C||{};var P=C.body;if(w instanceof v){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,C.headers||(this.headers=new u(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!P&&w._bodyInit!=null&&(P=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=C.credentials||this.credentials||"same-origin",(C.headers||!this.headers)&&(this.headers=new u(C.headers)),this.method=D(C.method||this.method||"GET"),this.mode=C.mode||this.mode||null,this.signal=C.signal||this.signal||(function(){if("AbortController"in e){var q=new AbortController;return q.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&P)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(P),(this.method==="GET"||this.method==="HEAD")&&(C.cache==="no-store"||C.cache==="no-cache")){var U=/([?&])_=[^&]*/;if(U.test(this.url))this.url=this.url.replace(U,"$1_="+new Date().getTime());else{var Z=/\?/;this.url+=(Z.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})};function S(w){var C=new FormData;return w.trim().split("&").forEach(function(P){if(P){var U=P.split("="),Z=U.shift().replace(/\+/g," "),q=U.join("=").replace(/\+/g," ");C.append(decodeURIComponent(Z),decodeURIComponent(q))}}),C}function E(w){var C=new u,P=w.replace(/\r?\n[\t ]+/g," ");return P.split("\r").map(function(U){return U.indexOf(`
3
+ `)===0?U.substr(1,U.length):U}).forEach(function(U){var Z=U.split(":"),q=Z.shift().trim();if(q){var Ce=Z.join(":").trim();try{C.append(q,Ce)}catch(ge){console.warn("Response "+ge.message)}}}),C}b.call(v.prototype);function k(w,C){if(!(this instanceof k))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(C||(C={}),this.type="default",this.status=C.status===void 0?200:C.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=C.statusText===void 0?"":""+C.statusText,this.headers=new u(C.headers),this.url=C.url||"",this._initBody(w)}b.call(k.prototype),k.prototype.clone=function(){return new k(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},k.error=function(){var w=new k(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var x=[301,302,303,307,308];k.redirect=function(w,C){if(x.indexOf(C)===-1)throw new RangeError("Invalid status code");return new k(null,{status:C,headers:{location:w}})},r.DOMException=e.DOMException;try{new r.DOMException}catch{r.DOMException=function(C,P){this.message=C,this.name=P;var U=Error(C);this.stack=U.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function z(w,C){return new Promise(function(P,U){var Z=new v(w,C);if(Z.signal&&Z.signal.aborted)return U(new r.DOMException("Aborted","AbortError"));var q=new XMLHttpRequest;function Ce(){q.abort()}q.onload=function(){var Q={statusText:q.statusText,headers:E(q.getAllResponseHeaders()||"")};Z.url.indexOf("file://")===0&&(q.status<200||q.status>599)?Q.status=200:Q.status=q.status,Q.url="responseURL"in q?q.responseURL:Q.headers.get("X-Request-URL");var ke="response"in q?q.response:q.responseText;setTimeout(function(){P(new k(ke,Q))},0)},q.onerror=function(){setTimeout(function(){U(new TypeError("Network request failed"))},0)},q.ontimeout=function(){setTimeout(function(){U(new TypeError("Network request timed out"))},0)},q.onabort=function(){setTimeout(function(){U(new r.DOMException("Aborted","AbortError"))},0)};function ge(Q){try{return Q===""&&e.location.href?e.location.href:Q}catch{return Q}}if(q.open(Z.method,ge(Z.url),!0),Z.credentials==="include"?q.withCredentials=!0:Z.credentials==="omit"&&(q.withCredentials=!1),"responseType"in q&&(t.blob?q.responseType="blob":t.arrayBuffer&&(q.responseType="arraybuffer")),C&&typeof C.headers=="object"&&!(C.headers instanceof u||e.Headers&&C.headers instanceof e.Headers)){var ye=[];Object.getOwnPropertyNames(C.headers).forEach(function(Q){ye.push(a(Q)),q.setRequestHeader(Q,l(C.headers[Q]))}),Z.headers.forEach(function(Q,ke){ye.indexOf(ke)===-1&&q.setRequestHeader(ke,Q)})}else Z.headers.forEach(function(Q,ke){q.setRequestHeader(ke,Q)});Z.signal&&(Z.signal.addEventListener("abort",Ce),q.onreadystatechange=function(){q.readyState===4&&Z.signal.removeEventListener("abort",Ce)}),q.send(typeof Z._bodyInit>"u"?null:Z._bodyInit)})}z.polyfill=!0,e.fetch||(e.fetch=z,e.Headers=u,e.Request=v,e.Response=k),r.Headers=u,r.Request=v,r.Response=k,r.fetch=z,Object.defineProperty(r,"__esModule",{value:!0})}))});var Al=J((Zw,Tl)=>{"use strict";Tl.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Ts=J((Gw,Il)=>{var nn=Al(),Rl={};for(let r of Object.keys(nn))Rl[nn[r]]=r;var M={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Il.exports=M;for(let r of Object.keys(M)){if(!("channels"in M[r]))throw new Error("missing channels property: "+r);if(!("labels"in M[r]))throw new Error("missing channel labels property: "+r);if(M[r].labels.length!==M[r].channels)throw new Error("channel and label counts mismatch: "+r);let{channels:e,labels:t}=M[r];delete M[r].channels,delete M[r].labels,Object.defineProperty(M[r],"channels",{value:e}),Object.defineProperty(M[r],"labels",{value:t})}M.rgb.hsl=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.min(e,t,n),o=Math.max(e,t,n),a=o-i,l,c;o===i?l=0:e===o?l=(t-n)/a:t===o?l=2+(n-e)/a:n===o&&(l=4+(e-t)/a),l=Math.min(l*60,360),l<0&&(l+=360);let u=(i+o)/2;return o===i?c=0:u<=.5?c=a/(o+i):c=a/(2-o-i),[l,c*100,u*100]};M.rgb.hsv=function(r){let e,t,n,i,o,a=r[0]/255,l=r[1]/255,c=r[2]/255,u=Math.max(a,l,c),h=u-Math.min(a,l,c),f=function(d){return(u-d)/6/h+1/2};return h===0?(i=0,o=0):(o=h/u,e=f(a),t=f(l),n=f(c),a===u?i=n-t:l===u?i=1/3+e-n:c===u&&(i=2/3+t-e),i<0?i+=1:i>1&&(i-=1)),[i*360,o*100,u*100]};M.rgb.hwb=function(r){let e=r[0],t=r[1],n=r[2],i=M.rgb.hsl(r)[0],o=1/255*Math.min(e,Math.min(t,n));return n=1-1/255*Math.max(e,Math.max(t,n)),[i,o*100,n*100]};M.rgb.cmyk=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.min(1-e,1-t,1-n),o=(1-e-i)/(1-i)||0,a=(1-t-i)/(1-i)||0,l=(1-n-i)/(1-i)||0;return[o*100,a*100,l*100,i*100]};function tm(r,e){return(r[0]-e[0])**2+(r[1]-e[1])**2+(r[2]-e[2])**2}M.rgb.keyword=function(r){let e=Rl[r];if(e)return e;let t=1/0,n;for(let i of Object.keys(nn)){let o=nn[i],a=tm(r,o);a<t&&(t=a,n=i)}return n};M.keyword.rgb=function(r){return nn[r]};M.rgb.xyz=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let i=e*.4124+t*.3576+n*.1805,o=e*.2126+t*.7152+n*.0722,a=e*.0193+t*.1192+n*.9505;return[i*100,o*100,a*100]};M.rgb.lab=function(r){let e=M.rgb.xyz(r),t=e[0],n=e[1],i=e[2];t/=95.047,n/=100,i/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;let o=116*n-16,a=500*(t-n),l=200*(n-i);return[o,a,l]};M.hsl.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100,i,o,a;if(t===0)return a=n*255,[a,a,a];n<.5?i=n*(1+t):i=n+t-n*t;let l=2*n-i,c=[0,0,0];for(let u=0;u<3;u++)o=e+1/3*-(u-1),o<0&&o++,o>1&&o--,6*o<1?a=l+(i-l)*6*o:2*o<1?a=i:3*o<2?a=l+(i-l)*(2/3-o)*6:a=l,c[u]=a*255;return c};M.hsl.hsv=function(r){let e=r[0],t=r[1]/100,n=r[2]/100,i=t,o=Math.max(n,.01);n*=2,t*=n<=1?n:2-n,i*=o<=1?o:2-o;let a=(n+t)/2,l=n===0?2*i/(o+i):2*t/(n+t);return[e,l*100,a*100]};M.hsv.rgb=function(r){let e=r[0]/60,t=r[1]/100,n=r[2]/100,i=Math.floor(e)%6,o=e-Math.floor(e),a=255*n*(1-t),l=255*n*(1-t*o),c=255*n*(1-t*(1-o));switch(n*=255,i){case 0:return[n,c,a];case 1:return[l,n,a];case 2:return[a,n,c];case 3:return[a,l,n];case 4:return[c,a,n];case 5:return[n,a,l]}};M.hsv.hsl=function(r){let e=r[0],t=r[1]/100,n=r[2]/100,i=Math.max(n,.01),o,a;a=(2-t)*n;let l=(2-t)*i;return o=t*i,o/=l<=1?l:2-l,o=o||0,a/=2,[e,o*100,a*100]};M.hwb.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100,i=t+n,o;i>1&&(t/=i,n/=i);let a=Math.floor(6*e),l=1-n;o=6*e-a,(a&1)!==0&&(o=1-o);let c=t+o*(l-t),u,h,f;switch(a){default:case 6:case 0:u=l,h=c,f=t;break;case 1:u=c,h=l,f=t;break;case 2:u=t,h=l,f=c;break;case 3:u=t,h=c,f=l;break;case 4:u=c,h=t,f=l;break;case 5:u=l,h=t,f=c;break}return[u*255,h*255,f*255]};M.cmyk.rgb=function(r){let e=r[0]/100,t=r[1]/100,n=r[2]/100,i=r[3]/100,o=1-Math.min(1,e*(1-i)+i),a=1-Math.min(1,t*(1-i)+i),l=1-Math.min(1,n*(1-i)+i);return[o*255,a*255,l*255]};M.xyz.rgb=function(r){let e=r[0]/100,t=r[1]/100,n=r[2]/100,i,o,a;return i=e*3.2406+t*-1.5372+n*-.4986,o=e*-.9689+t*1.8758+n*.0415,a=e*.0557+t*-.204+n*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,i=Math.min(Math.max(0,i),1),o=Math.min(Math.max(0,o),1),a=Math.min(Math.max(0,a),1),[i*255,o*255,a*255]};M.xyz.lab=function(r){let e=r[0],t=r[1],n=r[2];e/=95.047,t/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let i=116*t-16,o=500*(e-t),a=200*(t-n);return[i,o,a]};M.lab.xyz=function(r){let e=r[0],t=r[1],n=r[2],i,o,a;o=(e+16)/116,i=t/500+o,a=o-n/200;let l=o**3,c=i**3,u=a**3;return o=l>.008856?l:(o-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,a=u>.008856?u:(a-16/116)/7.787,i*=95.047,o*=100,a*=108.883,[i,o,a]};M.lab.lch=function(r){let e=r[0],t=r[1],n=r[2],i;i=Math.atan2(n,t)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(t*t+n*n);return[e,a,i]};M.lch.lab=function(r){let e=r[0],t=r[1],i=r[2]/360*2*Math.PI,o=t*Math.cos(i),a=t*Math.sin(i);return[e,o,a]};M.rgb.ansi16=function(r,e=null){let[t,n,i]=r,o=e===null?M.rgb.hsv(r)[2]:e;if(o=Math.round(o/50),o===0)return 30;let a=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return o===2&&(a+=60),a};M.hsv.ansi16=function(r){return M.rgb.ansi16(M.hsv.rgb(r),r[2])};M.rgb.ansi256=function(r){let e=r[0],t=r[1],n=r[2];return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)};M.ansi16.rgb=function(r){let e=r%10;if(e===0||e===7)return r>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let t=(~~(r>50)+1)*.5,n=(e&1)*t*255,i=(e>>1&1)*t*255,o=(e>>2&1)*t*255;return[n,i,o]};M.ansi256.rgb=function(r){if(r>=232){let o=(r-232)*10+8;return[o,o,o]}r-=16;let e,t=Math.floor(r/36)/5*255,n=Math.floor((e=r%36)/6)/5*255,i=e%6/5*255;return[t,n,i]};M.rgb.hex=function(r){let t=(((Math.round(r[0])&255)<<16)+((Math.round(r[1])&255)<<8)+(Math.round(r[2])&255)).toString(16).toUpperCase();return"000000".substring(t.length)+t};M.hex.rgb=function(r){let e=r.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let t=e[0];e[0].length===3&&(t=t.split("").map(l=>l+l).join(""));let n=parseInt(t,16),i=n>>16&255,o=n>>8&255,a=n&255;return[i,o,a]};M.rgb.hcg=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.max(Math.max(e,t),n),o=Math.min(Math.min(e,t),n),a=i-o,l,c;return a<1?l=o/(1-a):l=0,a<=0?c=0:i===e?c=(t-n)/a%6:i===t?c=2+(n-e)/a:c=4+(e-t)/a,c/=6,c%=1,[c*360,a*100,l*100]};M.hsl.hcg=function(r){let e=r[1]/100,t=r[2]/100,n=t<.5?2*e*t:2*e*(1-t),i=0;return n<1&&(i=(t-.5*n)/(1-n)),[r[0],n*100,i*100]};M.hsv.hcg=function(r){let e=r[1]/100,t=r[2]/100,n=e*t,i=0;return n<1&&(i=(t-n)/(1-n)),[r[0],n*100,i*100]};M.hcg.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100;if(t===0)return[n*255,n*255,n*255];let i=[0,0,0],o=e%1*6,a=o%1,l=1-a,c=0;switch(Math.floor(o)){case 0:i[0]=1,i[1]=a,i[2]=0;break;case 1:i[0]=l,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=a;break;case 3:i[0]=0,i[1]=l,i[2]=1;break;case 4:i[0]=a,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=l}return c=(1-t)*n,[(t*i[0]+c)*255,(t*i[1]+c)*255,(t*i[2]+c)*255]};M.hcg.hsv=function(r){let e=r[1]/100,t=r[2]/100,n=e+t*(1-e),i=0;return n>0&&(i=e/n),[r[0],i*100,n*100]};M.hcg.hsl=function(r){let e=r[1]/100,n=r[2]/100*(1-e)+.5*e,i=0;return n>0&&n<.5?i=e/(2*n):n>=.5&&n<1&&(i=e/(2*(1-n))),[r[0],i*100,n*100]};M.hcg.hwb=function(r){let e=r[1]/100,t=r[2]/100,n=e+t*(1-e);return[r[0],(n-e)*100,(1-n)*100]};M.hwb.hcg=function(r){let e=r[1]/100,n=1-r[2]/100,i=n-e,o=0;return i<1&&(o=(n-i)/(1-i)),[r[0],i*100,o*100]};M.apple.rgb=function(r){return[r[0]/65535*255,r[1]/65535*255,r[2]/65535*255]};M.rgb.apple=function(r){return[r[0]/255*65535,r[1]/255*65535,r[2]/255*65535]};M.gray.rgb=function(r){return[r[0]/100*255,r[0]/100*255,r[0]/100*255]};M.gray.hsl=function(r){return[0,0,r[0]]};M.gray.hsv=M.gray.hsl;M.gray.hwb=function(r){return[0,100,r[0]]};M.gray.cmyk=function(r){return[0,0,0,r[0]]};M.gray.lab=function(r){return[r[0],0,0]};M.gray.hex=function(r){let e=Math.round(r[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};M.rgb.gray=function(r){return[(r[0]+r[1]+r[2])/3/255*100]}});var Ml=J((Kw,Ol)=>{var Qn=Ts();function rm(){let r={},e=Object.keys(Qn);for(let t=e.length,n=0;n<t;n++)r[e[n]]={distance:-1,parent:null};return r}function nm(r){let e=rm(),t=[r];for(e[r].distance=0;t.length;){let n=t.pop(),i=Object.keys(Qn[n]);for(let o=i.length,a=0;a<o;a++){let l=i[a],c=e[l];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,t.unshift(l))}}return e}function im(r,e){return function(t){return e(r(t))}}function sm(r,e){let t=[e[r].parent,r],n=Qn[e[r].parent][r],i=e[r].parent;for(;e[i].parent;)t.unshift(e[i].parent),n=im(Qn[e[i].parent][i],n),i=e[i].parent;return n.conversion=t,n}Ol.exports=function(r){let e=nm(r),t={},n=Object.keys(e);for(let i=n.length,o=0;o<i;o++){let a=n[o];e[a].parent!==null&&(t[a]=sm(a,e))}return t}});var Bl=J((Hw,jl)=>{var As=Ts(),om=Ml(),xr={},am=Object.keys(As);function lm(r){let e=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),r(t))};return"conversion"in r&&(e.conversion=r.conversion),e}function cm(r){let e=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let i=r(t);if(typeof i=="object")for(let o=i.length,a=0;a<o;a++)i[a]=Math.round(i[a]);return i};return"conversion"in r&&(e.conversion=r.conversion),e}am.forEach(r=>{xr[r]={},Object.defineProperty(xr[r],"channels",{value:As[r].channels}),Object.defineProperty(xr[r],"labels",{value:As[r].labels});let e=om(r);Object.keys(e).forEach(n=>{let i=e[n];xr[r][n]=cm(i),xr[r][n].raw=lm(i)})});jl.exports=xr});var ql=J((Jw,zl)=>{"use strict";var Ll=(r,e)=>(...t)=>`\x1B[${r(...t)+e}m`,Nl=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};5;${n}m`},$l=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},Xn=r=>r,Ul=(r,e,t)=>[r,e,t],kr=(r,e,t)=>{Object.defineProperty(r,e,{get:()=>{let n=t();return Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},Rs,Fr=(r,e,t,n)=>{Rs===void 0&&(Rs=Bl());let i=n?10:0,o={};for(let[a,l]of Object.entries(Rs)){let c=a==="ansi16"?"ansi":a;a===e?o[c]=r(t,i):typeof l=="object"&&(o[c]=r(l[e],i))}return o};function um(){let r=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,n]of Object.entries(e)){for(let[i,o]of Object.entries(n))e[i]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[i]=e[i],r.set(o[0],o[1]);Object.defineProperty(e,t,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:r,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",kr(e.color,"ansi",()=>Fr(Ll,"ansi16",Xn,!1)),kr(e.color,"ansi256",()=>Fr(Nl,"ansi256",Xn,!1)),kr(e.color,"ansi16m",()=>Fr($l,"rgb",Ul,!1)),kr(e.bgColor,"ansi",()=>Fr(Ll,"ansi16",Xn,!0)),kr(e.bgColor,"ansi256",()=>Fr(Nl,"ansi256",Xn,!0)),kr(e.bgColor,"ansi16m",()=>Fr($l,"rgb",Ul,!0)),e}Object.defineProperty(zl,"exports",{enumerable:!0,get:um})});var Wl=J((Yw,Vl)=>{"use strict";Vl.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Kl=J((Qw,Gl)=>{"use strict";var dm=require("os"),Zl=require("tty"),Ae=Wl(),{env:se}=process,Ct;Ae("no-color")||Ae("no-colors")||Ae("color=false")||Ae("color=never")?Ct=0:(Ae("color")||Ae("colors")||Ae("color=true")||Ae("color=always"))&&(Ct=1);"FORCE_COLOR"in se&&(se.FORCE_COLOR==="true"?Ct=1:se.FORCE_COLOR==="false"?Ct=0:Ct=se.FORCE_COLOR.length===0?1:Math.min(parseInt(se.FORCE_COLOR,10),3));function Is(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Os(r,e){if(Ct===0)return 0;if(Ae("color=16m")||Ae("color=full")||Ae("color=truecolor"))return 3;if(Ae("color=256"))return 2;if(r&&!e&&Ct===void 0)return 0;let t=Ct||0;if(se.TERM==="dumb")return t;if(process.platform==="win32"){let n=dm.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in se)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in se)||se.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in se)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(se.TEAMCITY_VERSION)?1:0;if(se.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in se){let n=parseInt((se.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(se.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(se.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(se.TERM)||"COLORTERM"in se?1:t}function fm(r){let e=Os(r,r&&r.isTTY);return Is(e)}Gl.exports={supportsColor:fm,stdout:Is(Os(!0,Zl.isatty(1))),stderr:Is(Os(!0,Zl.isatty(2)))}});var Jl=J((Xw,Hl)=>{"use strict";var hm=(r,e,t)=>{let n=r.indexOf(e);if(n===-1)return r;let i=e.length,o=0,a="";do a+=r.substr(o,n-o)+e+t,o=n+i,n=r.indexOf(e,o);while(n!==-1);return a+=r.substr(o),a},pm=(r,e,t,n)=>{let i=0,o="";do{let a=r[n-1]==="\r";o+=r.substr(i,(a?n-1:n)-i)+e+(a?`\r
4
+ `:`
5
+ `)+t,i=n+1,n=r.indexOf(`
6
+ `,i)}while(n!==-1);return o+=r.substr(i),o};Hl.exports={stringReplaceAll:hm,stringEncaseCRLFWithFirstIndex:pm}});var tc=J((e1,ec)=>{"use strict";var mm=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,Yl=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,gm=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,ym=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,bm=new Map([["n",`
7
+ `],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function Xl(r){let e=r[0]==="u",t=r[1]==="{";return e&&!t&&r.length===5||r[0]==="x"&&r.length===3?String.fromCharCode(parseInt(r.slice(1),16)):e&&t?String.fromCodePoint(parseInt(r.slice(2,-1),16)):bm.get(r)||r}function vm(r,e){let t=[],n=e.trim().split(/\s*,\s*/g),i;for(let o of n){let a=Number(o);if(!Number.isNaN(a))t.push(a);else if(i=o.match(gm))t.push(i[2].replace(ym,(l,c,u)=>c?Xl(c):u));else throw new Error(`Invalid Chalk template style argument: ${o} (in style '${r}')`)}return t}function Dm(r){Yl.lastIndex=0;let e=[],t;for(;(t=Yl.exec(r))!==null;){let n=t[1];if(t[2]){let i=vm(n,t[2]);e.push([n].concat(i))}else e.push([n])}return e}function Ql(r,e){let t={};for(let i of e)for(let o of i.styles)t[o[0]]=i.inverse?null:o.slice(1);let n=r;for(let[i,o]of Object.entries(t))if(Array.isArray(o)){if(!(i in n))throw new Error(`Unknown Chalk style: ${i}`);n=o.length>0?n[i](...o):n[i]}return n}ec.exports=(r,e)=>{let t=[],n=[],i=[];if(e.replace(mm,(o,a,l,c,u,h)=>{if(a)i.push(Xl(a));else if(c){let f=i.join("");i=[],n.push(t.length===0?f:Ql(r,t)(f)),t.push({inverse:l,styles:Dm(c)})}else if(u){if(t.length===0)throw new Error("Found extraneous } in Chalk template literal");n.push(Ql(r,t)(i.join(""))),i=[],t.pop()}else i.push(h)}),n.push(i.join("")),t.length>0){let o=`Chalk template literal is missing ${t.length} closing bracket${t.length===1?"":"s"} (\`}\`)`;throw new Error(o)}return n.join("")}});var lc=J((t1,ac)=>{"use strict";var sn=ql(),{stdout:js,stderr:Bs}=Kl(),{stringReplaceAll:wm,stringEncaseCRLFWithFirstIndex:Sm}=Jl(),{isArray:ei}=Array,nc=["ansi","ansi","ansi256","ansi16m"],Pr=Object.create(null),Cm=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=js?js.level:0;r.level=e.level===void 0?t:e.level},Ls=class{constructor(e){return ic(e)}},ic=r=>{let e={};return Cm(e,r),e.template=(...t)=>oc(e.template,...t),Object.setPrototypeOf(e,ti.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=Ls,e.template};function ti(r){return ic(r)}for(let[r,e]of Object.entries(sn))Pr[r]={get(){let t=ri(this,Ns(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,r,{value:t}),t}};Pr.visible={get(){let r=ri(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:r}),r}};var sc=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let r of sc)Pr[r]={get(){let{level:e}=this;return function(...t){let n=Ns(sn.color[nc[e]][r](...t),sn.color.close,this._styler);return ri(this,n,this._isEmpty)}}};for(let r of sc){let e="bg"+r[0].toUpperCase()+r.slice(1);Pr[e]={get(){let{level:t}=this;return function(...n){let i=Ns(sn.bgColor[nc[t]][r](...n),sn.bgColor.close,this._styler);return ri(this,i,this._isEmpty)}}}}var Em=Object.defineProperties(()=>{},{...Pr,level:{enumerable:!0,get(){return this._generator.level},set(r){this._generator.level=r}}}),Ns=(r,e,t)=>{let n,i;return t===void 0?(n=r,i=e):(n=t.openAll+r,i=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:i,parent:t}},ri=(r,e,t)=>{let n=(...i)=>ei(i[0])&&ei(i[0].raw)?rc(n,oc(n,...i)):rc(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,Em),n._generator=r,n._styler=e,n._isEmpty=t,n},rc=(r,e)=>{if(r.level<=0||!e)return r._isEmpty?"":e;let t=r._styler;if(t===void 0)return e;let{openAll:n,closeAll:i}=t;if(e.indexOf("\x1B")!==-1)for(;t!==void 0;)e=wm(e,t.close,t.open),t=t.parent;let o=e.indexOf(`
8
+ `);return o!==-1&&(e=Sm(e,i,n,o)),n+e+i},Ms,oc=(r,...e)=>{let[t]=e;if(!ei(t)||!ei(t.raw))return e.join(" ");let n=e.slice(1),i=[t.raw[0]];for(let o=1;o<t.length;o++)i.push(String(n[o-1]).replace(/[{}\\]/g,"\\$&"),String(t.raw[o]));return Ms===void 0&&(Ms=tc()),Ms(r,i.join(""))};Object.defineProperties(ti.prototype,Pr);var ni=ti();ni.supportsColor=js;ni.stderr=ti({level:Bs?Bs.level:0});ni.stderr.supportsColor=Bs;ac.exports=ni});var cc=J($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.generateRandomBase64=xm;var _m=require("crypto");function xm(r=18){return(0,_m.randomBytes)(r).toString("base64")}});var uc=J(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.readFileAsBase64=Fm;var km=require("fs/promises");async function Fm(r){return{success:!0,base64:await(0,km.readFile)(r,"base64")}}});var mc=J(on=>{"use strict";var Vs=on&&on.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(on,"__esModule",{value:!0});on.terminalSize=Am;var Pm=require("child_process"),ii=Vs(require("fs")),Tr=Vs(require("process")),Tm=Vs(require("tty")),fc=80,hc=24,qs=(r,e,{shell:t,env:n}={})=>(0,Pm.execFileSync)(r,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500,shell:t,env:n}).trim(),si=(r,e)=>({columns:Number.parseInt(r,10),rows:Number.parseInt(e,10)}),pc=(r,e)=>{let{columns:t,rows:n}=si(r,e);if(!(Number.isNaN(t)||Number.isNaN(n))&&!(t===fc&&n===hc))return{columns:t,rows:n}};function Am(){let{env:r,stdout:e,stderr:t}=Tr.default;if(e?.columns&&e?.rows)return si(e.columns,e.rows);if(t?.columns&&t?.rows)return si(t.columns,t.rows);if(r.COLUMNS&&r.LINES)return si(r.COLUMNS,r.LINES);let n={columns:fc,rows:hc};return Tr.default.platform==="win32"?zs()??n:Tr.default.platform==="darwin"?dc()??zs()??n:dc()??zs()??Rm()??n}var dc=()=>{try{let r=Tr.default.platform==="darwin"?ii.default.constants.O_EVTONLY|ii.default.constants.O_NONBLOCK:ii.default.constants.O_NONBLOCK,{columns:e,rows:t}=Tm.default.WriteStream(ii.default.openSync("/dev/tty",r));return{columns:e,rows:t}}catch{}},zs=()=>{try{let r=qs("tput",["cols"],{env:{TERM:"dumb",...Tr.default.env}}),e=qs("tput",["lines"],{env:{TERM:"dumb",...Tr.default.env}});if(r&&e)return pc(r,e)}catch{}},Rm=()=>{try{let r=qs("resize",["-u"]).match(/\d+/g);if(r.length===2)return pc(r[0],r[1])}catch{}}});var it=J((s1,bc)=>{"use strict";var gc=["nodebuffer","arraybuffer","fragments"],yc=typeof Blob<"u";yc&&gc.push("blob");bc.exports={BINARY_TYPES:gc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:yc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var an=J((o1,oi)=>{"use strict";var{EMPTY_BUFFER:Im}=it(),Ws=Buffer[Symbol.species];function Om(r,e){if(r.length===0)return Im;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let i=0;i<r.length;i++){let o=r[i];t.set(o,n),n+=o.length}return n<e?new Ws(t.buffer,t.byteOffset,n):t}function vc(r,e,t,n,i){for(let o=0;o<i;o++)t[n+o]=r[o]^e[o&3]}function Dc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Mm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Zs(r){if(Zs.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ws(r):ArrayBuffer.isView(r)?e=new Ws(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Zs.readOnly=!1),e}oi.exports={concat:Om,mask:vc,toArrayBuffer:Mm,toBuffer:Zs,unmask:Dc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");oi.exports.mask=function(e,t,n,i,o){o<48?vc(e,t,n,i,o):r.mask(e,t,n,i,o)},oi.exports.unmask=function(e,t){e.length<32?Dc(e,t):r.unmask(e,t)}}catch{}});var Cc=J((a1,Sc)=>{"use strict";var wc=Symbol("kDone"),Gs=Symbol("kRun"),Ks=class{constructor(e){this[wc]=()=>{this.pending--,this[Gs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Gs]()}[Gs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wc])}}};Sc.exports=Ks});var cn=J((l1,kc)=>{"use strict";var ln=require("zlib"),Ec=an(),jm=Cc(),{kStatusCode:_c}=it(),Bm=Buffer[Symbol.species],Lm=Buffer.from([0,0,255,255]),li=Symbol("permessage-deflate"),st=Symbol("total-length"),Ar=Symbol("callback"),Et=Symbol("buffers"),Rr=Symbol("error"),ai,Hs=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ai){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ai=new jm(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Ar];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(i=>!(t.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>i.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let i=t[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=i})}),e}decompress(e,t,n){ai.add(i=>{this._decompress(e,t,(o,a)=>{i(),n(o,a)})})}compress(e,t,n){ai.add(i=>{this._compress(e,t,(o,a)=>{i(),n(o,a)})})}_decompress(e,t,n){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?ln.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=ln.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[li]=this,this._inflate[st]=0,this._inflate[Et]=[],this._inflate.on("error",$m),this._inflate.on("data",xc)}this._inflate[Ar]=n,this._inflate.write(e),t&&this._inflate.write(Lm),this._inflate.flush(()=>{let o=this._inflate[Rr];if(o){this._inflate.close(),this._inflate=null,n(o);return}let a=Ec.concat(this._inflate[Et],this._inflate[st]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[st]=0,this._inflate[Et]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?ln.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=ln.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[st]=0,this._deflate[Et]=[],this._deflate.on("data",Nm)}this._deflate[Ar]=n,this._deflate.write(e),this._deflate.flush(ln.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Ec.concat(this._deflate[Et],this._deflate[st]);t&&(o=new Bm(o.buffer,o.byteOffset,o.length-4)),this._deflate[Ar]=null,this._deflate[st]=0,this._deflate[Et]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};kc.exports=Hs;function Nm(r){this[Et].push(r),this[st]+=r.length}function xc(r){if(this[st]+=r.length,this[li]._maxPayload<1||this[st]<=this[li]._maxPayload){this[Et].push(r);return}this[Rr]=new RangeError("Max payload size exceeded"),this[Rr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Rr][_c]=1009,this.removeListener("data",xc),this.reset()}function $m(r){if(this[li]._inflate=null,this[Rr]){this[Ar](this[Rr]);return}r[_c]=1007,this[Ar](r)}});var Ir=J((c1,ci)=>{"use strict";var{isUtf8:Fc}=require("buffer"),{hasBlob:Um}=it(),zm=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function qm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Js(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Vm(r){return Um&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}ci.exports={isBlob:Vm,isValidStatusCode:qm,isValidUTF8:Js,tokenChars:zm};if(Fc)ci.exports.isValidUTF8=function(r){return r.length<24?Js(r):Fc(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");ci.exports.isValidUTF8=function(e){return e.length<32?Js(e):r(e)}}catch{}});var to=J((u1,Mc)=>{"use strict";var{Writable:Wm}=require("stream"),Pc=cn(),{BINARY_TYPES:Zm,EMPTY_BUFFER:Tc,kStatusCode:Gm,kWebSocket:Km}=it(),{concat:Ys,toArrayBuffer:Hm,unmask:Jm}=an(),{isValidStatusCode:Ym,isValidUTF8:Ac}=Ir(),ui=Buffer[Symbol.species],Re=0,Rc=1,Ic=2,Oc=3,Qs=4,Xs=5,di=6,eo=class extends Wm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Zm[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Km]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Re}_write(e,t,n){if(this._opcode===8&&this._state==Re)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new ui(n.buffer,n.byteOffset+e,n.length-e),new ui(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=t.length-e;e>=n.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new ui(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Re:this.getInfo(e);break;case Rc:this.getPayloadLength16(e);break;case Ic:this.getPayloadLength64(e);break;case Oc:this.getMask();break;case Qs:this.getData(e);break;case Xs:case di:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(t[0]&64)===64;if(n&&!this._extensions[Pc.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Rc:this._payloadLength===127?this._state=Ic:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Oc:this._state=Qs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Qs}getData(e){let t=Tc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Jm(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Xs,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Pc.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return t(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(o)}this.dataMessage(t),this._state===Re&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Re;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ys(n,t):this._binaryType==="arraybuffer"?i=Hm(Ys(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Re):(this._state=di,setImmediate(()=>{this.emit("message",i,!0),this._state=Re,this.startLoop(e)}))}else{let i=Ys(n,t);if(!this._skipUTF8Validation&&!Ac(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Xs||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Re):(this._state=di,setImmediate(()=>{this.emit("message",i,!1),this._state=Re,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Tc),this.end();else{let n=e.readUInt16BE(0);if(!Ym(n)){let o=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(o);return}let i=new ui(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ac(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Re;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Re):(this._state=di,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Re,this.startLoop(t)}))}createError(e,t,n,i,o){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=o,a[Gm]=i,a}};Mc.exports=eo});var io=J((f1,Lc)=>{"use strict";var{Duplex:d1}=require("stream"),{randomFillSync:Qm}=require("crypto"),jc=cn(),{EMPTY_BUFFER:Xm,kWebSocket:eg,NOOP:tg}=it(),{isBlob:Or,isValidStatusCode:rg}=Ir(),{mask:Bc,toBuffer:Yt}=an(),Ie=Symbol("kByteLength"),ng=Buffer.alloc(4),fi=8*1024,Qt,Mr=fi,Be=0,ig=1,sg=2,ro=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Be,this.onerror=tg,this[eg]=void 0}static frame(e,t){let n,i=!1,o=2,a=!1;t.mask&&(n=t.maskBuffer||ng,t.generateMask?t.generateMask(n):(Mr===fi&&(Qt===void 0&&(Qt=Buffer.alloc(fi)),Qm(Qt,0,fi),Mr=0),n[0]=Qt[Mr++],n[1]=Qt[Mr++],n[2]=Qt[Mr++],n[3]=Qt[Mr++]),a=(n[0]|n[1]|n[2]|n[3])===0,o=6);let l;typeof e=="string"?(!t.mask||a)&&t[Ie]!==void 0?l=t[Ie]:(e=Buffer.from(e),l=e.length):(l=e.length,i=t.mask&&t.readOnly&&!a);let c=l;l>=65536?(o+=8,c=127):l>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?l+o:o);return u[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),t.mask?(u[1]|=128,u[o-4]=n[0],u[o-3]=n[1],u[o-2]=n[2],u[o-1]=n[3],a?[u,e]:i?(Bc(e,n,u,o,l),[u]):(Bc(e,n,e,0,l),[u,e])):[u,e]}close(e,t,n,i){let o;if(e===void 0)o=Xm;else{if(typeof e!="number"||!rg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let l=Buffer.byteLength(t);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+l),o.writeUInt16BE(e,0),typeof t=="string"?o.write(t,2):o.set(t,2)}}let a={[Ie]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(r.frame(o,a),i)}ping(e,t,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Or(e)?(i=e.size,o=!1):(e=Yt(e),i=e.length,o=Yt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Ie]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Or(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Or(e)?(i=e.size,o=!1):(e=Yt(e),i=e.length,o=Yt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Ie]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Or(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[jc.extensionName],o=t.binary?2:1,a=t.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Or(e)?(l=e.size,c=!1):(e=Yt(e),l=e.length,c=Yt.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=l>=i._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);let u={[Ie]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};Or(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[Ie],this._state=sg,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(no,this,l,i);return}this._bufferedBytes-=n[Ie];let a=Yt(o);t?this.dispatch(a,t,n,i):(this._state=Be,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(o=>{process.nextTick(og,this,o,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let o=this._extensions[jc.extensionName];this._bufferedBytes+=n[Ie],this._state=ig,o.compress(e,n.fin,(a,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");no(this,c,i);return}this._bufferedBytes-=n[Ie],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(l,n),i),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ie],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ie],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Lc.exports=ro;function no(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let i=r._queue[n],o=i[i.length-1];typeof o=="function"&&o(e)}}function og(r,e,t){no(r,e,t),r.onerror(e)}});var Gc=J((h1,Zc)=>{"use strict";var{kForOnEventAttribute:un,kListener:so}=it(),Nc=Symbol("kCode"),$c=Symbol("kData"),Uc=Symbol("kError"),zc=Symbol("kMessage"),qc=Symbol("kReason"),jr=Symbol("kTarget"),Vc=Symbol("kType"),Wc=Symbol("kWasClean"),ot=class{constructor(e){this[jr]=null,this[Vc]=e}get target(){return this[jr]}get type(){return this[Vc]}};Object.defineProperty(ot.prototype,"target",{enumerable:!0});Object.defineProperty(ot.prototype,"type",{enumerable:!0});var Xt=class extends ot{constructor(e,t={}){super(e),this[Nc]=t.code===void 0?0:t.code,this[qc]=t.reason===void 0?"":t.reason,this[Wc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Nc]}get reason(){return this[qc]}get wasClean(){return this[Wc]}};Object.defineProperty(Xt.prototype,"code",{enumerable:!0});Object.defineProperty(Xt.prototype,"reason",{enumerable:!0});Object.defineProperty(Xt.prototype,"wasClean",{enumerable:!0});var Br=class extends ot{constructor(e,t={}){super(e),this[Uc]=t.error===void 0?null:t.error,this[zc]=t.message===void 0?"":t.message}get error(){return this[Uc]}get message(){return this[zc]}};Object.defineProperty(Br.prototype,"error",{enumerable:!0});Object.defineProperty(Br.prototype,"message",{enumerable:!0});var dn=class extends ot{constructor(e,t={}){super(e),this[$c]=t.data===void 0?null:t.data}get data(){return this[$c]}};Object.defineProperty(dn.prototype,"data",{enumerable:!0});var ag={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[un]&&i[so]===e&&!i[un])return;let n;if(r==="message")n=function(o,a){let l=new dn("message",{data:a?o:o.toString()});l[jr]=this,hi(e,this,l)};else if(r==="close")n=function(o,a){let l=new Xt("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[jr]=this,hi(e,this,l)};else if(r==="error")n=function(o){let a=new Br("error",{error:o,message:o.message});a[jr]=this,hi(e,this,a)};else if(r==="open")n=function(){let o=new ot("open");o[jr]=this,hi(e,this,o)};else return;n[un]=!!t[un],n[so]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[so]===e&&!t[un]){this.removeListener(r,t);break}}};Zc.exports={CloseEvent:Xt,ErrorEvent:Br,Event:ot,EventTarget:ag,MessageEvent:dn};function hi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var oo=J((p1,Kc)=>{"use strict";var{tokenChars:fn}=Ir();function Ve(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function lg(r){let e=Object.create(null),t=Object.create(null),n=!1,i=!1,o=!1,a,l,c=-1,u=-1,h=-1,f=0;for(;f<r.length;f++)if(u=r.charCodeAt(f),a===void 0)if(h===-1&&fn[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=r.slice(c,h);u===44?(Ve(e,p,t),t=Object.create(null)):a=p,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&fn[u]===1)c===-1&&(c=f);else if(u===32||u===9)h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f),Ve(t,r.slice(c,h),!0),u===44&&(Ve(e,a,t),t=Object.create(null),a=void 0),c=h=-1}else if(u===61&&c!==-1&&h===-1)l=r.slice(c,f),c=h=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(fn[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:n||(n=!0),i=!1}else if(o)if(fn[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)o=!1,h=f;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&r.charCodeAt(f-1)===61)o=!0;else if(h===-1&&fn[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))h===-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=r.slice(c,h);n&&(p=p.replace(/\\/g,""),n=!1),Ve(t,l,p),u===44&&(Ve(e,a,t),t=Object.create(null),a=void 0),l=void 0,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=f);let d=r.slice(c,h);return a===void 0?Ve(e,d,t):(l===void 0?Ve(t,d,!0):n?Ve(t,l,d.replace(/\\/g,"")):Ve(t,l,d),Ve(e,a,t)),e}function cg(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(i=>{let o=n[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Kc.exports={format:cg,parse:lg}});var yi=J((y1,ou)=>{"use strict";var ug=require("events"),dg=require("https"),fg=require("http"),Yc=require("net"),hg=require("tls"),{randomBytes:pg,createHash:mg}=require("crypto"),{Duplex:m1,Readable:g1}=require("stream"),{URL:ao}=require("url"),_t=cn(),gg=to(),yg=io(),{isBlob:bg}=Ir(),{BINARY_TYPES:Hc,CLOSE_TIMEOUT:vg,EMPTY_BUFFER:pi,GUID:Dg,kForOnEventAttribute:lo,kListener:wg,kStatusCode:Sg,kWebSocket:oe,NOOP:Qc}=it(),{EventTarget:{addEventListener:Cg,removeEventListener:Eg}}=Gc(),{format:_g,parse:xg}=oo(),{toBuffer:kg}=an(),Xc=Symbol("kAborted"),co=[8,13],at=["CONNECTING","OPEN","CLOSING","CLOSED"],Fg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,te=class r extends ug{constructor(e,t,n){super(),this._binaryType=Hc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=pi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),eu(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hc.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let i=new gg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new yg(e,this._extensions,n.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[oe]=this,o[oe]=this,e[oe]=this,i.on("conclude",Ag),i.on("drain",Rg),i.on("error",Ig),i.on("message",Og),i.on("ping",Mg),i.on("pong",jg),o.onerror=Bg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",nu),e.on("data",gi),e.on("end",iu),e.on("error",su),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[_t.extensionName]&&this._extensions[_t.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ru(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){uo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||pi,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){uo(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||pi,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){uo(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[_t.extensionName]||(i.compress=!1),this._sender.send(e||pi,i,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(te,"CONNECTING",{enumerable:!0,value:at.indexOf("CONNECTING")});Object.defineProperty(te.prototype,"CONNECTING",{enumerable:!0,value:at.indexOf("CONNECTING")});Object.defineProperty(te,"OPEN",{enumerable:!0,value:at.indexOf("OPEN")});Object.defineProperty(te.prototype,"OPEN",{enumerable:!0,value:at.indexOf("OPEN")});Object.defineProperty(te,"CLOSING",{enumerable:!0,value:at.indexOf("CLOSING")});Object.defineProperty(te.prototype,"CLOSING",{enumerable:!0,value:at.indexOf("CLOSING")});Object.defineProperty(te,"CLOSED",{enumerable:!0,value:at.indexOf("CLOSED")});Object.defineProperty(te.prototype,"CLOSED",{enumerable:!0,value:at.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(te.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(te.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[lo])return e[wg];return null},set(e){for(let t of this.listeners(r))if(t[lo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[lo]:!0})}})});te.prototype.addEventListener=Cg;te.prototype.removeEventListener=Eg;ou.exports=te;function eu(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:vg,protocolVersion:co[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=i.autoPong,r._closeTimeout=i.closeTimeout,!co.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${co.join(", ")})`);let o;if(e instanceof ao)o=e;else try{o=new ao(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),r._url=o.href;let a=o.protocol==="wss:",l=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!a&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(r._redirects===0)throw g;mi(r,g);return}let u=a?443:80,h=pg(16).toString("base64"),f=a?dg.request:fg.request,d=new Set,p;if(i.createConnection=i.createConnection||(a?Tg:Pg),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new _t(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=_g({[_t.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!Fg.test(g)||d.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(g)}i.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),l){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let m;if(i.followRedirects){if(r._redirects===0){r._originalIpc=l,r._originalSecure=a,r._originalHostOrSocketPath=l?i.socketPath:o.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[b,y]of Object.entries(g))n.headers[b.toLowerCase()]=y}else if(r.listenerCount("redirect")===0){let g=l?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:o.host===r._originalHostOrSocketPath;(!g||r._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=r._req=f(i),r._redirects&&r.emit("redirect",r.url,m)}else m=r._req=f(i);i.timeout&&m.on("timeout",()=>{Ee(r,m,"Opening handshake has timed out")}),m.on("error",g=>{m===null||m[Xc]||(m=r._req=null,mi(r,g))}),m.on("response",g=>{let b=g.headers.location,y=g.statusCode;if(b&&i.followRedirects&&y>=300&&y<400){if(++r._redirects>i.maxRedirects){Ee(r,m,"Maximum redirects exceeded");return}m.abort();let D;try{D=new ao(b,e)}catch{let S=new SyntaxError(`Invalid URL: ${b}`);mi(r,S);return}eu(r,D,t,n)}else r.emit("unexpected-response",m,g)||Ee(r,m,`Unexpected server response: ${g.statusCode}`)}),m.on("upgrade",(g,b,y)=>{if(r.emit("upgrade",g),r.readyState!==te.CONNECTING)return;m=r._req=null;let D=g.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){Ee(r,b,"Invalid Upgrade header");return}let v=mg("sha1").update(h+Dg).digest("base64");if(g.headers["sec-websocket-accept"]!==v){Ee(r,b,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],E;if(S!==void 0?d.size?d.has(S)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":d.size&&(E="Server sent no subprotocol"),E){Ee(r,b,E);return}S&&(r._protocol=S);let k=g.headers["sec-websocket-extensions"];if(k!==void 0){if(!p){Ee(r,b,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=xg(k)}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}let z=Object.keys(x);if(z.length!==1||z[0]!==_t.extensionName){Ee(r,b,"Server indicated an extension that was not requested");return}try{p.accept(x[_t.extensionName])}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[_t.extensionName]=p}r.setSocket(b,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,r):m.end()}function mi(r,e){r._readyState=te.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Pg(r){return r.path=r.socketPath,Yc.connect(r)}function Tg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Yc.isIP(r.host)?"":r.host),hg.connect(r)}function Ee(r,e,t){r._readyState=te.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ee),e.setHeader?(e[Xc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(mi,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function uo(r,e,t){if(e){let n=bg(e)?e.size:kg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${at[r.readyState]})`);process.nextTick(t,n)}}function Ag(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",gi),process.nextTick(tu,t._socket),r===1005?t.close():t.close(r,e))}function Rg(){let r=this[oe];r.isPaused||r._socket.resume()}function Ig(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",gi),process.nextTick(tu,e._socket),e.close(r[Sg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Jc(){this[oe].emitClose()}function Og(r,e){this[oe].emit("message",r,e)}function Mg(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,Qc),e.emit("ping",r)}function jg(r){this[oe].emit("pong",r)}function tu(r){r.resume()}function Bg(r){let e=this[oe];e.readyState!==te.CLOSED&&(e.readyState===te.OPEN&&(e._readyState=te.CLOSING,ru(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function ru(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function nu(){let r=this[oe];if(this.removeListener("close",nu),this.removeListener("data",gi),this.removeListener("end",iu),r._readyState=te.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Jc),r._receiver.on("finish",Jc))}function gi(r){this[oe]._receiver.write(r)||this.pause()}function iu(){let r=this[oe];r._readyState=te.CLOSING,r._receiver.end(),this.end()}function su(){let r=this[oe];this.removeListener("error",su),this.on("error",Qc),r&&(r._readyState=te.CLOSING,this.destroy())}});var uu=J((v1,cu)=>{"use strict";var b1=yi(),{Duplex:Lg}=require("stream");function au(r){r.emit("close")}function Ng(){!this.destroyed&&this._writableState.finished&&this.destroy()}function lu(r){this.removeListener("error",lu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function $g(r,e){let t=!0,n=new Lg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(o,a){let l=!a&&n._readableState.objectMode?o.toString():o;n.push(l)||r.pause()}),r.once("error",function(o){n.destroyed||(t=!1,n.destroy(o))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,o){if(r.readyState===r.CLOSED){o(i),process.nextTick(au,n);return}let a=!1;r.once("error",function(c){a=!0,o(c)}),r.once("close",function(){a||o(i),process.nextTick(au,n)}),t&&r.terminate()},n._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(i,o,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(i,o,a)});return}r.send(i,a)},n.on("end",Ng),n.on("error",lu),n}cu.exports=$g});var fu=J((D1,du)=>{"use strict";var{tokenChars:Ug}=Ir();function zg(r){let e=new Set,t=-1,n=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(n===-1&&Ug[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let l=r.slice(t,n);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let o=r.slice(t,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}du.exports={parse:zg}});var vu=J((S1,bu)=>{"use strict";var qg=require("events"),bi=require("http"),{Duplex:w1}=require("stream"),{createHash:Vg}=require("crypto"),hu=oo(),er=cn(),Wg=fu(),Zg=yi(),{CLOSE_TIMEOUT:Gg,GUID:Kg,kWebSocket:Hg}=it(),Jg=/^[+/0-9A-Za-z]{22}==$/,pu=0,mu=1,yu=2,fo=class extends qg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Gg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Zg,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=bi.createServer((n,i)=>{let o=bi.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Yg(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=pu}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yu){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(hn,this);return}if(e&&this.once("close",e),this._state!==mu)if(this._state=mu,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(hn,this):process.nextTick(hn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{hn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,i){t.on("error",gu);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){tr(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){tr(this,e,t,400,"Invalid Upgrade header");return}if(o===void 0||!Jg.test(o)){tr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){tr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){pn(t,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=Wg.parse(c)}catch{tr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&h!==void 0){let d=new er(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=hu.parse(h);p[er.extensionName]&&(d.accept(p[er.extensionName]),f[er.extensionName]=d)}catch{tr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(d,(p,m,g,b)=>{if(!p)return pn(t,m||401,g,b);this.completeUpgrade(f,o,u,e,t,n,i)});return}if(!this.options.verifyClient(d))return pn(t,401)}this.completeUpgrade(f,o,u,e,t,n,i)}completeUpgrade(e,t,n,i,o,a,l){if(!o.readable||!o.writable)return o.destroy();if(o[Hg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>pu)return pn(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Vg("sha1").update(t+Kg).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(n.size){let f=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),h._protocol=f)}if(e[er.extensionName]){let f=e[er.extensionName].params,d=hu.format({[er.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${d}`),h._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
9
+ `).join(`\r
10
+ `)),o.removeListener("error",gu),h.setSocket(o,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(hn,this)})),l(h,i)}};bu.exports=fo;function Yg(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function hn(r){r._state=yu,r.emit("close")}function gu(){this.destroy()}function pn(r,e,t,n){t=t||bi.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${bi.STATUS_CODES[e]}\r
11
+ `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
12
+ `)+`\r
13
+ \r
14
+ `+t)}function tr(r,e,t,n,i,o){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,tr),r.emit("wsClientError",a,t,e)}else pn(t,n,i,o)}});var wu=J((C1,Du)=>{"use strict";var lt=yi();lt.createWebSocketStream=uu();lt.Server=vu();lt.Receiver=to();lt.Sender=io();lt.WebSocket=lt;lt.WebSocketServer=lt.Server;Du.exports=lt});var Su=J(Lr=>{"use strict";var Qg=Lr&&Lr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.WebSocket=void 0;var Xg=Qg(wu());Lr.WebSocket=Xg.default});var Cu=J(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.WebSocket=We.terminalSize=We.readFileAsBase64=We.generateRandomBase64=void 0;var ey=cc();Object.defineProperty(We,"generateRandomBase64",{enumerable:!0,get:function(){return ey.generateRandomBase64}});var ty=uc();Object.defineProperty(We,"readFileAsBase64",{enumerable:!0,get:function(){return ty.readFileAsBase64}});var ry=mc();Object.defineProperty(We,"terminalSize",{enumerable:!0,get:function(){return ry.terminalSize}});var ny=Su();Object.defineProperty(We,"WebSocket",{enumerable:!0,get:function(){return ny.WebSocket}})});var qn=Me(require("fs")),fl=Me(require("path"));async function ms(r,e=""){let t="";try{let i=qn.readdirSync(r).filter(o=>!o.startsWith(".")&&o!=="node_modules"&&o!=="dist");for(let o of i.slice(0,50)){let a=fl.join(r,o),l=qn.statSync(a);t+=`${e}${o}${l.isDirectory()?"/":""}
15
+ `,l.isDirectory()&&e.length<6&&(t+=await ms(a,e+" "))}}catch{}return t}function hl(r){try{let e=r.match(/\[[\s\S]*\]/);if(!e)throw new Error("No JSON array found in response");let t=JSON.parse(e[0]);if(!Array.isArray(t))throw new Error("Response is not an array");return t.filter(n=>!n.type||!n.path?!1:["view","create","modify","delete"].includes(n.type))}catch(e){let t=e instanceof Error?e.message:"Unknown error";return console.error("Failed to parse workspace actions:",t),[]}}function Vn(r){return r.replace(/\\n/g,`
16
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}var pl=["(\u25D5\u203F\u25D5)","\u30FD(\xB4\u25BD`)/","(\uFF61\u25D5\u203F\u25D5\uFF61)","(\u3065\uFF61\u25D5\u203F\u203F\u25D5\uFF61)\u3065","\u0295\u2022\u1D25\u2022\u0294","(\uFF89\u25D5\u30EE\u25D5)\uFF89*:\uFF65\uFF9F\u2727","(\u25D5\u1D17\u25D5\u273F)","(\uFF61\u2665\u203F\u2665\uFF61)","\u266A(\u250C\u30FB\u3002\u30FB)\u250C","(\uFF89\xB4\u30EE`)\uFF89*: \uFF65\uFF9F","(\uFFE3\u25BD\uFFE3)\u30CE","(\u25E0\u203F\u25E0)","(\u2022\u203F\u2022)","\u2570(*\xB0\u25BD\xB0*)\u256F","(\u2267\u25E1\u2266)","(\u261E\uFF9F\u30EE\uFF9F)\u261E","(\u3065\uFFE3 \xB3\uFFE3)\u3065","\u30FE(\u2310\u25A0_\u25A0)\u30CE\u266A","(\u0E07 \u2022\u0300_\u2022\u0301)\u0E07","(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B","\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)","( \u2022_\u2022)>\u2310\u25A0-\u25A0","(\u2310\u25A0_\u25A0)","\xAF\\_(\u30C4)_/\xAF","( \u0361\xB0 \u035C\u0296 \u0361\xB0)","\u0CA0_\u0CA0"],ml=["(\u0E51\u2022\uFE4F\u2022)","(\u30FB_\u30FB\u30FE","( \u02D8\u03C9\u02D8 )","(\xB4-\u03C9-`)","( \xB4 \u25BD ` )"];function gs(){return pl[Math.floor(Math.random()*pl.length)]}function Wn(){return ml[Math.floor(Math.random()*ml.length)]}var Eh=Me(require("readline")),Oe=Me(require("fs")),zn=Me(require("path"));var Qr=Me(require("node:fs"),1),xs=require("node:path");var fw=Me(ys(),1),yl="11434",bl=`http://127.0.0.1:${yl}`,Oh="0.6.3",Mh=Object.defineProperty,jh=(r,e,t)=>e in r?Mh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,bs=(r,e,t)=>(jh(r,typeof e!="symbol"?e+"":e,t),t),ws=class r extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,r)}},Ss=class{constructor(e,t,n){bs(this,"abortController"),bs(this,"itr"),bs(this,"doneCallback"),this.abortController=e,this.itr=t,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},Cs=async r=>{if(r.ok)return;let e=`Error ${r.status}: ${r.statusText}`,t=null;if(r.headers.get("content-type")?.includes("application/json"))try{t=await r.json(),e=t.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await r.text()||e}catch{console.log("Failed to get text from error response")}throw new ws(e,r.status)};function Bh(){if(typeof window<"u"&&window.navigator){let r=navigator;return"userAgentData"in r&&r.userAgentData?.platform?`${r.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function Lh(r){if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}else return Array.isArray(r)?Object.fromEntries(r):r||{}}var Nh=(r,e)=>r[e],Es=async(r,e,t={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${Oh} (${Bh()})`};t.headers=Lh(t.headers);try{let o=new URL(e);if(o.protocol==="https:"&&o.hostname==="ollama.com"){let a=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?Nh(process.env,"OLLAMA_API_KEY"):void 0;!(t.headers.authorization||t.headers.Authorization)&&a&&(t.headers.Authorization=`Bearer ${a}`)}}catch(o){console.error("error parsing url",o)}let i=Object.fromEntries(Object.entries(t.headers).filter(([o])=>!Object.keys(n).some(a=>a.toLowerCase()===o.toLowerCase())));return t.headers={...n,...i},r(e,t)},vs=async(r,e,t)=>{let n=await Es(r,e,{headers:t?.headers});return await Cs(n),n},bt=async(r,e,t,n)=>{let o=(l=>l!==null&&typeof l=="object"&&!Array.isArray(l))(t)?JSON.stringify(t):t,a=await Es(r,e,{method:"POST",body:o,signal:n?.signal,headers:n?.headers});return await Cs(a),a},$h=async(r,e,t,n)=>{let i=await Es(r,e,{method:"DELETE",body:JSON.stringify(t),headers:n?.headers});return await Cs(i),i},Uh=async function*(r){let e=new TextDecoder("utf-8"),t="",n=r.getReader();for(;;){let{done:i,value:o}=await n.read();if(i)break;t+=e.decode(o,{stream:!0});let a=t.split(`
17
+ `);t=a.pop()??"";for(let l of a)try{yield JSON.parse(l)}catch{console.warn("invalid json: ",l)}}t+=e.decode();for(let i of t.split(`
18
+ `).filter(o=>o!==""))try{yield JSON.parse(i)}catch{console.warn("invalid json: ",i)}},zh=r=>{if(!r)return bl;let e=r.includes("://");r.startsWith(":")&&(r=`http://127.0.0.1${r}`,e=!0),e||(r=`http://${r}`);let t=new URL(r),n=t.port;n||(e?n=t.protocol==="https:"?"443":"80":n=yl);let i="";t.username&&(i=t.username,t.password&&(i+=`:${t.password}`),i+="@");let o=`${t.protocol}//${i}${t.hostname}:${n}${t.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},qh=Object.defineProperty,Vh=(r,e,t)=>e in r?qh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ds=(r,e,t)=>(Vh(r,typeof e!="symbol"?e+"":e,t),t),_s=class{constructor(e){Ds(this,"config"),Ds(this,"fetch"),Ds(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=zh(e?.host??bl)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let o=new AbortController,a=await bt(this.fetch,n,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let l=Uh(a.body),c=new Ss(o,l,()=>{let u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await bt(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),n="",i=t.byteLength;for(let o=0;o<i;o++)n+=String.fromCharCode(t[o]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await $h(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await bt(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await vs(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await bt(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await bt(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await bt(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await vs(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await vs(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await bt(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await bt(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},pw=new _s;var yw=Me(ys(),1),Xr=class extends _s{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(Qr.default.existsSync(e)){let t=await Qr.promises.readFile((0,xs.resolve)(e));return Buffer.from(t).toString("base64")}}catch{}return e}async fileExists(e){try{return await Qr.promises.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists((0,xs.resolve)(e.from)))throw Error("Creating with a local path is not currently supported from ollama-js");return e.stream?super.create(e):super.create(e)}},bw=new Xr;var s={};Rh(s,{BRAND:()=>gp,DIRTY:()=>Mt,EMPTY_PATH:()=>Kh,INVALID:()=>L,NEVER:()=>em,OK:()=>fe,ParseStatus:()=>ce,Schema:()=>W,ZodAny:()=>wt,ZodArray:()=>nt,ZodBigInt:()=>Bt,ZodBoolean:()=>Lt,ZodBranded:()=>tn,ZodCatch:()=>Ht,ZodDate:()=>Nt,ZodDefault:()=>Kt,ZodDiscriminatedUnion:()=>Hn,ZodEffects:()=>Te,ZodEnum:()=>Zt,ZodError:()=>ve,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>Yn,ZodIntersection:()=>qt,ZodIssueCode:()=>_,ZodLazy:()=>Vt,ZodLiteral:()=>Wt,ZodMap:()=>Cr,ZodNaN:()=>_r,ZodNativeEnum:()=>Gt,ZodNever:()=>je,ZodNull:()=>Ut,ZodNullable:()=>qe,ZodNumber:()=>jt,ZodObject:()=>De,ZodOptional:()=>Fe,ZodParsedType:()=>R,ZodPipeline:()=>rn,ZodPromise:()=>St,ZodReadonly:()=>Jt,ZodRecord:()=>Jn,ZodSchema:()=>W,ZodSet:()=>Er,ZodString:()=>Dt,ZodSymbol:()=>wr,ZodTransformer:()=>Te,ZodTuple:()=>ze,ZodType:()=>W,ZodUndefined:()=>$t,ZodUnion:()=>zt,ZodUnknown:()=>rt,ZodVoid:()=>Sr,addIssueToContext:()=>T,any:()=>_p,array:()=>Pp,bigint:()=>Dp,boolean:()=>Pl,coerce:()=>Xp,custom:()=>xl,date:()=>wp,datetimeRegex:()=>El,defaultErrorMap:()=>et,discriminatedUnion:()=>Ip,effect:()=>Wp,enum:()=>zp,function:()=>Np,getErrorMap:()=>br,getParsedType:()=>Ue,instanceof:()=>bp,intersection:()=>Op,isAborted:()=>Gn,isAsync:()=>vr,isDirty:()=>Kn,isValid:()=>vt,late:()=>yp,lazy:()=>$p,literal:()=>Up,makeIssue:()=>en,map:()=>Bp,nan:()=>vp,nativeEnum:()=>qp,never:()=>kp,null:()=>Ep,nullable:()=>Gp,number:()=>Fl,object:()=>Tp,objectUtil:()=>ks,oboolean:()=>Qp,onumber:()=>Yp,optional:()=>Zp,ostring:()=>Jp,pipeline:()=>Hp,preprocess:()=>Kp,promise:()=>Vp,quotelessJson:()=>Wh,record:()=>jp,set:()=>Lp,setErrorMap:()=>Gh,strictObject:()=>Ap,string:()=>kl,symbol:()=>Sp,transformer:()=>Wp,tuple:()=>Mp,undefined:()=>Cp,union:()=>Rp,unknown:()=>xp,util:()=>G,void:()=>Fp});var G;(function(r){r.assertEqual=i=>{};function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(l=>typeof i[i[l]]!="number"),a={};for(let l of o)a[l]=i[l];return r.objectValues(a)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},r.find=(i,o)=>{for(let a of i)if(o(a))return a},r.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(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(G||(G={}));var ks;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ks||(ks={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ue=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var _=G.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"]),Wh=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),ve=class r 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let l=n,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(t(a))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];t[o]=t[o]||[],t[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ve.create=r=>new ve(r);var Zh=(r,e)=>{let t;switch(r.code){case _.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case _.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case _.invalid_union:t="Invalid input";break;case _.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case _.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case _.invalid_arguments:t="Invalid function arguments";break;case _.invalid_return_type:t="Invalid function return type";break;case _.invalid_date:t="Invalid date";break;case _.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case _.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case _.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case _.custom:t="Invalid input";break;case _.invalid_intersection_types:t="Intersection results could not be merged";break;case _.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case _.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},et=Zh;var vl=et;function Gh(r){vl=r}function br(){return vl}var en=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let l="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)l=u(a,{data:e,defaultError:l}).message;return{...i,path:o,message:l}},Kh=[];function T(r,e){let t=br(),n=en({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===et?void 0:et].filter(i=>!!i)});r.common.issues.push(n)}var ce=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return L;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return L;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),Mt=r=>({status:"dirty",value:r}),fe=r=>({status:"valid",value:r}),Gn=r=>r.status==="aborted",Kn=r=>r.status==="dirty",vt=r=>r.status==="valid",vr=r=>typeof Promise<"u"&&r instanceof Promise;var O;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var Pe=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,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}},Dl=(r,e)=>{if(vt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new ve(r.common.issues);return this._error=t,this._error}}};function V(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||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:(a,l)=>{let{message:c}=r;return a.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??n??l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:c??t??l.defaultError}},description:i}}var W=class{get description(){return this._def.description}_getType(e){return Ue(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ue(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ce,ctx:{common:e.parent.common,data:e.data,parsedType:Ue(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(vr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ue(e)},i=this._parseSync({data:e,path:n.path,parent:n});return Dl(n,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ue(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return vt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>vt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ue(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(vr(i)?i:Promise.resolve(i));return Dl(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let a=e(i),l=()=>o.addIssue({code:_.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Te({schema:this,typeName:F.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:t=>this["~validate"](t)}}optional(){return Fe.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nt.create(this)}promise(){return St.create(this,this._def)}or(e){return zt.create([this,e],this._def)}and(e){return qt.create(this,e,this._def)}transform(e){return new Te({...V(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Kt({...V(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new tn({typeName:F.ZodBranded,type:this,...V(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ht({...V(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return rn.create(this,e)}readonly(){return Jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Hh=/^c[^\s-]{8,}$/i,Jh=/^[0-9a-z]+$/,Yh=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qh=/^[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,Xh=/^[a-z0-9_-]{21}$/i,ep=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tp=/^[-+]?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)?)??$/,rp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,np="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,ip=/^(?:(?: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])$/,sp=/^(?:(?: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])$/,op=/^(([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]))$/,ap=/^(([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])$/,lp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sl="((\\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])))",up=new RegExp(`^${Sl}$`);function Cl(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function dp(r){return new RegExp(`^${Cl(r)}$`)}function El(r){let e=`${Sl}T${Cl(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function fp(r,e){return!!((e==="v4"||!e)&&ip.test(r)||(e==="v6"||!e)&&op.test(r))}function hp(r,e){if(!ep.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 pp(r,e){return!!((e==="v4"||!e)&&sp.test(r)||(e==="v6"||!e)&&ap.test(r))}var Dt=class r extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let o=this._getOrReturnCtx(e);return T(o,{code:_.invalid_type,expected:R.string,received:o.parsedType}),L}let n=new ce,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:_.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),T(i,{code:_.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,l=e.data.length<o.value;(a||l)&&(i=this._getOrReturnCtx(e,i),a?T(i,{code:_.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):l&&T(i,{code:_.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")rp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"email",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Fs||(Fs=new RegExp(np,"u")),Fs.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"emoji",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")Qh.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"uuid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")Xh.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"nanoid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Hh.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Jh.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid2",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Yh.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ulid",code:_.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),T(i,{validation:"url",code:_.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),T(i,{validation:"regex",code:_.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),T(i,{code:_.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),T(i,{code:_.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:_.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?El(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:_.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?up.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:_.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?dp(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:_.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?tp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"duration",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?fp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ip",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?hp(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"jwt",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?pp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cidr",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?lp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64",code:_.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?cp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64url",code:_.invalid_string,message:o.message}),n.dirty()):G.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(i=>e.test(i),{validation:t,code:_.invalid_string,...O.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errToObj(t)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Dt.create=r=>new Dt({checks:[],typeName:F.ZodString,coerce:r?.coerce??!1,...V(r)});function mp(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=Number.parseInt(r.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var jt=class r extends W{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)!==R.number){let o=this._getOrReturnCtx(e);return T(o,{code:_.invalid_type,expected:R.number,received:o.parsedType}),L}let n,i=new ce;for(let o of this._def.checks)o.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:_.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),T(n,{code:_.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),T(n,{code:_.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?mp(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:_.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:_.not_finite,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};jt.create=r=>new jt({checks:[],typeName:F.ZodNumber,coerce:r?.coerce||!1,...V(r)});var Bt=class r extends W{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)!==R.bigint)return this._getInvalidInput(e);let n,i=new ce;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),T(n,{code:_.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),T(n,{code:_.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),T(n,{code:_.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:R.bigint,received:t.parsedType}),L}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Bt.create=r=>new Bt({checks:[],typeName:F.ZodBigInt,coerce:r?.coerce??!1,...V(r)});var Lt=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.boolean,received:n.parsedType}),L}return fe(e.data)}};Lt.create=r=>new Lt({typeName:F.ZodBoolean,coerce:r?.coerce||!1,...V(r)});var Nt=class r extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let o=this._getOrReturnCtx(e);return T(o,{code:_.invalid_type,expected:R.date,received:o.parsedType}),L}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return T(o,{code:_.invalid_date}),L}let n=new ce,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:_.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),T(i,{code:_.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):G.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Nt.create=r=>new Nt({checks:[],coerce:r?.coerce||!1,typeName:F.ZodDate,...V(r)});var wr=class extends W{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.symbol,received:n.parsedType}),L}return fe(e.data)}};wr.create=r=>new wr({typeName:F.ZodSymbol,...V(r)});var $t=class extends W{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.undefined,received:n.parsedType}),L}return fe(e.data)}};$t.create=r=>new $t({typeName:F.ZodUndefined,...V(r)});var Ut=class extends W{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.null,received:n.parsedType}),L}return fe(e.data)}};Ut.create=r=>new Ut({typeName:F.ZodNull,...V(r)});var wt=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return fe(e.data)}};wt.create=r=>new wt({typeName:F.ZodAny,...V(r)});var rt=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return fe(e.data)}};rt.create=r=>new rt({typeName:F.ZodUnknown,...V(r)});var je=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:_.invalid_type,expected:R.never,received:t.parsedType}),L}};je.create=r=>new je({typeName:F.ZodNever,...V(r)});var Sr=class extends W{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.void,received:n.parsedType}),L}return fe(e.data)}};Sr.create=r=>new Sr({typeName:F.ZodVoid,...V(r)});var nt=class r extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==R.array)return T(t,{code:_.invalid_type,expected:R.array,received:t.parsedType}),L;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,l=t.data.length<i.exactLength.value;(a||l)&&(T(t,{code:a?_.too_big:_.too_small,minimum:l?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(T(t,{code:_.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(T(t,{code:_.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,l)=>i.type._parseAsync(new Pe(t,a,t.path,l)))).then(a=>ce.mergeArray(n,a));let o=[...t.data].map((a,l)=>i.type._parseSync(new Pe(t,a,t.path,l)));return ce.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.toString(t)}})}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({type:r,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...V(e)});function Dr(r){if(r instanceof De){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Fe.create(Dr(n))}return new De({...r._def,shape:()=>e})}else return r instanceof nt?new nt({...r._def,type:Dr(r.element)}):r instanceof Fe?Fe.create(Dr(r.unwrap())):r instanceof qe?qe.create(Dr(r.unwrap())):r instanceof ze?ze.create(r.items.map(e=>Dr(e))):r}var De=class r extends W{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(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:_.invalid_type,expected:R.object,received:u.parsedType}),L}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof je&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||l.push(u);let c=[];for(let u of a){let h=o[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new Pe(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof je){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:i.data[h]}});else if(u==="strict")l.length>0&&(T(i,{code:_.unrecognized_keys,keys:l}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of l){let f=i.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new Pe(i,f,i.path,h)),alwaysSet:h in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let f=await h.key,d=await h.value;u.push({key:f,value:d,alwaysSet:h.alwaysSet})}return u}).then(u=>ce.mergeObjectSync(n,u)):ce.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let i=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Dr(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Fe;)o=o._def.innerType;t[n]=o}return new r({...this._def,shape:()=>t})}keyof(){return _l(G.objectKeys(this.shape))}};De.create=(r,e)=>new De({shape:()=>r,unknownKeys:"strip",catchall:je.create(),typeName:F.ZodObject,...V(e)});De.strictCreate=(r,e)=>new De({shape:()=>r,unknownKeys:"strict",catchall:je.create(),typeName:F.ZodObject,...V(e)});De.lazycreate=(r,e)=>new De({shape:r,unknownKeys:"strip",catchall:je.create(),typeName:F.ZodObject,...V(e)});var zt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let l of o)if(l.result.status==="valid")return l.result;for(let l of o)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let a=o.map(l=>new ve(l.ctx.common.issues));return T(t,{code:_.invalid_union,unionErrors:a}),L}if(t.common.async)return Promise.all(n.map(async o=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},h=c._parseSync({data:t.data,path:t.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!o&&(o={result:h,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let l=a.map(c=>new ve(c));return T(t,{code:_.invalid_union,unionErrors:l}),L}}get options(){return this._def.options}};zt.create=(r,e)=>new zt({options:r,typeName:F.ZodUnion,...V(e)});var tt=r=>r instanceof Vt?tt(r.schema):r instanceof Te?tt(r.innerType()):r instanceof Wt?[r.value]:r instanceof Zt?r.options:r instanceof Gt?G.objectValues(r.enum):r instanceof Kt?tt(r._def.innerType):r instanceof $t?[void 0]:r instanceof Ut?[null]:r instanceof Fe?[void 0,...tt(r.unwrap())]:r instanceof qe?[null,...tt(r.unwrap())]:r instanceof tn||r instanceof Jt?tt(r.unwrap()):r instanceof Ht?tt(r._def.innerType):[],Hn=class r extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return T(t,{code:_.invalid_type,expected:R.object,received:t.parsedType}),L;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(T(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let a=tt(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of a){if(i.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);i.set(l,o)}}return new r({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...V(n)})}};function Ps(r,e){let t=Ue(r),n=Ue(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let i=G.objectKeys(e),o=G.objectKeys(r).filter(l=>i.indexOf(l)!==-1),a={...r,...e};for(let l of o){let c=Ps(r[l],e[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<r.length;o++){let a=r[o],l=e[o],c=Ps(a,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var qt=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=(o,a)=>{if(Gn(o)||Gn(a))return L;let l=Ps(o.value,a.value);return l.valid?((Kn(o)||Kn(a))&&t.dirty(),{status:t.value,value:l.data}):(T(n,{code:_.invalid_intersection_types}),L)};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,a])=>i(o,a)):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}))}};qt.create=(r,e,t)=>new qt({left:r,right:e,typeName:F.ZodIntersection,...V(t)});var ze=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:_.invalid_type,expected:R.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return T(n,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((a,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Pe(n,a,n.path,l)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ce.mergeArray(t,a)):ce.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ze({items:r,typeName:F.ZodTuple,rest:null,...V(e)})};var Jn=class r extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:_.invalid_type,expected:R.object,received:n.parsedType}),L;let i=[],o=this._def.keyType,a=this._def.valueType;for(let l in n.data)i.push({key:o._parse(new Pe(n,l,n.path,l)),value:a._parse(new Pe(n,n.data[l],n.path,l)),alwaysSet:l in n.data});return n.common.async?ce.mergeObjectAsync(t,i):ce.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof W?new r({keyType:e,valueType:t,typeName:F.ZodRecord,...V(n)}):new r({keyType:Dt.create(),valueType:e,typeName:F.ZodRecord,...V(t)})}},Cr=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:_.invalid_type,expected:R.map,received:n.parsedType}),L;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([l,c],u)=>({key:i._parse(new Pe(n,l,n.path,[u,"key"])),value:o._parse(new Pe(n,c,n.path,[u,"value"]))}));if(n.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return L;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),l.set(u.value,h.value)}return{status:t.value,value:l}})}else{let l=new Map;for(let c of a){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return L;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),l.set(u.value,h.value)}return{status:t.value,value:l}}}};Cr.create=(r,e,t)=>new Cr({valueType:e,keyType:r,typeName:F.ZodMap,...V(t)});var Er=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:_.invalid_type,expected:R.set,received:n.parsedType}),L;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:_.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:_.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function a(c){let u=new Set;for(let h of c){if(h.status==="aborted")return L;h.status==="dirty"&&t.dirty(),u.add(h.value)}return{status:t.value,value:u}}let l=[...n.data.values()].map((c,u)=>o._parse(new Pe(n,c,n.path,u)));return n.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Er.create=(r,e)=>new Er({valueType:r,minSize:null,maxSize:null,typeName:F.ZodSet,...V(e)});var Yn=class r extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return T(t,{code:_.invalid_type,expected:R.function,received:t.parsedType}),L;function n(l,c){return en({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,br(),et].filter(u=>!!u),issueData:{code:_.invalid_arguments,argumentsError:c}})}function i(l,c){return en({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,br(),et].filter(u=>!!u),issueData:{code:_.invalid_return_type,returnTypeError:c}})}let o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof St){let l=this;return fe(async function(...c){let u=new ve([]),h=await l._def.args.parseAsync(c,o).catch(p=>{throw u.addIssue(n(c,p)),u}),f=await Reflect.apply(a,this,h);return await l._def.returns._def.type.parseAsync(f,o).catch(p=>{throw u.addIssue(i(f,p)),u})})}else{let l=this;return fe(function(...c){let u=l._def.args.safeParse(c,o);if(!u.success)throw new ve([n(c,u.error)]);let h=Reflect.apply(a,this,u.data),f=l._def.returns.safeParse(h,o);if(!f.success)throw new ve([i(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ze.create(e).rest(rt.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ze.create([]).rest(rt.create()),returns:t||rt.create(),typeName:F.ZodFunction,...V(n)})}},Vt=class extends W{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Vt.create=(r,e)=>new Vt({getter:r,typeName:F.ZodLazy,...V(e)});var Wt=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Wt.create=(r,e)=>new Wt({value:r,typeName:F.ZodLiteral,...V(e)});function _l(r,e){return new Zt({values:r,typeName:F.ZodEnum,...V(e)})}var Zt=class r extends W{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{expected:G.joinValues(n),received:t.parsedType,code:_.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{received:t.data,code:_.invalid_enum_value,options:n}),L}return fe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Zt.create=_l;var Gt=class extends W{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let i=G.objectValues(t);return T(n,{expected:G.joinValues(i),received:n.parsedType,code:_.invalid_type}),L}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=G.objectValues(t);return T(n,{received:n.data,code:_.invalid_enum_value,options:i}),L}return fe(e.data)}get enum(){return this._def.values}};Gt.create=(r,e)=>new Gt({values:r,typeName:F.ZodNativeEnum,...V(e)});var St=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return T(t,{code:_.invalid_type,expected:R.promise,received:t.parsedType}),L;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return fe(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};St.create=(r,e)=>new St({type:r,typeName:F.ZodPromise,...V(e)});var Te=class extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{T(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async l=>{if(t.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:l,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?Mt(c.value):t.value==="dirty"?Mt(c.value):c});{if(t.value==="aborted")return L;let l=this._def.schema._parseSync({data:a,path:n.path,parent:n});return l.status==="aborted"?L:l.status==="dirty"?Mt(l.value):t.value==="dirty"?Mt(l.value):l}}if(i.type==="refinement"){let a=l=>{let c=i.refinement(l,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 l};if(n.common.async===!1){let l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return l.status==="aborted"?L:(l.status==="dirty"&&t.dirty(),a(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>l.status==="aborted"?L:(l.status==="dirty"&&t.dirty(),a(l.value).then(()=>({status:t.value,value:l.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!vt(a))return L;let l=i.transform(a.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>vt(a)?Promise.resolve(i.transform(a.value,o)).then(l=>({status:t.value,value:l})):L);G.assertNever(i)}};Te.create=(r,e,t)=>new Te({schema:r,typeName:F.ZodEffects,effect:e,...V(t)});Te.createWithPreprocess=(r,e,t)=>new Te({schema:e,effect:{type:"preprocess",transform:r},typeName:F.ZodEffects,...V(t)});var Fe=class extends W{_parse(e){return this._getType(e)===R.undefined?fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Fe.create=(r,e)=>new Fe({innerType:r,typeName:F.ZodOptional,...V(e)});var qe=class extends W{_parse(e){return this._getType(e)===R.null?fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qe.create=(r,e)=>new qe({innerType:r,typeName:F.ZodNullable,...V(e)});var Kt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Kt.create=(r,e)=>new Kt({innerType:r,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var Ht=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return vr(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ve(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ve(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var _r=class extends W{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:_.invalid_type,expected:R.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};_r.create=r=>new _r({typeName:F.ZodNaN,...V(r)});var gp=Symbol("zod_brand"),tn=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},rn=class r extends W{_parse(e){let{status:t,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"?L:o.status==="dirty"?(t.dirty(),Mt(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"?L:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:F.ZodPipeline})}},Jt=class extends W{_parse(e){let t=this._def.innerType._parse(e),n=i=>(vt(i)&&(i.value=Object.freeze(i.value)),i);return vr(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Jt.create=(r,e)=>new Jt({innerType:r,typeName:F.ZodReadonly,...V(e)});function wl(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function xl(r,e={},t){return r?wt.create().superRefine((n,i)=>{let o=r(n);if(o instanceof Promise)return o.then(a=>{if(!a){let l=wl(e,n),c=l.fatal??t??!0;i.addIssue({code:"custom",...l,fatal:c})}});if(!o){let a=wl(e,n),l=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:l})}}):wt.create()}var yp={object:De.lazycreate},F;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(F||(F={}));var bp=(r,e={message:`Input not instance of ${r.name}`})=>xl(t=>t instanceof r,e),kl=Dt.create,Fl=jt.create,vp=_r.create,Dp=Bt.create,Pl=Lt.create,wp=Nt.create,Sp=wr.create,Cp=$t.create,Ep=Ut.create,_p=wt.create,xp=rt.create,kp=je.create,Fp=Sr.create,Pp=nt.create,Tp=De.create,Ap=De.strictCreate,Rp=zt.create,Ip=Hn.create,Op=qt.create,Mp=ze.create,jp=Jn.create,Bp=Cr.create,Lp=Er.create,Np=Yn.create,$p=Vt.create,Up=Wt.create,zp=Zt.create,qp=Gt.create,Vp=St.create,Wp=Te.create,Zp=Fe.create,Gp=qe.create,Kp=Te.createWithPreprocess,Hp=rn.create,Jp=()=>kl().optional(),Yp=()=>Fl().optional(),Qp=()=>Pl().optional(),Xp={string:(r=>Dt.create({...r,coerce:!0})),number:(r=>jt.create({...r,coerce:!0})),boolean:(r=>Lt.create({...r,coerce:!0})),bigint:(r=>Bt.create({...r,coerce:!0})),date:(r=>Nt.create({...r,coerce:!0}))};var em=L;var Dn=Me(require("process"),1),I=Me(lc(),1),Qe=Me(Cu(),1);var _u=Symbol("Let zodToJsonSchema decide on which parser to use");var Eu={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},xu=r=>typeof r=="string"?{...Eu,name:r}:{...Eu,...r};var ku=r=>{let e=xu(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ho(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function K(r,e,t,n,i){r[e]=t,ho(r,e,n,i)}var vi=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};function re(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?vi(e,r.currentPath):e.join("/")}}function Fu(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==F.ZodAny&&(t.items=$(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&K(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&K(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(K(t,"minItems",r.exactLength.value,r.exactLength.message,e),K(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Pu(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?K(t,"minimum",n.value,n.message,e):K(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),K(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(t,"maximum",n.value,n.message,e):K(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),K(t,"maximum",n.value,n.message,e));break;case"multipleOf":K(t,"multipleOf",n.value,n.message,e);break}return t}function Tu(){return{type:"boolean"}}function Di(r,e){return $(r.type._def,e)}var Au=(r,e)=>$(r.innerType._def,e);function po(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>po(r,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return iy(r,e)}}var iy=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":K(t,"minimum",n.value,n.message,e);break;case"max":K(t,"maximum",n.value,n.message,e);break}return t};function Ru(r,e){return{...$(r.innerType._def,e),default:r.defaultValue()}}function Iu(r,e){return e.effectStrategy==="input"?$(r.schema._def,e):re(e)}function Ou(r){return{type:"string",enum:Array.from(r.values)}}var sy=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Mu(r,e){let t=[$(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),$(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return t.forEach(o=>{if(sy(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:l,...c}=o;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function ju(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}var mo,Le={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(mo===void 0&&(mo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),mo),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function wi(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":K(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":K(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ne(t,"email",n.message,e);break;case"format:idn-email":Ne(t,"idn-email",n.message,e);break;case"pattern:zod":me(t,Le.email,n.message,e);break}break;case"url":Ne(t,"uri",n.message,e);break;case"uuid":Ne(t,"uuid",n.message,e);break;case"regex":me(t,n.regex,n.message,e);break;case"cuid":me(t,Le.cuid,n.message,e);break;case"cuid2":me(t,Le.cuid2,n.message,e);break;case"startsWith":me(t,RegExp(`^${go(n.value,e)}`),n.message,e);break;case"endsWith":me(t,RegExp(`${go(n.value,e)}$`),n.message,e);break;case"datetime":Ne(t,"date-time",n.message,e);break;case"date":Ne(t,"date",n.message,e);break;case"time":Ne(t,"time",n.message,e);break;case"duration":Ne(t,"duration",n.message,e);break;case"length":K(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),K(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{me(t,RegExp(go(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Ne(t,"ipv4",n.message,e),n.version!=="v4"&&Ne(t,"ipv6",n.message,e);break}case"base64url":me(t,Le.base64url,n.message,e);break;case"jwt":me(t,Le.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&me(t,Le.ipv4Cidr,n.message,e),n.version!=="v4"&&me(t,Le.ipv6Cidr,n.message,e);break}case"emoji":me(t,Le.emoji(),n.message,e);break;case"ulid":{me(t,Le.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ne(t,"binary",n.message,e);break}case"contentEncoding:base64":{K(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{me(t,Le.base64,n.message,e);break}}break}case"nanoid":me(t,Le.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function go(r,e){return e.patternStrategy==="escape"?ay(r):r}var oy=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ay(r){let e="";for(let t=0;t<r.length;t++)oy.has(r[t])||(e+="\\"),e+=r[t];return e}function Ne(r,e,t,n){r.format||r.anyOf?.some(i=>i.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):K(r,"format",e,t,n)}function me(r,e,t,n){r.pattern||r.allOf?.some(i=>i.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Bu(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):K(r,"pattern",Bu(e,n),t,n)}function Bu(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,i="",o=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(o){i+=n[c],o=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){l?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],l=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){i+=`(^|(?<=[\r
19
+ ]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
20
+ ]))`;continue}}if(t.s&&n[c]==="."){i+=a?`${n[c]}\r
21
+ `:`[${n[c]}\r
22
+ ]`;continue}i+=n[c],n[c]==="\\"?o=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}function Si(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,i)=>({...n,[i]:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??re(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===F.ZodString&&r.keyType._def.checks?.length){let{type:n,...i}=wi(r.keyType._def,e);return{...t,propertyNames:i}}else{if(r.keyType?._def.typeName===F.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===F.ZodBranded&&r.keyType._def.type._def.typeName===F.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...i}=Di(r.keyType._def,e);return{...t,propertyNames:i}}}return t}function Lu(r,e){if(e.mapStrategy==="record")return Si(r,e);let t=$(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||re(e),n=$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||re(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Nu(r){let e=r.values,n=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function $u(r){return r.target==="openAi"?void 0:{not:re({...r,currentPath:[...r.currentPath,"not"]})}}function Uu(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var mn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qu(r,e){if(e.target==="openApi3")return zu(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in mn&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((i,o)=>{let a=mn[o._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((i,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===t.length){let i=n.filter((o,a,l)=>l.indexOf(o)===a);return{type:i.length>1?i:i[0],enum:t.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return zu(r,e)}var zu=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,i)=>$(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Vu(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:mn[r.innerType._def.typeName],nullable:!0}:{type:[mn[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=$(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Wu(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",ho(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?K(t,"minimum",n.value,n.message,e):K(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),K(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(t,"maximum",n.value,n.message,e):K(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),K(t,"maximum",n.value,n.message,e));break;case"multipleOf":K(t,"multipleOf",n.value,n.message,e);break}return t}function Zu(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},i=[],o=r.shape();for(let l in o){let c=o[l];if(c===void 0||c._def===void 0)continue;let u=cy(c);u&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let h=$(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});h!==void 0&&(n.properties[l]=h,u||i.push(l))}i.length&&(n.required=i);let a=ly(r,e);return a!==void 0&&(n.additionalProperties=a),n}function ly(r,e){if(r.catchall._def.typeName!=="ZodNever")return $(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function cy(r){try{return r.isOptional()}catch{return!0}}var Gu=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return $(r.innerType._def,e);let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:re(e)},t]}:re(e)};var Ku=(r,e)=>{if(e.pipeStrategy==="input")return $(r.in._def,e);if(e.pipeStrategy==="output")return $(r.out._def,e);let t=$(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=$(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(i=>i!==void 0)}};function Hu(r,e){return $(r.type._def,e)}function Ju(r,e){let n={type:"array",uniqueItems:!0,items:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&K(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&K(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Yu(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:$(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Qu(r){return{not:re(r)}}function Xu(r){return re(r)}var ed=(r,e)=>$(r.innerType._def,e);var td=(r,e,t)=>{switch(e){case F.ZodString:return wi(r,t);case F.ZodNumber:return Wu(r,t);case F.ZodObject:return Zu(r,t);case F.ZodBigInt:return Pu(r,t);case F.ZodBoolean:return Tu();case F.ZodDate:return po(r,t);case F.ZodUndefined:return Qu(t);case F.ZodNull:return Uu(t);case F.ZodArray:return Fu(r,t);case F.ZodUnion:case F.ZodDiscriminatedUnion:return qu(r,t);case F.ZodIntersection:return Mu(r,t);case F.ZodTuple:return Yu(r,t);case F.ZodRecord:return Si(r,t);case F.ZodLiteral:return ju(r,t);case F.ZodEnum:return Ou(r);case F.ZodNativeEnum:return Nu(r);case F.ZodNullable:return Vu(r,t);case F.ZodOptional:return Gu(r,t);case F.ZodMap:return Lu(r,t);case F.ZodSet:return Ju(r,t);case F.ZodLazy:return()=>r.getter()._def;case F.ZodPromise:return Hu(r,t);case F.ZodNaN:case F.ZodNever:return $u(t);case F.ZodEffects:return Iu(r,t);case F.ZodAny:return re(t);case F.ZodUnknown:return Xu(t);case F.ZodDefault:return Ru(r,t);case F.ZodBranded:return Di(r,t);case F.ZodReadonly:return ed(r,t);case F.ZodCatch:return Au(r,t);case F.ZodPipeline:return Ku(r,t);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(n=>{})(e)}};function $(r,e,t=!1){let n=e.seen.get(r);if(e.override){let l=e.override?.(r,e,n,t);if(l!==_u)return l}if(n&&!t){let l=uy(n,e);if(l!==void 0)return l}let i={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,i);let o=td(r,r.typeName,e),a=typeof o=="function"?$(o(),e):o;if(a&&dy(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return i.jsonSchema=a,l}return i.jsonSchema=a,a}var uy=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:vi(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),re(e)):e.$refStrategy==="seen"?re(e):void 0}},dy=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Ci=(r,e)=>{let t=ku(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,h])=>({...c,[u]:$(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,u]},!0)??re(t)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=$(r._def,i===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,i]},!1)??re(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let l=i===void 0?n?{...o,[t.definitionPath]:n}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,i].join("/"),[t.definitionPath]:{...n,[i]:o}};return t.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};function fy(r){return typeof r=="object"&&r!==null&&typeof r.get=="function"&&typeof r.subscribe=="function"}var Ft=class{subscribeWithCleaner(e,t){let n=this.subscribe(t);e.register(n)}subscribeOnce(e){let t=this.subscribe(n=>{t(),e(n)});return t}subscribeOnceWithCleaner(e,t){let n=this.subscribeOnce(t);e.register(n)}derive(e,t=(n,i)=>n===i){if(fy(this))return $e.deriveFrom([this],e);let n=this;if(n.get!==void 0){if(n.get()===$e.NOT_AVAILABLE)return $e.createWithoutInitialValue(a=>n.subscribe(l=>{dt(l)&&a(e(l))}));let o=n;return $e.create(e(o.get()),a=>o.subscribe(l=>{a(e(l))}),t)}return $e.createWithoutInitialValue(i=>this.subscribe(o=>{dt(o)&&i(e(o))}),t)}},wn=class r extends Ft{constructor(){super(),this.subscribers=new Set,this.onSubscribed=null,this.onUnsubscribed=null}emit(e){queueMicrotask(()=>{for(let t of this.subscribers)t(e)})}static create(){let e=new r;return[e,n=>{e.emit(n)}]}subscribe(e){let t=this.subscribers.size;return this.subscribers.add(e),t===0&&this.subscribers.size===1&&this.onSubscribed?.(),()=>{let n=this.subscribers.size;this.subscribers.delete(e),n===1&&this.subscribers.size===0&&this.onUnsubscribed?.()}}batch({minIdleTimeMs:e=200,maxBatchTimeMs:t=1e3}){let[n,i]=r.create();return n.onSubscribed=()=>{let o=[],a=null,l=0,c=()=>{a=null,i(o),o=[]};n.onUnsubscribed=this.subscribe(u=>{if(o.push(u),a===null)l=Date.now(),a=setTimeout(c,Math.min(e,t));else{clearTimeout(a);let h=Date.now()-l;a=setTimeout(c,Math.min(e,Math.max(0,t-h)))}})},n}};function ee(){let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}}var qa=Symbol.for("immer-nothing"),yn=Symbol.for("immer-draftable"),Y=Symbol.for("immer-state"),Wd=process.env.NODE_ENV!=="production"?[function(r){return`The plugin for '${r}' has not been loaded into Immer. To enable the plugin, import and call \`enable${r}()\` when initializing your application.`},function(r){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${r}'`},"This object has been frozen and should not be mutated",function(r){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+r},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(r){return`'current' expects a draft, got: ${r}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(r){return`'original' expects a draft, got: ${r}`}]:[];function ie(r,...e){if(process.env.NODE_ENV!=="production"){let t=Wd[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var dr=Object.getPrototypeOf;function fr(r){return!!r&&!!r[Y]}function Xe(r){return r?Zd(r)||Array.isArray(r)||!!r[yn]||!!r.constructor?.[yn]||Ln(r)||Nn(r):!1}var hy=Object.prototype.constructor.toString();function Zd(r){if(!r||typeof r!="object")return!1;let e=dr(r);if(e===null)return!0;let t=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===hy}function Zr(r,e){hr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function hr(r){let e=r[Y];return e?e.type_:Array.isArray(r)?1:Ln(r)?2:Nn(r)?3:0}function Sn(r,e){return hr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function yo(r,e){return hr(r)===2?r.get(e):r[e]}function Gd(r,e,t){let n=hr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function py(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function Ln(r){return r instanceof Map}function Nn(r){return r instanceof Set}function ae(r){return r.copy_||r.base_}function jo(r,e){if(Ln(r))return new Map(r);if(Nn(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);let t=Zd(r);if(e===!0||e==="class_only"&&!t){let n=Object.getOwnPropertyDescriptors(r);delete n[Y];let i=Reflect.ownKeys(n);for(let o=0;o<i.length;o++){let a=i[o],l=n[a];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[a]={configurable:!0,writable:!0,enumerable:l.enumerable,value:r[a]})}return Object.create(dr(r),n)}else{let n=dr(r);if(n!==null&&t)return{...r};let i=Object.create(n);return Object.assign(i,r)}}function Va(r,e=!1){return as(r)||fr(r)||!Xe(r)||(hr(r)>1&&(r.set=r.add=r.clear=r.delete=my),Object.freeze(r),e&&Object.values(r).forEach(t=>Va(t,!0))),r}function my(){ie(2)}function as(r){return Object.isFrozen(r)}var Bo={};function pr(r){let e=Bo[r];return e||ie(0,r),e}function Kd(r,e){Bo[r]||(Bo[r]=e)}var Cn;function Li(){return Cn}function gy(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function rd(r,e){e&&(pr("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Lo(r){No(r),r.drafts_.forEach(yy),r.drafts_=null}function No(r){r===Cn&&(Cn=r.parent_)}function nd(r){return Cn=gy(Cn,r)}function yy(r){let e=r[Y];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function id(r,e){e.unfinalizedDrafts_=e.drafts_.length;let t=e.drafts_[0];return r!==void 0&&r!==t?(t[Y].modified_&&(Lo(e),ie(4)),Xe(r)&&(r=Ni(e,r),e.parent_||$i(e,r)),e.patches_&&pr("Patches").generateReplacementPatches_(t[Y].base_,r,e.patches_,e.inversePatches_)):r=Ni(e,t,[]),Lo(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==qa?r:void 0}function Ni(r,e,t){if(as(e))return e;let n=e[Y];if(!n)return Zr(e,(i,o)=>sd(r,n,e,i,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return $i(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,o=i,a=!1;n.type_===3&&(o=new Set(i),i.clear(),a=!0),Zr(o,(l,c)=>sd(r,n,i,l,c,t,a)),$i(r,i,!1),t&&r.patches_&&pr("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function sd(r,e,t,n,i,o,a){if(process.env.NODE_ENV!=="production"&&i===t&&ie(5),fr(i)){let l=o&&e&&e.type_!==3&&!Sn(e.assigned_,n)?o.concat(n):void 0,c=Ni(r,i,l);if(Gd(t,n,c),fr(c))r.canAutoFreeze_=!1;else return}else a&&t.add(i);if(Xe(i)&&!as(i)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Ni(r,i),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(t,n)&&$i(r,i)}}function $i(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Va(e,t)}function by(r,e){let t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Li(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,o=Wa;t&&(i=[n],o=En);let{revoke:a,proxy:l}=Proxy.revocable(i,o);return n.draft_=l,n.revoke_=a,l}var Wa={get(r,e){if(e===Y)return r;let t=ae(r);if(!Sn(t,e))return vy(r,t,e);let n=t[e];return r.finalized_||!Xe(n)?n:n===bo(r.base_,e)?(vo(r),r.copy_[e]=_n(n,r)):n},has(r,e){return e in ae(r)},ownKeys(r){return Reflect.ownKeys(ae(r))},set(r,e,t){let n=Hd(ae(r),e);if(n?.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){let i=bo(ae(r),e),o=i?.[Y];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(py(t,i)&&(t!==void 0||Sn(r.base_,e)))return!0;vo(r),ut(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_[e]=!0),!0},deleteProperty(r,e){return bo(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,vo(r),ut(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){let t=ae(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){ie(11)},getPrototypeOf(r){return dr(r.base_)},setPrototypeOf(){ie(12)}},En={};Zr(Wa,(r,e)=>{En[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});En.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ie(13),En.set.call(this,r,e,void 0)};En.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ie(14),Wa.set.call(this,r[0],e,t,r[0])};function bo(r,e){let t=r[Y];return(t?ae(t):r)[e]}function vy(r,e,t){let n=Hd(e,t);return n?"value"in n?n.value:n.get?.call(r.draft_):void 0}function Hd(r,e){if(!(e in r))return;let t=dr(r);for(;t;){let n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=dr(t)}}function ut(r){r.modified_||(r.modified_=!0,r.parent_&&ut(r.parent_))}function vo(r){r.copy_||(r.copy_=jo(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Dy=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){let o=t;t=e;let a=this;return function(c=o,...u){return a.produce(c,h=>t.call(this,h,...u))}}typeof t!="function"&&ie(6),n!==void 0&&typeof n!="function"&&ie(7);let i;if(Xe(e)){let o=nd(this),a=_n(e,void 0),l=!0;try{i=t(a),l=!1}finally{l?Lo(o):No(o)}return rd(o,n),id(i,o)}else if(!e||typeof e!="object"){if(i=t(e),i===void 0&&(i=e),i===qa&&(i=void 0),this.autoFreeze_&&Va(i,!0),n){let o=[],a=[];pr("Patches").generateReplacementPatches_(e,i,o,a),n(o,a)}return i}else ie(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(a,...l)=>this.produceWithPatches(a,c=>e(c,...l));let n,i;return[this.produce(e,t,(a,l)=>{n=a,i=l}),n,i]},typeof r?.autoFreeze=="boolean"&&this.setAutoFreeze(r.autoFreeze),typeof r?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(r.useStrictShallowCopy)}createDraft(r){Xe(r)||ie(8),fr(r)&&(r=wy(r));let e=nd(this),t=_n(r,void 0);return t[Y].isManual_=!0,No(e),t}finishDraft(r,e){let t=r&&r[Y];(!t||!t.isManual_)&&ie(9);let{scope_:n}=t;return rd(n,e),id(void 0,n)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){let i=e[t];if(i.path.length===0&&i.op==="replace"){r=i.value;break}}t>-1&&(e=e.slice(t+1));let n=pr("Patches").applyPatches_;return fr(r)?n(r,e):this.produce(r,i=>n(i,e))}};function _n(r,e){let t=Ln(r)?pr("MapSet").proxyMap_(r,e):Nn(r)?pr("MapSet").proxySet_(r,e):by(r,e);return(e?e.scope_:Li()).drafts_.push(t),t}function wy(r){return fr(r)||ie(10,r),Jd(r)}function Jd(r){if(!Xe(r)||as(r))return r;let e=r[Y],t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=jo(r,e.scope_.immer_.useStrictShallowCopy_)}else t=jo(r,!0);return Zr(t,(n,i)=>{Gd(t,n,Jd(i))}),e&&(e.finalized_=!1),t}function Sy(){class r extends Map{constructor(c,u){super(),this[Y]={type_:2,parent_:u,scope_:u?u.scope_:Li(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return ae(this[Y]).size}has(c){return ae(this[Y]).has(c)}set(c,u){let h=this[Y];return a(h),(!ae(h).has(c)||ae(h).get(c)!==u)&&(t(h),ut(h),h.assigned_.set(c,!0),h.copy_.set(c,u),h.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let u=this[Y];return a(u),t(u),ut(u),u.base_.has(c)?u.assigned_.set(c,!1):u.assigned_.delete(c),u.copy_.delete(c),!0}clear(){let c=this[Y];a(c),ae(c).size&&(t(c),ut(c),c.assigned_=new Map,Zr(c.base_,u=>{c.assigned_.set(u,!1)}),c.copy_.clear())}forEach(c,u){let h=this[Y];ae(h).forEach((f,d,p)=>{c.call(u,this.get(d),d,this)})}get(c){let u=this[Y];a(u);let h=ae(u).get(c);if(u.finalized_||!Xe(h)||h!==u.base_.get(c))return h;let f=_n(h,u);return t(u),u.copy_.set(c,f),f}keys(){return ae(this[Y]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let u=c.next();return u.done?u:{done:!1,value:this.get(u.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let u=c.next();if(u.done)return u;let h=this.get(u.value);return{done:!1,value:[u.value,h]}}}}[Symbol.iterator](){return this.entries()}}function e(l,c){return new r(l,c)}function t(l){l.copy_||(l.assigned_=new Map,l.copy_=new Map(l.base_))}class n extends Set{constructor(c,u){super(),this[Y]={type_:3,parent_:u,scope_:u?u.scope_:Li(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return ae(this[Y]).size}has(c){let u=this[Y];return a(u),u.copy_?!!(u.copy_.has(c)||u.drafts_.has(c)&&u.copy_.has(u.drafts_.get(c))):u.base_.has(c)}add(c){let u=this[Y];return a(u),this.has(c)||(o(u),ut(u),u.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let u=this[Y];return a(u),o(u),ut(u),u.copy_.delete(c)||(u.drafts_.has(c)?u.copy_.delete(u.drafts_.get(c)):!1)}clear(){let c=this[Y];a(c),ae(c).size&&(o(c),ut(c),c.copy_.clear())}values(){let c=this[Y];return a(c),o(c),c.copy_.values()}entries(){let c=this[Y];return a(c),o(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,u){let h=this.values(),f=h.next();for(;!f.done;)c.call(u,f.value,f.value,this),f=h.next()}}function i(l,c){return new n(l,c)}function o(l){l.copy_||(l.copy_=new Set,l.base_.forEach(c=>{if(Xe(c)){let u=_n(c,l);l.drafts_.set(c,u),l.copy_.add(u)}else l.copy_.add(c)}))}function a(l){l.revoked_&&ie(3,JSON.stringify(ae(l)))}Kd("MapSet",{proxyMap_:e,proxySet_:i})}function Cy(){process.env.NODE_ENV!=="production"&&Wd.push('Sets cannot have "replace" patches.',function(d){return"Unsupported patch operation: "+d},function(d){return"Cannot apply patch, path doesn't resolve: "+d},"Patching reserved attributes like __proto__, prototype and constructor is not allowed");let e="replace",t="add",n="remove";function i(d,p,m,g){switch(d.type_){case 0:case 2:return a(d,p,m,g);case 1:return o(d,p,m,g);case 3:return l(d,p,m,g)}}function o(d,p,m,g){let{base_:b,assigned_:y}=d,D=d.copy_;D.length<b.length&&([b,D]=[D,b],[m,g]=[g,m]);for(let v=0;v<b.length;v++)if(y[v]&&D[v]!==b[v]){let S=p.concat([v]);m.push({op:e,path:S,value:f(D[v])}),g.push({op:e,path:S,value:f(b[v])})}for(let v=b.length;v<D.length;v++){let S=p.concat([v]);m.push({op:t,path:S,value:f(D[v])})}for(let v=D.length-1;b.length<=v;--v){let S=p.concat([v]);g.push({op:n,path:S})}}function a(d,p,m,g){let{base_:b,copy_:y}=d;Zr(d.assigned_,(D,v)=>{let S=yo(b,D),E=yo(y,D),k=v?Sn(b,D)?e:t:n;if(S===E&&k===e)return;let x=p.concat(D);m.push(k===n?{op:k,path:x}:{op:k,path:x,value:E}),g.push(k===t?{op:n,path:x}:k===n?{op:t,path:x,value:f(S)}:{op:e,path:x,value:f(S)})})}function l(d,p,m,g){let{base_:b,copy_:y}=d,D=0;b.forEach(v=>{if(!y.has(v)){let S=p.concat([D]);m.push({op:n,path:S,value:v}),g.unshift({op:t,path:S,value:v})}D++}),D=0,y.forEach(v=>{if(!b.has(v)){let S=p.concat([D]);m.push({op:t,path:S,value:v}),g.unshift({op:n,path:S,value:v})}D++})}function c(d,p,m,g){m.push({op:e,path:[],value:p===qa?void 0:p}),g.push({op:e,path:[],value:d})}function u(d,p){return p.forEach(m=>{let{path:g,op:b}=m,y=d;for(let E=0;E<g.length-1;E++){let k=hr(y),x=g[E];typeof x!="string"&&typeof x!="number"&&(x=""+x),(k===0||k===1)&&(x==="__proto__"||x==="constructor")&&ie(19),typeof y=="function"&&x==="prototype"&&ie(19),y=yo(y,x),typeof y!="object"&&ie(18,g.join("/"))}let D=hr(y),v=h(m.value),S=g[g.length-1];switch(b){case e:switch(D){case 2:return y.set(S,v);case 3:ie(16);default:return y[S]=v}case t:switch(D){case 1:return S==="-"?y.push(v):y.splice(S,0,v);case 2:return y.set(S,v);case 3:return y.add(v);default:return y[S]=v}case n:switch(D){case 1:return y.splice(S,1);case 2:return y.delete(S);case 3:return y.delete(m.value);default:return delete y[S]}default:ie(17,b)}}),d}function h(d){if(!Xe(d))return d;if(Array.isArray(d))return d.map(h);if(Ln(d))return new Map(Array.from(d.entries()).map(([m,g])=>[m,h(g)]));if(Nn(d))return new Set(Array.from(d).map(h));let p=Object.create(dr(d));for(let m in d)p[m]=h(d[m]);return Sn(d,yn)&&(p[yn]=d[yn]),p}function f(d){return fr(d)?h(d):d}Kd("Patches",{applyPatches_:u,generatePatches_:i,generateReplacementPatches_:c})}var xe=new Dy;xe.produce;var Ey=xe.produceWithPatches.bind(xe);xe.setAutoFreeze.bind(xe);xe.setUseStrictShallowCopy.bind(xe);var $o=xe.applyPatches.bind(xe);xe.createDraft.bind(xe);xe.finishDraft.bind(xe);Sy();Cy();function Nr(...r){return r.filter(e=>e!==void 0).reduce((e,t)=>e.concat(t),[])}function od(r){return[{op:"replace",path:[],value:r}]}function Za(r,e){let t=(n,i)=>{r(()=>[n,od(n)],Nr(e?.(),i))};return t.withProducer=(n,i)=>{r(o=>{let[a,l]=Ey(o,n);if(dt(a))return[a,l];throw new Error("Cannot update value to NOT_AVAILABLE")},Nr(e?.(),i))},t.withUpdater=(n,i)=>{r(o=>{let a=n(o);return[a,od(a)]},Nr(e?.(),i))},t.withPatchUpdater=(n,i)=>{r(n,Nr(e?.(),i))},t.withPatches=(n,i)=>{r(o=>[$o(o,n),n],Nr(e?.(),i))},t.withValueAndPatches=(n,i,o)=>{r(()=>[n,i],Nr(e?.(),o))},t}var _y=(r,e)=>r===e,xn=class r extends Ft{static create(e,t=_y){let n=new r(e,t),o=Za((a,l)=>{n.update(a,l)});return[n,o]}static createReadonly(e){return r.create(e)[0]}constructor(e,t){super(),this.value=e,this.equalsPredicate=t,this.subscribers=new Set,this.queuedUpdaters=[],this.isEmitting=!1}get(){return this.value}pull(){return this.value}notifyFull(e,t,n){for(let{type:i,callback:o}of this.subscribers)i==="full"&&o(e,t,n)}notifyAll(e,t,n){for(let{type:i,callback:o}of this.subscribers)i==="regular"?o(e):o(e,t,n)}notifyAndUpdateIfChanged(e,t,n){this.equalsPredicate(this.value,e)?n.length>0&&this.notifyFull(e,t,n):(this.value=e,this.notifyAll(e,t,n))}isReplaceRoot(e){return e.path.length===0&&e.op==="replace"}update(e,t){if(this.queuedUpdaters.push([e,t]),!this.isEmitting){this.isEmitting=!0;try{for(;this.queuedUpdaters.length>0;){let n=this.value,i=[],o=[];for(;this.queuedUpdaters.length>0;){let[a,l]=this.queuedUpdaters.shift(),[c,u]=a(n);n=c;let h=u.findIndex(this.isReplaceRoot);h!==-1?i=u.slice(h):i.push(...u),l!==void 0&&o.push(...l)}this.notifyAndUpdateIfChanged(n,i,o)}}finally{this.isEmitting=!1}}}subscribe(e){let t={type:"regular",callback:e};return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}subscribeAndNow(e){let t=this.subscribe(e);return e(this.value),t}subscribeFull(e){let t={type:"full",callback:e};return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}async until(e){let t=this.get();if(e(t))return t;let{promise:n,resolve:i}=ee(),o=this.subscribe(a=>{e(a)&&(i(a),o())});return await n}};function dt(r){return r!==$e.NOT_AVAILABLE}var $e=class r extends Ft{static{this.NOT_AVAILABLE=Symbol("notAvailable")}static create(e,t,n=(i,o)=>i===o){return new r(e,t,n)}static createWithoutInitialValue(e,t=(n,i)=>n===i){let n=(i,o)=>i===r.NOT_AVAILABLE||o===r.NOT_AVAILABLE?i===o:t(i,o);return new r(r.NOT_AVAILABLE,e,n)}static deriveFrom(e,t,n){let i;n!==void 0&&(i=(a,l)=>a===r.NOT_AVAILABLE||l===r.NOT_AVAILABLE?a===l:n(a,l));let o=()=>{let a=e.map(l=>l.get());return a.some(l=>l===r.NOT_AVAILABLE)?r.NOT_AVAILABLE:t(...a)};return new r(o(),a=>{let l=e.map(u=>u.subscribe(()=>{let h=o();dt(h)&&a(h)})),c=o();return dt(c)&&a(c),()=>{l.forEach(u=>u())}},i)}static asyncDeriveFrom(e,t,n,i){let o;i!==void 0&&(o=(c,u)=>c===r.NOT_AVAILABLE||u===r.NOT_AVAILABLE?c===u:i(c,u));let a=-1,l=-1;return new r(r.NOT_AVAILABLE,c=>{let u=()=>{l++;let f=l,d=t.map(p=>p.get());d.some(p=>p===r.NOT_AVAILABLE)||n(...d).then(p=>{if(dt(p))if(e==="eager")f>a&&(a=f,c(p));else{let m=e;throw new Error(`Unknown strategy: ${m}`)}})},h=t.map(f=>f.subscribe(()=>{u()}));return u(),()=>{h.forEach(f=>f())}},o)}constructor(e,t,n=(i,o)=>i===o){super(),this.subscribeUpstream=t,this.dataIsStale=!0,this.upstreamUnsubscribe=null,this.subscribersCount=0,this.isSubscribedToUpstream=!1,this.updateReceivedSynchronousCallbacks=new Set,[this.signal,this.setValue]=xn.create(e,n),[this.updateReceivedEvent,this.emitUpdateReceivedEvent]=wn.create()}isStale(){return this.dataIsStale}subscribeToUpstream(){this.isSubscribedToUpstream=!0;let e=!0,t=!1,n=this.subscribeUpstream(Za((i,o)=>{if(e){this.setValue.withPatchUpdater(i,o),this.dataIsStale=t,this.emitUpdateReceivedEvent();for(let a of this.updateReceivedSynchronousCallbacks)a()}}),i=>{e&&(Promise.reject(i),this.dataIsStale=!0,this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe=null,e=!1)});this.upstreamUnsubscribe=()=>{e&&(e=!1,t=!0,n())}}unsubscribeFromUpstream(){this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe!==null&&(this.upstreamUnsubscribe(),this.upstreamUnsubscribe=null,this.dataIsStale=!0)}get(){return this.signal.get()}async pull(){let{promise:e,resolve:t}=ee();if(!this.isStale())t(this.get());else{let n=this.subscribe(()=>{});this.updateReceivedEvent.subscribeOnce(()=>{t(this.get())}),e.then(n)}return e}runOnNextFreshData(e){if(!this.isStale())e(this.get());else{let t=null,n=()=>{this.updateReceivedSynchronousCallbacks.delete(n),e(this.get()),t?.()};this.updateReceivedSynchronousCallbacks.add(n),t=this.subscribe(()=>{})}}async ensureAvailable(){return await this.pull(),this}subscribe(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let t=this.signal.subscribe(e),n=!1;return()=>{n||(t(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}subscribeFull(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let t=this.signal.subscribeFull(e),n=!1;return()=>{n||(t(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}passiveSubscribe(e){return this.signal.subscribe(e)}passiveSubscribeFull(e){return this.signal.subscribeFull(e)}async until(e){let t=this.get();if(dt(t)&&e(t))return t;let{promise:n,resolve:i}=ee(),o=this.subscribe(a=>{dt(a)&&e(a)&&(i(a),o())});return await n}},xy=[41343,52993,16141,39414,22931],gn=Symbol(),ht=class r extends Ft{static create(){let e=new r;return[e,n=>{e.emit(n)}]}constructor(){super(),this.subscriber=null,this.queued=[],this.isNotifying=!1}emit(e){this.queued.length===0&&this.queued.at(-1)!==gn&&this.queued.push(gn),this.queued.push(e),this.isNotifying||this.notifier()}async notifier(){for(this.isNotifying=!0;this.subscriber!==null&&this.queued.length>0;){let e=this.queued.shift();e===gn?await Promise.resolve():this.subscriber(e)}this.isNotifying=!1}subscribe(e){if(this.subscriber!==null)throw new Error("Cannot have more than one subscriber");return this.subscriber=e,!this.isNotifying&&this.queued.length>0&&(this.queued=[gn,...this.queued.filter(t=>t!==gn)],this.notifier()),()=>{this.subscriber=null}}flow(){let[e,t]=wn.create();return this.subscribe(t),e}},Uo=class extends Ft{constructor(){super(...arguments),this.canceled=!1,this.listeners=new Set}subscribe(e){if(this.canceled){let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}}return this.listeners.add(e),()=>{this.listeners.delete(e)}}cancel(){if(this.canceled)throw new Error("Already canceled");this.canceled=!0;for(let e of this.listeners)e()}isCanceled(){return this.canceled}},Ui=class{constructor(){this.eagerCleaned=!1,this.disposed=!1,this.cleanups=[]}register(e){if(this.eagerCleaned)throw new Error("Cannot register a cleanup after eagerClean() was called.");if(this.disposed)throw new Error("Cannot register a cleanup after the Cleaner was disposed.");this.cleanups.push(e)}runCleanersInternal(){for(let e of this.cleanups)e();this.cleanups.length=0}[Symbol.dispose](){if(!this.eagerCleaned){if(this.disposed)throw new Error("Cannot dispose a Cleaner that was already disposed.");this.runCleanersInternal()}}eagerClean(){if(this.eagerCleaned)throw new Error("Cannot call eagerClean() twice.");if(this.disposed)throw new Error("Cannot call eagerClean() after the Cleaner was disposed.");this.eagerCleaned=!0,this.runCleanersInternal()}};function A(r=0){let e=new Error().stack;return e?e.split(`
23
+ `).slice(2+r).join(`
24
+ `):""}function Do(r,e){if(Dn.default.env.LMS_KEEP_INTERNAL_STACK)return;let t=r.stack??"";r.stack=(t.substring(0,t.indexOf(`
25
+ at `)).trimEnd()+`
26
+ `+e).trimEnd()}var zi=class{constructor(e=0){this.nextId=e}next(){let e=this.nextId;return this.nextId++,e}};function ky(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ei={exports:{}},_i={exports:{}},wo,ad;function Fy(){return ad||(ad=1,wo=({onlyFirst:r=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,r?void 0:"g")}),wo}var So,ld;function Yd(){if(ld)return So;ld=1;let r=Fy();return So=e=>typeof e=="string"?e.replace(r(),""):e,So}var xi={exports:{}},cd;function Py(){if(cd)return xi.exports;cd=1;let r=e=>Number.isNaN(e)?!1:e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);return xi.exports=r,xi.exports.default=r,xi.exports}var Co,ud;function Ty(){return ud||(ud=1,Co=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}),Co}var dd;function ls(){if(dd)return _i.exports;dd=1;let r=Yd(),e=Py(),t=Ty(),n=i=>{if(typeof i!="string"||i.length===0||(i=r(i),i.length===0))return 0;i=i.replace(t()," ");let o=0;for(let a=0;a<i.length;a++){let l=i.codePointAt(a);l<=31||l>=127&&l<=159||l>=768&&l<=879||(l>65535&&a++,o+=e(l)?2:1)}return o};return _i.exports=n,_i.exports.default=n,_i.exports}var ki={exports:{}},fd;function Ay(){if(fd)return ki.exports;fd=1;let r=ls(),e=t=>{let n=0;for(let i of t.split(`
27
+ `))n=Math.max(n,r(i));return n};return ki.exports=e,ki.exports.default=e,ki.exports}var Fi={exports:{}},Ry={topLeft:"\u250C",topRight:"\u2510",bottomRight:"\u2518",bottomLeft:"\u2514",vertical:"\u2502",horizontal:"\u2500"},Iy={topLeft:"\u2554",topRight:"\u2557",bottomRight:"\u255D",bottomLeft:"\u255A",vertical:"\u2551",horizontal:"\u2550"},Oy={topLeft:"\u256D",topRight:"\u256E",bottomRight:"\u256F",bottomLeft:"\u2570",vertical:"\u2502",horizontal:"\u2500"},My={topLeft:"\u250F",topRight:"\u2513",bottomRight:"\u251B",bottomLeft:"\u2517",vertical:"\u2503",horizontal:"\u2501"},jy={topLeft:"\u2553",topRight:"\u2556",bottomRight:"\u255C",bottomLeft:"\u2559",vertical:"\u2551",horizontal:"\u2500"},By={topLeft:"\u2552",topRight:"\u2555",bottomRight:"\u255B",bottomLeft:"\u2558",vertical:"\u2502",horizontal:"\u2550"},Ly={topLeft:"+",topRight:"+",bottomRight:"+",bottomLeft:"+",vertical:"|",horizontal:"-"},Ny={single:Ry,double:Iy,round:Oy,bold:My,singleDouble:jy,doubleSingle:By,classic:Ly},hd;function $y(){if(hd)return Fi.exports;hd=1;let r=Ny;return Fi.exports=r,Fi.exports.default=r,Fi.exports}var Pi={exports:{}},pd;function Uy(){if(pd)return Pi.exports;pd=1;let r=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,o=new RegExp("^"+i.source),a=new RegExp(i.source+n.source,"gu"),l=new RegExp("\\d+"+n.source,"gu"),c=(d,p,m)=>{let g=!1,b=!1,y=!1;for(let D=0;D<d.length;D++){let v=d[D];g&&r.test(v)?(d=d.slice(0,D)+"-"+d.slice(D),g=!1,y=b,b=!0,D++):b&&y&&e.test(v)?(d=d.slice(0,D-1)+"-"+d.slice(D-1),y=b,b=!1,g=!0):(g=p(v)===v&&m(v)!==v,y=b,b=m(v)===v&&p(v)!==v)}return d},u=(d,p)=>(t.lastIndex=0,d.replace(t,m=>p(m))),h=(d,p)=>(a.lastIndex=0,l.lastIndex=0,d.replace(a,(m,g)=>p(g)).replace(l,m=>p(m))),f=(d,p)=>{if(!(typeof d=="string"||Array.isArray(d)))throw new TypeError("Expected the input to be `string | string[]`");if(p={pascalCase:!1,preserveConsecutiveUppercase:!1,...p},Array.isArray(d)?d=d.map(y=>y.trim()).filter(y=>y.length).join("-"):d=d.trim(),d.length===0)return"";let m=p.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(p.locale),g=p.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(p.locale);return d.length===1?p.pascalCase?g(d):m(d):(d!==m(d)&&(d=c(d,m,g)),d=d.replace(o,""),p.preserveConsecutiveUppercase?d=u(d,m):d=m(d),p.pascalCase&&(d=g(d.charAt(0))+d.slice(1)),h(d,g))};return Pi.exports=f,Pi.exports.default=f,Pi.exports}var Eo,md;function zy(){if(md)return Eo;md=1;let r=ls();function e(i,o){if(!i)return i;o=o||{};let a=o.align||"center";if(a==="left")return i;let l=o.split||`
28
+ `,c=o.pad||" ",u=a!=="right"?t:n,h=!1;Array.isArray(i)||(h=!0,i=String(i).split(l));let f,d=0;return i=i.map(function(p){return p=String(p),f=r(p),d=Math.max(f,d),{str:p,width:f}}).map(function(p){return new Array(u(d,p.width)+1).join(c)+p.str}),h?i.join(l):i}e.left=function(o){return e(o,{align:"left"})},e.center=function(o){return e(o,{align:"center"})},e.right=function(o){return e(o,{align:"right"})},Eo=e;function t(i,o){return Math.floor((i-o)/2)}function n(i,o){return i-o}return Eo}var Oi={exports:{}},_o,gd;function qy(){return gd||(gd=1,_o={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),_o}var xo,yd;function Qd(){if(yd)return xo;yd=1;let r=qy(),e={};for(let i of Object.keys(r))e[r[i]]=i;let t={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};xo=t;for(let i of Object.keys(t)){if(!("channels"in t[i]))throw new Error("missing channels property: "+i);if(!("labels"in t[i]))throw new Error("missing channel labels property: "+i);if(t[i].labels.length!==t[i].channels)throw new Error("channel and label counts mismatch: "+i);let{channels:o,labels:a}=t[i];delete t[i].channels,delete t[i].labels,Object.defineProperty(t[i],"channels",{value:o}),Object.defineProperty(t[i],"labels",{value:a})}t.rgb.hsl=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(o,a,l),u=Math.max(o,a,l),h=u-c,f,d;u===c?f=0:o===u?f=(a-l)/h:a===u?f=2+(l-o)/h:l===u&&(f=4+(o-a)/h),f=Math.min(f*60,360),f<0&&(f+=360);let p=(c+u)/2;return u===c?d=0:p<=.5?d=h/(u+c):d=h/(2-u-c),[f,d*100,p*100]},t.rgb.hsv=function(i){let o,a,l,c,u,h=i[0]/255,f=i[1]/255,d=i[2]/255,p=Math.max(h,f,d),m=p-Math.min(h,f,d),g=function(b){return(p-b)/6/m+1/2};return m===0?(c=0,u=0):(u=m/p,o=g(h),a=g(f),l=g(d),h===p?c=l-a:f===p?c=1/3+o-l:d===p&&(c=2/3+a-o),c<0?c+=1:c>1&&(c-=1)),[c*360,u*100,p*100]},t.rgb.hwb=function(i){let o=i[0],a=i[1],l=i[2],c=t.rgb.hsl(i)[0],u=1/255*Math.min(o,Math.min(a,l));return l=1-1/255*Math.max(o,Math.max(a,l)),[c,u*100,l*100]},t.rgb.cmyk=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(1-o,1-a,1-l),u=(1-o-c)/(1-c)||0,h=(1-a-c)/(1-c)||0,f=(1-l-c)/(1-c)||0;return[u*100,h*100,f*100,c*100]};function n(i,o){return(i[0]-o[0])**2+(i[1]-o[1])**2+(i[2]-o[2])**2}return t.rgb.keyword=function(i){let o=e[i];if(o)return o;let a=1/0,l;for(let c of Object.keys(r)){let u=r[c],h=n(i,u);h<a&&(a=h,l=c)}return l},t.keyword.rgb=function(i){return r[i]},t.rgb.xyz=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255;o=o>.04045?((o+.055)/1.055)**2.4:o/12.92,a=a>.04045?((a+.055)/1.055)**2.4:a/12.92,l=l>.04045?((l+.055)/1.055)**2.4:l/12.92;let c=o*.4124+a*.3576+l*.1805,u=o*.2126+a*.7152+l*.0722,h=o*.0193+a*.1192+l*.9505;return[c*100,u*100,h*100]},t.rgb.lab=function(i){let o=t.rgb.xyz(i),a=o[0],l=o[1],c=o[2];a/=95.047,l/=100,c/=108.883,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116,c=c>.008856?c**(1/3):7.787*c+16/116;let u=116*l-16,h=500*(a-l),f=200*(l-c);return[u,h,f]},t.hsl.rgb=function(i){let o=i[0]/360,a=i[1]/100,l=i[2]/100,c,u,h;if(a===0)return h=l*255,[h,h,h];l<.5?c=l*(1+a):c=l+a-l*a;let f=2*l-c,d=[0,0,0];for(let p=0;p<3;p++)u=o+1/3*-(p-1),u<0&&u++,u>1&&u--,6*u<1?h=f+(c-f)*6*u:2*u<1?h=c:3*u<2?h=f+(c-f)*(2/3-u)*6:h=f,d[p]=h*255;return d},t.hsl.hsv=function(i){let o=i[0],a=i[1]/100,l=i[2]/100,c=a,u=Math.max(l,.01);l*=2,a*=l<=1?l:2-l,c*=u<=1?u:2-u;let h=(l+a)/2,f=l===0?2*c/(u+c):2*a/(l+a);return[o,f*100,h*100]},t.hsv.rgb=function(i){let o=i[0]/60,a=i[1]/100,l=i[2]/100,c=Math.floor(o)%6,u=o-Math.floor(o),h=255*l*(1-a),f=255*l*(1-a*u),d=255*l*(1-a*(1-u));switch(l*=255,c){case 0:return[l,d,h];case 1:return[f,l,h];case 2:return[h,l,d];case 3:return[h,f,l];case 4:return[d,h,l];case 5:return[l,h,f]}},t.hsv.hsl=function(i){let o=i[0],a=i[1]/100,l=i[2]/100,c=Math.max(l,.01),u,h;h=(2-a)*l;let f=(2-a)*c;return u=a*c,u/=f<=1?f:2-f,u=u||0,h/=2,[o,u*100,h*100]},t.hwb.rgb=function(i){let o=i[0]/360,a=i[1]/100,l=i[2]/100,c=a+l,u;c>1&&(a/=c,l/=c);let h=Math.floor(6*o),f=1-l;u=6*o-h,(h&1)!==0&&(u=1-u);let d=a+u*(f-a),p,m,g;switch(h){default:case 6:case 0:p=f,m=d,g=a;break;case 1:p=d,m=f,g=a;break;case 2:p=a,m=f,g=d;break;case 3:p=a,m=d,g=f;break;case 4:p=d,m=a,g=f;break;case 5:p=f,m=a,g=d;break}return[p*255,m*255,g*255]},t.cmyk.rgb=function(i){let o=i[0]/100,a=i[1]/100,l=i[2]/100,c=i[3]/100,u=1-Math.min(1,o*(1-c)+c),h=1-Math.min(1,a*(1-c)+c),f=1-Math.min(1,l*(1-c)+c);return[u*255,h*255,f*255]},t.xyz.rgb=function(i){let o=i[0]/100,a=i[1]/100,l=i[2]/100,c,u,h;return c=o*3.2406+a*-1.5372+l*-.4986,u=o*-.9689+a*1.8758+l*.0415,h=o*.0557+a*-.204+l*1.057,c=c>.0031308?1.055*c**(1/2.4)-.055:c*12.92,u=u>.0031308?1.055*u**(1/2.4)-.055:u*12.92,h=h>.0031308?1.055*h**(1/2.4)-.055:h*12.92,c=Math.min(Math.max(0,c),1),u=Math.min(Math.max(0,u),1),h=Math.min(Math.max(0,h),1),[c*255,u*255,h*255]},t.xyz.lab=function(i){let o=i[0],a=i[1],l=i[2];o/=95.047,a/=100,l/=108.883,o=o>.008856?o**(1/3):7.787*o+16/116,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116;let c=116*a-16,u=500*(o-a),h=200*(a-l);return[c,u,h]},t.lab.xyz=function(i){let o=i[0],a=i[1],l=i[2],c,u,h;u=(o+16)/116,c=a/500+u,h=u-l/200;let f=u**3,d=c**3,p=h**3;return u=f>.008856?f:(u-16/116)/7.787,c=d>.008856?d:(c-16/116)/7.787,h=p>.008856?p:(h-16/116)/7.787,c*=95.047,u*=100,h*=108.883,[c,u,h]},t.lab.lch=function(i){let o=i[0],a=i[1],l=i[2],c;c=Math.atan2(l,a)*360/2/Math.PI,c<0&&(c+=360);let h=Math.sqrt(a*a+l*l);return[o,h,c]},t.lch.lab=function(i){let o=i[0],a=i[1],c=i[2]/360*2*Math.PI,u=a*Math.cos(c),h=a*Math.sin(c);return[o,u,h]},t.rgb.ansi16=function(i,o=null){let[a,l,c]=i,u=o===null?t.rgb.hsv(i)[2]:o;if(u=Math.round(u/50),u===0)return 30;let h=30+(Math.round(c/255)<<2|Math.round(l/255)<<1|Math.round(a/255));return u===2&&(h+=60),h},t.hsv.ansi16=function(i){return t.rgb.ansi16(t.hsv.rgb(i),i[2])},t.rgb.ansi256=function(i){let o=i[0],a=i[1],l=i[2];return o===a&&a===l?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(a/255*5)+Math.round(l/255*5)},t.ansi16.rgb=function(i){let o=i%10;if(o===0||o===7)return i>50&&(o+=3.5),o=o/10.5*255,[o,o,o];let a=(~~(i>50)+1)*.5,l=(o&1)*a*255,c=(o>>1&1)*a*255,u=(o>>2&1)*a*255;return[l,c,u]},t.ansi256.rgb=function(i){if(i>=232){let u=(i-232)*10+8;return[u,u,u]}i-=16;let o,a=Math.floor(i/36)/5*255,l=Math.floor((o=i%36)/6)/5*255,c=o%6/5*255;return[a,l,c]},t.rgb.hex=function(i){let a=(((Math.round(i[0])&255)<<16)+((Math.round(i[1])&255)<<8)+(Math.round(i[2])&255)).toString(16).toUpperCase();return"000000".substring(a.length)+a},t.hex.rgb=function(i){let o=i.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!o)return[0,0,0];let a=o[0];o[0].length===3&&(a=a.split("").map(f=>f+f).join(""));let l=parseInt(a,16),c=l>>16&255,u=l>>8&255,h=l&255;return[c,u,h]},t.rgb.hcg=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.max(Math.max(o,a),l),u=Math.min(Math.min(o,a),l),h=c-u,f,d;return h<1?f=u/(1-h):f=0,h<=0?d=0:c===o?d=(a-l)/h%6:c===a?d=2+(l-o)/h:d=4+(o-a)/h,d/=6,d%=1,[d*360,h*100,f*100]},t.hsl.hcg=function(i){let o=i[1]/100,a=i[2]/100,l=a<.5?2*o*a:2*o*(1-a),c=0;return l<1&&(c=(a-.5*l)/(1-l)),[i[0],l*100,c*100]},t.hsv.hcg=function(i){let o=i[1]/100,a=i[2]/100,l=o*a,c=0;return l<1&&(c=(a-l)/(1-l)),[i[0],l*100,c*100]},t.hcg.rgb=function(i){let o=i[0]/360,a=i[1]/100,l=i[2]/100;if(a===0)return[l*255,l*255,l*255];let c=[0,0,0],u=o%1*6,h=u%1,f=1-h,d=0;switch(Math.floor(u)){case 0:c[0]=1,c[1]=h,c[2]=0;break;case 1:c[0]=f,c[1]=1,c[2]=0;break;case 2:c[0]=0,c[1]=1,c[2]=h;break;case 3:c[0]=0,c[1]=f,c[2]=1;break;case 4:c[0]=h,c[1]=0,c[2]=1;break;default:c[0]=1,c[1]=0,c[2]=f}return d=(1-a)*l,[(a*c[0]+d)*255,(a*c[1]+d)*255,(a*c[2]+d)*255]},t.hcg.hsv=function(i){let o=i[1]/100,a=i[2]/100,l=o+a*(1-o),c=0;return l>0&&(c=o/l),[i[0],c*100,l*100]},t.hcg.hsl=function(i){let o=i[1]/100,l=i[2]/100*(1-o)+.5*o,c=0;return l>0&&l<.5?c=o/(2*l):l>=.5&&l<1&&(c=o/(2*(1-l))),[i[0],c*100,l*100]},t.hcg.hwb=function(i){let o=i[1]/100,a=i[2]/100,l=o+a*(1-o);return[i[0],(l-o)*100,(1-l)*100]},t.hwb.hcg=function(i){let o=i[1]/100,l=1-i[2]/100,c=l-o,u=0;return c<1&&(u=(l-c)/(1-c)),[i[0],c*100,u*100]},t.apple.rgb=function(i){return[i[0]/65535*255,i[1]/65535*255,i[2]/65535*255]},t.rgb.apple=function(i){return[i[0]/255*65535,i[1]/255*65535,i[2]/255*65535]},t.gray.rgb=function(i){return[i[0]/100*255,i[0]/100*255,i[0]/100*255]},t.gray.hsl=function(i){return[0,0,i[0]]},t.gray.hsv=t.gray.hsl,t.gray.hwb=function(i){return[0,100,i[0]]},t.gray.cmyk=function(i){return[0,0,0,i[0]]},t.gray.lab=function(i){return[i[0],0,0]},t.gray.hex=function(i){let o=Math.round(i[0]/100*255)&255,l=((o<<16)+(o<<8)+o).toString(16).toUpperCase();return"000000".substring(l.length)+l},t.rgb.gray=function(i){return[(i[0]+i[1]+i[2])/3/255*100]},xo}var ko,bd;function Vy(){if(bd)return ko;bd=1;let r=Qd();function e(){let o={},a=Object.keys(r);for(let l=a.length,c=0;c<l;c++)o[a[c]]={distance:-1,parent:null};return o}function t(o){let a=e(),l=[o];for(a[o].distance=0;l.length;){let c=l.pop(),u=Object.keys(r[c]);for(let h=u.length,f=0;f<h;f++){let d=u[f],p=a[d];p.distance===-1&&(p.distance=a[c].distance+1,p.parent=c,l.unshift(d))}}return a}function n(o,a){return function(l){return a(o(l))}}function i(o,a){let l=[a[o].parent,o],c=r[a[o].parent][o],u=a[o].parent;for(;a[u].parent;)l.unshift(a[u].parent),c=n(r[a[u].parent][u],c),u=a[u].parent;return c.conversion=l,c}return ko=function(o){let a=t(o),l={},c=Object.keys(a);for(let u=c.length,h=0;h<u;h++){let f=c[h];a[f].parent!==null&&(l[f]=i(f,a))}return l},ko}var Fo,vd;function Wy(){if(vd)return Fo;vd=1;let r=Qd(),e=Vy(),t={},n=Object.keys(r);function i(a){let l=function(...c){let u=c[0];return u==null?u:(u.length>1&&(c=u),a(c))};return"conversion"in a&&(l.conversion=a.conversion),l}function o(a){let l=function(...c){let u=c[0];if(u==null)return u;u.length>1&&(c=u);let h=a(c);if(typeof h=="object")for(let f=h.length,d=0;d<f;d++)h[d]=Math.round(h[d]);return h};return"conversion"in a&&(l.conversion=a.conversion),l}return n.forEach(a=>{t[a]={},Object.defineProperty(t[a],"channels",{value:r[a].channels}),Object.defineProperty(t[a],"labels",{value:r[a].labels});let l=e(a);Object.keys(l).forEach(u=>{let h=l[u];t[a][u]=o(h),t[a][u].raw=i(h)})}),Fo=t,Fo}Oi.exports;var Dd;function Zy(){return Dd||(Dd=1,(function(r){let e=(h,f)=>(...d)=>`\x1B[${h(...d)+f}m`,t=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};5;${p}m`},n=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};2;${p[0]};${p[1]};${p[2]}m`},i=h=>h,o=(h,f,d)=>[h,f,d],a=(h,f,d)=>{Object.defineProperty(h,f,{get:()=>{let p=d();return Object.defineProperty(h,f,{value:p,enumerable:!0,configurable:!0}),p},enumerable:!0,configurable:!0})},l,c=(h,f,d,p)=>{l===void 0&&(l=Wy());let m=p?10:0,g={};for(let[b,y]of Object.entries(l)){let D=b==="ansi16"?"ansi":b;b===f?g[D]=h(d,m):typeof y=="object"&&(g[D]=h(y[f],m))}return g};function u(){let h=new Map,f={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};f.color.gray=f.color.blackBright,f.bgColor.bgGray=f.bgColor.bgBlackBright,f.color.grey=f.color.blackBright,f.bgColor.bgGrey=f.bgColor.bgBlackBright;for(let[d,p]of Object.entries(f)){for(let[m,g]of Object.entries(p))f[m]={open:`\x1B[${g[0]}m`,close:`\x1B[${g[1]}m`},p[m]=f[m],h.set(g[0],g[1]);Object.defineProperty(f,d,{value:p,enumerable:!1})}return Object.defineProperty(f,"codes",{value:h,enumerable:!1}),f.color.close="\x1B[39m",f.bgColor.close="\x1B[49m",a(f.color,"ansi",()=>c(e,"ansi16",i,!1)),a(f.color,"ansi256",()=>c(t,"ansi256",i,!1)),a(f.color,"ansi16m",()=>c(n,"rgb",o,!1)),a(f.bgColor,"ansi",()=>c(e,"ansi16",i,!0)),a(f.bgColor,"ansi256",()=>c(t,"ansi256",i,!0)),a(f.bgColor,"ansi16m",()=>c(n,"rgb",o,!0)),f}Object.defineProperty(r,"exports",{enumerable:!0,get:u})})(Oi)),Oi.exports}var Po,wd;function Gy(){if(wd)return Po;wd=1;let r=ls(),e=Yd(),t=Zy(),n=new Set(["\x1B","\x9B"]),i=39,o="\x07",a="[",l="]",c="m",u=`${l}8;;`,h=b=>`${n.values().next().value}${a}${b}${c}`,f=b=>`${n.values().next().value}${u}${b}${o}`,d=b=>b.split(" ").map(y=>r(y)),p=(b,y,D)=>{let v=[...y],S=!1,E=!1,k=r(e(b[b.length-1]));for(let[x,z]of v.entries()){let w=r(z);if(k+w<=D?b[b.length-1]+=z:(b.push(z),k=0),n.has(z)&&(S=!0,E=v.slice(x+1).join("").startsWith(u)),S){E?z===o&&(S=!1,E=!1):z===c&&(S=!1);continue}k+=w,k===D&&x<v.length-1&&(b.push(""),k=0)}!k&&b[b.length-1].length>0&&b.length>1&&(b[b.length-2]+=b.pop())},m=b=>{let y=b.split(" "),D=y.length;for(;D>0&&!(r(y[D-1])>0);)D--;return D===y.length?b:y.slice(0,D).join(" ")+y.slice(D).join("")},g=(b,y,D={})=>{if(D.trim!==!1&&b.trim()==="")return"";let v="",S,E,k=d(b),x=[""];for(let[w,C]of b.split(" ").entries()){D.trim!==!1&&(x[x.length-1]=x[x.length-1].trimStart());let P=r(x[x.length-1]);if(w!==0&&(P>=y&&(D.wordWrap===!1||D.trim===!1)&&(x.push(""),P=0),(P>0||D.trim===!1)&&(x[x.length-1]+=" ",P++)),D.hard&&k[w]>y){let U=y-P,Z=1+Math.floor((k[w]-U-1)/y);Math.floor((k[w]-1)/y)<Z&&x.push(""),p(x,C,y);continue}if(P+k[w]>y&&P>0&&k[w]>0){if(D.wordWrap===!1&&P<y){p(x,C,y);continue}x.push("")}if(P+k[w]>y&&D.wordWrap===!1){p(x,C,y);continue}x[x.length-1]+=C}D.trim!==!1&&(x=x.map(m));let z=[...x.join(`
29
+ `)];for(let[w,C]of z.entries()){if(v+=C,n.has(C)){let{groups:U}=new RegExp(`(?:\\${a}(?<code>\\d+)m|\\${u}(?<uri>.*)${o})`).exec(z.slice(w).join(""))||{groups:{}};if(U.code!==void 0){let Z=Number.parseFloat(U.code);S=Z===i?void 0:Z}else U.uri!==void 0&&(E=U.uri.length===0?void 0:U.uri)}let P=t.codes.get(Number(S));z[w+1]===`
30
+ `?(E&&(v+=f("")),S&&P&&(v+=h(P))):C===`
31
+ `&&(S&&P&&(v+=h(S)),E&&(v+=f(E)))}return v};return Po=(b,y,D)=>String(b).normalize().replace(/\r\n/g,`
32
+ `).split(`
33
+ `).map(v=>g(v,y,D)).join(`
34
+ `),Po}var Sd;function Ky(){if(Sd)return Ei.exports;Sd=1;let r=ls(),e=I.default,t=Ay(),n=$y(),i=Uy(),o=zy(),a=Gy(),l=`
35
+ `,c=" ",u=()=>{let{env:D,stdout:v,stderr:S}=process;return v&&v.columns?v.columns:S&&S.columns?S.columns:D.COLUMNS?Number.parseInt(D.COLUMNS,10):80},h=D=>typeof D=="number"?{top:D,right:D*3,bottom:D,left:D*3}:{top:0,right:0,bottom:0,left:0,...D},f=D=>{let v=["topLeft","topRight","bottomRight","bottomLeft","vertical","horizontal"],S;if(typeof D=="string"){if(S=n[D],!S)throw new TypeError(`Invalid border style: ${D}`)}else{for(let E of v)if(!D[E]||typeof D[E]!="string")throw new TypeError(`Invalid border style: ${E}`);S=D}return S},d=(D,v,S)=>{let E="",k=r(D);switch(S){case"left":E=D+v.slice(k);break;case"right":E=v.slice(k)+D;break;default:v=v.slice(k),v.length%2===1?(v=v.slice(Math.floor(v.length/2)),E=v.slice(1)+D+v):(v=v.slice(v.length/2),E=v+D+v);break}return E},p=(D,v,S,E)=>{D=o(D,{align:E});let k=D.split(l),x=t(D),z=S-v.left-v.right;if(x>z){let P=[];for(let U of k){let Z=a(U,z,{hard:!0}),Ce=o(Z,{align:E}).split(`
36
+ `),ge=Math.max(...Ce.map(ye=>r(ye)));for(let ye of Ce){let Q;switch(E){case"center":Q=c.repeat((z-ge)/2)+ye;break;case"right":Q=c.repeat(z-ge)+ye;break;default:Q=ye;break}P.push(Q)}}k=P}E==="center"&&x<z?k=k.map(P=>c.repeat((z-x)/2)+P):E==="right"&&x<z&&(k=k.map(P=>c.repeat(z-x)+P));let w=c.repeat(v.left),C=c.repeat(v.right);return k=k.map(P=>w+P+C),k=k.map(P=>{if(S-r(P)>0)switch(E){case"center":return P+c.repeat(S-r(P));case"right":return P+c.repeat(S-r(P));default:return P+c.repeat(S-r(P))}return P}),v.top>0&&(k=new Array(v.top).fill(c.repeat(S)).concat(k)),v.bottom>0&&(k=k.concat(new Array(v.bottom).fill(c.repeat(S)))),k.join(l)},m=D=>D.match(/^#(?:[0-f]{3}){1,2}$/i),g=D=>typeof D=="string"&&(e[D]||m(D)),b=D=>m(D)?e.hex(D):e[D],y=D=>m(D)?e.bgHex(D):e[i(["bg",D])];return Ei.exports=(D,v)=>{v={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...v},v.align&&(v.textAlignment=v.align);let S=2;if(v.borderColor&&!g(v.borderColor))throw new Error(`${v.borderColor} is not a valid borderColor`);if(v.backgroundColor&&!g(v.backgroundColor))throw new Error(`${v.backgroundColor} is not a valid backgroundColor`);let E=f(v.borderStyle),k=h(v.padding),x=h(v.margin),z=be=>{let N=v.borderColor?b(v.borderColor)(be):be;return v.dimBorder?e.dim(N):N},w=be=>v.backgroundColor?y(v.backgroundColor)(be):be,C=u()-1,P=t(a(D,C-S,{hard:!0,trim:!1}))+k.left+k.right,U=v.title&&v.title.slice(0,C-4-x.left-x.right);if(U&&(U=` ${U} `,r(U)>P&&(P=r(U))),x.left&&x.right&&P+S+x.left+x.right>C){let N=(C-P-S)/(x.left+x.right);x.left=Math.max(0,Math.floor(x.left*N)),x.right=Math.max(0,Math.floor(x.right*N))}P=Math.min(P,C-S-x.left-x.right),D=p(D,k,P,v.textAlignment);let Z=c.repeat(x.left);if(v.float==="center"){let be=Math.max((C-P-S)/2,0);Z=c.repeat(be)}else if(v.float==="right"){let be=Math.max(C-P-x.right-S,0);Z=c.repeat(be)}let q=E.horizontal.repeat(P),Ce=z(l.repeat(x.top)+Z+E.topLeft+(U?d(U,q,v.titleAlignment):q)+E.topRight),ge=z(Z+E.bottomLeft+q+E.bottomRight+l.repeat(x.bottom)),ye=z(E.vertical),Q=l,Yr=D.split(l).map(be=>Z+ye+w(be)+ye).join(Q);return Ce+Q+Yr+Q+ge},Ei.exports._borderStyles=n,Ei.exports}var Hy=Ky(),Jy=ky(Hy);function mr(r,e,t){return pe(I.default.redBright(r)+`
37
+
38
+ `+e,t)}function pe(r,e){if(Dn.default.browser||Dn.default.env.LMS_NO_FANCY_ERRORS||(0,Qe.terminalSize)().columns<80){let t=new Error(r);return e===void 0?Do(t,""):Do(t,e),t}else{e!==void 0&&(r+=`
39
+
40
+
41
+ `+I.default.bgWhite.black(" </> STACK TRACE ")+`
42
+
43
+ `+I.default.gray(e));let t=new Error(`
44
+ `+Jy(r,{padding:1,margin:1,borderColor:"redBright",title:"Error"}));return Object.defineProperty(t,"lmstudioRawError",{value:r,enumerable:!1}),Do(t,""),t}}var Cd=new WeakMap;function j(r,...e){if(e.length+1!==r.length)throw new Error("text called with the wrong number of arguments.");let t=Cd.get(r);t===void 0&&(t=db(r),Cd.set(r,t));for(let n=0;n<e.length;n++)if(typeof e[n]=="object")if(typeof e[n].stack=="string")t[n*2+1]=e[n].stack;else try{t[n*2+1]=JSON.stringify(e[n])}catch{t[n*2+1]="[Object failed to stringify]"}else t[n*2+1]=String(e[n]);return t.join("")}function Yy(r){return r.replace(/^\n+/,"")}function Qy(r){return r.replace(/[\n ]+$/,"")}function Xy(r){return r.replace(/^ +/,"")}function eb(r){return r.replace(/ +$/,"")}function tb(r){let e=[],t=[];for(let n of r){let i=-1,o;for(;(o=n.indexOf(`
45
+ `,i+1))!==-1;)t.push(n.substring(i+1,o)),e.push(t),t=[],i=o;t.push(n.substring(i+1))}return e.push(t),e}function rb(r){let e=0;for(let t of r)if(t===" ")e++;else return e;return 1/0}function nb(r){let e=r[0],t=rb(e);return t===1/0?r.length===1?1/0:e.length:t}function ib(r){let e=1/0;for(let t of r)e=Math.min(e,nb(t));return e}function sb(r,e){return r.length<e?"":r.slice(e)}function ob(r,e){for(let t of r)t[0]=sb(t[0],e)}function ab(r){if(r.length!==1)return!1;for(let e of r[0])if(e!==" ")return!1;return!0}function lb(r){let e=r.map(ab),t=[],n=[];for(let i=0;i<r.length;i++){if(e[i]){n.length!==0&&(t.push(n),n=[]);continue}if(n.length!==0){let o=eb(n[n.length-1]),a=Xy(r[i][0]);n[n.length-1]=o+" "+a,n.push(...r[i].slice(1))}else n.push(...r[i])}return n.length!==0&&t.push(n),t}function cb(r){let e=[];if(r.length===0)return[""];e.push(...r[0]);for(let t=1;t<r.length;t++)e[e.length-1]+=`
46
+
47
+ `+r[t][0],e.push(...r[t].slice(1));return e}function ub(r){let e=[];for(let t=0;t<r.length;t++)e.push(r[t]),t<r.length-1&&e.push("");return e}function db(r){let e=[...r];e[0]=Yy(e[0]),e[e.length-1]=Qy(e[e.length-1]);let t=tb(e),n=ib(t);ob(t,n);let i=lb(t);return ub(cb(i))}var qi=class{constructor(e,t){this.data=e,this.mutable=t}_internalGetData(){return this.data}_internalToMutable(){return this.mutable?this:this.asMutableCopy()}asMutableCopy(){return this.create(this.cloneData(this.data),!0)}asImmutableCopy(){return this.mutable?this.create(this.cloneData(this.data),!1):this}guardMutable(){if(!this.mutable)throw new Error(j`
48
+ Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
49
+ mutable copy.
50
+ `)}};var zo=class r extends Ft{static{this.NOT_AVAILABLE=$e.NOT_AVAILABLE}applyOptimisticUpdates(e){for(let t of this.queuedUpdates)[e]=t.updater(e);return e}updateOptimisticValue(e){let t=this.innerSignal.get();dt(t)&&this.setOuterSignal(this.applyOptimisticUpdates(t),e)}constructor(e,t,n,i){super(),this.writeUpstream=n,this.isWriteLoopRunning=!1,this.isSubscriptionHandledByWriteLoop=!1,this.queuedUpdates=[],this.currentEnsureAvailablePromise=null,[this.writeErrorEvent,this.emitWriteErrorEvent]=wn.create(),[this.outerSignal,this.setOuterSignal]=xn.create(e,i),this.innerSignal=$e.create(e,t,i),this.innerSignal.passiveSubscribeFull((o,a,l)=>{this.isSubscriptionHandledByWriteLoop||this.updateOptimisticValue(l)})}static create(e,t,n,i=(o,a)=>o===a){let o=new r(e,t,n,i),a=Za(o.update.bind(o));return[o,a,(c,u)=>o.emitWriteErrorEvent({tags:c,error:u})]}static createWithoutInitialValue(e,t,n=(i,o)=>i===o){let i=(o,a)=>o===r.NOT_AVAILABLE||a===r.NOT_AVAILABLE?o===a:n(o,a);return r.create(r.NOT_AVAILABLE,e,t,i)}async update(e,t){let{promise:n,reject:i,resolve:o}=ee();return this.queuedUpdates.push({updater:e,tags:t??[],resolve:o,reject:i}),this.updateOptimisticValue(),this.ensureWriteLoop(),n}ensureWriteLoop(){this.isWriteLoopRunning||this.writeLoop()}async writeLoop(){let e=this.innerSignal.subscribe(()=>{});for(this.isWriteLoopRunning=!0,this.isStale()&&await this.innerSignal.pull();this.queuedUpdates.length>0;){let t=this.queuedUpdates.length,n=c=>{let u=[];for(let h=0;h<t;h++){let[f,d]=this.queuedUpdates[h].updater(c);c=f,u.push(...d)}return[c,u]},i=()=>{for(let c=0;c<t;c++)this.queuedUpdates[c].resolve()},o=c=>{for(let u=0;u<t;u++)this.queuedUpdates[u].reject(c)},a=this.queuedUpdates.flatMap(c=>c.tags),l=Date.now()+"-"+Math.random();await new Promise(c=>{this.isSubscriptionHandledByWriteLoop=!0;let u=[],h=()=>{this.isSubscriptionHandledByWriteLoop=!1,u.forEach(d=>d()),c()};u.push(this.innerSignal.subscribeFull((d,p,m)=>{this.isSubscriptionHandledByWriteLoop&&(m?.includes(l)?(h(),i(),this.queuedUpdates.splice(0,t),this.updateOptimisticValue(m.filter(g=>g!==l))):this.updateOptimisticValue(m))})),u.push(this.writeErrorEvent.subscribe(({tags:d,error:p})=>{this.isSubscriptionHandledByWriteLoop&&d.includes(l)&&(h(),o(p),this.queuedUpdates.splice(0,t))})),this.writeUpstream(...n(this.innerSignal.get()),[l,...a])||(h(),i(),this.queuedUpdates.splice(0,t),this.updateOptimisticValue(a.filter(d=>d!==l)))})}this.isWriteLoopRunning=!1,e()}isStale(){return this.innerSignal.isStale()}get(){return this.outerSignal.get()}getPessimistic(){return this.innerSignal.get()}async pull({optimistic:e=!0}={}){return e?this.applyOptimisticUpdates(await this.innerSignal.pull()):this.innerSignal.pull()}async ensureAvailable(){return this.currentEnsureAvailablePromise===null&&(this.currentEnsureAvailablePromise=(async()=>(await this.innerSignal.pull(),this))()),this.currentEnsureAvailablePromise}subscribe(e){let t=this.outerSignal.subscribe(e),n=this.innerSignal.subscribe(()=>{});return()=>{t(),n()}}subscribeFull(e){let t=this.outerSignal.subscribeFull(e),n=this.innerSignal.subscribeFull(()=>{});return()=>{t(),n()}}};function fb(r){r.includes(":")||(r=`local:${r}`);let e=r.indexOf(":"),t=r.slice(0,e),n=r.slice(e+1);switch(t){case"local":{if(n.includes("/")||n.includes("\\")||n.length===0)throw new Error(`Invalid local file name: ${n}.`);return{type:"local",fileName:n}}case"base64":return{type:"base64",base64Data:n};default:throw new Error(`Unknown file identifier namespace: ${t}.`)}}function hb(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)},{once:!0})})}function pb(r,e){return Promise.race([r,hb(e)])}var mb=["HSA_OVERRIDE_GFX_VERSION"],gb=s.enum(mb),yb=s.record(gb,s.string()),bb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,kn=s.string().regex(bb),vb=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/,Fn=s.string().regex(vb),Db=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u,Ed=s.string().regex(Db,{message:"Invalid file name"}),wb=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;s.string().regex(wb,{message:"Invalid relative path"});var Sb=s.object({type:s.literal("huggingface"),user:Ed,repo:Ed}),Xd=s.discriminatedUnion("type",[Sb]),Cb=s.enum(["baseModel","draftModel","custom"]),ef=s.object({purpose:Cb}),Eb=s.object({type:s.literal("model"),...ef.shape,modelKeys:s.array(s.string().min(1)),sources:s.array(Xd)}),_b=s.object({type:s.literal("artifact"),...ef.shape,owner:kn,name:Fn}),xb=s.discriminatedUnion("type",[Eb,_b]),Ga=s.object({owner:kn,name:Fn.min(1,"Name is required").max(100,"Name too long"),revision:s.number().int().optional(),dependencies:s.array(xb).optional(),tags:s.array(s.string()).optional()}),kb=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/,Fb=s.string().regex(kb,{message:"Invalid artifact identifier format. Expected 'owner/name'."}),Pb=s.object({type:s.literal("model"),...Ga.shape}),Tb=s.enum(["ecmascript","node","mcpBridge"]),Ka=s.object({type:s.literal("plugin"),runner:Tb,...Ga.shape}),Ab=s.object({type:s.literal("preset"),...Ga.shape});s.discriminatedUnion("type",[Ka,Ab,Pb]);var Rb=s.enum(["plugin","preset","model"]),tf=s.object({title:s.string(),description:s.string().optional(),noAutoDismiss:s.boolean().optional()}),rf=s.enum(["image","text/plain","application/pdf","application/word","text/other","unknown"]),Se=s.any().transform((r,e)=>{try{return JSON.parse(JSON.stringify(r))}catch(t){return e.addIssue({code:s.ZodIssueCode.custom,message:"Not JSON serializable: "+t.message}),r}}),Mi=s.object({type:s.literal("text"),text:s.string()}),ji=s.object({type:s.literal("file"),name:s.string(),identifier:s.string(),sizeBytes:s.number().int(),fileType:rf}),Ib=s.object({id:s.string().optional(),type:s.literal("function"),arguments:s.record(Se).optional(),name:s.string()}),Pn=s.discriminatedUnion("type",[Ib]),nf=s.object({type:s.literal("toolCallRequest"),toolCallRequest:Pn});s.object({content:s.string(),toolCallId:s.string().optional()});var sf=s.object({type:s.literal("toolCallResult"),content:s.string(),toolCallId:s.string().optional()});s.discriminatedUnion("type",[Mi,ji,nf,sf]);s.enum(["assistant","user","system","tool"]);var cr=s.discriminatedUnion("role",[s.object({role:s.literal("assistant"),content:s.array(s.discriminatedUnion("type",[Mi,ji,nf]))}),s.object({role:s.literal("user"),content:s.array(s.discriminatedUnion("type",[Mi,ji]))}),s.object({role:s.literal("system"),content:s.array(s.discriminatedUnion("type",[Mi,ji]))}),s.object({role:s.literal("tool"),content:s.array(sf)})]),ur=s.object({messages:s.array(cr)}),Ob=s.object({fileName:s.string(),absoluteFilePath:s.string().optional(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),Mb=s.enum(["red","green","blue","yellow","orange","purple","default"]),jb=Mb,Bb=s.discriminatedUnion("type",[s.object({type:s.literal("llm.prediction.input"),modelPath:s.string(),modelIdentifier:s.string(),input:s.string()})]),Lb=s.object({timestamp:s.number(),data:Bb}),of=s.union([s.number().min(0).max(1),s.literal("max"),s.literal("off")]),Nb=s.enum(["evenly","favorMainGpu"]),af=s.object({ratio:of.optional(),mainGpu:s.number().int().optional(),splitStrategy:Nb.optional(),disabledGpus:s.array(s.number().int()).optional()}),qo=["f32","f16","q8_0","q4_0","q4_1","iq4_nl","q5_0","q5_1"],$b=s.enum(qo),Ub=s.union([s.literal(8),s.literal(6),s.literal(4),s.literal(3),s.literal(2)]),zb=s.union([s.literal(32),s.literal(64),s.literal(128)]),qb=s.object({enabled:s.boolean(),bits:Ub,groupSize:zb,quantizedStart:s.number().int().nonnegative()}),Vb=s.object({gpu:af.optional(),gpuStrictVramCap:s.boolean().optional(),offloadKVCacheToGpu:s.boolean().optional(),contextLength:s.number().int().min(1).optional(),ropeFrequencyBase:s.number().optional(),ropeFrequencyScale:s.number().optional(),evalBatchSize:s.number().int().min(1).optional(),flashAttention:s.boolean().optional(),keepModelInMemory:s.boolean().optional(),seed:s.number().int().optional(),useFp16ForKVCache:s.boolean().optional(),tryMmap:s.boolean().optional(),numExperts:s.number().int().optional(),llamaKCacheQuantizationType:s.enum(qo).or(s.literal(!1)).optional(),llamaVCacheQuantizationType:s.enum(qo).or(s.literal(!1)).optional()}),Wb=s.object({gpu:af.optional(),contextLength:s.number().int().min(1).optional(),ropeFrequencyBase:s.number().optional(),ropeFrequencyScale:s.number().optional(),keepModelInMemory:s.boolean().optional(),tryMmap:s.boolean().optional()}),cs=s.enum(["gguf","safetensors","onnx","ggml","mlx_placeholder","torch_safetensors"]),Zb=s.object({name:s.string(),bits:s.number().int()}),Ha=s.object({modelKey:s.string(),format:cs,displayName:s.string(),path:s.string(),sizeBytes:s.number().int(),paramsString:s.string().optional(),architecture:s.string().optional(),quantization:Zb.optional()}),lf=Ha.extend({identifier:s.string(),instanceReference:s.string()}),cf=s.object({maxContextLength:s.number().int()}),Gb=s.object({contextLength:s.number().int()}),uf=s.object({type:s.literal("embedding")}).extend(Ha.shape).extend(cf.shape),df=s.object({type:s.literal("embedding")}).extend(lf.shape).extend(cf.shape).extend(Gb.shape),Tn=s.enum(["llm","embedding","imageGen","transcription","tts"]),qr=s.string().min(1).max(1024).refine(r=>r!=="__proto__",{message:'For security reasons, "__proto__" is not allowed'}).refine(r=>/\p{C}/u.test(r)===!1,{message:"Control characters are not allowed"}),Ja=s.object({domain:Tn.optional(),identifier:qr.optional(),path:qr.optional(),vision:s.boolean().optional()}),Je=s.discriminatedUnion("type",[s.object({type:s.literal("query"),query:Ja}),s.object({type:s.literal("instanceReference"),instanceReference:s.string()})]),Kb=[s.object({code:s.literal("generic.specificModelUnloaded")}),s.object({code:s.literal("generic.noModelMatchingQuery"),query:Ja,loadedModelsSample:s.array(s.string()),totalLoadedModels:s.number().int()}),s.object({code:s.literal("generic.pathNotFound"),path:s.string(),availablePathsSample:s.array(s.string()),totalModels:s.number().int()}),s.object({code:s.literal("generic.identifierNotFound"),identifier:s.string(),loadedModelsSample:s.array(s.string()),totalLoadedModels:s.number().int()}),s.object({code:s.literal("generic.domainMismatch"),path:s.string(),actualDomain:Tn,expectedDomain:Tn}),s.object({code:s.literal("generic.engineDoesNotSupportFeature"),feature:s.string(),engineName:s.string(),engineType:s.string(),installedVersion:s.string(),supportedVersion:s.string().nullable()}),s.object({code:s.literal("generic.presetNotFound"),specifiedFuzzyPresetIdentifier:s.string(),availablePresetsSample:s.array(s.object({identifier:s.string(),name:s.string()})),totalAvailablePresets:s.number().int()})],Hb=[],Jb=s.discriminatedUnion("code",[...Hb,...Kb]);function rr(r){return s.any().transform(e=>r.safeParse(e).success?e:void 0)}var _e=s.object({title:rr(s.string()).default("Unknown error"),cause:rr(s.string()).optional(),suggestion:rr(s.string()).optional(),errorData:rr(s.record(s.string(),s.unknown())).optional(),displayData:rr(Jb).optional(),stack:rr(s.string()).optional(),rootTitle:rr(s.string()).optional()});function ir(r){if(typeof r=="object"){let e=r.title??r.lmstudioRawError??r.message??"Unknown error";return _e.parse({title:e,cause:r.cause,suggestion:r.suggestion,errorData:r.errorData,displayData:r.displayData,stack:r.stack,rootTitle:e})}else{let e=String(r);return{title:e,rootTitle:e}}}function ff(r,e){let t=r;t.title=e.title,e.cause!==void 0&&(t.cause=e.cause),e.suggestion!==void 0&&(t.suggestion=e.suggestion),e.errorData!==void 0&&(t.errorData=e.errorData)}function Vi(r,e="Rehydrated error",t){let n=new Error(r.rootTitle);return ff(n,r),r.displayData!==void 0&&(n.displayData=r.displayData),t!==void 0?r.stack!==void 0?n.stack=`Error: ${e}
51
+ ${t}
52
+ - Caused By: ${r.stack}`:n.stack=`Error: ${e}
53
+ ${t}`:r.stack!==void 0?n.stack=`Error: ${e}
54
+ ${n.stack.substring(r.stack.indexOf(`
55
+ `)+1)}
56
+ - Caused By: `+r.stack:n.message+=` - caused by error without stack (${r.title})`,n}var Vo=s.object({library:s.string(),version:s.string()}),hf=s.object({parserId:Vo.optional()});s.enum(["local","base64"]);s.discriminatedUnion("type",[s.object({type:s.literal("local"),fileName:s.string()}),s.object({type:s.literal("base64"),base64Data:s.string()})]);var Yb=["evenly","priorityOrder","custom"],Qb=s.enum(Yb),Xb={strategy:"evenly",disabledGpus:[],priority:[],customRatio:[]},e0=s.object({strategy:Qb,disabledGpus:s.array(s.number().int().min(0)),priority:s.array(s.number().int().min(0)),customRatio:s.array(s.number().min(0))});function pf(r){return{strategy:r?.splitStrategy=="favorMainGpu"?"priorityOrder":r?.splitStrategy??"evenly",disabledGpus:r?.disabledGpus??[],priority:r?.mainGpu?[r.mainGpu]:[],customRatio:[]}}var mf=s.object({key:s.string(),value:s.any()}),X=s.object({fields:s.array(mf)}),t0=s.enum(["currentlyEditing","currentlyLoaded","apiOverride","conversationSpecific","conversationGlobal","preset","serverSession","httpServerRequestOverride","completeModeFormatting","instance","userModelDefault","virtualModel","modelDefault","hardware"]),r0=s.object({layerName:t0,config:X}),Wi=s.object({layers:s.array(r0)}),n0=s.object({key:s.string(),condition:s.discriminatedUnion("type",[s.object({type:s.literal("equals"),value:s.any()}),s.object({type:s.literal("notEquals"),value:s.any()})])}),gf=s.discriminatedUnion("type",[s.object({type:s.literal("default")}),s.object({type:s.literal("customLabel"),label:s.string(),color:s.optional(jb)}),s.object({type:s.literal("thinking"),ended:s.boolean().optional(),title:s.string().optional()})]),i0=s.discriminatedUnion("type",[s.object({type:s.literal("object"),properties:s.record(Se),required:s.array(s.string()).optional(),additionalProperties:s.boolean().optional(),$defs:s.record(Se).optional()})]),or=s.discriminatedUnion("type",[s.object({type:s.literal("function"),function:s.object({name:s.string(),description:s.string().optional(),parameters:i0.optional()})})]);s.array(or);var yf=s.discriminatedUnion("type",[s.object({type:s.literal("none")}),s.object({type:s.literal("toolArray"),tools:s.array(or).optional(),force:s.boolean().optional()})]),bf=s.object({omitBosToken:s.boolean().optional(),omitEosToken:s.boolean().optional(),toolDefinitions:s.array(or).optional()}),s0=s.discriminatedUnion("type",[s.object({type:s.literal("jsonFile"),absPath:s.string()}),s.object({type:s.literal("yamlFile"),absPath:s.string()})]);s.array(s.object({role:s.enum(["user","assistant","system"]),content:s.string()}));s.array(s.union([s.object({system:s.string()}),s.object({user:s.string()}),s.object({assistant:s.string()})]));var vf=s.object({vision:s.boolean(),trainedForToolUse:s.boolean(),maxContextLength:s.number().int()}),o0=s.object({contextLength:s.number().int()}),Df=s.object({type:s.literal("llm")}).extend(Ha.shape).extend(vf.shape),Wo=s.object({type:s.literal("llm")}).extend(lf.shape).extend(vf.shape).extend(o0.shape),wf=s.enum(["passThrough","removeSpecial","snakeCase","camelCase"]),gr=s.custom(r=>typeof r?.parse=="function","Expected a zod schema"),a0=s.object({beforeSystem:s.string(),afterSystem:s.string(),beforeUser:s.string(),afterUser:s.string(),beforeAssistant:s.string(),afterAssistant:s.string()}),l0=s.object({template:s.string()}),c0=s.enum(["manual","jinja"]),Sf=s.object({type:c0,manualPromptTemplate:a0.optional(),jinjaPromptTemplate:l0.optional(),stopStrings:s.array(s.string())}),u0=s.enum(["none","json","gbnf"]),Ya=s.object({type:u0,jsonSchema:Se.optional(),gbnfGrammar:s.string().optional()}),Cf=s.enum(["stopAtLimit","truncateMiddle","rollingWindow"]),Ef=s.object({enabled:s.boolean(),startString:s.string(),endString:s.string()}),Qa=s.object({maxTokens:s.number().int().min(-1).optional().or(s.literal(!1)),temperature:s.number().min(0).optional(),stopStrings:s.array(s.string()).optional(),toolCallStopStrings:s.array(s.string()).optional(),contextOverflowPolicy:Cf.optional(),structured:s.union([gr,Ya]).optional(),rawTools:yf.optional(),toolNaming:wf.optional(),topKSampling:s.number().optional(),repeatPenalty:s.number().optional().or(s.literal(!1)),minPSampling:s.number().optional().or(s.literal(!1)),topPSampling:s.number().optional().or(s.literal(!1)),cpuThreads:s.number().int().optional(),promptTemplate:Sf.optional(),draftModel:s.string().optional(),speculativeDecodingNumDraftTokensExact:s.number().int().min(1).optional(),speculativeDecodingMinDraftLengthToConsider:s.number().int().min(0).optional(),speculativeDecodingMinContinueDraftingProbability:s.number().optional(),reasoningParsing:Ef.optional(),raw:X.optional()});s.object({...Qa.shape,structured:Ya.optional()});var d0=s.object({version:s.union([s.literal(0),s.literal(1),s.literal(2)]),learningRate:s.number(),targetEntropy:s.number()}),f0=s.union([s.number(),s.literal("-inf")]),h0=s.array(s.tuple([s.number(),f0])),_f=s.enum(["none","reasoning","reasoningStartTag","reasoningEndTag"]),xf=s.object({content:s.string(),tokensCount:s.number().int(),containsDrafted:s.boolean(),reasoningType:_f,isStructural:s.boolean()}),kf=s.object({tokenCount:s.number().int().optional(),containsDrafted:s.boolean().optional(),reasoningType:_f.optional(),isStructural:s.boolean().optional()}),p0=s.enum(["userStopped","modelUnloaded","failed","eosFound","stopStringFound","toolCalls","maxPredictedTokensReached","contextLengthReached"]),Ff=s.object({stopReason:p0,tokensPerSecond:s.number().optional(),numGpuLayers:s.number().optional(),timeToFirstTokenSec:s.number().optional(),totalTimeSec:s.number().optional(),promptTokensCount:s.number().int().optional(),predictedTokensCount:s.number().int().optional(),totalTokensCount:s.number().int().optional(),usedDraftModelKey:s.string().optional(),totalDraftTokensCount:s.number().int().optional(),acceptedDraftTokensCount:s.number().int().optional(),rejectedDraftTokensCount:s.number().int().optional(),ignoredDraftTokensCount:s.number().int().optional()}),m0=s.object({indexedModelIdentifier:s.string(),identifier:s.string(),loadModelConfig:X,predictionConfig:X,stats:Ff}),g0=s.discriminatedUnion("type",[s.object({type:s.literal("beforeId"),id:s.string()}),s.object({type:s.literal("afterId"),id:s.string()})]),y0=s.enum(["waiting","loading","done","error","canceled"]),Pf=s.object({status:y0,text:s.string()}),Xa=s.object({type:s.literal("status.create"),id:s.string(),state:Pf,location:g0.optional(),indentation:s.number().int().optional()}),el=s.object({type:s.literal("status.update"),id:s.string(),state:Pf}),tl=s.object({type:s.literal("status.remove"),id:s.string()}),rl=s.object({type:s.literal("citationBlock.create"),id:s.string(),citedText:s.string(),fileName:s.string(),fileIdentifier:s.string(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),nl=s.object({type:s.literal("debugInfoBlock.create"),id:s.string(),debugInfo:s.string()}),Tf=s.object({type:s.literal("contentBlock.create"),id:s.string(),includeInContext:s.boolean(),roleOverride:s.enum(["user","assistant","system","tool"]).optional(),style:gf.optional(),prefix:s.string().optional(),suffix:s.string().optional()}),Af=s.object({type:s.literal("contentBlock.appendText"),id:s.string(),text:s.string(),tokensCount:s.number().int().optional(),fromDraftModel:s.boolean().optional(),isStructural:s.boolean().optional()}),Rf=s.object({type:s.literal("contentBlock.appendToolResult"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),content:s.string()}),If=s.object({type:s.literal("contentBlock.appendToolRequest"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),name:s.string(),parameters:s.record(s.unknown()),pluginIdentifier:s.string().optional()}),Of=s.object({type:s.literal("contentBlock.replaceToolRequest"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),name:s.string(),parameters:s.record(s.unknown()),pluginIdentifier:s.string().optional()}),Mf=s.object({type:s.literal("contentBlock.replaceText"),id:s.string(),text:s.string()}),b0=s.object({type:s.literal("contentBlock.setPrefix"),id:s.string(),prefix:s.string()}),v0=s.object({type:s.literal("contentBlock.setSuffix"),id:s.string(),suffix:s.string()}),jf=s.object({type:s.literal("contentBlock.attachGenInfo"),id:s.string(),genInfo:m0}),Bf=s.object({type:s.literal("contentBlock.setStyle"),id:s.string(),style:gf}),D0=s.discriminatedUnion("type",[s.object({type:s.literal("generatingToolCall"),name:s.string().optional(),pluginIdentifier:s.string().optional(),argumentsString:s.string().optional()}),s.object({type:s.literal("toolCallGenerationFailed"),error:s.string(),rawContent:s.string().optional()}),s.object({type:s.literal("toolCallQueued")}),s.object({type:s.literal("confirmingToolCall")}),s.object({type:s.literal("toolCallDenied"),denyReason:s.string().optional()}),s.object({type:s.literal("callingTool")}),s.object({type:s.literal("toolCallFailed"),error:s.string()}),s.object({type:s.literal("toolCallSucceeded"),timeMs:s.number().int()})]),Lf=s.object({status:D0,customStatus:s.string(),customWarnings:s.array(s.string())}),Nf=s.object({type:s.literal("toolStatus.create"),id:s.string(),callId:s.number().int(),state:Lf}),$f=s.object({type:s.literal("toolStatus.update"),id:s.string(),state:Lf}),Uf=s.object({type:s.literal("toolStatus.argumentFragment"),id:s.string(),content:s.string()}),zf=s.object({type:s.literal("setSenderName"),name:s.string()}),w0=s.discriminatedUnion("type",[Xa,el,tl,rl,nl,Tf,Af,If,Of,Rf,Mf,b0,v0,jf,Bf,Nf,$f,Uf,zf]);s.discriminatedUnion("type",[Xa,el,tl,rl,nl,Tf,Af,Mf,If,Of,Rf,jf,Bf,Nf,$f,Uf,zf]);var S0=s.object({type:s.literal("confirmToolCall"),callId:s.number().int(),pluginIdentifier:s.string().optional(),name:s.string(),parameters:s.record(s.any())}),C0=s.object({type:s.literal("textInput"),prompt:s.string()}),E0=s.discriminatedUnion("type",[S0,C0]),_0=s.object({type:s.literal("confirmToolCall"),result:s.discriminatedUnion("type",[s.object({type:s.literal("allow"),toolArgsOverride:s.record(s.any()).optional()}),s.object({type:s.literal("deny"),denyReason:s.string().optional()})])}),x0=s.object({type:s.literal("textInput"),result:s.string()}),k0=s.discriminatedUnion("type",[_0,x0]);s.object({modelTag:s.string().optional(),ignoreUserConfig:s.boolean().optional()});s.discriminatedUnion("type",[Xa,el,tl,rl,nl]);var F0=s.discriminatedUnion("type",[s.object({type:s.literal("model"),identifier:s.string()}),s.object({type:s.literal("generator"),pluginIdentifier:s.string()})]),P0=s.discriminatedUnion("type",[Df,uf]),T0=s.discriminatedUnion("type",[Wo,df]),_d=s.discriminatedUnion("type",[s.object({type:s.literal("direct"),config:X,workingDirectoryPath:s.string().optional()}),s.object({type:s.literal("predictionProcess"),pci:s.string(),token:s.string()})]),xd=s.object({identifier:s.string(),isDev:s.boolean(),isTrusted:s.boolean(),hasPromptPreprocessor:s.boolean(),hasPredictionLoopHandler:s.boolean(),hasToolsProvider:s.boolean(),hasGenerator:s.boolean()}),kd=s.object({displayName:s.string(),sizeBytes:s.number(),quantName:s.string().optional(),compatibilityType:cs}),Fd=s.enum(["pending","fetching","satisfied","completed"]),A0=s.discriminatedUnion("type",[s.object({type:s.literal("artifact"),owner:kn,name:Fn,state:Fd,artifactType:Rb.optional(),sizeBytes:s.number().int().optional(),dependencyNodes:s.array(s.number().int())}),s.object({type:s.literal("model"),state:Fd,resolvedSources:s.number().int().optional(),totalSources:s.number().int().optional(),alreadyOwned:kd.optional(),selected:kd.optional()})]),Pd=s.object({nodes:s.array(A0),downloadSizeBytes:s.number().int()}),R0=s.object({relativePath:s.string(),sizeBytes:s.number().int()}),I0=s.object({files:s.array(R0),usedIgnoreFile:s.string().nullable()}),To=s.object({downloadedBytes:s.number().int(),totalBytes:s.number().int(),speedBytesPerSecond:s.number()}),O0=s.enum(["fullGPUOffload","partialGPUOffload","fitWithoutGPU","willNotFit"]),M0=s.object({quantization:s.string().optional(),name:s.string(),sizeBytes:s.number().int(),fitEstimation:O0,recommended:s.boolean().optional(),downloadIdentifier:s.string(),indexedModelIdentifier:s.string()}),qf=s.discriminatedUnion("type",[s.object({type:s.literal("catalog"),identifier:s.string()}),s.object({type:s.literal("hf"),identifier:s.string()})]),j0=s.object({name:s.string(),identifier:qf,exact:s.boolean().optional(),staffPick:s.boolean().optional()}),Vf=s.object({searchTerm:s.string().optional(),limit:s.number().int().positive().max(25).optional(),compatibilityTypes:s.array(cs).optional()}),B0=s.object({content:s.string(),score:s.number(),sourceIndex:s.number().int(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),L0=s.object({entries:s.array(B0)});s.object({content:s.string(),score:s.number(),citation:Ob});var Wf=s.discriminatedUnion("type",[s.object({type:s.literal("recursive-v1"),chunkSize:s.number().int(),chunkOverlap:s.number().int()})]),Ao=s.enum(["loading","chunking","embedding"]),N0=s.enum(["unknown","integratedGpu","dedicatedGpu"]),$0=s.object({name:s.string(),deviceId:s.number().int(),totalMemoryBytes:s.number().int(),type:N0});s.object({key:s.string(),name:s.string(),accelerators:s.array($0)});var U0=s.object({shortKey:s.string(),fullKey:s.string(),typeKey:s.string(),typeParams:Se,defaultValue:Se}),Td=s.object({fields:s.array(U0),extensionPrefixes:s.array(s.string()).optional()});s.object({fullKey:s.string(),error:Se});var Ti=s.union([s.literal(!0),s.literal(!1),s.literal("mixed")]),z0=s.object({domain:Tn.optional(),architectures:s.array(s.string()).optional(),compatibilityTypes:s.array(cs).optional(),paramsStrings:s.array(s.string()).optional(),minMemoryUsageBytes:s.number().optional(),contextLengths:s.array(s.number()).optional(),trainedForToolUse:Ti.optional(),vision:Ti.optional(),reasoning:Ti.optional(),fim:Ti.optional()}),q0=s.object({key:s.string(),sources:s.array(Xd)}),il=s.object({type:s.literal("setJinjaVariable"),variable:s.string()}),V0=s.object({type:s.literal("prependSystemPrompt"),content:s.string()}),W0=s.object({type:s.literal("appendSystemPrompt"),content:s.string()}),sl=s.object({key:s.string(),displayName:s.string(),description:s.string()}),Z0=sl.extend({type:s.literal("boolean"),defaultValue:s.boolean(),effects:s.array(s.discriminatedUnion("type",[il,V0,W0]))}),G0=sl.extend({type:s.literal("string"),defaultValue:s.string(),effects:s.array(s.discriminatedUnion("type",[il]))}),K0=sl.extend({type:s.literal("select"),options:s.array(s.object({label:s.string(),value:s.string()})),defaultValue:s.string(),effects:s.array(s.discriminatedUnion("type",[il]))}),H0=s.discriminatedUnion("type",[Z0,G0,K0]),J0=s.object({type:s.literal("equals"),key:s.string(),value:Se}),Y0=s.discriminatedUnion("type",[J0]),Q0=s.object({message:s.string(),conditions:s.array(Y0),fields:s.array(mf).optional()});s.object({model:s.string().regex(/^[^/]+\/[^/]+$/),base:s.union([s.string(),s.array(q0)]),tags:s.array(s.string().max(100)).optional(),config:s.object({load:X.optional(),operation:X.optional()}).optional(),metadataOverrides:z0.optional(),customFields:s.array(H0).optional(),suggestions:s.array(Q0).optional()});var X0=s.enum(["debug","info","warn","error"]);function B(r,e,t,n){if(t!==void 0)try{let i=t(...n);typeof i=="object"&&typeof i.catch=="function"&&i.catch(o=>{r.error(`Error in the ${e} callback (triggered asynchronously):`,o)})}catch(i){r.error(`Error in the ${e} callback:`,i)}}function ev(r){return r?.isSimpleLogger===!0}var tv=I.default.greenBright("I"),rv=I.default.yellowBright("W"),nv=I.default.redBright("E"),iv=I.default.blueBright("D"),H=class r{constructor(e="",t=console,{useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:o,errorPrefix:a,debugPrefix:l}={}){this.isSimpleLogger=!0,this.infoPrefix=[],this.warnPrefix=[],this.errorPrefix=[],this.debugPrefix=[],ev(t)?(n=n??t.opts.useLogLevelPrefixes,i=i===void 0?t.opts.infoPrefix:i,o=o===void 0?t.opts.warnPrefix:o,a=a===void 0?t.opts.errorPrefix:a,l=l===void 0?t.opts.debugPrefix:l,e===""?(this.innerPrefix=t.innerPrefix,this.fullPrefix=t.fullPrefix):(t.fullPrefix===""?this.innerPrefix=e:this.innerPrefix=`${t.innerPrefix}][${e}`,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=t.parentLogger):(n=n??!1,i=i===void 0?tv:i,o=o===void 0?rv:o,a=a===void 0?nv:a,l=l===void 0?iv:l,e===""?(this.innerPrefix="",this.fullPrefix=""):(this.innerPrefix=e,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=t),n&&(i!==null&&this.infoPrefix.push(i),o!==null&&this.warnPrefix.push(o),a!==null&&this.errorPrefix.push(a),l!==null&&this.debugPrefix.push(l)),this.fullPrefix!==""&&(this.infoPrefix.push(this.fullPrefix),this.warnPrefix.push(this.fullPrefix),this.errorPrefix.push(this.fullPrefix),this.debugPrefix.push(this.fullPrefix)),this.opts={useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:o,errorPrefix:a,debugPrefix:l}}subclass(e){return new r(`${this.innerPrefix}:${e}`,this.parentLogger)}info(...e){this.parentLogger.info(...this.infoPrefix,...e)}infoText(e,...t){this.info(j(e,...t))}infoWithoutPrefix(...e){this.parentLogger.info(...e)}error(...e){this.parentLogger.error(...this.errorPrefix,...e)}errorText(e,...t){this.error(j(e,...t))}errorWithoutPrefix(...e){this.parentLogger.error(...e)}warn(...e){this.parentLogger.warn(...this.warnPrefix,...e)}warnText(e,...t){this.warn(j(e,...t))}warnWithoutPrefix(...e){this.parentLogger.warn(...e)}debug(...e){this.parentLogger.debug(...this.debugPrefix,...e)}debugText(e,...t){this.debug(j(e,...t))}debugWithoutPrefix(...e){this.parentLogger.debug(...e)}throw(e){throw new Error(`${this.fullPrefix} ${e}`)}logAtLevel(e,...t){switch(e){case"debug":this.debug(...t);break;case"info":this.info(...t);break;case"warn":this.warn(...t);break;case"error":this.error(...t);break}}static fromMultiple(e,t){return new r("",{debug:(...n)=>{for(let i of e)i.debug(...n)},info:(...n)=>{for(let i of e)i.info(...n)},warn:(...n)=>{for(let i of e)i.warn(...n)},error:(...n)=>{for(let i of e)i.error(...n)}},{...t,useLogLevelPrefixes:!1})}},Ad,Rd=Symbol("finished"),Zi=class{finished(e){if(this.status!=="pending")throw new Error("`finished` called while not pending");e===void 0?(this.status="resolved",this.nextFragmentPromiseBundle?.resolve(Rd),this.resolveFinal(this.collect(this.buffer))):(this.status="rejected",this.nextFragmentPromiseBundle?.reject(e),this.rejectFinal(e))}push(e){if(this.status!=="pending")throw new Error("`push` called while not pending");this.buffer.push(e),this.nextFragmentPromiseBundle?.resolve(e),this.nextFragmentPromiseBundle=null}constructor(){this.status="pending",this.buffer=[],this.nextFragmentPromiseBundle=null,this.hasIterator=!1,this[Ad]="StreamablePromise";let{promise:e,resolve:t,reject:n}=ee();this.promiseFinal=e,this.resolveFinal=t,this.rejectFinal=n}then(e,t){return this.promiseFinal.then(e,t)}catch(e){return this.promiseFinal.catch(e)}finally(e){return this.promiseFinal.finally(e)}obtainNextFragmentPromiseBundle(){return this.nextFragmentPromiseBundle===null&&(this.nextFragmentPromiseBundle=ee()),this.nextFragmentPromiseBundle}async*[(Ad=Symbol.toStringTag,Symbol.asyncIterator)](){this.hasIterator||(this.promiseFinal.catch(()=>{}),this.hasIterator=!0);let e=0;for(;e<this.buffer.length||this.status==="pending";)if(e<this.buffer.length)yield this.buffer[e],e++;else{let n=await this.obtainNextFragmentPromiseBundle().promise;if(n===Rd)break;yield n,e++}await this.promiseFinal,await Promise.resolve()}},Ye=class r{constructor({attachStack:e}={}){this.attachStack=e??!0}static prettyPrintZod(e,t){return t.errors.map(n=>{if(n.path.length===0)return`- ${I.default.redBright(e)}: ${n.message}`;let i=I.default.red(`.${n.path.join(".")}`);return`- ${I.default.redBright(e)}${i}: ${n.message}`}).join(`
57
+ `)}validateOrThrow(e,t,n,i,o){let a=n.safeParse(i);if(a.success)return a.data;throw pe(`${e}
58
+
59
+ ${r.prettyPrintZod(t,a.error)}`,this.attachStack?o:void 0)}validateMultipleOrThrow(e,t,n,i,o){let a=n.map((c,u)=>c.safeParse(i[u])),l=a.map((c,u)=>({result:c,index:u,rootObjectName:t[u]})).filter(({result:c})=>!c.success).map(({result:c,rootObjectName:u,index:h})=>({error:c.error,rootObjectName:u,index:h}));if(l.length===0)return a.map(c=>c.data);{let c=new Set(l.map(({index:h})=>h)),u=e(c);throw pe(`${u}
60
+
61
+ ${l.map(({error:h,rootObjectName:f})=>r.prettyPrintZod(f,h)).join(`
62
+ `)}`,this.attachStack?o:void 0)}}validateMethodParamOrThrow(e,t,n,i,o,a){let l=I.default.yellowBright(j`
63
+ ${e}.${t}(${I.default.redBright(n)})
64
+ `);return this.validateOrThrow(`Invalid parameter(s) for ${l}:`,n,i,o,a)}validateMethodParamsOrThrow(e,t,n,i,o,a){return this.validateMultipleOrThrow(l=>{let c=n.map((h,f)=>l.has(f)?I.default.redBright(h):h);return`Invalid parameter(s) for ${I.default.yellowBright(j`
65
+ ${e}.${t}(${c.join(", ")})
66
+ `)}:`},n,i,o,a)}validateConstructorParamOrThrow(e,t,n,i,o){let a=I.default.yellowBright(j`
67
+ ${e}(${I.default.redBright(t)})
68
+ `);return this.validateOrThrow(`Invalid parameter(s) when constructing ${a}`,t,n,i,o)}validateConstructorParamsOrThrow(e,t,n,i,o){return this.validateMultipleOrThrow(a=>{let l=t.map((u,h)=>a.has(h)?I.default.redBright(u):u);return`Invalid parameter(s) when constructing ${I.default.yellowBright(j`
69
+ ${e}(${l.join(", ")})
70
+ `)}:`},t,n,i,o)}},Zf=new Ye,he=class{constructor(e,t,n,i,o){this.filesNamespace=e,this.identifier=t,this.type=n,this.sizeBytes=i,this.name=o,this.parsedIdentifier=fb(t)}async getFilePath(){switch(this.parsedIdentifier.type){case"local":return(await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;case"base64":throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");default:{let e=this.parsedIdentifier;throw new Error(`Unexpected file identifier type: ${JSON.stringify(e)}`)}}}isImage(){return this.type==="image"}},ol=s.object({role:s.enum(["user","assistant","system"]).optional(),content:s.string().optional(),images:s.array(s.instanceof(he)).optional()}),sv=s.array(ol);function ov(r){return!Array.isArray(r.content)}function av(r){return!("messages"in r)}function Zo(r){let{role:e,content:t,images:n}=r,i=[];if(n===void 0||n.length===0)t===void 0&&i.push({type:"text",text:""});else for(let o of n)i.push({type:"file",identifier:o.identifier,name:o.name,fileType:o.type,sizeBytes:o.sizeBytes});return t!==void 0&&i.push({type:"text",text:t}),{role:e??"user",content:i}}var pt=class r extends qi{getClassName(){return"Chat"}create(e,t){return new r(e,t)}cloneData(e){return ur.parse(e)}constructor(e,t){super(e,t)}static empty(){return new r({messages:[]},!0)}static from(e){let t=A(1);if(Zf.validateMethodParamOrThrow("Chat","from","initializer",Wr,e,t),e instanceof r)return e.asMutableCopy();if(typeof e=="string"){let n=r.empty();return n.append("user",e),n}return Array.isArray(e)?new r({messages:e.map(Zo)},!0):av(e)?new r({messages:[Zo(e)]},!0):new r(e,!1).asMutableCopy()}static createRaw(e,t){return new r(e,t)}getRaw(){return this.data}append(...e){if(this.guardMutable(),e.length===1){let[t]=e,n=le.from(t),i=n._internalToMutable();this.data.messages.push(i._internalGetData())}else{let[t,n,i={}]=e;if(t==="user"||t==="system"||t==="assistant"){let o=[{type:"text",text:n}];if(i.images!==void 0)for(let a of i.images)o.push({type:"file",name:a.name,identifier:a.identifier,sizeBytes:a.sizeBytes,fileType:a.type});this.data.messages.push({role:t,content:o})}else throw new Error(j`
71
+ Unsupported role for append() API with [role, content] parameters: ${t}.
72
+ Supported roles are 'user', 'system', and 'assistant'.
73
+ `)}}withAppended(...e){let t=this.asMutableCopy();return t.append(...e),t}getLength(){return this.data.messages.length}get length(){return this.getLength()}pop(){if(this.guardMutable(),this.data.messages.length===0)throw new Error("Tried to pop from an empty history.");let e=this.data.messages.pop();return le.createRaw(e,!0)}getAllFiles(e){return this.data.messages.flatMap(t=>t.content.filter(n=>n.type==="file")).map(t=>new he(e.files,t.identifier,t.fileType,t.sizeBytes,t.name))}*files(e){for(let t of this.data.messages)for(let n of t.content)n.type==="file"&&(yield new he(e.files,n.identifier,n.fileType,n.sizeBytes,n.name))}hasFiles(){return this.data.messages.some(e=>e.content.some(t=>t.type==="file"))}at(e){let t=e;if(e<0&&(t=this.data.messages.length+e),t<0||t>=this.data.messages.length)throw new Error(j`
74
+ Tried to access the message at index ${e}, but the history only has
75
+ ${this.data.messages.length} messages.
76
+ `);return le.createRaw(this.data.messages[t],this.mutable)}getMessagesArray(){return this.data.messages.map(e=>le.createRaw(e,this.mutable))}map(e){return this.getMessagesArray().map(e)}flatMap(e){return this.getMessagesArray().flatMap(e)}*[Symbol.iterator](){for(let e of this.data.messages)yield le.createRaw(e,this.mutable)}consumeFiles(e,t){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...le.createRaw(i,!0).consumeFiles(e,t));return n}async consumeFilesAsync(e,t){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...await le.createRaw(i,!0).consumeFilesAsync(e,t));return n}getSystemPrompt(){return this.data.messages.filter(e=>e.role==="system").map(e=>e.content.filter(t=>t.type==="text").map(t=>t.text).join(" ")).join(`
77
+
78
+ `)}replaceSystemPrompt(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>t.role!=="system"),this.data.messages.unshift({role:"system",content:[{type:"text",text:e}]})}filterInPlace(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>e(le.createRaw(t,!0)))}toString(){return`Chat {
79
+ `+this.data.messages.map(e=>le.createRaw(e,!1).toString().split(`
80
+ `).map(n=>" "+n).join(`
81
+ `)).join(`
82
+ `)+`
83
+ }`}},Wr=s.union([s.instanceof(pt),ur,s.string(),sv,ol]),le=class r extends qi{getClassName(){return"ChatMessage"}create(e,t){return new r(e,t)}cloneData(e){return cr.parse(e)}constructor(e,t){super(e,t)}static create(e,t){return new r(cr.parse({role:e,content:[{type:"text",text:t}]}),!0)}static from(e){let t=A(1);return Zf.validateMethodParamOrThrow("ChatMessage","from","initializer",lv,e,t),e instanceof r?e.asMutableCopy():typeof e=="string"?new r(cr.parse({role:"user",content:[{type:"text",text:e}]}),!0):ov(e)?new r(Zo(e),!0):new r(e,!0)}static createRaw(e,t){return new r(e,t)}getRaw(){return this.data}getRole(){return this.data.role}setRole(e){this.guardMutable(),this.data.role=e}getFileParts(){return this.data.content.filter(e=>e.type==="file")}getText(){return this.data.content.filter(e=>e.type==="text").map(e=>e.text).join(" ")}getToolCallResults(){return this.data.content.filter(e=>e.type==="toolCallResult").map(e=>({content:e.content,toolCallId:e.toolCallId}))}getToolCallRequests(){return this.data.content.filter(e=>e.type==="toolCallRequest").map(e=>e.toolCallRequest)}getFiles(e){return this.getFileParts().map(t=>new he(e.files,t.identifier,t.fileType,t.sizeBytes,t.name))}*files(e){for(let t of this.getFileParts())yield new he(e.files,t.identifier,t.fileType,t.sizeBytes,t.name)}consumeFiles(e,t){this.guardMutable();let n=[],i=new Set;for(let[o,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new he(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);t(l)&&(n.push(l),i.add(o))}return this.data.content=this.data.content.filter((o,a)=>!i.has(a)),n}async consumeFilesAsync(e,t){this.guardMutable();let n=[],i=new Set;for(let[o,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new he(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);await t(l)&&(n.push(l),i.add(o))}return this.data.content=this.data.content.filter((o,a)=>!i.has(a)),n}hasFiles(){return this.data.content.some(e=>e.type==="file")}appendText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"text",text:e});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let t=this.data;throw new Error(`Unhandled role in switch statement: ${t.role}`)}}}appendFile(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"file",name:e.name,identifier:e.identifier,sizeBytes:e.sizeBytes,fileType:e.type});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let t=this.data;throw new Error(`Unhandled role in switch statement: ${t.role}`)}}}replaceText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content=[{type:"text",text:e},...this.data.content.filter(t=>t.type!=="text")];break;case"tool":throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);default:{let t=this.data;throw new Error(`Unhandled role in switch statement: ${t.role}`)}}}isSystemPrompt(){return this.data.role==="system"}isUserMessage(){return this.data.role==="user"}isAssistantMessage(){return this.data.role==="assistant"}toString(){let e=this.data.content.map(t=>{switch(t.type){case"text":return t.text;case"file":return`<file ${t.name}>`;case"toolCallRequest":return t.toolCallRequest.name+`(${JSON.stringify(t.toolCallRequest.arguments)})`;case"toolCallResult":return t.content;default:{let n=t;throw new Error(`Unknown part type: ${n.type}`)}}}).join(" ");return e.includes(`
84
+ `)?this.data.role+`:
85
+ `+e.split(`
86
+ `).map(t=>" "+t).join(`
87
+ `):this.data.role+": "+e}},lv=s.union([s.instanceof(le),ol,s.string(),cr]),Go=class{constructor(e){this.baseSchema=e,this.valueTypes=new Map}valueType(e,t){if(this.valueTypes.has(e))throw new Error(`ValueType with key ${e} already exists`);return this.valueTypes.set(e,{paramType:s.object({...this.baseSchema,...t.paramType}),schemaMaker:t.schemaMaker,effectiveEquals:t.effectiveEquals,stringify:t.stringify}),this}build(){return new Ko(new Map(this.valueTypes))}},Ko=class{constructor(e){this.valueTypes=e}getSchema(e,t){let n=this.valueTypes.get(e);if(n===void 0)throw new Error(`Cannot find value type ${e}`);return n.schemaMaker(n.paramType.parse(t))}parseParamTypes(e,t){return this.valueTypes.get(e).paramType.parse(t)}effectiveEquals(e,t,n,i){return this.valueTypes.get(e).effectiveEquals(n,i,t)}stringify(e,t,n,i){return this.valueTypes.get(e).stringify(i,t,n)}},Gi=class r{constructor(e){this.valueTypeLibrary=e,this.fields=new Map,this.extensionPrefixes=[]}field(e,t,n,i){let a=this.valueTypeLibrary.getSchema(t,n).safeParse(i);if(!a.success)throw new Error(`Invalid default value for field ${e}: ${a.error.message}`);if(i=a.data,this.fields.has(e))throw new Error(`Cannot add field with key ${e}. Key already exists in the schematics.`);return this.fields.set(e,{valueTypeKey:t,valueTypeParams:n,schema:this.valueTypeLibrary.getSchema(t,n),fullKey:e,defaultValue:i}),this}extension(e){return this.extensionPrefixes.push(`${e}.`),this}scope(e,t){let n=t(new r(this.valueTypeLibrary));for(let[i,{valueTypeKey:o,valueTypeParams:a,schema:l,defaultValue:c}]of n.fields.entries()){let u=`${e}.${i}`;if(this.fields.has(u))throw new Error(`Cannot add field with key ${u}. Key already exists in the schematics.`);this.fields.set(u,{valueTypeKey:o,valueTypeParams:a,schema:l,fullKey:u,defaultValue:c})}return this.extensionPrefixes.push(...n.extensionPrefixes.map(i=>`${e}.${i}`)),this}build(){return new An(this.valueTypeLibrary,this.fields,this.extensionPrefixes)}},Ki=Symbol("createParsedKVConfig"),An=class r{constructor(e,t,n){this.valueTypeLibrary=e,this.fields=t,this.extensionPrefixes=n,this.fullKepMap=void 0,this.lenientZodSchema=void 0}getFieldsMap(){return new Map([...this.fields.values()].map(e=>[e.fullKey,e]))}obtainField(e){let t=this.fields.get(e);if(t===void 0){let n=[...this.fields.keys()],i=n.slice(0,10).map(o=>`- ${o}`).join(`
88
+ `);throw n.length>10&&(i+=`
89
+ ... and ${n.length-10} more`),new Error(`Cannot access key ${e}. Key does not exist in the schematics. Available keys:
90
+
91
+ `+i)}return t}obtainFieldByFullKey(e){let t=this.getFullKeyMap().get(e);if(t===void 0){let n=[...this.getFullKeyMap().keys()],i=n.slice(0,10).map(o=>`- ${o}`).join(`
92
+ `);throw n.length>10&&(i+=`
93
+ ... and ${n.length-10} more`),new Error(`Cannot access full key ${e}. Full key does not exist in the schematics. Availablekeys:
94
+
95
+ `+i)}return t}getSchemaForKey(e){return this.obtainField(e).schema}parseField(e,t){if(t===void 0){if(e.defaultValue===void 0)throw new Error(`Field with key ${e.fullKey} is missing and has no default value`);return e.defaultValue}let n=e.schema.safeParse(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}parseFieldWithoutDefault(e,t){if(t===void 0)return;let n=e.schema.safeParse(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}access(e,t){let n=this.obtainField(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessByFullKey(e,t){let n=this.obtainFieldByFullKey(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessPartial(e,t){let n=this.obtainField(t);return this.parseFieldWithoutDefault(n,e.fields.find(i=>i.key===n.fullKey)?.value)}sliced(...e){let t=e.map(i=>i.endsWith("*")?{type:"prefix",value:i.substring(0,i.length-1)}:{type:"exact",value:i}),n=new Map;for(let[i,o]of this.fields.entries())for(let a of t)(a.type==="exact"&&i===a.value||a.type==="prefix"&&i.startsWith(a.value))&&n.set(i,o);return new r(this.valueTypeLibrary,n,this.extensionPrefixes)}scoped(e){let t=new Map;for(let[n,i]of this.fields.entries())n.startsWith(`${e}.`)&&t.set(n.substring(e.length+1),i);return new r(this.valueTypeLibrary,t,this.extensionPrefixes)}union(e){let t=new Map;for(let[n,i]of this.fields.entries())t.set(n,i);for(let[n,i]of e.fields.entries()){if(t.has(n))throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: "+n);t.set(n,i)}return new r(this.valueTypeLibrary,t,[...this.extensionPrefixes,...e.extensionPrefixes])}flattenBaseKey(){let e=new Map;for(let t of this.fields.values())e.set(t.fullKey,t);return new r(this.valueTypeLibrary,e,this.extensionPrefixes)}parseToMap(e){let t=ct(e),n=new Map;for(let[i,o]of this.fields.entries()){let a=t.get(o.fullKey),l=this.parseField(o,a);n.set(i,l)}return n}parseToMapWithFullKey(e){let t=ct(e),n=new Map;for(let i of this.fields.values()){let o=t.get(i.fullKey),a=this.parseField(i,o);n.set(i.fullKey,a)}return n}parseToMapPartial(e){let t=ct(e),n=new Map;for(let[i,o]of this.fields.entries()){let a=t.get(o.fullKey),l=this.parseFieldWithoutDefault(o,a);l!==void 0&&n.set(i,l)}return n}parse(e){return Jo[Ki](this.parseToMap(e))}parsePartial(e){return Yo[Ki](this.parseToMapPartial(e))}buildFullConfig(e){return{fields:Array.from(this.fields.entries()).map(([t,n])=>{let i=this.parseField(n,e[t]);return{key:n.fullKey,value:i}})}}buildPartialConfig(e){return{fields:Object.entries(e).filter(([t,n])=>n!==void 0).map(([t,n])=>{let i=this.obtainField(t);return{key:i.fullKey,value:this.parseField(i,n)}})}}createBuildPartialConfigInput(){return{}}configBuilder(){return new Ho(this.fields)}clone(){return new r(this.valueTypeLibrary,new Map(this.fields),this.extensionPrefixes)}withTypeParamOverride(e,t){let n=this.obtainField(e),i=this.clone();return i.fields.set(e,{...n,valueTypeParams:t(n.valueTypeParams),schema:this.valueTypeLibrary.getSchema(n.valueTypeKey,t(n.valueTypeParams))}),i}getFullKeyMap(){return this.fullKepMap!==void 0?this.fullKepMap:(this.fullKepMap=new Map([...this.fields.values()].map(e=>[e.fullKey,e])),this.fullKepMap)}makeLenientZodSchema(){let e=this.getFullKeyMap();return X.transform(t=>{let n=new Set;return{fields:t.fields.filter(i=>{if(this.extensionPrefixes.some(l=>i.key.startsWith(l)))return!0;if(n.has(i.key))return!1;let o=e.get(i.key);return o===void 0||!o.schema.safeParse(i.value).success?!1:(n.add(i.key),!0)})}})}getLenientZodSchema(){return this.lenientZodSchema!==void 0?this.lenientZodSchema:(this.lenientZodSchema=this.makeLenientZodSchema(),this.lenientZodSchema)}getValueType(e){let t=this.fields.get(e);return t===void 0?null:t.valueTypeKey}getValueTypeParam(e){let t=this.fields.get(e);return t===void 0?null:t.valueTypeParams}getValueTypeParamByFullKey(e){let t=this.getFullKeyMap().get(e);if(t===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return t.valueTypeParams}hasFullKey(e){return this.getFullKeyMap().get(e)!==void 0}filterConfig(e,t){let n=this.getFullKeyMap();return{fields:e.fields.filter(i=>{let o=n.get(i.key);return o===void 0?!1:t!==void 0?t(o.fullKey,{type:o.valueTypeKey,param:o.valueTypeParams}):!0})}}filterStack(e){return{layers:e.layers.map(t=>({layerName:t.layerName,config:this.filterConfig(t.config)}))}}twoWayFilterConfig(e,t){let n=[],i=[],o=this.getFullKeyMap();for(let a of e.fields){let l=o.get(a.key),c=l!==void 0;l!==void 0&&t!==void 0&&(c=t(l.fullKey,{type:l.valueTypeKey,param:l.valueTypeParams})),c?n.push(a):i.push(a)}return[{fields:n},{fields:i}]}filterFullKeys(e){let t=this.getFullKeyMap();return e.filter(n=>t.has(n))}configEffectiveEquals(e,t){let n=ct(e),i=ct(t);for(let o of this.fields.values()){let a=n.get(o.fullKey),l=i.get(o.fullKey);if(a===void 0){if(l===void 0)continue;return!1}this.valueTypeLibrary.effectiveEquals(o.valueTypeKey,o.valueTypeParams,a,l)}return!0}fieldEffectiveEquals(e,t,n){let i=this.obtainField(e);return this.valueTypeLibrary.effectiveEquals(i.valueTypeKey,i.valueTypeParams,i.schema.parse(t),i.schema.parse(n))}fieldEffectiveEqualsWithFullKey(e,t,n){let o=this.getFullKeyMap().get(e);if(o===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return this.valueTypeLibrary.effectiveEquals(o.valueTypeKey,o.valueTypeParams,o.schema.parse(t),o.schema.parse(n))}makeInternalFieldStringifyOpts(e){return{t:e.t??((t,n)=>n),desiredLength:e.desiredLength}}stringifyField(e,t,n={}){let i=this.obtainField(e);return this.valueTypeLibrary.stringify(i.valueTypeKey,i.valueTypeParams,this.makeInternalFieldStringifyOpts(n),t)}tryStringifyFieldWithFullKey(e,t,n){let o=this.getFullKeyMap().get(e);return o===void 0?null:this.valueTypeLibrary.stringify(o.valueTypeKey,o.valueTypeParams,this.makeInternalFieldStringifyOpts(n),t)}apply(e,t){let n=this.filterConfig(t);return Gf([e,n])}unApply(e,t){let n=this.filterConfig(t),i=ct(n),o=new Map(ct(e)),a=this.getFullKeyMap();for(let[l,c]of i.entries()){let u=a.get(l);if(u===void 0)continue;let h=o.get(l);if(h!==void 0){if(!this.valueTypeLibrary.effectiveEquals(u.valueTypeKey,u.valueTypeParams,c,h))continue;o.delete(l)}}return al(o)}*iterateFieldsOfConfig(e){let t=this.getFullKeyMap();for(let{key:n,value:i}of e.fields)t.get(n)!==void 0&&(yield[n,i])}*fullKeys(){let e=this.getFullKeyMap();for(let t of e.keys())yield t}effectiveCompareConfig(e,t,n={}){let{fieldFilter:i}=n,o=ct(e),a=ct(t),l=[],c=[],u=[];for(let h of this.fields.values()){if(i!==void 0&&!i(h.fullKey,{type:h.valueTypeKey,param:h.valueTypeParams}))continue;let f=o.get(h.fullKey),d=a.get(h.fullKey);if(f===void 0){if(d===void 0)continue;c.push(h.fullKey)}else d===void 0?l.push(h.fullKey):this.valueTypeLibrary.effectiveEquals(h.valueTypeKey,h.valueTypeParams,f,d)||u.push(h.fullKey)}return{onlyInA:l,onlyInB:c,inBothButDifferent:u}}serialize(){return{fields:[...this.fields.entries()].map(([e,t])=>({shortKey:e,fullKey:t.fullKey,typeKey:t.valueTypeKey,typeParams:t.valueTypeParams,defaultValue:t.defaultValue})),extensionPrefixes:this.extensionPrefixes}}hasFieldsWithPrefix(e){for(let t of this.fields.values())if(t.fullKey.startsWith(e))return!0;return!1}static deserialize(e,t){let n=new Map(t.fields.map(i=>{let o=e.parseParamTypes(i.typeKey,i.typeParams),a=e.getSchema(i.typeKey,o);return[i.shortKey,{valueTypeKey:i.typeKey,valueTypeParams:o,schema:a,fullKey:i.fullKey,defaultValue:a.parse(i.defaultValue)}]}));return new r(e,n,t.extensionPrefixes??[])}static tryDeserialize(e,t){let n=new Map,i=[];for(let o of t.fields)try{let a=e.parseParamTypes(o.typeKey,o.typeParams),l=e.getSchema(o.typeKey,a);n.set(o.shortKey,{valueTypeKey:o.typeKey,valueTypeParams:a,schema:l,fullKey:o.fullKey,defaultValue:l.parse(o.defaultValue)})}catch(a){i.push({fullKey:o.fullKey,error:ir(a)})}return{schematics:new r(e,n,t.extensionPrefixes??[]),errors:i}}},Ho=class{constructor(e){this.fieldDefs=e,this.fields=new Map}with(e,t){let n=this.fieldDefs.get(e);if(n===void 0)throw new Error(`Field with key ${e} does not exist in the schematics.`);return this.fields.set(n.fullKey,t),this}build(){return al(this.fields)}},Jo=class r{constructor(e){this.configMap=e}static[Ki](e){return new r(e)}get(e){return this.configMap.get(e)}},Yo=class r{constructor(e){this.configMap=e}static[Ki](e){return new r(e)}get(e){return this.configMap.get(e)}has(e){return this.configMap.has(e)}};function ct(r){return new Map(r.fields.map(e=>[e.key,e.value]))}function al(r){return{fields:Array.from(r.entries()).map(([e,t])=>({key:e,value:t}))}}function Gf(r){let e=new Map;for(let t of r)for(let{key:n,value:i}of t.fields)e.set(n,i);return al(e)}var Kf={fields:[]};function Id(r,e){return{layers:[{layerName:r,config:e}]}}function Ro(r,e,t){return{layers:[...r.layers,{layerName:e,config:t}]}}function Ke(r,e){if(r===e)return!0;if(typeof r!="object"||typeof e!="object"||r===null||e===null||Array.isArray(r)!==Array.isArray(e))return!1;if(Array.isArray(r)){if(r.length!==e?.length)return!1;for(let i=0;i<r.length;i++)if(!Ke(r[i],e[i]))return!1;return!0}let t=new Set(Object.keys(r)),n=new Set(Object.keys(e));if(t.size!==n.size)return!1;for(let i of t)if(!n.has(i)||!Ke(r[i],e[i]))return!1;return!0}function Qo(r,e){return r===void 0||r===""?e??'""':JSON.stringify(r)}function $r(r,e){return Qo(r?.replace(/\\n/g,`
96
+ `),e)}var Hf=new Go({displayName:s.string().optional(),hint:s.string().optional(),modelCentric:s.boolean().optional(),nonConfigurable:s.boolean().optional(),engineDoesNotSupport:s.boolean().optional(),machineDependent:s.boolean().optional(),warning:s.string().optional(),subtitle:s.string().optional(),isExperimental:s.boolean().optional(),dependencies:s.array(n0).optional()}).valueType("numeric",{paramType:{min:s.number().optional(),max:s.number().optional(),step:s.number().optional(),int:s.boolean().optional(),precision:s.number().int().nonnegative().optional(),slider:s.object({min:s.number(),max:s.number(),step:s.number()}).optional(),shortHand:s.string().optional()},schemaMaker:({min:r,max:e,int:t,precision:n})=>{let i=s.number();if(r!==void 0&&(i=i.min(r)),e!==void 0&&(i=i.max(e)),t){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return i},effectiveEquals:(r,e)=>r===e,stringify:(r,{int:e,precision:t})=>e?String(Math.round(r)):r.toFixed(t??2)}).valueType("string",{paramType:{minLength:s.number().optional(),maxLength:s.number().optional(),isParagraph:s.boolean().optional(),isProtected:s.boolean().optional(),isToken:s.boolean().optional(),placeholder:s.string().optional()},schemaMaker:({minLength:r,maxLength:e})=>{let t=s.string();return r!==void 0&&(t=t.min(r)),e!==void 0&&(t=t.max(e)),t},effectiveEquals:(r,e)=>r===e,stringify:(r,{isParagraph:e,isProtected:t},{t:n,desiredLength:i})=>{if(t)return"********";if(e)return r===""?n("config:customInputs.string.emptyParagraph","<Empty>"):i===void 0||r.length<=i?r:r.slice(0,Math.floor(i/2))+" ... "+r.slice(-Math.ceil(i/2));{let o=Qo(r);return i===void 0||o.length<=i?o:o.slice(0,Math.floor(i/2))+"..."+o.slice(-Math.ceil(i/2))}}}).valueType("select",{paramType:{options:s.array(s.object({value:s.string().nonempty(),displayName:s.string()}).or(s.string())).refine(r=>{let e=new Set;for(let t of r){let n=typeof t=="string"?t:t.value;if(e.has(n))return!1;e.add(n)}return!0},{message:"Duplicate values in options."})},schemaMaker:({options:r})=>{let e=new Set(r.map(t=>typeof t=="string"?t:t.value));return s.string().refine(t=>e.has(t))},effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("boolean",{paramType:{},schemaMaker:()=>s.boolean(),effectiveEquals:(r,e)=>r===e,stringify:r=>r?"ON":"OFF"}).valueType("stringArray",{paramType:{maxNumItems:s.number().optional(),allowEmptyStrings:s.boolean().optional()},schemaMaker:({maxNumItems:r,allowEmptyStrings:e})=>{let t=s.string();e||(t=t.min(1));let n=s.array(t);return r!==void 0&&(n=n.max(r)),n},effectiveEquals:(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),stringify:(r,e,{t,desiredLength:n})=>{let i=r.map(a=>Qo(a));if(i.length===0)return t("config:customInputs.stringArray.empty","<Empty>");if(i.length<=2||n===void 0)return i.join(", ");let o=i[0].length+i[1].length+6;for(let a=1;a<i.length-1;a++)if(o+=i[a].length+2,o>=n)return i.slice(0,a).join(", ")+", ..."+i[i.length-1];return i.join(", ")}});Hf.build();var Jf=Hf.valueType("checkboxNumeric",{paramType:{min:s.number().optional(),max:s.number().optional(),step:s.number().optional(),int:s.boolean().optional(),uncheckedHint:s.string().optional(),precision:s.number().int().nonnegative().optional(),slider:s.object({min:s.number(),max:s.number(),step:s.number()}).optional()},schemaMaker:({min:r,max:e,int:t,precision:n})=>{let i=s.number();if(r!==void 0&&(i=i.min(r)),e!==void 0&&(i=i.max(e)),t){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return s.object({checked:s.boolean(),value:i})},effectiveEquals:(r,e)=>r.checked!==e.checked?!1:r.checked?r.value===e.value:!0,stringify:(r,{int:e,precision:t},{t:n})=>r.checked?e?String(Math.round(r.value)):r.value.toFixed(t??2):n("config:customInputs.checkboxNumeric.off","OFF")}).valueType("numericArray",{paramType:{min:s.number().optional(),max:s.number().optional(),int:s.boolean().optional()},schemaMaker:({min:r,max:e,int:t})=>{let n=s.number();return r!==void 0&&(n=n.min(r)),e!==void 0&&(n=n.max(e)),t&&(n=n.int()),s.array(n)},effectiveEquals:(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),stringify:(r,{int:e})=>r.map(t=>String(e?Math.round(t):t)).join(", ")}).valueType("contextOverflowPolicy",{paramType:{},schemaMaker:()=>Cf,effectiveEquals:(r,e)=>r===e,stringify:(r,e,{t})=>{switch(r){case"stopAtLimit":return t("config:customInputs.contextOverflowPolicy.stopAtLimit","Stop At Limit");case"truncateMiddle":return t("config:customInputs.contextOverflowPolicy.truncateMiddle","Truncate Middle");case"rollingWindow":return t("config:customInputs.contextOverflowPolicy.rollingWindow","Rolling Window")}}}).valueType("context",{paramType:{},schemaMaker:()=>s.array(s0),effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("contextLength",{paramType:{max:s.number().optional()},schemaMaker:()=>s.number().int().positive(),effectiveEquals:(r,e)=>r===e,stringify:(r,{max:e})=>e===void 0?String(r):`${r}/${e}`}).valueType("modelIdentifier",{paramType:{domain:s.array(Tn).optional()},schemaMaker:()=>s.string(),effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("llmPromptTemplate",{paramType:{},schemaMaker:()=>Sf,effectiveEquals:(r,e)=>{if(r.type!==e.type||r.stopStrings.length!==e.stopStrings.length||!r.stopStrings.every((t,n)=>t===e.stopStrings[n]))return!1;switch(r.type){case"jinja":return r.jinjaPromptTemplate?.template===e.jinjaPromptTemplate?.template;case"manual":return r.manualPromptTemplate?.beforeSystem===e.manualPromptTemplate?.beforeSystem&&r.manualPromptTemplate?.afterSystem===e.manualPromptTemplate?.afterSystem&&r.manualPromptTemplate?.beforeUser===e.manualPromptTemplate?.beforeUser&&r.manualPromptTemplate?.afterUser===e.manualPromptTemplate?.afterUser&&r.manualPromptTemplate?.beforeAssistant===e.manualPromptTemplate?.beforeAssistant&&r.manualPromptTemplate?.afterAssistant===e.manualPromptTemplate?.afterAssistant;default:{let t=r.type;throw new Error("Unknown template type: "+t)}}},stringify:(r,e,{t,desiredLength:n})=>{switch(r.type){case"jinja":{let i=`${t("config:customInputs.llmPromptTemplate.type","Type")}: ${t("config:customInputs.llmPromptTemplate.types.jinja/label","Jinja")}
97
+ ${t("config:customInputs.llmPromptTemplate.jinja.template/label","Template")}: `;if(n===void 0)return i+r.jinjaPromptTemplate?.template;let o=i.length,a=Math.min(100,n-o),l=r.jinjaPromptTemplate?.template??"";return l.length<=a?i+l:i+l.slice(0,Math.floor(a/2))+"..."+l.slice(-Math.ceil(a/2))}case"manual":return`${t("config:customInputs.llmPromptTemplate.type","Type")}: ${t("config:customInputs.llmPromptTemplate.types.manual/label","Manual")}
98
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label","Before System")}: ${$r(r.manualPromptTemplate?.beforeSystem)}
99
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label","After System")}: ${$r(r.manualPromptTemplate?.afterSystem)}
100
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label","Before User")}: ${$r(r.manualPromptTemplate?.beforeUser)}
101
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label","After User")}: ${$r(r.manualPromptTemplate?.afterUser)}
102
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label","Before Assistant")}: ${$r(r.manualPromptTemplate?.beforeAssistant)}
103
+ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label","After Assistant")}: ${$r(r.manualPromptTemplate?.afterAssistant)}`;default:{let i=r.type;throw new Error("Unknown template type: "+i)}}}}).valueType("llmReasoningParsing",{paramType:{},schemaMaker:()=>Ef,effectiveEquals:(r,e)=>r.startString===e.startString&&r.endString===e.endString,stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaStructuredOutput",{paramType:{},schemaMaker:()=>Ya,effectiveEquals:(r,e)=>r.type==="json"&&e.type==="json"?Ke(r,e):r.type==="none"&&e.type==="none",stringify:r=>JSON.stringify(r,null,2)}).valueType("speculativeDecodingDraftModel",{paramType:{},schemaMaker:()=>s.string(),effectiveEquals:(r,e)=>r===e,stringify:(r,e,{t})=>r===""?t("config:customInputs.speculativeDecodingDraftModel.off","OFF"):r}).valueType("toolUse",{paramType:{},schemaMaker:()=>yf,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("toolNaming",{paramType:{},schemaMaker:()=>wf,effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("llamaAccelerationOffloadRatio",{paramType:{numLayers:s.number().optional()},schemaMaker:()=>of,effectiveEquals:(r,e)=>(r==="max"?1:r==="off"?0:r)===(e==="max"?1:e==="off"?0:e),stringify:(r,{numLayers:e},{t})=>{if(r==="max"||r===1){let n=t("config:customInputs.llamaAccelerationOffloadRatio.max","MAX");return e!==0?`${n} (${e})`:n}return r==="off"||r===0?t("config:customInputs.llamaAccelerationOffloadRatio.off","OFF"):e!==void 0?String(Math.round(e*r)):(r*100).toFixed(0)+"%"}}).valueType("llamaMirostatSampling",{paramType:{},schemaMaker:()=>d0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaLogitBias",{paramType:{},schemaMaker:()=>h0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaCacheQuantizationType",{paramType:{},schemaMaker:()=>s.object({checked:s.boolean(),value:$b}),effectiveEquals:(r,e)=>r.checked!==e.checked?!1:r.checked?r.value===e.value:!0,stringify:(r,e,{t})=>r.checked?r.value:t("config:customInputs.llamaCacheQuantizationType.off","OFF")}).valueType("mlxKvCacheQuantizationType",{paramType:{},schemaMaker:()=>qb,effectiveEquals:(r,e)=>r.enabled!==e.enabled?!1:r.enabled?r.bits===e.bits&&r.groupSize===e.groupSize&&r.quantizedStart===e.quantizedStart:!0,stringify:r=>JSON.stringify(r,null,2)}).valueType("retrievalChunkingMethod",{paramType:{},schemaMaker:()=>Wf,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("envVars",{paramType:{},schemaMaker:()=>yb,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("gpuSplitConfig",{paramType:{},schemaMaker:()=>e0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).build(),Pt=new Gi(Jf).extension("ext.virtualModel.customField").field("envVars","envVars",{},{}).scope("llm.prediction",r=>r.field("temperature","numeric",{min:0,step:.01,slider:{min:0,max:1,step:.01},precision:2,shortHand:"temp"},.8).field("contextOverflowPolicy","contextOverflowPolicy",{},"truncateMiddle").field("maxPredictedTokens","checkboxNumeric",{min:1,int:!0},{checked:!1,value:1e3}).field("stopStrings","stringArray",{},[]).field("toolCallStopStrings","stringArray",{},[]).field("structured","llamaStructuredOutput",{},{type:"none"}).scope("speculativeDecoding",e=>e.field("draftModel","speculativeDecodingDraftModel",{modelCentric:!0},"").field("minDraftLengthToConsider","numeric",{modelCentric:!0,min:0,int:!0,slider:{min:0,max:10,step:1}},0).field("numReuseTokens","numeric",{modelCentric:!0,min:1,int:!0},256).field("minContinueDraftingProbability","numeric",{modelCentric:!0,min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},.75).field("maxTokensToDraft","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:10,max:30,step:1}},16).field("numDraftTokensExact","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:1,max:10,step:1}},2)).field("tools","toolUse",{},{type:"none"}).field("toolNaming","toolNaming",{},"removeSpecial").field("promptTemplate","llmPromptTemplate",{modelCentric:!0},{type:"manual",manualPromptTemplate:{beforeSystem:"Instruct: ",afterSystem:`
104
+ `,beforeAssistant:"AI: ",afterAssistant:`
105
+ `,beforeUser:"Human: ",afterUser:`
106
+ `},stopStrings:[]}).field("systemPrompt","string",{isParagraph:!0},"").field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("contextPrefill","context",{},[]).field("topKSampling","numeric",{min:-1,max:500,int:!0},40).field("repeatPenalty","checkboxNumeric",{min:-1,step:.01},{checked:!0,value:1.1}).field("minPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.05}).field("topPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.95}).field("logProbs","checkboxNumeric",{min:0,max:100,int:!0},{checked:!1,value:0}).scope("reasoning",e=>e.field("parsing","llmReasoningParsing",{},{enabled:!0,startString:"<think>",endString:"</think>"})).scope("llama",e=>e.field("cpuThreads","numeric",{min:1,int:!0},4).field("frequencyPenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("xtcProbability","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.5}).field("xtcThreshold","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:.5,step:.01}},{checked:!1,value:.1}).field("presencePenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("mirostatSampling","llamaMirostatSampling",{},{version:0,learningRate:.1,targetEntropy:5}).field("tailFreeSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.95}).field("locallyTypicalSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.9}).field("logitBias","llamaLogitBias",{},[]))).scope("llm.load",r=>r.field("contextLength","contextLength",{machineDependent:!0},2048).field("numExperts","numeric",{min:0,int:!0},0).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("offloadKVCacheToGpu","boolean",{},!0).field("numCpuExpertLayersRatio","llamaAccelerationOffloadRatio",{machineDependent:!0,isExperimental:!0},"off").scope("llama",e=>e.scope("acceleration",t=>t.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("cpuThreadPoolSize","numeric",{min:1,machineDependent:!0},4).field("evalBatchSize","numeric",{min:1,int:!0},512).field("flashAttention","boolean",{isExperimental:!0,warning:"config:flashAttentionWarning"},!1).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("useFp16ForKVCache","boolean",{},!0).field("tryMmap","boolean",{},!0).field("kCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0},{checked:!1,value:"f16"}).field("vCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0,warning:"config:llamaKvCacheQuantizationWarning"},{checked:!1,value:"f16"})).scope("mlx",e=>e.field("kvCacheQuantization","mlxKvCacheQuantizationType",{isExperimental:!0},{enabled:!1,bits:8,groupSize:64,quantizedStart:5e3}))).scope("load",r=>r.field("gpuSplitConfig","gpuSplitConfig",{},Xb).field("gpuStrictVramCap","boolean",{},!1)).scope("embedding.load",r=>r.field("contextLength","contextLength",{machineDependent:!0},2048).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).scope("llama",e=>e.scope("acceleration",t=>t.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("evalBatchSize","numeric",{min:1,int:!0},512).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("tryMmap","boolean",{},!0))).scope("retrieval",r=>r.field("databaseFile","string",{machineDependent:!0},"").field("chunkingMethod","retrievalChunkingMethod",{},{type:"recursive-v1",chunkSize:512,chunkOverlap:100}).field("limit","numeric",{min:1,int:!0},5).field("embeddingModel","modelIdentifier",{domain:["embedding"]},"")).build(),Kr=Pt.scoped("llm.prediction"),$n=Kr.sliced("temperature","maxPredictedTokens","promptTemplate","systemPrompt","seed","contextPrefill","tools","toolNaming","reasoning.*");$n.union(Kr.sliced("llama.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","topKSampling","repeatPenalty","minPSampling","topPSampling","logProbs","speculativeDecoding.draftModel","speculativeDecoding.minContinueDraftingProbability","speculativeDecoding.minDraftLengthToConsider","speculativeDecoding.maxTokensToDraft","speculativeDecoding.numReuseTokens"));$n.union(Kr.sliced("mlx.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","repeatPenalty","minPSampling","topPSampling","topKSampling","speculativeDecoding.draftModel","speculativeDecoding.numDraftTokensExact"));$n.union(Kr.sliced("transformers.*"));$n.union(Kr.sliced("onnx.*","repeatPenalty","topPSampling","topKSampling"));var Hr=Pt.scoped("llm.load").union(Pt.sliced("envVars")),Un=Hr.sliced("contextLength","seed","envVars"),Yf=Pt.sliced("llama.load.*","load.*"),cv=Un.union(Hr.sliced("llama.*","load.*","offloadKVCacheToGpu")).union(Yf);Un.union(Hr.sliced("mlx.*"));Un.union(Hr.sliced("transformers.*"));Un.union(Hr.sliced("onnx.*"));var uv=Hr.sliced("numExperts","numCpuExpertLayersRatio"),dv=cv.union(uv),Qf=Pt.scoped("embedding.load").union(Pt.sliced("load.*")),Xf=Qf.sliced("contextLength","seed"),fv=Pt.scoped("retrieval"),hv=Xf.union(Qf.sliced("llama.*")).union(Yf);new Gi(Jf).build();function nr(r,e){if(r!==void 0)return r===!1?{checked:!1,value:e}:{checked:!0,value:r}}function pv(r){let e=Kr.buildPartialConfig({temperature:r.temperature,contextOverflowPolicy:r.contextOverflowPolicy,maxPredictedTokens:nr(r.maxTokens,1),stopStrings:r.stopStrings,toolCallStopStrings:r.toolCallStopStrings,structured:r.structured,tools:r.rawTools,toolNaming:r.toolNaming,topKSampling:r.topKSampling,repeatPenalty:nr(r.repeatPenalty,1.1),minPSampling:nr(r.minPSampling,.05),topPSampling:nr(r.topPSampling,.95),"llama.xtcProbability":nr(r.xtcProbability,0),"llama.xtcThreshold":nr(r.xtcThreshold,0),logProbs:nr(r.logProbs,0),"llama.cpuThreads":r.cpuThreads,promptTemplate:r.promptTemplate,"speculativeDecoding.draftModel":r.draftModel,"speculativeDecoding.numDraftTokensExact":r.speculativeDecodingNumDraftTokensExact,"speculativeDecoding.minDraftLengthToConsider":r.speculativeDecodingMinDraftLengthToConsider,"speculativeDecoding.minContinueDraftingProbability":r.speculativeDecodingMinContinueDraftingProbability,"reasoning.parsing":r.reasoningParsing});return r.raw!==void 0?Gf([r.raw,e]):e}var Ze={},ue={},Od;function ar(){if(Od)return ue;Od=1;var r=ue.ValidationError=function(g,b,y,D,v,S){if(Array.isArray(D)?(this.path=D,this.property=D.reduce(function(k,x){return k+l(x)},"instance")):D!==void 0&&(this.property=D),g&&(this.message=g),y){var E=y.$id||y.id;this.schema=E||y}b!==void 0&&(this.instance=b),this.name=v,this.argument=S,this.stack=this.toString()};r.prototype.toString=function(){return this.property+" "+this.message};var e=ue.ValidatorResult=function(g,b,y,D){this.instance=g,this.schema=b,this.options=y,this.path=D.path,this.propertyPath=D.propertyPath,this.errors=[],this.throwError=y&&y.throwError,this.throwFirst=y&&y.throwFirst,this.throwAll=y&&y.throwAll,this.disableFormat=y&&y.disableFormat===!0};e.prototype.addError=function(g){var b;if(typeof g=="string")b=new r(g,this.instance,this.schema,this.path);else{if(!g)throw new Error("Missing error detail");if(!g.message)throw new Error("Missing error message");if(!g.name)throw new Error("Missing validator type");b=new r(g.message,this.instance,this.schema,this.path,g.name,g.argument)}if(this.errors.push(b),this.throwFirst)throw new n(this);if(this.throwError)throw b;return b},e.prototype.importErrors=function(g){typeof g=="string"||g&&g.validatorType?this.addError(g):g&&g.errors&&(this.errors=this.errors.concat(g.errors))};function t(m,g){return g+": "+m.toString()+`
107
+ `}e.prototype.toString=function(g){return this.errors.map(t).join("")},Object.defineProperty(e.prototype,"valid",{get:function(){return!this.errors.length}}),ue.ValidatorResultError=n;function n(m){typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n),this.instance=m.instance,this.schema=m.schema,this.options=m.options,this.errors=m.errors}n.prototype=new Error,n.prototype.constructor=n,n.prototype.name="Validation Error";var i=ue.SchemaError=function m(g,b){this.message=g,this.schema=b,Error.call(this,g),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,m)};i.prototype=Object.create(Error.prototype,{constructor:{value:i,enumerable:!1},name:{value:"SchemaError",enumerable:!1}});var o=ue.SchemaContext=function(g,b,y,D,v){this.schema=g,this.options=b,Array.isArray(y)?(this.path=y,this.propertyPath=y.reduce(function(S,E){return S+l(E)},"instance")):this.propertyPath=y,this.base=D,this.schemas=v};o.prototype.resolve=function(g){return p(this.base,g)},o.prototype.makeChild=function(g,b){var y=b===void 0?this.path:this.path.concat([b]),D=g.$id||g.id;let v=p(this.base,D||"");var S=new o(g,this.options,y,v,Object.create(this.schemas));return D&&!S.schemas[v]&&(S.schemas[v]=g),S};var a=ue.FORMAT_REGEXPS={"date-time":/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,date:/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,time:/^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,duration:/P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,email:/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,"idn-email":/^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,"ip-address":/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ipv6:/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-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-Fa-f]{1,4}:){5}(((:[0-9A-Fa-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-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-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-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-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-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-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-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-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-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-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}))|:)))(%.+)?\s*$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"uri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,iri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"iri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,uuid:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,"uri-template":/(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,"json-pointer":/^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,"relative-json-pointer":/^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,hostname:/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"host-name":/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"utc-millisec":function(m){return typeof m=="string"&&parseFloat(m)===parseInt(m,10)&&!isNaN(m)},regex:function(m){var g=!0;try{new RegExp(m)}catch{g=!1}return g},style:/[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,color:/^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,phone:/^\+(?:[0-9] ?){6,14}[0-9]$/,alpha:/^[a-zA-Z]+$/,alphanumeric:/^[a-zA-Z0-9]+$/};a.regexp=a.regex,a.pattern=a.regex,a.ipv4=a["ip-address"],ue.isFormat=function(g,b,y){if(typeof g=="string"&&a[b]!==void 0){if(a[b]instanceof RegExp)return a[b].test(g);if(typeof a[b]=="function")return a[b](g)}else if(y&&y.customFormats&&typeof y.customFormats[b]=="function")return y.customFormats[b](g);return!0};var l=ue.makeSuffix=function(g){return g=g.toString(),!g.match(/[.\s\[\]]/)&&!g.match(/^[\d]/)?"."+g:g.match(/^\d+$/)?"["+g+"]":"["+JSON.stringify(g)+"]"};ue.deepCompareStrict=function m(g,b){if(typeof g!=typeof b)return!1;if(Array.isArray(g))return!Array.isArray(b)||g.length!==b.length?!1:g.every(function(v,S){return m(g[S],b[S])});if(typeof g=="object"){if(!g||!b)return g===b;var y=Object.keys(g),D=Object.keys(b);return y.length!==D.length?!1:y.every(function(v){return m(g[v],b[v])})}return g===b};function c(m,g,b,y){typeof b=="object"?g[y]=f(m[y],b):m.indexOf(b)===-1&&g.push(b)}function u(m,g,b){g[b]=m[b]}function h(m,g,b,y){typeof g[y]!="object"||!g[y]?b[y]=g[y]:m[y]?b[y]=f(m[y],g[y]):b[y]=g[y]}function f(m,g){var b=Array.isArray(g),y=b&&[]||{};return b?(m=m||[],y=y.concat(m),g.forEach(c.bind(null,m,y))):(m&&typeof m=="object"&&Object.keys(m).forEach(u.bind(null,m,y)),Object.keys(g).forEach(h.bind(null,m,g,y))),y}ue.deepMerge=f,ue.objectGetPath=function(g,b){for(var y=b.split("/").slice(1),D;typeof(D=y.shift())=="string";){var v=decodeURIComponent(D.replace(/~0/,"~").replace(/~1/g,"/"));if(!(v in g))return;g=g[v]}return g};function d(m){return"/"+encodeURIComponent(m).replace(/~/g,"%7E")}ue.encodePath=function(g){return g.map(d).join("")},ue.getDecimalPlaces=function(g){var b=0;if(isNaN(g))return b;typeof g!="number"&&(g=Number(g));var y=g.toString().split("e");if(y.length===2){if(y[1][0]!=="-")return b;b=Number(y[1].slice(1))}var D=y[0].split(".");return D.length===2&&(b+=D[1].length),b},ue.isSchema=function(g){return typeof g=="object"&&g||typeof g=="boolean"};var p=ue.resolveUrl=function(g,b){let y=new URL(b,new URL(g,"resolve://"));if(y.protocol==="resolve:"){let{pathname:D,search:v,hash:S}=y;return D+v+S}return y.toString()};return ue}var Io,Md;function mv(){if(Md)return Io;Md=1;var r=ar(),e=r.ValidatorResult,t=r.SchemaError,n={};n.ignoreProperties={id:!0,default:!0,description:!0,title:!0,additionalItems:!0,then:!0,else:!0,$schema:!0,$ref:!0,extends:!0};var i=n.validators={};i.type=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),b=Array.isArray(d.type)?d.type:[d.type];if(!b.some(this.testType.bind(this,f,d,p,m))){var y=b.map(function(D){if(D){var v=D.$id||D.id;return v?"<"+v+">":D+""}});g.addError({name:"type",argument:y,message:"is not of a type(s) "+y})}return g};function o(h,f,d,p,m){var g=f.throwError,b=f.throwAll;f.throwError=!1,f.throwAll=!1;var y=this.validateSchema(h,m,f,d);return f.throwError=g,f.throwAll=b,!y.valid&&p instanceof Function&&p(y),y.valid}i.anyOf=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),b=new e(f,d,p,m);if(!Array.isArray(d.anyOf))throw new t("anyOf must be an array");if(!d.anyOf.some(o.bind(this,f,p,m,function(D){b.importErrors(D)}))){var y=d.anyOf.map(function(D,v){var S=D.$id||D.id;return S?"<"+S+">":D.title&&JSON.stringify(D.title)||D.$ref&&"<"+D.$ref+">"||"[subschema "+v+"]"});p.nestedErrors&&g.importErrors(b),g.addError({name:"anyOf",argument:y,message:"is not any of "+y.join(",")})}return g},i.allOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.allOf))throw new t("allOf must be an array");var g=new e(f,d,p,m),b=this;return d.allOf.forEach(function(y,D){var v=b.validateSchema(f,y,p,m);if(!v.valid){var S=y.$id||y.id,E=S||y.title&&JSON.stringify(y.title)||y.$ref&&"<"+y.$ref+">"||"[subschema "+D+"]";g.addError({name:"allOf",argument:{id:E,length:v.errors.length,valid:v},message:"does not match allOf schema "+E+" with "+v.errors.length+" error[s]:"}),g.importErrors(v)}}),g},i.oneOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.oneOf))throw new t("oneOf must be an array");var g=new e(f,d,p,m),b=new e(f,d,p,m),y=d.oneOf.filter(o.bind(this,f,p,m,function(v){b.importErrors(v)})).length,D=d.oneOf.map(function(v,S){var E=v.$id||v.id;return E||v.title&&JSON.stringify(v.title)||v.$ref&&"<"+v.$ref+">"||"[subschema "+S+"]"});return y!==1&&(p.nestedErrors&&g.importErrors(b),g.addError({name:"oneOf",argument:D,message:"is not exactly one from "+D.join(",")})),g},i.if=function(f,d,p,m){if(f===void 0)return null;if(!r.isSchema(d.if))throw new Error('Expected "if" keyword to be a schema');var g=o.call(this,f,p,m,null,d.if),b=new e(f,d,p,m),y;if(g){if(d.then===void 0)return;if(!r.isSchema(d.then))throw new Error('Expected "then" keyword to be a schema');y=this.validateSchema(f,d.then,p,m.makeChild(d.then)),b.importErrors(y)}else{if(d.else===void 0)return;if(!r.isSchema(d.else))throw new Error('Expected "else" keyword to be a schema');y=this.validateSchema(f,d.else,p,m.makeChild(d.else)),b.importErrors(y)}return b};function a(h,f){if(Object.hasOwnProperty.call(h,f))return h[f];if(f in h){for(;h=Object.getPrototypeOf(h);)if(Object.propertyIsEnumerable.call(h,f))return h[f]}}i.propertyNames=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=d.propertyNames!==void 0?d.propertyNames:{};if(!r.isSchema(b))throw new t('Expected "propertyNames" to be a schema (object or boolean)');for(var y in f)if(a(f,y)!==void 0){var D=this.validateSchema(y,b,p,m.makeChild(b));g.importErrors(D)}return g}},i.properties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=d.properties||{};for(var y in b){var D=b[y];if(D!==void 0){if(D===null)throw new t('Unexpected null, expected schema in "properties"');typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,y,D,p,m);var v=a(f,y),S=this.validateSchema(v,D,p,m.makeChild(D,y));S.instance!==g.instance[y]&&(g.instance[y]=S.instance),g.importErrors(S)}}return g}};function l(h,f,d,p,m,g){if(this.types.object(h)&&!(f.properties&&f.properties[m]!==void 0))if(f.additionalProperties===!1)g.addError({name:"additionalProperties",argument:m,message:"is not allowed to have the additional property "+JSON.stringify(m)});else{var b=f.additionalProperties||{};typeof d.preValidateProperty=="function"&&d.preValidateProperty(h,m,b,d,p);var y=this.validateSchema(h[m],b,d,p.makeChild(b,m));y.instance!==g.instance[m]&&(g.instance[m]=y.instance),g.importErrors(y)}}i.patternProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=d.patternProperties||{};for(var y in f){var D=!0;for(var v in b){var S=b[v];if(S!==void 0){if(S===null)throw new t('Unexpected null, expected schema in "patternProperties"');try{var E=new RegExp(v,"u")}catch{E=new RegExp(v)}if(E.test(y)){D=!1,typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,y,S,p,m);var k=this.validateSchema(f[y],S,p,m.makeChild(S,y));k.instance!==g.instance[y]&&(g.instance[y]=k.instance),g.importErrors(k)}}}D&&l.call(this,f,d,p,m,y,g)}return g}},i.additionalProperties=function(f,d,p,m){if(this.types.object(f)){if(d.patternProperties)return null;var g=new e(f,d,p,m);for(var b in f)l.call(this,f,d,p,m,b,g);return g}},i.minProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=Object.keys(f);return b.length>=d.minProperties||g.addError({name:"minProperties",argument:d.minProperties,message:"does not meet minimum property length of "+d.minProperties}),g}},i.maxProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=Object.keys(f);return b.length<=d.maxProperties||g.addError({name:"maxProperties",argument:d.maxProperties,message:"does not meet maximum property length of "+d.maxProperties}),g}},i.items=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.items!==void 0){var b=new e(f,d,p,m);return f.every(function(y,D){if(Array.isArray(d.items))var v=d.items[D]===void 0?d.additionalItems:d.items[D];else var v=d.items;if(v===void 0)return!0;if(v===!1)return b.addError({name:"items",message:"additionalItems not permitted"}),!1;var S=g.validateSchema(y,v,p,m.makeChild(v,D));return S.instance!==b.instance[D]&&(b.instance[D]=S.instance),b.importErrors(S),!0}),b}},i.contains=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.contains!==void 0){if(!r.isSchema(d.contains))throw new Error('Expected "contains" keyword to be a schema');var b=new e(f,d,p,m),y=f.some(function(D,v){var S=g.validateSchema(D,d.contains,p,m.makeChild(d.contains,v));return S.errors.length===0});return y===!1&&b.addError({name:"contains",argument:d.contains,message:"must contain an item matching given schema"}),b}},i.minimum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMinimum&&d.exclusiveMinimum===!0?f>d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than "+d.minimum}):f>=d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than or equal to "+d.minimum}),g}},i.maximum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMaximum&&d.exclusiveMaximum===!0?f<d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than "+d.maximum}):f<=d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than or equal to "+d.maximum}),g}},i.exclusiveMinimum=function(f,d,p,m){if(typeof d.exclusiveMinimum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),b=f>d.exclusiveMinimum;return b||g.addError({name:"exclusiveMinimum",argument:d.exclusiveMinimum,message:"must be strictly greater than "+d.exclusiveMinimum}),g}},i.exclusiveMaximum=function(f,d,p,m){if(typeof d.exclusiveMaximum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),b=f<d.exclusiveMaximum;return b||g.addError({name:"exclusiveMaximum",argument:d.exclusiveMaximum,message:"must be strictly less than "+d.exclusiveMaximum}),g}};var c=function(f,d,p,m,g,b){if(this.types.number(f)){var y=d[g];if(y==0)throw new t(g+" cannot be zero");var D=new e(f,d,p,m),v=r.getDecimalPlaces(f),S=r.getDecimalPlaces(y),E=Math.max(v,S),k=Math.pow(10,E);return Math.round(f*k)%Math.round(y*k)!==0&&D.addError({name:g,argument:y,message:b+JSON.stringify(y)}),D}};i.multipleOf=function(f,d,p,m){return c.call(this,f,d,p,m,"multipleOf","is not a multiple of (divisible by) ")},i.divisibleBy=function(f,d,p,m){return c.call(this,f,d,p,m,"divisibleBy","is not divisible by (multiple of) ")},i.required=function(f,d,p,m){var g=new e(f,d,p,m);return f===void 0&&d.required===!0?g.addError({name:"required",message:"is required"}):this.types.object(f)&&Array.isArray(d.required)&&d.required.forEach(function(b){a(f,b)===void 0&&g.addError({name:"required",argument:b,message:"requires property "+JSON.stringify(b)})}),g},i.pattern=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),b=d.pattern;try{var y=new RegExp(b,"u")}catch{y=new RegExp(b)}return f.match(y)||g.addError({name:"pattern",argument:d.pattern,message:"does not match pattern "+JSON.stringify(d.pattern.toString())}),g}},i.format=function(f,d,p,m){if(f!==void 0){var g=new e(f,d,p,m);return!g.disableFormat&&!r.isFormat(f,d.format,this)&&g.addError({name:"format",argument:d.format,message:"does not conform to the "+JSON.stringify(d.format)+" format"}),g}},i.minLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),b=f.match(/[\uDC00-\uDFFF]/g),y=f.length-(b?b.length:0);return y>=d.minLength||g.addError({name:"minLength",argument:d.minLength,message:"does not meet minimum length of "+d.minLength}),g}},i.maxLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),b=f.match(/[\uDC00-\uDFFF]/g),y=f.length-(b?b.length:0);return y<=d.maxLength||g.addError({name:"maxLength",argument:d.maxLength,message:"does not meet maximum length of "+d.maxLength}),g}},i.minItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length>=d.minItems||g.addError({name:"minItems",argument:d.minItems,message:"does not meet minimum length of "+d.minItems}),g}},i.maxItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length<=d.maxItems||g.addError({name:"maxItems",argument:d.maxItems,message:"does not meet maximum length of "+d.maxItems}),g}};function u(h,f,d){var p,m=d.length;for(p=f+1,m;p<m;p++)if(r.deepCompareStrict(h,d[p]))return!1;return!0}return i.uniqueItems=function(f,d,p,m){if(d.uniqueItems===!0&&this.types.array(f)){var g=new e(f,d,p,m);return f.every(u)||g.addError({name:"uniqueItems",message:"contains duplicate item"}),g}},i.dependencies=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m);for(var b in d.dependencies)if(f[b]!==void 0){var y=d.dependencies[b],D=m.makeChild(y,b);if(typeof y=="string"&&(y=[y]),Array.isArray(y))y.forEach(function(S){f[S]===void 0&&g.addError({name:"dependencies",argument:D.propertyPath,message:"property "+S+" not found, required by "+D.propertyPath})});else{var v=this.validateSchema(f,y,p,D);g.instance!==v.instance&&(g.instance=v.instance),v&&v.errors.length&&(g.addError({name:"dependencies",argument:D.propertyPath,message:"does not meet dependency required by "+D.propertyPath}),g.importErrors(v))}}return g}},i.enum=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.enum))throw new t("enum expects an array",d);var g=new e(f,d,p,m);return d.enum.some(r.deepCompareStrict.bind(null,f))||g.addError({name:"enum",argument:d.enum,message:"is not one of enum values: "+d.enum.map(String).join(",")}),g},i.const=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m);return r.deepCompareStrict(d.const,f)||g.addError({name:"const",argument:d.const,message:"does not exactly match expected constant: "+d.const}),g},i.not=i.disallow=function(f,d,p,m){var g=this;if(f===void 0)return null;var b=new e(f,d,p,m),y=d.not||d.disallow;return y?(Array.isArray(y)||(y=[y]),y.forEach(function(D){if(g.testType(f,d,p,m,D)){var v=D&&(D.$id||D.id),S=v||D;b.addError({name:"not",argument:S,message:"is of prohibited type "+S})}}),b):null},Io=n,Io}var Ai={},jd;function Xo(){if(jd)return Ai;jd=1;var r=ar();Ai.SchemaScanResult=e;function e(t,n){this.id=t,this.ref=n}return Ai.scan=function(n,i){function o(h,f){if(!f||typeof f!="object")return;if(f.$ref){let g=r.resolveUrl(h,f.$ref);u[g]=u[g]?u[g]+1:0;return}var d=f.$id||f.id;let p=r.resolveUrl(h,d);var m=d?p:h;if(m){if(m.indexOf("#")<0&&(m+="#"),c[m]){if(!r.deepCompareStrict(c[m],f))throw new Error("Schema <"+m+"> already exists with different definition");return c[m]}c[m]=f,m[m.length-1]=="#"&&(c[m.substring(0,m.length-1)]=f)}a(m+"/items",Array.isArray(f.items)?f.items:[f.items]),a(m+"/extends",Array.isArray(f.extends)?f.extends:[f.extends]),o(m+"/additionalItems",f.additionalItems),l(m+"/properties",f.properties),o(m+"/additionalProperties",f.additionalProperties),l(m+"/definitions",f.definitions),l(m+"/patternProperties",f.patternProperties),l(m+"/dependencies",f.dependencies),a(m+"/disallow",f.disallow),a(m+"/allOf",f.allOf),a(m+"/anyOf",f.anyOf),a(m+"/oneOf",f.oneOf),o(m+"/not",f.not)}function a(h,f){if(Array.isArray(f))for(var d=0;d<f.length;d++)o(h+"/"+d,f[d])}function l(h,f){if(!(!f||typeof f!="object"))for(var d in f)o(h+"/"+d,f[d])}var c={},u={};return o(n,i),new e(c,u)},Ai}var Oo,Bd;function gv(){if(Bd)return Oo;Bd=1;var r=mv(),e=ar(),t=Xo().scan,n=e.ValidatorResult,i=e.ValidatorResultError,o=e.SchemaError,a=e.SchemaContext,l="/",c=function f(){this.customFormats=Object.create(f.prototype.customFormats),this.schemas={},this.unresolvedRefs=[],this.types=Object.create(h),this.attributes=Object.create(r.validators)};c.prototype.customFormats={},c.prototype.schemas=null,c.prototype.types=null,c.prototype.attributes=null,c.prototype.unresolvedRefs=null,c.prototype.addSchema=function(d,p){var m=this;if(!d)return null;var g=t(p||l,d),b=p||d.$id||d.id;for(var y in g.id)this.schemas[y]=g.id[y];for(var y in g.ref)this.unresolvedRefs.push(y);return this.unresolvedRefs=this.unresolvedRefs.filter(function(D){return typeof m.schemas[D]>"u"}),this.schemas[b]},c.prototype.addSubSchemaArray=function(d,p){if(Array.isArray(p))for(var m=0;m<p.length;m++)this.addSubSchema(d,p[m])},c.prototype.addSubSchemaObject=function(d,p){if(!(!p||typeof p!="object"))for(var m in p)this.addSubSchema(d,p[m])},c.prototype.setSchemas=function(d){this.schemas=d},c.prototype.getSchema=function(d){return this.schemas[d]},c.prototype.validate=function(d,p,m,g){if(typeof p!="boolean"&&typeof p!="object"||p===null)throw new o("Expected `schema` to be an object or boolean");m||(m={});var b=p.$id||p.id;let y=e.resolveUrl(m.base,b||"");if(!g){g=new a(p,m,[],y,Object.create(this.schemas)),g.schemas[y]||(g.schemas[y]=p);var D=t(y,p);for(var v in D.id){var S=D.id[v];g.schemas[v]=S}}if(m.required&&d===void 0){var E=new n(d,p,m,g);return E.addError("is required, but is undefined"),E}var E=this.validateSchema(d,p,m,g);if(E){if(m.throwAll&&E.errors.length)throw new i(E)}else throw new Error("Result undefined");return E};function u(f){var d=typeof f=="string"?f:f.$ref;return typeof d=="string"?d:!1}c.prototype.validateSchema=function(d,p,m,g){var b=new n(d,p,m,g);if(typeof p=="boolean")p===!0?p={}:p===!1&&(p={type:[]});else if(!p)throw new Error("schema is undefined");if(p.extends)if(Array.isArray(p.extends)){var y={schema:p,ctx:g};p.extends.forEach(this.schemaTraverser.bind(this,y)),p=y.schema,y.schema=null,y.ctx=null,y=null}else p=e.deepMerge(p,this.superResolve(p.extends,g));var D=u(p);if(D){var v=this.resolve(p,D,g),S=new a(v.subschema,m,g.path,v.switchSchema,g.schemas);return this.validateSchema(d,v.subschema,m,S)}var E=m&&m.skipAttributes||[];for(var k in p)if(!r.ignoreProperties[k]&&E.indexOf(k)<0){var x=null,z=this.attributes[k];if(z)x=z.call(this,d,p,m,g);else if(m.allowUnknownAttributes===!1)throw new o("Unsupported attribute: "+k,p);x&&b.importErrors(x)}if(typeof m.rewrite=="function"){var w=m.rewrite.call(this,d,p,m,g);b.instance=w}return b},c.prototype.schemaTraverser=function(d,p){d.schema=e.deepMerge(d.schema,this.superResolve(p,d.ctx))},c.prototype.superResolve=function(d,p){var m=u(d);return m?this.resolve(d,m,p).subschema:d},c.prototype.resolve=function(d,p,m){if(p=m.resolve(p),m.schemas[p])return{subschema:m.schemas[p],switchSchema:p};let b=new URL(p,"thismessage::/").hash;var y=b&&b.length&&p.substr(0,p.length-b.length);if(!y||!m.schemas[y])throw new o("no such schema <"+p+">",d);var D=e.objectGetPath(m.schemas[y],b.substr(1));if(D===void 0)throw new o("no such schema "+b+" located in <"+y+">",d);return{subschema:D,switchSchema:p}},c.prototype.testType=function(d,p,m,g,b){if(b!==void 0){if(b===null)throw new o('Unexpected null in "type" keyword');if(typeof this.types[b]=="function")return this.types[b].call(this,d);if(b&&typeof b=="object"){var y=this.validateSchema(d,b,m,g);return y===void 0||!(y&&y.errors.length)}return!0}};var h=c.prototype.types={};return h.string=function(d){return typeof d=="string"},h.number=function(d){return typeof d=="number"&&isFinite(d)},h.integer=function(d){return typeof d=="number"&&d%1===0},h.boolean=function(d){return typeof d=="boolean"},h.array=function(d){return Array.isArray(d)},h.null=function(d){return d===null},h.date=function(d){return d instanceof Date},h.any=function(d){return!0},h.object=function(d){return d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof Date)},Oo=c,Oo}var Ld;function yv(){if(Ld)return Ze;Ld=1;var r=Ze.Validator=gv();return Ze.ValidatorResult=ar().ValidatorResult,Ze.ValidatorResultError=ar().ValidatorResultError,Ze.ValidationError=ar().ValidationError,Ze.SchemaError=ar().SchemaError,Ze.SchemaScanResult=Xo().SchemaScanResult,Ze.scan=Xo().scan,Ze.validate=function(e,t,n){var i=new r;return i.validate(e,t,n)},Ze}var bv=yv(),us=s.object({name:s.string(),description:s.string()}),ea=class{constructor(e,t,n){this.logger=e,this.signal=t,this.callId=n}status(e){this.logger.info(e)}warn(e){this.logger.warn(e)}},vv=us.extend({type:s.literal("function"),parametersSchema:gr,checkParameters:s.function(),implementation:s.function()}),Dv=us.extend({type:s.literal("rawFunction"),parametersSchema:gr,checkParameters:s.function(),implementation:s.function()}),wv=us.extend({type:s.literal("unimplementedRawFunction"),parametersJsonSchema:gr,checkParameters:s.function(),implementation:s.function()}),Sv=us.extend({type:s.literal("remoteTool"),pluginIdentifier:s.string(),parametersJsonSchema:gr,checkParameters:s.function(),implementation:s.function()});s.discriminatedUnion("type",[vv,Dv,wv,Sv]);function Cv(r,e){return e.map(t=>`${[r,...t.path].join(".")} ${t.message}`).join(`
108
+ `)}var ta=class extends Error{constructor(e){super(`Tool "${e}" is not implemented.`)}};function Ev({name:r,description:e,pluginIdentifier:t,parametersJsonSchema:n,implementation:i}){return{name:r,description:e,type:"remoteTool",pluginIdentifier:t,parametersJsonSchema:n,checkParameters:o=>{let l=new bv.Validator().validate(o,n);if(l.errors.length>0)throw new Error(j`
109
+ Failed to parse arguments for tool "${r}":
110
+ ${Cv("params",l.errors)}
111
+ `)},implementation:i}}function _v(r){return{type:"function",function:{name:r.name,description:r.description,parameters:Ci(r.parametersSchema)}}}function xv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function kv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function ll(r){let e=r.type;switch(e){case"function":return _v(r);case"rawFunction":case"unimplementedRawFunction":return xv(r);case"remoteTool":return kv(r);default:{let t=e;throw new Error(`Unhandled type: ${t}`)}}}var lr=class extends Error{constructor(e,t){super(e),this.rawContent=t}},Tt=class{constructor(){this.unhandledEndpoints=new Set,this.existingEndpointNames=new Set,this.rpcEndpoints=new Map,this.channelEndpoints=new Map,this.signalEndpoints=new Map,this.writableSignalEndpoints=new Map}withContextType(){return this}assertEndpointNameNotExists(e){if(this.existingEndpointNames.has(e))throw new Error(`Endpoint with name ${e} already exists`)}addRpcEndpoint(e,{parameter:t,returns:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.rpcEndpoints.set(e,{name:e,parameter:t,returns:n,serialization:i,handler:null}),this}addChannelEndpoint(e,{creationParameter:t,toServerPacket:n,toClientPacket:i,serialization:o="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.channelEndpoints.set(e,{name:e,creationParameter:t,toServerPacket:n,toClientPacket:i,serialization:o,handler:null}),this}addSignalEndpoint(e,{creationParameter:t,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.signalEndpoints.set(e,{name:e,creationParameter:t,signalData:n,serialization:i,handler:null}),this}addWritableSignalEndpoint(e,{creationParameter:t,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.writableSignalEndpoints.set(e,{name:e,creationParameter:t,signalData:n,serialization:i,handler:null}),this}handleRpcEndpoint(e,t){let n=this.rpcEndpoints.get(e);if(n===void 0)throw new Error(`No Rpc endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Rpc endpoint with name ${e} already has a handler`);n.handler=t,this.unhandledEndpoints.delete(e)}handleChannelEndpoint(e,t){let n=this.channelEndpoints.get(e);if(n===void 0)throw new Error(`No channel endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Channel endpoint with name ${e} already has a handler`);n.handler=t,this.unhandledEndpoints.delete(e)}handleSignalEndpoint(e,t){let n=this.signalEndpoints.get(e);if(n===void 0)throw new Error(`No signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Signal endpoint with name ${e} already has a handler`);n.handler=t,this.unhandledEndpoints.delete(e)}handleWritableSignalEndpoint(e,t){let n=this.writableSignalEndpoints.get(e);if(n===void 0)throw new Error(`No writable signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Writable signal endpoint with name ${e} already has a handler`);n.handler=t,this.unhandledEndpoints.delete(e)}assertAllEndpointsHandled(){if(this.unhandledEndpoints.size>0)throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`)}getRpcEndpoint(e){return this.rpcEndpoints.get(e)}getAllRpcEndpoints(){return[...this.rpcEndpoints.values()]}getChannelEndpoint(e){return this.channelEndpoints.get(e)}getAllChannelEndpoints(){return[...this.channelEndpoints.values()]}getSignalEndpoint(e){return this.signalEndpoints.get(e)}getAllSignalEndpoints(){return[...this.signalEndpoints.values()]}getWritableSignalEndpoint(e){return this.writableSignalEndpoints.get(e)}getAllWritableSignalEndpoints(){return[...this.writableSignalEndpoints.values()]}},xt;(function(r){r.Connected="CONNECTED",r.Errored="ERRORED",r.Closed="CLOSED"})(xt||(xt={}));var Ri=new H("Channel"),ra=class r{constructor(e){this.innerSend=e,this.nextAckId=0,this.waitingForAck=new Map,this.receivedACK=t=>{if(this.connectionStatus.get()!==xt.Connected){Ri.warn("Received ACK while in status",this.connectionStatus.get());return}let n=this.waitingForAck.get(t);if(n===void 0){Ri.warn("Received ACK for a message that is no longer waiting for ACK, ackId =",t);return}n.resolve(),this.waitingForAck.delete(t)},this.receivedMessage=t=>{if(this.connectionStatus.get()!==xt.Connected){Ri.warn("Received message while in status",this.connectionStatus.get());return}this.emitOnMessage(t)},this.errored=t=>{if(this.connectionStatus.get()!==xt.Connected){Ri.warn("Received error while in status",this.connectionStatus.get());return}this.rejectAllWaitingForAck(t),this.setConnectionStatus(xt.Errored),this.emitOnError(t)},this.closed=()=>{this.rejectAllWaitingForAck(new Error("Channel closed")),this.setConnectionStatus(xt.Closed),this.emitOnClose()},[this.onMessage,this.emitOnMessage]=ht.create(),[this.onError,this.emitOnError]=ht.create(),[this.onClose,this.emitOnClose]=ht.create(),[this.connectionStatus,this.setConnectionStatus]=xn.create(xt.Connected)}rejectAllWaitingForAck(e){let t=Array.from(this.waitingForAck.values()).map(({reject:n})=>n);this.waitingForAck.clear();for(let n of t)n(e)}static create(e){let t=new r(e);return{channel:t,receivedAck:t.receivedACK,receivedMessage:t.receivedMessage,errored:t.errored,closed:t.closed}}send(e){this.innerSend(e)}sendAndWaitForACK(e){let{promise:t,resolve:n,reject:i}=ee(),o=this.nextAckId;return this.nextAckId++,this.waitingForAck.set(o,{resolve:n,reject:i}),this.innerSend(e,o),t}},Fv=(function(){function r(){this.keyToValue=new Map,this.valueToKey=new Map}return r.prototype.set=function(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)},r.prototype.getByKey=function(e){return this.keyToValue.get(e)},r.prototype.getByValue=function(e){return this.valueToKey.get(e)},r.prototype.clear=function(){this.keyToValue.clear(),this.valueToKey.clear()},r})(),eh=(function(){function r(e){this.generateIdentifier=e,this.kv=new Fv}return r.prototype.register=function(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))},r.prototype.clear=function(){this.kv.clear()},r.prototype.getIdentifier=function(e){return this.kv.getByValue(e)},r.prototype.getValue=function(e){return this.kv.getByKey(e)},r})(),Pv=globalThis&&globalThis.__extends||(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),Tv=(function(r){Pv(e,r);function e(){var t=r.call(this,function(n){return n.name})||this;return t.classToAllowedProps=new Map,t}return e.prototype.register=function(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),r.prototype.register.call(this,t,n.identifier)):r.prototype.register.call(this,t,n)},e.prototype.getAllowedProps=function(t){return this.classToAllowedProps.get(t)},e})(eh),Av=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o};function Rv(r){if("values"in Object)return Object.values(r);var e=[];for(var t in r)r.hasOwnProperty(t)&&e.push(r[t]);return e}function Iv(r,e){var t=Rv(r);if("find"in t)return t.find(e);for(var n=t,i=0;i<n.length;i++){var o=n[i];if(e(o))return o}}function Gr(r,e){Object.entries(r).forEach(function(t){var n=Av(t,2),i=n[0],o=n[1];return e(o,i)})}function Bi(r,e){return r.indexOf(e)!==-1}function Nd(r,e){for(var t=0;t<r.length;t++){var n=r[t];if(e(n))return n}}var Ov=(function(){function r(){this.transfomers={}}return r.prototype.register=function(e){this.transfomers[e.name]=e},r.prototype.findApplicable=function(e){return Iv(this.transfomers,function(t){return t.isApplicable(e)})},r.prototype.findByName=function(e){return this.transfomers[e]},r})(),Mv=function(r){return Object.prototype.toString.call(r).slice(8,-1)},th=function(r){return typeof r>"u"},jv=function(r){return r===null},Rn=function(r){return typeof r!="object"||r===null||r===Object.prototype?!1:Object.getPrototypeOf(r)===null?!0:Object.getPrototypeOf(r)===Object.prototype},na=function(r){return Rn(r)&&Object.keys(r).length===0},At=function(r){return Array.isArray(r)},Bv=function(r){return typeof r=="string"},Lv=function(r){return typeof r=="number"&&!isNaN(r)},Nv=function(r){return typeof r=="boolean"},$v=function(r){return r instanceof RegExp},In=function(r){return r instanceof Map},On=function(r){return r instanceof Set},rh=function(r){return Mv(r)==="Symbol"},Uv=function(r){return r instanceof Date&&!isNaN(r.valueOf())},zv=function(r){return r instanceof Error},$d=function(r){return typeof r=="number"&&isNaN(r)},qv=function(r){return Nv(r)||jv(r)||th(r)||Lv(r)||Bv(r)||rh(r)},Vv=function(r){return typeof r=="bigint"},Wv=function(r){return r===1/0||r===-1/0},Zv=function(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)},Gv=function(r){return r instanceof URL},nh=function(r){return r.replace(/\./g,"\\.")},Mo=function(r){return r.map(String).map(nh).join(".")},bn=function(r){for(var e=[],t="",n=0;n<r.length;n++){var i=r.charAt(n),o=i==="\\"&&r.charAt(n+1)===".";if(o){t+=".",n++;continue}var a=i===".";if(a){e.push(t),t="";continue}t+=i}var l=t;return e.push(l),e},ia=globalThis&&globalThis.__assign||function(){return ia=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},ia.apply(this,arguments)},sa=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},oa=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r};function Ge(r,e,t,n){return{isApplicable:r,annotation:e,transform:t,untransform:n}}var ih=[Ge(th,"undefined",function(){return null},function(){}),Ge(Vv,"bigint",function(r){return r.toString()},function(r){return typeof BigInt<"u"?BigInt(r):(console.error("Please add a BigInt polyfill."),r)}),Ge(Uv,"Date",function(r){return r.toISOString()},function(r){return new Date(r)}),Ge(zv,"Error",function(r,e){var t={name:r.name,message:r.message};return e.allowedErrorProps.forEach(function(n){t[n]=r[n]}),t},function(r,e){var t=new Error(r.message);return t.name=r.name,t.stack=r.stack,e.allowedErrorProps.forEach(function(n){t[n]=r[n]}),t}),Ge($v,"regexp",function(r){return""+r},function(r){var e=r.slice(1,r.lastIndexOf("/")),t=r.slice(r.lastIndexOf("/")+1);return new RegExp(e,t)}),Ge(On,"set",function(r){return oa([],sa(r.values()))},function(r){return new Set(r)}),Ge(In,"map",function(r){return oa([],sa(r.entries()))},function(r){return new Map(r)}),Ge(function(r){return $d(r)||Wv(r)},"number",function(r){return $d(r)?"NaN":r>0?"Infinity":"-Infinity"},Number),Ge(function(r){return r===0&&1/r===-1/0},"number",function(){return"-0"},Number),Ge(Gv,"URL",function(r){return r.toString()},function(r){return new URL(r)})];function ds(r,e,t,n){return{isApplicable:r,annotation:e,transform:t,untransform:n}}var sh=ds(function(r,e){if(rh(r)){var t=!!e.symbolRegistry.getIdentifier(r);return t}return!1},function(r,e){var t=e.symbolRegistry.getIdentifier(r);return["symbol",t]},function(r){return r.description},function(r,e,t){var n=t.symbolRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),Kv=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce(function(r,e){return r[e.name]=e,r},{}),oh=ds(Zv,function(r){return["typed-array",r.constructor.name]},function(r){return oa([],sa(r))},function(r,e){var t=Kv[e[1]];if(!t)throw new Error("Trying to deserialize unknown typed array");return new t(r)});function ah(r,e){if(r?.constructor){var t=!!e.classRegistry.getIdentifier(r.constructor);return t}return!1}var lh=ds(ah,function(r,e){var t=e.classRegistry.getIdentifier(r.constructor);return["class",t]},function(r,e){var t=e.classRegistry.getAllowedProps(r.constructor);if(!t)return ia({},r);var n={};return t.forEach(function(i){n[i]=r[i]}),n},function(r,e,t){var n=t.classRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(n.prototype),r)}),ch=ds(function(r,e){return!!e.customTransformerRegistry.findApplicable(r)},function(r,e){var t=e.customTransformerRegistry.findApplicable(r);return["custom",t.name]},function(r,e){var t=e.customTransformerRegistry.findApplicable(r);return t.serialize(r)},function(r,e,t){var n=t.customTransformerRegistry.findByName(e[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(r)}),Hv=[lh,sh,ch,oh],Ud=function(r,e){var t=Nd(Hv,function(i){return i.isApplicable(r,e)});if(t)return{value:t.transform(r,e),type:t.annotation(r,e)};var n=Nd(ih,function(i){return i.isApplicable(r,e)});if(n)return{value:n.transform(r,e),type:n.annotation}},uh={};ih.forEach(function(r){uh[r.annotation]=r});var Jv=function(r,e,t){if(At(e))switch(e[0]){case"symbol":return sh.untransform(r,e,t);case"class":return lh.untransform(r,e,t);case"custom":return ch.untransform(r,e,t);case"typed-array":return oh.untransform(r,e,t);default:throw new Error("Unknown transformation: "+e)}else{var n=uh[e];if(!n)throw new Error("Unknown transformation: "+e);return n.untransform(r,t)}},Vr=function(r,e){for(var t=r.keys();e>0;)t.next(),e--;return t.next().value};function dh(r){if(Bi(r,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Bi(r,"prototype"))throw new Error("prototype is not allowed as a property");if(Bi(r,"constructor"))throw new Error("constructor is not allowed as a property")}var Yv=function(r,e){dh(e);for(var t=0;t<e.length;t++){var n=e[t];if(On(r))r=Vr(r,+n);else if(In(r)){var i=+n,o=+e[++t]==0?"key":"value",a=Vr(r,i);switch(o){case"key":r=a;break;case"value":r=r.get(a);break}}else r=r[n]}return r},aa=function(r,e,t){if(dh(e),e.length===0)return t(r);for(var n=r,i=0;i<e.length-1;i++){var o=e[i];if(At(n)){var a=+o;n=n[a]}else if(Rn(n))n=n[o];else if(On(n)){var l=+o;n=Vr(n,l)}else if(In(n)){var c=i===e.length-2;if(c)break;var l=+o,u=+e[++i]==0?"key":"value",h=Vr(n,l);switch(u){case"key":n=h;break;case"value":n=n.get(h);break}}}var f=e[e.length-1];if(At(n)?n[+f]=t(n[+f]):Rn(n)&&(n[f]=t(n[f])),On(n)){var d=Vr(n,+f),p=t(d);d!==p&&(n.delete(d),n.add(p))}if(In(n)){var l=+e[e.length-2],m=Vr(n,l),u=+f==0?"key":"value";switch(u){case"key":{var g=t(m);n.set(g,n.get(m)),g!==m&&n.delete(m);break}case"value":{n.set(m,t(n.get(m)));break}}}return r},ft=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},kt=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r};function la(r,e,t){if(t===void 0&&(t=[]),!!r){if(!At(r)){Gr(r,function(a,l){return la(a,e,kt(kt([],ft(t)),ft(bn(l))))});return}var n=ft(r,2),i=n[0],o=n[1];o&&Gr(o,function(a,l){la(a,e,kt(kt([],ft(t)),ft(bn(l))))}),e(i,t)}}function Qv(r,e,t){return la(e,function(n,i){r=aa(r,i,function(o){return Jv(o,n,t)})}),r}function Xv(r,e){function t(a,l){var c=Yv(r,bn(l));a.map(bn).forEach(function(u){r=aa(r,u,function(){return c})})}if(At(e)){var n=ft(e,2),i=n[0],o=n[1];i.forEach(function(a){r=aa(r,bn(a),function(){return r})}),o&&Gr(o,t)}else Gr(e,t);return r}var eD=function(r,e){return Rn(r)||At(r)||In(r)||On(r)||ah(r,e)};function tD(r,e,t){var n=t.get(r);n?n.push(e):t.set(r,[e])}function rD(r,e){var t={},n=void 0;return r.forEach(function(i){if(!(i.length<=1)){e||(i=i.map(function(c){return c.map(String)}).sort(function(c,u){return c.length-u.length}));var o=ft(i),a=o[0],l=o.slice(1);a.length===0?n=l.map(Mo):t[Mo(a)]=l.map(Mo)}}),n?na(t)?[n]:[n,t]:na(t)?void 0:t}var fh=function(r,e,t,n,i,o,a){var l;i===void 0&&(i=[]),o===void 0&&(o=[]),a===void 0&&(a=new Map);var c=qv(r);if(!c){tD(r,i,e);var u=a.get(r);if(u)return n?{transformedValue:null}:u}if(!eD(r,t)){var h=Ud(r,t),f=h?{transformedValue:h.value,annotations:[h.type]}:{transformedValue:r};return c||a.set(r,f),f}if(Bi(o,r))return{transformedValue:null};var d=Ud(r,t),p=(l=d?.value)!==null&&l!==void 0?l:r,m=At(p)?[]:{},g={};Gr(p,function(y,D){var v=fh(y,e,t,n,kt(kt([],ft(i)),[D]),kt(kt([],ft(o)),[r]),a);m[D]=v.transformedValue,At(v.annotations)?g[D]=v.annotations:Rn(v.annotations)&&Gr(v.annotations,function(S,E){g[nh(D)+"."+E]=S})});var b=na(g)?{transformedValue:m,annotations:d?[d.type]:void 0}:{transformedValue:m,annotations:d?[d.type,g]:g};return c||a.set(r,b),b};function hh(r){return Object.prototype.toString.call(r).slice(8,-1)}function zd(r){return hh(r)==="Array"}function nD(r){if(hh(r)!=="Object")return!1;let e=Object.getPrototypeOf(r);return!!e&&e.constructor===Object&&e===Object.prototype}function iD(r,e,t,n,i){let o={}.propertyIsEnumerable.call(n,e)?"enumerable":"nonenumerable";o==="enumerable"&&(r[e]=t),i&&o==="nonenumerable"&&Object.defineProperty(r,e,{value:t,enumerable:!1,writable:!0,configurable:!0})}function ca(r,e={}){if(zd(r))return r.map(i=>ca(i,e));if(!nD(r))return r;let t=Object.getOwnPropertyNames(r),n=Object.getOwnPropertySymbols(r);return[...t,...n].reduce((i,o)=>{if(zd(e.props)&&!e.props.includes(o))return i;let a=r[o],l=ca(a,e);return iD(i,o,l,r,e.nonenumerable),i},{})}var sr=globalThis&&globalThis.__assign||function(){return sr=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},sr.apply(this,arguments)},sD=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},oD=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r},ph=(function(){function r(e){var t=e===void 0?{}:e,n=t.dedupe,i=n===void 0?!1:n;this.classRegistry=new Tv,this.symbolRegistry=new eh(function(o){var a;return(a=o.description)!==null&&a!==void 0?a:""}),this.customTransformerRegistry=new Ov,this.allowedErrorProps=[],this.dedupe=i}return r.prototype.serialize=function(e){var t=new Map,n=fh(e,t,this,this.dedupe),i={json:n.transformedValue};n.annotations&&(i.meta=sr(sr({},i.meta),{values:n.annotations}));var o=rD(t,this.dedupe);return o&&(i.meta=sr(sr({},i.meta),{referentialEqualities:o})),i},r.prototype.deserialize=function(e){var t=e.json,n=e.meta,i=ca(t);return n?.values&&(i=Qv(i,n.values,this)),n?.referentialEqualities&&(i=Xv(i,n.referentialEqualities)),i},r.prototype.stringify=function(e){return JSON.stringify(this.serialize(e))},r.prototype.parse=function(e){return this.deserialize(JSON.parse(e))},r.prototype.registerClass=function(e,t){this.classRegistry.register(e,t)},r.prototype.registerSymbol=function(e,t){this.symbolRegistry.register(e,t)},r.prototype.registerCustom=function(e,t){this.customTransformerRegistry.register(sr({name:t},e))},r.prototype.allowErrorProps=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];(e=this.allowedErrorProps).push.apply(e,oD([],sD(t)))},r.defaultInstance=new r,r.serialize=r.defaultInstance.serialize.bind(r.defaultInstance),r.deserialize=r.defaultInstance.deserialize.bind(r.defaultInstance),r.stringify=r.defaultInstance.stringify.bind(r.defaultInstance),r.parse=r.defaultInstance.parse.bind(r.defaultInstance),r.registerClass=r.defaultInstance.registerClass.bind(r.defaultInstance),r.registerSymbol=r.defaultInstance.registerSymbol.bind(r.defaultInstance),r.registerCustom=r.defaultInstance.registerCustom.bind(r.defaultInstance),r.allowErrorProps=r.defaultInstance.allowErrorProps.bind(r.defaultInstance),r})(),aD=ph.serialize,lD=ph.deserialize;function Ur(r,e){switch(r){case"raw":return e;case"superjson":return aD(e)}}function Ii(r,e){switch(r){case"raw":return e;case"superjson":return lD(e)}}var He=s.any(),cD=s.discriminatedUnion("type",[s.object({type:s.literal("communicationWarning"),warning:s.string()}),s.object({type:s.literal("keepAlive")}),s.object({type:s.literal("channelCreate"),endpoint:s.string(),channelId:s.number().int(),creationParameter:He}),s.object({type:s.literal("channelSend"),channelId:s.number().int(),message:He,ackId:s.number().int().optional()}),s.object({type:s.literal("channelAck"),channelId:s.number().int(),ackId:s.number().int()}),s.object({type:s.literal("rpcCall"),endpoint:s.string(),callId:s.number().int(),parameter:He}),s.object({type:s.literal("signalSubscribe"),creationParameter:He,endpoint:s.string(),subscribeId:s.number().int()}),s.object({type:s.literal("signalUnsubscribe"),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalSubscribe"),creationParameter:He,endpoint:s.string(),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalUnsubscribe"),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalUpdate"),subscribeId:s.number().int(),patches:s.array(He),tags:s.array(s.string())})]),uD=s.discriminatedUnion("type",[s.object({type:s.literal("communicationWarning"),warning:s.string()}),s.object({type:s.literal("keepAliveAck")}),s.object({type:s.literal("channelSend"),channelId:s.number().int(),message:He,ackId:s.number().int().optional()}),s.object({type:s.literal("channelAck"),channelId:s.number().int(),ackId:s.number().int()}),s.object({type:s.literal("channelClose"),channelId:s.number().int()}),s.object({type:s.literal("channelError"),channelId:s.number().int(),error:_e}),s.object({type:s.literal("rpcResult"),callId:s.number().int(),result:He}),s.object({type:s.literal("rpcError"),callId:s.number().int(),error:_e}),s.object({type:s.literal("signalUpdate"),subscribeId:s.number().int(),patches:s.array(He),tags:s.array(s.string())}),s.object({type:s.literal("signalError"),subscribeId:s.number().int(),error:_e}),s.object({type:s.literal("writableSignalUpdate"),subscribeId:s.number().int(),patches:s.array(He),tags:s.array(s.string())}),s.object({type:s.literal("writableSignalError"),subscribeId:s.number().int(),error:_e})]),ua=class{constructor(){this.disposed=!1}async[Symbol.asyncDispose](){if(this.disposed)throw new Error("Cannot dispose twice");this.disposed=!0}},Hi=class extends ua{parseIncomingMessage(e){return uD.parse(e)}send(e){let t=cD.parse(e);this.sendViaTransport(t)}onHavingOneOrMoreOpenCommunication(){}onHavingNoOpenCommunication(){}},dD=s.discriminatedUnion("success",[s.object({success:s.literal(!0)}),s.object({success:s.literal(!1),error:s.string()})]),we;(function(r){r.Disconnected="DISCONNECTED",r.Connecting="CONNECTING",r.Connected="CONNECTED"})(we||(we={}));var da=class r extends Hi{constructor(e,t,n,{abortSignal:i,parentLogger:o}={}){super(),this.url=e,this.receivedMessage=t,this.errored=n,this.ws=null,this.queuedMessages=[],this.status=we.Disconnected,this.resolvedUrl=null,this.shouldRef=!1,this.resolveDisposed=null,this.abortSignal=i,this.logger=new H("WsClientTransport",o)}static createWsClientTransportFactory(e,{abortSignal:t}={}){return(n,i,o)=>new r(e,n,i,{abortSignal:t,parentLogger:o})}connect(){if(this.status!==we.Disconnected){this.logger.warn("connect() called while not disconnected");return}if(this.disposed)throw new Error(j`
112
+ Cannot establish WebSocket connection because the transport has been disposed.
113
+ `);if(this.abortSignal!==void 0&&this.abortSignal.aborted)throw new Error(this.abortSignal.reason);this.status=we.Connecting,Promise.resolve(this.url).then(e=>{this.resolvedUrl=e,this.ws=new Qe.WebSocket(e),this.ws.addEventListener("open",this.onWsOpen.bind(this)),this.ws.addEventListener("error",n=>this.onWsError(n.error)),this.ws.addEventListener("close",()=>{this.onWsError(new Error("WebSocket connection closed"))});let t=this.abortSignal;if(t!==void 0)if(t.aborted)this.onWsError(t.reason);else{let n=()=>{this.onWsError(t.reason)};t.addEventListener("abort",n,{once:!0}),this.ws.addEventListener("close",()=>{t.removeEventListener("abort",n)})}})}onWsOpen(){this.ws.addEventListener("message",this.onWsMessage.bind(this)),this.status=we.Connected,this.queuedMessages.forEach(e=>this.sendViaTransport(e)),this.queuedMessages=[],this.updateShouldRef(this.shouldRef)}onWsMessage(e){if(this.status!==we.Connected){this.logger.warn("Received message while not connected. Message ignored:",e.data);return}let t;try{t=JSON.parse(String(e.data))}catch{this.logger.warn("Received invalid JSON message from server:",e.data);return}let n;try{n=this.parseIncomingMessage(t)}catch{this.logger.warn("Received invalid message from server:",t);return}this.receivedMessage(n)}onWsError(e){if(this.status!==we.Disconnected){this.logger.warn("WebSocket error:",e),e.code==="ECONNREFUSED"&&this.logger.warnText`
114
+ WebSocket connection refused. This can happen if the server is not running or the client
115
+ is trying to connect to the wrong path. The server path that this client is
116
+ attempting to connect to is:
117
+ ${this.resolvedUrl??"Unknown"}.
118
+
119
+ Please make sure the following:
120
+
121
+ 1. LM Studio is running
122
+
123
+ 2. The API server in LM Studio has started
124
+
125
+ 3. The client is attempting to connect to the correct path
126
+ `;try{this.ws?.close()}catch{}this.status=we.Disconnected,this.errored(e)}}onWsTimeout(){if(this.status!==we.Disconnected){this.logger.warn("Websocket timed out");try{this.ws?.close()}catch{}this.status=we.Disconnected,this.errored(new Error("WebSocket timed out"))}}onHavingNoOpenCommunication(){this.updateShouldRef(!1),this.disposed&&this.resolveDisposed!==null&&(this.resolveDisposed(),this.resolveDisposed=null)}onHavingOneOrMoreOpenCommunication(){this.updateShouldRef(!0)}updateShouldRef(e){this.shouldRef=e,this.ws!==null&&this.ws._socket&&(e?this.ws._socket.ref():this.ws._socket.unref())}sendViaTransport(e){this.status===we.Connected?this.ws.send(JSON.stringify(e)):(this.queuedMessages.push(e),this.status===we.Disconnected&&this.connect())}async[Symbol.asyncDispose](){if(await super[Symbol.asyncDispose](),this.shouldRef){let{promise:e,resolve:t}=ee();this.resolveDisposed=t,await e}if(this.ws!==null){try{this.ws.close()}catch{}this.ws=null}this.errored(new Error("WebSocket client transport disposed")),this.status=we.Disconnected}},fa=class r extends da{constructor(e,t,n,i,o,{parentLogger:a,abortSignal:l}={}){super(e,i,o,{parentLogger:a,abortSignal:l}),this.clientIdentifier=t,this.clientPasskey=n,this.logger=this.logger.subclass("AuthenticatedWsClientTransport")}static createAuthenticatedWsClientTransportFactory({url:e,clientIdentifier:t,clientPasskey:n,abortSignal:i}){return(o,a,l)=>new r(e,t,n,o,a,{parentLogger:l,abortSignal:i})}onWsOpen(){this.ws.send(JSON.stringify({authVersion:1,clientIdentifier:this.clientIdentifier,clientPasskey:this.clientPasskey})),this.ws.addEventListener("message",e=>{try{let t=JSON.parse(e.data.toString("utf-8")),n=dD.parse(t);n.success?super.onWsOpen():this.onWsError(new Error("Failed to authenticate: "+n.error))}catch(t){this.onWsError(new Error("Failed to parse authentication result: "+t?.message))}},{once:!0})}};function fD(r,e,t){return Vi(r,e,t)}var Ji=class{constructor(e,t,{parentLogger:n,errorDeserializer:i,verboseErrorMessage:o}={}){this.backendInterface=e,this.openChannels=new Map,this.ongoingRpcs=new Map,this.openSignalSubscriptions=new Map,this.openWritableSignalSubscriptions=new Map,this.openCommunicationsCount=0,this.nextChannelId=0,this.nextSubscribeId=0,this.nextWritableSubscribeId=0,this.producedCommunicationWarningsCount=0,this.receivedMessage=a=>{switch(a.type){case"channelSend":{this.receivedChannelSend(a);break}case"channelAck":{this.receivedChannelAck(a);break}case"channelClose":{this.receivedChannelClose(a);break}case"channelError":{this.receivedChannelError(a);break}case"rpcResult":{this.receivedRpcResult(a);break}case"rpcError":{this.receivedRpcError(a);break}case"signalUpdate":{this.receivedSignalUpdate(a);break}case"signalError":{this.receivedSignalError(a);break}case"writableSignalUpdate":{this.receivedWritableSignalUpdate(a);break}case"writableSignalError":{this.receivedWritableSignalError(a);break}case"communicationWarning":{this.receivedCommunicationWarning(a);break}case"keepAliveAck":{this.receivedKeepAliveAck(a);break}}},this.errored=a=>{for(let l of this.openChannels.values())l.errored(a);this.openChannels.clear();for(let l of this.ongoingRpcs.values())l.reject(a);this.ongoingRpcs.clear();for(let l of this.openSignalSubscriptions.values())l.errored(a);this.openSignalSubscriptions.clear();for(let l of this.openWritableSignalSubscriptions.values())l.errored(a);this.openWritableSignalSubscriptions.clear(),this.updateOpenCommunicationsCount()},this.logger=new H("ClientPort",n),this.errorDeserializer=i??fD,this.verboseErrorMessage=o??!0,this.transport=t(this.receivedMessage,this.errored,this.logger)}communicationWarning(e){this.producedCommunicationWarningsCount>=5||(this.logger.warnText`
127
+ Produced communication warning: ${e}
128
+
129
+ This is usually caused by communication protocol incompatibility. Please make sure you are
130
+ using the up-to-date versions of the SDK and LM Studio.
131
+ `,this.transport.send({type:"communicationWarning",warning:e}),this.producedCommunicationWarningsCount++,this.producedCommunicationWarningsCount>=5&&this.logger.errorText`
132
+ 5 communication warnings have been produced. Further warnings will not be printed.
133
+ `)}updateOpenCommunicationsCount(){let e=this.openCommunicationsCount;this.openCommunicationsCount=this.openChannels.size+this.ongoingRpcs.size+this.openSignalSubscriptions.size+this.openWritableSignalSubscriptions.size,this.openCommunicationsCount===0&&e>0?this.transport.onHavingNoOpenCommunication():this.openCommunicationsCount===1&&e===0&&this.transport.onHavingOneOrMoreOpenCommunication()}receivedChannelSend(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelSend for unknown channel, channelId = ${e.channelId}`);return}let n=Ii(t.endpoint.serialization,e.message),i=t.endpoint.toClientPacket.safeParse(n);if(!i.success){this.communicationWarning(j`
134
+ Received invalid message for channel: endpointName = ${t.endpoint.name}, message =
135
+ ${n}. Zod error:
136
+
137
+ ${Ye.prettyPrintZod("message",i.error)}
138
+ `);return}t.receivedMessage(i.data)}receivedChannelAck(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelAck for unknown channel, channelId = ${e.channelId}`);return}t.receivedAck(e.ackId)}receivedChannelClose(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelClose for unknown channel, channelId = ${e.channelId}`);return}this.openChannels.delete(e.channelId),t.closed(),this.updateOpenCommunicationsCount()}receivedChannelError(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelError for unknown channel, channelId = ${e.channelId}`);return}this.openChannels.delete(e.channelId);let n=this.errorDeserializer(e.error,"Channel Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.updateOpenCommunicationsCount()}receivedRpcResult(e){let t=this.ongoingRpcs.get(e.callId);if(t===void 0){this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${e.callId}`);return}let n=Ii(t.endpoint.serialization,e.result),i=t.endpoint.returns.safeParse(n);if(!i.success){this.communicationWarning(j`
139
+ Received invalid result for rpc, endpointName = ${t.endpoint.name}, result =
140
+ ${n}. Zod error:
141
+
142
+ ${Ye.prettyPrintZod("result",i.error)}
143
+ `);return}t.resolve(i.data),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedRpcError(e){let t=this.ongoingRpcs.get(e.callId);if(t===void 0){this.communicationWarning(`Received rpcError for unknown rpc, callId = ${e.callId}`);return}let n=this.errorDeserializer(e.error,"RPC Error",this.verboseErrorMessage?t.stack:void 0);t.reject(n),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedSignalUpdate(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>Ii(t.endpoint.serialization,l)),i=t.getValue(),o;try{o=$o(i,n)}catch(l){this.communicationWarning(j`
144
+ Failed to apply patches to signal on signalUpdate. subscribeId = ${e.subscribeId}.
145
+
146
+ beforeValue = ${JSON.stringify(i,null,2)},
147
+
148
+ patches = ${JSON.stringify(n,null,2)}.
149
+
150
+ Error: ${String(l)}
151
+ `);return}let a=t.endpoint.signalData.safeParse(o);if(!a.success){this.communicationWarning(j`
152
+ Received invalid signal patch data, subscribeId = ${e.subscribeId}
153
+
154
+ patches = ${n},
155
+
156
+ beforeValue = ${i},
157
+
158
+ afterValue = ${o}.
159
+
160
+ Zod error:
161
+
162
+ ${Ye.prettyPrintZod("value",a.error)}
163
+ `);return}t.receivedPatches(o,n,e.tags)}receivedSignalError(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0){this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Signal Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.openSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedWritableSignalUpdate(e){let t=this.openWritableSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>Ii(t.endpoint.serialization,l)),i=t.getValue(),o;try{o=$o(t.getValue(),n)}catch(l){this.communicationWarning(j`
164
+ Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
165
+ ${e.subscribeId}.
166
+
167
+ beforeValue = ${JSON.stringify(i,null,2)},
168
+
169
+ patches = ${JSON.stringify(n,null,2)}.
170
+
171
+ Error: ${String(l)}
172
+ `)}let a=t.endpoint.signalData.safeParse(o);if(!a.success){this.communicationWarning(j`
173
+ Received invalid writable signal patch data, subscribeId = ${e.subscribeId}
174
+
175
+ patches = ${n},
176
+
177
+ beforeValue = ${i},
178
+
179
+ afterValue = ${o}.
180
+
181
+ Zod error:
182
+
183
+ ${Ye.prettyPrintZod("value",a.error)}
184
+ `);return}t.firstUpdateReceived=!0,t.receivedPatches(o,n,e.tags)}receivedWritableSignalError(e){let t=this.openWritableSignalSubscriptions.get(e.subscribeId);if(t===void 0){this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Writable Signal Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.openWritableSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedCommunicationWarning(e){this.logger.warnText`
185
+ Received communication warning from the server: ${e.warning}
186
+
187
+ This is usually caused by communication protocol incompatibility. Please make sure you are
188
+ using the up-to-date versions of the SDK and LM Studio.
189
+
190
+ Note: This warning was received from the server and is printed on the client for convenience.
191
+ `}receivedKeepAliveAck(e){}async callRpc(e,t,{stack:n}={}){let i=this.backendInterface.getRpcEndpoint(e);if(i===void 0)throw new Error(`No Rpc endpoint with name ${e}`);let o=i.parameter.parse(t),a=Ur(i.serialization,o),l=this.nextChannelId;this.nextChannelId++;let{promise:c,resolve:u,reject:h}=ee();return n=n??A(1),this.ongoingRpcs.set(l,{endpoint:i,stack:n,resolve:u,reject:h}),this.transport.send({type:"rpcCall",endpoint:e,callId:l,parameter:a}),this.updateOpenCommunicationsCount(),await c}createChannel(e,t,n,{stack:i}={}){let o=this.backendInterface.getChannelEndpoint(e);if(o===void 0)throw new Error(`No channel endpoint with name ${e}`);let a=o.creationParameter.parse(t),l=Ur(o.serialization,a),c=this.nextChannelId;this.nextChannelId++,this.transport.send({type:"channelCreate",endpoint:e,channelId:c,creationParameter:l}),i=i??A(1);let u={endpoint:o,stack:i,...ra.create(h=>{let f=o.toServerPacket.parse(h),d=Ur(o.serialization,f);this.transport.send({type:"channelSend",channelId:c,message:d})})};return n!==void 0&&u.channel.onMessage.subscribe(n),this.openChannels.set(c,u),this.updateOpenCommunicationsCount(),u.channel}createSignal(e,t,{stack:n}={}){let i=this.backendInterface.getSignalEndpoint(e);if(i===void 0)throw new Error(`No signal endpoint with name ${e}`);let o=i.creationParameter.parse(t),a=Ur(i.serialization,o);n=n??A(1);let l=$e.createWithoutInitialValue((c,u)=>{let h=this.nextSubscribeId;return this.nextSubscribeId++,this.transport.send({type:"signalSubscribe",endpoint:e,subscribeId:h,creationParameter:a}),this.openSignalSubscriptions.set(h,{endpoint:i,getValue:()=>l.get(),receivedPatches:c.withValueAndPatches,errored:u,stack:n}),this.updateOpenCommunicationsCount(),()=>{this.transport.send({type:"signalUnsubscribe",subscribeId:h}),this.openSignalSubscriptions.delete(h)}});return l}createWritableSignal(e,t,{stack:n}={}){let i=this.backendInterface.getWritableSignalEndpoint(e);if(i===void 0)throw new Error(`No writable signal endpoint with name ${e}`);let o=i.creationParameter.parse(t),a=Ur(i.serialization,o);n=n??A(1);let l=null,c=(f,d,p)=>l===null?(console.warn("writeUpstream called when not subscribed"),!1):this.openWritableSignalSubscriptions.get(l)?.firstUpdateReceived?(this.transport.send({type:"writableSignalUpdate",subscribeId:l,patches:d.map(g=>Ur(i.serialization,g)),tags:p}),!0):(console.warn("writeUpstream called before the first update is received"),!1),[u,h]=zo.createWithoutInitialValue((f,d)=>{let p=this.nextWritableSubscribeId;return l=p,this.nextWritableSubscribeId++,this.transport.send({type:"writableSignalSubscribe",endpoint:e,subscribeId:p,creationParameter:a}),this.openWritableSignalSubscriptions.set(p,{endpoint:i,getValue:()=>u.getPessimistic(),receivedPatches:f.withValueAndPatches,firstUpdateReceived:!1,errored:d,stack:n}),this.updateOpenCommunicationsCount(),()=>{l=null,this.transport.send({type:"writableSignalUnsubscribe",subscribeId:p}),this.openWritableSignalSubscriptions.delete(p)}},c);return[u,h]}async[Symbol.asyncDispose](){await this.transport[Symbol.asyncDispose]()}},ha=class r extends Hi{constructor(e,t,n,i,o,a){super(),this.sendMessage=n,this.receivedMessage=i,this.errored=o,this.closed=!1,this.logger=new H("GenericClientTransport",a),e.subscribe(l=>{let c;try{c=this.parseIncomingMessage(l)}catch{this.logger.warn("Received invalid message from server:",l);return}this.receivedMessage(c)}),t.subscribeOnce(()=>{this.closed||(this.closed=!0,this.errored(new Error("Server closed the connection")))})}static createFactory(e,t,n){return(i,o,a)=>new r(e,t,n,i,o,a)}sendViaTransport(e){this.sendMessage(e)}};function mh(){let r;try{r=window}catch{r=void 0}return r!==void 0&&r.lmsHostedEnv!==void 0?r.lmsHostedEnv:null}function gh(r,e){let t=r,n=e;return new Tt().addChannelEndpoint("loadModel",{creationParameter:s.object({modelKey:s.string(),identifier:s.string().optional(),ttlMs:s.number().int().min(1).optional(),loadConfigStack:Wi}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("resolved"),info:n,ambiguous:s.array(s.string()).optional()}),s.object({type:s.literal("progress"),progress:s.number()}),s.object({type:s.literal("success"),info:t})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("unloadModel",{parameter:s.object({identifier:s.string()}),returns:s.void()}).addRpcEndpoint("listLoaded",{parameter:s.undefined(),returns:s.array(t)}).addRpcEndpoint("getModelInfo",{parameter:s.object({specifier:Je,throwIfNotFound:s.boolean()}),returns:t.optional()}).addRpcEndpoint("getLoadConfig",{parameter:s.object({specifier:Je}),returns:X}).addChannelEndpoint("getOrLoad",{creationParameter:s.object({identifier:s.string(),loadTtlMs:s.number().int().min(1).optional(),loadConfigStack:Wi}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("alreadyLoaded"),info:t}),s.object({type:s.literal("startLoading"),identifier:s.string(),info:n}),s.object({type:s.literal("unloadingOtherJITModel"),info:T0}),s.object({type:s.literal("loadProgress"),progress:s.number()}),s.object({type:s.literal("loadSuccess"),info:t})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])})}function hD(){return new Tt().addChannelEndpoint("streamLogs",{creationParameter:s.void(),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("stop")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("log"),log:Lb})])})}function pD(){return gh(df,uf).addRpcEndpoint("embedString",{parameter:s.object({modelSpecifier:Je,inputString:s.string()}),returns:s.object({embedding:s.array(s.number())})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})})}function mD(){return new Tt().addRpcEndpoint("getLocalFileAbsolutePath",{parameter:s.object({fileName:s.string()}),returns:s.object({path:s.string()})}).addRpcEndpoint("uploadFileBase64",{parameter:s.object({name:s.string(),contentBase64:s.string()}),returns:s.object({identifier:s.string(),fileType:rf,sizeBytes:s.number().int()})}).addChannelEndpoint("retrieve",{creationParameter:s.object({query:s.string(),fileIdentifiers:s.array(s.string()),config:X}),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("stop")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("onFileProcessList"),indices:s.array(s.number().int())}),s.object({type:s.literal("onFileProcessingStart"),index:s.number().int()}),s.object({type:s.literal("onFileProcessingEnd"),index:s.number().int()}),s.object({type:s.literal("onFileProcessingStepStart"),index:s.number().int(),step:Ao}),s.object({type:s.literal("onFileProcessingStepProgress"),index:s.number().int(),step:Ao,progress:s.number()}),s.object({type:s.literal("onFileProcessingStepEnd"),index:s.number().int(),step:Ao}),s.object({type:s.literal("onSearchingStart")}),s.object({type:s.literal("onSearchingEnd")}),s.object({type:s.literal("result"),result:L0})])}).addChannelEndpoint("parseDocument",{creationParameter:s.object({fileIdentifier:s.string(),parseOpts:hf}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("parserLoaded"),parser:Vo}),s.object({type:s.literal("progress"),progress:s.number()}),s.object({type:s.literal("result"),content:s.string(),parser:Vo})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("getDocumentParsingLibrary",{parameter:s.object({fileIdentifier:s.string()}),returns:s.object({library:s.string(),version:s.string()})})}function gD(){return gh(Wo,Df).addChannelEndpoint("predict",{creationParameter:s.object({modelSpecifier:Je,history:ur,predictionConfigStack:Wi,fuzzyPresetIdentifier:s.string().optional(),ignoreServerSessionConfig:s.boolean().optional()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:xf,logprobs:s.array(s.array(s.object({text:s.string(),logprob:s.number()}))).optional()}),s.object({type:s.literal("promptProcessingProgress"),progress:s.number()}),s.object({type:s.literal("toolCallGenerationStart"),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),name:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnd"),toolCallRequest:Pn,rawContent:s.string().optional()}),s.object({type:s.literal("toolCallGenerationFailed"),error:_e,rawContent:s.string().optional()}),s.object({type:s.literal("success"),stats:Ff,modelInfo:Wo,loadModelConfig:X,predictionConfig:X})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("applyPromptTemplate",{parameter:s.object({specifier:Je,history:ur,predictionConfigStack:Wi,opts:bf}),returns:s.object({formatted:s.string()})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})}).addRpcEndpoint("preloadDraftModel",{parameter:s.object({specifier:Je,draftModelKey:s.string()}),returns:s.void()})}function yD(){return new Tt().addChannelEndpoint("startToolUseSession",{creationParameter:s.object({pluginIdentifier:s.string(),pluginConfigSpecifier:_d}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("sessionReady"),toolDefinitions:s.array(or)}),s.object({type:s.literal("toolCallComplete"),callId:s.number(),result:Se}),s.object({type:s.literal("toolCallError"),callId:s.number(),error:_e}),s.object({type:s.literal("toolCallStatus"),callId:s.number(),statusText:s.string()}),s.object({type:s.literal("toolCallWarn"),callId:s.number(),warnText:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("callTool"),callId:s.number(),name:s.string(),arguments:Se}),s.object({type:s.literal("abortToolCall"),callId:s.number()}),s.object({type:s.literal("discardSession")})])}).addChannelEndpoint("generateWithGenerator",{creationParameter:s.object({pluginIdentifier:s.string(),pluginConfigSpecifier:_d,tools:s.array(or),history:ur}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:xf}),s.object({type:s.literal("promptProcessingProgress"),progress:s.number()}),s.object({type:s.literal("toolCallGenerationStart"),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),name:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnd"),toolCallRequest:Pn}),s.object({type:s.literal("toolCallGenerationFailed")}),s.object({type:s.literal("success")})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addChannelEndpoint("registerDevelopmentPlugin",{creationParameter:s.object({manifest:Ka}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("ready"),clientIdentifier:s.string(),clientPasskey:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("end")})])}).addRpcEndpoint("reindexPlugins",{parameter:s.void(),returns:s.void()}).addChannelEndpoint("setPromptPreprocessor",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("preprocess"),taskId:s.string(),input:cr,config:X,pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),enabledPluginInfos:s.array(xd),pci:s.string(),token:s.string()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string(),processed:cr}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:_e})])}).addChannelEndpoint("setPredictionLoopHandler",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("handlePredictionLoop"),taskId:s.string(),config:X,pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),enabledPluginInfos:s.array(xd),pci:s.string(),token:s.string()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string()}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:_e})])}).addChannelEndpoint("setToolsProvider",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("initSession"),pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),sessionId:s.string()}),s.object({type:s.literal("discardSession"),sessionId:s.string()}),s.object({type:s.literal("callTool"),sessionId:s.string(),callId:s.string(),toolName:s.string(),parameters:Se}),s.object({type:s.literal("abortToolCall"),sessionId:s.string(),callId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("sessionInitialized"),sessionId:s.string(),toolDefinitions:s.array(or)}),s.object({type:s.literal("sessionInitializationFailed"),sessionId:s.string(),error:_e}),s.object({type:s.literal("toolCallComplete"),sessionId:s.string(),callId:s.string(),result:Se}),s.object({type:s.literal("toolCallError"),sessionId:s.string(),callId:s.string(),error:_e}),s.object({type:s.literal("toolCallStatus"),sessionId:s.string(),callId:s.string(),statusText:s.string()}),s.object({type:s.literal("toolCallWarn"),sessionId:s.string(),callId:s.string(),warnText:s.string()})])}).addChannelEndpoint("setGenerator",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("generate"),taskId:s.string(),input:ur,pluginConfig:X,globalPluginConfig:X,toolDefinitions:s.array(or),workingDirectoryPath:s.string().nullable()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string()}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:_e}),s.object({type:s.literal("fragmentGenerated"),taskId:s.string(),content:s.string(),opts:kf}),s.object({type:s.literal("toolCallGenerationStarted"),taskId:s.string(),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),taskId:s.string(),toolName:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),taskId:s.string(),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnded"),taskId:s.string(),toolCallRequest:Pn}),s.object({type:s.literal("toolCallGenerationFailed"),taskId:s.string(),error:_e})])}).addRpcEndpoint("processingHandleUpdate",{parameter:s.object({pci:s.string(),token:s.string(),update:w0}),returns:s.void()}).addRpcEndpoint("processingHandleRequest",{parameter:s.object({pci:s.string(),token:s.string(),request:E0}),returns:s.object({response:k0})}).addRpcEndpoint("processingPullHistory",{parameter:s.object({pci:s.string(),token:s.string(),includeCurrent:s.boolean()}),returns:ur}).addRpcEndpoint("processingGetOrLoadTokenSource",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.object({tokenSourceIdentifier:F0})}).addRpcEndpoint("processingHasStatus",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.boolean()}).addRpcEndpoint("processingNeedsNaming",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.boolean()}).addRpcEndpoint("processingSuggestName",{parameter:s.object({pci:s.string(),token:s.string(),name:s.string()}),returns:s.void()}).addRpcEndpoint("processingSetSenderName",{parameter:s.object({pci:s.string(),token:s.string(),name:s.string()}),returns:s.void()}).addRpcEndpoint("setConfigSchematics",{parameter:s.object({schematics:Td}),returns:s.void()}).addRpcEndpoint("setGlobalConfigSchematics",{parameter:s.object({schematics:Td}),returns:s.void()}).addRpcEndpoint("pluginInitCompleted",{parameter:s.void(),returns:s.void()})}function bD(){return new Tt().addRpcEndpoint("searchModels",{parameter:s.object({opts:Vf}),returns:s.object({results:s.array(j0)})}).addRpcEndpoint("getModelDownloadOptions",{parameter:s.object({modelSearchResultIdentifier:qf}),returns:s.object({results:s.array(M0)})}).addChannelEndpoint("downloadModel",{creationParameter:s.object({downloadIdentifier:s.string()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("downloadProgress"),update:To}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success"),defaultIdentifier:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addChannelEndpoint("downloadArtifact",{creationParameter:s.object({artifactOwner:kn,artifactName:Fn,revisionNumber:s.number().int().nullable(),path:s.string()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("downloadProgress"),update:To}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success")})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("installPluginDependencies",{parameter:s.object({pluginFolder:s.string()}),returns:s.void()}).addRpcEndpoint("getLocalArtifactFiles",{parameter:s.object({path:s.string()}),returns:s.object({fileList:I0})}).addChannelEndpoint("pushArtifact",{creationParameter:s.object({path:s.string(),description:s.string().max(1e3).optional(),makePrivate:s.boolean().optional(),writeRevision:s.boolean().optional(),overrides:Se.optional()}),toServerPacket:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("message"),message:s.string()})])}).addChannelEndpoint("ensureAuthenticated",{creationParameter:s.void(),toServerPacket:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("authenticationUrl"),url:s.string()}),s.object({type:s.literal("authenticated")})])}).addRpcEndpoint("loginWithPreAuthenticatedKeys",{parameter:s.object({keyId:s.string(),publicKey:s.string(),privateKey:s.string()}),returns:s.object({userName:s.string()})}).addChannelEndpoint("createArtifactDownloadPlan",{creationParameter:s.object({owner:kn,name:Fn}),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")}),s.object({type:s.literal("commit")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("planUpdated"),plan:Pd}),s.object({type:s.literal("planReady"),plan:Pd}),s.object({type:s.literal("downloadProgress"),update:To}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success")})])})}function vD(){return new Tt().addRpcEndpoint("listDownloadedModels",{parameter:s.void(),returns:s.array(P0)}).addChannelEndpoint("alive",{creationParameter:s.void(),toServerPacket:s.void(),toClientPacket:s.void()}).addRpcEndpoint("notify",{parameter:tf,returns:s.void()}).addRpcEndpoint("version",{parameter:s.void(),returns:s.object({version:s.string(),build:s.number()})}).addRpcEndpoint("setExperimentFlag",{parameter:s.object({code:s.string(),value:s.boolean()}),returns:s.void()}).addRpcEndpoint("getExperimentFlags",{parameter:s.void(),returns:s.array(s.string())}).addRpcEndpoint("startHttpServer",{parameter:s.object({port:s.number().int().min(1).max(65535).optional(),cors:s.boolean().optional()}),returns:s.void()}).addRpcEndpoint("stopHttpServer",{parameter:s.void(),returns:s.void()})}function DD(r,e,t,n){let[i,o]=ht.create(),[a,l]=ht.create(),c=e.getApiIpcTunnel(r,{authVersion:1,clientIdentifier:t,clientPasskey:n},o,l);return ha.createFactory(i,a,c)}function wD(r,e,t,n){return fa.createAuthenticatedWsClientTransportFactory({url:Promise.resolve(e).then(i=>`${i}/${r}`),clientIdentifier:t,clientPasskey:n})}function SD(r,e,t,n,i,o,{errorDeserializer:a,verboseErrorMessage:l}={}){let c=mh();return c!==null?(e!==void 0&&o.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error."),new Ji(r,DD(t,c,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})):new Ji(r,wD(t,e,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})}var pa=class{constructor(e,t,n){this.diagnosticsPort=e,this.validator=t,this.logger=new H("Diagnostics",n)}unstable_streamLogs(e){let t=A(1);this.validator.validateMethodParamOrThrow("client.diagnostics","unstable_streamLogs","listener",s.function(),e,t);let n=this.diagnosticsPort.createChannel("streamLogs",void 0,void 0,{stack:t}),i=n.onMessage.subscribe(o=>{o.type==="log"&&e(o.log)});return()=>{i(),n.send({type:"stop"})}}};function CD(r){return s.object({identifier:s.string().optional(),config:r.optional(),signal:s.instanceof(AbortSignal).optional(),ttl:s.number().optional(),verbose:s.union([s.boolean(),X0]).optional(),onProgress:s.function().optional()})}var Yi=class{getLoadModelOptsSchema(){return this.loadModelOptsSchema===null&&(this.loadModelOptsSchema=CD(this.loadModelConfigSchema)),this.loadModelOptsSchema}constructor(e,t,n,i){this.client=e,this.port=t,this.logger=n,this.validator=i,this.loadModelOptsSchema=null}async load(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"load",["modelKey","opts"],[qr,this.getLoadModelOptsSchema()],[e,t],n);let{identifier:i,signal:o,verbose:a="info",config:l,onProgress:c}=t,u=0,{promise:h,resolve:f,reject:d}=ee(),p=typeof a=="boolean"?"info":a,m=Date.now();a&&this.logger.logAtLevel(p,j`
192
+ Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
193
+ client.llm.load.
194
+ `);let g=e,b=this.port.createChannel("loadModel",{modelKey:e,identifier:i,ttlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:Id("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},y=>{switch(y.type){case"resolved":{g=y.info.modelKey,y.ambiguous!==void 0&&this.logger.warn(j`
195
+ Multiple models found for key ${e}:
196
+
197
+ ${y.ambiguous.map(D=>` - ${D}`).join(`
198
+ `)}
199
+
200
+ Using the first one.
201
+ `),a&&this.logger.logAtLevel(p,j`
202
+ Start loading model ${g}...
203
+ `);break}case"success":{a&&this.logger.logAtLevel(p,j`
204
+ Successfully loaded model ${g} in ${Date.now()-m}ms
205
+ `),f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger));break}case"progress":{let{progress:D}=y;if(c!==void 0)B(this.logger,"onProgress",c,[D]);else if(a){let v=Date.now();if(v-u>500||D===1){let S=(D*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${S}%`),u=v}}}}},{stack:n});return b.onError.subscribeOnce(d),o!==void 0&&(o.aborted?(b.send({type:"cancel"}),d(o.reason)):o.addEventListener("abort",()=>{b.send({type:"cancel"}),d(o.reason)},{once:!0})),await h}unload(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"unload","identifier",qr,e,t),this.port.callRpc("unloadModel",{identifier:e},{stack:t})}async listLoaded(){let e=A(1);return(await this.port.callRpc("listLoaded",void 0,{stack:e})).map(n=>this.createDomainSpecificModel(this.port,n,this.validator,this.logger))}async getAny(e){let t=await this.port.callRpc("getModelInfo",{specifier:{type:"query",query:{}},throwIfNotFound:!0},{stack:e});if(t===void 0)throw new Error("Backend should have thrown.");return this.createDomainSpecificModel(this.port,t,this.validator,new H("LLM",this.logger))}createDynamicHandle(e){let t=A(1);this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandle","param",s.union([qr,Ja]),e,t);let n;if(typeof e=="string"?n={identifier:e}:n=e,n.path?.includes("\\"))throw pe(j`
206
+ Model path should not contain backslashes, even if you are on Windows. Use forward
207
+ slashes instead.
208
+ `,t);return this.createDomainDynamicHandle(this.port,{type:"query",query:n},this.validator,new H("DynamicHandle",this.logger))}createDynamicHandleFromInstanceReference(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandleFromInstanceReference","instanceReference",s.string(),e,t),this.createDomainDynamicHandle(this.port,{type:"instanceReference",instanceReference:e},this.validator,new H("DynamicHandle",this.logger))}async model(e,t={}){let n=A(1);if(e===void 0)return await this.getAny(n);[e,t]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"model",["modelKey","opts"],[qr,this.getLoadModelOptsSchema()],[e,t],n);let{identifier:i,signal:o,verbose:a="info",config:l,onProgress:c}=t;if(i!==void 0)throw new Error("The identifier option is not allowed when using `.model`.");let u=0,{promise:h,resolve:f,reject:d}=ee(),p=typeof a=="boolean"?"info":a,m=Date.now(),g=this.port.createChannel("getOrLoad",{identifier:e,loadTtlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:Id("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},b=>{switch(b.type){case"alreadyLoaded":return f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger));case"unloadingOtherJITModel":{a&&this.logger.logAtLevel(p,j`
209
+ Unloading other JIT model ${b.info.modelKey}. (You can disable this behavior
210
+ by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
211
+ `);break}case"startLoading":{a&&(this.logger.logAtLevel(p,j`
212
+ Verbose logging is enabled. To hide progress logs, set the "verbose" option to
213
+ false in .model().
214
+ `),this.logger.logAtLevel(p,j`
215
+ Model ${e} is not loaded. Start loading...
216
+ `));break}case"loadProgress":{let{progress:y}=b;if(c!==void 0)B(this.logger,"onProgress",c,[y]);else if(a){let D=Date.now();if(D-u>500||y===1){let v=(y*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${v}%`),u=D}}break}case"loadSuccess":a&&this.logger.logAtLevel(p,j`
217
+ Successfully loaded model ${b.info.modelKey} in ${Date.now()-m}ms
218
+ `),f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger))}},{stack:n});return g.onError.subscribeOnce(d),o?.addEventListener("abort",()=>{g.send({type:"cancel"}),d(o.reason)}),await h}};function vn(r,e,t){if(r!==void 0)return r===e?{checked:!1,value:t}:{checked:!0,value:r}}var Qi=class{constructor(e,t){this.port=e,this.specifier=t}async getModelInfo(){let e=await this.port.callRpc("getModelInfo",{specifier:this.specifier,throwIfNotFound:!1},{stack:A(1)});if(e!==void 0)return e}async getLoadConfig(e){return await this.port.callRpc("getLoadConfig",{specifier:this.specifier},{stack:e})}},Mn=class extends Qi{constructor(e,t,n,i=new H("EmbeddingModel")){super(e,t),this.validator=n,this.logger=i}async embed(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("client.embedding","embed","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?await Promise.all(e.map(n=>this.port.callRpc("embedString",{inputString:n,modelSpecifier:this.specifier},{stack:t}))):await this.port.callRpc("embedString",{inputString:e,modelSpecifier:this.specifier},{stack:t})}async getContextLength(){let e=A(1),t=await this.getLoadConfig(e);return Xf.access(t,"contextLength")}async getEvalBatchSize(){let e=A(1),t=await this.getLoadConfig(e);return Pt.access(t,"embedding.load.llama.evalBatchSize")}async tokenize(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:t})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:t})).tokens}async countTokens(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",s.string(),e,t),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:t})).tokenCount}},ma=class extends Mn{constructor(e,t,n,i=new H("EmbeddingModel")){let o={type:"instanceReference",instanceReference:t.instanceReference};super(e,o,n,i),this.identifier=t.identifier,this.path=t.path,this.modelKey=t.modelKey,this.format=t.format,this.displayName=t.displayName,this.sizeBytes=t.sizeBytes}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let t=A(1);throw pe("This model has already been unloaded",t)}return e}},ga=class extends Yi{constructor(){super(...arguments),this.namespace="embedding",this.defaultLoadConfig={},this.loadModelConfigSchema=Wb}loadConfigToKVConfig(e){return hv.buildPartialConfig({"llama.acceleration.offloadRatio":e.gpu?.ratio,"load.gpuSplitConfig":pf(e.gpu),contextLength:e.contextLength,"llama.ropeFrequencyBase":vn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":vn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,"llama.tryMmap":e.tryMmap})}createDomainSpecificModel(e,t,n,i){return new ma(e,t,n,i)}createDomainDynamicHandle(e,t,n,i){return new Mn(e,t,n,i)}},ED=hf.extend({onProgress:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),_D=s.object({onFileProcessList:s.function().optional(),onFileProcessingStart:s.function().optional(),onFileProcessingEnd:s.function().optional(),onFileProcessingStepStart:s.function().optional(),onFileProcessingStepProgress:s.function().optional(),onFileProcessingStepEnd:s.function().optional(),onSearchingStart:s.function().optional(),onSearchingEnd:s.function().optional(),verbose:s.union([s.boolean(),s.string()]).optional()}),xD=s.object({chunkingMethod:Wf.optional(),limit:s.number().int().optional(),embeddingModel:s.instanceof(Mn).optional(),databasePath:s.string().optional(),signal:s.instanceof(AbortSignal).optional(),..._D.shape});function kD(r){switch(r){case"loading":return"Loading";case"chunking":return"Chunking";case"embedding":return"Embedding";default:{let e=r;throw new Error(`Unexpected processing step: ${e}`)}}}var ya=class{constructor(e,t,n){this.filesPort=e,this.validator=t,this.logger=new H("File",n)}async getLocalFileAbsolutePath(e,t){return await this.filesPort.callRpc("getLocalFileAbsolutePath",{fileName:e},{stack:t})}createFileHandleFromChatMessagePartFileData(e){return new he(this,e.identifier,e.fileType,e.sizeBytes,e.name)}async prepareImage(e){let t=await(0,Qe.readFileAsBase64)(e);if(t.success===!1)throw new Error(j`
219
+ Your current JavaScript environment does not support reading files. If you can read the file
220
+ using other methods, please use "prepareImageBase64".
221
+ `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new he(this,i,o,a,n)}async prepareImageBase64(e,t){let{identifier:n,fileType:i,sizeBytes:o}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:t});return new he(this,n,i,o,e)}async prepareFile(e){let t=await(0,Qe.readFileAsBase64)(e);if(t.success===!1)throw new Error(j`
222
+ Your current JavaScript environment does not support reading files. If you can read the file
223
+ using other methods, please use "prepareFileBase64".
224
+ `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new he(this,i,o,a,n)}async prepareFileBase64(e,t){let{identifier:n,fileType:i,sizeBytes:o}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:t});return new he(this,n,i,o,e)}async retrieve(e,t,n={}){let i=this.logger,o=A(1);this.validator.validateMethodParamsOrThrow("client.retrieval","retrieve",["query","filePaths","opts"],[s.string(),s.array(s.instanceof(he)),xD],[e,t,n],o);let{verbose:a="info"}=n,l=typeof a=="boolean"?"info":a,c=a&&n.onFileProcessList===void 0&&n.onFileProcessingStart===void 0&&n.onFileProcessingEnd===void 0&&n.onFileProcessingStepStart===void 0&&n.onFileProcessingStepProgress===void 0&&n.onFileProcessingStepEnd===void 0&&n.onSearchingStart===void 0&&n.onSearchingEnd===void 0;if(n.embeddingModel===void 0)throw new Error("Embedding model currently is required.");let u=y=>{let D=t[y];if(D===void 0)throw new Error(`File not found: ${y}`);return D},h=y=>y.map(u),f=fv.buildPartialConfig({chunkingMethod:n.chunkingMethod,databaseFile:n.databasePath,embeddingModel:(await n.embeddingModel.getModelInfo())?.identifier,limit:n.limit}),d,p=[],m=0,g=0,b="";return await new Promise((y,D)=>{let v=this.filesPort.createChannel("retrieve",{query:e,fileIdentifiers:t.map(S=>S.identifier),config:f},S=>{switch(S.type){case"onFileProcessList":d=h(S.indices),B(i,"onFileProcessList",n.onFileProcessList,[d]),c&&i.logAtLevel(l,j`
225
+ Found ${d.length} files need processing:
226
+ ${d.map(E=>E.name).join(", ")}
227
+ `);break;case"onFileProcessingStart":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingStart");let E=u(S.index);B(i,"onFileProcessingStart",n.onFileProcessingStart,[E,d.indexOf(E),d]),c&&(p[S.index]=Date.now(),i.logAtLevel(l,j`
228
+ Start processing file: ${E.name}
229
+ (${S.index+1}/${d.length})
230
+ `));break}case"onFileProcessingEnd":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingEnd");let E=u(S.index);B(i,"onFileProcessingEnd",n.onFileProcessingEnd,[E,d.indexOf(E),d]),c&&i.logAtLevel(l,j`
231
+ File processed: ${E.name}.
232
+ Time took: ${Date.now()-p[S.index]}ms
233
+ `);break}case"onFileProcessingStepStart":B(i,"onFileProcessingStepStart",n.onFileProcessingStepStart,[u(S.index),S.step]);break;case"onFileProcessingStepProgress":{B(i,"onFileProcessingStepProgress",n.onFileProcessingStepProgress,[u(S.index),S.step,S.progress]);let E=Date.now();if(c&&(E-g>500||S.progress===1)){g=E;let k=j`
234
+ > ${kD(S.step)}: ${Math.round(S.progress*100)}%
235
+ `;b!==k&&(b=k,i.logAtLevel(l,k))}break}case"onFileProcessingStepEnd":B(i,"onFileProcessingStepEnd",n.onFileProcessingStepEnd,[u(S.index),S.step]);break;case"onSearchingStart":B(i,"onSearchingStart",n.onSearchingStart,[]),c&&(m=Date.now(),i.logAtLevel(l,"Start searching in the vector database..."));break;case"onSearchingEnd":B(i,"onSearchingEnd",n.onSearchingEnd,[]),c&&i.logAtLevel(l,j`
236
+ Finished searching in the vector database.
237
+ Time took: ${Date.now()-m}ms
238
+ `);break;case"result":{y({entries:S.result.entries.map(E=>({content:E.content,score:E.score,source:t[E.sourceIndex]}))});break}}});n.signal!==void 0&&(n.signal.aborted?(D(n.signal.reason),v.send({type:"stop"})):n.signal?.addEventListener("abort",()=>{D(n.signal.reason),v.send({type:"stop"})})),v.onError.subscribeOnce(D)})}async parseDocument(e,t={}){let n=A(1);this.validator.validateMethodParamsOrThrow("client.files","parseDocument",["fileHandle","opts"],[s.instanceof(he),ED],[e,t],n);let{onParserLoaded:i,onProgress:o,signal:a,...l}=t,{promise:c,resolve:u,reject:h}=ee();t.signal?.throwIfAborted();let f=!1,d=this.filesPort.createChannel("parseDocument",{fileIdentifier:e.identifier,parseOpts:l},p=>{switch(p.type){case"progress":{B(this.logger,"onProgress",o,[p.progress]);break}case"parserLoaded":{B(this.logger,"onParserLoaded",i,[p.parser]);break}case"result":{u({content:p.content,parser:p.parser}),f=!0;break}}},{stack:n});return a?.addEventListener("abort",()=>{f||(h(a.reason),d.send({type:"cancel"}))}),d.onError.subscribeOnce(h),d.onClose.subscribeOnce(()=>{f||h(new Error("Channel closed before receiving a result."))}),await c}async getDocumentParsingLibrary(e){let t=A(1);return await this.filesPort.callRpc("getDocumentParsingLibrary",{fileIdentifier:e.identifier},{stack:t})}};function qd(r,e){let t=I.default.redBright(` ${r.title} `);return r.suggestion!==void 0&&(t+=`
239
+
240
+
241
+ `+I.default.bgWhite.black(" (!) SUGGESTION ")+`
242
+
243
+ `+I.default.white(r.suggestion)),r.cause!==void 0&&(t+=`
244
+
245
+
246
+ `+I.default.bgWhite.black(" (X) CAUSE ")+`
247
+
248
+ `+I.default.gray(r.cause)),pe(t,e)}var yh=new Map;function Jr(r,e){yh.set(r,e)}function FD(r,e){if(r.length===0)return I.default.gray(" You don't have any LLMs downloaded.");let t=r.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
249
+ `);return r.length<e&&(t+=I.default.gray(`
250
+ ... (and ${e-r.length} more)`)),t}Jr("generic.pathNotFound",({availablePathsSample:r,path:e,totalModels:t},n)=>mr(`Cannot find a model with path "${I.default.yellowBright(e)}"`,j`
251
+ Here are your available models:
252
+
253
+ ${FD(r,t)}
254
+
255
+ Run
256
+
257
+ ${I.default.yellowBright("lms ls")}
258
+
259
+ to see a full list of loadable models
260
+ `,n));function bh(r,e){if(r.length===0)return I.default.gray(" You don't have any models loaded.");let t=r.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
261
+ `);return r.length<e&&(t+=I.default.gray(`
262
+ ... (and ${e-r.length} more)`)),t}Jr("generic.identifierNotFound",({loadedModelsSample:r,identifier:e,totalLoadedModels:t},n)=>mr(`Cannot find a model with identifier "${I.default.yellowBright(e)}"`,j`
263
+ Here are your loaded models:
264
+
265
+ ${bh(r,t)}
266
+
267
+ Run
268
+
269
+ ${I.default.yellowBright("lms ps")}
270
+
271
+ to see a full list of loaded models
272
+ `,n));Jr("generic.specificModelUnloaded",(r,e)=>pe(I.default.bgRed.white(j`
273
+ This model has already been unloaded.
274
+ `),e));function ba(r){switch(r){case"llm":return"an LLM";case"embedding":return"an embedding model";case"imageGen":return"an image generation model";case"transcription":return"a transcription model";case"tts":return"a text-to-speech model";default:return console.error(`Unexpected domain type: ${r}`),"Unknown Model Domain"}}function PD(r){let e=[];return r.domain!==void 0&&e.push(j`
275
+ The model must be ${I.default.yellowBright(ba(r.domain))}
276
+ `),r.identifier!==void 0&&e.push(`The identifier must be exactly "${I.default.yellowBright(r.identifier)}"`),r.path!==void 0&&e.push(`The path must match "${I.default.yellowBright(r.path)}"`),e.length===0?I.default.gray(" \u2022 Any Model"):e.map(t=>I.default.white(" \u2022 "+t)).join(`
277
+ `)}Jr("generic.noModelMatchingQuery",({loadedModelsSample:r,totalLoadedModels:e,query:t},n)=>pe(j`
278
+ ${I.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
279
+
280
+ Loaded Models:
281
+
282
+ ${bh(r,e)}
283
+
284
+ Your query:
285
+
286
+ ${PD(t)}
287
+
288
+ Run
289
+
290
+ ${I.default.yellowBright("lms ps")}
291
+
292
+ to see a full list of loaded models with details
293
+ `,n));Jr("generic.domainMismatch",({actualDomain:r,expectedDomain:e,path:t},n)=>pe(j`
294
+ ${I.default.bgRed.white(" Model has wrong domain. ")}
295
+
296
+ Expecting ${I.default.greenBright(t)} to be ${I.default.yellowBright(ba(e))}, but it is actually ${I.default.yellowBright(ba(r))}.
297
+ `,n));function TD(r,e){if(r.length===0)return I.default.gray(" You don't have any presets available.");let t=r.map(({identifier:n,name:i})=>I.default.cyanBright(` \u2022 ${i} (${I.default.cyan(n)})`)).join(`
298
+ `);return r.length<e&&(t+=I.default.gray(`
299
+ ... (and ${e-r.length} more)`)),t}Jr("generic.presetNotFound",({specifiedFuzzyPresetIdentifier:r,availablePresetsSample:e,totalAvailablePresets:t})=>mr(`Cannot find a preset with identifier "${I.default.yellowBright(r)}"`,j`
300
+ Here are your available presets:
301
+
302
+ ${TD(e,t)}
303
+
304
+ Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
305
+ can get a preset's identifier by right-clicking on it and then select "Copy Preset
306
+ Identifier".
307
+ `));function AD(r,e,t){if(r.displayData===void 0)return qd(r,t);let n,i=yh.get(r.displayData.code);return i!==void 0?(n=i(r.displayData,t),ff(n,r),n):qd(r,t)}function Vd({value:r,falseDefault:e}){return r===void 0?void 0:r===!1?{checked:!1,value:e}:{checked:!0,value:r}}var va=class{constructor(e,t){this.rounds=e,this.totalExecutionTimeSeconds=t}},RD=new zi(Math.floor(Math.random()*(Number.MAX_SAFE_INTEGER/2/1e4))*1e4),Da=class{needsQueueing(){return!1}async runInQueue(e,t){if(t?.aborted)throw new Error("Operation aborted");return e()}},wa=class{constructor(){this.queue=[],this.executing=!1,this.poisoned=!1,this.poisonError=null}needsQueueing(){return this.executing||this.queue.length>0}async runInQueue(e,t){if(t?.aborted)throw new Error("Operation aborted");if(this.poisoned)throw this.poisonError??new Error("Queue has been poisoned by a previous error");if(!this.needsQueueing()){this.executing=!0;try{if(t?.aborted)throw new Error("Operation aborted");return await e()}catch(n){throw this.poisoned=!0,this.poisonError=n,this.clearQueue(n),n}finally{this.executing=!1,this.processQueue()}}return new Promise((n,i)=>{if(t){if(t.aborted)return i(new Error("Operation aborted"));t.addEventListener("abort",()=>{let o=this.queue.findIndex(a=>a.resolve===n&&a.reject===i);o!==-1&&(this.queue.splice(o,1),i(new Error("Operation aborted")))},{once:!0})}this.queue.push({fn:async()=>{try{if(t?.aborted)throw new Error("Operation aborted");let o=await e();return n(o),o}catch(o){throw i(o),o}},resolve:n,reject:i,signal:t})})}async processQueue(){if(this.executing||this.queue.length===0||this.poisoned)return;let e=this.queue.shift();if(e){if(e.signal?.aborted){e.reject(new Error("Operation aborted")),this.processQueue();return}this.executing=!0;try{await e.fn()}catch(t){this.poisoned=!0,this.poisonError=t,this.clearQueue(t)}finally{this.executing=!1,this.poisoned||this.processQueue()}}}clearQueue(e){for(let t of this.queue)t.reject(e);this.queue=[]}},Sa=class{constructor(e,t,n){this.toolCallRequest=e,this.tool=t,this.resultContainer=n,this.allow=()=>{this.assertNoResultYet("allow",A(1)),this.resultContainer[0]={type:"allow"}},this.allowAndOverrideParameters=i=>{this.assertNoResultYet("allowAndOverrideParameters",A(1)),this.resultContainer[0]={type:"allowAndOverrideParameters",parameters:i}},this.deny=i=>{this.assertNoResultYet("deny",A(1)),this.resultContainer[0]={type:"deny",reason:i}}}assertNoResultYet(e,t){if(this.resultContainer[0]!==null)throw mr(`Cannot call ${e} after a result has been set`,j`
308
+ This tool call guard has already set a result previously (${this.resultContainer[0].type}).
309
+ You cannot set a result more than once.
310
+ `,t)}},vh=s.object({onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onMessage:s.function().optional(),onRoundStart:s.function().optional(),onRoundEnd:s.function().optional(),onPredictionCompleted:s.function().optional(),onPromptProcessingProgress:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFinalized:s.function().optional(),onToolCallRequestFailure:s.function().optional(),onToolCallRequestDequeued:s.function().optional(),guardToolCall:s.function().optional(),handleInvalidToolRequest:s.function().optional(),maxPredictionRounds:s.number().int().min(1).optional(),signal:s.instanceof(AbortSignal).optional(),allowParallelToolExecution:s.boolean().optional()}),ID=(r,e)=>{if(e)return r.message;throw r};async function Dh(r,e,t,n,i,o,a,l){let c=new AbortController,u=pt.from(r),h=-1,f=!1;t.signal!==void 0&&(t.signal.aborted?c.abort(t.signal.reason):t.signal.addEventListener("abort",()=>{c.abort(t.signal?.reason)},{once:!0}));let d=!1,p=0,m=new Map;for(let g of e)m.has(g.name)&&i.warnText`
311
+ Duplicate tool (${g.name}) found in the tools array. The last tool with the same name
312
+ will be used.
313
+ `,m.set(g.name,g);do{let g=!0;t.maxPredictionRounds!==void 0&&p+1>=t.maxPredictionRounds&&(g=!1);let b=!1,y=!1,D=[],v=[],S=[],E=[],k=0,x=[],z=[],{promise:w,resolve:C,reject:P}=ee(),{promise:U,resolve:Z,reject:q}=ee(),Ce=async(N,ne,de)=>{let mt;try{mt=await(t.handleInvalidToolRequest??ID)(N,ne)}catch(gt){throw c.signal.aborted?c.signal.reason:(c.abort(),gt)}if(mt===void 0)return;let It;try{It=JSON.stringify(mt)}catch{throw c.abort(),pe("handleInvalidToolRequest returned a value that cannot be converted to JSON.",n)}ne===void 0?i.warnText`
314
+ The "handleInvalidToolRequest" callback has returned a result, but the tool request has
315
+ completely failed to parse, thus LM Studio cannot provide the result to the tool call.
316
+ Please avoid returning a result when the second parameter of the callback is undefined.
317
+ See the documentation for "handleInvalidToolRequest" for more information.
318
+ `:(x.push({index:de,data:{type:"toolCallResult",toolCallId:ne.id,content:It}}),k++)};c.signal.throwIfAborted(),B(i,"onRoundStart",t.onRoundStart,[p]);let ge=!1,ye=new AbortController,Q=t.allowParallelToolExecution?new Da:new wa,ke=!1,Yr=!1;a({allowTools:g,history:u._internalGetData(),signal:ye.signal,handleFragment:N=>{y||(y=!0,B(i,"onFirstToken",t.onFirstToken,[p])),B(i,"onFragment",t.onPredictionFragment,[{roundIndex:p,...N}]),D.push(N.content),N.isStructural||(N.reasoningType==="reasoning"?v.push(N.content):S.push(N.content))},handlePromptProcessingProgress:N=>{B(i,"onPromptProcessingProgress",t.onPromptProcessingProgress,[p,N])},handleToolCallGenerationStart:N=>{h=RD.next(),ke=!1,Yr=!1,ge=!0,B(i,"onToolCallRequestStart",t.onToolCallRequestStart,[p,h,{toolCallId:N}])},handleToolCallGenerationNameReceived:N=>{ke=!0,B(i,"onToolCallRequestNameReceived",t.onToolCallRequestNameReceived,[p,h,N])},handleToolCallGenerationArgumentFragmentGenerated:N=>{Yr=!0,B(i,"onToolCallRequestArgumentFragmentGenerated",t.onToolCallRequestArgumentFragmentGenerated,[p,h,N])},handleToolCallGenerationEnd:(N,ne)=>{let de=h;ge=!1;let mt=k;k++,ke||B(i,"onToolCallRequestNameReceived",t.onToolCallRequestNameReceived,[p,de,N.name]),Yr||B(i,"onToolCallRequestArgumentFragmentGenerated",t.onToolCallRequestArgumentFragmentGenerated,[p,de,JSON.stringify(N.arguments??{},null,2)]);let It={...N};E.push(It);let gt=m.get(N.name);if(gt===void 0){let yt=new lr(`Cannot find tool with name ${N.name}.`,ne);z.push(Ce(yt,N,mt).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,de,yt]);return}try{gt.checkParameters(It.arguments)}catch(yt){let yr=new lr(yt.message,ne);z.push(Ce(yr,N,mt).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,de,yr]);return}let xh=new ea(new H(`Tool(${N.name})`,i),c.signal,de),dl=Q.needsQueueing();B(i,"onToolCallRequestEnd",t.onToolCallRequestEnd,[p,de,{isQueued:dl,toolCallRequest:N,rawContent:ne}]),z.push(Q.runInQueue(async()=>{if(dl&&B(i,"onToolCallRequestDequeued",t.onToolCallRequestDequeued,[p,de]),t.guardToolCall!==void 0){let Ot=[null];if(await t.guardToolCall(p,de,new Sa(N,gt,Ot)),Ot[0]===null)throw mr("Tool call guard did not allow or deny the tool call.",j`
319
+ The \`guardToolCall\` handler must call one of the methods on the controller
320
+ to allow or deny the tool call.
321
+ `,n);let hs=Ot[0];switch(hs.type){case"allow":break;case"allowAndOverrideParameters":{It.arguments=hs.parameters;break}case"deny":{x.push({index:mt,data:{type:"toolCallResult",toolCallId:N.id,content:JSON.stringify({error:hs.reason})}});return}}}B(i,"onToolCallRequestFinalized",t.onToolCallRequestFinalized,[p,de,{toolCallRequest:N,rawContent:ne}]);let yt;try{yt=await gt.implementation(It.arguments??{},xh)}catch(Ot){if(!(Ot instanceof ta))throw Ot;f=!0}let yr;if(yt===void 0)yr="undefined";else try{yr=JSON.stringify(yt)}catch{throw pe(`Return value of tool ${gt.name} cannot be converted to JSON.`,n)}x.push({index:mt,data:{type:"toolCallResult",toolCallId:N.id,content:yr}})},c.signal).catch(q))},handleToolCallGenerationFailed:(N,ne)=>{ge=!1;let de=new lr(N.message,ne);z.push(Ce(de,void 0,0).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,h,de])},handlePredictionEnd:N=>{let ne=l({endPacket:N,content:D.join(""),reasoningContent:v.join(""),nonReasoningContent:S.join(""),predictionsPerformed:p});B(i,"onPredictionCompleted",t.onPredictionCompleted,[ne]),C()},handleError:N=>{if(ge){let ne=new lr(`Generation failed: ${N.message}`,void 0);ge=!1,B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,h,ne])}b=!0,P(N)}});let be=()=>{b||(b=!0,ye.abort(c.signal.reason))};if(c.signal.addEventListener("abort",be),w.then(()=>{let N=le.from({role:"assistant",content:[{type:"text",text:D.join("")},...E.map(ne=>({type:"toolCallRequest",toolCallRequest:ne}))]});u.append(N.asMutableCopy()),B(i,"onMessage",t.onMessage,[N])}).then(()=>Promise.all(z)).then(()=>Z(),q),await U,d=!1,x.length>0){x.sort((ne,de)=>ne.index-de.index);let N=le.from({role:"tool",content:x.map(ne=>ne.data)});u.append(N.asMutableCopy()),B(i,"onMessage",t.onMessage,[N]),d=!0}B(i,"onRoundEnd",t.onRoundEnd,[p]),p++,t.maxPredictionRounds!==void 0&&p>=t.maxPredictionRounds&&(d=!1),d&&=!f}while(d);return new va(p,(performance.now()-o)/1e3)}var jn=class{constructor(e,t,n,i,o,a,l,c){this.content=e,this.reasoningContent=t,this.nonReasoningContent=n,this.stats=i,this.modelInfo=o,this.roundIndex=a,this.loadConfig=l,this.predictionConfig=c}},Ca=class extends jn{constructor(e,t,n,i,o,a,l,c,u){super(e,t,n,i,o,a,l,c),this.parsed=u}},Xi=class r extends Zi{async collect(e){let t=e.map(({content:o})=>o).join(""),n=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="reasoning").map(({content:o})=>o).join(""),i=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="none").map(({content:o})=>o).join("");if(this.stats===null)throw new Error("Stats should not be null");if(this.modelInfo===null)throw new Error("Model info should not be null");if(this.loadModelConfig===null)throw new Error("Load model config should not be null");if(this.predictionConfig===null)throw new Error("Prediction config should not be null");return this.parser===null?new jn(t,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig):new Ca(t,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig,this.parser(t))}constructor(e,t){super(),this.onCancel=e,this.parser=t,this.stats=null,this.modelInfo=null,this.loadModelConfig=null,this.predictionConfig=null}static create(e,t){let n=new r(e,t);return{ongoingPrediction:n,finished:(l,c,u,h)=>{n.stats=l,n.modelInfo=c,n.loadModelConfig=u,n.predictionConfig=h,n.finished()},failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},wh=Qa.extend({onPromptProcessingProgress:s.function().optional(),onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFailure:s.function().optional(),signal:s.instanceof(AbortSignal).optional(),preset:s.string().optional()});function Sh(r){let{onPromptProcessingProgress:e,onFirstToken:t,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:o,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h,...f}=r;return[f,{onPromptProcessingProgress:e,onFirstToken:t,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:o,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h}]}var OD=wh.extend({onMessage:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFailure:s.function().optional()});function MD(r){let{onMessage:e,...t}=r,[n,i]=Sh(t);return[n,i,{onMessage:e}]}var jD=Qa.extend(vh.shape).extend({preset:s.string().optional()});function BD(r){let{onFirstToken:e,onPredictionFragment:t,onMessage:n,onRoundStart:i,onRoundEnd:o,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:b,maxPredictionRounds:y,signal:D,preset:v,allowParallelToolExecution:S,...E}=r;return[E,{onFirstToken:e,onPredictionFragment:t,onMessage:n,onRoundStart:i,onRoundEnd:o,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:b,maxPredictionRounds:y,signal:D,preset:v,allowParallelToolExecution:S}]}var LD=j`
322
+ {% for message in messages %}{{ message['content'] }}{% endfor %}
323
+ `,es=class extends Qi{constructor(e,t,n,i=new H("LLMModel")){super(e,t),this.validator=n,this.logger=i,this.internalKVConfigStack={layers:[]},this.internalIgnoreServerSessionConfig=void 0}internalPredict(e,t,n,i,o,a,l){let c=!1,u=!1,h=null,f=!1,d=!1,p=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:e,predictionConfigStack:t,fuzzyPresetIdentifier:i.preset,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},m=>{switch(m.type){case"fragment":{u||(u=!0,B(this.logger,"onFirstToken",i.onFirstToken,[])),B(this.logger,"onFragment",i.onPredictionFragment,[m.fragment]),o(m.fragment);break}case"promptProcessingProgress":{B(this.logger,"onPromptProcessingProgress",i.onPromptProcessingProgress,[m.progress]);break}case"toolCallGenerationStart":{h===null?h=0:h++,f=!1,d=!1,B(this.logger,"onToolCallGenerationStart",i.onToolCallRequestStart,[h,{toolCallId:m.toolCallId}]);break}case"toolCallGenerationNameReceived":{f=!0,B(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.name]);break}case"toolCallGenerationArgumentFragmentGenerated":{d=!0,B(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,m.content]);break}case"toolCallGenerationEnd":{f||B(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.toolCallRequest.name]),d||B(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,JSON.stringify(m.toolCallRequest.arguments??{},null,2)]),B(this.logger,"onToolCallGenerationEnd",i.onToolCallRequestEnd,[h??-1,{toolCallRequest:m.toolCallRequest,rawContent:m.rawContent}]);break}case"toolCallGenerationFailed":{let g=new lr(Vi(m.error).message,m.rawContent);B(this.logger,"onToolCallGenerationFailed",i.onToolCallRequestFailure,[h??-1,g]);break}case"success":{c=!0,a(m.stats,m.modelInfo,m.loadModelConfig,m.predictionConfig);break}}},{stack:A(2)});n.subscribeOnce(()=>{c||p.send({type:"cancel"})}),p.onError.subscribeOnce(l)}predictionConfigInputToKVConfig(e){let t;typeof e.structured?.parse=="function"?t={type:"json",jsonSchema:Ci(e.structured)}:t=e.structured;let n={...e,structured:t};return pv(n)}createZodParser(e){return t=>{try{return e.parse(JSON.parse(t))}catch(n){throw new Error("Failed to parse structured output: "+JSON.stringify(t),{cause:n})}}}complete(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("model","complete",["prompt","opts"],[s.string(),wh],[e,t],n);let[i,o]=Sh(t),[a,l]=ht.create();o.signal!==void 0&&(o.signal.aborted?l():o.signal.addEventListener("abort",()=>{l()},{once:!0}));let c=gr.safeParse(i.structured),{ongoingPrediction:u,finished:h,failed:f,push:d}=Xi.create(l,c.success?this.createZodParser(c.data):null);return this.internalPredict(this.resolveCompletionContext(e),{layers:[...this.internalKVConfigStack.layers,{layerName:"apiOverride",config:this.predictionConfigInputToKVConfig({stopStrings:[],...i})},{layerName:"completeModeFormatting",config:$n.buildPartialConfig({promptTemplate:{type:"jinja",jinjaPromptTemplate:{template:LD},stopStrings:[]}})}]},a,o,p=>d(p),(p,m,g,b)=>h(p,m,g,b),p=>f(p)),u}resolveCompletionContext(e){return{messages:[{role:"user",content:[{type:"text",text:e}]}]}}respond(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("model","respond",["chat","opts"],[Wr,OD],[e,t],n);let[i,o]=ht.create(),[a,l,c]=MD(t);l.signal!==void 0&&(l.signal.aborted?o():l.signal.addEventListener("abort",()=>{o()},{once:!0}));let u=gr.safeParse(a.structured),{ongoingPrediction:h,finished:f,failed:d,push:p}=Xi.create(o,u.success?this.createZodParser(u.data):null);return this.internalPredict(pt.from(e)._internalGetData(),Ro(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig(a)),i,l,m=>p(m),(m,g,b,y)=>f(m,g,b,y),m=>d(m)),h.then(m=>{B(this.logger,"onMessage",c.onMessage,[le.create("assistant",m.content)])},()=>{}),h}async act(e,t,n={}){let i=performance.now(),o=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("model","act",["chat","opts"],[Wr,jD],[e,n],o);let[a,{preset:l,...c}]=BD(n);if(a.structured!==void 0&&a.structured.type!=="none"&&t.length>0)throw pe("Structured output is currently not supported in .act() when there are tools.",o);if(a.structured!==void 0&&a.structured.parse!==void 0)throw pe("zod schema is not supported in .act().",o);if(a.rawTools!==void 0)throw pe("`rawTools` is not supported in act. Use `tools` instead",o);let u;t.length===0?u={type:"none"}:u={type:"toolArray",tools:t.map(ll)};let h=Ro(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:u})),f=Ro(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:{type:"none"}}));return await Dh(e,t,c,o,this.logger,i,async({allowTools:d,history:p,signal:m,handleFragment:g,handlePromptProcessingProgress:b,handleToolCallGenerationStart:y,handleToolCallGenerationNameReceived:D,handleToolCallGenerationArgumentFragmentGenerated:v,handleToolCallGenerationEnd:S,handleToolCallGenerationFailed:E,handlePredictionEnd:k,handleError:x})=>{let z=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:p,predictionConfigStack:d?h:f,fuzzyPresetIdentifier:l,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},w=>{switch(w.type){case"fragment":{g(w.fragment);break}case"promptProcessingProgress":{b(w.progress);break}case"toolCallGenerationStart":{y(w.toolCallId);break}case"toolCallGenerationNameReceived":{D(w.name);break}case"toolCallGenerationArgumentFragmentGenerated":{v(w.content);break}case"toolCallGenerationEnd":{S(w.toolCallRequest,w.rawContent);break}case"toolCallGenerationFailed":{E(Vi(w.error),w.rawContent);break}case"success":{k({stats:w.stats,modelInfo:w.modelInfo,loadModelConfig:w.loadModelConfig,predictionConfig:w.predictionConfig});break}}},{stack:o});m.aborted?z.send({type:"cancel"}):m.addEventListener("abort",()=>{z.send({type:"cancel"})},{once:!0}),z.onError.subscribeOnce(x)},({endPacket:d,content:p,nonReasoningContent:m,reasoningContent:g,predictionsPerformed:b})=>new jn(p,g,m,d.stats,d.modelInfo,b,d.loadModelConfig,d.predictionConfig))}async getContextLength(){let e=A(1),t=await this.getLoadConfig(e);return Un.access(t,"contextLength")}async applyPromptTemplate(e,t={}){let n=A(1);return[e,t]=this.validator.validateMethodParamsOrThrow("model","applyPromptTemplate",["history","opts"],[Wr,bf],[e,t],n),(await this.port.callRpc("applyPromptTemplate",{specifier:this.specifier,history:pt.from(e)._internalGetData(),predictionConfigStack:this.internalKVConfigStack,opts:t},{stack:n})).formatted}async tokenize(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:t})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:t})).tokens}async countTokens(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",s.string(),e,t),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:t})).tokenCount}async unstable_preloadDraftModel(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("model","unstable_preloadDraftModel","draftModelKey",s.string(),e,t),await this.port.callRpc("preloadDraftModel",{specifier:this.specifier,draftModelKey:e},{stack:t})}},Ea=class extends es{constructor(e,t,n,i=new H("LLM")){let o={type:"instanceReference",instanceReference:t.instanceReference};super(e,o,n,i),this.identifier=t.identifier,this.path=t.path,this.modelKey=t.modelKey,this.format=t.format,this.displayName=t.displayName,this.sizeBytes=t.sizeBytes,this.vision=t.vision,this.trainedForToolUse=t.trainedForToolUse}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let t=A(1);throw pe("This model has already been unloaded",t)}return e}},_a=class extends Yi{constructor(){super(...arguments),this.namespace="llm",this.defaultLoadConfig={},this.loadModelConfigSchema=Vb}loadConfigToKVConfig(e){return dv.buildPartialConfig({contextLength:e.contextLength,"llama.evalBatchSize":e.evalBatchSize,"llama.acceleration.offloadRatio":e.gpu?.ratio,numCpuExpertLayersRatio:e.gpu?.numCpuExpertLayersRatio,"load.gpuSplitConfig":pf(e.gpu),"llama.flashAttention":e.flashAttention,"llama.ropeFrequencyBase":vn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":vn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,seed:vn(e.seed,-1,0),"llama.useFp16ForKVCache":e.useFp16ForKVCache,"llama.tryMmap":e.tryMmap,numExperts:e.numExperts,"llama.kCacheQuantizationType":Vd({value:e.llamaKCacheQuantizationType,falseDefault:"f16"}),"llama.vCacheQuantizationType":Vd({value:e.llamaVCacheQuantizationType,falseDefault:"f16"})})}createDomainSpecificModel(e,t,n,i){return new Ea(e,t,n,i)}createDomainDynamicHandle(e,t,n,i){return new es(e,t,n,i)}},ts=class{constructor(e,t,n,i){this.content=e,this.reasoningContent=t,this.nonReasoningContent=n,this.pluginIdentifier=i}},xa=class r extends Zi{async collect(e){let t=e.map(({content:o})=>o).join(""),n=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="reasoning").map(({content:o})=>o).join(""),i=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="none").map(({content:o})=>o).join("");return new ts(t,n,i,this.pluginIdentifier)}constructor(e,t){super(),this.pluginIdentifier=e,this.onCancel=t}static create(e,t){let n=new r(e,t);return{ongoingPrediction:n,finished:()=>n.finished(),failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},ND=s.object({onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onMessage:s.function().optional(),signal:s.instanceof(AbortSignal).optional(),pluginConfig:X.optional(),workingDirectory:s.string().optional()}),$D=vh.extend({pluginConfig:X.optional(),workingDirectory:s.string().optional()}),rs=class{constructor(e,t,n,i,o=new H("LLMGeneratorHandle")){this.port=e,this.pluginIdentifier=t,this.validator=n,this.associatedPredictionProcess=i,this.logger=o,this.identifier=this.pluginIdentifier}getPluginConfigSpecifier(e,t,n){if(this.associatedPredictionProcess===null)return{type:"direct",config:e??Kf,workingDirectoryPath:t??void 0};if(e!==void 0)throw mr("Cannot use plugin config with prediction process",j`
324
+ You cannot provide a plugin config to the generator handle when it is associated with a
325
+ prediction process. The plugin config that was configured for the prediction process will
326
+ be used instead.
327
+
328
+ If you want to use a different plugin config, you will need to create a separate
329
+ GeneratorHandle instead.
330
+ `,n);if(t!==void 0)throw mr("Cannot use working directory with prediction process",j`
331
+ You cannot provide a working directory to the generator handle when it is associated with
332
+ a prediction process. The working directory that was configured for the prediction process
333
+ will be used instead.
334
+
335
+ If you want to use a different working directory, you will need to create a separate
336
+ GeneratorHandle instead.
337
+ `,n);return{type:"predictionProcess",pci:this.associatedPredictionProcess.pci,token:this.associatedPredictionProcess.token}}respond(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","respond",["chat","opts"],[Wr,ND],[e,t],n);let{onFirstToken:i,onPredictionFragment:o,onMessage:a,signal:l,pluginConfig:c,workingDirectory:u}=t,h=!1,f=!1,d=new Uo;l!==void 0&&(l.aborted?d.cancel():l.addEventListener("abort",()=>d.cancel(),{once:!0}));let{ongoingPrediction:p,finished:m,failed:g,push:b}=xa.create(this.pluginIdentifier,()=>{d.cancel()}),y=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(c,u,n),tools:[],history:pt.from(e)._internalGetData()},D=>{switch(D.type){case"fragment":{f||(f=!0,B(this.logger,"onFirstToken",i,[])),B(this.logger,"onPredictionFragment",o,[D.fragment]),b(D.fragment);break}case"success":{h=!0,m();break}}},{stack:n});return y.onError.subscribeOnce(D=>{h||(h=!0,g(D))}),d.subscribeOnce(()=>{h||y.send({type:"cancel"})}),p.then(D=>{B(this.logger,"onMessage",a,[le.create("assistant",D.content)])},()=>{}),p}async act(e,t,n={}){let i=performance.now(),o=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","act",["chat","opts"],[Wr,$D],[e,n],o);let{pluginConfig:a,workingDirectory:l,...c}=n,u=t.map(ll);return await Dh(e,t,c,o,this.logger,i,async({allowTools:h,history:f,signal:d,handleFragment:p,handlePromptProcessingProgress:m,handleToolCallGenerationStart:g,handleToolCallGenerationNameReceived:b,handleToolCallGenerationArgumentFragmentGenerated:y,handleToolCallGenerationEnd:D,handleToolCallGenerationFailed:v,handlePredictionEnd:S,handleError:E})=>{let k=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(a,l,o),tools:h?u:[],history:f},x=>{switch(x.type){case"fragment":{p(x.fragment);break}case"promptProcessingProgress":{m(x.progress);break}case"toolCallGenerationStart":{g(x.toolCallId);break}case"toolCallGenerationNameReceived":{b(x.name);break}case"toolCallGenerationArgumentFragmentGenerated":{y(x.content);break}case"toolCallGenerationEnd":{D(x.toolCallRequest,void 0);break}case"toolCallGenerationFailed":{v(new Error("Tool call generation failed"),void 0);break}case"success":{S(void 0);break}}},{stack:o});d.aborted?k.send({type:"cancel"}):d.addEventListener("abort",()=>{k.send({type:"cancel"})},{once:!0}),k.onError.subscribeOnce(E)},({content:h,nonReasoningContent:f,reasoningContent:d})=>new ts(h,d,f,this.pluginIdentifier))}},UD=s.function(),Bn=class{constructor(e,t,n,i,o){this.client=e,this.abortSignal=t,this.pluginConfig=n,this.globalPluginConfig=i,this.workingDirectoryPath=o}getWorkingDirectory(){if(this.workingDirectoryPath===null)throw new Error("This prediction process is not attached to a working directory.");return this.workingDirectoryPath}getPluginConfig(e){return e.parse(this.pluginConfig)}getGlobalPluginConfig(e){return e.parse(this.globalPluginConfig)}onAborted(e){this.abortSignal.aborted?e():this.abortSignal.addEventListener("abort",e,{once:!0})}},ka=class extends Bn{constructor(e,t,n,i,o,a,l,c){super(e,o,t,n,i),this.toolDefinitions=a,this.connector=l,this.validator=c}getToolDefinitions(){return this.toolDefinitions}fragmentGenerated(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("GeneratorController","fragmentGenerated",["content","opts"],[s.string(),kf],[e,t],n),this.connector.fragmentGenerated(e,t)}toolCallGenerationStarted({toolCallId:e}={}){this.connector.toolCallGenerationStarted(e)}toolCallGenerationNameReceived(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationNameReceived","toolName",s.string(),e,t),this.connector.toolCallGenerationNameReceived(e)}toolCallGenerationArgumentFragmentGenerated(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationArgumentFragmentGenerated","content",s.string(),e,t),this.connector.toolCallGenerationArgumentFragmentGenerated(e)}toolCallGenerationEnded(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationEnded","toolCallRequest",Pn,e,t),this.connector.toolCallGenerationEnded(e)}toolCallGenerationFailed(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationFailed","error",s.instanceof(Error),e,t),this.connector.toolCallGenerationFailed(e)}},zD=globalThis&&globalThis.__addDisposableResource||function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(o){return Promise.reject(o)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},qD=globalThis&&globalThis.__disposeResources||(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function o(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(o);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(o,function(l){return t(l),o()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return o()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});function VD(r){switch(typeof r){case"string":return r;case"number":return r.toString();case"boolean":return r?"true":"false";case"undefined":return"undefined";case"object":return r===null?"null":r instanceof Error?r.stack:JSON.stringify(r,null,2);case"bigint":return r.toString();case"symbol":return r.toString();case"function":return r.toString();default:return"unknown"}}function WD(...r){return r.map(VD).join(" ")}function zr(){return`${Date.now()}-${Math.random()}`}var ns=class{constructor(e,t,n,i,o){this.pluginsPort=e,this.abortSignal=t,this.processingContextIdentifier=n,this.token=i,this.logger=o}handleUpdate(e){this.pluginsPort.callRpc("processingHandleUpdate",{pci:this.processingContextIdentifier,token:this.token,update:e}).catch(t=>{this.logger.error("Failed to send update",t)})}async handleRequest(e){let{response:t}=await this.pluginsPort.callRpc("processingHandleRequest",{pci:this.processingContextIdentifier,token:this.token,request:e});return t}async pullHistory(e){let t=await this.pluginsPort.callRpc("processingPullHistory",{pci:this.processingContextIdentifier,token:this.token,includeCurrent:e});return pt.createRaw(t,!1).asMutableCopy()}async getOrLoadTokenSource(){return(await this.pluginsPort.callRpc("processingGetOrLoadTokenSource",{pci:this.processingContextIdentifier,token:this.token})).tokenSourceIdentifier}async hasStatus(){return await this.pluginsPort.callRpc("processingHasStatus",{pci:this.processingContextIdentifier,token:this.token})}async needsNaming(){return await this.pluginsPort.callRpc("processingNeedsNaming",{pci:this.processingContextIdentifier,token:this.token})}async suggestName(e){await this.pluginsPort.callRpc("processingSuggestName",{pci:this.processingContextIdentifier,token:this.token,name:e})}},is=class extends Bn{constructor(e,t,n,i,o,a,l,c){super(e,a.abortSignal,t,n,i),this.enabledPluginInfos=o,this.connector=a,this.config=l,this.shouldIncludeCurrentInHistory=c,this.processingControllerHandle={abortSignal:a.abortSignal,sendUpdate:u=>{a.handleUpdate(u)},sendRequest:async u=>{let h=u.type,f=await a.handleRequest(u);if(f.type!==h)throw new Error(`Expected response type ${h}, but got ${f.type}. This is a bug.`);return f}}}sendUpdate(e){this.processingControllerHandle.sendUpdate(e)}async pullHistory(){return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory)}createStatus(e){let t=zr();return this.sendUpdate({type:"status.create",id:t,state:e}),new Fa(this.processingControllerHandle,e,t)}addCitations(e){if(Array.isArray(e))for(let t of e)this.createCitationBlock(t.content,{fileName:t.source.name,fileIdentifier:t.source.identifier});else for(let t of e.entries)this.createCitationBlock(t.content,{fileName:t.source.name,fileIdentifier:t.source.identifier})}createCitationBlock(e,t){let n=zr();return this.sendUpdate({type:"citationBlock.create",id:n,citedText:e,...t}),new Pa(this.processingControllerHandle,n)}createDebugInfoBlock(e){let t=zr();return this.sendUpdate({type:"debugInfoBlock.create",id:t,debugInfo:e}),new Ta(this.processingControllerHandle,t)}createContentBlock({roleOverride:e,includeInContext:t=!0,style:n,prefix:i,suffix:o}={}){let a=zr();return this.sendUpdate({type:"contentBlock.create",id:a,roleOverride:e,includeInContext:t,style:n,prefix:i,suffix:o}),new Aa(this.processingControllerHandle,a,e??"assistant")}debug(...e){this.createDebugInfoBlock(WD(...e))}async tokenSource(){let e=await this.connector.getOrLoadTokenSource();switch(e.type){case"model":{let n=await this.client.llm.model(e.identifier);return n.internalIgnoreServerSessionConfig=!0,n.internalKVConfigStack={layers:[{layerName:"conversationSpecific",config:this.config}]},n}case"generator":return this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(e.pluginIdentifier,this.connector.processingContextIdentifier,this.connector.token)}}async setSenderName(e){this.sendUpdate({type:"setSenderName",name:e})}guardAbort(){this.abortSignal.throwIfAborted()}async hasStatus(){return await this.connector.hasStatus()}async needsNaming(){return await this.connector.needsNaming()}async suggestName(e){await this.connector.suggestName(e)}async requestConfirmToolCall({callId:e,pluginIdentifier:t,name:n,parameters:i}){let{result:o}=await pb(this.processingControllerHandle.sendRequest({type:"confirmToolCall",callId:e,pluginIdentifier:t,name:n,parameters:i}),this.abortSignal),a=o.type;switch(a){case"allow":return{type:"allow",toolArgsOverride:o.toolArgsOverride};case"deny":return{type:"deny",denyReason:o.denyReason};default:{let l=a;throw new Error(`Unexpected result type ${l}. This is a bug. Please report it.`)}}}createToolStatus(e,t){let n=zr();return this.sendUpdate({type:"toolStatus.create",id:n,callId:e,state:{status:t,customStatus:"",customWarnings:[]}}),new Ra(this.processingControllerHandle,n,t)}async startToolUseSession(){let e=this.enabledPluginInfos.filter(({hasToolsProvider:t})=>t).map(({identifier:t})=>t);return await this.client.plugins.startToolUseSessionUsingPredictionProcess(e,this.connector.processingContextIdentifier,this.connector.token)}},Fa=class r{constructor(e,t,n,i=0){this.handle=e,this.id=n,this.indentation=i,this.lastSubStatus=this,this.lastState=t}setText(e){this.lastState.text=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:this.lastState})}setState(e){this.lastState=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:e})}remove(){this.handle.sendUpdate({type:"status.remove",id:this.id})}getNestedLastSubStatusBlockId(){let e=this.lastSubStatus;for(;e!==e.lastSubStatus;)e=e.lastSubStatus;return e.id}addSubStatus(e){let t=zr();this.handle.sendUpdate({type:"status.create",id:t,state:e,location:{type:"afterId",id:this.getNestedLastSubStatusBlockId()},indentation:this.indentation+1});let n=new r(this.handle,e,t,this.indentation+1);return this.lastSubStatus=n,n}},Pa=class{constructor(e,t){this.handle=e,this.id=t}},Ta=class{constructor(e,t){this.handle=e,this.id=t}},Aa=class{constructor(e,t,n){this.handle=e,this.id=t,this.role=n}appendText(e,{tokensCount:t,fromDraftModel:n,isStructural:i}={}){if(this.role==="tool")throw new Error("Text cannot be appended to tool blocks.");this.handle.sendUpdate({type:"contentBlock.appendText",id:this.id,text:e,tokensCount:t,fromDraftModel:n,isStructural:i})}appendToolRequest({callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o}){if(this.role!=="assistant")throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolRequest",id:this.id,callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o})}replaceToolRequest({callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o}){if(this.role!=="assistant")throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.replaceToolRequest",id:this.id,callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o})}appendToolResult({callId:e,toolCallRequestId:t,content:n}){if(this.role!=="tool")throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolResult",id:this.id,callId:e,toolCallRequestId:t,content:n})}replaceText(e){if(this.role==="tool")throw new Error("Text cannot be set in tool blocks.");this.handle.sendUpdate({type:"contentBlock.replaceText",id:this.id,text:e})}setStyle(e){this.handle.sendUpdate({type:"contentBlock.setStyle",id:this.id,style:e})}setPrefix(e){this.handle.sendUpdate({type:"contentBlock.setPrefix",id:this.id,prefix:e})}setSuffix(e){this.handle.sendUpdate({type:"contentBlock.setSuffix",id:this.id,suffix:e})}attachGenInfo(e){this.handle.sendUpdate({type:"contentBlock.attachGenInfo",id:this.id,genInfo:e})}async pipeFrom(e){let t={stack:[],error:void 0,hasError:!1};try{let n=zD(t,new Ui,!1),i=()=>{e.cancel()};this.handle.abortSignal.addEventListener("abort",i),n.register(()=>{this.handle.abortSignal.removeEventListener("abort",i)});for await(let{content:a}of e)this.appendText(a);let o=await e;return this.attachGenInfo({indexedModelIdentifier:o.modelInfo.path,identifier:o.modelInfo.identifier,loadModelConfig:o.loadConfig,predictionConfig:o.predictionConfig,stats:o.stats}),this.handle.abortSignal.throwIfAborted(),o}catch(n){t.error=n,t.hasError=!0}finally{qD(t)}}},Ra=class{constructor(e,t,n){this.handle=e,this.id=t,this.customStatus="",this.customWarnings=[],this.status=n}updateState(){this.handle.sendUpdate({type:"toolStatus.update",id:this.id,state:{status:this.status,customStatus:this.customStatus,customWarnings:this.customWarnings}})}setCustomStatusText(e){this.customStatus=e,this.updateState()}addWarning(e){this.customWarnings.push(e),this.updateState()}setStatus(e){this.status=e,this.updateState()}appendArgumentFragment(e){this.handle.sendUpdate({type:"toolStatus.argumentFragment",id:this.id,content:e})}},Ia=class extends Bn{constructor(e,t,n,i,o){super(e,t,n,i,o)}},Oa=class{constructor(e,t){this.channel=e,this.taskId=t}fragmentGenerated(e,t){this.channel.send({type:"fragmentGenerated",taskId:this.taskId,content:e,opts:t})}toolCallGenerationStarted(e){this.channel.send({type:"toolCallGenerationStarted",taskId:this.taskId,toolCallId:e})}toolCallGenerationNameReceived(e){this.channel.send({type:"toolCallGenerationNameReceived",taskId:this.taskId,toolName:e})}toolCallGenerationArgumentFragmentGenerated(e){this.channel.send({type:"toolCallGenerationArgumentFragmentGenerated",taskId:this.taskId,content:e})}toolCallGenerationEnded(e){this.channel.send({type:"toolCallGenerationEnded",taskId:this.taskId,toolCallRequest:e})}toolCallGenerationFailed(e){this.channel.send({type:"toolCallGenerationFailed",taskId:this.taskId,error:ir(e)})}},Ma=class{constructor(e,t,n,i){this.port=e,this.client=t,this.rootLogger=n,this.validator=i}setPromptPreprocessor(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","registerPromptPreprocessor","promptPreprocessor",s.function(),e,t);let n=new H("PromptPreprocessor",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setPromptPreprocessor",void 0,a=>{switch(a.type){case"preprocess":{let l=new H(`Request (${a.taskId.substring(0,6)})`,n);l.info("New preprocess request received.");let c=new AbortController,u=new ns(this.port,c.signal,a.pci,a.token,l),h=le.createRaw(a.input,!1),f=new is(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!1);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(f,h.asMutableCopy()).then(d=>{l.info("Preprocess request completed.");let p=s.union([s.string(),s.custom(b=>b instanceof le)]).safeParse(d);if(!p.success)throw new Error("PromptPreprocessor returned an invalid value:"+Ye.prettyPrintZod("result",p.error));let m=p.data,g;if(typeof m=="string"){let b=h.asMutableCopy();b.replaceText(m),g=b.getRaw()}else g=m.getRaw();o.send({type:"complete",taskId:a.taskId,processed:g})}).catch(d=>{if(d.name==="AbortError"){n.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId});return}n.warn("Preprocessing failed.",d),o.send({type:"error",taskId:a.taskId,error:ir(d)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:t})}setPredictionLoopHandler(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setPredictionLoopHandler","predictionLoopHandler",s.function(),e,t);let n=new H(" PredictionLoopHandler",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setPredictionLoopHandler",void 0,a=>{switch(a.type){case"handlePredictionLoop":{let l=new H(`Request (${a.taskId.substring(0,6)})`,n);l.info("New prediction loop handling request received.");let c=new AbortController,u=new ns(this.port,c.signal,a.pci,a.token,l),h=new is(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!0);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(h).then(()=>{o.send({type:"complete",taskId:a.taskId})}).catch(f=>{if(f.name==="AbortError"){n.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId});return}n.warn("Generation failed.",f),o.send({type:"error",taskId:a.taskId,error:ir(f)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:t})}async setConfigSchematics(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setConfigSchematics","configSchematics",s.instanceof(An),e,t),await this.port.callRpc("setConfigSchematics",{schematics:e.serialize()},{stack:t})}async setGlobalConfigSchematics(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setGlobalConfigSchematics","globalConfigSchematics",s.instanceof(An),e,t),await this.port.callRpc("setGlobalConfigSchematics",{schematics:e.serialize()},{stack:t})}setToolsProvider(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setToolsProvider","toolsProvider",s.function(),e,t),new H("Tools Prvdr.",this.rootLogger).info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setToolsProvider",void 0,a=>{let l=a.type;switch(l){case"initSession":{let c=a.sessionId,u=new AbortController,h={tools:null,ongoingToolCalls:new Map,discarded:!1,abortController:u};i.set(c,h);let f=new Ia(this.client,u.signal,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath);e(f).then(d=>{let p=d.map(ll);h.discarded||(o.send({type:"sessionInitialized",sessionId:c,toolDefinitions:p}),h.tools=new Map(d.map(m=>[m.name,m])))},d=>{h.discarded||(o.send({type:"sessionInitializationFailed",sessionId:c,error:ir(d)}),h.discarded=!0,i.delete(c))});break}case"discardSession":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;u.discarded=!0,u.abortController.abort(),i.delete(c);break}case"callTool":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;if(u.tools===null)throw new Error("Tool called before initialization completed. This is unexpected.");let h=u.tools.get(a.toolName);if(h===void 0)throw new Error(`Tool ${a.toolName} not found.`);let f=a.callId,d={settled:!1,abortController:new AbortController};u.ongoingToolCalls.set(f,d),new H(`Tool (${a.toolName})`,this.rootLogger);let p={status(m){o.send({type:"toolCallStatus",sessionId:c,callId:f,statusText:m})},warn(m){o.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:m})},signal:d.abortController.signal,callId:0};(async()=>await h.implementation(a.parameters,p))().then(m=>{if(!u.discarded&&!d.settled&&!d.abortController.signal.aborted){m===void 0&&(m="undefined",o.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:j`
338
+ Tool call returned undefined. This is not expected as the model always expects
339
+ a result. If you don't want to return anything, you can just return a string
340
+ reporting that the tool call was successful. For example: "operation
341
+ successful." In this case, we will give the model string "${m}".
342
+ `}));try{JSON.stringify(m)}catch{m=j`
343
+ Error: Tool call completed but returned a value that cannot be serialized to JSON
344
+ `,o.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:j`
345
+ Tool call succeeded, but returned a value that is not JSON serializable. In
346
+ order to provide the result to the model, return values of tools must be JSON
347
+ serializable. In this case, we will give the model string "${m}".
348
+ `})}o.send({type:"toolCallComplete",sessionId:c,callId:f,result:m}),d.settled=!0,u.ongoingToolCalls.delete(f)}},m=>{u.discarded||d.settled||d.abortController.signal.aborted||(o.send({type:"toolCallError",sessionId:c,callId:f,error:ir(m)}),d.settled=!0,u.ongoingToolCalls.delete(f))});break}case"abortToolCall":{let c=a.sessionId,u=a.callId,h=i.get(c);if(h===void 0)return;let f=h.ongoingToolCalls.get(u);if(f===void 0)return;f.settled=!0,f.abortController.abort(),h.ongoingToolCalls.delete(u);break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}setGenerator(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setGenerator","generator",UD,e,t);let n=new H("Generator",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setGenerator",void 0,a=>{let l=a.type;switch(l){case"generate":{let c=new H(`Request (${a.taskId.substring(0,6)})`,n);c.info("New generate request received.");let u=new AbortController,h=new Oa(o,a.taskId),f=new ka(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,u.signal,a.toolDefinitions,h,this.validator);i.set(a.taskId,{cancel:()=>{u.abort()},taskLogger:c});let d=pt.createRaw(a.input,!1);e(f,d).then(p=>{p!==void 0&&c.warnText`
349
+ The generator has returned a value. This it not expected. You should report
350
+ generated content using method on the controller. The returned value will be
351
+ ignored.
352
+ `,o.send({type:"complete",taskId:a.taskId})},p=>{p.name==="AbortError"?(c.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId})):(o.send({type:"error",taskId:a.taskId,error:ir(p)}),c.warn("Generation failed.",p))}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let c=i.get(a.taskId);c!==void 0&&(c.taskLogger.info("Received abort request."),c.cancel(),i.delete(a.taskId));break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}async initCompleted(){let e=A(1);await this.port.callRpc("pluginInitCompleted",void 0,{stack:e})}},ZD=globalThis&&globalThis.__addDisposableResource||function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(o){return Promise.reject(o)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},GD=globalThis&&globalThis.__disposeResources||(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function o(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(o);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(o,function(l){return t(l),o()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return o()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n}),ss=class r{static async create(e,t,n,i,o){let a=new r(e,t,n,i);return await a.init(o),a}constructor(e,t,n,i){this.pluginsPort=e,this.pluginIdentifier=t,this.pluginConfigSpecifier=n,this.logger=i,this.status="initializing",this.poison=null,this.ongoingToolCalls=new Map,this.callIdGiver=new zi(0)}async init(e){let{promise:t,resolve:n,reject:i}=ee(),o=this.pluginsPort.createChannel("startToolUseSession",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.pluginConfigSpecifier},a=>{let l=a.type;switch(l){case"sessionReady":{if(this.status!=="initializing"){this.logger.error("Received sessionReady message while not initializing");return}this.status="ready",n(),this.tools=a.toolDefinitions.map(c=>this.makeTool(c));break}case"toolCallComplete":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.resolve(a.result);break}case"toolCallError":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reject(Vi(a.error));break}case"toolCallStatus":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportStatus(a.statusText);break}case"toolCallWarn":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportWarning(a.warnText);break}default:{let c=l;this.logger.warn(`Received unexpected message type in tool use session: ${c}`)}}},{stack:e});o.onError.subscribeOnce(a=>{this.status==="initializing"?i(a):(this.logger.error("Tool use session error.",a),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),o.onClose.subscribeOnce(()=>{let a;this.status==="initializing"?(a=new Error("Tool use session channel closed unexpectedly during initialization."),i(a)):(a=new Error("Tool use session has already ended."),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),this.channel=o,await t}[Symbol.dispose](){if(this.status!=="disposed"){this.channel.send({type:"discardSession"}),this.status="disposed";let e=new Error("Session disposed by client.");for(let t of this.ongoingToolCalls.values())t.reject(e);this.poison=e}}makeTool(e){return Ev({name:e.function.name,description:e.function.description??"",pluginIdentifier:this.pluginIdentifier,parametersJsonSchema:e.function.parameters??{},implementation:async(t,n)=>{let i={stack:[],error:void 0,hasError:!1};try{if(this.poison!==null)throw this.poison;if(n.signal.aborted)throw n.signal.reason;let o=this.callIdGiver.next(),{promise:a,resolve:l,reject:c}=ee(),u=ZD(i,new Ui,!1);return this.ongoingToolCalls.set(o,{callId:o,resolve:l,reject:c,reportStatus:h=>n.status(h),reportWarning:h=>n.warn(h)}),u.register(()=>{this.ongoingToolCalls.delete(o)}),this.channel.send({type:"callTool",callId:o,name:e.function.name,arguments:t}),n.signal.addEventListener("abort",()=>{this.status!=="disposed"&&(this.channel.send({type:"abortToolCall",callId:o}),c(n.signal.reason))},{once:!0}),await a}catch(o){i.error=o,i.hasError=!0}finally{GD(i)}}})}},ja=class r{static async createUsingPredictionProcess(e,t,n,i,o,a){let l=await Promise.allSettled(t.map(u=>ss.create(e,u,{type:"predictionProcess",pci:n,token:i},o,a))),c=l.filter(u=>u.status==="rejected");if(c.length>0){for(let u of l)if(u.status==="fulfilled")try{u.value[Symbol.dispose]()}catch(h){o.error("Failed to dispose a session after initialization failure.",h)}throw new AggregateError(c.map(u=>u.reason),"Failed to initialize some tool use sessions.")}return new r(l.map(u=>u.value),o)}constructor(e,t){this.sessions=e,this.logger=t,this.tools=[],this.tools=e.flatMap(n=>n.tools)}[Symbol.dispose](){for(let e of this.sessions)try{e[Symbol.dispose]()}catch(t){this.logger.error("Failed to dispose a session.",t)}}},KD=s.object({pluginConfig:X.optional(),workingDirectory:s.string().optional()}),HD=s.object({manifest:Ka}),Ba=class{constructor(e,t,n,i,o){this.port=e,this.client=t,this.validator=n,this.rootLogger=o,this.logger=new H("Plugins",i)}async registerDevelopmentPlugin(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","registerDevelopmentPlugin","opts",HD,e,t);let{promise:n,resolve:i}=ee(),o=this.port.createChannel("registerDevelopmentPlugin",e,u=>{u.type==="ready"&&i({clientIdentifier:u.clientIdentifier,clientPasskey:u.clientPasskey})},{stack:t}),a=!1,l=async()=>{if(a)return;a=!0,o.send({type:"end"});let{promise:u,resolve:h}=ee();o.onClose.subscribeOnce(h),await u};return{...await n,unregister:l}}async reindexPlugins(){let e=A(1);await this.port.callRpc("reindexPlugins",void 0,{stack:e})}getSelfRegistrationHost(){return new Ma(this.port,this.client,this.rootLogger,this.validator)}async internalStartToolUseSession(e,t,n){return await ss.create(this.port,e,t,this.logger)}async pluginTools(e,t={}){let n=A(1);return[e,t]=this.validator.validateMethodParamsOrThrow("plugins","pluginTools",["pluginIdentifier","opts"],[Fb,KD],[e,t],n),await this.internalStartToolUseSession(e,{type:"direct",config:t.pluginConfig??Kf,workingDirectoryPath:t.workingDirectory})}async startToolUseSessionUsingPredictionProcess(e,t,n,i){return await ja.createUsingPredictionProcess(this.port,e,t,n,this.logger,i)}createGeneratorHandle(e){return new rs(this.port,e,this.validator,null,this.logger)}createGeneratorHandleAssociatedWithPredictionProcess(e,t,n){return new rs(this.port,e,this.validator,{pci:t,token:n},this.logger)}},JD=s.object({onStartFinalizing:s.function().optional(),onProgress:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),La=class{constructor(e,t,n,i,o,a){this.owner=e,this.name=t,this.onPlanUpdated=n,this.channel=i,this.validator=o,this.onDisposed=a,this.readyDeferredPromise=ee(),this.isReadyBoolean=!1,this.currentDownload=null,this.errorReceivedBeforeDownloadStart=null,this.logger=new H(`ArtifactDownloadPlanner(${e}/${t})`),this.readyDeferredPromise.promise.catch(()=>{}),this.planValue={nodes:[{type:"artifact",owner:e,name:t,state:"pending",dependencyNodes:[]}],downloadSizeBytes:0},this.channel.onMessage.subscribe(l=>{switch(l.type){case"planReady":{this.isReadyBoolean=!0,this.readyDeferredPromise.resolve(),this.planValue=l.plan;break}case"planUpdated":{this.planValue=l.plan,B(this.logger,"onPlanUpdated",this.onPlanUpdated,[l.plan]);break}case"success":{if(this.currentDownload===null)throw new Error("Unexpected: received success message without a download.");this.currentDownload.downloadFinished();break}case"downloadProgress":{if(this.currentDownload===null)throw new Error("Unexpected: received progress message without a download.");this.currentDownload.progressUpdate(l.update);break}case"startFinalizing":{if(this.currentDownload===null)throw new Error("Unexpected: received startFinalizing message without a download.");this.currentDownload.startFinalizing();break}}}),this.channel.onError.subscribeOnce(l=>{this.currentDownload===null?(this.errorReceivedBeforeDownloadStart=l,this.readyDeferredPromise.reject(l)):this.currentDownload.downloadFailed(l)})}[Symbol.dispose](){this.channel.send({type:"cancel"}),this.onDisposed()}isReady(){return this.isReadyBoolean}async untilReady(){return await this.readyDeferredPromise.promise}getPlan(){return this.planValue}async download(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner","download","opts",JD,e,t);let{onProgress:n,onStartFinalizing:i,signal:o=new AbortController().signal}=e;if(this.currentDownload!==null)throw new Error("You can only call `download` once for each planner.");if(this.errorReceivedBeforeDownloadStart!==null){let u=this.errorReceivedBeforeDownloadStart;throw this.errorReceivedBeforeDownloadStart=null,u}let{promise:a,resolve:l,reject:c}=ee();return this.currentDownload={downloadFinished:()=>{l()},startFinalizing:()=>{B(this.logger,"onStartFinalizing",i,[])},progressUpdate:u=>{B(this.logger,"onProgress",n,[u])},downloadFailed:u=>{c(u)}},this.channel.send({type:"commit"}),o.aborted?this.channel.send({type:"cancel"}):o.addEventListener("abort",()=>{this.channel.send({type:"cancel"})}),await a.catch(u=>{throw o.aborted?o.reason:u})}},YD=s.object({onProgress:s.function().optional(),onStartFinalizing:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),Na=class{constructor(e,t,n,i){this.repositoryPort=e,this.validator=t,this.logger=n,this.data=i,this.quantization=i.quantization,this.name=i.name,this.sizeBytes=i.sizeBytes,this.fitEstimation=this.data.fitEstimation,this.indexedModelIdentifier=this.data.indexedModelIdentifier}isRecommended(){return this.data.recommended??!1}async download(e={}){let t=A(1);this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption","download","opts",YD,e,t);let{promise:n,resolve:i,reject:o}=ee(),a=this.repositoryPort.createChannel("downloadModel",{downloadIdentifier:this.data.downloadIdentifier},c=>{switch(c.type){case"downloadProgress":{B(this.logger,"onProgress",e.onProgress,[c.update]);break}case"startFinalizing":{B(this.logger,"onStartFinalizing",e.onStartFinalizing,[]);break}case"success":{i(c.defaultIdentifier);break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}},{stack:t});a.onError.subscribeOnce(c=>{e.signal?.aborted?o(e.signal.reason):o(c)}),a.onClose.subscribeOnce(()=>{e.signal?.aborted?o(e.signal.reason):o(new Error("Channel closed unexpectedly."))});let l=()=>{a.send({type:"cancel"})};return e.signal?.addEventListener("abort",l),n.finally(()=>{e.signal?.removeEventListener("abort",l)}),await n}},$a=class{constructor(e,t,n,i){this.repositoryPort=e,this.validator=t,this.logger=n,this.data=i,this.name=i.name}isExactMatch(){return this.data.exact??!1}isStaffPick(){return this.data.staffPick??!1}async getDownloadOptions(){let{results:e}=await this.repositoryPort.callRpc("getModelDownloadOptions",{modelSearchResultIdentifier:this.data.identifier});return e.map(t=>new Na(this.repositoryPort,this.validator,this.logger,t))}},QD=s.object({owner:s.string(),name:s.string(),revisionNumber:s.number(),path:s.string(),onProgress:s.function().optional(),onStartFinalizing:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),XD=s.object({path:s.string(),description:s.string().optional(),makePrivate:s.boolean().optional(),writeRevision:s.boolean().optional(),overrides:Se.optional(),onMessage:s.function().optional()}),ew=s.object({onAuthenticationUrl:s.function()}),tw=s.object({keyId:s.string(),publicKey:s.string(),privateKey:s.string()});s.object({userName:s.string()});var rw=s.object({owner:s.string(),name:s.string(),onPlanUpdated:s.function().optional()}),Ua=class{constructor(e,t,n){this.repositoryPort=e,this.validator=t,this.downloadPlanFinalizationRegistry=new FinalizationRegistry(({owner:i,name:o})=>{this.logger.warn(`
353
+ A download plan for artifact ${i}/${o} has been garbage collected without being
354
+ disposed. Please make sure you are creating the download plan with the "using" keyword.
355
+
356
+ This is a memory leak and needs to be fixed.
357
+ `)}),this.logger=new H("Repository",n)}async searchModels(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("repository","search","opts",Vf,e,t);let{results:n}=await this.repositoryPort.callRpc("searchModels",{opts:e},{stack:t});return n.map(i=>new $a(this.repositoryPort,this.validator,this.logger,i))}async installPluginDependencies(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","installPluginDependencies","pluginFolder",s.string(),e,t),await this.repositoryPort.callRpc("installPluginDependencies",{pluginFolder:e},{stack:t})}async downloadArtifact(e){let t=A(1);this.validator.validateMethodParamOrThrow("client.repository","downloadArtifact","opts",QD,e,t);let{owner:n,name:i,revisionNumber:o,path:a,onProgress:l,onStartFinalizing:c,signal:u}=e,{promise:h,resolve:f,reject:d}=ee(),p=this.repositoryPort.createChannel("downloadArtifact",{artifactOwner:n,artifactName:i,revisionNumber:o,path:a},g=>{switch(g.type){case"downloadProgress":{B(this.logger,"onProgress",l,[g.update]);break}case"startFinalizing":{B(this.logger,"onStartFinalizing",c,[]);break}case"success":{f();break}default:{let b=g;throw new Error(`Unexpected message type: ${b}`)}}},{stack:t});p.onError.subscribeOnce(d),p.onClose.subscribeOnce(()=>{u?.aborted?d(u.reason):d(new Error("Channel closed unexpectedly."))});let m=()=>{p.send({type:"cancel"})};return u?.addEventListener("abort",m),h.finally(()=>{u?.removeEventListener("abort",m)}),await h}async pushArtifact(e){let t=A(1),{path:n,description:i,makePrivate:o,writeRevision:a,overrides:l,onMessage:c}=this.validator.validateMethodParamOrThrow("repository","pushArtifact","opts",XD,e,t),u=this.repositoryPort.createChannel("pushArtifact",{path:n,description:i,makePrivate:o,writeRevision:a,overrides:l},p=>{let m=p.type;if(m==="message")B(this.logger,"onMessage",c,[p.message]);else{let g=m;throw new Error(`Unexpected message type: ${g}`)}},{stack:t}),{promise:h,resolve:f,reject:d}=ee();u.onError.subscribeOnce(d),u.onClose.subscribeOnce(f),await h}async getLocalArtifactFileList(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","getLocalArtifactFileList","path",s.string(),e,t);let{fileList:n}=await this.repositoryPort.callRpc("getLocalArtifactFiles",{path:e},{stack:t});return n}async ensureAuthenticated(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","ensureAuthenticated","opts",ew,e,t);let{promise:n,resolve:i,reject:o}=ee();this.repositoryPort.createChannel("ensureAuthenticated",void 0,l=>{let c=l.type;switch(c){case"authenticationUrl":{B(this.logger,"onAuthenticationUrl",e.onAuthenticationUrl,[l.url]);break}case"authenticated":{i();break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}}).onError.subscribeOnce(o),await n}async loginWithPreAuthenticatedKeys(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","loginWithPreAuthenticatedKeys","opts",tw,e,t);let{keyId:n,publicKey:i,privateKey:o}=e,{userName:a}=await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys",{keyId:n,publicKey:i,privateKey:o},{stack:t});return{userName:a}}createArtifactDownloadPlanner(e){let{owner:t,name:n,onPlanUpdated:i}=this.validator.validateMethodParamOrThrow("repository","createArtifactDownloadPlanner","opts",rw,e),o=A(1),a=this.repositoryPort.createChannel("createArtifactDownloadPlan",{owner:t,name:n},void 0,{stack:o}),l=new La(t,n,i,a,this.validator,()=>{this.downloadPlanFinalizationRegistry.unregister(l)});return this.downloadPlanFinalizationRegistry.register(l,{owner:t,name:n},l),l}},nw=s.object({port:s.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),cors:s.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")}),za=class{constructor(e,t,n){this.systemPort=e,this.validator=t,this.logger=new H("System",n)}async listDownloadedModels(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("client.system","listDownloadedModels","domain",s.union([s.literal("llm"),s.literal("embedding"),s.undefined()]),e,t);let n=await this.systemPort.callRpc("listDownloadedModels",void 0,{stack:A(1)});return e===void 0?n:n.filter(i=>i.type===e)}async whenDisconnected(){let e=A(1),t=this.systemPort.createChannel("alive",void 0,void 0,{stack:e}),{promise:n,resolve:i}=ee();t.onError.subscribeOnce(i),t.onClose.subscribeOnce(i),await n}async notify(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("client.system","notify","notification",tf,e,t),await this.systemPort.callRpc("notify",e,{stack:t})}async getLMStudioVersion(){let e=A(1);return await this.systemPort.callRpc("version",void 0,{stack:e})}async unstable_setExperimentFlag(e,t){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("client.system","setExperimentFlag",["flag","value"],[s.string(),s.boolean()],[e,t],n),await this.systemPort.callRpc("setExperimentFlag",{code:e,value:t},{stack:n})}async unstable_getExperimentFlags(){let e=A(1);return await this.systemPort.callRpc("getExperimentFlags",void 0,{stack:e})}async startHttpServer(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("client.system","startHttpServer","args",nw,e),await this.systemPort.callRpc("startHttpServer",{port:e.port,cors:e.cors},{stack:t})}async stopHttpServer(){let e=A(1);return await this.systemPort.callRpc("stopHttpServer",void 0,{stack:e})}},iw=s.object({logger:s.any().optional(),baseUrl:s.string().optional(),verboseErrorMessages:s.boolean().optional(),clientIdentifier:s.string().optional(),clientPasskey:s.string().optional(),disableConnection:s.boolean().optional(),llmPort:s.any().optional(),embeddingPort:s.any().optional(),systemPort:s.any().optional(),diagnosticsPort:s.any().optional(),retrievalPort:s.any().optional(),filesPort:s.any().optional(),repositoryPort:s.any().optional(),pluginsPort:s.any().optional()}).strict(),os=class{validateBaseUrlOrThrow(e){let t;try{t=new URL(e)}catch{this.logger.throw(j`
358
+ Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${e}
359
+ `)}["ws:","wss:"].includes(t.protocol)||this.logger.throw(j`
360
+ Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss".
361
+ Received: ${e}
362
+ `),t.search!==""&&this.logger.throw(j`
363
+ Failed to construct LMStudioClient. The baseUrl passed contains search parameters
364
+ ("${t.search}").
365
+ `),t.hash!==""&&this.logger.throw(j`
366
+ Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${t.hash}").
367
+ `),(t.username!==""||t.password!=="")&&this.logger.throw(j`
368
+ Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We
369
+ do not support these in the baseUrl. Received: ${e}
370
+ `),e.endsWith("/")&&this.logger.throw(j`
371
+ Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
372
+ are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
373
+ ${e}
374
+ `)}async isLocalhostWithGivenPortLMStudioServer(e){let t=await fetch(`http://127.0.0.1:${e}/lmstudio-greeting`);if(t.status!==200)throw new Error("Status is not 200.");if((await t.json())?.lmstudio!==!0)throw new Error("Not an LM Studio server.");return e}async guessBaseUrl(e){if(mh()!==null)return Promise.resolve("Using hosted env");if(Dn.default.browser)try{return this.isLocalhostWithGivenPortLMStudioServer(1234),"ws://127.0.0.1:1234"}catch{j`
375
+ ${I.default.redBright("Failed to connect to LM Studio.")}
376
+
377
+ Is LM Studio running? If not, please start it by running:
378
+
379
+ ${I.default.yellow("lms server start --cors")}
380
+
381
+ If you are attempting to connect to LM Studio on a separate machine, please provide the
382
+ baseUrl option when creating the LMStudioClient:
383
+
384
+ ${I.default.blueBright(j`
385
+ const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });
386
+ `)}
387
+
388
+ ${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
389
+
390
+ ${I.default.gray("https://lmstudio.ai/docs/local-server")}
391
+ `}return Promise.any(xy.map(this.isLocalhostWithGivenPortLMStudioServer)).then(t=>`ws://127.0.0.1:${t}`,()=>{throw pe(j`
392
+ ${I.default.redBright("Failed to connect to LM Studio.")}
393
+
394
+ Please make sure LM Studio is running on your machine.
395
+
396
+ If you are attempting to connect to LM Studio on a separate machine, please provide the
397
+ baseUrl option when creating the LMStudioClient:
398
+
399
+ ${I.default.blueBright(j`
400
+ const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });
401
+ `)}
402
+
403
+ ${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
404
+
405
+ ${I.default.gray("https://lmstudio.ai/docs/local-server")}
406
+ `,e)})}createPort(e,t,n){return SD(n,this.resolvingBaseUrl,e,this.clientIdentifier,this.clientPasskey,new H(t,this.logger),{errorDeserializer:AD,verboseErrorMessage:this.verboseErrorMessages})}constructor(e={}){let{logger:t,baseUrl:n,verboseErrorMessages:i,clientIdentifier:o,clientPasskey:a,disableConnection:l,llmPort:c,embeddingPort:u,systemPort:h,diagnosticsPort:f,retrievalPort:d,filesPort:p,repositoryPort:m,pluginsPort:g}=new Ye().validateConstructorParamOrThrow("LMStudioClient","opts",iw,e);if(globalThis.__LMS_PLUGIN_CONTEXT&&e.baseUrl===void 0)throw new Error(j`
407
+ You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
408
+ the "client" property attached to the Controllers.
409
+
410
+ For example, instead of:
411
+
412
+ ${`const client = new LMStudioClient(); // <-- Error
413
+ export async function generate(ctl: GeneratorController) {
414
+ const model = await client.llm.model(...);
415
+ }`}
416
+
417
+ Do this:
418
+
419
+ ${`export async function generate(ctl: GeneratorController) {
420
+ const model = await ctl.client.llm.model(...);
421
+ }`}
422
+
423
+ If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to
424
+ the LMStudioClient constructor:
425
+
426
+ ${"const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });"}
427
+ `);this.logger=new H("LMStudioClient",t),this.clientIdentifier=o??(0,Qe.generateRandomBase64)(18),this.clientPasskey=a??(0,Qe.generateRandomBase64)(18);let b=A(1);l?this.resolvingBaseUrl=new Promise(()=>{}):n===void 0?this.resolvingBaseUrl=this.guessBaseUrl(i?b:void 0):(this.validateBaseUrlOrThrow(n),this.resolvingBaseUrl=n),this.verboseErrorMessages=i??!0,this.llmPort=c??this.createPort("llm","LLM",gD()),this.embeddingPort=u??this.createPort("embedding","Embedding",pD()),this.systemPort=h??this.createPort("system","System",vD()),this.diagnosticsPort=f??this.createPort("diagnostics","Diagnostics",hD()),this.filesPort=p??this.createPort("files","Files",mD()),this.repositoryPort=m??this.createPort("repository","Repository",bD()),this.pluginsPort=g??this.createPort("plugins","Plugins",yD());let y=new Ye;this.llm=new _a(this,this.llmPort,new H("LLM",this.logger),y),this.embedding=new ga(this,this.embeddingPort,new H("Embedding",this.logger),y),this.system=new za(this.systemPort,y,this.logger),this.diagnostics=new pa(this.diagnosticsPort,y,this.logger),this.files=new ya(this.filesPort,y,this.logger),this.repository=new Ua(this.repositoryPort,y,this.logger),this.plugins=new Ba(this.pluginsPort,this,y,this.logger,t)}async[Symbol.asyncDispose](){await Promise.all([this.llmPort[Symbol.asyncDispose](),this.embeddingPort[Symbol.asyncDispose](),this.systemPort[Symbol.asyncDispose](),this.diagnosticsPort[Symbol.asyncDispose](),this.filesPort[Symbol.asyncDispose](),this.repositoryPort[Symbol.asyncDispose](),this.pluginsPort[Symbol.asyncDispose]()])}};function Rt(r,...e){for(let t of e){let n=r.indexOf(t);if(n!==-1&&r[n+1]&&!r[n+1].startsWith("-"))return r[n+1]}}function _h(r,...e){return e.some(t=>r.includes(t))}function sw(r){let e=Rt(r,"-p","--platform")||process.env.ASKII_PLATFORM||"ollama",t=e==="lmstudio"?"ws://localhost:1234":"http://localhost:11434";return{platform:e,url:Rt(r,"--url")||process.env.ASKII_URL||t,model:Rt(r,"-m","--model")||process.env.ASKII_MODEL||(e==="lmstudio"?"qwen/qwen3-coder-30b":"gemma3:270m"),mode:Rt(r,"--mode")||process.env.ASKII_MODE||"funny",maxRounds:parseInt(Rt(r,"--max-rounds")||process.env.ASKII_MAX_ROUNDS||"5"),yes:_h(r,"-y","--yes")}}async function fs(r,e,t){if(r.platform==="lmstudio"){let i=await new os({baseUrl:r.url}).llm.model(r.model),o=t?[{role:"system",content:t},{role:"user",content:e}]:[{role:"user",content:e}];return(await i.respond(o)).content||"No response"}else return(await new Xr({host:r.url}).generate({model:r.model,system:t,prompt:e,stream:!1})).response||"No response"}async function cl(){return process.stdin.isTTY?null:new Promise(r=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>e+=t),process.stdin.on("end",()=>r(e.trim()||null))})}async function ul(r,e,t){return t?(console.error(`${e} (auto-confirmed)`),!0):new Promise(n=>{r.question(`${e} (y/N) `,i=>n(i.toLowerCase()==="y"))})}function Ch(){console.log(`ASKII CLI ( \u2022_\u2022)>\u2310\u25A0-\u25A0 (\u2310\u25A0_\u25A0)
428
+ AI code assistant for your terminal
429
+
430
+ Usage: askii <command> [options]
431
+
432
+ Commands:
433
+ ask <question> Ask a question about code
434
+ edit <instruction> Edit code and print the result to stdout
435
+ explain <line> Explain a single line of code
436
+ do <task> Agentic task runner \u2014 creates, modifies, and deletes files
437
+
438
+ Options:
439
+ -p, --platform <platform> LLM platform: ollama, lmstudio (default: ollama)
440
+ --url <url> LLM server URL
441
+ -m, --model <model> Model to use
442
+ --mode <mode> Response mode: helpful, funny (default: funny)
443
+ --max-rounds <n> Max agent rounds for "do" (default: 5)
444
+ --dir <path> Working directory for "do" (default: cwd)
445
+ -c, --code <code> Code input (alternative to stdin)
446
+ -y, --yes Auto-confirm all file operations in "do"
447
+ -h, --help Show help
448
+
449
+ Environment variables:
450
+ ASKII_PLATFORM, ASKII_URL, ASKII_MODEL, ASKII_MODE, ASKII_MAX_ROUNDS
451
+
452
+ Examples:
453
+ cat myfile.ts | askii ask "what does this do?"
454
+ cat myfile.ts | askii edit "add error handling"
455
+ askii explain "const x = arr.reduce((a, b) => a + b, 0)"
456
+ askii do "create a Jest test file for src/utils.ts"
457
+ askii do --yes "scaffold a README for this project"
458
+ `)}async function ow(){let r=process.argv.slice(2),e=r[0]||"help",t=r,n=r.filter(o=>!o.startsWith("-"));(_h(t,"-h","--help")||e==="help")&&(Ch(),process.exit(0));let i=sw(t);if(e==="ask"){let o=await cl(),a=Rt(t,"-c","--code")||o,l=n.slice(1).join(" ");l||(console.error("Error: provide a question as an argument"),process.exit(1));let c=a?`Code:
459
+ \`\`\`
460
+ ${a}
461
+ \`\`\`
462
+
463
+ Question: ${l}`:`Question: ${l}`;console.error(`ASKII is thinking... ${Wn()}`);try{let u=await fs(i,c);console.log(`
464
+ ASKII Says: ${gs()}
465
+ `),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let o=await cl(),a=Rt(t,"-c","--code")||o,l=n.slice(1).join(" ");a||(console.error("Error: provide code via stdin or -c/--code"),process.exit(1)),l||(console.error("Error: provide an instruction as an argument"),process.exit(1));let c=`Update this code:
466
+ \`\`\`
467
+ ${a}
468
+ \`\`\`
469
+
470
+ Request: ${l}
471
+
472
+ Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let u=await fs(i,c);u.startsWith("```")&&(u=u.replace(/^```[a-z]*\n?/,"").replace(/\n?```$/,"").trim()),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="explain"){let o=await cl(),a=n.slice(1).join(" ")||o;a||(console.error("Error: provide a line of code as an argument or via stdin"),process.exit(1));let l=i.mode==="helpful",c=l?"You are ASKII, a helpful coding assistant. Provide clear, concise explanations.":"You are ASKII, a witty coding assistant. Provide humorous comments.",u=l?`Explain this code in one sentence: ${a}`:`Make a funny comment about this code in one sentence: ${a}`;console.error(`ASKII is thinking... ${Wn()}`);try{let h=await fs(i,u,c);console.log(h)}catch(h){console.error(`Error: ${h instanceof Error?h.message:"Unknown error"}`),process.exit(1)}}else if(e==="do"){let o=n.slice(1).join(" ");o||(console.error("Error: provide a task as an argument"),process.exit(1));let a=Rt(t,"--dir")||process.cwd();console.error(`ASKII is working... ${Wn()}`);let l=Eh.createInterface({input:process.stdin,output:process.stderr});try{let c=await ms(a),u=0,h=0,f=`You are ASKII, an AI agent that can create, modify, view, and delete files in a workspace.
473
+
474
+ Current workspace structure:
475
+ \`\`\`
476
+ ${c}
477
+ \`\`\`
478
+
479
+ You have access to the following action types:
480
+ - {"type": "view", "path": "path/to/file"} - View file contents
481
+ - {"type": "create", "path": "path/to/file", "content": "file content"}
482
+ - {"type": "modify", "path": "path/to/file", "oldContent": "text to replace", "newContent": "replacement text"}
483
+ - {"type": "delete", "path": "path/to/file"}
484
+
485
+ Always respond with ONLY a valid JSON array containing the actions. You can request to view files to inspect them, and their contents will be sent back to you.`,d=o;for(;h<i.maxRounds;){let p=h===0?`${f}
486
+
487
+ User request: ${d}`:`${f}
488
+
489
+ ${d}`,m=await fs(i,p),g=hl(m);if(g.length===0)break;let b=g.filter(v=>v.type==="view"),y=g.filter(v=>v.type!=="view"),D={};for(let v of b){let S=zn.join(a,v.path);try{D[v.path]=Oe.readFileSync(S,"utf-8")}catch{D[v.path]="Error: Cannot read file"}}for(let v of y){let S=zn.join(a,v.path);if(v.type==="create"){if(await ul(l,`Create file: ${v.path}?`,i.yes)){let k=zn.dirname(S);Oe.existsSync(k)||Oe.mkdirSync(k,{recursive:!0});let x=v.content?Vn(v.content):"";Oe.writeFileSync(S,x),u++,console.error(` \u2713 Created: ${v.path}`)}}else if(v.type==="modify"){if(await ul(l,`Modify file: ${v.path}?`,i.yes))try{let k=Oe.readFileSync(S,"utf-8"),x=v.oldContent?Vn(v.oldContent):"",z=v.newContent?Vn(v.newContent):"";Oe.writeFileSync(S,k.replace(x,z)),u++,console.error(` \u2713 Modified: ${v.path}`)}catch{console.error(` \u2717 Cannot modify: ${v.path}`)}}else if(v.type==="delete"&&await ul(l,`Delete file: ${v.path}? This cannot be undone.`,i.yes))try{Oe.unlinkSync(S),u++,console.error(` \u2713 Deleted: ${v.path}`)}catch{console.error(` \u2717 Cannot delete: ${v.path}`)}}if(Object.keys(D).length>0)d=`File contents retrieved:
490
+ ${JSON.stringify(D,null,2)}
491
+
492
+ Based on these files, what would you like to do next? Respond with only a JSON array of actions or an empty array [] if done.`,h++;else break}l.close(),console.error(`
493
+ Completed ${u} actions! ${gs()}`)}catch(c){l.close(),console.error(`Error: ${c instanceof Error?c.message:"Unknown error"}`),process.exit(1)}}else console.error(`Unknown command: ${e}`),Ch(),process.exit(1)}ow();