Files
StudyDiary-20251025/.obsidian/plugins/tars/main.js
2025-10-08 10:49:47 +08:00

200 lines
445 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Ry=Object.create;var ii=Object.defineProperty;var Ty=Object.getOwnPropertyDescriptor;var Iy=Object.getOwnPropertyNames;var ky=Object.getPrototypeOf,Oy=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),nd=(t,e)=>{for(var r in e)ii(t,r,{get:e[r],enumerable:!0})},sd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Iy(e))!Oy.call(t,s)&&s!==r&&ii(t,s,{get:()=>e[s],enumerable:!(n=Ty(e,s))||n.enumerable});return t};var My=(t,e,r)=>(r=t!=null?Ry(ky(t)):{},sd(e||!t||!t.__esModule?ii(r,"default",{value:t,enumerable:!0}):r,t)),Ly=t=>sd(ii({},"__esModule",{value:!0}),t);var Se=j(Ie=>{"use strict";Ie.__esModule=!0;Ie.extend=Nm;Ie.indexOf=iE;Ie.escapeExpression=aE;Ie.isEmpty=lE;Ie.createFrame=cE;Ie.blockParams=uE;Ie.appendContextPath=fE;var rE={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},nE=/[&<>"'`=]/g,sE=/[&<>"'`=]/;function oE(t){return rE[t]}function Nm(t){for(var e=1;e<arguments.length;e++)for(var r in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],r)&&(t[r]=arguments[e][r]);return t}var sf=Object.prototype.toString;Ie.toString=sf;var nf=function(e){return typeof e=="function"};nf(/x/)&&(Ie.isFunction=nf=function(t){return typeof t=="function"&&sf.call(t)==="[object Function]"});Ie.isFunction=nf;var Dm=Array.isArray||function(t){return t&&typeof t=="object"?sf.call(t)==="[object Array]":!1};Ie.isArray=Dm;function iE(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}function aE(t){if(typeof t!="string"){if(t&&t.toHTML)return t.toHTML();if(t==null)return"";if(!t)return t+"";t=""+t}return sE.test(t)?t.replace(nE,oE):t}function lE(t){return!t&&t!==0?!0:!!(Dm(t)&&t.length===0)}function cE(t){var e=Nm({},t);return e._parent=t,e}function uE(t,e){return t.path=e,t}function fE(t,e){return(t?t+".":"")+e}});var Ue=j((Qa,Bm)=>{"use strict";Qa.__esModule=!0;var of=["description","fileName","lineNumber","endLineNumber","message","name","number","stack"];function af(t,e){var r=e&&e.loc,n=void 0,s=void 0,o=void 0,i=void 0;r&&(n=r.start.line,s=r.end.line,o=r.start.column,i=r.end.column,t+=" - "+n+":"+o);for(var a=Error.prototype.constructor.call(this,t),c=0;c<of.length;c++)this[of[c]]=a[of[c]];Error.captureStackTrace&&Error.captureStackTrace(this,af);try{r&&(this.lineNumber=n,this.endLineNumber=s,Object.defineProperty?(Object.defineProperty(this,"column",{value:o,enumerable:!0}),Object.defineProperty(this,"endColumn",{value:i,enumerable:!0})):(this.column=o,this.endColumn=i))}catch(l){}}af.prototype=new Error;Qa.default=af;Bm.exports=Qa.default});var qm=j((Za,Fm)=>{"use strict";Za.__esModule=!0;var lf=Se();Za.default=function(t){t.registerHelper("blockHelperMissing",function(e,r){var n=r.inverse,s=r.fn;if(e===!0)return s(this);if(e===!1||e==null)return n(this);if(lf.isArray(e))return e.length>0?(r.ids&&(r.ids=[r.name]),t.helpers.each(e,r)):n(this);if(r.data&&r.ids){var o=lf.createFrame(r.data);o.contextPath=lf.appendContextPath(r.data.contextPath,r.name),r={data:o}}return s(e,r)})};Fm.exports=Za.default});var $m=j((el,Um)=>{"use strict";el.__esModule=!0;function dE(t){return t&&t.__esModule?t:{default:t}}var Ko=Se(),hE=Ue(),pE=dE(hE);el.default=function(t){t.registerHelper("each",function(e,r){if(!r)throw new pE.default("Must pass iterator to #each");var n=r.fn,s=r.inverse,o=0,i="",a=void 0,c=void 0;r.data&&r.ids&&(c=Ko.appendContextPath(r.data.contextPath,r.ids[0])+"."),Ko.isFunction(e)&&(e=e.call(this)),r.data&&(a=Ko.createFrame(r.data));function l(p,y,g){a&&(a.key=p,a.index=y,a.first=y===0,a.last=!!g,c&&(a.contextPath=c+p)),i=i+n(e[p],{data:a,blockParams:Ko.blockParams([e[p],p],[c+p,null])})}if(e&&typeof e=="object")if(Ko.isArray(e))for(var f=e.length;o<f;o++)o in e&&l(o,o,o===e.length-1);else if(typeof Symbol=="function"&&e[Symbol.iterator]){for(var u=[],d=e[Symbol.iterator](),h=d.next();!h.done;h=d.next())u.push(h.value);e=u;for(var f=e.length;o<f;o++)l(o,o,o===e.length-1)}else(function(){var p=void 0;Object.keys(e).forEach(function(y){p!==void 0&&l(p,o-1),p=y,o++}),p!==void 0&&l(p,o-1,!0)})();return o===0&&(i=s(this)),i})};Um.exports=el.default});var jm=j((tl,Hm)=>{"use strict";tl.__esModule=!0;function mE(t){return t&&t.__esModule?t:{default:t}}var gE=Ue(),yE=mE(gE);tl.default=function(t){t.registerHelper("helperMissing",function(){if(arguments.length!==1)throw new yE.default('Missing helper: "'+arguments[arguments.length-1].name+'"')})};Hm.exports=tl.default});var Gm=j((rl,Km)=>{"use strict";rl.__esModule=!0;function bE(t){return t&&t.__esModule?t:{default:t}}var Wm=Se(),wE=Ue(),Vm=bE(wE);rl.default=function(t){t.registerHelper("if",function(e,r){if(arguments.length!=2)throw new Vm.default("#if requires exactly one argument");return Wm.isFunction(e)&&(e=e.call(this)),!r.hash.includeZero&&!e||Wm.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,r){if(arguments.length!=2)throw new Vm.default("#unless requires exactly one argument");return t.helpers.if.call(this,e,{fn:r.inverse,inverse:r.fn,hash:r.hash})})};Km.exports=rl.default});var zm=j((nl,Jm)=>{"use strict";nl.__esModule=!0;nl.default=function(t){t.registerHelper("log",function(){for(var e=[void 0],r=arguments[arguments.length-1],n=0;n<arguments.length-1;n++)e.push(arguments[n]);var s=1;r.hash.level!=null?s=r.hash.level:r.data&&r.data.level!=null&&(s=r.data.level),e[0]=s,t.log.apply(t,e)})};Jm.exports=nl.default});var Ym=j((sl,Xm)=>{"use strict";sl.__esModule=!0;sl.default=function(t){t.registerHelper("lookup",function(e,r,n){return e&&n.lookupProperty(e,r)})};Xm.exports=sl.default});var Zm=j((ol,Qm)=>{"use strict";ol.__esModule=!0;function _E(t){return t&&t.__esModule?t:{default:t}}var Go=Se(),SE=Ue(),xE=_E(SE);ol.default=function(t){t.registerHelper("with",function(e,r){if(arguments.length!=2)throw new xE.default("#with requires exactly one argument");Go.isFunction(e)&&(e=e.call(this));var n=r.fn;if(Go.isEmpty(e))return r.inverse(this);var s=r.data;return r.data&&r.ids&&(s=Go.createFrame(r.data),s.contextPath=Go.appendContextPath(r.data.contextPath,r.ids[0])),n(e,{data:s,blockParams:Go.blockParams([e],[s&&s.contextPath])})})};Qm.exports=ol.default});var cf=j(il=>{"use strict";il.__esModule=!0;il.registerDefaultHelpers=BE;il.moveHelperToHooks=FE;function Yr(t){return t&&t.__esModule?t:{default:t}}var EE=qm(),AE=Yr(EE),vE=$m(),CE=Yr(vE),PE=jm(),RE=Yr(PE),TE=Gm(),IE=Yr(TE),kE=zm(),OE=Yr(kE),ME=Ym(),LE=Yr(ME),NE=Zm(),DE=Yr(NE);function BE(t){AE.default(t),CE.default(t),RE.default(t),IE.default(t),OE.default(t),LE.default(t),DE.default(t)}function FE(t,e,r){t.helpers[e]&&(t.hooks[e]=t.helpers[e],r||delete t.helpers[e])}});var tg=j((al,eg)=>{"use strict";al.__esModule=!0;var qE=Se();al.default=function(t){t.registerDecorator("inline",function(e,r,n,s){var o=e;return r.partials||(r.partials={},o=function(i,a){var c=n.partials;n.partials=qE.extend({},c,r.partials);var l=e(i,a);return n.partials=c,l}),r.partials[s.args[0]]=s.fn,o})};eg.exports=al.default});var rg=j(uf=>{"use strict";uf.__esModule=!0;uf.registerDefaultDecorators=jE;function UE(t){return t&&t.__esModule?t:{default:t}}var $E=tg(),HE=UE($E);function jE(t){HE.default(t)}});var ff=j((ll,ng)=>{"use strict";ll.__esModule=!0;var WE=Se(),vs={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(e){if(typeof e=="string"){var r=WE.indexOf(vs.methodMap,e.toLowerCase());r>=0?e=r:e=parseInt(e,10)}return e},log:function(e){if(e=vs.lookupLevel(e),typeof console!="undefined"&&vs.lookupLevel(vs.level)<=e){var r=vs.methodMap[e];console[r]||(r="log");for(var n=arguments.length,s=Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];console[r].apply(console,s)}}};ll.default=vs;ng.exports=ll.default});var sg=j(df=>{"use strict";df.__esModule=!0;df.createNewLookupObject=KE;var VE=Se();function KE(){for(var t=arguments.length,e=Array(t),r=0;r<t;r++)e[r]=arguments[r];return VE.extend.apply(void 0,[Object.create(null)].concat(e))}});var hf=j(Jo=>{"use strict";Jo.__esModule=!0;Jo.createProtoAccessControl=XE;Jo.resultIsAllowed=YE;Jo.resetLoggedProperties=ZE;function GE(t){return t&&t.__esModule?t:{default:t}}var og=sg(),JE=ff(),zE=GE(JE),cl=Object.create(null);function XE(t){var e=Object.create(null);e.constructor=!1,e.__defineGetter__=!1,e.__defineSetter__=!1,e.__lookupGetter__=!1;var r=Object.create(null);return r.__proto__=!1,{properties:{whitelist:og.createNewLookupObject(r,t.allowedProtoProperties),defaultValue:t.allowProtoPropertiesByDefault},methods:{whitelist:og.createNewLookupObject(e,t.allowedProtoMethods),defaultValue:t.allowProtoMethodsByDefault}}}function YE(t,e,r){return ig(typeof t=="function"?e.methods:e.properties,r)}function ig(t,e){return t.whitelist[e]!==void 0?t.whitelist[e]===!0:t.defaultValue!==void 0?t.defaultValue:(QE(e),!1)}function QE(t){cl[t]!==!0&&(cl[t]=!0,zE.default.log("error",'Handlebars: Access has been denied to resolve the property "'+t+`" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`))}function ZE(){Object.keys(cl).forEach(function(t){delete cl[t]})}});var fl=j(bt=>{"use strict";bt.__esModule=!0;bt.HandlebarsEnvironment=gf;function ag(t){return t&&t.__esModule?t:{default:t}}var Qr=Se(),e2=Ue(),pf=ag(e2),t2=cf(),r2=rg(),n2=ff(),ul=ag(n2),s2=hf(),o2="4.7.8";bt.VERSION=o2;var i2=8;bt.COMPILER_REVISION=i2;var a2=7;bt.LAST_COMPATIBLE_COMPILER_REVISION=a2;var l2={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};bt.REVISION_CHANGES=l2;var mf="[object Object]";function gf(t,e,r){this.helpers=t||{},this.partials=e||{},this.decorators=r||{},t2.registerDefaultHelpers(this),r2.registerDefaultDecorators(this)}gf.prototype={constructor:gf,logger:ul.default,log:ul.default.log,registerHelper:function(e,r){if(Qr.toString.call(e)===mf){if(r)throw new pf.default("Arg not supported with multiple helpers");Qr.extend(this.helpers,e)}else this.helpers[e]=r},unregisterHelper:function(e){delete this.helpers[e]},registerPartial:function(e,r){if(Qr.toString.call(e)===mf)Qr.extend(this.partials,e);else{if(typeof r=="undefined")throw new pf.default('Attempting to register a partial called "'+e+'" as undefined');this.partials[e]=r}},unregisterPartial:function(e){delete this.partials[e]},registerDecorator:function(e,r){if(Qr.toString.call(e)===mf){if(r)throw new pf.default("Arg not supported with multiple decorators");Qr.extend(this.decorators,e)}else this.decorators[e]=r},unregisterDecorator:function(e){delete this.decorators[e]},resetLoggedPropertyAccesses:function(){s2.resetLoggedProperties()}};var c2=ul.default.log;bt.log=c2;bt.createFrame=Qr.createFrame;bt.logger=ul.default});var cg=j((dl,lg)=>{"use strict";dl.__esModule=!0;function yf(t){this.string=t}yf.prototype.toString=yf.prototype.toHTML=function(){return""+this.string};dl.default=yf;lg.exports=dl.default});var ug=j(bf=>{"use strict";bf.__esModule=!0;bf.wrapHelper=u2;function u2(t,e){if(typeof t!="function")return t;var r=function(){var s=arguments[arguments.length-1];return arguments[arguments.length-1]=e(s),t.apply(this,arguments)};return r}});var mg=j(cr=>{"use strict";cr.__esModule=!0;cr.checkRevision=g2;cr.template=y2;cr.wrapProgram=hl;cr.resolvePartial=b2;cr.invokePartial=w2;cr.noop=hg;function f2(t){return t&&t.__esModule?t:{default:t}}function d2(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}var h2=Se(),Lt=d2(h2),p2=Ue(),Nt=f2(p2),Dt=fl(),fg=cf(),m2=ug(),dg=hf();function g2(t){var e=t&&t[0]||1,r=Dt.COMPILER_REVISION;if(!(e>=Dt.LAST_COMPATIBLE_COMPILER_REVISION&&e<=Dt.COMPILER_REVISION))if(e<Dt.LAST_COMPATIBLE_COMPILER_REVISION){var n=Dt.REVISION_CHANGES[r],s=Dt.REVISION_CHANGES[e];throw new Nt.default("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+n+") or downgrade your runtime to an older version ("+s+").")}else throw new Nt.default("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+t[1]+").")}function y2(t,e){if(!e)throw new Nt.default("No environment passed to template");if(!t||!t.main)throw new Nt.default("Unknown template object: "+typeof t);t.main.decorator=t.main_d,e.VM.checkRevision(t.compiler);var r=t.compiler&&t.compiler[0]===7;function n(i,a,c){c.hash&&(a=Lt.extend({},a,c.hash),c.ids&&(c.ids[0]=!0)),i=e.VM.resolvePartial.call(this,i,a,c);var l=Lt.extend({},c,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),f=e.VM.invokePartial.call(this,i,a,l);if(f==null&&e.compile&&(c.partials[c.name]=e.compile(i,t.compilerOptions,e),f=c.partials[c.name](a,l)),f!=null){if(c.indent){for(var u=f.split(`
`),d=0,h=u.length;d<h&&!(!u[d]&&d+1===h);d++)u[d]=c.indent+u[d];f=u.join(`
`)}return f}else throw new Nt.default("The partial "+c.name+" could not be compiled when running in runtime-only mode")}var s={strict:function(a,c,l){if(!a||!(c in a))throw new Nt.default('"'+c+'" not defined in '+a,{loc:l});return s.lookupProperty(a,c)},lookupProperty:function(a,c){var l=a[c];if(l==null||Object.prototype.hasOwnProperty.call(a,c)||dg.resultIsAllowed(l,s.protoAccessControl,c))return l},lookup:function(a,c){for(var l=a.length,f=0;f<l;f++){var u=a[f]&&s.lookupProperty(a[f],c);if(u!=null)return a[f][c]}},lambda:function(a,c){return typeof a=="function"?a.call(c):a},escapeExpression:Lt.escapeExpression,invokePartial:n,fn:function(a){var c=t[a];return c.decorator=t[a+"_d"],c},programs:[],program:function(a,c,l,f,u){var d=this.programs[a],h=this.fn(a);return c||u||f||l?d=hl(this,a,h,c,l,f,u):d||(d=this.programs[a]=hl(this,a,h)),d},data:function(a,c){for(;a&&c--;)a=a._parent;return a},mergeIfNeeded:function(a,c){var l=a||c;return a&&c&&a!==c&&(l=Lt.extend({},c,a)),l},nullContext:Object.seal({}),noop:e.VM.noop,compilerInfo:t.compiler};function o(i){var a=arguments.length<=1||arguments[1]===void 0?{}:arguments[1],c=a.data;o._setup(a),!a.partial&&t.useData&&(c=_2(i,c));var l=void 0,f=t.useBlockParams?[]:void 0;t.useDepths&&(a.depths?l=i!=a.depths[0]?[i].concat(a.depths):a.depths:l=[i]);function u(d){return""+t.main(s,d,s.helpers,s.partials,c,f,l)}return u=pg(t.main,u,s,a.depths||[],c,f),u(i,a)}return o.isTop=!0,o._setup=function(i){if(i.partial)s.protoAccessControl=i.protoAccessControl,s.helpers=i.helpers,s.partials=i.partials,s.decorators=i.decorators,s.hooks=i.hooks;else{var a=Lt.extend({},e.helpers,i.helpers);S2(a,s),s.helpers=a,t.usePartial&&(s.partials=s.mergeIfNeeded(i.partials,e.partials)),(t.usePartial||t.useDecorators)&&(s.decorators=Lt.extend({},e.decorators,i.decorators)),s.hooks={},s.protoAccessControl=dg.createProtoAccessControl(i);var c=i.allowCallsToHelperMissing||r;fg.moveHelperToHooks(s,"helperMissing",c),fg.moveHelperToHooks(s,"blockHelperMissing",c)}},o._child=function(i,a,c,l){if(t.useBlockParams&&!c)throw new Nt.default("must pass block params");if(t.useDepths&&!l)throw new Nt.default("must pass parent depths");return hl(s,i,t[i],a,0,c,l)},o}function hl(t,e,r,n,s,o,i){function a(c){var l=arguments.length<=1||arguments[1]===void 0?{}:arguments[1],f=i;return i&&c!=i[0]&&!(c===t.nullContext&&i[0]===null)&&(f=[c].concat(i)),r(t,c,t.helpers,t.partials,l.data||n,o&&[l.blockParams].concat(o),f)}return a=pg(r,a,t,i,n,o),a.program=e,a.depth=i?i.length:0,a.blockParams=s||0,a}function b2(t,e,r){return t?!t.call&&!r.name&&(r.name=t,t=r.partials[t]):r.name==="@partial-block"?t=r.data["partial-block"]:t=r.partials[r.name],t}function w2(t,e,r){var n=r.data&&r.data["partial-block"];r.partial=!0,r.ids&&(r.data.contextPath=r.ids[0]||r.data.contextPath);var s=void 0;if(r.fn&&r.fn!==hg&&function(){r.data=Dt.createFrame(r.data);var o=r.fn;s=r.data["partial-block"]=function(a){var c=arguments.length<=1||arguments[1]===void 0?{}:arguments[1];return c.data=Dt.createFrame(c.data),c.data["partial-block"]=n,o(a,c)},o.partials&&(r.partials=Lt.extend({},r.partials,o.partials))}(),t===void 0&&s&&(t=s),t===void 0)throw new Nt.default("The partial "+r.name+" could not be found");if(t instanceof Function)return t(e,r)}function hg(){return""}function _2(t,e){return(!e||!("root"in e))&&(e=e?Dt.createFrame(e):{},e.root=t),e}function pg(t,e,r,n,s,o){if(t.decorator){var i={};e=t.decorator(e,i,r,n&&n[0],s,o,n),Lt.extend(e,i)}return e}function S2(t,e){Object.keys(t).forEach(function(r){var n=t[r];t[r]=x2(n,e)})}function x2(t,e){var r=e.lookupProperty;return m2.wrapHelper(t,function(n){return Lt.extend({lookupProperty:r},n)})}});var wf=j((pl,gg)=>{"use strict";pl.__esModule=!0;pl.default=function(t){(function(){typeof globalThis!="object"&&(Object.prototype.__defineGetter__("__magic__",function(){return this}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__)})();var e=globalThis.Handlebars;t.noConflict=function(){return globalThis.Handlebars===t&&(globalThis.Handlebars=e),t}};gg.exports=pl.default});var Sg=j((ml,_g)=>{"use strict";ml.__esModule=!0;function Sf(t){return t&&t.__esModule?t:{default:t}}function xf(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}var E2=fl(),yg=xf(E2),A2=cg(),v2=Sf(A2),C2=Ue(),P2=Sf(C2),R2=Se(),_f=xf(R2),T2=mg(),bg=xf(T2),I2=wf(),k2=Sf(I2);function wg(){var t=new yg.HandlebarsEnvironment;return _f.extend(t,yg),t.SafeString=v2.default,t.Exception=P2.default,t.Utils=_f,t.escapeExpression=_f.escapeExpression,t.VM=bg,t.template=function(e){return bg.template(e,t)},t}var zo=wg();zo.create=wg;k2.default(zo);zo.default=zo;ml.default=zo;_g.exports=ml.default});var Ef=j((gl,Eg)=>{"use strict";gl.__esModule=!0;var xg={helpers:{helperExpression:function(e){return e.type==="SubExpression"||(e.type==="MustacheStatement"||e.type==="BlockStatement")&&!!(e.params&&e.params.length||e.hash)},scopedId:function(e){return/^\.|this\b/.test(e.original)},simpleId:function(e){return e.parts.length===1&&!xg.helpers.scopedId(e)&&!e.depth}}};gl.default=xg;Eg.exports=gl.default});var vg=j((yl,Ag)=>{"use strict";yl.__esModule=!0;var O2=function(){var t={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(s,o,i,a,c,l,f){var u=l.length-1;switch(c){case 1:return l[u-1];case 2:this.$=a.prepareProgram(l[u]);break;case 3:this.$=l[u];break;case 4:this.$=l[u];break;case 5:this.$=l[u];break;case 6:this.$=l[u];break;case 7:this.$=l[u];break;case 8:this.$=l[u];break;case 9:this.$={type:"CommentStatement",value:a.stripComment(l[u]),strip:a.stripFlags(l[u],l[u]),loc:a.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:l[u],value:l[u],loc:a.locInfo(this._$)};break;case 11:this.$=a.prepareRawBlock(l[u-2],l[u-1],l[u],this._$);break;case 12:this.$={path:l[u-3],params:l[u-2],hash:l[u-1]};break;case 13:this.$=a.prepareBlock(l[u-3],l[u-2],l[u-1],l[u],!1,this._$);break;case 14:this.$=a.prepareBlock(l[u-3],l[u-2],l[u-1],l[u],!0,this._$);break;case 15:this.$={open:l[u-5],path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 16:this.$={path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 17:this.$={path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 18:this.$={strip:a.stripFlags(l[u-1],l[u-1]),program:l[u]};break;case 19:var d=a.prepareBlock(l[u-2],l[u-1],l[u],l[u],!1,this._$),h=a.prepareProgram([d],l[u-1].loc);h.chained=!0,this.$={strip:l[u-2].strip,program:h,chain:!0};break;case 20:this.$=l[u];break;case 21:this.$={path:l[u-1],strip:a.stripFlags(l[u-2],l[u])};break;case 22:this.$=a.prepareMustache(l[u-3],l[u-2],l[u-1],l[u-4],a.stripFlags(l[u-4],l[u]),this._$);break;case 23:this.$=a.prepareMustache(l[u-3],l[u-2],l[u-1],l[u-4],a.stripFlags(l[u-4],l[u]),this._$);break;case 24:this.$={type:"PartialStatement",name:l[u-3],params:l[u-2],hash:l[u-1],indent:"",strip:a.stripFlags(l[u-4],l[u]),loc:a.locInfo(this._$)};break;case 25:this.$=a.preparePartialBlock(l[u-2],l[u-1],l[u],this._$);break;case 26:this.$={path:l[u-3],params:l[u-2],hash:l[u-1],strip:a.stripFlags(l[u-4],l[u])};break;case 27:this.$=l[u];break;case 28:this.$=l[u];break;case 29:this.$={type:"SubExpression",path:l[u-3],params:l[u-2],hash:l[u-1],loc:a.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:l[u],loc:a.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:a.id(l[u-2]),value:l[u],loc:a.locInfo(this._$)};break;case 32:this.$=a.id(l[u-1]);break;case 33:this.$=l[u];break;case 34:this.$=l[u];break;case 35:this.$={type:"StringLiteral",value:l[u],original:l[u],loc:a.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(l[u]),original:Number(l[u]),loc:a.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:l[u]==="true",original:l[u]==="true",loc:a.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:a.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:a.locInfo(this._$)};break;case 40:this.$=l[u];break;case 41:this.$=l[u];break;case 42:this.$=a.preparePath(!0,l[u],this._$);break;case 43:this.$=a.preparePath(!1,l[u],this._$);break;case 44:l[u-2].push({part:a.id(l[u]),original:l[u],separator:l[u-1]}),this.$=l[u-2];break;case 45:this.$=[{part:a.id(l[u]),original:l[u]}];break;case 46:this.$=[];break;case 47:l[u-1].push(l[u]);break;case 48:this.$=[];break;case 49:l[u-1].push(l[u]);break;case 50:this.$=[];break;case 51:l[u-1].push(l[u]);break;case 58:this.$=[];break;case 59:l[u-1].push(l[u]);break;case 64:this.$=[];break;case 65:l[u-1].push(l[u]);break;case 70:this.$=[];break;case 71:l[u-1].push(l[u]);break;case 78:this.$=[];break;case 79:l[u-1].push(l[u]);break;case 82:this.$=[];break;case 83:l[u-1].push(l[u]);break;case 86:this.$=[];break;case 87:l[u-1].push(l[u]);break;case 90:this.$=[];break;case 91:l[u-1].push(l[u]);break;case 94:this.$=[];break;case 95:l[u-1].push(l[u]);break;case 98:this.$=[l[u]];break;case 99:l[u-1].push(l[u]);break;case 100:this.$=[l[u]];break;case 101:l[u-1].push(l[u]);break}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},parseError:function(s,o){throw new Error(s)},parse:function(s){var o=this,i=[0],a=[null],c=[],l=this.table,f="",u=0,d=0,h=0,p=2,y=1;this.lexer.setInput(s),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,typeof this.lexer.yylloc=="undefined"&&(this.lexer.yylloc={});var g=this.lexer.yylloc;c.push(g);var S=this.lexer.options&&this.lexer.options.ranges;typeof this.yy.parseError=="function"&&(this.parseError=this.yy.parseError);function _(Oe){i.length=i.length-2*Oe,a.length=a.length-Oe,c.length=c.length-Oe}function v(){var Oe;return Oe=o.lexer.lex()||1,typeof Oe!="number"&&(Oe=o.symbols_[Oe]||Oe),Oe}for(var C,x,P,k,O,F,q={},V,H,ee,xe;;){if(P=i[i.length-1],this.defaultActions[P]?k=this.defaultActions[P]:((C===null||typeof C=="undefined")&&(C=v()),k=l[P]&&l[P][C]),typeof k=="undefined"||!k.length||!k[0]){var ue="";if(!h){xe=[];for(V in l[P])this.terminals_[V]&&V>2&&xe.push("'"+this.terminals_[V]+"'");this.lexer.showPosition?ue="Parse error on line "+(u+1)+`:
`+this.lexer.showPosition()+`
Expecting `+xe.join(", ")+", got '"+(this.terminals_[C]||C)+"'":ue="Parse error on line "+(u+1)+": Unexpected "+(C==1?"end of input":"'"+(this.terminals_[C]||C)+"'"),this.parseError(ue,{text:this.lexer.match,token:this.terminals_[C]||C,line:this.lexer.yylineno,loc:g,expected:xe})}}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+P+", token: "+C);switch(k[0]){case 1:i.push(C),a.push(this.lexer.yytext),c.push(this.lexer.yylloc),i.push(k[1]),C=null,x?(C=x,x=null):(d=this.lexer.yyleng,f=this.lexer.yytext,u=this.lexer.yylineno,g=this.lexer.yylloc,h>0&&h--);break;case 2:if(H=this.productions_[k[1]][1],q.$=a[a.length-H],q._$={first_line:c[c.length-(H||1)].first_line,last_line:c[c.length-1].last_line,first_column:c[c.length-(H||1)].first_column,last_column:c[c.length-1].last_column},S&&(q._$.range=[c[c.length-(H||1)].range[0],c[c.length-1].range[1]]),F=this.performAction.call(q,f,d,u,this.yy,k[1],a,c),typeof F!="undefined")return F;H&&(i=i.slice(0,-1*H*2),a=a.slice(0,-1*H),c=c.slice(0,-1*H)),i.push(this.productions_[k[1]][0]),a.push(q.$),c.push(q._$),ee=l[i[i.length-2]][i[i.length-1]],i.push(ee);break;case 3:return!0}}return!0}},e=function(){var n={EOF:1,parseError:function(o,i){if(this.yy.parser)this.yy.parser.parseError(o,i);else throw new Error(o)},setInput:function(o){return this._input=o,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var o=this._input[0];this.yytext+=o,this.yyleng++,this.offset++,this.match+=o,this.matched+=o;var i=o.match(/(?:\r\n?|\n).*/g);return i?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),o},unput:function(o){var i=o.length,a=o.split(/(?:\r\n?|\n)/g);this._input=o+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-i-1),this.offset-=i;var c=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),a.length-1&&(this.yylineno-=a.length-1);var l=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:a?(a.length===c.length?this.yylloc.first_column:0)+c[c.length-a.length].length-a[0].length:this.yylloc.first_column-i},this.options.ranges&&(this.yylloc.range=[l[0],l[0]+this.yyleng-i]),this},more:function(){return this._more=!0,this},less:function(o){this.unput(this.match.slice(o))},pastInput:function(){var o=this.matched.substr(0,this.matched.length-this.match.length);return(o.length>20?"...":"")+o.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var o=this.match;return o.length<20&&(o+=this._input.substr(0,20-o.length)),(o.substr(0,20)+(o.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var o=this.pastInput(),i=new Array(o.length+1).join("-");return o+this.upcomingInput()+`
`+i+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var o,i,a,c,l,f;this._more||(this.yytext="",this.match="");for(var u=this._currentRules(),d=0;d<u.length&&(a=this._input.match(this.rules[u[d]]),!(a&&(!i||a[0].length>i[0].length)&&(i=a,c=d,!this.options.flex)));d++);return i?(f=i[0].match(/(?:\r\n?|\n).*/g),f&&(this.yylineno+=f.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:f?f[f.length-1].length-f[f.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+i[0].length},this.yytext+=i[0],this.match+=i[0],this.matches=i,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(i[0].length),this.matched+=i[0],o=this.performAction.call(this,this.yy,this,u[c],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),o||void 0):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text.
`+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var o=this.next();return typeof o!="undefined"?o:this.lex()},begin:function(o){this.conditionStack.push(o)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(o){this.begin(o)}};return n.options={},n.performAction=function(o,i,a,c){function l(u,d){return i.yytext=i.yytext.substring(u,i.yyleng-d+u)}var f=c;switch(a){case 0:if(i.yytext.slice(-2)==="\\\\"?(l(0,1),this.begin("mu")):i.yytext.slice(-1)==="\\"?(l(0,1),this.begin("emu")):this.begin("mu"),i.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;break;case 3:return this.begin("raw"),15;break;case 4:return this.popState(),this.conditionStack[this.conditionStack.length-1]==="raw"?15:(l(5,9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;break;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;break;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;break;case 16:return this.popState(),44;break;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(i.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;break;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;break;case 30:return this.popState(),33;break;case 31:return i.yytext=l(1,2).replace(/\\"/g,'"'),80;break;case 32:return i.yytext=l(1,2).replace(/\\'/g,"'"),80;break;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return i.yytext=i.yytext.replace(/\\([\\\]])/g,"$1"),72;break;case 43:return"INVALID";case 44:return 5}},n.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]+?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],n.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},n}();t.lexer=e;function r(){this.yy={}}return r.prototype=t,t.Parser=r,new r}();yl.default=O2;Ag.exports=yl.default});var vf=j((_l,Rg)=>{"use strict";_l.__esModule=!0;function M2(t){return t&&t.__esModule?t:{default:t}}var L2=Ue(),Af=M2(L2);function bl(){this.parents=[]}bl.prototype={constructor:bl,mutating:!1,acceptKey:function(e,r){var n=this.accept(e[r]);if(this.mutating){if(n&&!bl.prototype[n.type])throw new Af.default('Unexpected node type "'+n.type+'" found when accepting '+r+" on "+e.type);e[r]=n}},acceptRequired:function(e,r){if(this.acceptKey(e,r),!e[r])throw new Af.default(e.type+" requires "+r)},acceptArray:function(e){for(var r=0,n=e.length;r<n;r++)this.acceptKey(e,r),e[r]||(e.splice(r,1),r--,n--)},accept:function(e){if(e){if(!this[e.type])throw new Af.default("Unknown type: "+e.type,e);this.current&&this.parents.unshift(this.current),this.current=e;var r=this[e.type](e);if(this.current=this.parents.shift(),!this.mutating||r)return r;if(r!==!1)return e}},Program:function(e){this.acceptArray(e.body)},MustacheStatement:wl,Decorator:wl,BlockStatement:Cg,DecoratorBlock:Cg,PartialStatement:Pg,PartialBlockStatement:function(e){Pg.call(this,e),this.acceptKey(e,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:wl,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(e){this.acceptArray(e.pairs)},HashPair:function(e){this.acceptRequired(e,"value")}};function wl(t){this.acceptRequired(t,"path"),this.acceptArray(t.params),this.acceptKey(t,"hash")}function Cg(t){wl.call(this,t),this.acceptKey(t,"program"),this.acceptKey(t,"inverse")}function Pg(t){this.acceptRequired(t,"name"),this.acceptArray(t.params),this.acceptKey(t,"hash")}_l.default=bl;Rg.exports=_l.default});var Ig=j((Sl,Tg)=>{"use strict";Sl.__esModule=!0;function N2(t){return t&&t.__esModule?t:{default:t}}var D2=vf(),B2=N2(D2);function wt(){var t=arguments.length<=0||arguments[0]===void 0?{}:arguments[0];this.options=t}wt.prototype=new B2.default;wt.prototype.Program=function(t){var e=!this.options.ignoreStandalone,r=!this.isRootSeen;this.isRootSeen=!0;for(var n=t.body,s=0,o=n.length;s<o;s++){var i=n[s],a=this.accept(i);if(a){var c=Cf(n,s,r),l=Pf(n,s,r),f=a.openStandalone&&c,u=a.closeStandalone&&l,d=a.inlineStandalone&&c&&l;a.close&&Zr(n,s,!0),a.open&&ur(n,s,!0),e&&d&&(Zr(n,s),ur(n,s)&&i.type==="PartialStatement"&&(i.indent=/([ \t]+$)/.exec(n[s-1].original)[1])),e&&f&&(Zr((i.program||i.inverse).body),ur(n,s)),e&&u&&(Zr(n,s),ur((i.inverse||i.program).body))}}return t};wt.prototype.BlockStatement=wt.prototype.DecoratorBlock=wt.prototype.PartialBlockStatement=function(t){this.accept(t.program),this.accept(t.inverse);var e=t.program||t.inverse,r=t.program&&t.inverse,n=r,s=r;if(r&&r.chained)for(n=r.body[0].program;s.chained;)s=s.body[s.body.length-1].program;var o={open:t.openStrip.open,close:t.closeStrip.close,openStandalone:Pf(e.body),closeStandalone:Cf((n||e).body)};if(t.openStrip.close&&Zr(e.body,null,!0),r){var i=t.inverseStrip;i.open&&ur(e.body,null,!0),i.close&&Zr(n.body,null,!0),t.closeStrip.open&&ur(s.body,null,!0),!this.options.ignoreStandalone&&Cf(e.body)&&Pf(n.body)&&(ur(e.body),Zr(n.body))}else t.closeStrip.open&&ur(e.body,null,!0);return o};wt.prototype.Decorator=wt.prototype.MustacheStatement=function(t){return t.strip};wt.prototype.PartialStatement=wt.prototype.CommentStatement=function(t){var e=t.strip||{};return{inlineStandalone:!0,open:e.open,close:e.close}};function Cf(t,e,r){e===void 0&&(e=t.length);var n=t[e-1],s=t[e-2];if(!n)return r;if(n.type==="ContentStatement")return(s||!r?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(n.original)}function Pf(t,e,r){e===void 0&&(e=-1);var n=t[e+1],s=t[e+2];if(!n)return r;if(n.type==="ContentStatement")return(s||!r?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(n.original)}function Zr(t,e,r){var n=t[e==null?0:e+1];if(!(!n||n.type!=="ContentStatement"||!r&&n.rightStripped)){var s=n.value;n.value=n.value.replace(r?/^\s+/:/^[ \t]*\r?\n?/,""),n.rightStripped=n.value!==s}}function ur(t,e,r){var n=t[e==null?t.length-1:e-1];if(!(!n||n.type!=="ContentStatement"||!r&&n.leftStripped)){var s=n.value;return n.value=n.value.replace(r?/\s+$/:/[ \t]+$/,""),n.leftStripped=n.value!==s,n.leftStripped}}Sl.default=wt;Tg.exports=Sl.default});var kg=j($e=>{"use strict";$e.__esModule=!0;$e.SourceLocation=U2;$e.id=$2;$e.stripFlags=H2;$e.stripComment=j2;$e.preparePath=W2;$e.prepareMustache=V2;$e.prepareRawBlock=K2;$e.prepareBlock=G2;$e.prepareProgram=J2;$e.preparePartialBlock=z2;function F2(t){return t&&t.__esModule?t:{default:t}}var q2=Ue(),Rf=F2(q2);function Tf(t,e){if(e=e.path?e.path.original:e,t.path.original!==e){var r={loc:t.path.loc};throw new Rf.default(t.path.original+" doesn't match "+e,r)}}function U2(t,e){this.source=t,this.start={line:e.first_line,column:e.first_column},this.end={line:e.last_line,column:e.last_column}}function $2(t){return/^\[.*\]$/.test(t)?t.substring(1,t.length-1):t}function H2(t,e){return{open:t.charAt(2)==="~",close:e.charAt(e.length-3)==="~"}}function j2(t){return t.replace(/^\{\{~?!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function W2(t,e,r){r=this.locInfo(r);for(var n=t?"@":"",s=[],o=0,i=0,a=e.length;i<a;i++){var c=e[i].part,l=e[i].original!==c;if(n+=(e[i].separator||"")+c,!l&&(c===".."||c==="."||c==="this")){if(s.length>0)throw new Rf.default("Invalid path: "+n,{loc:r});c===".."&&o++}else s.push(c)}return{type:"PathExpression",data:t,depth:o,parts:s,original:n,loc:r}}function V2(t,e,r,n,s,o){var i=n.charAt(3)||n.charAt(2),a=i!=="{"&&i!=="&",c=/\*/.test(n);return{type:c?"Decorator":"MustacheStatement",path:t,params:e,hash:r,escaped:a,strip:s,loc:this.locInfo(o)}}function K2(t,e,r,n){Tf(t,r),n=this.locInfo(n);var s={type:"Program",body:e,strip:{},loc:n};return{type:"BlockStatement",path:t.path,params:t.params,hash:t.hash,program:s,openStrip:{},inverseStrip:{},closeStrip:{},loc:n}}function G2(t,e,r,n,s,o){n&&n.path&&Tf(t,n);var i=/\*/.test(t.open);e.blockParams=t.blockParams;var a=void 0,c=void 0;if(r){if(i)throw new Rf.default("Unexpected inverse block on decorator",r);r.chain&&(r.program.body[0].closeStrip=n.strip),c=r.strip,a=r.program}return s&&(s=a,a=e,e=s),{type:i?"DecoratorBlock":"BlockStatement",path:t.path,params:t.params,hash:t.hash,program:e,inverse:a,openStrip:t.strip,inverseStrip:c,closeStrip:n&&n.strip,loc:this.locInfo(o)}}function J2(t,e){if(!e&&t.length){var r=t[0].loc,n=t[t.length-1].loc;r&&n&&(e={source:r.source,start:{line:r.start.line,column:r.start.column},end:{line:n.end.line,column:n.end.column}})}return{type:"Program",body:t,strip:{},loc:e}}function z2(t,e,r,n){return Tf(t,r),{type:"PartialBlockStatement",name:t.path,params:t.params,hash:t.hash,program:e,openStrip:t.strip,closeStrip:r&&r.strip,loc:this.locInfo(n)}}});var Lg=j(Xo=>{"use strict";Xo.__esModule=!0;Xo.parseWithoutProcessing=Mg;Xo.parse=n0;function X2(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function Og(t){return t&&t.__esModule?t:{default:t}}var Y2=vg(),If=Og(Y2),Q2=Ig(),Z2=Og(Q2),e0=kg(),t0=X2(e0),r0=Se();Xo.parser=If.default;var xl={};r0.extend(xl,t0);function Mg(t,e){if(t.type==="Program")return t;If.default.yy=xl,xl.locInfo=function(n){return new xl.SourceLocation(e&&e.srcName,n)};var r=If.default.parse(t);return r}function n0(t,e){var r=Mg(t,e),n=new Z2.default(e);return n.accept(r)}});var Fg=j(ei=>{"use strict";ei.__esModule=!0;ei.Compiler=kf;ei.precompile=a0;ei.compile=l0;function Dg(t){return t&&t.__esModule?t:{default:t}}var s0=Ue(),Qo=Dg(s0),Zo=Se(),o0=Ef(),Yo=Dg(o0),i0=[].slice;function kf(){}kf.prototype={compiler:kf,equals:function(e){var r=this.opcodes.length;if(e.opcodes.length!==r)return!1;for(var n=0;n<r;n++){var s=this.opcodes[n],o=e.opcodes[n];if(s.opcode!==o.opcode||!Bg(s.args,o.args))return!1}r=this.children.length;for(var n=0;n<r;n++)if(!this.children[n].equals(e.children[n]))return!1;return!0},guid:0,compile:function(e,r){return this.sourceNode=[],this.opcodes=[],this.children=[],this.options=r,this.stringParams=r.stringParams,this.trackIds=r.trackIds,r.blockParams=r.blockParams||[],r.knownHelpers=Zo.extend(Object.create(null),{helperMissing:!0,blockHelperMissing:!0,each:!0,if:!0,unless:!0,with:!0,log:!0,lookup:!0},r.knownHelpers),this.accept(e)},compileProgram:function(e){var r=new this.compiler,n=r.compile(e,this.options),s=this.guid++;return this.usePartial=this.usePartial||n.usePartial,this.children[s]=n,this.useDepths=this.useDepths||n.useDepths,s},accept:function(e){if(!this[e.type])throw new Qo.default("Unknown type: "+e.type,e);this.sourceNode.unshift(e);var r=this[e.type](e);return this.sourceNode.shift(),r},Program:function(e){this.options.blockParams.unshift(e.blockParams);for(var r=e.body,n=r.length,s=0;s<n;s++)this.accept(r[s]);return this.options.blockParams.shift(),this.isSimple=n===1,this.blockParams=e.blockParams?e.blockParams.length:0,this},BlockStatement:function(e){Ng(e);var r=e.program,n=e.inverse;r=r&&this.compileProgram(r),n=n&&this.compileProgram(n);var s=this.classifySexpr(e);s==="helper"?this.helperSexpr(e,r,n):s==="simple"?(this.simpleSexpr(e),this.opcode("pushProgram",r),this.opcode("pushProgram",n),this.opcode("emptyHash"),this.opcode("blockValue",e.path.original)):(this.ambiguousSexpr(e,r,n),this.opcode("pushProgram",r),this.opcode("pushProgram",n),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(e){var r=e.program&&this.compileProgram(e.program),n=this.setupFullMustacheParams(e,r,void 0),s=e.path;this.useDecorators=!0,this.opcode("registerDecorator",n.length,s.original)},PartialStatement:function(e){this.usePartial=!0;var r=e.program;r&&(r=this.compileProgram(e.program));var n=e.params;if(n.length>1)throw new Qo.default("Unsupported number of partial arguments: "+n.length,e);n.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):n.push({type:"PathExpression",parts:[],depth:0}));var s=e.name.original,o=e.name.type==="SubExpression";o&&this.accept(e.name),this.setupFullMustacheParams(e,r,void 0,!0);var i=e.indent||"";this.options.preventIndent&&i&&(this.opcode("appendContent",i),i=""),this.opcode("invokePartial",o,s,i),this.opcode("append")},PartialBlockStatement:function(e){this.PartialStatement(e)},MustacheStatement:function(e){this.SubExpression(e),e.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(e){this.DecoratorBlock(e)},ContentStatement:function(e){e.value&&this.opcode("appendContent",e.value)},CommentStatement:function(){},SubExpression:function(e){Ng(e);var r=this.classifySexpr(e);r==="simple"?this.simpleSexpr(e):r==="helper"?this.helperSexpr(e):this.ambiguousSexpr(e)},ambiguousSexpr:function(e,r,n){var s=e.path,o=s.parts[0],i=r!=null||n!=null;this.opcode("getContext",s.depth),this.opcode("pushProgram",r),this.opcode("pushProgram",n),s.strict=!0,this.accept(s),this.opcode("invokeAmbiguous",o,i)},simpleSexpr:function(e){var r=e.path;r.strict=!0,this.accept(r),this.opcode("resolvePossibleLambda")},helperSexpr:function(e,r,n){var s=this.setupFullMustacheParams(e,r,n),o=e.path,i=o.parts[0];if(this.options.knownHelpers[i])this.opcode("invokeKnownHelper",s.length,i);else{if(this.options.knownHelpersOnly)throw new Qo.default("You specified knownHelpersOnly, but used the unknown helper "+i,e);o.strict=!0,o.falsy=!0,this.accept(o),this.opcode("invokeHelper",s.length,o.original,Yo.default.helpers.simpleId(o))}},PathExpression:function(e){this.addDepth(e.depth),this.opcode("getContext",e.depth);var r=e.parts[0],n=Yo.default.helpers.scopedId(e),s=!e.depth&&!n&&this.blockParamIndex(r);s?this.opcode("lookupBlockParam",s,e.parts):r?e.data?(this.options.data=!0,this.opcode("lookupData",e.depth,e.parts,e.strict)):this.opcode("lookupOnContext",e.parts,e.falsy,e.strict,n):this.opcode("pushContext")},StringLiteral:function(e){this.opcode("pushString",e.value)},NumberLiteral:function(e){this.opcode("pushLiteral",e.value)},BooleanLiteral:function(e){this.opcode("pushLiteral",e.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(e){var r=e.pairs,n=0,s=r.length;for(this.opcode("pushHash");n<s;n++)this.pushParam(r[n].value);for(;n--;)this.opcode("assignToHash",r[n].key);this.opcode("popHash")},opcode:function(e){this.opcodes.push({opcode:e,args:i0.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(e){e&&(this.useDepths=!0)},classifySexpr:function(e){var r=Yo.default.helpers.simpleId(e.path),n=r&&!!this.blockParamIndex(e.path.parts[0]),s=!n&&Yo.default.helpers.helperExpression(e),o=!n&&(s||r);if(o&&!s){var i=e.path.parts[0],a=this.options;a.knownHelpers[i]?s=!0:a.knownHelpersOnly&&(o=!1)}return s?"helper":o?"ambiguous":"simple"},pushParams:function(e){for(var r=0,n=e.length;r<n;r++)this.pushParam(e[r])},pushParam:function(e){var r=e.value!=null?e.value:e.original||"";if(this.stringParams)r.replace&&(r=r.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),e.depth&&this.addDepth(e.depth),this.opcode("getContext",e.depth||0),this.opcode("pushStringParam",r,e.type),e.type==="SubExpression"&&this.accept(e);else{if(this.trackIds){var n=void 0;if(e.parts&&!Yo.default.helpers.scopedId(e)&&!e.depth&&(n=this.blockParamIndex(e.parts[0])),n){var s=e.parts.slice(1).join(".");this.opcode("pushId","BlockParam",n,s)}else r=e.original||r,r.replace&&(r=r.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",e.type,r)}this.accept(e)}},setupFullMustacheParams:function(e,r,n,s){var o=e.params;return this.pushParams(o),this.opcode("pushProgram",r),this.opcode("pushProgram",n),e.hash?this.accept(e.hash):this.opcode("emptyHash",s),o},blockParamIndex:function(e){for(var r=0,n=this.options.blockParams.length;r<n;r++){var s=this.options.blockParams[r],o=s&&Zo.indexOf(s,e);if(s&&o>=0)return[r,o]}}};function a0(t,e,r){if(t==null||typeof t!="string"&&t.type!=="Program")throw new Qo.default("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+t);e=e||{},"data"in e||(e.data=!0),e.compat&&(e.useDepths=!0);var n=r.parse(t,e),s=new r.Compiler().compile(n,e);return new r.JavaScriptCompiler().compile(s,e)}function l0(t,e,r){if(e===void 0&&(e={}),t==null||typeof t!="string"&&t.type!=="Program")throw new Qo.default("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+t);e=Zo.extend({},e),"data"in e||(e.data=!0),e.compat&&(e.useDepths=!0);var n=void 0;function s(){var i=r.parse(t,e),a=new r.Compiler().compile(i,e),c=new r.JavaScriptCompiler().compile(a,e,void 0,!0);return r.template(c)}function o(i,a){return n||(n=s()),n.call(this,i,a)}return o._setup=function(i){return n||(n=s()),n._setup(i)},o._child=function(i,a,c,l){return n||(n=s()),n._child(i,a,c,l)},o}function Bg(t,e){if(t===e)return!0;if(Zo.isArray(t)&&Zo.isArray(e)&&t.length===e.length){for(var r=0;r<t.length;r++)if(!Bg(t[r],e[r]))return!1;return!0}}function Ng(t){if(!t.path.parts){var e=t.path;t.path={type:"PathExpression",data:!1,depth:0,parts:[e.original+""],original:e.original+"",loc:e.loc}}}});var Ug=j(Of=>{var qg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");Of.encode=function(t){if(0<=t&&t<qg.length)return qg[t];throw new TypeError("Must be between 0 and 63: "+t)};Of.decode=function(t){var e=65,r=90,n=97,s=122,o=48,i=57,a=43,c=47,l=26,f=52;return e<=t&&t<=r?t-e:n<=t&&t<=s?t-n+l:o<=t&&t<=i?t-o+f:t==a?62:t==c?63:-1}});var Nf=j(Lf=>{var $g=Ug(),Mf=5,Hg=1<<Mf,jg=Hg-1,Wg=Hg;function c0(t){return t<0?(-t<<1)+1:(t<<1)+0}function u0(t){var e=(t&1)===1,r=t>>1;return e?-r:r}Lf.encode=function(e){var r="",n,s=c0(e);do n=s&jg,s>>>=Mf,s>0&&(n|=Wg),r+=$g.encode(n);while(s>0);return r};Lf.decode=function(e,r,n){var s=e.length,o=0,i=0,a,c;do{if(r>=s)throw new Error("Expected more digits in base 64 VLQ value.");if(c=$g.decode(e.charCodeAt(r++)),c===-1)throw new Error("Invalid base64 digit: "+e.charAt(r-1));a=!!(c&Wg),c&=jg,o=o+(c<<i),i+=Mf}while(a);n.value=u0(o),n.rest=r}});var Rs=j(be=>{function f0(t,e,r){if(e in t)return t[e];if(arguments.length===3)return r;throw new Error('"'+e+'" is a required argument.')}be.getArg=f0;var Vg=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,d0=/^data:.+\,.+$/;function ti(t){var e=t.match(Vg);return e?{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}:null}be.urlParse=ti;function Cs(t){var e="";return t.scheme&&(e+=t.scheme+":"),e+="//",t.auth&&(e+=t.auth+"@"),t.host&&(e+=t.host),t.port&&(e+=":"+t.port),t.path&&(e+=t.path),e}be.urlGenerate=Cs;function Df(t){var e=t,r=ti(t);if(r){if(!r.path)return t;e=r.path}for(var n=be.isAbsolute(e),s=e.split(/\/+/),o,i=0,a=s.length-1;a>=0;a--)o=s[a],o==="."?s.splice(a,1):o===".."?i++:i>0&&(o===""?(s.splice(a+1,i),i=0):(s.splice(a,2),i--));return e=s.join("/"),e===""&&(e=n?"/":"."),r?(r.path=e,Cs(r)):e}be.normalize=Df;function Kg(t,e){t===""&&(t="."),e===""&&(e=".");var r=ti(e),n=ti(t);if(n&&(t=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),Cs(r);if(r||e.match(d0))return e;if(n&&!n.host&&!n.path)return n.host=e,Cs(n);var s=e.charAt(0)==="/"?e:Df(t.replace(/\/+$/,"")+"/"+e);return n?(n.path=s,Cs(n)):s}be.join=Kg;be.isAbsolute=function(t){return t.charAt(0)==="/"||Vg.test(t)};function h0(t,e){t===""&&(t="."),t=t.replace(/\/$/,"");for(var r=0;e.indexOf(t+"/")!==0;){var n=t.lastIndexOf("/");if(n<0||(t=t.slice(0,n),t.match(/^([^\/]+:\/)?\/*$/)))return e;++r}return Array(r+1).join("../")+e.substr(t.length+1)}be.relative=h0;var Gg=function(){var t=Object.create(null);return!("__proto__"in t)}();function Jg(t){return t}function p0(t){return zg(t)?"$"+t:t}be.toSetString=Gg?Jg:p0;function m0(t){return zg(t)?t.slice(1):t}be.fromSetString=Gg?Jg:m0;function zg(t){if(!t)return!1;var e=t.length;if(e<9||t.charCodeAt(e-1)!==95||t.charCodeAt(e-2)!==95||t.charCodeAt(e-3)!==111||t.charCodeAt(e-4)!==116||t.charCodeAt(e-5)!==111||t.charCodeAt(e-6)!==114||t.charCodeAt(e-7)!==112||t.charCodeAt(e-8)!==95||t.charCodeAt(e-9)!==95)return!1;for(var r=e-10;r>=0;r--)if(t.charCodeAt(r)!==36)return!1;return!0}function g0(t,e,r){var n=Ps(t.source,e.source);return n!==0||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Ps(t.name,e.name)}be.compareByOriginalPositions=g0;function y0(t,e,r){var n=t.generatedLine-e.generatedLine;return n!==0||(n=t.generatedColumn-e.generatedColumn,n!==0||r)||(n=Ps(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Ps(t.name,e.name)}be.compareByGeneratedPositionsDeflated=y0;function Ps(t,e){return t===e?0:t===null?1:e===null?-1:t>e?1:-1}function b0(t,e){var r=t.generatedLine-e.generatedLine;return r!==0||(r=t.generatedColumn-e.generatedColumn,r!==0)||(r=Ps(t.source,e.source),r!==0)||(r=t.originalLine-e.originalLine,r!==0)||(r=t.originalColumn-e.originalColumn,r!==0)?r:Ps(t.name,e.name)}be.compareByGeneratedPositionsInflated=b0;function w0(t){return JSON.parse(t.replace(/^\)]}'[^\n]*\n/,""))}be.parseSourceMapInput=w0;function _0(t,e,r){if(e=e||"",t&&(t[t.length-1]!=="/"&&e[0]!=="/"&&(t+="/"),e=t+e),r){var n=ti(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var s=n.path.lastIndexOf("/");s>=0&&(n.path=n.path.substring(0,s+1))}e=Kg(Cs(n),e)}return Df(e)}be.computeSourceURL=_0});var qf=j(Xg=>{var Bf=Rs(),Ff=Object.prototype.hasOwnProperty,en=typeof Map!="undefined";function Bt(){this._array=[],this._set=en?new Map:Object.create(null)}Bt.fromArray=function(e,r){for(var n=new Bt,s=0,o=e.length;s<o;s++)n.add(e[s],r);return n};Bt.prototype.size=function(){return en?this._set.size:Object.getOwnPropertyNames(this._set).length};Bt.prototype.add=function(e,r){var n=en?e:Bf.toSetString(e),s=en?this.has(e):Ff.call(this._set,n),o=this._array.length;(!s||r)&&this._array.push(e),s||(en?this._set.set(e,o):this._set[n]=o)};Bt.prototype.has=function(e){if(en)return this._set.has(e);var r=Bf.toSetString(e);return Ff.call(this._set,r)};Bt.prototype.indexOf=function(e){if(en){var r=this._set.get(e);if(r>=0)return r}else{var n=Bf.toSetString(e);if(Ff.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')};Bt.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)};Bt.prototype.toArray=function(){return this._array.slice()};Xg.ArraySet=Bt});var Zg=j(Qg=>{var Yg=Rs();function S0(t,e){var r=t.generatedLine,n=e.generatedLine,s=t.generatedColumn,o=e.generatedColumn;return n>r||n==r&&o>=s||Yg.compareByGeneratedPositionsInflated(t,e)<=0}function El(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}El.prototype.unsortedForEach=function(e,r){this._array.forEach(e,r)};El.prototype.add=function(e){S0(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))};El.prototype.toArray=function(){return this._sorted||(this._array.sort(Yg.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};Qg.MappingList=El});var Uf=j(ey=>{var ri=Nf(),Z=Rs(),Al=qf().ArraySet,x0=Zg().MappingList;function He(t){t||(t={}),this._file=Z.getArg(t,"file",null),this._sourceRoot=Z.getArg(t,"sourceRoot",null),this._skipValidation=Z.getArg(t,"skipValidation",!1),this._sources=new Al,this._names=new Al,this._mappings=new x0,this._sourcesContents=null}He.prototype._version=3;He.fromSourceMap=function(e){var r=e.sourceRoot,n=new He({file:e.file,sourceRoot:r});return e.eachMapping(function(s){var o={generated:{line:s.generatedLine,column:s.generatedColumn}};s.source!=null&&(o.source=s.source,r!=null&&(o.source=Z.relative(r,o.source)),o.original={line:s.originalLine,column:s.originalColumn},s.name!=null&&(o.name=s.name)),n.addMapping(o)}),e.sources.forEach(function(s){var o=s;r!==null&&(o=Z.relative(r,s)),n._sources.has(o)||n._sources.add(o);var i=e.sourceContentFor(s);i!=null&&n.setSourceContent(s,i)}),n};He.prototype.addMapping=function(e){var r=Z.getArg(e,"generated"),n=Z.getArg(e,"original",null),s=Z.getArg(e,"source",null),o=Z.getArg(e,"name",null);this._skipValidation||this._validateMapping(r,n,s,o),s!=null&&(s=String(s),this._sources.has(s)||this._sources.add(s)),o!=null&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:s,name:o})};He.prototype.setSourceContent=function(e,r){var n=e;this._sourceRoot!=null&&(n=Z.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Z.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[Z.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))};He.prototype.applySourceMap=function(e,r,n){var s=r;if(r==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);s=e.file}var o=this._sourceRoot;o!=null&&(s=Z.relative(o,s));var i=new Al,a=new Al;this._mappings.unsortedForEach(function(c){if(c.source===s&&c.originalLine!=null){var l=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});l.source!=null&&(c.source=l.source,n!=null&&(c.source=Z.join(n,c.source)),o!=null&&(c.source=Z.relative(o,c.source)),c.originalLine=l.line,c.originalColumn=l.column,l.name!=null&&(c.name=l.name))}var f=c.source;f!=null&&!i.has(f)&&i.add(f);var u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=i,this._names=a,e.sources.forEach(function(c){var l=e.sourceContentFor(c);l!=null&&(n!=null&&(c=Z.join(n,c)),o!=null&&(c=Z.relative(o,c)),this.setSourceContent(c,l))},this)};He.prototype._validateMapping=function(e,r,n,s){if(r&&typeof r.line!="number"&&typeof r.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!r&&!n&&!s)){if(e&&"line"in e&&"column"in e&&r&&"line"in r&&"column"in r&&e.line>0&&e.column>=0&&r.line>0&&r.column>=0&&n)return;throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:r,name:s}))}};He.prototype._serializeMappings=function(){for(var e=0,r=1,n=0,s=0,o=0,i=0,a="",c,l,f,u,d=this._mappings.toArray(),h=0,p=d.length;h<p;h++){if(l=d[h],c="",l.generatedLine!==r)for(e=0;l.generatedLine!==r;)c+=";",r++;else if(h>0){if(!Z.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=ri.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(u=this._sources.indexOf(l.source),c+=ri.encode(u-i),i=u,c+=ri.encode(l.originalLine-1-s),s=l.originalLine-1,c+=ri.encode(l.originalColumn-n),n=l.originalColumn,l.name!=null&&(f=this._names.indexOf(l.name),c+=ri.encode(f-o),o=f)),a+=c}return a};He.prototype._generateSourcesContent=function(e,r){return e.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=Z.relative(r,n));var s=Z.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,s)?this._sourcesContents[s]:null},this)};He.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e};He.prototype.toString=function(){return JSON.stringify(this.toJSON())};ey.SourceMapGenerator=He});var ty=j(tn=>{tn.GREATEST_LOWER_BOUND=1;tn.LEAST_UPPER_BOUND=2;function $f(t,e,r,n,s,o){var i=Math.floor((e-t)/2)+t,a=s(r,n[i],!0);return a===0?i:a>0?e-i>1?$f(i,e,r,n,s,o):o==tn.LEAST_UPPER_BOUND?e<n.length?e:-1:i:i-t>1?$f(t,i,r,n,s,o):o==tn.LEAST_UPPER_BOUND?i:t<0?-1:t}tn.search=function(e,r,n,s){if(r.length===0)return-1;var o=$f(-1,r.length,e,r,n,s||tn.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&n(r[o],r[o-1],!0)===0;)--o;return o}});var ny=j(ry=>{function Hf(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function E0(t,e){return Math.round(t+Math.random()*(e-t))}function jf(t,e,r,n){if(r<n){var s=E0(r,n),o=r-1;Hf(t,s,n);for(var i=t[n],a=r;a<n;a++)e(t[a],i)<=0&&(o+=1,Hf(t,o,a));Hf(t,o+1,a);var c=o+1;jf(t,e,r,c-1),jf(t,e,c+1,n)}}ry.quickSort=function(t,e){jf(t,e,0,t.length-1)}});var oy=j(vl=>{var M=Rs(),Wf=ty(),Ts=qf().ArraySet,A0=Nf(),ni=ny().quickSort;function G(t,e){var r=t;return typeof t=="string"&&(r=M.parseSourceMapInput(t)),r.sections!=null?new Ye(r,e):new me(r,e)}G.fromSourceMap=function(t,e){return me.fromSourceMap(t,e)};G.prototype._version=3;G.prototype.__generatedMappings=null;Object.defineProperty(G.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}});G.prototype.__originalMappings=null;Object.defineProperty(G.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}});G.prototype._charIsMappingSeparator=function(e,r){var n=e.charAt(r);return n===";"||n===","};G.prototype._parseMappings=function(e,r){throw new Error("Subclasses must implement _parseMappings")};G.GENERATED_ORDER=1;G.ORIGINAL_ORDER=2;G.GREATEST_LOWER_BOUND=1;G.LEAST_UPPER_BOUND=2;G.prototype.eachMapping=function(e,r,n){var s=r||null,o=n||G.GENERATED_ORDER,i;switch(o){case G.GENERATED_ORDER:i=this._generatedMappings;break;case G.ORIGINAL_ORDER:i=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var a=this.sourceRoot;i.map(function(c){var l=c.source===null?null:this._sources.at(c.source);return l=M.computeSourceURL(a,l,this._sourceMapURL),{source:l,generatedLine:c.generatedLine,generatedColumn:c.generatedColumn,originalLine:c.originalLine,originalColumn:c.originalColumn,name:c.name===null?null:this._names.at(c.name)}},this).forEach(e,s)};G.prototype.allGeneratedPositionsFor=function(e){var r=M.getArg(e,"line"),n={source:M.getArg(e,"source"),originalLine:r,originalColumn:M.getArg(e,"column",0)};if(n.source=this._findSourceIndex(n.source),n.source<0)return[];var s=[],o=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",M.compareByOriginalPositions,Wf.LEAST_UPPER_BOUND);if(o>=0){var i=this._originalMappings[o];if(e.column===void 0)for(var a=i.originalLine;i&&i.originalLine===a;)s.push({line:M.getArg(i,"generatedLine",null),column:M.getArg(i,"generatedColumn",null),lastColumn:M.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var c=i.originalColumn;i&&i.originalLine===r&&i.originalColumn==c;)s.push({line:M.getArg(i,"generatedLine",null),column:M.getArg(i,"generatedColumn",null),lastColumn:M.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return s};vl.SourceMapConsumer=G;function me(t,e){var r=t;typeof t=="string"&&(r=M.parseSourceMapInput(t));var n=M.getArg(r,"version"),s=M.getArg(r,"sources"),o=M.getArg(r,"names",[]),i=M.getArg(r,"sourceRoot",null),a=M.getArg(r,"sourcesContent",null),c=M.getArg(r,"mappings"),l=M.getArg(r,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);i&&(i=M.normalize(i)),s=s.map(String).map(M.normalize).map(function(f){return i&&M.isAbsolute(i)&&M.isAbsolute(f)?M.relative(i,f):f}),this._names=Ts.fromArray(o.map(String),!0),this._sources=Ts.fromArray(s,!0),this._absoluteSources=this._sources.toArray().map(function(f){return M.computeSourceURL(i,f,e)}),this.sourceRoot=i,this.sourcesContent=a,this._mappings=c,this._sourceMapURL=e,this.file=l}me.prototype=Object.create(G.prototype);me.prototype.consumer=G;me.prototype._findSourceIndex=function(t){var e=t;if(this.sourceRoot!=null&&(e=M.relative(this.sourceRoot,e)),this._sources.has(e))return this._sources.indexOf(e);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==t)return r;return-1};me.fromSourceMap=function(e,r){var n=Object.create(me.prototype),s=n._names=Ts.fromArray(e._names.toArray(),!0),o=n._sources=Ts.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file,n._sourceMapURL=r,n._absoluteSources=n._sources.toArray().map(function(h){return M.computeSourceURL(n.sourceRoot,h,r)});for(var i=e._mappings.toArray().slice(),a=n.__generatedMappings=[],c=n.__originalMappings=[],l=0,f=i.length;l<f;l++){var u=i[l],d=new sy;d.generatedLine=u.generatedLine,d.generatedColumn=u.generatedColumn,u.source&&(d.source=o.indexOf(u.source),d.originalLine=u.originalLine,d.originalColumn=u.originalColumn,u.name&&(d.name=s.indexOf(u.name)),c.push(d)),a.push(d)}return ni(n.__originalMappings,M.compareByOriginalPositions),n};me.prototype._version=3;Object.defineProperty(me.prototype,"sources",{get:function(){return this._absoluteSources.slice()}});function sy(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}me.prototype._parseMappings=function(e,r){for(var n=1,s=0,o=0,i=0,a=0,c=0,l=e.length,f=0,u={},d={},h=[],p=[],y,g,S,_,v;f<l;)if(e.charAt(f)===";")n++,f++,s=0;else if(e.charAt(f)===",")f++;else{for(y=new sy,y.generatedLine=n,_=f;_<l&&!this._charIsMappingSeparator(e,_);_++);if(g=e.slice(f,_),S=u[g],S)f+=g.length;else{for(S=[];f<_;)A0.decode(e,f,d),v=d.value,f=d.rest,S.push(v);if(S.length===2)throw new Error("Found a source, but no line and column");if(S.length===3)throw new Error("Found a source and line, but no column");u[g]=S}y.generatedColumn=s+S[0],s=y.generatedColumn,S.length>1&&(y.source=a+S[1],a+=S[1],y.originalLine=o+S[2],o=y.originalLine,y.originalLine+=1,y.originalColumn=i+S[3],i=y.originalColumn,S.length>4&&(y.name=c+S[4],c+=S[4])),p.push(y),typeof y.originalLine=="number"&&h.push(y)}ni(p,M.compareByGeneratedPositionsDeflated),this.__generatedMappings=p,ni(h,M.compareByOriginalPositions),this.__originalMappings=h};me.prototype._findMapping=function(e,r,n,s,o,i){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[s]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[s]);return Wf.search(e,r,o,i)};me.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var r=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(r.generatedLine===n.generatedLine){r.lastGeneratedColumn=n.generatedColumn-1;continue}}r.lastGeneratedColumn=1/0}};me.prototype.originalPositionFor=function(e){var r={generatedLine:M.getArg(e,"line"),generatedColumn:M.getArg(e,"column")},n=this._findMapping(r,this._generatedMappings,"generatedLine","generatedColumn",M.compareByGeneratedPositionsDeflated,M.getArg(e,"bias",G.GREATEST_LOWER_BOUND));if(n>=0){var s=this._generatedMappings[n];if(s.generatedLine===r.generatedLine){var o=M.getArg(s,"source",null);o!==null&&(o=this._sources.at(o),o=M.computeSourceURL(this.sourceRoot,o,this._sourceMapURL));var i=M.getArg(s,"name",null);return i!==null&&(i=this._names.at(i)),{source:o,line:M.getArg(s,"originalLine",null),column:M.getArg(s,"originalColumn",null),name:i}}}return{source:null,line:null,column:null,name:null}};me.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1};me.prototype.sourceContentFor=function(e,r){if(!this.sourcesContent)return null;var n=this._findSourceIndex(e);if(n>=0)return this.sourcesContent[n];var s=e;this.sourceRoot!=null&&(s=M.relative(this.sourceRoot,s));var o;if(this.sourceRoot!=null&&(o=M.urlParse(this.sourceRoot))){var i=s.replace(/^file:\/\//,"");if(o.scheme=="file"&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||o.path=="/")&&this._sources.has("/"+s))return this.sourcesContent[this._sources.indexOf("/"+s)]}if(r)return null;throw new Error('"'+s+'" is not in the SourceMap.')};me.prototype.generatedPositionFor=function(e){var r=M.getArg(e,"source");if(r=this._findSourceIndex(r),r<0)return{line:null,column:null,lastColumn:null};var n={source:r,originalLine:M.getArg(e,"line"),originalColumn:M.getArg(e,"column")},s=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",M.compareByOriginalPositions,M.getArg(e,"bias",G.GREATEST_LOWER_BOUND));if(s>=0){var o=this._originalMappings[s];if(o.source===n.source)return{line:M.getArg(o,"generatedLine",null),column:M.getArg(o,"generatedColumn",null),lastColumn:M.getArg(o,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};vl.BasicSourceMapConsumer=me;function Ye(t,e){var r=t;typeof t=="string"&&(r=M.parseSourceMapInput(t));var n=M.getArg(r,"version"),s=M.getArg(r,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);this._sources=new Ts,this._names=new Ts;var o={line:-1,column:0};this._sections=s.map(function(i){if(i.url)throw new Error("Support for url field in sections not implemented.");var a=M.getArg(i,"offset"),c=M.getArg(a,"line"),l=M.getArg(a,"column");if(c<o.line||c===o.line&&l<o.column)throw new Error("Section offsets must be ordered and non-overlapping.");return o=a,{generatedOffset:{generatedLine:c+1,generatedColumn:l+1},consumer:new G(M.getArg(i,"map"),e)}})}Ye.prototype=Object.create(G.prototype);Ye.prototype.constructor=G;Ye.prototype._version=3;Object.defineProperty(Ye.prototype,"sources",{get:function(){for(var t=[],e=0;e<this._sections.length;e++)for(var r=0;r<this._sections[e].consumer.sources.length;r++)t.push(this._sections[e].consumer.sources[r]);return t}});Ye.prototype.originalPositionFor=function(e){var r={generatedLine:M.getArg(e,"line"),generatedColumn:M.getArg(e,"column")},n=Wf.search(r,this._sections,function(o,i){var a=o.generatedLine-i.generatedOffset.generatedLine;return a||o.generatedColumn-i.generatedOffset.generatedColumn}),s=this._sections[n];return s?s.consumer.originalPositionFor({line:r.generatedLine-(s.generatedOffset.generatedLine-1),column:r.generatedColumn-(s.generatedOffset.generatedLine===r.generatedLine?s.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}};Ye.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})};Ye.prototype.sourceContentFor=function(e,r){for(var n=0;n<this._sections.length;n++){var s=this._sections[n],o=s.consumer.sourceContentFor(e,!0);if(o)return o}if(r)return null;throw new Error('"'+e+'" is not in the SourceMap.')};Ye.prototype.generatedPositionFor=function(e){for(var r=0;r<this._sections.length;r++){var n=this._sections[r];if(n.consumer._findSourceIndex(M.getArg(e,"source"))!==-1){var s=n.consumer.generatedPositionFor(e);if(s){var o={line:s.line+(n.generatedOffset.generatedLine-1),column:s.column+(n.generatedOffset.generatedLine===s.line?n.generatedOffset.generatedColumn-1:0)};return o}}}return{line:null,column:null}};Ye.prototype._parseMappings=function(e,r){this.__generatedMappings=[],this.__originalMappings=[];for(var n=0;n<this._sections.length;n++)for(var s=this._sections[n],o=s.consumer._generatedMappings,i=0;i<o.length;i++){var a=o[i],c=s.consumer._sources.at(a.source);c=M.computeSourceURL(s.consumer.sourceRoot,c,this._sourceMapURL),this._sources.add(c),c=this._sources.indexOf(c);var l=null;a.name&&(l=s.consumer._names.at(a.name),this._names.add(l),l=this._names.indexOf(l));var f={source:c,generatedLine:a.generatedLine+(s.generatedOffset.generatedLine-1),generatedColumn:a.generatedColumn+(s.generatedOffset.generatedLine===a.generatedLine?s.generatedOffset.generatedColumn-1:0),originalLine:a.originalLine,originalColumn:a.originalColumn,name:l};this.__generatedMappings.push(f),typeof f.originalLine=="number"&&this.__originalMappings.push(f)}ni(this.__generatedMappings,M.compareByGeneratedPositionsDeflated),ni(this.__originalMappings,M.compareByOriginalPositions)};vl.IndexedSourceMapConsumer=Ye});var ay=j(iy=>{var v0=Uf().SourceMapGenerator,Cl=Rs(),C0=/(\r?\n)/,P0=10,Is="$$$isSourceNode$$$";function ke(t,e,r,n,s){this.children=[],this.sourceContents={},this.line=t==null?null:t,this.column=e==null?null:e,this.source=r==null?null:r,this.name=s==null?null:s,this[Is]=!0,n!=null&&this.add(n)}ke.fromStringWithSourceMap=function(e,r,n){var s=new ke,o=e.split(C0),i=0,a=function(){var d=p(),h=p()||"";return d+h;function p(){return i<o.length?o[i++]:void 0}},c=1,l=0,f=null;return r.eachMapping(function(d){if(f!==null)if(c<d.generatedLine)u(f,a()),c++,l=0;else{var h=o[i]||"",p=h.substr(0,d.generatedColumn-l);o[i]=h.substr(d.generatedColumn-l),l=d.generatedColumn,u(f,p),f=d;return}for(;c<d.generatedLine;)s.add(a()),c++;if(l<d.generatedColumn){var h=o[i]||"";s.add(h.substr(0,d.generatedColumn)),o[i]=h.substr(d.generatedColumn),l=d.generatedColumn}f=d},this),i<o.length&&(f&&u(f,a()),s.add(o.splice(i).join(""))),r.sources.forEach(function(d){var h=r.sourceContentFor(d);h!=null&&(n!=null&&(d=Cl.join(n,d)),s.setSourceContent(d,h))}),s;function u(d,h){if(d===null||d.source===void 0)s.add(h);else{var p=n?Cl.join(n,d.source):d.source;s.add(new ke(d.originalLine,d.originalColumn,p,h,d.name))}}};ke.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(r){this.add(r)},this);else if(e[Is]||typeof e=="string")e&&this.children.push(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};ke.prototype.prepend=function(e){if(Array.isArray(e))for(var r=e.length-1;r>=0;r--)this.prepend(e[r]);else if(e[Is]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};ke.prototype.walk=function(e){for(var r,n=0,s=this.children.length;n<s;n++)r=this.children[n],r[Is]?r.walk(e):r!==""&&e(r,{source:this.source,line:this.line,column:this.column,name:this.name})};ke.prototype.join=function(e){var r,n,s=this.children.length;if(s>0){for(r=[],n=0;n<s-1;n++)r.push(this.children[n]),r.push(e);r.push(this.children[n]),this.children=r}return this};ke.prototype.replaceRight=function(e,r){var n=this.children[this.children.length-1];return n[Is]?n.replaceRight(e,r):typeof n=="string"?this.children[this.children.length-1]=n.replace(e,r):this.children.push("".replace(e,r)),this};ke.prototype.setSourceContent=function(e,r){this.sourceContents[Cl.toSetString(e)]=r};ke.prototype.walkSourceContents=function(e){for(var r=0,n=this.children.length;r<n;r++)this.children[r][Is]&&this.children[r].walkSourceContents(e);for(var s=Object.keys(this.sourceContents),r=0,n=s.length;r<n;r++)e(Cl.fromSetString(s[r]),this.sourceContents[s[r]])};ke.prototype.toString=function(){var e="";return this.walk(function(r){e+=r}),e};ke.prototype.toStringWithSourceMap=function(e){var r={code:"",line:1,column:0},n=new v0(e),s=!1,o=null,i=null,a=null,c=null;return this.walk(function(l,f){r.code+=l,f.source!==null&&f.line!==null&&f.column!==null?((o!==f.source||i!==f.line||a!==f.column||c!==f.name)&&n.addMapping({source:f.source,original:{line:f.line,column:f.column},generated:{line:r.line,column:r.column},name:f.name}),o=f.source,i=f.line,a=f.column,c=f.name,s=!0):s&&(n.addMapping({generated:{line:r.line,column:r.column}}),o=null,s=!1);for(var u=0,d=l.length;u<d;u++)l.charCodeAt(u)===P0?(r.line++,r.column=0,u+1===d?(o=null,s=!1):s&&n.addMapping({source:f.source,original:{line:f.line,column:f.column},generated:{line:r.line,column:r.column},name:f.name})):r.column++}),this.walkSourceContents(function(l,f){n.setSourceContent(l,f)}),{code:r.code,map:n}};iy.SourceNode=ke});var ly=j(Pl=>{Pl.SourceMapGenerator=Uf().SourceMapGenerator;Pl.SourceMapConsumer=oy().SourceMapConsumer;Pl.SourceNode=ay().SourceNode});var dy=j((Rl,fy)=>{"use strict";Rl.__esModule=!0;var Kf=Se(),rn=void 0;try{(typeof define!="function"||!define.amd)&&(cy=ly(),rn=cy.SourceNode)}catch(t){}var cy;rn||(rn=function(t,e,r,n){this.src="",n&&this.add(n)},rn.prototype={add:function(e){Kf.isArray(e)&&(e=e.join("")),this.src+=e},prepend:function(e){Kf.isArray(e)&&(e=e.join("")),this.src=e+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}});function Vf(t,e,r){if(Kf.isArray(t)){for(var n=[],s=0,o=t.length;s<o;s++)n.push(e.wrap(t[s],r));return n}else if(typeof t=="boolean"||typeof t=="number")return t+"";return t}function uy(t){this.srcFile=t,this.source=[]}uy.prototype={isEmpty:function(){return!this.source.length},prepend:function(e,r){this.source.unshift(this.wrap(e,r))},push:function(e,r){this.source.push(this.wrap(e,r))},merge:function(){var e=this.empty();return this.each(function(r){e.add([" ",r,`
`])}),e},each:function(e){for(var r=0,n=this.source.length;r<n;r++)e(this.source[r])},empty:function(){var e=this.currentLocation||{start:{}};return new rn(e.start.line,e.start.column,this.srcFile)},wrap:function(e){var r=arguments.length<=1||arguments[1]===void 0?this.currentLocation||{start:{}}:arguments[1];return e instanceof rn?e:(e=Vf(e,this,r),new rn(r.start.line,r.start.column,this.srcFile,e))},functionCall:function(e,r,n){return n=this.generateList(n),this.wrap([e,r?"."+r+"(":"(",n,")"])},quotedString:function(e){return'"'+(e+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(e){var r=this,n=[];Object.keys(e).forEach(function(o){var i=Vf(e[o],r);i!=="undefined"&&n.push([r.quotedString(o),":",i])});var s=this.generateList(n);return s.prepend("{"),s.add("}"),s},generateList:function(e){for(var r=this.empty(),n=0,s=e.length;n<s;n++)n&&r.add(","),r.add(Vf(e[n],this));return r},generateArray:function(e){var r=this.generateList(e);return r.prepend("["),r.add("]"),r}};Rl.default=uy;fy.exports=Rl.default});var yy=j((Tl,gy)=>{"use strict";Tl.__esModule=!0;function my(t){return t&&t.__esModule?t:{default:t}}var hy=fl(),R0=Ue(),Gf=my(R0),T0=Se(),I0=dy(),py=my(I0);function ks(t){this.value=t}function Os(){}Os.prototype={nameLookup:function(e,r){return this.internalNameLookup(e,r)},depthedLookup:function(e){return[this.aliasable("container.lookup"),"(depths, ",JSON.stringify(e),")"]},compilerInfo:function(){var e=hy.COMPILER_REVISION,r=hy.REVISION_CHANGES[e];return[e,r]},appendToBuffer:function(e,r,n){return T0.isArray(e)||(e=[e]),e=this.source.wrap(e,r),this.environment.isSimple?["return ",e,";"]:n?["buffer += ",e,";"]:(e.appendToBuffer=!0,e)},initializeBuffer:function(){return this.quotedString("")},internalNameLookup:function(e,r){return this.lookupPropertyFunctionIsUsed=!0,["lookupProperty(",e,",",JSON.stringify(r),")"]},lookupPropertyFunctionIsUsed:!1,compile:function(e,r,n,s){this.environment=e,this.options=r,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!s,this.name=this.environment.name,this.isChild=!!n,this.context=n||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(e,r),this.useDepths=this.useDepths||e.useDepths||e.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||e.useBlockParams;var o=e.opcodes,i=void 0,a=void 0,c=void 0,l=void 0;for(c=0,l=o.length;c<l;c++)i=o[c],this.source.currentLocation=i.loc,a=a||i.loc,this[i.opcode].apply(this,i.args);if(this.source.currentLocation=a,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new Gf.default("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend(["var decorators = container.decorators, ",this.lookupPropertyFunctionVarDeclaration(),`;
`]),this.decorators.push("return fn;"),s?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend(`function(fn, props, container, depth0, data, blockParams, depths) {
`),this.decorators.push(`}
`),this.decorators=this.decorators.merge()));var f=this.createFunctionContext(s);if(this.isChild)return f;var u={compiler:this.compilerInfo(),main:f};this.decorators&&(u.main_d=this.decorators,u.useDecorators=!0);var d=this.context,h=d.programs,p=d.decorators;for(c=0,l=h.length;c<l;c++)h[c]&&(u[c]=h[c],p[c]&&(u[c+"_d"]=p[c],u.useDecorators=!0));return this.environment.usePartial&&(u.usePartial=!0),this.options.data&&(u.useData=!0),this.useDepths&&(u.useDepths=!0),this.useBlockParams&&(u.useBlockParams=!0),this.options.compat&&(u.compat=!0),s?u.compilerOptions=this.options:(u.compiler=JSON.stringify(u.compiler),this.source.currentLocation={start:{line:1,column:0}},u=this.objectLiteral(u),r.srcName?(u=u.toStringWithSourceMap({file:r.destName}),u.map=u.map&&u.map.toString()):u=u.toString()),u},preamble:function(){this.lastContext=0,this.source=new py.default(this.options.srcName),this.decorators=new py.default(this.options.srcName)},createFunctionContext:function(e){var r=this,n="",s=this.stackVars.concat(this.registers.list);s.length>0&&(n+=", "+s.join(", "));var o=0;Object.keys(this.aliases).forEach(function(c){var l=r.aliases[c];l.children&&l.referenceCount>1&&(n+=", alias"+ ++o+"="+c,l.children[0]="alias"+o)}),this.lookupPropertyFunctionIsUsed&&(n+=", "+this.lookupPropertyFunctionVarDeclaration());var i=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&i.push("blockParams"),this.useDepths&&i.push("depths");var a=this.mergeSource(n);return e?(i.push(a),Function.apply(this,i)):this.source.wrap(["function(",i.join(","),`) {
`,a,"}"])},mergeSource:function(e){var r=this.environment.isSimple,n=!this.forceBuffer,s=void 0,o=void 0,i=void 0,a=void 0;return this.source.each(function(c){c.appendToBuffer?(i?c.prepend(" + "):i=c,a=c):(i&&(o?i.prepend("buffer += "):s=!0,a.add(";"),i=a=void 0),o=!0,r||(n=!1))}),n?i?(i.prepend("return "),a.add(";")):o||this.source.push('return "";'):(e+=", buffer = "+(s?"":this.initializeBuffer()),i?(i.prepend("return buffer + "),a.add(";")):this.source.push("return buffer;")),e&&this.source.prepend("var "+e.substring(2)+(s?"":`;
`)),this.source.merge()},lookupPropertyFunctionVarDeclaration:function(){return`
lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
}
`.trim()},blockValue:function(e){var r=this.aliasable("container.hooks.blockHelperMissing"),n=[this.contextName(0)];this.setupHelperArgs(e,0,n);var s=this.popStack();n.splice(1,0,s),this.push(this.source.functionCall(r,"call",n))},ambiguousBlockValue:function(){var e=this.aliasable("container.hooks.blockHelperMissing"),r=[this.contextName(0)];this.setupHelperArgs("",0,r,!0),this.flushInline();var n=this.topStack();r.splice(1,0,n),this.pushSource(["if (!",this.lastHelper,") { ",n," = ",this.source.functionCall(e,"call",r),"}"])},appendContent:function(e){this.pendingContent?e=this.pendingContent+e:this.pendingLocation=this.source.currentLocation,this.pendingContent=e},append:function(){if(this.isInline())this.replaceStack(function(r){return[" != null ? ",r,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var e=this.popStack();this.pushSource(["if (",e," != null) { ",this.appendToBuffer(e,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(e){this.lastContext=e},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(e,r,n,s){var o=0;!s&&this.options.compat&&!this.lastContext?this.push(this.depthedLookup(e[o++])):this.pushContext(),this.resolvePath("context",e,o,r,n)},lookupBlockParam:function(e,r){this.useBlockParams=!0,this.push(["blockParams[",e[0],"][",e[1],"]"]),this.resolvePath("context",r,1)},lookupData:function(e,r,n){e?this.pushStackLiteral("container.data(data, "+e+")"):this.pushStackLiteral("data"),this.resolvePath("data",r,0,!0,n)},resolvePath:function(e,r,n,s,o){var i=this;if(this.options.strict||this.options.assumeObjects){this.push(k0(this.options.strict&&o,this,r,n,e));return}for(var a=r.length;n<a;n++)this.replaceStack(function(c){var l=i.nameLookup(c,r[n],e);return s?[" && ",l]:[" != null ? ",l," : ",c]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(e,r){this.pushContext(),this.pushString(r),r!=="SubExpression"&&(typeof e=="string"?this.pushString(e):this.pushStackLiteral(e))},emptyHash:function(e){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(e?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:{},types:[],contexts:[],ids:[]}},popHash:function(){var e=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(e.ids)),this.stringParams&&(this.push(this.objectLiteral(e.contexts)),this.push(this.objectLiteral(e.types))),this.push(this.objectLiteral(e.values))},pushString:function(e){this.pushStackLiteral(this.quotedString(e))},pushLiteral:function(e){this.pushStackLiteral(e)},pushProgram:function(e){e!=null?this.pushStackLiteral(this.programExpression(e)):this.pushStackLiteral(null)},registerDecorator:function(e,r){var n=this.nameLookup("decorators",r,"decorator"),s=this.setupHelperArgs(r,e);this.decorators.push(["fn = ",this.decorators.functionCall(n,"",["fn","props","container",s])," || fn;"])},invokeHelper:function(e,r,n){var s=this.popStack(),o=this.setupHelper(e,r),i=[];n&&i.push(o.name),i.push(s),this.options.strict||i.push(this.aliasable("container.hooks.helperMissing"));var a=["(",this.itemsSeparatedBy(i,"||"),")"],c=this.source.functionCall(a,"call",o.callParams);this.push(c)},itemsSeparatedBy:function(e,r){var n=[];n.push(e[0]);for(var s=1;s<e.length;s++)n.push(r,e[s]);return n},invokeKnownHelper:function(e,r){var n=this.setupHelper(e,r);this.push(this.source.functionCall(n.name,"call",n.callParams))},invokeAmbiguous:function(e,r){this.useRegister("helper");var n=this.popStack();this.emptyHash();var s=this.setupHelper(0,e,r),o=this.lastHelper=this.nameLookup("helpers",e,"helper"),i=["(","(helper = ",o," || ",n,")"];this.options.strict||(i[0]="(helper = ",i.push(" != null ? helper : ",this.aliasable("container.hooks.helperMissing"))),this.push(["(",i,s.paramsInit?["),(",s.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",s.callParams)," : helper))"])},invokePartial:function(e,r,n){var s=[],o=this.setupParams(r,1,s);e&&(r=this.popStack(),delete o.name),n&&(o.indent=JSON.stringify(n)),o.helpers="helpers",o.partials="partials",o.decorators="container.decorators",e?s.unshift(r):s.unshift(this.nameLookup("partials",r,"partial")),this.options.compat&&(o.depths="depths"),o=this.objectLiteral(o),s.push(o),this.push(this.source.functionCall("container.invokePartial","",s))},assignToHash:function(e){var r=this.popStack(),n=void 0,s=void 0,o=void 0;this.trackIds&&(o=this.popStack()),this.stringParams&&(s=this.popStack(),n=this.popStack());var i=this.hash;n&&(i.contexts[e]=n),s&&(i.types[e]=s),o&&(i.ids[e]=o),i.values[e]=r},pushId:function(e,r,n){e==="BlockParam"?this.pushStackLiteral("blockParams["+r[0]+"].path["+r[1]+"]"+(n?" + "+JSON.stringify("."+n):"")):e==="PathExpression"?this.pushString(r):e==="SubExpression"?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:Os,compileChildren:function(e,r){for(var n=e.children,s=void 0,o=void 0,i=0,a=n.length;i<a;i++){s=n[i],o=new this.compiler;var c=this.matchExistingProgram(s);if(c==null){this.context.programs.push("");var l=this.context.programs.length;s.index=l,s.name="program"+l,this.context.programs[l]=o.compile(s,r,this.context,!this.precompile),this.context.decorators[l]=o.decorators,this.context.environments[l]=s,this.useDepths=this.useDepths||o.useDepths,this.useBlockParams=this.useBlockParams||o.useBlockParams,s.useDepths=this.useDepths,s.useBlockParams=this.useBlockParams}else s.index=c.index,s.name="program"+c.index,this.useDepths=this.useDepths||c.useDepths,this.useBlockParams=this.useBlockParams||c.useBlockParams}},matchExistingProgram:function(e){for(var r=0,n=this.context.environments.length;r<n;r++){var s=this.context.environments[r];if(s&&s.equals(e))return s}},programExpression:function(e){var r=this.environment.children[e],n=[r.index,"data",r.blockParams];return(this.useBlockParams||this.useDepths)&&n.push("blockParams"),this.useDepths&&n.push("depths"),"container.program("+n.join(", ")+")"},useRegister:function(e){this.registers[e]||(this.registers[e]=!0,this.registers.list.push(e))},push:function(e){return e instanceof ks||(e=this.source.wrap(e)),this.inlineStack.push(e),e},pushStackLiteral:function(e){this.push(new ks(e))},pushSource:function(e){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),e&&this.source.push(e)},replaceStack:function(e){var r=["("],n=void 0,s=void 0,o=void 0;if(!this.isInline())throw new Gf.default("replaceStack on non-inline");var i=this.popStack(!0);if(i instanceof ks)n=[i.value],r=["(",n],o=!0;else{s=!0;var a=this.incrStack();r=["((",this.push(a)," = ",i,")"],n=this.topStack()}var c=e.call(this,n);o||this.popStack(),s&&this.stackSlot--,this.push(r.concat(c,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var e=this.inlineStack;this.inlineStack=[];for(var r=0,n=e.length;r<n;r++){var s=e[r];if(s instanceof ks)this.compileStack.push(s);else{var o=this.incrStack();this.pushSource([o," = ",s,";"]),this.compileStack.push(o)}}},isInline:function(){return this.inlineStack.length},popStack:function(e){var r=this.isInline(),n=(r?this.inlineStack:this.compileStack).pop();if(!e&&n instanceof ks)return n.value;if(!r){if(!this.stackSlot)throw new Gf.default("Invalid stack pop");this.stackSlot--}return n},topStack:function(){var e=this.isInline()?this.inlineStack:this.compileStack,r=e[e.length-1];return r instanceof ks?r.value:r},contextName:function(e){return this.useDepths&&e?"depths["+e+"]":"depth"+e},quotedString:function(e){return this.source.quotedString(e)},objectLiteral:function(e){return this.source.objectLiteral(e)},aliasable:function(e){var r=this.aliases[e];return r?(r.referenceCount++,r):(r=this.aliases[e]=this.source.wrap(e),r.aliasable=!0,r.referenceCount=1,r)},setupHelper:function(e,r,n){var s=[],o=this.setupHelperArgs(r,e,s,n),i=this.nameLookup("helpers",r,"helper"),a=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:s,paramsInit:o,name:i,callParams:[a].concat(s)}},setupParams:function(e,r,n){var s={},o=[],i=[],a=[],c=!n,l=void 0;c&&(n=[]),s.name=this.quotedString(e),s.hash=this.popStack(),this.trackIds&&(s.hashIds=this.popStack()),this.stringParams&&(s.hashTypes=this.popStack(),s.hashContexts=this.popStack());var f=this.popStack(),u=this.popStack();(u||f)&&(s.fn=u||"container.noop",s.inverse=f||"container.noop");for(var d=r;d--;)l=this.popStack(),n[d]=l,this.trackIds&&(a[d]=this.popStack()),this.stringParams&&(i[d]=this.popStack(),o[d]=this.popStack());return c&&(s.args=this.source.generateArray(n)),this.trackIds&&(s.ids=this.source.generateArray(a)),this.stringParams&&(s.types=this.source.generateArray(i),s.contexts=this.source.generateArray(o)),this.options.data&&(s.data="data"),this.useBlockParams&&(s.blockParams="blockParams"),s},setupHelperArgs:function(e,r,n,s){var o=this.setupParams(e,r,n);return o.loc=JSON.stringify(this.source.currentLocation),o=this.objectLiteral(o),s?(this.useRegister("options"),n.push("options"),["options=",o]):n?(n.push(o),""):o}};(function(){for(var t="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),e=Os.RESERVED_WORDS={},r=0,n=t.length;r<n;r++)e[t[r]]=!0})();Os.isValidJavaScriptVariableName=function(t){return!Os.RESERVED_WORDS[t]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)};function k0(t,e,r,n,s){var o=e.popStack(),i=r.length;for(t&&i--;n<i;n++)o=e.nameLookup(o,r[n],s);return t?[e.aliasable("container.strict"),"(",o,", ",e.quotedString(r[n]),", ",JSON.stringify(e.source.currentLocation)," )"]:o}Tl.default=Os;gy.exports=Tl.default});var _y=j((Il,wy)=>{"use strict";Il.__esModule=!0;function si(t){return t&&t.__esModule?t:{default:t}}var O0=Sg(),M0=si(O0),L0=Ef(),N0=si(L0),Jf=Lg(),zf=Fg(),D0=yy(),B0=si(D0),F0=vf(),q0=si(F0),U0=wf(),$0=si(U0),H0=M0.default.create;function by(){var t=H0();return t.compile=function(e,r){return zf.compile(e,r,t)},t.precompile=function(e,r){return zf.precompile(e,r,t)},t.AST=N0.default,t.Compiler=zf.Compiler,t.JavaScriptCompiler=B0.default,t.Parser=Jf.parser,t.parse=Jf.parse,t.parseWithoutProcessing=Jf.parseWithoutProcessing,t}var Ms=by();Ms.create=by;$0.default(Ms);Ms.Visitor=q0.default;Ms.default=Ms;Il.default=Ms;wy.exports=Il.default});var X0={};nd(X0,{default:()=>Dl});module.exports=Ly(X0);var Ft=require("obsidian");var yt=require("obsidian");var ze=require("obsidian");var Bl={Error:"Error",user:"user",system:"system",assistant:"assistant",newChat:"newChat","Conversion failed. Selected sections is a":"Conversion failed. Selected sections is a",message:"message","Check the developer console for error details. ":"Check the developer console for error details. ","Cancel generation":"Cancel generation","Regenerate?":"Regenerate?","This will delete the current response content. You can configure this in settings to not require confirmation.":"This will delete the current response content. You can configure this in settings to not require confirmation.",Yes:"Yes","Export conversations to JSONL":"Export conversations to JSONL","No conversation found":"No conversation found","Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.":"Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.","Replace speaker with tag":"Replace speaker with tag","No speaker found":"No speaker found","Replace the names of the two most frequently occurring speakers with tag format.":"Replace the names of the two most frequently occurring speakers with tag format.",Replace:"Replace","Select message at cursor":"Select message at cursor","No message found at cursor":"No message found at cursor","API key is required":"API key is required","API secret is required":"API secret is required","Model is required":"Model is required","API URL is required":"API URL is required","API key may be incorrect. Please check your API key.":"API key may be incorrect. Please check your API key.","Access denied. Please check your API permissions.":"Access denied. Please check your API permissions.","Text Generation":"Text Generation","Image Vision":"Image Vision","PDF Vision":"PDF Vision","Image Generation":"Image Generation","Image Editing":"Image Editing","Web Search":"Web Search",Reasoning:"Reasoning","Only PNG, JPEG, GIF, and WebP images are supported.":"Only PNG, JPEG, GIF, and WebP images are supported.","Only PNG, JPEG, GIF, WebP, and PDF files are supported.":"Only PNG, JPEG, GIF, WebP, and PDF files are supported.","Only the last user message is used for image generation. Other messages are ignored.":"Only the last user message is used for image generation. Other messages are ignored.","Multiple embeds found, only the first one will be used":"Multiple embeds found, only the first one will be used","Only PNG, JPEG, and WebP images are supported for editing.":"Only PNG, JPEG, and WebP images are supported for editing.","Embed data is empty or invalid":"Embed data is empty or invalid","Failed to generate image. no data received from API":"Failed to generate image. no data received from API","Load template file: ":"Load template file: ","Templates have been updated: ":"Templates have been updated: ","Syntax Error Report":"Syntax Error Report","Create prompt template file":"Create prompt template file","Expected at least 2 sections, heading and content":"Expected at least 2 sections, heading and content","Expected heading":"Expected heading","Duplicate title:":"Duplicate title:","Please add a user message first, or wait for the user message to be parsed.":"Please add a user message first, or wait for the user message to be parsed.","Waiting for metadata to be ready. Please try again.":"Waiting for metadata to be ready. Please try again.","No text generated":"No text generated",characters:"characters","Removed commands":"Removed commands","Added commands":"Added commands","No active generation to cancel":"No active generation to cancel","Generation already cancelled":"Generation already cancelled","Generation cancelled":"Generation cancelled","Restore default":"Restore default","AI assistants":"AI assistants","New AI assistant":"New AI assistant","For those compatible with the OpenAI protocol, you can select OpenAI.":"For those compatible with the OpenAI protocol, you can select OpenAI.","Add AI Provider":"Add AI Provider","Please add at least one AI assistant to start using the plugin.":"Please add at least one AI assistant to start using the plugin.","Message tags":"Message tags","Keywords for tags in the text box are separated by spaces":"Keywords for tags in the text box are separated by spaces","New chat tags":"New chat tags","User message tags":"User message tags","System message tags":"System message tags","At least one tag is required":"At least one tag is required","Assistant message tag":"Assistant message tag","Tag used to trigger AI text generation":"Tag used to trigger AI text generation","Obtain key from ":"Obtain key from ","Web search":"Web search","Enable web search for AI":"Enable web search for AI","API key (required)":"API key (required)","Default:":"Default:","Refer to the technical documentation":"Refer to the technical documentation","Keyword for tag must not contain #":"Keyword for tag must not contain #","Keyword for tag must not contain space":"Keyword for tag must not contain space","Keyword for tag must be unique":"Keyword for tag must be unique",Model:"Model","Supported features":"Supported features","Select the model to use":"Select the model to use","Please input API key first":"Please input API key first","Please enter a number":"Please enter a number","Minimum value is 256":"Minimum value is 256","Invalid URL":"Invalid URL","Override input parameters":"Override input parameters",'Developer feature, in JSON format. For example, if the model list doesn\'t have the model you want, enter {"model": "your desired model"}':`Developer feature, in JSON format. For example, if the model list doesn't have the model you want, enter {"model": "your desired model"}`,"Remove AI assistant":"Remove AI assistant",Remove:"Remove",Endpoint:"Endpoint","API version":"API version","Select assistant":"Select assistant","Confirm before regeneration":"Confirm before regeneration","Confirm before replacing existing assistant responses when using assistant commands":"Confirm before replacing existing assistant responses when using assistant commands","Internal links":"Internal links","Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.":"Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.","Internal links for assistant messages":"Internal links for assistant messages","Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.":"Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.","System message":"System message","Enable default system message":"Enable default system message","Automatically add a system message when none exists in the conversation":"Automatically add a system message when none exists in the conversation","Default system message":"Default system message",Advanced:"Advanced","Delay before answer (Seconds)":"Delay before answer (Seconds)","If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.":"If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.","Replace tag Command":"Replace tag Command","Export to JSONL Command":"Export to JSONL Command","Tag suggest":"Tag suggest","If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.":"If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.","Image Display Width":"Image Display Width","Example: 400px width would output as ![[image.jpg|400]]":"Example: 400px width would output as ![[image.jpg|400]]","Number of images":"Number of images","Number of images to generate (1-5)":"Number of images to generate (1-5)","Image size":"Image size",landscape:"landscape",portrait:"portrait","Output format":"Output format",Quality:"Quality","Quality level for generated images. default: Auto":"Quality level for generated images. default: Auto",Auto:"Auto",High:"High",Medium:"Medium",Low:"Low",Background:"Background","Background of the generated image. default: Auto":"Background of the generated image. default: Auto",Transparent:"Transparent",Opaque:"Opaque","Output compression":"Output compression","Compression level of the output image, 10% - 100%. Only for webp or jpeg output format":"Compression level of the output image, 10% - 100%. Only for webp or jpeg output format","AI generate":"AI generate","Text generated successfully":"Text generated successfully","This is a non-streaming request, please wait...":"This is a non-streaming request, please wait...",promptFileName:"prompt.en",PRESET_PROMPT_TEMPLATES:`# Instructions
- Collect your commonly used prompts here for use with the Tars plugin commands.
- This file follows Obsidian's slide format, using \`---\` to separate each page.
- The first page contains instructions, and each subsequent page is a prompt template.
- Each template starts with a title in Markdown heading format, titles cannot be repeated. This is followed by the template content. Both title and content are required.
- If the content contains \`{{s}}\`, it will be replaced with your selected text.
- If there's no \`{{s}}\`, the selected text will be appended.
- If no text is selected, the template content will be used as is.
- If a page contains syntax errors, it won't appear in the command list.
- If you've edited this file, to load the updated templates into commands, please ==run the 'Load template file' command==, which will also check for syntax errors and display them in a popup.
---
# Prompt example
Tell me a joke
---
# Translation
Translate the following content into English\uFF1A{{s}}
---
# One-sentence summary
{{s}} Summarize the above content in one sentence
`,Thinking:"Thinking","When enabled, Claude will show its reasoning process before giving the final answer.":"When enabled, Claude will show its reasoning process before giving the final answer.","Budget tokens for thinking":"Budget tokens for thinking","Must be \u22651024 and less than max_tokens":"Must be \u22651024 and less than max_tokens","Minimum value is 1024":"Minimum value is 1024","AI Generation Details":"AI Generation Details",Round:"Round",Duration:"Duration","Start Time":"Start Time","End Time":"End Time","Error Details":"Error Details","Error Type":"Error Type","Error Message":"Error Message","Occurrence Time":"Occurrence Time","Stack Trace":"Stack Trace","Copy Error Info":"Copy Error Info","Error info copied to clipboard":"Error info copied to clipboard","Unknown Error":"Unknown Error","Tars AI assistant is ready":"Tars AI assistant is ready","Generating round":"Generating round","answer...":"answer...","Generating...":"Generating...","Click status bar for error details. ":"Click status bar for error details. ",Vendor:"Vendor",Characters:"Characters"};var od={Error:"\u5F02\u5E38",user:"\u7528\u6237",system:"\u7CFB\u7EDF",assistant:"\u52A9\u624B",newChat:"\u65B0\u5BF9\u8BDD","Conversion failed. Selected sections is a":"\u8F6C\u6362\u5931\u8D25\u3002\u9009\u4E2D\u7684\u6BB5\u843D\u662F",message:"\u6D88\u606F","Check the developer console for error details. ":"\u67E5\u770B\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u4E86\u89E3\u9519\u8BEF\u8BE6\u60C5\u3002","Cancel generation":"\u53D6\u6D88\u751F\u6210","Regenerate?":"\u91CD\u65B0\u751F\u6210?","This will delete the current response content. You can configure this in settings to not require confirmation.":"\u8FD9\u4F1A\u5220\u6389\u5F53\u524D\u7684\u56DE\u7B54\u5185\u5BB9\u3002\u4F60\u53EF\u4EE5\u5728\u8BBE\u7F6E\u91CC\u914D\u7F6E\u4E0D\u9700\u8981\u5F39\u7A97\u786E\u8BA4\u3002",Yes:"\u662F","Export conversations to JSONL":"\u5BFC\u51FA\u5BF9\u8BDD\u5230 JSONL","No conversation found":"\u6CA1\u6709\u627E\u5230\u5BF9\u8BDD","Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.":"\u5DF2\u7ECF\u5BFC\u51FA\u5230\u540C\u4E00\u76EE\u5F55\uFF0Cobsidian \u4E0D\u663E\u793A jsonl \u683C\u5F0F\uFF0C\u8BF7\u7528\u5176\u4ED6\u8F6F\u4EF6\u6253\u5F00","Replace speaker with tag":"\u628A\u8BF4\u8BDD\u8005\u66FF\u6362\u4E3A\u6807\u7B7E","No speaker found":"\u6CA1\u6709\u627E\u5230\u8BF4\u8BDD\u8005","Replace the names of the two most frequently occurring speakers with tag format.":"\u7528\u6807\u7B7E\u683C\u5F0F\u66FF\u6362\u4E24\u4E2A\u6700\u5E38\u51FA\u73B0\u7684\u8BF4\u8BDD\u8005\u7684\u540D\u5B57",Replace:"\u66FF\u6362","Select message at cursor":"\u9009\u62E9\u5149\u6807\u5904\u7684\u6D88\u606F","No message found at cursor":"\u5149\u6807\u5904\u6CA1\u6709\u627E\u5230\u6D88\u606F","API key is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API key","API secret is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API secret","Model is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684\u6A21\u578B","API URL is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API URL","API key may be incorrect. Please check your API key.":"API key \u53EF\u80FD\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API key\u3002","Access denied. Please check your API permissions.":"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API \u6743\u9650\u3002","Text Generation":"\u6587\u672C\u751F\u6210","Image Vision":"\u56FE\u50CF\u89C6\u89C9","PDF Vision":"PDF\u89C6\u89C9","Image Generation":"\u56FE\u50CF\u751F\u6210","Image Editing":"\u56FE\u50CF\u7F16\u8F91","Web Search":"\u7F51\u7EDC\u641C\u7D22",Reasoning:"\u63A8\u7406","Only PNG, JPEG, GIF, and WebP images are supported.":"\u4EC5\u652F\u6301 PNG\u3001JPEG\u3001GIF \u548C WebP \u683C\u5F0F\u7684\u56FE\u7247\u3002","Only PNG, JPEG, GIF, WebP, and PDF files are supported.":"\u4EC5\u652F\u6301 PNG\u3001JPEG\u3001GIF\u3001WebP \u548C PDF \u6587\u4EF6\u3002","Only the last user message is used for image generation. Other messages are ignored.":"\u4EC5\u4F7F\u7528\u6700\u540E\u4E00\u6761\u7528\u6237\u6D88\u606F\u8FDB\u884C\u56FE\u7247\u751F\u6210\uFF0C\u5176\u4ED6\u6D88\u606F\u5C06\u88AB\u5FFD\u7565\u3002","Multiple embeds found, only the first one will be used":"\u53D1\u73B0\u591A\u4E2A\u5D4C\u5165\u5185\u5BB9\uFF0C\u4EC5\u4F7F\u7528\u7B2C\u4E00\u4E2A","Only PNG, JPEG, and WebP images are supported for editing.":"\u4EC5\u652F\u6301 PNG\u3001JPEG \u548C WebP \u683C\u5F0F\u7684\u56FE\u7247\u8FDB\u884C\u7F16\u8F91","Embed data is empty or invalid":"\u5D4C\u5165\u6570\u636E\u4E3A\u7A7A\u6216\u65E0\u6548","Failed to generate image. no data received from API":"\u751F\u6210\u56FE\u7247\u5931\u8D25\u3002\u6CA1\u6709\u4ECE API \u63A5\u6536\u5230\u6570\u636E","Load template file: ":"\u52A0\u8F7D\u6A21\u677F\u6587\u4EF6: ","Templates have been updated: ":"\u6A21\u677F\u5DF2\u66F4\u65B0: ","Syntax Error Report":"\u8BED\u6CD5\u9519\u8BEF\u62A5\u544A","Create prompt template file":"\u521B\u5EFA\u63D0\u793A\u8BCD\u6A21\u677F\u6587\u4EF6","Expected at least 2 sections, heading and content":"\u81F3\u5C11\u9700\u8981 2 \u4E2A\u90E8\u5206\uFF0C\u6807\u9898\u548C\u5185\u5BB9","Expected heading":"\u9700\u8981\u6807\u9898","Duplicate title:":"\u91CD\u590D\u7684\u6807\u9898:","Please add a user message first, or wait for the user message to be parsed.":"\u8BF7\u5148\u6DFB\u52A0\u7528\u6237\u6D88\u606F\uFF0C\u6216\u8005\u7A0D\u7B49\u7528\u6237\u6D88\u606F\u89E3\u6790\u5B8C\u6210","Waiting for metadata to be ready. Please try again.":"\u6B63\u5728\u7B49\u5F85\u5143\u6570\u636E\u51C6\u5907\u5C31\u7EEA\u3002\u8BF7\u91CD\u8BD5\u3002","No text generated":"\u6CA1\u6709\u751F\u6210\u6587\u672C",characters:"\u4E2A\u5B57\u7B26","Removed commands":"\u5DF2\u79FB\u9664\u547D\u4EE4","Added commands":"\u5DF2\u6DFB\u52A0\u547D\u4EE4","No active generation to cancel":"\u6CA1\u6709\u6B63\u5728\u8FDB\u884C\u7684\u751F\u6210\u53EF\u53D6\u6D88","Generation already cancelled":"\u751F\u6210\u5DF2\u7ECF\u53D6\u6D88","Generation cancelled":"\u5DF2\u53D6\u6D88\u751F\u6210","Restore default":"\u6062\u590D\u9ED8\u8BA4","AI assistants":"AI \u52A9\u624B","New AI assistant":"\u65B0\u7684 AI \u52A9\u624B","For those compatible with the OpenAI protocol, you can select OpenAI.":"\u5BF9\u4E8E\u517C\u5BB9 OpenAI \u534F\u8BAE\u7684\uFF0C\u53EF\u4EE5\u9009\u62E9 OpenAI.","Add AI Provider":"\u6DFB\u52A0 AI \u670D\u52A1\u5546","Please add at least one AI assistant to start using the plugin.":"\u8BF7\u81F3\u5C11\u6DFB\u52A0\u4E00\u4E2A AI \u52A9\u624B\uFF0C\u4EE5\u4FBF\u5F00\u59CB\u4F7F\u7528\u63D2\u4EF6","Message tags":"\u6D88\u606F\u6807\u7B7E","Keywords for tags in the text box are separated by spaces":"\u5728\u6587\u672C\u6846\u4E2D\u7684\u6807\u7B7E\u5173\u952E\u5B57\u7528\u7A7A\u683C\u5206\u9694","New chat tags":"\u65B0\u5BF9\u8BDD\u7684\u6807\u7B7E","User message tags":"\u7528\u6237\u6D88\u606F\u7684\u6807\u7B7E","System message tags":"\u7CFB\u7EDF\u6D88\u606F\u7684\u6807\u7B7E","At least one tag is required":"\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u6807\u7B7E","Assistant message tag":"\u52A9\u624B\u6D88\u606F\u7684\u6807\u7B7E","Tag used to trigger AI text generation":"\u7528\u4E8E\u89E6\u53D1 AI \u6587\u672C\u751F\u6210\u7684\u6807\u7B7E","Obtain key from ":"\u83B7\u53D6 key \u7F51\u7AD9 ","Web search":"\u7F51\u7EDC\u641C\u7D22","Enable web search for AI":"\u4E3A\u5F53\u524D AI \u542F\u7528\u7F51\u7EDC\u641C\u7D22","API key (required)":"API Key (\u5FC5\u586B)","Default:":"\u9ED8\u8BA4:","Refer to the technical documentation":"\u53C2\u8003\u6280\u672F\u6587\u6863","Keyword for tag must not contain #":"\u6807\u7B7E\u5173\u952E\u5B57\u4E0D\u80FD\u5305\u542B #","Keyword for tag must not contain space":"\u6807\u7B7E\u5173\u952E\u5B57\u4E0D\u80FD\u5305\u542B\u7A7A\u683C","Keyword for tag must be unique":"\u6807\u7B7E\u5173\u952E\u5B57\u5FC5\u987B\u552F\u4E00",Model:"\u6A21\u578B","Supported features":"\u652F\u6301\u529F\u80FD","Select the model to use":"\u9009\u62E9\u8981\u4F7F\u7528\u7684\u6A21\u578B","Please input API key first":"\u8BF7\u5148\u8F93\u5165 API key","Please enter a number":"\u8BF7\u8F93\u5165\u4E00\u4E2A\u6570\u5B57","Minimum value is 256":"\u6700\u5C0F\u503C\u662F256","Invalid URL":"\u65E0\u6548\u7684 URL","Override input parameters":"\u8986\u76D6\u8F93\u5165\u53C2\u6570",'Developer feature, in JSON format. For example, if the model list doesn\'t have the model you want, enter {"model": "your desired model"}':'\u5F00\u53D1\u8005\u529F\u80FD\uFF0C\u4EE5 JSON \u683C\u5F0F\u3002\u4F8B\u5982: \u6A21\u578B\u5217\u8868\u4E2D\u6CA1\u6709\u4F60\u9700\u8981\u7684\u6A21\u578B\u65F6\uFF0C\u53EF\u4EE5\u586B\u5165 {"model": "\u4F60\u60F3\u8981\u7684model"}',"Remove AI assistant":"\u79FB\u9664 AI \u52A9\u624B",Remove:"\u79FB\u9664",Endpoint:"\u7EC8\u7ED3\u70B9","API version":"API \u7248\u672C","Select assistant":"\u9009\u62E9\u52A9\u624B","Confirm before regeneration":"\u91CD\u65B0\u751F\u6210\u524D\u662F\u5426\u9700\u8981\u786E\u8BA4","Confirm before replacing existing assistant responses when using assistant commands":"\u5728\u4F7F\u7528\u52A9\u624B\u6807\u7B7E\u547D\u4EE4\u65F6\uFF0C\u66FF\u6362\u65E7\u7684\u52A9\u624B\u6D88\u606F\uFF0C\u662F\u5426\u9700\u8981\u5F39\u7A97\u786E\u8BA4","Internal links":"\u5185\u90E8\u94FE\u63A5","Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.":"\u7528\u6237\u548C\u7CFB\u7EDF\u6D88\u606F\u4E2D\u7684\u5185\u90E8\u94FE\u63A5\u5C06\u88AB\u66FF\u6362\u4E3A\u5176\u5F15\u7528\u7684\u5185\u5BB9\u3002\u7981\u7528\u65F6\uFF0C\u4EC5\u4F7F\u7528\u94FE\u63A5\u7684\u539F\u59CB\u6587\u672C\u3002","Internal links for assistant messages":"\u52A9\u624B\u6D88\u606F\u7684\u5185\u90E8\u94FE\u63A5","Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.":"\u52A9\u624B\u6D88\u606F\u4E2D\u7684\u5185\u90E8\u94FE\u63A5\u66FF\u6362\u4E3A\u5176\u5F15\u7528\u7684\u5185\u5BB9\u3002\u6CE8\u610F\uFF1A\u901A\u5E38\u60C5\u51B5\u4E0B\u4E0D\u5EFA\u8BAE\u542F\u7528\u6B64\u529F\u80FD\uFF0C\u56E0\u4E3A\u52A9\u624B\u751F\u6210\u7684\u5185\u5BB9\u53EF\u80FD\u5305\u542B\u4E0D\u5B58\u5728\u7684\u94FE\u63A5\u3002","System message":"\u7CFB\u7EDF\u6D88\u606F","Enable default system message":"\u542F\u7528\u9ED8\u8BA4\u7CFB\u7EDF\u6D88\u606F","Automatically add a system message when none exists in the conversation":"\u5F53\u5BF9\u8BDD\u4E2D\u6CA1\u6709\u7CFB\u7EDF\u6D88\u606F\u65F6\uFF0C\u81EA\u52A8\u6DFB\u52A0\u81EA\u5B9A\u4E49\u7684\u9ED8\u8BA4\u7684\u7CFB\u7EDF\u6D88\u606F","Default system message":"\u9ED8\u8BA4\u7CFB\u7EDF\u6D88\u606F",Advanced:"\u9AD8\u7EA7","Delay before answer (Seconds)":"\u56DE\u7B54\u524D\u7684\u5EF6\u8FDF\uFF08\u79D2\uFF09","If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.":"\u5728\u9009\u4E2D\u6587\u672C\u6267\u884C\u52A9\u624B\u547D\u4EE4\u7684\u65F6\u5019\uFF0C\u5982\u679C\u9047\u5230\u7F3A\u5C11\u7528\u6237\u6D88\u606F\u7684\u9519\u8BEF\uFF0C\u53EF\u80FD\u662F\u9700\u8981\u66F4\u591A\u65F6\u95F4\u6765\u89E3\u6790\u6D88\u606F\uFF0C\u8BF7\u7A0D\u5FAE\u589E\u52A0\u5EF6\u8FDF","Replace tag Command":"\u66FF\u6362\u6807\u7B7E\u547D\u4EE4","Export to JSONL Command":"\u5BFC\u51FA\u5230 JSONL \u547D\u4EE4","Tag suggest":"\u6807\u7B7E\u5EFA\u8BAE","If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.":"\u5982\u679C\u4F60\u53EA\u4F7F\u7528\u547D\u4EE4\u800C\u4E0D\u9700\u8981\u6807\u7B7E\u5EFA\u8BAE\uFF0C\u53EF\u4EE5\u7981\u7528\u6B64\u529F\u80FD\u3002\u66F4\u6539\u5C06\u5728\u91CD\u65B0\u542F\u52A8\u63D2\u4EF6\u540E\u751F\u6548\u3002","Image Display Width":"\u56FE\u7247\u663E\u793A\u5BBD\u5EA6","Example: 400px width would output as ![[image.jpg|400]]":"\u4F8B\u5982: 400px \u5BBD\u5EA6\u4F1A\u8F93\u51FA\u4E3A ![[image.jpg|400]]","Number of images":"\u56FE\u7247\u6570\u91CF","Number of images to generate (1-5)":"\u751F\u6210\u7684\u56FE\u7247\u6570\u91CF (1-5)","Image size":"\u56FE\u7247\u5C3A\u5BF8",landscape:"\u6A2A\u5411",portrait:"\u7EB5\u5411","Output format":"\u8F93\u51FA\u683C\u5F0F",Quality:"\u8D28\u91CF","Quality level for generated images. default: Auto":"\u751F\u6210\u56FE\u7247\u7684\u8D28\u91CF\u7B49\u7EA7\u3002\u9ED8\u8BA4: \u81EA\u52A8",Auto:"\u81EA\u52A8",High:"\u9AD8",Medium:"\u4E2D",Low:"\u4F4E",Background:"\u80CC\u666F","Background of the generated image. default: Auto":"\u751F\u6210\u56FE\u7247\u7684\u80CC\u666F\u3002\u9ED8\u8BA4: \u81EA\u52A8",Transparent:"\u900F\u660E",Opaque:"\u4E0D\u900F\u660E","Output compression":"\u8F93\u51FA\u538B\u7F29","Compression level of the output image, 10% - 100%. Only for webp or jpeg output format":"\u8F93\u51FA\u56FE\u7247\u7684\u538B\u7F29\u7EA7\u522B\uFF0C10% - 100%\u3002\u4EC5\u9002\u7528\u4E8E webp \u6216 jpeg \u8F93\u51FA\u683C\u5F0F","AI generate":"AI \u751F\u6210","Text generated successfully":"\u6587\u672C\u751F\u6210\u6210\u529F","This is a non-streaming request, please wait...":"\u8FD9\u662F\u4E00\u4E2A\u975E\u6D41\u5F0F\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u5019...",promptFileName:"prompt.zh",PRESET_PROMPT_TEMPLATES:`# \u4F7F\u7528\u8BF4\u660E
- \u628A\u4F60\u7684\u5E38\u7528\u63D0\u793A\u8BCD\u6536\u96C6\u5230\u8FD9\u91CC\uFF0C\u4EE5\u4FBF\u5728Tars\u63D2\u4EF6\u7684\u547D\u4EE4\u4E2D\u4F7F\u7528\u3002
- \u672C\u6587\u4EF6\u6309\u7167 obsidian \u7684\u5E7B\u706F\u7247\u683C\u5F0F\uFF0C\u7528\`---\`\u6765\u5206\u9694\u6BCF\u4E00\u9875
- \u7B2C\u4E00\u9875\u662F\u8BF4\u660E\uFF0C\u540E\u9762\u7684\u6BCF\u4E00\u9875\u90FD\u662F\u4E00\u4E2A\u63D0\u793A\u8BCD\u6A21\u677F
- \u9996\u5148\u662F\u6A21\u677F\u7684\u6807\u9898, \u4EE5markdown\u7684\u6807\u9898\u683C\u5F0F, \u6807\u9898\u4E0D\u80FD\u91CD\u590D\u3002\u63A5\u4E0B\u6765\u90FD\u662F\u6A21\u677F\u7684\u5185\u5BB9\u3002\u6807\u9898\u548C\u5185\u5BB9\u90FD\u4E0D\u53EF\u7F3A\u5C11\u3002
- \u5982\u679C\u5185\u5BB9\u6709 \`{{s}}\`\uFF0C\u4F1A\u628A \`{{s}}\`\u66FF\u6362\u4E3A\u9009\u4E2D\u7684\u6587\u672C
- \u5982\u679C\u6CA1\u6709 \`{{s}}\`\uFF0C\u5219\u8FFD\u52A0
- \u5982\u679C\u6CA1\u6709\u9009\u4E2D\u7684\u6587\u672C\uFF0C\u5219\u76F4\u63A5\u4F7F\u7528\u6A21\u677F\u7684\u5185\u5BB9
- \u5982\u679C\u67D0\u4E00\u9875\u6709\u8BED\u6CD5\u9519\u8BEF\uFF0C\u5219\u4E0D\u4F1A\u51FA\u73B0\u5728\u547D\u4EE4\u4E2D
- \u5982\u679C\u4F60\u7F16\u8F91\u4E86\u8BE5\u6587\u4EF6\uFF0C\u8981\u628A\u66F4\u65B0\u540E\u7684\u6A21\u677F\u52A0\u8F7D\u5230\u547D\u4EE4\u4E2D\uFF0C==\u6267\u884C\u547D\u4EE4\u201C\u52A0\u8F7D\u6A21\u677F\u6587\u4EF6\u201D==\uFF0C\u8BE5\u547D\u4EE4\u540C\u65F6\u4F1A\u68C0\u67E5\u8BED\u6CD5\u9519\u8BEF\u5E76\u5F39\u7A97\u663E\u793A\u3002
---
# \u63D0\u793A\u8BCD\u4F8B\u5B50
\u7ED9\u6211\u8BB2\u4E2A\u7B11\u8BDD
---
# \u7FFB\u8BD1
\u628A\u4EE5\u4E0B\u5185\u5BB9\u7FFB\u8BD1\u4E3A\u4E2D\u6587\uFF1A{{s}}
---
# \u4E00\u53E5\u8BDD\u603B\u7ED3
{{s}} \u7528\u4E00\u53E5\u8BDD\u603B\u7ED3\u4EE5\u4E0A\u5185\u5BB9
`,Thinking:"\u601D\u8003","When enabled, Claude will show its reasoning process before giving the final answer.":"\u542F\u7528\u540E\uFF0CClaude \u5C06\u5728\u7ED9\u51FA\u6700\u7EC8\u7B54\u6848\u524D\u5C55\u793A\u5176\u63A8\u7406\u8FC7\u7A0B","Budget tokens for thinking":"\u601D\u8003\u4EE4\u724C\u9884\u7B97","Must be \u22651024 and less than max_tokens":"\u5FC5\u987B \u22651024 \u4E14\u5C0F\u4E8E max_tokens","Minimum value is 1024":"\u6700\u5C0F\u503C\u4E3A 1024","AI Generation Details":"AI \u751F\u6210\u8BE6\u60C5",Round:"\u56DE\u5408",Duration:"\u7528\u65F6","Start Time":"\u5F00\u59CB\u65F6\u95F4","End Time":"\u7ED3\u675F\u65F6\u95F4","Error Details":"\u9519\u8BEF\u8BE6\u60C5","Error Type":"\u9519\u8BEF\u7C7B\u578B","Error Message":"\u9519\u8BEF\u4FE1\u606F","Occurrence Time":"\u53D1\u751F\u65F6\u95F4","Stack Trace":"\u5806\u6808\u8DDF\u8E2A","Copy Error Info":"\u590D\u5236\u9519\u8BEF\u4FE1\u606F","Error info copied to clipboard":"\u9519\u8BEF\u4FE1\u606F\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","Unknown Error":"\u672A\u77E5\u9519\u8BEF","Tars AI assistant is ready":"Tars AI \u52A9\u624B\u5DF2\u5C31\u7EEA","Generating round":"\u6B63\u5728\u751F\u6210\u7B2C","answer...":"\u8F6E\u56DE\u7B54...","Generating...":"\u6B63\u5728\u751F\u6210...","Click status bar for error details. ":"\u70B9\u51FB\u72B6\u6001\u680F\u67E5\u770B\u9519\u8BEF\u8BE6\u60C5\u3002",Vendor:"\u670D\u52A1\u5546",Characters:"\u5B57\u7B26\u6570"};var id={};var Ny={en:Bl,"zh-TW":id,zh:od},ad=window.localStorage.getItem("language"),Fl=Ny[ad||"en"];function m(t){return Fl||console.error("Error: locale not found",ad),Fl&&Fl[t]||Bl[t]}var Em=require("obsidian");function N(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function b(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var ql=function(){let{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return ql=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Ls(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Ns=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch(e){}try{return new Error(JSON.stringify(t))}catch(e){}}return new Error(t)};var T=class extends Error{},te=class t extends T{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=r;let o=r;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,r,n){let s=r!=null&&r.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new qt({message:n,cause:Ns(r)});let o=r==null?void 0:r.error;return e===400?new sn(e,o,n,s):e===401?new on(e,o,n,s):e===403?new an(e,o,n,s):e===404?new ln(e,o,n,s):e===409?new cn(e,o,n,s):e===422?new un(e,o,n,s):e===429?new fn(e,o,n,s):e>=500?new dn(e,o,n,s):new t(e,o,n,s)}},X=class extends te{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},qt=class extends te{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ut=class extends qt{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},sn=class extends te{},on=class extends te{},an=class extends te{},ln=class extends te{},cn=class extends te{},un=class extends te{},fn=class extends te{},dn=class extends te{},hn=class extends T{constructor(){super("Could not parse response content as the length limit was reached")}},pn=class extends T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var By=/^[a-z][a-z0-9+.-]*:/i,ld=t=>By.test(t);function cd(t){return typeof t!="object"?{}:t!=null?t:{}}function ud(t){if(!t)return!0;for(let e in t)return!1;return!0}function fd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function mn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var dd=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new T(`${t} must be an integer`);if(e<0)throw new T(`${t} must be a positive integer`);return e};var hd=t=>{try{return JSON.parse(t)}catch(e){return}};var Ze=t=>new Promise(e=>setTimeout(e,t));var li={off:0,error:200,warn:300,info:400,debug:500},Ul=(t,e,r)=>{if(t){if(fd(li,t))return t;re(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(li))}`)}};function Ds(){}function ai(t,e,r){return!e||li[t]>li[r]?Ds:e[t].bind(e)}var Fy={error:Ds,warn:Ds,info:Ds,debug:Ds},pd=new WeakMap;function re(t){var o;let e=t.logger,r=(o=t.logLevel)!=null?o:"off";if(!e)return Fy;let n=pd.get(e);if(n&&n[0]===r)return n[1];let s={error:ai("error",e,r),warn:ai("warn",e,r),info:ai("info",e,r),debug:ai("debug",e,r)};return pd.set(e,[r,s]),s}var _t=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var $t="5.1.1";var yd=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";function qy(){return typeof Deno!="undefined"&&Deno.build!=null?"deno":typeof EdgeRuntime!="undefined"?"edge":Object.prototype.toString.call(typeof globalThis.process!="undefined"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Uy=()=>{var r,n,s,o,i;let t=qy();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$t,"X-Stainless-OS":gd(Deno.build.os),"X-Stainless-Arch":md(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(n=(r=Deno.version)==null?void 0:r.deno)!=null?n:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$t,"X-Stainless-OS":gd((s=globalThis.process.platform)!=null?s:"unknown"),"X-Stainless-Arch":md((o=globalThis.process.arch)!=null?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!=null?i:"unknown"};let e=$y();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$t,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function $y(){if(typeof navigator=="undefined"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var md=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",gd=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),ci,bd=()=>ci!=null?ci:ci=Uy();function wd(){if(typeof fetch!="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function $l(...t){let e=globalThis.ReadableStream;if(typeof e=="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function ui(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return $l({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}function Hl(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r!=null&&r.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function _d(t){var n,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(n=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Sd=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Bs="RFC3986",Fs={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:t=>String(t)},jl="RFC1738";var Wy=Array.isArray,et=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var Wl=1024,xd=(t,e,r,n,s)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Wl){let c=o.length>=Wl?o.slice(a,a+Wl):o,l=[];for(let f=0;f<c.length;++f){let u=c.charCodeAt(f);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||s===jl&&(u===40||u===41)){l[l.length]=c.charAt(f);continue}if(u<128){l[l.length]=et[u];continue}if(u<2048){l[l.length]=et[192|u>>6]+et[128|u&63];continue}if(u<55296||u>=57344){l[l.length]=et[224|u>>12]+et[128|u>>6&63]+et[128|u&63];continue}f+=1,u=65536+((u&1023)<<10|c.charCodeAt(f)&1023),l[l.length]=et[240|u>>18]+et[128|u>>12&63]+et[128|u>>6&63]+et[128|u&63]}i+=l.join("")}return i};function Ed(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Vl(t,e){if(Wy(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Vy=Object.prototype.hasOwnProperty,Ad={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},tt=Array.isArray,Ky=Array.prototype.push,vd=function(t,e){Ky.apply(t,tt(e)?e:[e])},Gy=Date.prototype.toISOString,ne={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xd,encodeValuesOnly:!1,format:Bs,formatter:Fs[Bs],indices:!1,serializeDate(t){return Gy.call(t)},skipNulls:!1,strictNullHandling:!1};function Jy(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Kl={};function Cd(t,e,r,n,s,o,i,a,c,l,f,u,d,h,p,y,g,S){let _=t,v=S,C=0,x=!1;for(;(v=v.get(Kl))!==void 0&&!x;){let q=v.get(t);if(C+=1,typeof q!="undefined"){if(q===C)throw new RangeError("Cyclic object value");x=!0}typeof v.get(Kl)=="undefined"&&(C=0)}if(typeof l=="function"?_=l(e,_):_ instanceof Date?_=d==null?void 0:d(_):r==="comma"&&tt(_)&&(_=Vl(_,function(q){return q instanceof Date?d==null?void 0:d(q):q})),_===null){if(o)return c&&!y?c(e,ne.encoder,g,"key",h):e;_=""}if(Jy(_)||Ed(_)){if(c){let q=y?e:c(e,ne.encoder,g,"key",h);return[(p==null?void 0:p(q))+"="+(p==null?void 0:p(c(_,ne.encoder,g,"value",h)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(_)))]}let P=[];if(typeof _=="undefined")return P;let k;if(r==="comma"&&tt(_))y&&c&&(_=Vl(_,c)),k=[{value:_.length>0?_.join(",")||null:void 0}];else if(tt(l))k=l;else{let q=Object.keys(_);k=f?q.sort(f):q}let O=a?String(e).replace(/\./g,"%2E"):String(e),F=n&&tt(_)&&_.length===1?O+"[]":O;if(s&&tt(_)&&_.length===0)return F+"[]";for(let q=0;q<k.length;++q){let V=k[q],H=typeof V=="object"&&typeof V.value!="undefined"?V.value:_[V];if(i&&H===null)continue;let ee=u&&a?V.replace(/\./g,"%2E"):V,xe=tt(_)?typeof r=="function"?r(F,ee):F:F+(u?"."+ee:"["+ee+"]");S.set(t,C);let ue=new WeakMap;ue.set(Kl,S),vd(P,Cd(H,xe,r,n,s,o,i,a,r==="comma"&&y&&tt(_)?null:c,l,f,u,d,h,p,y,g,ue))}return P}function zy(t=ne){if(typeof t.allowEmptyArrays!="undefined"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys!="undefined"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder!="undefined"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ne.charset;if(typeof t.charset!="undefined"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Bs;if(typeof t.format!="undefined"){if(!Vy.call(Fs,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Fs[r],s=ne.filter;(typeof t.filter=="function"||tt(t.filter))&&(s=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in Ad?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=ne.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots=="undefined"?t.encodeDotInKeys?!0:ne.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ne.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ne.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ne.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter=="undefined"?ne.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ne.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ne.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ne.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ne.encodeValuesOnly,filter:s,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ne.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ne.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ne.strictNullHandling}}function Gl(t,e={}){let r=t,n=zy(e),s,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):tt(n.filter)&&(o=n.filter,s=o);let i=[];if(typeof r!="object"||r===null)return"";let a=Ad[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;s||(s=Object.keys(r)),n.sort&&s.sort(n.sort);let l=new WeakMap;for(let d=0;d<s.length;++d){let h=s[d];n.skipNulls&&r[h]===null||vd(i,Cd(r[h],h,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let f=i.join(n.delimiter),u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),f.length>0?u+f:""}function Pd(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var fi;function gn(t){let e;return(fi!=null?fi:(e=new globalThis.TextEncoder,fi=e.encode.bind(e)))(t)}var di;function Jl(t){let e;return(di!=null?di:(e=new globalThis.TextDecoder,di=e.decode.bind(e)))(t)}var Ee,Ae,fr=class{constructor(){Ee.set(this,void 0),Ae.set(this,void 0),N(this,Ee,new Uint8Array,"f"),N(this,Ae,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gn(e):e;N(this,Ee,Pd([b(this,Ee,"f"),r]),"f");let n=[],s;for(;(s=Yy(b(this,Ee,"f"),b(this,Ae,"f")))!=null;){if(s.carriage&&b(this,Ae,"f")==null){N(this,Ae,s.index,"f");continue}if(b(this,Ae,"f")!=null&&(s.index!==b(this,Ae,"f")+1||s.carriage)){n.push(Jl(b(this,Ee,"f").subarray(0,b(this,Ae,"f")-1))),N(this,Ee,b(this,Ee,"f").subarray(b(this,Ae,"f")),"f"),N(this,Ae,null,"f");continue}let o=b(this,Ae,"f")!==null?s.preceding-1:s.preceding,i=Jl(b(this,Ee,"f").subarray(0,o));n.push(i),N(this,Ee,b(this,Ee,"f").subarray(s.index),"f"),N(this,Ae,null,"f")}return n}flush(){return b(this,Ee,"f").length?this.decode(`
`):[]}};Ee=new WeakMap,Ae=new WeakMap;fr.NEWLINE_CHARS=new Set([`
`,"\r"]);fr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Yy(t,e){for(let s=e!=null?e:0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Rd(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var rt=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*s(){if(n)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let i of Qy(e,r))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(a&&a.error)throw new te(void 0,a.error,void 0,e.headers);yield a}else{let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new te(void 0,a.error,a.message,void 0);yield{event:i.event,data:a}}}o=!0}catch(i){if(Ls(i))return;throw i}finally{o||r.abort()}}return new t(s,r)}static fromReadableStream(e,r){let n=!1;async function*s(){let i=new fr,a=Hl(e);for await(let c of a)for(let l of i.decode(c))yield l;for(let c of i.flush())yield c}async function*o(){if(n)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of s())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(Ls(a))return;throw a}finally{i||r.abort()}}return new t(o,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>s(e),this.controller),new t(()=>s(r),this.controller)]}toReadableStream(){let e=this,r;return $l({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await r.next();if(o)return n.close();let i=gn(JSON.stringify(s)+`
`);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=r.return)==null?void 0:n.call(r))}})}};async function*Qy(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new T("Attempted to iterate over a response with no body");let r=new zl,n=new fr,s=Hl(t.body);for await(let o of Zy(s))for(let i of n.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of n.flush()){let i=r.decode(o);i&&(yield i)}}async function*Zy(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?gn(r):r,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=Rd(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var zl=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,s]=eb(e,":");return s.startsWith(" ")&&(s=s.substring(1)),r==="event"?this.event=s:r==="data"&&this.data.push(s),null}};function eb(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function hi(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var u;if(e.options.stream)return re(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):rt.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let a=r.headers.get("content-type"),c=(u=a==null?void 0:a.split(";")[0])==null?void 0:u.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){let d=await r.json();return Xl(d,r)}return await r.text()})();return re(t).debug(`[${n}] response parsed`,_t({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function Xl(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var qs,dr=class t extends Promise{constructor(e,r,n=hi){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,qs.set(this,void 0),N(this,qs,e,"f")}_thenUnwrap(e){return new t(b(this,qs,"f"),this.responsePromise,async(r,n)=>Xl(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(b(this,qs,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};qs=new WeakMap;var pi,mi=class{constructor(e,r,n,s){pi.set(this,void 0),N(this,pi,e,"f"),this.options=s,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await b(this,pi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(pi=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Us=class extends dr{constructor(e,r,n){super(e,r,async(s,o)=>new n(s,o.response,await hi(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},nt=class extends mi{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}nextPageRequestOptions(){return null}},W=class extends mi{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;let e=this.getPaginatedItems(),r=(n=e[e.length-1])==null?void 0:n.id;return r?{...this.options,query:{...cd(this.options.query),after:r}}:null}};var Ql=()=>{var t;if(typeof File=="undefined"){let{process:e}=globalThis,r=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function yn(t,e,r){return Ql(),new File(t,e!=null?e:"unknown_file",r)}function $s(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Zl=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var ve=async(t,e)=>({...t,body:await nb(t.body,e)}),Td=new WeakMap;function rb(t){let e=typeof t=="function"?t:t.fetch,r=Td.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch(s){return!0}})();return Td.set(e,n),n}var nb=async(t,e)=>{if(!await rb(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>Yl(r,n,s))),r},sb=t=>t instanceof Blob&&"name"in t;var Yl=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,yn([await r.blob()],$s(r)));else if(Zl(r))t.append(e,yn([await new Response(ui(r)).blob()],$s(r)));else if(sb(r))t.append(e,r,$s(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Yl(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Yl(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Id=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",ob=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Id(t),ib=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function gi(t,e,r){if(Ql(),t=await t,ob(t))return t instanceof File?t:yn([await t.arrayBuffer()],t.name);if(ib(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),yn(await ec(s),e,r)}let n=await ec(t);if(e||(e=$s(t)),!(r!=null&&r.type)){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return yn(n,e,r)}async function ec(t){var r;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Id(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Zl(t))for await(let n of t)e.push(...await ec(n));else{let n=(r=t==null?void 0:t.constructor)==null?void 0:r.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${ab(t)}`)}return e}function ab(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var R=class{constructor(e){this._client=e}};function kd(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var cb=(t=kd)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=r.reduce((f,u,d)=>(/[?#]/.test(u)&&(s=!0),f+u+(d===n.length?"":(s?encodeURIComponent:t)(String(n[d])))),""),i=o.split(/[?#]/,1)[0],a=[],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(i))!==null;)a.push({start:l.index,length:l[0].length});if(a.length>0){let f=0,u=a.reduce((d,h)=>{let p=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,d+p+y},"");throw new T(`Path parameters result in path with invalid segments:
${o}
${u}`)}return o},A=cb(kd);var hr=class extends R{list(e,r={},n){return this._client.getAPIList(A`/chat/completions/${e}/messages`,W,{query:r,...n})}};function Od(t){return typeof t.parse=="function"}var bn=t=>(t==null?void 0:t.role)==="assistant",tc=t=>(t==null?void 0:t.role)==="tool";var rc,yi,bi,Hs,js,wi,Ws,St,Vs,_i,Si,wn,Md,Ht=class{constructor(){rc.add(this),this.controller=new AbortController,yi.set(this,void 0),bi.set(this,()=>{}),Hs.set(this,()=>{}),js.set(this,void 0),wi.set(this,()=>{}),Ws.set(this,()=>{}),St.set(this,{}),Vs.set(this,!1),_i.set(this,!1),Si.set(this,!1),wn.set(this,!1),N(this,yi,new Promise((e,r)=>{N(this,bi,e,"f"),N(this,Hs,r,"f")}),"f"),N(this,js,new Promise((e,r)=>{N(this,wi,e,"f"),N(this,Ws,r,"f")}),"f"),b(this,yi,"f").catch(()=>{}),b(this,js,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},b(this,rc,"m",Md).bind(this))},0)}_connected(){this.ended||(b(this,bi,"f").call(this),this._emit("connect"))}get ended(){return b(this,Vs,"f")}get errored(){return b(this,_i,"f")}get aborted(){return b(this,Si,"f")}abort(){this.controller.abort()}on(e,r){return(b(this,St,"f")[e]||(b(this,St,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=b(this,St,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(b(this,St,"f")[e]||(b(this,St,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{N(this,wn,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){N(this,wn,!0,"f"),await b(this,js,"f")}_emit(e,...r){if(b(this,Vs,"f"))return;e==="end"&&(N(this,Vs,!0,"f"),b(this,wi,"f").call(this));let n=b(this,St,"f")[e];if(n&&(b(this,St,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!b(this,wn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),b(this,Hs,"f").call(this,s),b(this,Ws,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!b(this,wn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),b(this,Hs,"f").call(this,s),b(this,Ws,"f").call(this,s),this._emit("end")}}_emitFinal(){}};yi=new WeakMap,bi=new WeakMap,Hs=new WeakMap,js=new WeakMap,wi=new WeakMap,Ws=new WeakMap,St=new WeakMap,Vs=new WeakMap,_i=new WeakMap,Si=new WeakMap,wn=new WeakMap,rc=new WeakSet,Md=function(e){if(N(this,_i,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return N(this,Si,!0,"f"),this._emit("abort",e);if(e instanceof T)return this._emit("error",e);if(e instanceof Error){let r=new T(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new T(String(e)))};function Ks(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function pr(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function Ld(t,e){return!e||!nc(e)?{...t,choices:t.choices.map(r=>({...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Gs(t,e)}function Gs(t,e){let r=t.choices.map(n=>{var s,o;if(n.finish_reason==="length")throw new hn;if(n.finish_reason==="content_filter")throw new pn;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:(o=(s=n.message.tool_calls)==null?void 0:s.map(i=>hb(e,i)))!=null?o:void 0}:void 0,parsed:n.message.content&&!n.message.refusal?db(e,n.message.content):null}}});return{...t,choices:r}}function db(t,e){var r,n;return((r=t.response_format)==null?void 0:r.type)!=="json_schema"?null:((n=t.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function hb(t,e){var n;let r=(n=t.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:pr(r)?r.$parseRaw(e.function.arguments):r!=null&&r.function.strict?JSON.parse(e.function.arguments):null}}}function Nd(t,e){var n;if(!t)return!1;let r=(n=t.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return pr(r)||(r==null?void 0:r.function.strict)||!1}function nc(t){var e,r;return Ks(t.response_format)?!0:(r=(e=t.tools)==null?void 0:e.some(n=>pr(n)||n.type==="function"&&n.function.strict===!0))!=null?r:!1}function Dd(t){for(let e of t!=null?t:[]){if(e.type!=="function")throw new T(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new T(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var we,sc,xi,oc,ic,ac,Bd,Fd,pb=10,_n=class extends Ht{constructor(){super(...arguments),we.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=(n=e.choices[0])==null?void 0:n.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),tc(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(bn(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new T("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),b(this,we,"m",sc).call(this)}async finalMessage(){return await this.done(),b(this,we,"m",xi).call(this)}async finalFunctionToolCall(){return await this.done(),b(this,we,"m",oc).call(this)}async finalFunctionToolCallResult(){return await this.done(),b(this,we,"m",ic).call(this)}async totalUsage(){return await this.done(),b(this,we,"m",ac).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=b(this,we,"m",xi).call(this);r&&this._emit("finalMessage",r);let n=b(this,we,"m",sc).call(this);n&&this._emit("finalContent",n);let s=b(this,we,"m",oc).call(this);s&&this._emit("finalFunctionToolCall",s);let o=b(this,we,"m",ic).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",b(this,we,"m",ac).call(this))}async _createChatCompletion(e,r,n){let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,we,"m",Bd).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Gs(o,r))}async _runChatCompletion(e,r,n){for(let s of r.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){var h,p,y;let s="tool",{tool_choice:o="auto",stream:i,...a}=r,c=typeof o!="string"&&((h=o==null?void 0:o.function)==null?void 0:h.name),{maxChatCompletions:l=pb}=n||{},f=r.tools.map(g=>{if(pr(g)){if(!g.$callback)throw new T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:g.$callback,name:g.function.name,description:g.function.description||"",parameters:g.function.parameters,parse:g.$parseRaw,strict:!0}}}return g}),u={};for(let g of f)g.type==="function"&&(u[g.function.name||g.function.function.name]=g.function);let d="tools"in r?f.map(g=>g.type==="function"?{type:"function",function:{name:g.function.name||g.function.function.name,parameters:g.function.parameters,description:g.function.description,strict:g.function.strict}}:g):void 0;for(let g of r.messages)this._addMessage(g,!1);for(let g=0;g<l;++g){let _=(p=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:d,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!_)throw new T("missing message in ChatCompletion response");if(!((y=_.tool_calls)!=null&&y.length))return;for(let v of _.tool_calls){if(v.type!=="function")continue;let C=v.id,{name:x,arguments:P}=v.function,k=u[x];if(k){if(c&&c!==x){let V=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:C,content:V});continue}}else{let V=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(u).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:C,content:V});continue}let O;try{O=Od(k)?await k.parse(P):P}catch(V){let H=V instanceof Error?V.message:String(V);this._addMessage({role:s,tool_call_id:C,content:H});continue}let F=await k.function(O,this),q=b(this,we,"m",Fd).call(this,F);if(this._addMessage({role:s,tool_call_id:C,content:q}),c)return}}}};we=new WeakSet,sc=function(){var e;return(e=b(this,we,"m",xi).call(this).content)!=null?e:null},xi=function(){var r,n;let e=this.messages.length;for(;e-- >0;){let s=this.messages[e];if(bn(s))return{...s,content:(r=s.content)!=null?r:null,refusal:(n=s.refusal)!=null?n:null}}throw new T("stream ended without producing a ChatCompletionMessage with role=assistant")},oc=function(){var e,r;for(let n=this.messages.length-1;n>=0;n--){let s=this.messages[n];if(bn(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(r=s.tool_calls.at(-1))==null?void 0:r.function}},ic=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(tc(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===r.tool_call_id))}))return r.content}},ac=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},Bd=function(e){if(e.n!=null&&e.n>1)throw new T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Fd=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Js=class t extends _n{static runTools(e,r,n){let s=new t,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}_addMessage(e,r=!0){super._addMessage(e,r),bn(e)&&e.content&&this._emit("content",e.content)}};var ae={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},lc=class extends Error{},cc=class extends Error{};function mb(t,e=ae.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return gb(t.trim(),e)}var gb=(t,e)=>{let r=t.length,n=0,s=d=>{throw new lc(`${d} at position ${n}`)},o=d=>{throw new cc(`${d} at position ${n}`)},i=()=>(u(),n>=r&&s("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||ae.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ae.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ae.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ae.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ae.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ae.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):f()),a=()=>{let d=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(d,++n-Number(h)))}catch(p){o(String(p))}else if(ae.STR&e)try{return JSON.parse(t.substring(d,n-Number(h))+'"')}catch(p){return JSON.parse(t.substring(d,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{n++,u();let d={};try{for(;t[n]!=="}";){if(u(),n>=r&&ae.OBJ&e)return d;let h=a();u(),n++;try{let p=i();Object.defineProperty(d,h,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(ae.OBJ&e)return d;throw p}u(),t[n]===","&&n++}}catch(h){if(ae.OBJ&e)return d;s("Expected '}' at end of object")}return n++,d},l=()=>{n++;let d=[];try{for(;t[n]!=="]";)d.push(i()),u(),t[n]===","&&n++}catch(h){if(ae.ARR&e)return d;s("Expected ']' at end of array")}return n++,d},f=()=>{if(n===0){t==="-"&&ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(ae.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch(p){}o(String(h))}}let d=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ae.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(d,n))}catch(h){t.substring(d,n)==="-"&&ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(d,t.lastIndexOf("e")))}catch(p){o(String(p))}}},u=()=>{for(;n<r&&`
\r `.includes(t[n]);)n++};return i()},uc=t=>mb(t,ae.ALL^ae.NUM);var se,xt,Sn,jt,fc,Ei,dc,hc,pc,Ai,mc,qd,mr=class t extends _n{constructor(e){super(),se.add(this),xt.set(this,void 0),Sn.set(this,void 0),jt.set(this,void 0),N(this,xt,e,"f"),N(this,Sn,[],"f")}get currentChatCompletionSnapshot(){return b(this,jt,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let s=new t(r);return s._run(()=>s._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,r,n){var i;super._createChatCompletion;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,se,"m",fc).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of o)b(this,se,"m",dc).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new X;return this._addChatCompletion(b(this,se,"m",Ai).call(this))}async _fromReadableStream(e,r){var i;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),b(this,se,"m",fc).call(this),this._connected();let s=rt.fromReadableStream(e,this.controller),o;for await(let a of s)o&&o!==a.id&&this._addChatCompletion(b(this,se,"m",Ai).call(this)),b(this,se,"m",dc).call(this,a),o=a.id;if((i=s.controller.signal)!=null&&i.aborted)throw new X;return this._addChatCompletion(b(this,se,"m",Ai).call(this))}[(xt=new WeakMap,Sn=new WeakMap,jt=new WeakMap,se=new WeakSet,fc=function(){this.ended||N(this,jt,void 0,"f")},Ei=function(r){let n=b(this,Sn,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},b(this,Sn,"f")[r.index]=n,n)},dc=function(r){var s,o,i,a,c,l,f,u,d,h,p,y,g,S,_,v,C,x,P,k;if(this.ended)return;let n=b(this,se,"m",qd).call(this,r);this._emit("chunk",r,n);for(let O of r.choices){let F=n.choices[O.index];O.delta.content!=null&&((s=F.message)==null?void 0:s.role)==="assistant"&&((o=F.message)!=null&&o.content)&&(this._emit("content",O.delta.content,F.message.content),this._emit("content.delta",{delta:O.delta.content,snapshot:F.message.content,parsed:F.message.parsed})),O.delta.refusal!=null&&((i=F.message)==null?void 0:i.role)==="assistant"&&((a=F.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:O.delta.refusal,snapshot:F.message.refusal}),((c=O.logprobs)==null?void 0:c.content)!=null&&((l=F.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=O.logprobs)==null?void 0:f.content,snapshot:(d=(u=F.logprobs)==null?void 0:u.content)!=null?d:[]}),((h=O.logprobs)==null?void 0:h.refusal)!=null&&((p=F.message)==null?void 0:p.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=O.logprobs)==null?void 0:y.refusal,snapshot:(S=(g=F.logprobs)==null?void 0:g.refusal)!=null?S:[]});let q=b(this,se,"m",Ei).call(this,F);F.finish_reason&&(b(this,se,"m",pc).call(this,F),q.current_tool_call_index!=null&&b(this,se,"m",hc).call(this,F,q.current_tool_call_index));for(let V of(_=O.delta.tool_calls)!=null?_:[])q.current_tool_call_index!==V.index&&(b(this,se,"m",pc).call(this,F),q.current_tool_call_index!=null&&b(this,se,"m",hc).call(this,F,q.current_tool_call_index)),q.current_tool_call_index=V.index;for(let V of(v=O.delta.tool_calls)!=null?v:[]){let H=(C=F.message.tool_calls)==null?void 0:C[V.index];H!=null&&H.type&&((H==null?void 0:H.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(x=H.function)==null?void 0:x.name,index:V.index,arguments:H.function.arguments,parsed_arguments:H.function.parsed_arguments,arguments_delta:(k=(P=V.function)==null?void 0:P.arguments)!=null?k:""}):(H==null||H.type,void 0))}}},hc=function(r,n){var i,a,c;if(b(this,se,"m",Ei).call(this,r).done_tool_calls.has(n))return;let o=(i=r.message.tool_calls)==null?void 0:i[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let l=(c=(a=b(this,xt,"f"))==null?void 0:a.tools)==null?void 0:c.find(f=>f.type==="function"&&f.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:pr(l)?l.$parseRaw(o.function.arguments):l!=null&&l.function.strict?JSON.parse(o.function.arguments):null})}else o.type},pc=function(r){var s,o;let n=b(this,se,"m",Ei).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=b(this,se,"m",mc).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),(s=r.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),(o=r.logprobs)!=null&&o.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Ai=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let r=b(this,jt,"f");if(!r)throw new T("request ended without sending any chunks");return N(this,jt,void 0,"f"),N(this,Sn,[],"f"),yb(r,b(this,xt,"f"))},mc=function(){var n;let r=(n=b(this,xt,"f"))==null?void 0:n.response_format;return Ks(r)?r:null},qd=function(r){var f,u,d,h,p,y;var n,s,o,i;let a=b(this,jt,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=N(this,jt,{...l,choices:[]},"f");for(let{delta:g,finish_reason:S,index:_,logprobs:v=null,...C}of r.choices){let x=a.choices[_];if(x||(x=a.choices[_]={finish_reason:S,index:_,message:{},logprobs:v,...C}),v)if(!x.logprobs)x.logprobs=Object.assign({},v);else{let{content:H,refusal:ee,...xe}=v;Object.assign(x.logprobs,xe),H&&((f=(n=x.logprobs).content)!=null||(n.content=[]),x.logprobs.content.push(...H)),ee&&((u=(s=x.logprobs).refusal)!=null||(s.refusal=[]),x.logprobs.refusal.push(...ee))}if(S&&(x.finish_reason=S,b(this,xt,"f")&&nc(b(this,xt,"f")))){if(S==="length")throw new hn;if(S==="content_filter")throw new pn}if(Object.assign(x,C),!g)continue;let{content:P,refusal:k,function_call:O,role:F,tool_calls:q,...V}=g;if(Object.assign(x.message,V),k&&(x.message.refusal=(x.message.refusal||"")+k),F&&(x.message.role=F),O&&(x.message.function_call?(O.name&&(x.message.function_call.name=O.name),O.arguments&&((d=(o=x.message.function_call).arguments)!=null||(o.arguments=""),x.message.function_call.arguments+=O.arguments)):x.message.function_call=O),P&&(x.message.content=(x.message.content||"")+P,!x.message.refusal&&b(this,se,"m",mc).call(this)&&(x.message.parsed=uc(x.message.content))),q){x.message.tool_calls||(x.message.tool_calls=[]);for(let{index:H,id:ee,type:xe,function:ue,...Oe}of q){let Qe=(h=(i=x.message.tool_calls)[H])!=null?h:i[H]={};Object.assign(Qe,Oe),ee&&(Qe.id=ee),xe&&(Qe.type=xe),ue&&((y=Qe.function)!=null||(Qe.function={name:(p=ue.name)!=null?p:"",arguments:""})),ue!=null&&ue.name&&(Qe.function.name=ue.name),ue!=null&&ue.arguments&&(Qe.function.arguments+=ue.arguments,Nd(b(this,xt,"f"),Qe)&&(Qe.function.parsed_arguments=uc(Qe.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new rt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function yb(t,e){let{id:r,choices:n,created:s,model:o,system_fingerprint:i,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:f,index:u,logprobs:d,...h})=>{var v,C,x;if(!f)throw new T(`missing finish_reason for choice ${u}`);let{content:p=null,function_call:y,tool_calls:g,...S}=l,_=l.role;if(!_)throw new T(`missing role for choice ${u}`);if(y){let{arguments:P,name:k}=y;if(P==null)throw new T(`missing function_call.arguments for choice ${u}`);if(!k)throw new T(`missing function_call.name for choice ${u}`);return{...h,message:{content:p,function_call:{arguments:P,name:k},role:_,refusal:(v=l.refusal)!=null?v:null},finish_reason:f,index:u,logprobs:d}}return g?{...h,index:u,finish_reason:f,logprobs:d,message:{...S,role:_,content:p,refusal:(C=l.refusal)!=null?C:null,tool_calls:g.map((P,k)=>{let{function:O,type:F,id:q,...V}=P,{arguments:H,name:ee,...xe}=O||{};if(q==null)throw new T(`missing choices[${u}].tool_calls[${k}].id
${vi(t)}`);if(F==null)throw new T(`missing choices[${u}].tool_calls[${k}].type
${vi(t)}`);if(ee==null)throw new T(`missing choices[${u}].tool_calls[${k}].function.name
${vi(t)}`);if(H==null)throw new T(`missing choices[${u}].tool_calls[${k}].function.arguments
${vi(t)}`);return{...V,id:q,type:F,function:{...xe,name:ee,arguments:H}}})}}:{...h,message:{...S,content:p,role:_,refusal:(x=l.refusal)!=null?x:null},finish_reason:f,index:u,logprobs:d}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Ld(c,e)}function vi(t){return JSON.stringify(t)}var zs=class t extends mr{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let s=new t(r),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}};var Et=class extends R{constructor(){super(...arguments),this.messages=new hr(this._client)}create(e,r){var n;return this._client.post("/chat/completions",{body:e,...r,stream:(n=e.stream)!=null?n:!1})}retrieve(e,r){return this._client.get(A`/chat/completions/${e}`,r)}update(e,r,n){return this._client.post(A`/chat/completions/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/chat/completions",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/chat/completions/${e}`,r)}parse(e,r){return Dd(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Gs(n,e))}runTools(e,r){return e.stream?zs.runTools(this._client,e,r):Js.runTools(this._client,e,r)}stream(e,r){return mr.createChatCompletion(this._client,e,r)}};Et.Messages=hr;var Wt=class extends R{constructor(){super(...arguments),this.completions=new Et(this._client)}};Wt.Completions=Et;var $d=Symbol("brand.privateNullableHeaders"),Ud=Array.isArray;function*wb(t){if(!t)return;if($d in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Ud(t)?r=t:(e=!0,r=Object.entries(t!=null?t:{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Ud(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var I=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,i]of wb(n)){let a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[$d]:!0,values:e,nulls:r}};var xn=class extends R{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:I([{Accept:"application/octet-stream"},r==null?void 0:r.headers]),__binaryResponse:!0})}};var En=class extends R{create(e,r){var n;return this._client.post("/audio/transcriptions",ve({body:e,...r,stream:(n=e.stream)!=null?n:!1,__metadata:{model:e.model}},this._client))}};var An=class extends R{create(e,r){return this._client.post("/audio/translations",ve({body:e,...r,__metadata:{model:e.model}},this._client))}};var st=class extends R{constructor(){super(...arguments),this.transcriptions=new En(this._client),this.translations=new An(this._client),this.speech=new xn(this._client)}};st.Transcriptions=En;st.Translations=An;st.Speech=xn;var gr=class extends R{create(e,r){return this._client.post("/batches",{body:e,...r})}retrieve(e,r){return this._client.get(A`/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/batches",W,{query:e,...r})}cancel(e,r){return this._client.post(A`/batches/${e}/cancel`,r)}};var vn=class extends R{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/assistants/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},r){return this._client.getAPIList("/assistants",W,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,r){return this._client.delete(A`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var Cn=class extends R{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var Pn=class extends R{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var Vt=class extends R{constructor(){super(...arguments),this.sessions=new Cn(this._client),this.transcriptionSessions=new Pn(this._client)}};Vt.Sessions=Cn;Vt.TranscriptionSessions=Pn;var Rn=class extends R{create(e,r,n){return this._client.post(A`/threads/${e}/messages`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(A`/threads/${s}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/messages/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/threads/${e}/messages`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r,n){let{thread_id:s}=r;return this._client.delete(A`/threads/${s}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var Tn=class extends R{retrieve(e,r,n){let{thread_id:s,run_id:o,...i}=r;return this._client.get(A`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r,n){let{thread_id:s,...o}=r;return this._client.getAPIList(A`/threads/${s}/runs/${e}/steps`,W,{query:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var Hd=t=>{if(typeof Buffer!="undefined"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var ot=t=>{var e,r,n,s,o,i;if(typeof globalThis.process!="undefined")return(n=(r=(e=globalThis.process.env)==null?void 0:e[t])==null?void 0:r.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(i=(o=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:o.call(s,t))==null?void 0:i.trim()};var fe,br,gc,it,Ci,We,wr,In,yr,Ti,Ce,Pi,Ri,Qs,Xs,Ys,jd,Wd,Vd,Kd,Gd,Jd,zd,At=class extends Ht{constructor(){super(...arguments),fe.add(this),gc.set(this,[]),it.set(this,{}),Ci.set(this,{}),We.set(this,void 0),wr.set(this,void 0),In.set(this,void 0),yr.set(this,void 0),Ti.set(this,void 0),Ce.set(this,void 0),Pi.set(this,void 0),Ri.set(this,void 0),Qs.set(this,void 0)}[(gc=new WeakMap,it=new WeakMap,Ci=new WeakMap,We=new WeakMap,wr=new WeakMap,In=new WeakMap,yr=new WeakMap,Ti=new WeakMap,Ce=new WeakMap,Pi=new WeakMap,Ri=new WeakMap,Qs=new WeakMap,fe=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new br;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=rt.fromReadableStream(e,this.controller);for await(let i of s)b(this,fe,"m",Xs).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}toReadableStream(){return new rt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,s){let o=new br;return o._run(()=>o._runToolAssistantStream(e,r,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,s){var c;let o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...s,signal:this.controller.signal});this._connected();for await(let l of a)b(this,fe,"m",Xs).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}static createThreadAssistantStream(e,r,n){let s=new br;return s._run(()=>s._threadAssistantStream(e,r,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,r,n,s){let o=new br;return o._run(()=>o._runAssistantStream(e,r,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return b(this,Pi,"f")}currentRun(){return b(this,Ri,"f")}currentMessageSnapshot(){return b(this,We,"f")}currentRunStepSnapshot(){return b(this,Qs,"f")}async finalRunSteps(){return await this.done(),Object.values(b(this,it,"f"))}async finalMessages(){return await this.done(),Object.values(b(this,Ci,"f"))}async finalRun(){if(await this.done(),!b(this,wr,"f"))throw Error("Final run was not received.");return b(this,wr,"f")}async _createThreadAssistantStream(e,r,n){var a;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let c of i)b(this,fe,"m",Xs).call(this,c);if((a=i.controller.signal)!=null&&a.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}async _createAssistantStream(e,r,n,s){var c;let o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...s,signal:this.controller.signal});this._connected();for await(let l of a)b(this,fe,"m",Xs).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}static accumulateDelta(e,r){for(let[n,s]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(mn(o)&&mn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!mn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,s){return await this._createAssistantStream(r,e,n,s)}async _runToolAssistantStream(e,r,n,s){return await this._createToolAssistantStream(r,e,n,s)}};br=At,Xs=function(e){if(!this.ended)switch(N(this,Pi,e,"f"),b(this,fe,"m",Vd).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":b(this,fe,"m",zd).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":b(this,fe,"m",Wd).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":b(this,fe,"m",jd).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Ys=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");if(!b(this,wr,"f"))throw Error("Final run has not been received");return b(this,wr,"f")},jd=function(e){let[r,n]=b(this,fe,"m",Gd).call(this,e,b(this,We,"f"));N(this,We,r,"f"),b(this,Ci,"f")[r.id]=r;for(let s of n){let o=r.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=r.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=b(this,In,"f")){if(b(this,yr,"f"))switch(b(this,yr,"f").type){case"text":this._emit("textDone",b(this,yr,"f").text,b(this,We,"f"));break;case"image_file":this._emit("imageFileDone",b(this,yr,"f").image_file,b(this,We,"f"));break}N(this,In,s.index,"f")}N(this,yr,r.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(b(this,In,"f")!==void 0){let s=e.data.content[b(this,In,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,b(this,We,"f"));break;case"text":this._emit("textDone",s.text,b(this,We,"f"));break}}b(this,We,"f")&&this._emit("messageDone",e.data),N(this,We,void 0,"f")}},Wd=function(e){let r=b(this,fe,"m",Kd).call(this,e);switch(N(this,Qs,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==b(this,Ti,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(b(this,Ce,"f")&&this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ti,o.index,"f"),N(this,Ce,r.step_details.tool_calls[o.index],"f"),b(this,Ce,"f")&&this._emit("toolCallCreated",b(this,Ce,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":N(this,Qs,void 0,"f"),e.data.step_details.type=="tool_calls"&&b(this,Ce,"f")&&(this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ce,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Vd=function(e){b(this,gc,"f").push(e),this._emit("event",e)},Kd=function(e){switch(e.event){case"thread.run.step.created":return b(this,it,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=b(this,it,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=br.accumulateDelta(r,n.delta);b(this,it,"f")[e.data.id]=s}return b(this,it,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":b(this,it,"f")[e.data.id]=e.data;break}if(b(this,it,"f")[e.data.id])return b(this,it,"f")[e.data.id];throw new Error("No snapshot available")},Gd=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in r.content){let i=r.content[o.index];r.content[o.index]=b(this,fe,"m",Jd).call(this,o,i)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Jd=function(e,r){return br.accumulateDelta(r,e)},zd=function(e){switch(N(this,Ri,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":N(this,wr,e.data,"f"),b(this,Ce,"f")&&(this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ce,void 0,"f"));break;case"thread.run.cancelling":break}};var _r=class extends R{constructor(){super(...arguments),this.steps=new Tn(this._client)}create(e,r,n){var i;let{include:s,...o}=r;return this._client.post(A`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:(i=r.stream)!=null?i:!1})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(A`/threads/${s}/runs/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/runs/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/threads/${e}/runs`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,r,n){let{thread_id:s}=r;return this._client.post(A`/threads/${s}/runs/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,r,n){return At.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let{data:a,response:c}=await this.retrieve(e,r,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=c.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ze(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,r,n){return At.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){var i;let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:(i=r.stream)!=null?i:!1})}async submitToolOutputsAndPoll(e,r,n){let s=await this.submitToolOutputs(e,r,n);return await this.poll(s.id,r,n)}submitToolOutputsStream(e,r,n){return At.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};_r.Steps=Tn;var Kt=class extends R{constructor(){super(...arguments),this.runs=new _r(this._client),this.messages=new Rn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/threads/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r){return this._client.delete(A`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}createAndRun(e,r){var n;return this._client.post("/threads/runs",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:(n=e.stream)!=null?n:!1})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return At.createThreadAssistantStream(e,this._client.beta.threads,r)}};Kt.Runs=_r;Kt.Messages=Rn;var at=class extends R{constructor(){super(...arguments),this.realtime=new Vt(this._client),this.assistants=new vn(this._client),this.threads=new Kt(this._client)}};at.Realtime=Vt;at.Assistants=vn;at.Threads=Kt;var Sr=class extends R{create(e,r){var n;return this._client.post("/completions",{body:e,...r,stream:(n=e.stream)!=null?n:!1})}};var kn=class extends R{retrieve(e,r,n){let{container_id:s}=r;return this._client.get(A`/containers/${s}/files/${e}/content`,{...n,headers:I([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}};var xr=class extends R{constructor(){super(...arguments),this.content=new kn(this._client)}create(e,r,n){return this._client.post(A`/containers/${e}/files`,ve({body:r,...n},this._client))}retrieve(e,r,n){let{container_id:s}=r;return this._client.get(A`/containers/${s}/files/${e}`,n)}list(e,r={},n){return this._client.getAPIList(A`/containers/${e}/files`,W,{query:r,...n})}delete(e,r,n){let{container_id:s}=r;return this._client.delete(A`/containers/${s}/files/${e}`,{...n,headers:I([{Accept:"*/*"},n==null?void 0:n.headers])})}};xr.Content=kn;var Gt=class extends R{constructor(){super(...arguments),this.files=new xr(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r})}retrieve(e,r){return this._client.get(A`/containers/${e}`,r)}list(e={},r){return this._client.getAPIList("/containers",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/containers/${e}`,{...r,headers:I([{Accept:"*/*"},r==null?void 0:r.headers])})}};Gt.Files=xr;var Er=class extends R{create(e,r){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&re(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...r});return n?o:(re(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=Hd(c)}),i)))}};var On=class extends R{retrieve(e,r,n){let{eval_id:s,run_id:o}=r;return this._client.get(A`/evals/${s}/runs/${o}/output_items/${e}`,n)}list(e,r,n){let{eval_id:s,...o}=r;return this._client.getAPIList(A`/evals/${s}/runs/${e}/output_items`,W,{query:o,...n})}};var Ar=class extends R{constructor(){super(...arguments),this.outputItems=new On(this._client)}create(e,r,n){return this._client.post(A`/evals/${e}/runs`,{body:r,...n})}retrieve(e,r,n){let{eval_id:s}=r;return this._client.get(A`/evals/${s}/runs/${e}`,n)}list(e,r={},n){return this._client.getAPIList(A`/evals/${e}/runs`,W,{query:r,...n})}delete(e,r,n){let{eval_id:s}=r;return this._client.delete(A`/evals/${s}/runs/${e}`,n)}cancel(e,r,n){let{eval_id:s}=r;return this._client.post(A`/evals/${s}/runs/${e}`,n)}};Ar.OutputItems=On;var Jt=class extends R{constructor(){super(...arguments),this.runs=new Ar(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r})}retrieve(e,r){return this._client.get(A`/evals/${e}`,r)}update(e,r,n){return this._client.post(A`/evals/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/evals",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/evals/${e}`,r)}};Jt.Runs=Ar;var vr=class extends R{create(e,r){return this._client.post("/files",ve({body:e,...r},this._client))}retrieve(e,r){return this._client.get(A`/files/${e}`,r)}list(e={},r){return this._client.getAPIList("/files",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/files/${e}`,r)}content(e,r){return this._client.get(A`/files/${e}/content`,{...r,headers:I([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Ze(r),i=await this.retrieve(e),Date.now()-o>n)throw new Ut({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var Mn=class extends R{};var Ln=class extends R{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r})}};var Cr=class extends R{constructor(){super(...arguments),this.graders=new Ln(this._client)}};Cr.Graders=Ln;var Nn=class extends R{create(e,r,n){return this._client.getAPIList(A`/fine_tuning/checkpoints/${e}/permissions`,nt,{body:r,method:"post",...n})}retrieve(e,r={},n){return this._client.get(A`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n})}delete(e,r,n){let{fine_tuned_model_checkpoint:s}=r;return this._client.delete(A`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var Pr=class extends R{constructor(){super(...arguments),this.permissions=new Nn(this._client)}};Pr.Permissions=Nn;var Dn=class extends R{list(e,r={},n){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/checkpoints`,W,{query:r,...n})}};var Rr=class extends R{constructor(){super(...arguments),this.checkpoints=new Dn(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r})}retrieve(e,r){return this._client.get(A`/fine_tuning/jobs/${e}`,r)}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",W,{query:e,...r})}cancel(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/cancel`,r)}listEvents(e,r={},n){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/events`,W,{query:r,...n})}pause(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/pause`,r)}resume(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/resume`,r)}};Rr.Checkpoints=Dn;var Ve=class extends R{constructor(){super(...arguments),this.methods=new Mn(this._client),this.jobs=new Rr(this._client),this.checkpoints=new Pr(this._client),this.alpha=new Cr(this._client)}};Ve.Methods=Mn;Ve.Jobs=Rr;Ve.Checkpoints=Pr;Ve.Alpha=Cr;var Bn=class extends R{};var zt=class extends R{constructor(){super(...arguments),this.graderModels=new Bn(this._client)}};zt.GraderModels=Bn;var Tr=class extends R{createVariation(e,r){return this._client.post("/images/variations",ve({body:e,...r},this._client))}edit(e,r){return this._client.post("/images/edits",ve({body:e,...r},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r})}};var Ir=class extends R{retrieve(e,r){return this._client.get(A`/models/${e}`,r)}list(e){return this._client.getAPIList("/models",nt,e)}delete(e,r){return this._client.delete(A`/models/${e}`,r)}};var kr=class extends R{create(e,r){return this._client.post("/moderations",{body:e,...r})}};function Xd(t,e){return!e||!Wb(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:yc(t,e)}function yc(t,e){let r=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Gb(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:jb(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||bc(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function jb(t,e){var r,n,s,o;return((n=(r=t.text)==null?void 0:r.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((o=t.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function Wb(t){var e;return!!Ks((e=t.text)==null?void 0:e.format)}function Vb(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function Kb(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Gb(t,e){var n;let r=Kb((n=t.tools)!=null?n:[],e.name);return{...e,...e,parsed_arguments:Vb(r)?r.$parseRaw(e.arguments):r!=null&&r.strict?JSON.parse(e.arguments):null}}function bc(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Fn,Ii,Xt,ki,Yd,Qd,Zd,eh,Oi=class t extends Ht{constructor(e){super(),Fn.add(this),Ii.set(this,void 0),Xt.set(this,void 0),ki.set(this,void 0),N(this,Ii,e,"f")}static createResponse(e,r,n){let s=new t(r);return s._run(()=>s._createOrRetrieveResponse(e,r,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,r,n){var a,c;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,Fn,"m",Yd).call(this);let o,i=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=(a=r.starting_after)!=null?a:null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let l of o)b(this,Fn,"m",Qd).call(this,l,i);if((c=o.controller.signal)!=null&&c.aborted)throw new X;return b(this,Fn,"m",Zd).call(this)}[(Ii=new WeakMap,Xt=new WeakMap,ki=new WeakMap,Fn=new WeakSet,Yd=function(){this.ended||N(this,Xt,void 0,"f")},Qd=function(r,n){if(this.ended)return;let s=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},o=b(this,Fn,"m",eh).call(this,r);switch(s("event",r),r.type){case"response.output_text.delta":{let i=o.output[r.output_index];if(!i)throw new T(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new T(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new T(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[r.output_index];if(!i)throw new T(`missing output at index ${r.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:s(r.type,r);break}},Zd=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let r=b(this,Xt,"f");if(!r)throw new T("request ended without sending any events");N(this,Xt,void 0,"f");let n=Jb(r,b(this,Ii,"f"));return N(this,ki,n,"f"),n},eh=function(r){let n=b(this,Xt,"f");if(!n){if(r.type!=="response.created")throw new T(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=N(this,Xt,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);s.type==="message"&&s.content.push(r.part);break}case"response.output_text.delta":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);if(s.type==="message"){let o=s.content[r.content_index];if(!o)throw new T(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new T(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);s.type==="function_call"&&(s.arguments+=r.delta);break}case"response.completed":{N(this,Xt,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=b(this,ki,"f");if(!e)throw new T("stream ended without producing a ChatCompletion");return e}};function Jb(t,e){return Xd(t,e)}var qn=class extends R{list(e,r={},n){return this._client.getAPIList(A`/responses/${e}/input_items`,W,{query:r,...n})}};var Yt=class extends R{constructor(){super(...arguments),this.inputItems=new qn(this._client)}create(e,r){var n;return this._client.post("/responses",{body:e,...r,stream:(n=e.stream)!=null?n:!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&bc(s),s))}retrieve(e,r={},n){var s;return this._client.get(A`/responses/${e}`,{query:r,...n,stream:(s=r==null?void 0:r.stream)!=null?s:!1})}delete(e,r){return this._client.delete(A`/responses/${e}`,{...r,headers:I([{Accept:"*/*"},r==null?void 0:r.headers])})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>yc(n,e))}stream(e,r){return Oi.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(A`/responses/${e}/cancel`,r)}};Yt.InputItems=qn;var Un=class extends R{create(e,r,n){return this._client.post(A`/uploads/${e}/parts`,ve({body:r,...n},this._client))}};var Qt=class extends R{constructor(){super(...arguments),this.parts=new Un(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r})}cancel(e,r){return this._client.post(A`/uploads/${e}/cancel`,r)}complete(e,r,n){return this._client.post(A`/uploads/${e}/complete`,{body:r,...n})}};Qt.Parts=Un;var th=async t=>{let e=await Promise.allSettled(t),r=e.filter(s=>s.status==="rejected");if(r.length){for(let s of r)console.error(s.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var $n=class extends R{create(e,r,n){return this._client.post(A`/vector_stores/${e}/file_batches`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(A`/vector_stores/${s}/file_batches/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,r,n){let{vector_store_id:s}=r;return this._client.post(A`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r);return await this.poll(e,s.id,n)}listFiles(e,r,n){let{vector_store_id:s,...o}=r;return this._client.getAPIList(A`/vector_stores/${s}/file_batches/${e}/files`,W,{query:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let{data:a,response:c}=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse();switch(a.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=c.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ze(l);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},s){var d;if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=(d=s==null?void 0:s.maxConcurrency)!=null?d:5,i=Math.min(o,r.length),a=this._client,c=r.values(),l=[...n];async function f(h){for(let p of h){let y=await a.files.create({file:p,purpose:"assistants"},s);l.push(y.id)}}let u=Array(i).fill(c).map(f);return await th(u),await this.createAndPoll(e,{file_ids:l})}};var Hn=class extends R{create(e,r,n){return this._client.post(A`/vector_stores/${e}/files`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(A`/vector_stores/${s}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{vector_store_id:s,...o}=r;return this._client.post(A`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/vector_stores/${e}/files`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r,n){let{vector_store_id:s}=r;return this._client.delete(A`/vector_stores/${s}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(e,s.id,n)}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let a=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse(),c=a.data;switch(c.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=a.response.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ze(l);break;case"failed":case"completed":return c}}}async upload(e,r,n){let s=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,r,n){let s=await this.upload(e,r,n);return await this.poll(e,s.id,n)}content(e,r,n){let{vector_store_id:s}=r;return this._client.getAPIList(A`/vector_stores/${s}/files/${e}/content`,nt,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var vt=class extends R{constructor(){super(...arguments),this.files=new Hn(this._client),this.fileBatches=new $n(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/vector_stores/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},r){return this._client.getAPIList("/vector_stores",W,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,r){return this._client.delete(A`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}search(e,r,n){return this._client.getAPIList(A`/vector_stores/${e}/search`,nt,{body:r,method:"post",...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};vt.Files=Hn;vt.FileBatches=$n;var wc,Mi,D=class{constructor({baseURL:e=ot("OPENAI_BASE_URL"),apiKey:r=ot("OPENAI_API_KEY"),organization:n=(i=>(i=ot("OPENAI_ORG_ID"))!=null?i:null)(),project:s=(a=>(a=ot("OPENAI_PROJECT_ID"))!=null?a:null)(),...o}={}){var f,u,d,h,p,y;if(Mi.set(this,void 0),this.completions=new Sr(this),this.chat=new Wt(this),this.embeddings=new Er(this),this.files=new vr(this),this.images=new Tr(this),this.audio=new st(this),this.moderations=new kr(this),this.models=new Ir(this),this.fineTuning=new Ve(this),this.graders=new zt(this),this.vectorStores=new vt(this),this.beta=new at(this),this.batches=new gr(this),this.uploads=new Qt(this),this.responses=new Yt(this),this.evals=new Jt(this),this.containers=new Gt(this),r===void 0)throw new T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:r,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&yd())throw new T(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=c.baseURL,this.timeout=(f=c.timeout)!=null?f:wc.DEFAULT_TIMEOUT,this.logger=(u=c.logger)!=null?u:console;let l="warn";this.logLevel=l,this.logLevel=(h=(d=Ul(c.logLevel,"ClientOptions.logLevel",this))!=null?d:Ul(ot("OPENAI_LOG"),"process.env['OPENAI_LOG']",this))!=null?h:l,this.fetchOptions=c.fetchOptions,this.maxRetries=(p=c.maxRetries)!=null?p:2,this.fetch=(y=c.fetch)!=null?y:wd(),N(this,Mi,Sd,"f"),this._options=c,this.apiKey=r,this.organization=n,this.project=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}authHeaders(e){return I([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gl(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${$t}`}defaultIdempotencyKey(){return`stainless-node-retry-${ql()}`}makeStatusError(e,r,n,s){return te.generate(e,r,n,s)}buildURL(e,r){let n=ld(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return ud(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(n.search=this.stringifyQuery(r)),n.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new dr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){var S,_,v;let s=await e,o=(S=s.maxRetries)!=null?S:this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:c}=this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=n===void 0?"":`, retryOf: ${n}`,u=Date.now();if(re(this).debug(`[${l}] sending request`,_t({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),(_=s.signal)!=null&&_.aborted)throw new X;let d=new AbortController,h=await this.fetchWithTimeout(a,i,c,d).catch(Ns),p=Date.now();if(h instanceof Error){let C=`retrying, ${r} attempts remaining`;if((v=s.signal)!=null&&v.aborted)throw new X;let x=Ls(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return re(this).info(`[${l}] connection ${x?"timed out":"failed"} - ${C}`),re(this).debug(`[${l}] connection ${x?"timed out":"failed"} (${C})`,_t({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(s,r,n!=null?n:l);throw re(this).info(`[${l}] connection ${x?"timed out":"failed"} - error; no more retries left`),re(this).debug(`[${l}] connection ${x?"timed out":"failed"} (error; no more retries left)`,_t({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),x?new Ut:new qt({cause:h})}let y=[...h.headers.entries()].filter(([C])=>C==="x-request-id").map(([C,x])=>", "+C+": "+JSON.stringify(x)).join(""),g=`[${l}${f}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){let C=this.shouldRetry(h);if(r&&C){let q=`retrying, ${r} attempts remaining`;return await _d(h.body),re(this).info(`${g} - ${q}`),re(this).debug(`[${l}] response error (${q})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(s,r,n!=null?n:l,h.headers)}let x=C?"error; no more retries left":"error; not retryable";re(this).info(`${g} - ${x}`);let P=await h.text().catch(q=>Ns(q).message),k=hd(P),O=k?void 0:P;throw re(this).debug(`[${l}] response error (${x})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:O,durationMs:Date.now()-u})),this.makeStatusError(h.status,k,O,h.headers)}return re(this).info(g),re(this).debug(`[${l}] response start`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:s,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Us(this,n,e)}async fetchWithTimeout(e,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){var c;let o,i=s==null?void 0:s.get("retry-after-ms");if(i){let l=parseFloat(i);Number.isNaN(l)||(o=l)}let a=s==null?void 0:s.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=(c=e.maxRetries)!=null?c:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await Ze(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}buildRequest(e,{retryCount:r=0}={}){var d,h,p;let n={...e},{method:s,path:o,query:i}=n,a=this.buildURL(o,i);"timeout"in n&&dd("timeout",n.timeout),n.timeout=(d=n.timeout)!=null?d:this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n}),f=this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:r});return{req:{method:s,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...(h=this.fetchOptions)!=null?h:{},...(p=n.fetchOptions)!=null?p:{}},url:a,timeout:n.timeout}}buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=I([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...bd(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=I([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ui(e)}:b(this,Mi,"f").call(this,{body:e,headers:n})}};wc=D,Mi=new WeakMap;D.OpenAI=wc;D.DEFAULT_TIMEOUT=6e5;D.OpenAIError=T;D.APIError=te;D.APIConnectionError=qt;D.APIConnectionTimeoutError=Ut;D.APIUserAbortError=X;D.NotFoundError=ln;D.ConflictError=cn;D.RateLimitError=fn;D.BadRequestError=sn;D.AuthenticationError=on;D.InternalServerError=dn;D.PermissionDeniedError=an;D.UnprocessableEntityError=un;D.toFile=gi;D.Completions=Sr;D.Chat=Wt;D.Embeddings=Er;D.Files=vr;D.Images=Tr;D.Audio=st;D.Moderations=kr;D.Models=Ir;D.FineTuning=Ve;D.Graders=zt;D.VectorStores=vt;D.Beta=at;D.Batches=gr;D.Uploads=Qt;D.Responses=Yt;D.Evals=Jt;D.Containers=Gt;var Zs=class extends D{constructor({baseURL:e=ot("OPENAI_BASE_URL"),apiKey:r=ot("AZURE_OPENAI_API_KEY"),apiVersion:n=ot("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:a,...c}={}){if(!n)throw new T("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof i=="function"&&(a=!0),!i&&!r)throw new T("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&r)throw new T("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r!=null||(r=rh),c.defaultQuery={...c.defaultQuery,"api-version":n},e){if(s)throw new T("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new T("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:r,baseURL:e,...c,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this._azureADTokenProvider=i,this.apiVersion=n,this.deploymentName=o}buildRequest(e,r={}){var n;if(ew.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!mn(e.body))throw new Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||((n=e.__metadata)==null?void 0:n.model);s!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${s}${e.path}`)}return super.buildRequest(e,r)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new T(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){}async prepareOptions(e){if(e.headers=I([e.headers]),e.headers.values.get("Authorization")||e.headers.values.get("api-key"))return super.prepareOptions(e);let r=await this._getAzureADToken();if(r)e.headers.values.set("Authorization",`Bearer ${r}`);else if(this.apiKey!==rh)e.headers.values.set("api-key",this.apiKey);else throw new T("Unable to handle auth");return super.prepareOptions(e)}},ew=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]),rh="<Missing Key>";var Or=t=>{var n;let e=((n=t.split(".").pop())==null?void 0:n.toLowerCase())||"";return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",xml:"application/xml",md:"text/markdown",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",flac:"audio/flac",m4a:"audio/mp4",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",wmv:"video/x-ms-wmv",webm:"video/webm"}[e]||"application/octet-stream"},Me=`
> [!quote]-
> `,Le=`
`,Mr=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(r[s]);return window.btoa(e)},lt=async(t,e)=>{let r=Or(t.link);if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)===!1)throw new Error(m("Only PNG, JPEG, GIF, and WebP images are supported."));let n=await e(t),s=Mr(n);return{type:"image_url",image_url:{url:`data:${r};base64,${s}`}}},jn=t=>{switch(t){case"Text Generation":return"\u270D\uFE0F";case"Image Vision":return"\u{1F441}\uFE0F";case"PDF Vision":return"\u{1F4C4}";case"Image Generation":return"\u{1F3A8}";case"Image Editing":return"\u270F\uFE0F";case"Web Search":return"\u{1F50D}";case"Reasoning":return"\u{1F9E0}"}};var tw=t=>async function*(e,r,n){var S,_;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,model:c,endpoint:l,apiVersion:f,...u}=i;if(!a)throw new Error(m("API key is required"));let d=new Zs({endpoint:l,apiKey:a,apiVersion:f,deployment:c,dangerouslyAllowBrowser:!0});e=[{role:"system",content:`Initiate your response with "<think>
\u55EF" at the beginning of every output.`},...e];let h=await d.chat.completions.create({model:c,messages:e,stream:!0,...u},{signal:r.signal}),p=!1,y=!1,g=!1;for await(let v of h){v.usage&&v.usage.prompt_tokens&&v.usage.completion_tokens&&console.debug(`Prompt tokens: ${v.usage.prompt_tokens}, completion tokens: ${v.usage.completion_tokens}`);let C=(_=(S=v.choices[0])==null?void 0:S.delta)==null?void 0:_.content;if(C){if(C==="<think>"){if(y)continue;p=!0,y=!0,yield Me;continue}if(C==="</think>"){if(g)continue;p=!1,g=!0,yield Le;continue}yield p?C.replace(/\n/g,`
> `):C}}},nh=["o3-mini","deepseek-r1","phi-4","o1","o1-mini","gpt-4o","gpt-4o-mini"],sh={name:"Azure",defaultOptions:{apiKey:"",baseURL:"",model:nh[0],endpoint:"",apiVersion:"",parameters:{}},sendRequestFunc:tw,models:nh,websiteToObtainKey:"https://portal.azure.com",capabilities:["Text Generation","Reasoning"]};function U(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function E(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var _c=function(){let{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return _c=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Ct(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var eo=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch(e){}try{return new Error(JSON.stringify(t))}catch(e){}}return new Error(t)};var B=class extends Error{},le=class t extends B{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=r}static makeMessage(e,r,n){let s=r!=null&&r.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new Zt({message:n,cause:eo(r)});let o=r;return e===400?new Vn(e,o,n,s):e===401?new Kn(e,o,n,s):e===403?new Gn(e,o,n,s):e===404?new Jn(e,o,n,s):e===409?new zn(e,o,n,s):e===422?new Xn(e,o,n,s):e===429?new Yn(e,o,n,s):e>=500?new Qn(e,o,n,s):new t(e,o,n,s)}},de=class extends le{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Zt=class extends le{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Wn=class extends Zt{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},Vn=class extends le{},Kn=class extends le{},Gn=class extends le{},Jn=class extends le{},zn=class extends le{},Xn=class extends le{},Yn=class extends le{},Qn=class extends le{};var nw=/^[a-z][a-z0-9+.-]*:/i,oh=t=>nw.test(t),Sc=t=>(Sc=Array.isArray,Sc(t)),xc=Sc;function Ec(t){return typeof t!="object"?{}:t!=null?t:{}}function ih(t){if(!t)return!0;for(let e in t)return!1;return!0}function ah(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var lh=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new B(`${t} must be an integer`);if(e<0)throw new B(`${t} must be a positive integer`);return e};var Li=t=>{try{return JSON.parse(t)}catch(e){return}};var ch=t=>new Promise(e=>setTimeout(e,t));var er="0.56.0";var dh=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";function sw(){return typeof Deno!="undefined"&&Deno.build!=null?"deno":typeof EdgeRuntime!="undefined"?"edge":Object.prototype.toString.call(typeof globalThis.process!="undefined"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ow=()=>{var r,n,s,o,i;let t=sw();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":fh(Deno.build.os),"X-Stainless-Arch":uh(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(n=(r=Deno.version)==null?void 0:r.deno)!=null?n:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":fh((s=globalThis.process.platform)!=null?s:"unknown"),"X-Stainless-Arch":uh((o=globalThis.process.arch)!=null?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!=null?i:"unknown"};let e=iw();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function iw(){if(typeof navigator=="undefined"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var uh=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",fh=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Ni,hh=()=>Ni!=null?Ni:Ni=ow();function ph(){if(typeof fetch!="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ac(...t){let e=globalThis.ReadableStream;if(typeof e=="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Di(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ac({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}function to(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r!=null&&r.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function mh(t){var n,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(n=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var gh=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function yh(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var Bi;function ro(t){let e;return(Bi!=null?Bi:(e=new globalThis.TextEncoder,Bi=e.encode.bind(e)))(t)}var Fi;function vc(t){let e;return(Fi!=null?Fi:(e=new globalThis.TextDecoder,Fi=e.decode.bind(e)))(t)}var Pe,Re,Pt=class{constructor(){Pe.set(this,void 0),Re.set(this,void 0),U(this,Pe,new Uint8Array,"f"),U(this,Re,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ro(e):e;U(this,Pe,yh([E(this,Pe,"f"),r]),"f");let n=[],s;for(;(s=cw(E(this,Pe,"f"),E(this,Re,"f")))!=null;){if(s.carriage&&E(this,Re,"f")==null){U(this,Re,s.index,"f");continue}if(E(this,Re,"f")!=null&&(s.index!==E(this,Re,"f")+1||s.carriage)){n.push(vc(E(this,Pe,"f").subarray(0,E(this,Re,"f")-1))),U(this,Pe,E(this,Pe,"f").subarray(E(this,Re,"f")),"f"),U(this,Re,null,"f");continue}let o=E(this,Re,"f")!==null?s.preceding-1:s.preceding,i=vc(E(this,Pe,"f").subarray(0,o));n.push(i),U(this,Pe,E(this,Pe,"f").subarray(s.index),"f"),U(this,Re,null,"f")}return n}flush(){return E(this,Pe,"f").length?this.decode(`
`):[]}};Pe=new WeakMap,Re=new WeakMap;Pt.NEWLINE_CHARS=new Set([`
`,"\r"]);Pt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cw(t,e){for(let s=e!=null?e:0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function bh(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Ui={off:0,error:200,warn:300,info:400,debug:500},Cc=(t,e,r)=>{if(t){if(ah(Ui,t))return t;ce(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ui))}`)}};function no(){}function qi(t,e,r){return!e||Ui[t]>Ui[r]?no:e[t].bind(e)}var uw={error:no,warn:no,info:no,debug:no},wh=new WeakMap;function ce(t){var o;let e=t.logger,r=(o=t.logLevel)!=null?o:"off";if(!e)return uw;let n=wh.get(e);if(n&&n[0]===r)return n[1];let s={error:qi("error",e,r),warn:qi("warn",e,r),info:qi("info",e,r),debug:qi("debug",e,r)};return wh.set(e,[r,s]),s}var Rt=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var so,ct=class t{constructor(e,r,n){this.iterator=e,so.set(this,void 0),this.controller=r,U(this,so,n,"f")}static fromSSEResponse(e,r,n){let s=!1,o=n?ce(n):console;async function*i(){var c;if(s)throw new B("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let l of fw(e,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(f){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),f}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(f){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),f}if(l.event!=="ping"&&l.event==="error")throw new le(void 0,(c=Li(l.data))!=null?c:l.data,void 0,e.headers)}a=!0}catch(l){if(Ct(l))return;throw l}finally{a||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let s=!1;async function*o(){let a=new Pt,c=to(e);for await(let l of c)for(let f of a.decode(l))yield f;for(let l of a.flush())yield l}async function*i(){if(s)throw new B("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Ct(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(so=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>s(e),this.controller,E(this,so,"f")),new t(()=>s(r),this.controller,E(this,so,"f"))]}toReadableStream(){let e=this,r;return Ac({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await r.next();if(o)return n.close();let i=ro(JSON.stringify(s)+`
`);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=r.return)==null?void 0:n.call(r))}})}};async function*fw(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new B("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new B("Attempted to iterate over a response with no body");let r=new Pc,n=new Pt,s=to(t.body);for await(let o of dw(s))for(let i of n.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of n.flush()){let i=r.decode(o);i&&(yield i)}}async function*dw(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?ro(r):r,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=bh(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Pc=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,s]=hw(e,":");return s.startsWith(" ")&&(s=s.substring(1)),r==="event"?this.event=s:r==="data"&&this.data.push(s),null}};function hw(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function $i(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var u;if(e.options.stream)return ce(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):ct.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let a=r.headers.get("content-type"),c=(u=a==null?void 0:a.split(";")[0])==null?void 0:u.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){let d=await r.json();return Rc(d,r)}return await r.text()})();return ce(t).debug(`[${n}] response parsed`,Rt({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function Rc(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var oo,Lr=class t extends Promise{constructor(e,r,n=$i){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,oo.set(this,void 0),U(this,oo,e,"f")}_thenUnwrap(e){return new t(E(this,oo,"f"),this.responsePromise,async(r,n)=>Rc(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(E(this,oo,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};oo=new WeakMap;var Hi,Tc=class{constructor(e,r,n,s){Hi.set(this,void 0),U(this,Hi,e,"f"),this.options=s,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new B("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await E(this,Hi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Hi=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},io=class extends Lr{constructor(e,r,n){super(e,r,async(s,o)=>new n(s,o.response,await $i(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Ne=class extends Tc{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;if((r=this.options.query)!=null&&r.before_id){let n=this.first_id;return n?{...this.options,query:{...Ec(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...Ec(this.options.query),after_id:e}}:null}};var kc=()=>{var t;if(typeof File=="undefined"){let{process:e}=globalThis,r=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Nr(t,e,r){return kc(),new File(t,e!=null?e:"unknown_file",r)}function ao(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Oc=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var Sh=async(t,e)=>({...t,body:await gw(t.body,e)}),_h=new WeakMap;function mw(t){let e=typeof t=="function"?t:t.fetch,r=_h.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch(s){return!0}})();return _h.set(e,n),n}var gw=async(t,e)=>{if(!await mw(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>Ic(r,n,s))),r},yw=t=>t instanceof Blob&&"name"in t;var Ic=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let n={},s=r.headers.get("Content-Type");s&&(n={type:s}),t.append(e,Nr([await r.blob()],ao(r),n))}else if(Oc(r))t.append(e,Nr([await new Response(Di(r)).blob()],ao(r)));else if(yw(r))t.append(e,Nr([r],ao(r),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>Ic(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Ic(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var xh=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",bw=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&xh(t),ww=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ji(t,e,r){if(kc(),t=await t,e||(e=ao(t)),bw(t))return t instanceof File&&e==null&&r==null?t:Nr([await t.arrayBuffer()],e!=null?e:t.name,{type:t.type,lastModified:t.lastModified,...r});if(ww(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Nr(await Mc(s),e,r)}let n=await Mc(t);if(!(r!=null&&r.type)){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return Nr(n,e,r)}async function Mc(t){var r;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(xh(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Oc(t))for await(let n of t)e.push(...await Mc(n));else{let n=(r=t==null?void 0:t.constructor)==null?void 0:r.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${_w(t)}`)}return e}function _w(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var Y=class{constructor(e){this._client=e}};var Eh=Symbol.for("brand.privateNullableHeaders");function*xw(t){if(!t)return;if(Eh in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():xc(t)?r=t:(e=!0,r=Object.entries(t!=null?t:{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=xc(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var K=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,i]of xw(n)){let a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[Eh]:!0,values:e,nulls:r}};function vh(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ah=Object.freeze(Object.create(null)),Ew=(t=vh)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((f,u,d)=>{var y,g,S;/[?#]/.test(u)&&(s=!0);let h=n[d],p=(s?encodeURIComponent:t)(""+h);return d!==n.length&&(h==null||typeof h=="object"&&h.toString===((S=Object.getPrototypeOf((g=Object.getPrototypeOf((y=h.hasOwnProperty)!=null?y:Ah))!=null?g:Ah))==null?void 0:S.toString))&&(p=h+"",o.push({start:f.length+u.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),f+u+(d===n.length?"":p)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((f,u)=>f.start-u.start),o.length>0){let f=0,u=o.reduce((d,h)=>{let p=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,d+p+y},"");throw new B(`Path parameters result in path with invalid segments:
${o.map(d=>d.error).join(`
`)}
${i}
${u}`)}return i},ge=Ew(vh);var Zn=class extends Y{list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/files",Ne,{query:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}delete(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.delete(ge`/v1/files/${e}`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}download(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/files/${e}/content`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/files/${e}`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}upload(e,r){let{betas:n,...s}=e;return this._client.post("/v1/files",Sh({body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])},this._client))}};var es=class extends Y{retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/models/${e}?beta=true`,{...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/models?beta=true",Ne,{query:s,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}};var ts=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new Pt;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new B("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new B("Attempted to iterate over a response with no body");return new t(to(e.body),r)}};var rs=class extends Y{create(e,r){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/messages/batches/${e}?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/messages/batches?beta=true",Ne,{query:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}delete(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.delete(ge`/v1/messages/batches/${e}?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}cancel(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.post(ge`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}async results(e,r={},n){let s=await this.retrieve(e);if(!s.results_url)throw new B(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:o}=r!=null?r:{};return this._client.get(s.results_url,{...n,headers:K([{"anthropic-beta":[...o!=null?o:[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,a)=>ts.fromResponse(a.response,a.controller))}};var Pw=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e++;continue}if(n==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(n===":"){r.push({type:"separator",value:":"}),e++;continue}if(n===","){r.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",c=!1;for(n=t[++e];n!=='"';){if(e===t.length){c=!0;break}if(n==="\\"){if(e++,e===t.length){c=!0;break}a+=n+t[e],n=t[++e]}else a+=n,n=t[++e]}n=t[++e],c||r.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=t[++e]);n&&o.test(n)||n===".";)a+=n,n=t[++e];r.push({type:"number",value:a});continue}let i=/[a-z]/i;if(n&&i.test(n)){let a="";for(;n&&i.test(n)&&e!==t.length;)a+=n,n=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},ns=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),ns(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),ns(t);case"string":let n=t[t.length-2];if((n==null?void 0:n.type)==="delimiter")return t=t.slice(0,t.length-1),ns(t);if((n==null?void 0:n.type)==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),ns(t);break;case"delimiter":return t=t.slice(0,t.length-1),ns(t);break}return t},Rw=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},Tw=t=>{let e="";return t.map(r=>{switch(r.type){case"string":e+='"'+r.value+'"';break;default:e+=r.value;break}}),e},Wi=t=>JSON.parse(Tw(Rw(ns(Pw(t)))));var De,tr,lo,Vi,co,uo,Ki,fo,Tt,ho,Gi,Ji,ss,zi,Xi,Lc,Ch,Yi,Nc,Dc,Bc,Ph,Rh="__json_buf";function Th(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Qi=class t{constructor(){De.add(this),this.messages=[],this.receivedMessages=[],tr.set(this,void 0),this.controller=new AbortController,lo.set(this,void 0),Vi.set(this,()=>{}),co.set(this,()=>{}),uo.set(this,void 0),Ki.set(this,()=>{}),fo.set(this,()=>{}),Tt.set(this,{}),ho.set(this,!1),Gi.set(this,!1),Ji.set(this,!1),ss.set(this,!1),zi.set(this,void 0),Xi.set(this,void 0),Yi.set(this,e=>{if(U(this,Gi,!0,"f"),Ct(e)&&(e=new de),e instanceof de)return U(this,Ji,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){let r=new B(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new B(String(e)))}),U(this,lo,new Promise((e,r)=>{U(this,Vi,e,"f"),U(this,co,r,"f")}),"f"),U(this,uo,new Promise((e,r)=>{U(this,Ki,e,"f"),U(this,fo,r,"f")}),"f"),E(this,lo,"f").catch(()=>{}),E(this,uo,"f").catch(()=>{})}get response(){return E(this,zi,"f")}get request_id(){return E(this,Xi,"f")}async withResponse(){let e=await E(this,lo,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let s=new t;for(let o of r.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},E(this,Yi,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){var i;let s=n==null?void 0:n.signal,o;s&&(s.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),s.addEventListener("abort",o));try{E(this,De,"m",Nc).call(this);let{response:a,data:c}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)E(this,De,"m",Dc).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new de;E(this,De,"m",Bc).call(this)}finally{s&&o&&s.removeEventListener("abort",o)}}_connected(e){this.ended||(U(this,zi,e,"f"),U(this,Xi,e==null?void 0:e.headers.get("request-id"),"f"),E(this,Vi,"f").call(this,e),this._emit("connect"))}get ended(){return E(this,ho,"f")}get errored(){return E(this,Gi,"f")}get aborted(){return E(this,Ji,"f")}abort(){this.controller.abort()}on(e,r){return(E(this,Tt,"f")[e]||(E(this,Tt,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=E(this,Tt,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(E(this,Tt,"f")[e]||(E(this,Tt,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{U(this,ss,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){U(this,ss,!0,"f"),await E(this,uo,"f")}get currentMessage(){return E(this,tr,"f")}async finalMessage(){return await this.done(),E(this,De,"m",Lc).call(this)}async finalText(){return await this.done(),E(this,De,"m",Ch).call(this)}_emit(e,...r){if(E(this,ho,"f"))return;e==="end"&&(U(this,ho,!0,"f"),E(this,Ki,"f").call(this));let n=E(this,Tt,"f")[e];if(n&&(E(this,Tt,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!E(this,ss,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,co,"f").call(this,s),E(this,fo,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!E(this,ss,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,co,"f").call(this,s),E(this,fo,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",E(this,De,"m",Lc).call(this))}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal,s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{E(this,De,"m",Nc).call(this),this._connected(null);let i=ct.fromReadableStream(e,this.controller);for await(let a of i)E(this,De,"m",Dc).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new de;E(this,De,"m",Bc).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(tr=new WeakMap,lo=new WeakMap,Vi=new WeakMap,co=new WeakMap,uo=new WeakMap,Ki=new WeakMap,fo=new WeakMap,Tt=new WeakMap,ho=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,ss=new WeakMap,zi=new WeakMap,Xi=new WeakMap,Yi=new WeakMap,De=new WeakSet,Lc=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ch=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new B("stream ended without producing a content block with type=text");return r.join(" ")},Nc=function(){this.ended||U(this,tr,void 0,"f")},Dc=function(r){var s;if(this.ended)return;let n=E(this,De,"m",Ph).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let o=n.content.at(-1);switch(r.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",r.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",r.delta.citation,(s=o.citations)!=null?s:[]);break}case"input_json_delta":{Th(o)&&o.input&&this._emit("inputJson",r.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",r.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{U(this,tr,n,"f");break}case"content_block_start":case"message_delta":break}},Bc=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");let r=E(this,tr,"f");if(!r)throw new B("request ended without sending any chunks");return U(this,tr,void 0,"f"),r},Ph=function(r){var s;let n=E(this,tr,"f");if(r.type==="message_start"){if(n)throw new B(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new B(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.container=r.delta.container,n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push(r.content_block),n;case"content_block_delta":{let o=n.content.at(r.index);switch(r.delta.type){case"text_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,text:(o.text||"")+r.delta.text});break}case"citations_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,citations:[...(s=o.citations)!=null?s:[],r.delta.citation]});break}case"input_json_delta":{if(o&&Th(o)){let i=o[Rh]||"";i+=r.delta.partial_json;let a={...o};if(Object.defineProperty(a,Rh,{value:i,enumerable:!1,writable:!0}),i)try{a.input=Wi(i)}catch(c){let l=new B(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${i}`);E(this,Yi,"f").call(this,l)}n.content[r.index]=a}break}case"thinking_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,thinking:o.thinking+r.delta.thinking});break}case"signature_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Zi={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192};var Ih={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},Dr=class extends Y{constructor(){super(...arguments),this.batches=new rs(this._client)}create(e,r){var i,a;let{betas:n,...s}=e;s.model in Ih&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Ih[s.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let o=this._client._options.timeout;if(!s.stream&&o==null){let c=(i=Zi[s.model])!=null?i:void 0;o=this._client.calculateNonstreamingTimeout(s.max_tokens,c)}return this._client.post("/v1/messages?beta=true",{body:s,timeout:o!=null?o:6e5,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers]),stream:(a=e.stream)!=null?a:!1})}stream(e,r){return Qi.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"token-counting-2024-11-01"].toString()},r==null?void 0:r.headers])})}};Dr.Batches=rs;var ut=class extends Y{constructor(){super(...arguments),this.models=new es(this._client),this.messages=new Dr(this._client),this.files=new Zn(this._client)}};ut.Models=es;ut.Messages=Dr;ut.Files=Zn;var Br=class extends Y{create(e,r){var o,i;let{betas:n,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:(o=this._client._options.timeout)!=null?o:6e5,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers]),stream:(i=e.stream)!=null?i:!1})}};var Be,rr,po,ea,mo,go,ta,yo,It,bo,ra,na,os,sa,oa,Fc,kh,qc,Uc,$c,Hc,Oh,Mh="__json_buf";function Lh(t){return t.type==="tool_use"||t.type==="server_tool_use"}var ia=class t{constructor(){Be.add(this),this.messages=[],this.receivedMessages=[],rr.set(this,void 0),this.controller=new AbortController,po.set(this,void 0),ea.set(this,()=>{}),mo.set(this,()=>{}),go.set(this,void 0),ta.set(this,()=>{}),yo.set(this,()=>{}),It.set(this,{}),bo.set(this,!1),ra.set(this,!1),na.set(this,!1),os.set(this,!1),sa.set(this,void 0),oa.set(this,void 0),qc.set(this,e=>{if(U(this,ra,!0,"f"),Ct(e)&&(e=new de),e instanceof de)return U(this,na,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){let r=new B(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new B(String(e)))}),U(this,po,new Promise((e,r)=>{U(this,ea,e,"f"),U(this,mo,r,"f")}),"f"),U(this,go,new Promise((e,r)=>{U(this,ta,e,"f"),U(this,yo,r,"f")}),"f"),E(this,po,"f").catch(()=>{}),E(this,go,"f").catch(()=>{})}get response(){return E(this,sa,"f")}get request_id(){return E(this,oa,"f")}async withResponse(){let e=await E(this,po,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let s=new t;for(let o of r.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},E(this,qc,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){var i;let s=n==null?void 0:n.signal,o;s&&(s.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),s.addEventListener("abort",o));try{E(this,Be,"m",Uc).call(this);let{response:a,data:c}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)E(this,Be,"m",$c).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new de;E(this,Be,"m",Hc).call(this)}finally{s&&o&&s.removeEventListener("abort",o)}}_connected(e){this.ended||(U(this,sa,e,"f"),U(this,oa,e==null?void 0:e.headers.get("request-id"),"f"),E(this,ea,"f").call(this,e),this._emit("connect"))}get ended(){return E(this,bo,"f")}get errored(){return E(this,ra,"f")}get aborted(){return E(this,na,"f")}abort(){this.controller.abort()}on(e,r){return(E(this,It,"f")[e]||(E(this,It,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=E(this,It,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(E(this,It,"f")[e]||(E(this,It,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{U(this,os,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){U(this,os,!0,"f"),await E(this,go,"f")}get currentMessage(){return E(this,rr,"f")}async finalMessage(){return await this.done(),E(this,Be,"m",Fc).call(this)}async finalText(){return await this.done(),E(this,Be,"m",kh).call(this)}_emit(e,...r){if(E(this,bo,"f"))return;e==="end"&&(U(this,bo,!0,"f"),E(this,ta,"f").call(this));let n=E(this,It,"f")[e];if(n&&(E(this,It,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!E(this,os,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,mo,"f").call(this,s),E(this,yo,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!E(this,os,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,mo,"f").call(this,s),E(this,yo,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",E(this,Be,"m",Fc).call(this))}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal,s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{E(this,Be,"m",Uc).call(this),this._connected(null);let i=ct.fromReadableStream(e,this.controller);for await(let a of i)E(this,Be,"m",$c).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new de;E(this,Be,"m",Hc).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(rr=new WeakMap,po=new WeakMap,ea=new WeakMap,mo=new WeakMap,go=new WeakMap,ta=new WeakMap,yo=new WeakMap,It=new WeakMap,bo=new WeakMap,ra=new WeakMap,na=new WeakMap,os=new WeakMap,sa=new WeakMap,oa=new WeakMap,qc=new WeakMap,Be=new WeakSet,Fc=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},kh=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new B("stream ended without producing a content block with type=text");return r.join(" ")},Uc=function(){this.ended||U(this,rr,void 0,"f")},$c=function(r){var s;if(this.ended)return;let n=E(this,Be,"m",Oh).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let o=n.content.at(-1);switch(r.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",r.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",r.delta.citation,(s=o.citations)!=null?s:[]);break}case"input_json_delta":{Lh(o)&&o.input&&this._emit("inputJson",r.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",r.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{U(this,rr,n,"f");break}case"content_block_start":case"message_delta":break}},Hc=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");let r=E(this,rr,"f");if(!r)throw new B("request ended without sending any chunks");return U(this,rr,void 0,"f"),r},Oh=function(r){var s;let n=E(this,rr,"f");if(r.type==="message_start"){if(n)throw new B(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new B(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push({...r.content_block}),n;case"content_block_delta":{let o=n.content.at(r.index);switch(r.delta.type){case"text_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,text:(o.text||"")+r.delta.text});break}case"citations_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,citations:[...(s=o.citations)!=null?s:[],r.delta.citation]});break}case"input_json_delta":{if(o&&Lh(o)){let i=o[Mh]||"";i+=r.delta.partial_json;let a={...o};Object.defineProperty(a,Mh,{value:i,enumerable:!1,writable:!0}),i&&(a.input=Wi(i)),n.content[r.index]=a}break}case"thinking_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,thinking:o.thinking+r.delta.thinking});break}case"signature_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var is=class extends Y{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(ge`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",Ne,{query:e,...r})}delete(e,r){return this._client.delete(ge`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(ge`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new B(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:K([{Accept:"application/binary"},r==null?void 0:r.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,o)=>ts.fromResponse(o.response,o.controller))}};var nr=class extends Y{constructor(){super(...arguments),this.batches=new is(this._client)}create(e,r){var s,o;e.model in Nh&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Nh[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let i=(s=Zi[e.model])!=null?s:void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}return this._client.post("/v1/messages",{body:e,timeout:n!=null?n:6e5,...r,stream:(o=e.stream)!=null?o:!1})}stream(e,r){return ia.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Nh={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};nr.Batches=is;var Fr=class extends Y{retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/models/${e}`,{...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/models",Ne,{query:s,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}};var wo=t=>{var e,r,n,s,o,i;if(typeof globalThis.process!="undefined")return(n=(r=(e=globalThis.process.env)==null?void 0:e[t])==null?void 0:r.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(i=(o=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:o.call(s,t))==null?void 0:i.trim()};var jc,Wc,aa,Dh,J=class{constructor({baseURL:e=wo("ANTHROPIC_BASE_URL"),apiKey:r=(o=>(o=wo("ANTHROPIC_API_KEY"))!=null?o:null)(),authToken:n=(i=>(i=wo("ANTHROPIC_AUTH_TOKEN"))!=null?i:null)(),...s}={}){var l,f,u,d,h,p;jc.add(this),aa.set(this,void 0);let a={apiKey:r,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&dh())throw new B(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=a.baseURL,this.timeout=(l=a.timeout)!=null?l:Wc.DEFAULT_TIMEOUT,this.logger=(f=a.logger)!=null?f:console;let c="warn";this.logLevel=c,this.logLevel=(d=(u=Cc(a.logLevel,"ClientOptions.logLevel",this))!=null?u:Cc(wo("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this))!=null?d:c,this.fetchOptions=a.fetchOptions,this.maxRetries=(h=a.maxRetries)!=null?h:2,this.fetch=(p=a.fetch)!=null?p:ph(),U(this,aa,gh,"f"),this._options=a,this.apiKey=r,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){return K([this.apiKeyAuth(e),this.bearerAuth(e)])}apiKeyAuth(e){if(this.apiKey!=null)return K([{"X-Api-Key":this.apiKey}])}bearerAuth(e){if(this.authToken!=null)return K([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n!="undefined").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new B(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${er}`}defaultIdempotencyKey(){return`stainless-node-retry-${_c()}`}makeStatusError(e,r,n,s){return le.generate(e,r,n,s)}buildURL(e,r,n){let s=!E(this,jc,"m",Dh).call(this)&&n||this.baseURL,o=oh(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return ih(i)||(r={...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new B("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new Lr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){var S,_,v;let s=await e,o=(S=s.maxRetries)!=null?S:this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:c}=this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=n===void 0?"":`, retryOf: ${n}`,u=Date.now();if(ce(this).debug(`[${l}] sending request`,Rt({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),(_=s.signal)!=null&&_.aborted)throw new de;let d=new AbortController,h=await this.fetchWithTimeout(a,i,c,d).catch(eo),p=Date.now();if(h instanceof Error){let C=`retrying, ${r} attempts remaining`;if((v=s.signal)!=null&&v.aborted)throw new de;let x=Ct(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return ce(this).info(`[${l}] connection ${x?"timed out":"failed"} - ${C}`),ce(this).debug(`[${l}] connection ${x?"timed out":"failed"} (${C})`,Rt({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(s,r,n!=null?n:l);throw ce(this).info(`[${l}] connection ${x?"timed out":"failed"} - error; no more retries left`),ce(this).debug(`[${l}] connection ${x?"timed out":"failed"} (error; no more retries left)`,Rt({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),x?new Wn:new Zt({cause:h})}let y=[...h.headers.entries()].filter(([C])=>C==="request-id").map(([C,x])=>", "+C+": "+JSON.stringify(x)).join(""),g=`[${l}${f}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){let C=this.shouldRetry(h);if(r&&C){let q=`retrying, ${r} attempts remaining`;return await mh(h.body),ce(this).info(`${g} - ${q}`),ce(this).debug(`[${l}] response error (${q})`,Rt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(s,r,n!=null?n:l,h.headers)}let x=C?"error; no more retries left":"error; not retryable";ce(this).info(`${g} - ${x}`);let P=await h.text().catch(q=>eo(q).message),k=Li(P),O=k?void 0:P;throw ce(this).debug(`[${l}] response error (${x})`,Rt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:O,durationMs:Date.now()-u})),this.makeStatusError(h.status,k,O,h.headers)}return ce(this).info(g),ce(this).debug(`[${l}] response start`,Rt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:s,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new io(this,n,e)}async fetchWithTimeout(e,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){var c;let o,i=s==null?void 0:s.get("retry-after-ms");if(i){let l=parseFloat(i);Number.isNaN(l)||(o=l)}let a=s==null?void 0:s.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=(c=e.maxRetries)!=null?c:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await ch(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new B("Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}buildRequest(e,{retryCount:r=0}={}){var h,p,y;let n={...e},{method:s,path:o,query:i,defaultBaseURL:a}=n,c=this.buildURL(o,i,a);"timeout"in n&&lh("timeout",n.timeout),n.timeout=(h=n.timeout)!=null?h:this.timeout;let{bodyHeaders:l,body:f}=this.buildBody({options:n}),u=this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:u,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...(p=this.fetchOptions)!=null?p:{},...(y=n.fetchOptions)!=null?y:{}},url:c,timeout:n.timeout}}buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=K([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...hh(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=K([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Di(e)}:E(this,aa,"f").call(this,{body:e,headers:n})}};Wc=J,aa=new WeakMap,jc=new WeakSet,Dh=function(){return this.baseURL!=="https://api.anthropic.com"};J.Anthropic=Wc;J.HUMAN_PROMPT=`
Human:`;J.AI_PROMPT=`
Assistant:`;J.DEFAULT_TIMEOUT=6e5;J.AnthropicError=B;J.APIError=le;J.APIConnectionError=Zt;J.APIConnectionTimeoutError=Wn;J.APIUserAbortError=de;J.NotFoundError=Jn;J.ConflictError=zn;J.RateLimitError=Yn;J.BadRequestError=Vn;J.AuthenticationError=Kn;J.InternalServerError=Qn;J.PermissionDeniedError=Gn;J.UnprocessableEntityError=Xn;J.toFile=ji;var Ke=class extends J{constructor(){super(...arguments),this.completions=new Br(this),this.messages=new nr(this),this.models=new Fr(this),this.beta=new ut(this)}};Ke.Completions=Br;Ke.Messages=nr;Ke.Models=Fr;Ke.Beta=ut;var{HUMAN_PROMPT:Mw,AI_PROMPT:Lw}=Ke;var Fh=require("obsidian");var Nw=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Dw(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},Dw=async(t,e)=>{let r=Or(t.link);if(r==="application/pdf"){let n=await e(t),s=Mr(n);return{type:"document",source:{type:"base64",media_type:r,data:s}}}else if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)){let n=await e(t),s=Mr(n);return{type:"image",source:{type:"base64",media_type:r,data:s}}}else throw new Error(m("Only PNG, JPEG, GIF, WebP, and PDF files are supported."))},Bw=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,max_tokens:f,enableWebSearch:u=!1,enableThinking:d=!1,budget_tokens:h=1600}=i,p=c;if(!a)throw new Error(m("API key is required"));p.endsWith("/v1/messages/")?p=p.slice(0,-13):p.endsWith("/v1/messages")&&(p=p.slice(0,-12));let[y,g]=e[0].role==="system"?[e[0],e.slice(1)]:[null,e];g.forEach(P=>{if(P.role==="system")throw new Error("System messages are only allowed as the first message")});let S=await Promise.all(g.map(P=>Nw(P,n))),_=new Ke({apiKey:a,baseURL:p,fetch:globalThis.fetch,dangerouslyAllowBrowser:!0}),v={model:l,max_tokens:f,messages:S,stream:!0,...y&&{system:y.content},...u&&{tools:[{name:"web_search",type:"web_search_20250305"}]},...d&&{thinking:{type:"enabled",budget_tokens:h}}},C=await _.messages.create(v,{signal:r.signal}),x=!1;for await(let P of C)if(P.type==="content_block_delta")P.delta.type==="text_delta"&&(x?(x=!1,yield Le+P.delta.text):yield P.delta.text),P.delta.type==="thinking_delta"&&(yield(x?"":(x=!0,Me))+P.delta.thinking.replace(/\n/g,`
> `));else if(P.type==="content_block_start")P.content_block.type==="server_tool_use"&&P.content_block.name==="web_search"&&new Fh.Notice(jn("Web Search")+"Web Search");else if(P.type==="message_delta"&&P.delta.stop_reason){let k=P.delta.stop_reason;if(k!=="end_turn")throw new Error(`\u{1F534} Unexpected stop reason: ${k}`)}},Bh=["claude-sonnet-4-0","claude-opus-4-0","claude-3-7-sonnet-latest","claude-3-5-sonnet-latest","claude-3-opus-latest","claude-3-5-haiku-latest"],la={name:"Claude",defaultOptions:{apiKey:"",baseURL:"https://api.anthropic.com",model:Bh[0],max_tokens:8192,enableWebSearch:!1,enableThinking:!1,budget_tokens:1600,parameters:{}},sendRequestFunc:Bw,models:Bh,websiteToObtainKey:"https://console.anthropic.com",capabilities:["Text Generation","Web Search","Reasoning","Image Vision","PDF Vision"]};var Fw=t=>async function*(e,r,n){var p;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let d=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:e,stream:!0,...f},{signal:r.signal}),h=!1;for await(let y of d){y.usage&&y.usage.prompt_tokens&&y.usage.completion_tokens&&console.debug(`Prompt tokens: ${y.usage.prompt_tokens}, completion tokens: ${y.usage.completion_tokens}`);let g=(p=y.choices[0])==null?void 0:p.delta,S=g==null?void 0:g.reasoning_content;if(S)yield(h?"":(h=!0,Me))+S.replace(/\n/g,`
> `);else{let _=h?(h=!1,Le):"";g!=null&&g.content&&(yield _+(g==null?void 0:g.content))}}},qh=["deepseek-chat","deepseek-reasoner"],Uh={name:"DeepSeek",defaultOptions:{apiKey:"",baseURL:"https://api.deepseek.com",model:qh[0],parameters:{}},sendRequestFunc:Fw,models:qh,websiteToObtainKey:"https://platform.deepseek.com",capabilities:["Text Generation","Reasoning"]};var ca=require("obsidian");var qw=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u={model:l,messages:e,stream:!1,...f};new ca.Notice(m("This is a non-streaming request, please wait..."),5*1e3),yield(await(0,ca.requestUrl)({url:c,method:"POST",body:JSON.stringify(u),headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}})).json.choices[0].message.content},$h={name:"Doubao",defaultOptions:{apiKey:"",baseURL:"https://ark.cn-beijing.volces.com/api/v3/chat/completions",model:"",parameters:{}},sendRequestFunc:qw,models:[],websiteToObtainKey:"https://www.volcengine.com",capabilities:["Text Generation"]};var Hh;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(Hh||(Hh={}));var jh;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(jh||(jh={}));var Wh;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Wh||(Wh={}));var Vh=["user","model","function","system"],Kh;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"})(Kh||(Kh={}));var Gh;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Gh||(Gh={}));var Jh;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Jh||(Jh={}));var zh;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(zh||(zh={}));var _o;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER"})(_o||(_o={}));var Xh;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(Xh||(Xh={}));var Yh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(Yh||(Yh={}));var Qh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Qh||(Qh={}));var ye=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},sr=class extends ye{constructor(e,r){super(e),this.response=r}},fa=class extends ye{constructor(e,r,n,s){super(e),this.status=r,this.statusText=n,this.errorDetails=s}},ft=class extends ye{};var Uw="https://generativelanguage.googleapis.com",$w="v1beta",Hw="0.21.0",jw="genai-js",qr;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(qr||(qr={}));var Vc=class{constructor(e,r,n,s,o){this.model=e,this.task=r,this.apiKey=n,this.stream=s,this.requestOptions=o}toString(){var e,r;let n=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||$w,o=`${((r=this.requestOptions)===null||r===void 0?void 0:r.baseUrl)||Uw}/${n}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}};function Ww(t){let e=[];return t!=null&&t.apiClient&&e.push(t.apiClient),e.push(`${jw}/${Hw}`),e.join(" ")}async function Vw(t){var e;let r=new Headers;r.append("Content-Type","application/json"),r.append("x-goog-api-client",Ww(t.requestOptions)),r.append("x-goog-api-key",t.apiKey);let n=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(s){throw new ft(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${s.message}`)}for(let[s,o]of n.entries()){if(s==="x-goog-api-key")throw new ft(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new ft(`Header name ${s} can only be set using the apiClient field`);r.append(s,o)}}return r}async function Kw(t,e,r,n,s,o){let i=new Vc(t,e,r,n,o);return{url:i.toString(),fetchOptions:Object.assign(Object.assign({},Xw(o)),{method:"POST",headers:await Vw(i),body:s})}}async function Eo(t,e,r,n,s,o={},i=fetch){let{url:a,fetchOptions:c}=await Kw(t,e,r,n,s,o);return Gw(a,c,i)}async function Gw(t,e,r=fetch){let n;try{n=await r(t,e)}catch(s){Jw(s,t)}return n.ok||await zw(n,t),n}function Jw(t,e){let r=t;throw t instanceof fa||t instanceof ft||(r=new ye(`Error fetching from ${e.toString()}: ${t.message}`),r.stack=t.stack),r}async function zw(t,e){let r="",n;try{let s=await t.json();r=s.error.message,s.error.details&&(r+=` ${JSON.stringify(s.error.details)}`,n=s.error.details)}catch(s){}throw new fa(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${r}`,t.status,t.statusText,n)}function Xw(t){let e={};if((t==null?void 0:t.signal)!==void 0||(t==null?void 0:t.timeout)>=0){let r=new AbortController;(t==null?void 0:t.timeout)>=0&&setTimeout(()=>r.abort(),t.timeout),t!=null&&t.signal&&t.signal.addEventListener("abort",()=>{r.abort()}),e.signal=r.signal}return e}function Gc(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return Yw(t)}else if(t.promptFeedback)throw new sr(`Text not available. ${or(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Zh(t)[0]}else if(t.promptFeedback)throw new sr(`Function call not available. ${or(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return Zh(t)}else if(t.promptFeedback)throw new sr(`Function call not available. ${or(t)}`,t)},t}function Yw(t){var e,r,n,s;let o=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let i of(s=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)i.text&&o.push(i.text),i.executableCode&&o.push("\n```"+i.executableCode.language+`
`+i.executableCode.code+"\n```\n"),i.codeExecutionResult&&o.push("\n```\n"+i.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Zh(t){var e,r,n,s;let o=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let i of(s=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)i.functionCall&&o.push(i.functionCall);if(o.length>0)return o}var Qw=[_o.RECITATION,_o.SAFETY,_o.LANGUAGE];function ua(t){return!!t.finishReason&&Qw.includes(t.finishReason)}function or(t){var e,r,n;let s="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)s+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${t.promptFeedback.blockReason}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(s+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let o=t.candidates[0];ua(o)&&(s+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(s+=`: ${o.finishMessage}`))}return s}function So(t){return this instanceof So?(this.v=t,this):new So(t)}function Zw(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,o=[];return s={},i("next"),i("throw"),i("return"),s[Symbol.asyncIterator]=function(){return this},s;function i(d){n[d]&&(s[d]=function(h){return new Promise(function(p,y){o.push([d,h,p,y])>1||a(d,h)})})}function a(d,h){try{c(n[d](h))}catch(p){u(o[0][3],p)}}function c(d){d.value instanceof So?Promise.resolve(d.value.v).then(l,f):u(o[0][2],d)}function l(d){a("next",d)}function f(d){a("throw",d)}function u(d,h){d(h),o.shift(),o.length&&a(o[0][0],o[0][1])}}var ep=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function e_(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=n_(e),[n,s]=r.tee();return{stream:r_(n),response:t_(s)}}async function t_(t){let e=[],r=t.getReader();for(;;){let{done:n,value:s}=await r.read();if(n)return Gc(s_(e));e.push(s)}}function r_(t){return Zw(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:s}=yield So(r.read());if(s)break;yield yield So(Gc(n))}})}function n_(t){let e=t.getReader();return new ReadableStream({start(n){let s="";return o();function o(){return e.read().then(({value:i,done:a})=>{if(a){if(s.trim()){n.error(new ye("Failed to parse stream"));return}n.close();return}s+=i;let c=s.match(ep),l;for(;c;){try{l=JSON.parse(c[1])}catch(f){n.error(new ye(`Error parsing JSON response: "${c[1]}"`));return}n.enqueue(l),s=s.substring(c[0].length),c=s.match(ep)}return o()})}}})}function s_(t){let e=t[t.length-1],r={promptFeedback:e==null?void 0:e.promptFeedback};for(let n of t){if(n.candidates)for(let s of n.candidates){let o=s.index;if(r.candidates||(r.candidates=[]),r.candidates[o]||(r.candidates[o]={index:s.index}),r.candidates[o].citationMetadata=s.citationMetadata,r.candidates[o].groundingMetadata=s.groundingMetadata,r.candidates[o].finishReason=s.finishReason,r.candidates[o].finishMessage=s.finishMessage,r.candidates[o].safetyRatings=s.safetyRatings,s.content&&s.content.parts){r.candidates[o].content||(r.candidates[o].content={role:s.content.role||"user",parts:[]});let i={};for(let a of s.content.parts)a.text&&(i.text=a.text),a.functionCall&&(i.functionCall=a.functionCall),a.executableCode&&(i.executableCode=a.executableCode),a.codeExecutionResult&&(i.codeExecutionResult=a.codeExecutionResult),Object.keys(i).length===0&&(i.text=""),r.candidates[o].content.parts.push(i)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function sp(t,e,r,n){let s=await Eo(e,qr.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return e_(s)}async function op(t,e,r,n){let o=await(await Eo(e,qr.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:Gc(o)}}function ip(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function xo(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return o_(e)}function o_(t){let e={role:"user",parts:[]},r={role:"function",parts:[]},n=!1,s=!1;for(let o of t)"functionResponse"in o?(r.parts.push(o),s=!0):(e.parts.push(o),n=!0);if(n&&s)throw new ye("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!s)throw new ye("No content is provided for sending chat message.");return n?e:r}function i_(t,e){var r;let n={model:e==null?void 0:e.model,generationConfig:e==null?void 0:e.generationConfig,safetySettings:e==null?void 0:e.safetySettings,tools:e==null?void 0:e.tools,toolConfig:e==null?void 0:e.toolConfig,systemInstruction:e==null?void 0:e.systemInstruction,cachedContent:(r=e==null?void 0:e.cachedContent)===null||r===void 0?void 0:r.name,contents:[]},s=t.generateContentRequest!=null;if(t.contents){if(s)throw new ft("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=t.contents}else if(s)n=Object.assign(Object.assign({},n),t.generateContentRequest);else{let o=xo(t);n.contents=[o]}return{generateContentRequest:n}}function tp(t){let e;return t.contents?e=t:e={contents:[xo(t)]},t.systemInstruction&&(e.systemInstruction=ip(t.systemInstruction)),e}function a_(t){return typeof t=="string"||Array.isArray(t)?{content:xo(t)}:t}var rp=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],l_={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function c_(t){let e=!1;for(let r of t){let{role:n,parts:s}=r;if(!e&&n!=="user")throw new ye(`First content should be with role 'user', got ${n}`);if(!Vh.includes(n))throw new ye(`Each item should include role field. Got ${n} but valid roles are: ${JSON.stringify(Vh)}`);if(!Array.isArray(s))throw new ye("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new ye("Each Content should have at least one part");let o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let a of s)for(let c of rp)c in a&&(o[c]+=1);let i=l_[n];for(let a of rp)if(!i.includes(a)&&o[a]>0)throw new ye(`Content with role '${n}' can't contain '${a}' part`);e=!0}}var np="SILENT_ERROR",Kc=class{constructor(e,r,n,s={}){this.model=r,this.params=n,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n!=null&&n.history&&(c_(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,r={}){var n,s,o,i,a,c;await this._sendPromise;let l=xo(e),f={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),r),d;return this._sendPromise=this._sendPromise.then(()=>op(this._apiKey,this.model,f,u)).then(h=>{var p;if(h.response.candidates&&h.response.candidates.length>0){this._history.push(l);let y=Object.assign({parts:[],role:"model"},(p=h.response.candidates)===null||p===void 0?void 0:p[0].content);this._history.push(y)}else{let y=or(h.response);y&&console.warn(`sendMessage() was unsuccessful. ${y}. Inspect response object for details.`)}d=h}),await this._sendPromise,d}async sendMessageStream(e,r={}){var n,s,o,i,a,c;await this._sendPromise;let l=xo(e),f={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),r),d=sp(this._apiKey,this.model,f,u);return this._sendPromise=this._sendPromise.then(()=>d).catch(h=>{throw new Error(np)}).then(h=>h.response).then(h=>{if(h.candidates&&h.candidates.length>0){this._history.push(l);let p=Object.assign({},h.candidates[0].content);p.role||(p.role="model"),this._history.push(p)}else{let p=or(h);p&&console.warn(`sendMessageStream() was unsuccessful. ${p}. Inspect response object for details.`)}}).catch(h=>{h.message!==np&&console.error(h)}),d}};async function u_(t,e,r,n){return(await Eo(e,qr.COUNT_TOKENS,t,!1,JSON.stringify(r),n)).json()}async function f_(t,e,r,n){return(await Eo(e,qr.EMBED_CONTENT,t,!1,JSON.stringify(r),n)).json()}async function d_(t,e,r,n){let s=r.requests.map(i=>Object.assign(Object.assign({},i),{model:e}));return(await Eo(e,qr.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:s}),n)).json()}var da=class{constructor(e,r,n={}){this.apiKey=e,this._requestOptions=n,r.model.includes("/")?this.model=r.model:this.model=`models/${r.model}`,this.generationConfig=r.generationConfig||{},this.safetySettings=r.safetySettings||[],this.tools=r.tools,this.toolConfig=r.toolConfig,this.systemInstruction=ip(r.systemInstruction),this.cachedContent=r.cachedContent}async generateContent(e,r={}){var n;let s=tp(e),o=Object.assign(Object.assign({},this._requestOptions),r);return op(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}async generateContentStream(e,r={}){var n;let s=tp(e),o=Object.assign(Object.assign({},this._requestOptions),r);return sp(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}startChat(e){var r;return new Kc(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},e),this._requestOptions)}async countTokens(e,r={}){let n=i_(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),r);return u_(this.apiKey,this.model,n,s)}async embedContent(e,r={}){let n=a_(e),s=Object.assign(Object.assign({},this._requestOptions),r);return f_(this.apiKey,this.model,n,s)}async batchEmbedContents(e,r={}){let n=Object.assign(Object.assign({},this._requestOptions),r);return d_(this.apiKey,this.model,e,n)}};var ha=class{constructor(e){this.apiKey=e}getGenerativeModel(e,r){if(!e.model)throw new ye("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new da(this.apiKey,e,r)}getGenerativeModelFromCachedContent(e,r,n){if(!e.name)throw new ft("Cached content must contain a `name` field.");if(!e.model)throw new ft("Cached content must contain a `model` field.");let s=["model","systemInstruction"];for(let i of s)if(r!=null&&r[i]&&e[i]&&(r==null?void 0:r[i])!==e[i]){if(i==="model"){let a=r.model.startsWith("models/")?r.model.replace("models/",""):r.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(a===c)continue}throw new ft(`Different value for "${i}" specified in modelParams (${r[i]}) and cachedContent (${e[i]})`)}let o=Object.assign(Object.assign({},r),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new da(this.apiKey,o,n)}};var h_=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l}=i;if(!a)throw new Error(m("API key is required"));let[f,u,d]=e[0].role==="system"?[e[0],e.slice(1,-1),e[e.length-1]]:[null,e.slice(0,-1),e[e.length-1]],h=f==null?void 0:f.content,p=u.map(v=>({role:v.role==="assistant"?"model":v.role,parts:[{text:v.content}]})),_=await new ha(a).getGenerativeModel({model:l,systemInstruction:h},{baseUrl:c}).startChat({history:p}).sendMessageStream(d.content,{signal:r.signal});for await(let v of _.stream)yield v.text()},ap={name:"Gemini",defaultOptions:{apiKey:"",baseURL:"https://generativelanguage.googleapis.com",model:"gemini-1.5-flash",parameters:{}},sendRequestFunc:h_,models:[],websiteToObtainKey:"https://makersuite.google.com/app/apikey",capabilities:["Text Generation"]};var pa=require("obsidian");var lp=["gpt-image-1"],Ur={n:2,displayWidth:400,background:"auto",output_format:"jpeg",output_compression:90,quality:"auto",size:"auto"},p_=t=>async function*(e,r,n,s){let{parameters:o,...i}=t,a={...i,...o},{apiKey:c,baseURL:l,model:f,displayWidth:u,background:d,n:h,output_compression:p,output_format:y,quality:g,size:S}=a;if(!c)throw new Error(m("API key is required"));if(!s)throw new Error("saveAttachment is required");console.debug("messages:",e),console.debug("options:",a),e.length>1&&new pa.Notice(m("Only the last user message is used for image generation. Other messages are ignored."));let _=e.last();if(!_)throw new Error("No user message found in the conversation");let v=_.content,C=new D({apiKey:c,baseURL:l,dangerouslyAllowBrowser:!0});new pa.Notice(m("This is a non-streaming request, please wait..."),5*1e3);let x=null;if(_.embeds&&_.embeds.length>0){_.embeds.length>1&&new pa.Notice(m("Multiple embeds found, only the first one will be used"));let O=_.embeds[0],F=Or(O.link);if(!["image/png","image/jpeg","image/webp"].includes(F))throw new Error(m("Only PNG, JPEG, and WebP images are supported for editing."));let V=await n(O);if(!V||V.byteLength===0)throw new Error(m("Embed data is empty or invalid"));let H=new File([V],O.link,{type:F});x=await C.images.edit({image:H,prompt:v,background:d,model:f,n:h,size:S,quality:g},{signal:r.signal})}else x=await C.images.generate({prompt:v,background:d,model:f,size:S,n:h,output_compression:y==="jpeg"||y==="webp"?p:void 0,output_format:y,quality:g},{signal:r.signal});if(!x.data||x.data.length===0)throw new Error(m("Failed to generate image. no data received from API"));yield`
`;let P=new Date,k=`${P.getFullYear()}${String(P.getMonth()+1).padStart(2,"0")}${String(P.getDate()).padStart(2,"0")}_${String(P.getHours()).padStart(2,"0")}${String(P.getMinutes()).padStart(2,"0")}${String(P.getSeconds()).padStart(2,"0")}`;for(let O=0;O<x.data.length;O++){let q=x.data[O].b64_json;if(!q){console.error(`No base64 image data returned for image ${O+1}`);continue}let V=Buffer.from(q,"base64"),H=h>1?`-${O+1}`:"",ee=`gptImage-${k}${H}.${y}`;console.debug(`Saving image as ${ee}`),await s(ee,V),yield`![[${ee}|${u}]]
`}},ma={name:"GptImage",defaultOptions:{apiKey:"",baseURL:"https://api.openai.com/v1",model:lp[0],n:Ur.n,displayWidth:Ur.displayWidth,background:Ur.background,output_compression:Ur.output_compression,output_format:Ur.output_format,quality:Ur.quality,size:Ur.size,parameters:{}},sendRequestFunc:p_,models:lp,websiteToObtainKey:"https://platform.openai.com/api-keys",capabilities:["Image Generation","Image Editing"]};function Ao(t,e){return function(){return t.apply(e,arguments)}}var{toString:m_}=Object.prototype,{getPrototypeOf:zc}=Object,ya=(t=>e=>{let r=m_.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ge=t=>(t=t.toLowerCase(),e=>ya(e)===t),ba=t=>e=>typeof e===t,{isArray:as}=Array,vo=ba("undefined");function g_(t){return t!==null&&!vo(t)&&t.constructor!==null&&!vo(t.constructor)&&Te(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var up=Ge("ArrayBuffer");function y_(t){let e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&up(t.buffer),e}var b_=ba("string"),Te=ba("function"),fp=ba("number"),wa=t=>t!==null&&typeof t=="object",w_=t=>t===!0||t===!1,ga=t=>{if(ya(t)!=="object")return!1;let e=zc(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},__=Ge("Date"),S_=Ge("File"),x_=Ge("Blob"),E_=Ge("FileList"),A_=t=>wa(t)&&Te(t.pipe),v_=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Te(t.append)&&((e=ya(t))==="formdata"||e==="object"&&Te(t.toString)&&t.toString()==="[object FormData]"))},C_=Ge("URLSearchParams"),[P_,R_,T_,I_]=["ReadableStream","Request","Response","Headers"].map(Ge),k_=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Co(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t=="undefined")return;let n,s;if(typeof t!="object"&&(t=[t]),as(t))for(n=0,s=t.length;n<s;n++)e.call(null,t[n],n,t);else{let o=r?Object.getOwnPropertyNames(t):Object.keys(t),i=o.length,a;for(n=0;n<i;n++)a=o[n],e.call(null,t[a],a,t)}}function dp(t,e){e=e.toLowerCase();let r=Object.keys(t),n=r.length,s;for(;n-- >0;)if(s=r[n],e===s.toLowerCase())return s;return null}var $r=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:global,hp=t=>!vo(t)&&t!==$r;function Jc(){let{caseless:t}=hp(this)&&this||{},e={},r=(n,s)=>{let o=t&&dp(e,s)||s;ga(e[o])&&ga(n)?e[o]=Jc(e[o],n):ga(n)?e[o]=Jc({},n):as(n)?e[o]=n.slice():e[o]=n};for(let n=0,s=arguments.length;n<s;n++)arguments[n]&&Co(arguments[n],r);return e}var O_=(t,e,r,{allOwnKeys:n}={})=>(Co(e,(s,o)=>{r&&Te(s)?t[o]=Ao(s,r):t[o]=s},{allOwnKeys:n}),t),M_=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),L_=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},N_=(t,e,r,n)=>{let s,o,i,a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!n||n(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=r!==!1&&zc(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},D_=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},B_=t=>{if(!t)return null;if(as(t))return t;let e=t.length;if(!fp(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},F_=(t=>e=>t&&e instanceof t)(typeof Uint8Array!="undefined"&&zc(Uint8Array)),q_=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),s;for(;(s=n.next())&&!s.done;){let o=s.value;e.call(t,o[0],o[1])}},U_=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},$_=Ge("HTMLFormElement"),H_=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),cp=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),j_=Ge("RegExp"),pp=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Co(r,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(n[o]=i||s)}),Object.defineProperties(t,n)},W_=t=>{pp(t,(e,r)=>{if(Te(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(Te(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},V_=(t,e)=>{let r={},n=s=>{s.forEach(o=>{r[o]=!0})};return as(t)?n(t):n(String(t).split(e)),r},K_=()=>{},G_=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function J_(t){return!!(t&&Te(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var z_=t=>{let e=new Array(10),r=(n,s)=>{if(wa(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[s]=n;let o=as(n)?[]:{};return Co(n,(i,a)=>{let c=r(i,s+1);!vo(c)&&(o[a]=c)}),e[s]=void 0,o}}return n};return r(t,0)},X_=Ge("AsyncFunction"),Y_=t=>t&&(wa(t)||Te(t))&&Te(t.then)&&Te(t.catch),mp=((t,e)=>t?setImmediate:e?((r,n)=>($r.addEventListener("message",({source:s,data:o})=>{s===$r&&o===r&&n.length&&n.shift()()},!1),s=>{n.push(s),$r.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Te($r.postMessage)),Q_=typeof queueMicrotask!="undefined"?queueMicrotask.bind($r):typeof process!="undefined"&&process.nextTick||mp,w={isArray:as,isArrayBuffer:up,isBuffer:g_,isFormData:v_,isArrayBufferView:y_,isString:b_,isNumber:fp,isBoolean:w_,isObject:wa,isPlainObject:ga,isReadableStream:P_,isRequest:R_,isResponse:T_,isHeaders:I_,isUndefined:vo,isDate:__,isFile:S_,isBlob:x_,isRegExp:j_,isFunction:Te,isStream:A_,isURLSearchParams:C_,isTypedArray:F_,isFileList:E_,forEach:Co,merge:Jc,extend:O_,trim:k_,stripBOM:M_,inherits:L_,toFlatObject:N_,kindOf:ya,kindOfTest:Ge,endsWith:D_,toArray:B_,forEachEntry:q_,matchAll:U_,isHTMLForm:$_,hasOwnProperty:cp,hasOwnProp:cp,reduceDescriptors:pp,freezeMethods:W_,toObjectSet:V_,toCamelCase:H_,noop:K_,toFiniteNumber:G_,findKey:dp,global:$r,isContextDefined:hp,isSpecCompliantForm:J_,toJSONObject:z_,isAsyncFn:X_,isThenable:Y_,setImmediate:mp,asap:Q_};function ls(t,e,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}w.inherits(ls,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:w.toJSONObject(this.config),code:this.code,status:this.status}}});var gp=ls.prototype,yp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{yp[t]={value:t}});Object.defineProperties(ls,yp);Object.defineProperty(gp,"isAxiosError",{value:!0});ls.from=(t,e,r,n,s,o)=>{let i=Object.create(gp);return w.toFlatObject(t,i,function(c){return c!==Error.prototype},a=>a!=="isAxiosError"),ls.call(i,t.message,e,r,n,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};var $=ls;var _a=null;function Xc(t){return w.isPlainObject(t)||w.isArray(t)}function wp(t){return w.endsWith(t,"[]")?t.slice(0,-2):t}function bp(t,e,r){return t?t.concat(e).map(function(s,o){return s=wp(s),!r&&o?"["+s+"]":s}).join(r?".":""):e}function Z_(t){return w.isArray(t)&&!t.some(Xc)}var eS=w.toFlatObject(w,{},null,function(e){return/^is[A-Z]/.test(e)});function tS(t,e,r){if(!w.isObject(t))throw new TypeError("target must be an object");e=e||new(_a||FormData),r=w.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,g){return!w.isUndefined(g[y])});let n=r.metaTokens,s=r.visitor||f,o=r.dots,i=r.indexes,c=(r.Blob||typeof Blob!="undefined"&&Blob)&&w.isSpecCompliantForm(e);if(!w.isFunction(s))throw new TypeError("visitor must be a function");function l(p){if(p===null)return"";if(w.isDate(p))return p.toISOString();if(!c&&w.isBlob(p))throw new $("Blob is not supported. Use a Buffer instead.");return w.isArrayBuffer(p)||w.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function f(p,y,g){let S=p;if(p&&!g&&typeof p=="object"){if(w.endsWith(y,"{}"))y=n?y:y.slice(0,-2),p=JSON.stringify(p);else if(w.isArray(p)&&Z_(p)||(w.isFileList(p)||w.endsWith(y,"[]"))&&(S=w.toArray(p)))return y=wp(y),S.forEach(function(v,C){!(w.isUndefined(v)||v===null)&&e.append(i===!0?bp([y],C,o):i===null?y:y+"[]",l(v))}),!1}return Xc(p)?!0:(e.append(bp(g,y,o),l(p)),!1)}let u=[],d=Object.assign(eS,{defaultVisitor:f,convertValue:l,isVisitable:Xc});function h(p,y){if(!w.isUndefined(p)){if(u.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));u.push(p),w.forEach(p,function(S,_){(!(w.isUndefined(S)||S===null)&&s.call(e,S,w.isString(_)?_.trim():_,y,d))===!0&&h(S,y?y.concat(_):[_])}),u.pop()}}if(!w.isObject(t))throw new TypeError("data must be an object");return h(t),e}var ir=tS;function _p(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function Sp(t,e){this._pairs=[],t&&ir(t,this,e)}var xp=Sp.prototype;xp.append=function(e,r){this._pairs.push([e,r])};xp.toString=function(e){let r=e?function(n){return e.call(this,n,_p)}:_p;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};var Sa=Sp;function rS(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Po(t,e,r){if(!e)return t;let n=r&&r.encode||rS;w.isFunction(r)&&(r={serialize:r});let s=r&&r.serialize,o;if(s?o=s(e,r):o=w.isURLSearchParams(e)?e.toString():new Sa(e,r).toString(n),o){let i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}var Yc=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){w.forEach(this.handlers,function(n){n!==null&&e(n)})}},Qc=Yc;var xa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Ep=typeof URLSearchParams!="undefined"?URLSearchParams:Sa;var Ap=typeof FormData!="undefined"?FormData:null;var vp=typeof Blob!="undefined"?Blob:null;var Cp={isBrowser:!0,classes:{URLSearchParams:Ep,FormData:Ap,Blob:vp},protocols:["http","https","file","blob","url","data"]};var tu={};nd(tu,{hasBrowserEnv:()=>eu,hasStandardBrowserEnv:()=>nS,hasStandardBrowserWebWorkerEnv:()=>sS,navigator:()=>Zc,origin:()=>oS});var eu=typeof window!="undefined"&&typeof document!="undefined",Zc=typeof navigator=="object"&&navigator||void 0,nS=eu&&(!Zc||["ReactNative","NativeScript","NS"].indexOf(Zc.product)<0),sS=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",oS=eu&&window.location.href||"http://localhost";var z={...tu,...Cp};function ru(t,e){return ir(t,new z.classes.URLSearchParams,Object.assign({visitor:function(r,n,s,o){return z.isNode&&w.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},e))}function iS(t){return w.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function aS(t){let e={},r=Object.keys(t),n,s=r.length,o;for(n=0;n<s;n++)o=r[n],e[o]=t[o];return e}function lS(t){function e(r,n,s,o){let i=r[o++];if(i==="__proto__")return!0;let a=Number.isFinite(+i),c=o>=r.length;return i=!i&&w.isArray(s)?s.length:i,c?(w.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!a):((!s[i]||!w.isObject(s[i]))&&(s[i]=[]),e(r,n,s[i],o)&&w.isArray(s[i])&&(s[i]=aS(s[i])),!a)}if(w.isFormData(t)&&w.isFunction(t.entries)){let r={};return w.forEachEntry(t,(n,s)=>{e(iS(n),s,r,0)}),r}return null}var Ea=lS;function cS(t,e,r){if(w.isString(t))try{return(e||JSON.parse)(t),w.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var nu={transitional:xa,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){let n=r.getContentType()||"",s=n.indexOf("application/json")>-1,o=w.isObject(e);if(o&&w.isHTMLForm(e)&&(e=new FormData(e)),w.isFormData(e))return s?JSON.stringify(Ea(e)):e;if(w.isArrayBuffer(e)||w.isBuffer(e)||w.isStream(e)||w.isFile(e)||w.isBlob(e)||w.isReadableStream(e))return e;if(w.isArrayBufferView(e))return e.buffer;if(w.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return ru(e,this.formSerializer).toString();if((a=w.isFileList(e))||n.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return ir(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return o||s?(r.setContentType("application/json",!1),cS(e)):e}],transformResponse:[function(e){let r=this.transitional||nu.transitional,n=r&&r.forcedJSONParsing,s=this.responseType==="json";if(w.isResponse(e)||w.isReadableStream(e))return e;if(e&&w.isString(e)&&(n&&!this.responseType||s)){let i=!(r&&r.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(i)throw a.name==="SyntaxError"?$.from(a,$.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:z.classes.FormData,Blob:z.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};w.forEach(["delete","get","head","post","put","patch"],t=>{nu.headers[t]={}});var cs=nu;var uS=w.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Pp=t=>{let e={},r,n,s;return t&&t.split(`
`).forEach(function(i){s=i.indexOf(":"),r=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!r||e[r]&&uS[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e};var Rp=Symbol("internals");function Ro(t){return t&&String(t).trim().toLowerCase()}function Aa(t){return t===!1||t==null?t:w.isArray(t)?t.map(Aa):String(t)}function fS(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var dS=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function su(t,e,r,n,s){if(w.isFunction(n))return n.call(this,e,r);if(s&&(e=r),!!w.isString(e)){if(w.isString(n))return e.indexOf(n)!==-1;if(w.isRegExp(n))return n.test(e)}}function hS(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function pS(t,e){let r=w.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}var us=class{constructor(e){e&&this.set(e)}set(e,r,n){let s=this;function o(a,c,l){let f=Ro(c);if(!f)throw new Error("header name must be a non-empty string");let u=w.findKey(s,f);(!u||s[u]===void 0||l===!0||l===void 0&&s[u]!==!1)&&(s[u||c]=Aa(a))}let i=(a,c)=>w.forEach(a,(l,f)=>o(l,f,c));if(w.isPlainObject(e)||e instanceof this.constructor)i(e,r);else if(w.isString(e)&&(e=e.trim())&&!dS(e))i(Pp(e),r);else if(w.isHeaders(e))for(let[a,c]of e.entries())o(c,a,n);else e!=null&&o(r,e,n);return this}get(e,r){if(e=Ro(e),e){let n=w.findKey(this,e);if(n){let s=this[n];if(!r)return s;if(r===!0)return fS(s);if(w.isFunction(r))return r.call(this,s,n);if(w.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=Ro(e),e){let n=w.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||su(this,this[n],n,r)))}return!1}delete(e,r){let n=this,s=!1;function o(i){if(i=Ro(i),i){let a=w.findKey(n,i);a&&(!r||su(n,n[a],a,r))&&(delete n[a],s=!0)}}return w.isArray(e)?e.forEach(o):o(e),s}clear(e){let r=Object.keys(this),n=r.length,s=!1;for(;n--;){let o=r[n];(!e||su(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){let r=this,n={};return w.forEach(this,(s,o)=>{let i=w.findKey(n,o);if(i){r[i]=Aa(s),delete r[o];return}let a=e?hS(o):String(o).trim();a!==o&&delete r[o],r[a]=Aa(s),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return w.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=e&&w.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(`
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(s=>n.set(s)),n}static accessor(e){let n=(this[Rp]=this[Rp]={accessors:{}}).accessors,s=this.prototype;function o(i){let a=Ro(i);n[a]||(pS(s,i),n[a]=!0)}return w.isArray(e)?e.forEach(o):o(e),this}};us.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);w.reduceDescriptors(us.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});w.freezeMethods(us);var oe=us;function To(t,e){let r=this||cs,n=e||r,s=oe.from(n.headers),o=n.data;return w.forEach(t,function(a){o=a.call(r,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Io(t){return!!(t&&t.__CANCEL__)}function Tp(t,e,r){$.call(this,t==null?"canceled":t,$.ERR_CANCELED,e,r),this.name="CanceledError"}w.inherits(Tp,$,{__CANCEL__:!0});var dt=Tp;function ko(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new $("Request failed with status code "+r.status,[$.ERR_BAD_REQUEST,$.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function ou(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function mS(t,e){t=t||10;let r=new Array(t),n=new Array(t),s=0,o=0,i;return e=e!==void 0?e:1e3,function(c){let l=Date.now(),f=n[o];i||(i=l),r[s]=c,n[s]=l;let u=o,d=0;for(;u!==s;)d+=r[u++],u=u%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),l-i<e)return;let h=f&&l-f;return h?Math.round(d*1e3/h):void 0}}var Ip=mS;function gS(t,e){let r=0,n=1e3/e,s,o,i=(l,f=Date.now())=>{r=f,s=null,o&&(clearTimeout(o),o=null),t.apply(null,l)};return[(...l)=>{let f=Date.now(),u=f-r;u>=n?i(l,f):(s=l,o||(o=setTimeout(()=>{o=null,i(s)},n-u)))},()=>s&&i(s)]}var kp=gS;var fs=(t,e,r=3)=>{let n=0,s=Ip(50,250);return kp(o=>{let i=o.loaded,a=o.lengthComputable?o.total:void 0,c=i-n,l=s(c),f=i<=a;n=i;let u={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&f?(a-i)/l:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(u)},r)},iu=(t,e)=>{let r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},au=t=>(...e)=>w.asap(()=>t(...e));var Op=z.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,z.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(z.origin),z.navigator&&/(msie|trident)/i.test(z.navigator.userAgent)):()=>!0;var Mp=z.hasStandardBrowserEnv?{write(t,e,r,n,s,o){let i=[t+"="+encodeURIComponent(e)];w.isNumber(r)&&i.push("expires="+new Date(r).toGMTString()),w.isString(n)&&i.push("path="+n),w.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function lu(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function cu(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Oo(t,e,r){let n=!lu(e);return t&&n||r==!1?cu(t,e):e}var Lp=t=>t instanceof oe?{...t}:t;function Je(t,e){e=e||{};let r={};function n(l,f,u,d){return w.isPlainObject(l)&&w.isPlainObject(f)?w.merge.call({caseless:d},l,f):w.isPlainObject(f)?w.merge({},f):w.isArray(f)?f.slice():f}function s(l,f,u,d){if(w.isUndefined(f)){if(!w.isUndefined(l))return n(void 0,l,u,d)}else return n(l,f,u,d)}function o(l,f){if(!w.isUndefined(f))return n(void 0,f)}function i(l,f){if(w.isUndefined(f)){if(!w.isUndefined(l))return n(void 0,l)}else return n(void 0,f)}function a(l,f,u){if(u in e)return n(l,f);if(u in t)return n(void 0,l)}let c={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(l,f,u)=>s(Lp(l),Lp(f),u,!0)};return w.forEach(Object.keys(Object.assign({},t,e)),function(f){let u=c[f]||s,d=u(t[f],e[f],f);w.isUndefined(d)&&u!==a||(r[f]=d)}),r}var va=t=>{let e=Je({},t),{data:r,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;e.headers=i=oe.from(i),e.url=Po(Oo(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(w.isFormData(r)){if(z.hasStandardBrowserEnv||z.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((c=i.getContentType())!==!1){let[l,...f]=c?c.split(";").map(u=>u.trim()).filter(Boolean):[];i.setContentType([l||"multipart/form-data",...f].join("; "))}}if(z.hasStandardBrowserEnv&&(n&&w.isFunction(n)&&(n=n(e)),n||n!==!1&&Op(e.url))){let l=s&&o&&Mp.read(o);l&&i.set(s,l)}return e};var yS=typeof XMLHttpRequest!="undefined",Np=yS&&function(t){return new Promise(function(r,n){let s=va(t),o=s.data,i=oe.from(s.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:l}=s,f,u,d,h,p;function y(){h&&h(),p&&p(),s.cancelToken&&s.cancelToken.unsubscribe(f),s.signal&&s.signal.removeEventListener("abort",f)}let g=new XMLHttpRequest;g.open(s.method.toUpperCase(),s.url,!0),g.timeout=s.timeout;function S(){if(!g)return;let v=oe.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),x={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:v,config:t,request:g};ko(function(k){r(k),y()},function(k){n(k),y()},x),g=null}"onloadend"in g?g.onloadend=S:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(S)},g.onabort=function(){g&&(n(new $("Request aborted",$.ECONNABORTED,t,g)),g=null)},g.onerror=function(){n(new $("Network Error",$.ERR_NETWORK,t,g)),g=null},g.ontimeout=function(){let C=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded",x=s.transitional||xa;s.timeoutErrorMessage&&(C=s.timeoutErrorMessage),n(new $(C,x.clarifyTimeoutError?$.ETIMEDOUT:$.ECONNABORTED,t,g)),g=null},o===void 0&&i.setContentType(null),"setRequestHeader"in g&&w.forEach(i.toJSON(),function(C,x){g.setRequestHeader(x,C)}),w.isUndefined(s.withCredentials)||(g.withCredentials=!!s.withCredentials),a&&a!=="json"&&(g.responseType=s.responseType),l&&([d,p]=fs(l,!0),g.addEventListener("progress",d)),c&&g.upload&&([u,h]=fs(c),g.upload.addEventListener("progress",u),g.upload.addEventListener("loadend",h)),(s.cancelToken||s.signal)&&(f=v=>{g&&(n(!v||v.type?new dt(null,t,g):v),g.abort(),g=null)},s.cancelToken&&s.cancelToken.subscribe(f),s.signal&&(s.signal.aborted?f():s.signal.addEventListener("abort",f)));let _=ou(s.url);if(_&&z.protocols.indexOf(_)===-1){n(new $("Unsupported protocol "+_+":",$.ERR_BAD_REQUEST,t));return}g.send(o||null)})};var bS=(t,e)=>{let{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,s,o=function(l){if(!s){s=!0,a();let f=l instanceof Error?l:this.reason;n.abort(f instanceof $?f:new dt(f instanceof Error?f.message:f))}},i=e&&setTimeout(()=>{i=null,o(new $(`timeout ${e} of ms exceeded`,$.ETIMEDOUT))},e),a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),t=null)};t.forEach(l=>l.addEventListener("abort",o));let{signal:c}=n;return c.unsubscribe=()=>w.asap(a),c}},Dp=bS;var wS=function*(t,e){let r=t.byteLength;if(!e||r<e){yield t;return}let n=0,s;for(;n<r;)s=n+e,yield t.slice(n,s),n=s},_S=async function*(t,e){for await(let r of SS(t))yield*wS(r,e)},SS=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}let e=t.getReader();try{for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},uu=(t,e,r,n)=>{let s=_S(t,e),o=0,i,a=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:l,value:f}=await s.next();if(l){a(),c.close();return}let u=f.byteLength;if(r){let d=o+=u;r(d)}c.enqueue(new Uint8Array(f))}catch(l){throw a(l),l}},cancel(c){return a(c),s.return()}},{highWaterMark:2})};var Pa=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Fp=Pa&&typeof ReadableStream=="function",xS=Pa&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),qp=(t,...e)=>{try{return!!t(...e)}catch(r){return!1}},ES=Fp&&qp(()=>{let t=!1,e=new Request(z.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),Bp=64*1024,fu=Fp&&qp(()=>w.isReadableStream(new Response("").body)),Ca={stream:fu&&(t=>t.body)};Pa&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ca[e]&&(Ca[e]=w.isFunction(t[e])?r=>r[e]():(r,n)=>{throw new $(`Response type '${e}' is not supported`,$.ERR_NOT_SUPPORT,n)})})})(new Response);var AS=async t=>{if(t==null)return 0;if(w.isBlob(t))return t.size;if(w.isSpecCompliantForm(t))return(await new Request(z.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(w.isArrayBufferView(t)||w.isArrayBuffer(t))return t.byteLength;if(w.isURLSearchParams(t)&&(t=t+""),w.isString(t))return(await xS(t)).byteLength},vS=async(t,e)=>{let r=w.toFiniteNumber(t.getContentLength());return r==null?AS(e):r},Up=Pa&&(async t=>{let{url:e,method:r,data:n,signal:s,cancelToken:o,timeout:i,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:f,withCredentials:u="same-origin",fetchOptions:d}=va(t);l=l?(l+"").toLowerCase():"text";let h=Dp([s,o&&o.toAbortSignal()],i),p,y=h&&h.unsubscribe&&(()=>{h.unsubscribe()}),g;try{if(c&&ES&&r!=="get"&&r!=="head"&&(g=await vS(f,n))!==0){let x=new Request(e,{method:"POST",body:n,duplex:"half"}),P;if(w.isFormData(n)&&(P=x.headers.get("content-type"))&&f.setContentType(P),x.body){let[k,O]=iu(g,fs(au(c)));n=uu(x.body,Bp,k,O)}}w.isString(u)||(u=u?"include":"omit");let S="credentials"in Request.prototype;p=new Request(e,{...d,signal:h,method:r.toUpperCase(),headers:f.normalize().toJSON(),body:n,duplex:"half",credentials:S?u:void 0});let _=await fetch(p),v=fu&&(l==="stream"||l==="response");if(fu&&(a||v&&y)){let x={};["status","statusText","headers"].forEach(F=>{x[F]=_[F]});let P=w.toFiniteNumber(_.headers.get("content-length")),[k,O]=a&&iu(P,fs(au(a),!0))||[];_=new Response(uu(_.body,Bp,k,()=>{O&&O(),y&&y()}),x)}l=l||"text";let C=await Ca[w.findKey(Ca,l)||"text"](_,t);return!v&&y&&y(),await new Promise((x,P)=>{ko(x,P,{data:C,headers:oe.from(_.headers),status:_.status,statusText:_.statusText,config:t,request:p})})}catch(S){throw y&&y(),S&&S.name==="TypeError"&&/fetch/i.test(S.message)?Object.assign(new $("Network Error",$.ERR_NETWORK,t,p),{cause:S.cause||S}):$.from(S,S&&S.code,t,p)}});var du={http:_a,xhr:Np,fetch:Up};w.forEach(du,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(r){}Object.defineProperty(t,"adapterName",{value:e})}});var $p=t=>`- ${t}`,CS=t=>w.isFunction(t)||t===null||t===!1,Ra={getAdapter:t=>{t=w.isArray(t)?t:[t];let{length:e}=t,r,n,s={};for(let o=0;o<e;o++){r=t[o];let i;if(n=r,!CS(r)&&(n=du[(i=String(r)).toLowerCase()],n===void 0))throw new $(`Unknown adapter '${i}'`);if(n)break;s[i||"#"+o]=n}if(!n){let o=Object.entries(s).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build")),i=e?o.length>1?`since :
`+o.map($p).join(`
`):" "+$p(o[0]):"as no adapter specified";throw new $("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return n},adapters:du};function hu(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new dt(null,t)}function Ta(t){return hu(t),t.headers=oe.from(t.headers),t.data=To.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Ra.getAdapter(t.adapter||cs.adapter)(t).then(function(n){return hu(t),n.data=To.call(t,t.transformResponse,n),n.headers=oe.from(n.headers),n},function(n){return Io(n)||(hu(t),n&&n.response&&(n.response.data=To.call(t,t.transformResponse,n.response),n.response.headers=oe.from(n.response.headers))),Promise.reject(n)})}var Ia="1.8.3";var ka={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ka[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var Hp={};ka.transitional=function(e,r,n){function s(o,i){return"[Axios v"+Ia+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,a)=>{if(e===!1)throw new $(s(i," has been removed"+(r?" in "+r:"")),$.ERR_DEPRECATED);return r&&!Hp[i]&&(Hp[i]=!0,console.warn(s(i," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(o,i,a):!0}};ka.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function PS(t,e,r){if(typeof t!="object")throw new $("options must be an object",$.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),s=n.length;for(;s-- >0;){let o=n[s],i=e[o];if(i){let a=t[o],c=a===void 0||i(a,o,t);if(c!==!0)throw new $("option "+o+" must be "+c,$.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new $("Unknown option "+o,$.ERR_BAD_OPTION)}}var Mo={assertOptions:PS,validators:ka};var ht=Mo.validators,ds=class{constructor(e){this.defaults=e,this.interceptors={request:new Qc,response:new Qc}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;let o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
`+o):n.stack=o}catch(i){}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Je(this.defaults,r);let{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&Mo.assertOptions(n,{silentJSONParsing:ht.transitional(ht.boolean),forcedJSONParsing:ht.transitional(ht.boolean),clarifyTimeoutError:ht.transitional(ht.boolean)},!1),s!=null&&(w.isFunction(s)?r.paramsSerializer={serialize:s}:Mo.assertOptions(s,{encode:ht.function,serialize:ht.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Mo.assertOptions(r,{baseUrl:ht.spelling("baseURL"),withXsrfToken:ht.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&w.merge(o.common,o[r.method]);o&&w.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),r.headers=oe.concat(i,o);let a=[],c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});let l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let f,u=0,d;if(!c){let p=[Ta.bind(this),void 0];for(p.unshift.apply(p,a),p.push.apply(p,l),d=p.length,f=Promise.resolve(r);u<d;)f=f.then(p[u++],p[u++]);return f}d=a.length;let h=r;for(u=0;u<d;){let p=a[u++],y=a[u++];try{h=p(h)}catch(g){y.call(this,g);break}}try{f=Ta.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,d=l.length;u<d;)f=f.then(l[u++],l[u++]);return f}getUri(e){e=Je(this.defaults,e);let r=Oo(e.baseURL,e.url,e.allowAbsoluteUrls);return Po(r,e.params,e.paramsSerializer)}};w.forEach(["delete","get","head","options"],function(e){ds.prototype[e]=function(r,n){return this.request(Je(n||{},{method:e,url:r,data:(n||{}).data}))}});w.forEach(["post","put","patch"],function(e){function r(n){return function(o,i,a){return this.request(Je(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}ds.prototype[e]=r(),ds.prototype[e+"Form"]=r(!0)});var Lo=ds;var pu=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o,i=new Promise(a=>{n.subscribe(a),o=a}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,a){n.reason||(n.reason=new dt(o,i,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(s){e=s}),cancel:e}}},jp=pu;function mu(t){return function(r){return t.apply(null,r)}}function gu(t){return w.isObject(t)&&t.isAxiosError===!0}var yu={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(yu).forEach(([t,e])=>{yu[e]=t});var Wp=yu;function Vp(t){let e=new Lo(t),r=Ao(Lo.prototype.request,e);return w.extend(r,Lo.prototype,e,{allOwnKeys:!0}),w.extend(r,e,null,{allOwnKeys:!0}),r.create=function(s){return Vp(Je(t,s))},r}var Q=Vp(cs);Q.Axios=Lo;Q.CanceledError=dt;Q.CancelToken=jp;Q.isCancel=Io;Q.VERSION=Ia;Q.toFormData=ir;Q.AxiosError=$;Q.Cancel=Q.CanceledError;Q.all=function(e){return Promise.all(e)};Q.spread=mu;Q.isAxiosError=gu;Q.mergeConfig=Je;Q.AxiosHeaders=oe;Q.formToJSON=t=>Ea(w.isHTMLForm(t)?new FormData(t):t);Q.getAdapter=Ra.getAdapter;Q.HttpStatusCode=Wp;Q.default=Q;var ar=Q;var{Axios:QL,AxiosError:ZL,CanceledError:eN,isCancel:tN,CancelToken:rN,VERSION:nN,all:sN,Cancel:oN,isAxiosError:iN,spread:aN,toFormData:lN,AxiosHeaders:cN,HttpStatusCode:uN,formToJSON:fN,getAdapter:dN,mergeConfig:hN}=ar;var RS=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u=await Promise.all(e.map(S=>TS(S,n))),d={model:l,messages:u,stream:!0,...f},p=(await ar.post(c,d,{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},adapter:"fetch",responseType:"stream",withCredentials:!1,signal:r.signal})).data.pipeThrough(new TextDecoderStream).getReader(),y=!0,g=!1;for(;y;){let{done:S,value:_}=await p.read();if(S){y=!1;break}let v=_.split(`
`);for(let C of v){if(C.includes("data: [DONE]")){y=!1;break}let x=C.replace(/^data: /,"").trim();if(x){let P=JSON.parse(x);if(P.choices&&P.choices[0].delta){let k=P.choices[0].delta,O=k.reasoning_content;if(O)yield(g?"":(g=!0,Me))+O.replace(/\n/g,`
> `);else{let F=g?(g=!1,Le):"";k.content&&(yield F+k.content)}}}}}},TS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>lt(n,e))):[];return r.length===0?{role:t.role,content:t.content}:(t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r})},Oa={name:"Grok",defaultOptions:{apiKey:"",baseURL:"https://api.x.ai/v1/chat/completions",model:"",parameters:{}},sendRequestFunc:RS,models:[],websiteToObtainKey:"https://x.ai",capabilities:["Text Generation","Reasoning","Image Vision"]};var IS=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u=await Promise.all(e.map(S=>kS(S,n))),d={model:l,messages:u,stream:!0,...f},p=(await ar.post(c,d,{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},adapter:"fetch",responseType:"stream",withCredentials:!1,signal:r.signal})).data.pipeThrough(new TextDecoderStream).getReader(),y=!0,g=!1;for(;y;){let{done:S,value:_}=await p.read();if(S){y=!1;break}let v=_.split(`
`);for(let C of v){if(C.includes("data: [DONE]")){y=!1;break}let x=C.replace(/^data: /,"").trim();if(x){let P=JSON.parse(x);if(P.choices&&P.choices[0].delta){let k=P.choices[0].delta,O=k.reasoning_content;if(O)yield(g?"":(g=!0,Me))+O.replace(/\n/g,`
> `);else{let F=g?(g=!1,Le):"";k.content&&(yield F+k.content)}}}}}},kS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>lt(n,e))):[];return r.length===0?{role:t.role,content:t.content}:(t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r})},Ma={name:"Kimi",defaultOptions:{apiKey:"",baseURL:"https://api.moonshot.cn/v1/chat/completions",model:"",parameters:{}},sendRequestFunc:IS,models:[],websiteToObtainKey:"https://www.moonshot.cn",capabilities:["Text Generation","Image Vision","Reasoning"]};var he=typeof globalThis!="undefined"&&globalThis||typeof self!="undefined"&&self||typeof global!="undefined"&&global||{},_e={searchParams:"URLSearchParams"in he,iterable:"Symbol"in he&&"iterator"in Symbol,blob:"FileReader"in he&&"Blob"in he&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in he,arrayBuffer:"ArrayBuffer"in he};function OS(t){return t&&DataView.prototype.isPrototypeOf(t)}_e.arrayBuffer&&(Kp=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Jp=ArrayBuffer.isView||function(t){return t&&Kp.indexOf(Object.prototype.toString.call(t))>-1});var Kp,Jp;function hs(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function wu(t){return typeof t!="string"&&(t=String(t)),t}function _u(t){var e={next:function(){var r=t.shift();return{done:r===void 0,value:r}}};return _e.iterable&&(e[Symbol.iterator]=function(){return e}),e}function ie(t){this.map={},t instanceof ie?t.forEach(function(e,r){this.append(r,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}ie.prototype.append=function(t,e){t=hs(t),e=wu(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};ie.prototype.delete=function(t){delete this.map[hs(t)]};ie.prototype.get=function(t){return t=hs(t),this.has(t)?this.map[t]:null};ie.prototype.has=function(t){return this.map.hasOwnProperty(hs(t))};ie.prototype.set=function(t,e){this.map[hs(t)]=wu(e)};ie.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};ie.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),_u(t)};ie.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),_u(t)};ie.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),_u(t)};_e.iterable&&(ie.prototype[Symbol.iterator]=ie.prototype.entries);function bu(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function zp(t){return new Promise(function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}})}function MS(t){var e=new FileReader,r=zp(e);return e.readAsArrayBuffer(t),r}function LS(t){var e=new FileReader,r=zp(e),n=/charset=([A-Za-z0-9_-]+)/.exec(t.type),s=n?n[1]:"utf-8";return e.readAsText(t,s),r}function NS(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}function Gp(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function Xp(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:_e.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:_e.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:_e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():_e.arrayBuffer&&_e.blob&&OS(t)?(this._bodyArrayBuffer=Gp(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):_e.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||Jp(t))?this._bodyArrayBuffer=Gp(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):_e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},_e.blob&&(this.blob=function(){var t=bu(this);if(t)return t;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 t=bu(this);return t||(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(_e.blob)return this.blob().then(MS);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=bu(this);if(t)return t;if(this._bodyBlob)return LS(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(NS(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},_e.formData&&(this.formData=function(){return this.text().then(FS)}),this.json=function(){return this.text().then(JSON.parse)},this}var DS=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function BS(t){var e=t.toUpperCase();return DS.indexOf(e)>-1?e:t}function jr(t,e){if(!(this instanceof jr))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var r=e.body;if(t instanceof jr){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new ie(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!r&&t._bodyInit!=null&&(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new ie(e.headers)),this.method=BS(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in he){var o=new AbortController;return o.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+new Date().getTime());else{var s=/\?/;this.url+=(s.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}jr.prototype.clone=function(){return new jr(this,{body:this._bodyInit})};function FS(t){var e=new FormData;return t.trim().split("&").forEach(function(r){if(r){var n=r.split("="),s=n.shift().replace(/\+/g," "),o=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(o))}}),e}function qS(t){var e=new ie,r=t.replace(/\r?\n[\t ]+/g," ");return r.split("\r").map(function(n){return n.indexOf(`
`)===0?n.substr(1,n.length):n}).forEach(function(n){var s=n.split(":"),o=s.shift().trim();if(o){var i=s.join(":").trim();try{e.append(o,i)}catch(a){console.warn("Response "+a.message)}}}),e}Xp.call(jr.prototype);function pt(t,e){if(!(this instanceof pt))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.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=e.statusText===void 0?"":""+e.statusText,this.headers=new ie(e.headers),this.url=e.url||"",this._initBody(t)}Xp.call(pt.prototype);pt.prototype.clone=function(){return new pt(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new ie(this.headers),url:this.url})};pt.error=function(){var t=new pt(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var US=[301,302,303,307,308];pt.redirect=function(t,e){if(US.indexOf(e)===-1)throw new RangeError("Invalid status code");return new pt(null,{status:e,headers:{location:t}})};var Hr=he.DOMException;try{new Hr}catch(t){Hr=function(e,r){this.message=e,this.name=r;var n=Error(e);this.stack=n.stack},Hr.prototype=Object.create(Error.prototype),Hr.prototype.constructor=Hr}function Yp(t,e){return new Promise(function(r,n){var s=new jr(t,e);if(s.signal&&s.signal.aborted)return n(new Hr("Aborted","AbortError"));var o=new XMLHttpRequest;function i(){o.abort()}o.onload=function(){var l={statusText:o.statusText,headers:qS(o.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(o.status<200||o.status>599)?l.status=200:l.status=o.status,l.url="responseURL"in o?o.responseURL:l.headers.get("X-Request-URL");var f="response"in o?o.response:o.responseText;setTimeout(function(){r(new pt(f,l))},0)},o.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},o.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},o.onabort=function(){setTimeout(function(){n(new Hr("Aborted","AbortError"))},0)};function a(l){try{return l===""&&he.location.href?he.location.href:l}catch(f){return l}}if(o.open(s.method,a(s.url),!0),s.credentials==="include"?o.withCredentials=!0:s.credentials==="omit"&&(o.withCredentials=!1),"responseType"in o&&(_e.blob?o.responseType="blob":_e.arrayBuffer&&(o.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof ie||he.Headers&&e.headers instanceof he.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){c.push(hs(l)),o.setRequestHeader(l,wu(e.headers[l]))}),s.headers.forEach(function(l,f){c.indexOf(f)===-1&&o.setRequestHeader(f,l)})}else s.headers.forEach(function(l,f){o.setRequestHeader(f,l)});s.signal&&(s.signal.addEventListener("abort",i),o.onreadystatechange=function(){o.readyState===4&&s.signal.removeEventListener("abort",i)}),o.send(typeof s._bodyInit=="undefined"?null:s._bodyInit)})}Yp.polyfill=!0;he.fetch||(he.fetch=Yp,he.Headers=ie,he.Request=jr,he.Response=pt);var Zp="11434",em=`http://127.0.0.1:${Zp}`,$S="0.5.16",HS=Object.defineProperty,jS=(t,e,r)=>e in t?HS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Su=(t,e,r)=>(jS(t,typeof e!="symbol"?e+"":e,r),r),Eu=class t extends Error{constructor(e,r){super(e),this.error=e,this.status_code=r,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,t)}},Au=class{constructor(e,r,n){Su(this,"abortController"),Su(this,"itr"),Su(this,"doneCallback"),this.abortController=e,this.itr=r,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.")}},vu=async t=>{var n;if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,r=null;if((n=t.headers.get("content-type"))!=null&&n.includes("application/json"))try{r=await t.json(),e=r.error||e}catch(s){console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch(s){console.log("Failed to get text from error response")}throw new Eu(e,t.status)};function WS(){var t;if(typeof window!="undefined"&&window.navigator){let e=navigator;return"userAgentData"in e&&((t=e.userAgentData)!=null&&t.platform)?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process!="undefined")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function VS(t){if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var Cu=async(t,e,r={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${$S} (${WS()})`};r.headers=VS(r.headers);let s=Object.fromEntries(Object.entries(r.headers).filter(([o])=>!Object.keys(n).some(i=>i.toLowerCase()===o.toLowerCase())));return r.headers={...n,...s},t(e,r)},Qp=async(t,e,r)=>{let n=await Cu(t,e,{headers:r==null?void 0:r.headers});return await vu(n),n},ps=async(t,e,r,n)=>{let o=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(r)?JSON.stringify(r):r,i=await Cu(t,e,{method:"POST",body:o,signal:n==null?void 0:n.signal,headers:n==null?void 0:n.headers});return await vu(i),i},KS=async(t,e,r,n)=>{let s=await Cu(t,e,{method:"DELETE",body:JSON.stringify(r),headers:n==null?void 0:n.headers});return await vu(s),s},GS=async function*(t){var s;let e=new TextDecoder("utf-8"),r="",n=t.getReader();for(;;){let{done:o,value:i}=await n.read();if(o)break;r+=e.decode(i);let a=r.split(`
`);r=(s=a.pop())!=null?s:"";for(let c of a)try{yield JSON.parse(c)}catch(l){console.warn("invalid json: ",c)}}for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch(i){console.warn("invalid json: ",o)}},JS=t=>{if(!t)return em;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=Zp);let s="";r.username&&(s=r.username,r.password&&(s+=`:${r.password}`),s+="@");let o=`${r.protocol}//${s}${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},zS=Object.defineProperty,XS=(t,e,r)=>e in t?zS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xu=(t,e,r)=>(XS(t,typeof e!="symbol"?e+"":e,r),r),Pu=class{constructor(e){var r,n;xu(this,"config"),xu(this,"fetch"),xu(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=JS((r=e==null?void 0:e.host)!=null?r:em)),this.fetch=(n=e==null?void 0:e.fetch)!=null?n:fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){var o;r.stream=(o=r.stream)!=null?o:!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await ps(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let c=GS(a.body),l=new Au(i,c,()=>{let f=this.ongoingStreamedRequests.indexOf(l);f>-1&&this.ongoingStreamedRequests.splice(f,1)});return this.ongoingStreamedRequests.push(l),l}return await(await ps(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",s=r.byteLength;for(let o=0;o<s;o++)n+=String.fromCharCode(r[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 r of e.messages)r.images&&(r.images=await Promise.all(r.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 KS(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await ps(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Qp(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await ps(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await ps(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await ps(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Qp(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},CN=new Pu;var YS=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{baseURL:a,model:c,...l}=i,f=new Pu({host:a}),u=await f.chat({model:c,messages:e,stream:!0,...l});for await(let d of u){if(r.signal.aborted){f.abort();break}yield d.message.content}},La={name:"Ollama",defaultOptions:{apiKey:"",baseURL:"http://127.0.0.1:11434",model:"llama3.1",parameters:{}},sendRequestFunc:YS,models:[],websiteToObtainKey:"https://ollama.com",capabilities:["Text Generation"]};var QS=t=>async function*(e,r,n){var p,y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>ZS(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal});for await(let g of h){let S=(y=(p=g.choices[0])==null?void 0:p.delta)==null?void 0:y.content;S&&(yield S)}},ZS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>lt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},tm={name:"OpenAI",defaultOptions:{apiKey:"",baseURL:"https://api.openai.com/v1",model:"gpt-4.1",parameters:{}},sendRequestFunc:QS,models:[],websiteToObtainKey:"https://platform.openai.com/api-keys",capabilities:["Text Generation","Image Vision"]};var ex=t=>async function*(e,r,n){var S;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u=await Promise.all(e.map(_=>rx(_,n))),d={model:l,messages:u,stream:!0,...f},p=(S=(await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:r.signal})).body)==null?void 0:S.getReader();if(!p)throw new Error("Response body is not readable");let y=new TextDecoder,g="";try{for(;;){let{done:_,value:v}=await p.read();if(_)break;for(g+=y.decode(v,{stream:!0});;){let C=g.indexOf(`
`);if(C===-1)break;let x=g.slice(0,C).trim();if(g=g.slice(C+1),x.startsWith("data: ")){let P=x.slice(6);if(P==="[DONE]")break;try{let O=JSON.parse(P).choices[0].delta.content;O&&(yield O)}catch(k){}}}}}finally{p.cancel()}},tx=async(t,e)=>{let r=Or(t.link);if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)){let n=await e(t),s=Mr(n);return{type:"image_url",image_url:{url:`data:${r};base64,${s}`}}}else if(r==="application/pdf"){let n=await e(t),s=Mr(n);return{type:"file",file:{filename:t.link,file_data:`data:${r};base64,${s}`}}}else throw new Error(m("Only PNG, JPEG, GIF, WebP, and PDF files are supported."))},rx=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>tx(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},Na={name:"OpenRouter",defaultOptions:{apiKey:"",baseURL:"https://openrouter.ai/api/v1/chat/completions",model:"",parameters:{}},sendRequestFunc:ex,models:[],websiteToObtainKey:"https://openrouter.ai",capabilities:["Text Generation","Image Vision","PDF Vision"]};var Wr=require("obsidian");var nx=async(t,e)=>{if(!t||!e)throw new Error("Invalid API key secret");let r={grant_type:"client_credentials",client_id:t,client_secret:e},n=new URLSearchParams(r).toString(),o=(await(0,Wr.requestUrl)(`https://aip.baidubce.com/oauth/2.0/token?${n}`)).json;return{accessToken:o.access_token,exp:Date.now()+o.expires_in,apiKey:t,apiSecret:e}},sx=async(t,e,r)=>{let n=Date.now();if(t&&t.apiKey===e&&t.apiSecret===r&&t.exp>n+180*1e3)return{isValid:!0,token:t};let s=await nx(e,r);return console.debug("create new token",s),{isValid:!1,token:s}},ox=(t,e)=>{let r=e.endsWith(`
`)||e.endsWith("\r"),n=e.split(/\r\n|[\n\r]/g);return n.length===1&&!r?(t.push(n[0]),[]):(t.length>0&&(n=[t.join("")+n[0],...n.slice(1)],t=[]),r||(t=[n.pop()||""]),n)},ix=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,apiSecret:c,baseURL:l,model:f,token:u,...d}=i;if(!a)throw new Error(m("API key is required"));if(!c)throw new Error(m("API secret is required"));if(!f)throw new Error(m("Model is required"));let{token:h}=await sx(u,a,c);if(t.token=h,Wr.Platform.isDesktopApp){let p={messages:e,stream:!0,...d},y=await ar.post(l+`/${f}?access_token=${h.accessToken}`,p,{headers:{"Content-Type":"application/json"},adapter:"fetch",responseType:"stream",withCredentials:!1,signal:r.signal}),g=[],S=new TextDecoder("utf-8");for await(let _ of y.data){let v=S.decode(Buffer.from(_)),C=ox(g,v);for(let x of C)if(x.startsWith("data: ")){let P=x.slice(6),O=JSON.parse(P).result;O&&(yield O)}}}else{let p={messages:e,stream:!1,...d};new Wr.Notice(m("This is a non-streaming request, please wait..."),5*1e3);let y=await(0,Wr.requestUrl)({url:l+`/${f}?access_token=${h.accessToken}`,method:"POST",body:JSON.stringify(p),headers:{"Content-Type":"application/json"}});console.debug("response",y.json),yield y.json.result}},rm=["ernie-4.0-8k-latest","ernie-4.0-turbo-8k","ernie-3.5-128k","ernie_speed","ernie-speed-128k","gemma_7b_it","yi_34b_chat","mixtral_8x7b_instruct","llama_2_70b"],nm={name:"QianFan",defaultOptions:{apiKey:"",apiSecret:"",baseURL:"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat",model:rm[0],parameters:{}},sendRequestFunc:ix,models:rm,websiteToObtainKey:"https://qianfan.cloud.baidu.com",capabilities:["Text Generation"]};var ax=t=>async function*(e,r,n){var p,y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>lx(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal});for await(let g of h){let S=(y=(p=g.choices[0])==null?void 0:p.delta)==null?void 0:y.content;S&&(yield S)}},lx=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>lt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},sm=["qwen-turbo","qwen-plus","qwen-max","qwen-vl-max"],om={name:"Qwen",defaultOptions:{apiKey:"",baseURL:"https://dashscope.aliyuncs.com/compatible-mode/v1",model:sm[0],parameters:{}},sendRequestFunc:ax,models:sm,websiteToObtainKey:"https://dashscope.console.aliyun.com",capabilities:["Text Generation","Image Vision"]};var cx=t=>async function*(e,r,n){var y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>ux(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal}),p=!1;for await(let g of h){let S=(y=g.choices[0])==null?void 0:y.delta,_=S==null?void 0:S.reasoning_content;if(_)yield(p?"":(p=!0,Me))+_.replace(/\n/g,`
> `);else{let v=p?(p=!1,Le):"";S!=null&&S.content&&(yield v+(S==null?void 0:S.content))}}},ux=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>lt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},Da={name:"SiliconFlow",defaultOptions:{apiKey:"",baseURL:"https://api.siliconflow.cn/v1",model:"",parameters:{}},sendRequestFunc:cx,models:[],websiteToObtainKey:"https://siliconflow.cn",capabilities:["Text Generation","Image Vision","Reasoning"]};var ms=crypto,Ba=t=>t instanceof CryptoKey;var kt=new TextEncoder,No=new TextDecoder,zN=2**32;function im(...t){let e=t.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var fx=t=>{let e=t;typeof e=="string"&&(e=kt.encode(e));let r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));return btoa(n.join(""))},Fa=t=>fx(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),dx=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},qa=t=>{let e=t;e instanceof Uint8Array&&(e=No.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return dx(e)}catch(r){throw new TypeError("The input to be decoded is not correctly encoded.")}};var pe=class extends Error{constructor(e,r){var n;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};pe.code="ERR_JOSE_GENERIC";var Ru=class extends pe{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=s,this.payload=r}};Ru.code="ERR_JWT_CLAIM_VALIDATION_FAILED";var Tu=class extends pe{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=s,this.payload=r}};Tu.code="ERR_JWT_EXPIRED";var Iu=class extends pe{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}};Iu.code="ERR_JOSE_ALG_NOT_ALLOWED";var Fe=class extends pe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}};Fe.code="ERR_JOSE_NOT_SUPPORTED";var ku=class extends pe{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}};ku.code="ERR_JWE_DECRYPTION_FAILED";var Ou=class extends pe{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}};Ou.code="ERR_JWE_INVALID";var Ot=class extends pe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}};Ot.code="ERR_JWS_INVALID";var Do=class extends pe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}};Do.code="ERR_JWT_INVALID";var Mu=class extends pe{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}};Mu.code="ERR_JWK_INVALID";var Lu=class extends pe{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}};Lu.code="ERR_JWKS_INVALID";var Nu=class extends pe{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}};Nu.code="ERR_JWKS_NO_MATCHING_KEY";var Du=class extends pe{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Du.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";var Bu=class extends pe{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}};Bu.code="ERR_JWKS_TIMEOUT";var Fu=class extends pe{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};Fu.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function Mt(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function Ua(t,e){return t.name===e}function qu(t){return parseInt(t.name.slice(4),10)}function hx(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function px(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function am(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ua(t.algorithm,"HMAC"))throw Mt("HMAC");let n=parseInt(e.slice(2),10);if(qu(t.algorithm.hash)!==n)throw Mt(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ua(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Mt("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(qu(t.algorithm.hash)!==n)throw Mt(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ua(t.algorithm,"RSA-PSS"))throw Mt("RSA-PSS");let n=parseInt(e.slice(2),10);if(qu(t.algorithm.hash)!==n)throw Mt(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw Mt("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!Ua(t.algorithm,"ECDSA"))throw Mt("ECDSA");let n=hx(e);if(t.algorithm.namedCurve!==n)throw Mt(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}px(t,r)}function lm(t,e,...r){var n;if(r=r.filter(Boolean),r.length>2){let s=r.pop();t+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(n=e.constructor)!=null&&n.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Uu=(t,...e)=>lm("Key must be ",t,...e);function $u(t,e,...r){return lm(`Key for the ${t} algorithm must be `,e,...r)}var Hu=t=>Ba(t)?!0:(t==null?void 0:t[Symbol.toStringTag])==="KeyObject",gs=["CryptoKey"];var mx=(...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},cm=mx;function gx(t){return typeof t=="object"&&t!==null}function Bo(t){if(!gx(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var um=(t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}};function Vr(t){return Bo(t)&&typeof t.kty=="string"}function fm(t){return t.kty!=="oct"&&typeof t.d=="string"}function dm(t){return t.kty!=="oct"&&typeof t.d=="undefined"}function hm(t){return Vr(t)&&t.kty==="oct"&&typeof t.k=="string"}function bx(t){let e,r;switch(t.kty){case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new Fe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var wx=async t=>{var o,i;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=bx(t),n=[e,(o=t.ext)!=null?o:!1,(i=t.key_ops)!=null?i:r],s={...t};return delete s.alg,delete s.use,ms.subtle.importKey("jwk",s,...n)},pm=wx;var mm=t=>qa(t),ys,bs,gm=t=>(t==null?void 0:t[Symbol.toStringTag])==="KeyObject",$a=async(t,e,r,n,s=!1)=>{let o=t.get(e);if(o!=null&&o[n])return o[n];let i=await pm({...r,alg:n});return s&&Object.freeze(e),o?o[n]=i:t.set(e,{[n]:i}),i},_x=(t,e)=>{if(gm(t)){let r=t.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?mm(r.k):(bs||(bs=new WeakMap),$a(bs,t,r,e))}return Vr(t)?t.k?qa(t.k):(bs||(bs=new WeakMap),$a(bs,t,t,e,!0)):t},Sx=(t,e)=>{if(gm(t)){let r=t.export({format:"jwk"});return r.k?mm(r.k):(ys||(ys=new WeakMap),$a(ys,t,r,e))}return Vr(t)?t.k?qa(t.k):(ys||(ys=new WeakMap),$a(ys,t,t,e,!0)):t},ju={normalizePublicKey:_x,normalizePrivateKey:Sx};var ws=t=>t==null?void 0:t[Symbol.toStringTag],Wu=(t,e,r)=>{var n,s;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((s=(n=e.key_ops).includes)==null?void 0:s.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},xx=(t,e,r,n)=>{if(!(e instanceof Uint8Array)){if(n&&Vr(e)){if(hm(e)&&Wu(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Hu(e))throw new TypeError($u(t,e,...gs,"Uint8Array",n?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ws(e)} instances for symmetric algorithms must be of type "secret"`)}},Ex=(t,e,r,n)=>{if(n&&Vr(e))switch(r){case"sign":if(fm(e)&&Wu(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(dm(e)&&Wu(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Hu(e))throw new TypeError($u(t,e,...gs,n?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ws(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ws(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ws(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ws(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ws(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function ym(t,e,r,n){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?xx(e,r,n,t):Ex(e,r,n,t)}var y3=ym.bind(void 0,!1),bm=ym.bind(void 0,!0);function Ax(t,e,r,n,s){if(s.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(let i of n.crit){if(!o.has(i))throw new Fe(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var wm=Ax;function Vu(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new Fe(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Ku(t,e,r){if(r==="sign"&&(e=await ju.normalizePrivateKey(e,t)),r==="verify"&&(e=await ju.normalizePublicKey(e,t)),Ba(e))return am(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Uu(e,...gs));return ms.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Uu(e,...gs,"Uint8Array","JSON Web Key"))}var lr=t=>Math.floor(t.getTime()/1e3);var vx=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ha=t=>{let e=vx.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return e[1]==="-"||e[4]==="ago"?-s:s};var Cx=async(t,e,r)=>{let n=await Ku(t,e,"sign");um(t,n);let s=await ms.subtle.sign(Vu(t,n.algorithm),n,r);return new Uint8Array(s)},_m=Cx;var ja=class{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Ot("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!cm(this._protectedHeader,this._unprotectedHeader))throw new Ot("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=wm(Ot,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new Ot('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new Ot('JWS "alg" (Algorithm) Header Parameter missing or invalid');bm(i,e,"sign");let a=this._payload;o&&(a=kt.encode(Fa(a)));let c;this._protectedHeader?c=kt.encode(Fa(JSON.stringify(this._protectedHeader))):c=kt.encode("");let l=im(c,kt.encode("."),a),f=await _m(i,e,l),u={signature:Fa(f),payload:""};return o&&(u.payload=No.decode(a)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=No.decode(c)),u}};var Wa=class{constructor(e){this._flattened=new ja(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function Kr(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Va=class{constructor(e={}){if(!Bo(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:Kr("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Kr("setNotBefore",lr(e))}:this._payload={...this._payload,nbf:lr(new Date)+Ha(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:Kr("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Kr("setExpirationTime",lr(e))}:this._payload={...this._payload,exp:lr(new Date)+Ha(e)},this}setIssuedAt(e){return typeof e=="undefined"?this._payload={...this._payload,iat:lr(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Kr("setIssuedAt",lr(e))}:typeof e=="string"?this._payload={...this._payload,iat:Kr("setIssuedAt",lr(new Date)+Ha(e))}:this._payload={...this._payload,iat:Kr("setIssuedAt",e)},this}};var Fo=class extends Va{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var s;let n=new Wa(kt.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((s=this._protectedHeader)==null?void 0:s.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Do("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}};var Rx=t=>async function*(e,r,n){var _,v;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,token:f,tokenExpireInMinutes:u,enableWebSearch:d,...h}=i;if(!a)throw new Error(m("API key is required"));console.debug("zhipu options",{baseURL:c,apiKey:a,model:l,currentToken:f,tokenExpireInMinutes:u,enableWebSearch:d});let{token:p}=await Ix(f,a,u);t.token=p;let y=new D({apiKey:p.id,baseURL:c,dangerouslyAllowBrowser:!0}),g=d?[{type:"web_search",web_search:{enable:!0}}]:[],S=await y.chat.completions.create({model:l,messages:e,stream:!0,tools:g,...h},{signal:r.signal});for await(let C of S){let x=(v=(_=C.choices[0])==null?void 0:_.delta)==null?void 0:v.content;x&&(yield x)}},Tx=async(t,e)=>{let[r,n]=t.split(".");if(!r||!n)throw new Error('Invalid API key secret, must be in the format "apiKey.apiSecret"');let s=Date.now(),o={api_key:r,exp:s+e*60*1e3,timestamp:s};return{id:await new Fo({...o}).setProtectedHeader({alg:"HS256",sign_type:"SIGN"}).sign(new TextEncoder().encode(n)),exp:o.exp,apiKeySecret:t}},Ix=async(t,e,r)=>{let n=Date.now();if(t&&t.apiKeySecret===e&&t.exp>n+180*1e3)return{isValid:!0,token:t};let s=await Tx(e,r);return console.debug("create new token",s),{isValid:!1,token:s}},Sm=["glm-4-plus","glm-4-air","glm-4-airx","glm-4-long","glm-4-flash","glm-4-flashx"],xm={name:"Zhipu",defaultOptions:{apiKey:"",baseURL:"https://open.bigmodel.cn/api/paas/v4/",model:Sm[0],tokenExpireInMinutes:1440,enableWebSearch:!1,parameters:{}},sendRequestFunc:Rx,models:Sm,websiteToObtainKey:"https://open.bigmodel.cn/",capabilities:["Text Generation","Web Search"]};var qe="Tars",mt={editorStatus:{isTextInserting:!1},providers:[],systemTags:["System","\u7CFB\u7EDF"],newChatTags:["NewChat","\u65B0\u5BF9\u8BDD"],userTags:["User","\u6211"],roleEmojis:{assistant:"\u2728",system:"\u{1F527}",newChat:"\u{1F680}",user:"\u{1F4AC}"},promptTemplates:[],enableInternalLink:!0,enableInternalLinkForAssistantMsg:!1,answerDelayInMilliseconds:2e3,confirmRegenerate:!0,enableTagSuggest:!0,tagSuggestMaxLineLength:20,enableExportToJSONL:!1,enableReplaceTag:!1,enableDefaultSystemMsg:!1,defaultSystemMsg:"",enableStreamLog:!1},qo=[tm,sh,la,Uh,$h,ap,ma,Oa,Ma,La,Na,nm,om,Da,xm];var Am=(t,e)=>async function*(r,n,s,o){let i=Date.now(),a=[];try{for await(let c of t(r,n,s,o)){let l=Date.now();a.push({text:c,time:l-i}),yield c}}finally{let c=r[r.length-1],l=/[<>:"/\\|?*\u0000-\u001F\u007F-\u009F]/g,f=c.content.slice(0,20).replace(l,"").trim()||"untitled",u=(0,Em.normalizePath)(`${qe}/${kx(new Date)}-${f}.json`),d={lastMsg:r[r.length-1].content.trim(),createdAt:new Date().toISOString(),texts:a};await e(u,JSON.stringify(d,null,2)),console.debug("Response logged to:",u)}},kx=t=>{let e=a=>a.toString().padStart(2,"0"),r=t.getFullYear().toString().slice(-2),n=e(t.getMonth()+1),s=e(t.getDate()),o=e(t.getHours()),i=e(t.getMinutes());return`${r}${n}${s}-${o}${i}`};var vm=["callout"],Xe=async(t,e)=>{var p,y;let r=t.workspace.getActiveFile();if(!r)throw new Error("No active file");let n=t.metadataCache,s=t.vault,o=await s.cachedRead(r),i=r.path,a=n.getFileCache(r);if(!a)throw new Error(m("Waiting for metadata to be ready. Please try again."));let c=((p=a.sections)==null?void 0:p.filter(g=>vm.includes(g.type)))||[],l=(a.tags||[]).filter(g=>!c.some(S=>S.position.start.offset<=g.position.start.offset&&g.position.end.offset<=S.position.end.offset)),f={newChatTags:e.newChatTags,userTags:e.userTags,assistantTags:e.providers.map(g=>g.tag),systemTags:e.systemTags,enableInternalLink:e.enableInternalLink,enableInternalLinkForAssistantMsg:e.enableInternalLinkForAssistantMsg,enableDefaultSystemMsg:e.enableDefaultSystemMsg,defaultSystemMsg:e.defaultSystemMsg,enableStreamLog:e.enableStreamLog},u=async(g,S)=>{let _=await t.fileManager.getAvailablePathForAttachment(g);await s.createBinary(_,S)},d=async g=>{let{path:S,subpath:_}=(0,ze.parseLinktext)(g.link);console.debug("resolveEmbed path",S,"subpath",_);let v=n.getFirstLinkpathDest(S,i);if(v===null)throw new Error("LinkText broken: "+g.link.substring(0,20));return await s.readBinary(v)},h=async(g,S)=>{await s.create(g,S)};return{appMeta:n,vault:s,fileText:o,filePath:i,tags:l,sections:((y=a.sections)==null?void 0:y.filter(g=>!vm.includes(g.type)))||[],links:a.links,embeds:a.embeds,options:f,saveAttachment:u,resolveEmbed:d,createPlainText:h}},Ox=async(t,e)=>{let{appMeta:r,vault:n,filePath:s}=t,{path:o,subpath:i}=(0,ze.parseLinktext)(e);console.debug("path",o,"subpath",i);let a=r.getFirstLinkpathDest(o,s);if(a===null)throw new Error("LinkText broken: "+e.substring(0,20));let c=r.getFileCache(a);if(c===null)throw new Error(`No metadata found: ${o} ${i}`);let l=await n.cachedRead(a);if(i){let f=(0,ze.resolveSubpath)(c,i);if(f===null)throw new Error(`no subpath data found: ${i}`);return l.substring(f.start.offset,f.end?f.end.offset:void 0)}else return l},Cm=(t,e,r)=>{let{tags:n,sections:s,options:{userTags:o,assistantTags:i,systemTags:a}}=t,c=n.filter(u=>e<=u.position.start.offset&&u.position.end.offset<=r).map(u=>{let d=u.tag.slice(1).split("/")[0].toLowerCase(),h=o.some(p=>p.toLowerCase()===d)?"user":i.some(p=>p.toLowerCase()===d)?"assistant":a.some(p=>p.toLowerCase()===d)?"system":null;return h!=null?{tag:u.tag,role:h,lowerCaseTag:d,tagRange:[u.position.start.offset,u.position.end.offset],tagLine:u.position.start.line}:null}).filter(u=>u!==null);console.debug("roleMappedTags",c);let f=c.map((u,d)=>[u.tagRange[0],c[d+1]?c[d+1].tagRange[0]-1:r]).map((u,d)=>({...c[d],contentRange:[c[d].tagRange[1]+2,c[d+1]?c[d+1].tagRange[0]-1:r],sections:s.filter(h=>h.position.end.offset<=u[1]&&(h.position.start.offset<u[0]?h.position.end.offset>u[0]:!0)),line:[c[d].tagLine,c[d+1]?c[d+1].tagLine-1:1/0]}));return console.debug("taggedBlocks",f),f},Mx=async(t,e,r,n)=>{let{fileText:s,links:o=[],embeds:i=[],options:{enableInternalLink:a,enableInternalLinkForAssistantMsg:c}}=t,l=e.position.start.offset<=r[0]?r[0]:e.position.start.offset,f=e.position.end.offset,u=o.map(_=>({ref:_,type:"link"})),d=i.map(_=>({ref:_,type:"embed"})),p=[...u,...d].sort((_,v)=>_.ref.position.start.offset-v.ref.position.start.offset).filter(_=>l<=_.ref.position.start.offset&&_.ref.position.end.offset<=f),y=n==="assistant"?c:a,S=(await Promise.all(p.map(async _=>{let v=_.ref;return _.type==="link"?{referCache:v,text:y?await Ox(t,v.link):v.original}:{referCache:v,text:""}}))).reduce((_,{referCache:v,text:C})=>({endOffset:v.position.end.offset,text:_.text+s.slice(_.endOffset,v.position.start.offset)+C}),{endOffset:l,text:""});return console.debug("accumulatedText",S),{text:S.text+s.slice(S.endOffset,f),range:[l,f]}},Pm=async(t,e)=>{let r=await Promise.all(e.sections.map(s=>Mx(t,s,e.contentRange,e.role)));return console.debug("textRanges",r),r.map(s=>s.text).join(`
`).trim()},Lx=(t,e)=>{var r;return(r=t.embeds)==null?void 0:r.filter(n=>e[0]<=n.position.start.offset&&n.position.end.offset<=e[1])},Nx=async(t,e,r)=>{let{tags:n,options:{newChatTags:s}}=t,o=n.findLast(l=>s.some(f=>l.tag.slice(1).split("/")[0].toLowerCase()===f.toLowerCase())&&e<=l.position.start.offset&&l.position.end.offset<=r),i=o?o.position.end.offset:e,a=Cm(t,i,r);return await Promise.all(a.map(async l=>{let f={...l,content:await Pm(t,l)},u=Lx(t,l.contentRange);return u&&u.length>0&&(f.embeds=u),f}))},Dx=(0,ze.debounce)(t=>{t.isTextInserting=!1},1e3,!0),Bx=(t,e,r,n)=>{r.isTextInserting=!0;let s=t.getCursor("to");n!==null&&(n.line!==s.line||n.ch!==s.ch)&&(s=n);let o=t.getLine(s.line);o.length>s.ch&&(s={line:s.line,ch:o.length});let i=e.split(`
`),a={line:s.line+i.length-1,ch:i.length===1?s.ch+e.length:i[i.length-1].length};return t.replaceRange(e,s),t.setCursor(a),Dx(r),a},Rm=async t=>{let{tags:e,options:{newChatTags:r}}=t,o=[0,...e.filter(c=>r.some(l=>c.tag.slice(1).split("/")[0].toLowerCase()===l.toLowerCase())).flatMap(c=>[c.position.start.offset-1,c.position.end.offset+1]),1/0],i=o.filter((c,l)=>l%2===0).map((c,l)=>({startOffset:c,endOffset:o[l*2+1]}));return console.debug("ranges",i),(await Promise.all(i.map(async c=>{let l=Cm(t,c.startOffset,c.endOffset);return Promise.all(l.map(async u=>({...u,content:await Pm(t,u)})))}))).filter(c=>c.length>0)},Tm=(t,e)=>{let{tags:r,sections:n,options:{systemTags:s,userTags:o,assistantTags:i}}=t,a=[...s,...o,...i],c=r.filter(y=>a.some(g=>y.tag.slice(1).split("/")[0].toLowerCase()===g.toLowerCase()));console.debug("msgTagsInMeta",c);let l=c.findLastIndex(y=>y.position.start.line<=e);if(l<0)return[-1,-1];console.debug("msgTag",c[l]);let f=c[l].position.end.offset+2,u=l+1,d=u<c.length?c[u].position.start.offset:1/0;console.debug("nextTag",c[u]);let h=n.findLast(y=>y.position.end.offset<=d&&y.position.start.line>=e);if(!h)return[-1,-1];let p=h.position.end.offset;return console.debug("startOff",f,"endOffset",p),[f,p]},Fx=t=>`${(t/1e3).toFixed(2)}s`,qx=async(t,e,r)=>t.options.enableStreamLog?(await t.vault.adapter.exists((0,ze.normalizePath)(qe))||await t.vault.createFolder(qe),console.debug("Using stream logging"),Am(e.sendRequestFunc(r.options),t.createPlainText)):e.sendRequestFunc(r.options),Gr=async(t,e,r,n,s,o,i)=>{var a;try{let c=qo.find(P=>P.name===r.vendor);if(!c)throw new Error("No vendor found "+r.vendor);let f=(await Nx(t,0,n)).map(P=>P.embeds?{role:P.role,content:P.content,embeds:P.embeds}:{role:P.role,content:P.content});console.debug("messages",f);let u=f.last();if(!u||u.role!=="user"||u.content.trim().length===0)throw new Error(m("Please add a user message first, or wait for the user message to be parsed."));t.options.enableDefaultSystemMsg&&((a=f[0])==null?void 0:a.role)!=="system"&&t.options.defaultSystemMsg&&(f.unshift({role:"system",content:t.options.defaultSystemMsg}),console.debug("Default system message added:",t.options.defaultSystemMsg));let d=f.filter(P=>P.role==="assistant").length+1,h=await qx(t,c,r),p=new Date;s.setGeneratingStatus(d);let y="",g=i.getController(),S=null,_=null;for await(let P of h(f,g,t.resolveEmbed,t.saveAttachment))_==null&&(_=e.getCursor("to")),S=Bx(e,P,o,S),y+=P,s.updateGeneratingProgress(y.length);let v=new Date,C=Fx(v.getTime()-p.getTime()),x={round:d,characters:y.length,duration:C,model:r.options.model,vendor:r.vendor,startTime:p,endTime:v};if(s.setSuccessStatus(x),y.length===0)throw new Error(m("No text generated"));if(console.debug("\u2728 "+m("AI generate")+" \u2728 ",y),_){let P=e.getCursor("to"),k=e.getRange(_,P),O=Ux(y);k!==O&&(console.debug("format text with leading breaks"),e.replaceRange(O,_,P))}if(g.signal.aborted)throw new DOMException("Operation was aborted","AbortError");new ze.Notice(m("Text generated successfully"))}finally{i.cleanup()}},Ux=t=>{let e=t.split(`
`)[0];return e.startsWith("#")||e.startsWith("```")?`
`+t:e.startsWith("| ")?`
`+t:t};var Jr=require("obsidian");var gt=t=>`#${t} : `,Uo=t=>`#${t} `,$x=(t,e,r=!1)=>r?`
#${e}`:t==="newChat"?Uo(e):gt(e),Hx=[" "," "," :"," \uFF1A"],Im=t=>{let e=Math.max(0,...t.newChatTags.map(n=>n.length)),r=Math.max(0,...t.systemTags.map(n=>n.length),...t.userTags.map(n=>n.length),...t.providers.map(n=>n.tag.length));return 4+(e+1)+(r+2)},jx=t=>{let e=[],r=/[^\s#::]+/g,n;for(let s=0;s<3&&(n=r.exec(t),!!n);s++)e.push(n[0]);return e},Wx=(t,e)=>t.line>=1&&e.getLine(t.line-1).trim().length>0,Ka=class extends Jr.EditorSuggest{constructor(e,r,n,s,o){super(e),this.app=e,this.settings=r,this.tagLowerCaseMap=n,this.statusBarManager=s,this.requestController=o}onTrigger(e,r,n){if(this.settings.editorStatus.isTextInserting||e.ch<1||e.ch>this.settings.tagSuggestMaxLineLength)return null;let s=r.getLine(e.line);if(s.length>e.ch)return null;let o=jx(s);if(o.length===0||o.length>=3)return null;let i=this.tagLowerCaseMap.get(o[0].toLowerCase());if(!i)return null;let a;if(o.length===2&&(a=this.tagLowerCaseMap.get(o[1].toLowerCase()),!a||i.role!=="newChat"))return null;let c=a||i,l=o.length===2?o[1]:o[0],f=s.indexOf(l),u=s.slice(f+l.length);if(u){if(c.role==="newChat")return null;if(!Hx.includes(u))return null}let d=Wx(e,r);return{start:{line:e.line,ch:f>0&&s[f-1]==="#"?f-1:f},end:{line:e.line,ch:e.ch},query:JSON.stringify({...c,replacement:$x(c.role,c.tag,d)})}}async getSuggestions(e){return[JSON.parse(e.query)]}renderSuggestion(e,r){if(e.replacement.includes(`
`)){r.createSpan({text:e.replacement});return}let n=this.settings.roleEmojis.assistant;switch(e.role){case"assistant":{r.createSpan({text:`${e.replacement} ${n} ${m("AI generate")} ${n} `});break}case"user":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.user} `});break}case"system":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.system} `});break}case"newChat":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.newChat} `});break}default:r.createSpan({text:e.replacement})}}async selectSuggestion(e,r){if(!this.context)return;let n=this.context.editor;if(n.replaceRange(e.replacement,this.context.start,this.context.end),e.role!=="assistant"||e.replacement.includes(`
`)){this.close();return}console.debug("element",e);try{let s=this.settings.providers.find(a=>a.tag===e.tag);if(!s)throw new Error("No provider found "+e.tag);let o=await Xe(this.app,this.settings),i=n.posToOffset(this.context.start);console.debug("endOffset",i),await Gr(o,n,s,i,this.statusBarManager,this.settings.editorStatus,this.requestController)}catch(s){if(console.error("error",s),s.name==="AbortError"){this.statusBarManager.setCancelledStatus(),new Jr.Notice(m("Generation cancelled"));return}this.statusBarManager.setErrorStatus(s),new Jr.Notice(`\u{1F534} ${Jr.Platform.isDesktopApp?m("Click status bar for error details. "):""}${s}`,10*1e3)}this.close()}};var Gu=`
`,Vx=t=>{let e=t.listSelections();if(e.length===0)throw new Error("No selection");if(e.length>1)throw new Error("Multiple selections");return e[0]},_s=(t,e,r)=>{let n=Ju(t,e);return Kx(t,e,n,r)},Ju=(t,e)=>{let r=Vx(e);console.debug("anchor",r.anchor),console.debug("head",r.head);let n=e.getCursor(),{sections:s}=Om(t);if(!s)return console.debug("No sections"),{from:{line:n.line,ch:0},to:{line:n.line,ch:e.getLine(n.line).length}};let o=e.posToOffset(r.anchor),i=e.posToOffset(r.head),[a,c]=o<i?[o,i]:[i,o],l=s.filter(f=>a<=f.position.end.offset&&f.position.start.offset<=c);return l.length===0?(console.debug("No overlapping sections"),{from:{line:n.line,ch:0},to:{line:n.line,ch:e.getLine(n.line).length}}):{from:{line:l[0].position.start.line,ch:l[0].position.start.col},to:{line:l[l.length-1].position.end.line,ch:l[l.length-1].position.end.col}}},Ss=(t,e)=>{let{from:r,to:n}=e;return t.getRange(r,n).trim().length===0},xs=(t,e,r)=>{let n=e.line,s="";return e.line>0&&t.getLine(e.line-1).trim().length>0?(s=`
`+r,n+=1):s=r,t.replaceRange(s,e,e),t.setSelection({line:n,ch:t.getLine(n).length}),n},Es=(t,e,r)=>{let{from:n,to:s}=e,o="",i=s.line;n.line>0&&t.getLine(n.line-1).trim().length>0&&n.ch===0?(o=`
`+r,i+=1):o=r,t.replaceRange(o,n,n),t.setSelection({line:i,ch:t.getLine(i).length})},Ga=(t,e,r,n)=>{let{to:s}=e;r&&(t.replaceRange("#"+n,r.from,r.to),t.setSelection({line:s.line,ch:t.getLine(s.line).length}))},Kx=(t,e,r,n)=>{let{tags:s}=Om(t);if(!s)return{tagContent:null,role:null,range:r,tagRange:null};let{from:o,to:i}=r,a=s.find(c=>e.posToOffset(o)<=c.position.start.offset&&c.position.end.offset<=e.posToOffset(i));if(a){let c=n.userTags,l=n.providers.map(p=>p.tag),f=n.systemTags,u=n.newChatTags,d=a.tag.slice(1).split("/")[0].toLowerCase();if(u.some(p=>p.toLowerCase()===d)){let p=s.find(y=>a.position.end.offset<=y.position.start.offset&&y.position.end.offset<=e.posToOffset(i));return p?{tagContent:p.tag.slice(1),role:km(p,{userTags:c,assistantTags:l,systemTags:f,newChatTags:u}),range:{from:e.offsetToPos(a.position.end.offset+1),to:r.to},tagRange:{from:e.offsetToPos(p.position.start.offset),to:e.offsetToPos(p.position.end.offset)}}:{tagContent:a.tag.slice(1),role:null,range:{from:e.offsetToPos(a.position.end.offset+1),to:r.to},tagRange:{from:e.offsetToPos(a.position.start.offset),to:e.offsetToPos(a.position.end.offset)}}}return{tagContent:a.tag.slice(1),role:km(a,{userTags:c,assistantTags:l,systemTags:f,newChatTags:u}),range:r,tagRange:{from:e.offsetToPos(a.position.start.offset),to:e.offsetToPos(a.position.end.offset)}}}else return{tagContent:null,role:null,range:r,tagRange:null}},km=(t,e)=>{let{userTags:r,assistantTags:n,systemTags:s,newChatTags:o}=e,i=t.tag.slice(1).split("/")[0].toLowerCase();return r.some(c=>c.toLowerCase()===i)?"user":n.some(c=>c.toLowerCase()===i)?"assistant":s.some(c=>c.toLowerCase()===i)?"system":o.some(c=>c.toLowerCase()===i)?"newChat":null},Om=t=>{let e=t.workspace.getActiveFile();if(!e)throw new Error("No active file");let r=t.metadataCache.getFileCache(e);if(!r)throw new Error(m("Waiting for metadata to be ready. Please try again."));let n=r.tags;return{sections:r.sections,tags:n}},$o=(t,e)=>{let r=t.getCursor("to"),n=e.split(`
`),s={line:r.line+n.length-1,ch:n.length===1?r.ch+e.length:n[n.length-1].length};return t.replaceRange(e,r),t.setCursor(s),s.line};var Xu=({id:t,name:e,tag:r},n,s,o,i)=>({id:t,name:e,editorCallback:async(a,c)=>{try{let l=s.providers.find(g=>g.tag===r);if(!l){new yt.Notice(`Assistant ${r} not found`);return}let f=gt(s.userTags[0]),u=gt(r),{range:d,role:h,tagContent:p,tagRange:y}=_s(n,a,s);if(console.debug("asstTagCmd",{range:d,role:h,tagContent:p,tagRange:y}),Ss(a,d)){let g=xs(a,d.from,u),S=a.posToOffset({line:g,ch:0}),_=await Xe(n,s);await Gr(_,a,l,S,o,s.editorStatus,i);return}if(h===null){Es(a,d,f),a.setCursor({line:d.to.line,ch:a.getLine(d.to.line).length}),$o(a,Gu+`
`);let g=await Gx(a,u,s.answerDelayInMilliseconds),S=a.posToOffset({line:g,ch:0}),_=await Xe(n,s);await Gr(_,a,l,S,o,s.editorStatus,i)}else if(h==="assistant")if(s.confirmRegenerate){let g=async()=>{await Mm(n,s,o,i,a,l,d,u)};new zu(n,g).open()}else await Mm(n,s,o,i,a,l,d,u);else{a.setCursor({line:d.to.line,ch:a.getLine(d.to.line).length});let g=$o(a,Gu+`
`+u),S=a.posToOffset({line:g,ch:0}),_=await Xe(n,s);await Gr(_,a,l,S,o,s.editorStatus,i)}}catch(l){if(console.error(l),l.name==="AbortError"){o.setCancelledStatus(),new yt.Notice(m("Generation cancelled"));return}o.setErrorStatus(l),new yt.Notice(`\u{1F534} ${yt.Platform.isDesktopApp?m("Click status bar for error details. "):""}${l}`,10*1e3)}}}),Mm=async(t,e,r,n,s,o,i,a)=>{s.replaceRange(a,i.from,i.to),s.setCursor({line:i.from.line,ch:s.getLine(i.from.line).length});let c=s.posToOffset({line:i.from.line,ch:0}),l=await Xe(t,e);await Gr(l,s,o,c,r,e.editorStatus,n)},zu=class extends yt.Modal{constructor(e,r){super(e),this.onConfirm=r}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:m("Regenerate?")}),e.createEl("p",{text:m("This will delete the current response content. You can configure this in settings to not require confirmation.")}),new yt.Setting(e).addButton(r=>r.setButtonText(m("Yes")).setCta().onClick(async()=>{this.close(),await this.onConfirm()}))}},Gx=async(t,e,r)=>{let n=e.length-2;if(n<=0)throw new Error("mark length must be greater than 2");let s=Math.round(r/n),o=$o(t,e[0]+e[1]);for(let i=2;i<e.length;i++)await new Promise(a=>setTimeout(a,s)),o=$o(t,e[i]);return o};var As=require("obsidian");var Ja="export-to-jsonl",Ho=(t,e)=>({id:Ja,name:m("Export conversations to JSONL"),callback:async()=>{await Jx(t,e)}}),Jx=async(t,e)=>{var f,u,d;let r=await Xe(t,e),n=await Rm(r);console.debug("conversations",n);let s=[];try{s=n.map(zx)}catch(h){console.error("error",h),new As.Notice(`\u{1F534}${m("Error")}: ${h}`,10*1e3);return}if(s.length===0){new As.Notice(m("No conversation found"));return}let o=s.map(h=>JSON.stringify(h)).join(`
`),i=(u=(f=t.workspace.getActiveFile())==null?void 0:f.parent)==null?void 0:u.path,a=(d=t.workspace.getActiveFile())==null?void 0:d.basename,c=(0,As.normalizePath)(`${i}/${a}.jsonl`),l=t.vault.getFileByPath(c);l?await t.vault.process(l,h=>o):await t.vault.create(c,o),new As.Notice(m("Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software."),5*1e3)},zx=t=>{var c,l;let e=t.slice();if(e.length<2)throw new Error("No conversation");let r=null;((c=e.first())==null?void 0:c.role)==="system"&&(r=(l=e.shift())==null?void 0:l.content);let n=[];for(;e.length>0;){let f=e.shift(),u=e.shift();if((f==null?void 0:f.role)!=="user"||(u==null?void 0:u.role)!=="assistant")throw new Error("Invalid message role");if((f==null?void 0:f.content.trim().length)===0||(u==null?void 0:u.content.trim().length)===0)throw new Error("Empty message content");n.push([f.content,u.content])}let s=n.pop();if(!s)throw new Error("No conversation");let[o,i]=s,a={system:r,query:o,response:i,history:n.length>0?n:null};return Object.fromEntries(Object.entries(a).filter(([f,u])=>u!=null))};var za=require("obsidian");var Yu=({id:t,name:e,tag:r})=>({id:t,name:e,editorCallback:async(n,s)=>{try{let o=n.getCursor(),i=Uo(r);n.replaceRange(i,o),n.setCursor(o.line,o.ch+i.length)}catch(o){console.error(o),new za.Notice(`\u{1F534} ${za.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${o}`,10*1e3)}}});var zr=require("obsidian");var Xa="replace-tag",jo=t=>({id:Xa,name:m("Replace speaker with tag"),callback:async()=>{let e=t.workspace.getActiveFile();if(!e)return;let r=await t.vault.cachedRead(e),n=Qx(r);if(n.length<1){new zr.Notice(m("No speaker found"));return}console.debug("twoMostFrequentSpeakers",n);let s=n.map(o=>({original:o.name,count:o.count,newTag:Xx(o.name)}));new Qu(t,s,async o=>{await t.vault.process(e,i=>Zx(i,o))}).open()}}),Xx=t=>t.trim().startsWith("#")?t:"#"+t.trim().replace(/\s(?!:)/g,"-"),Qu=class extends zr.Modal{constructor(e,r,n){super(e),this.recommendTags=r,this.onSubmit=n}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:m("Replace speaker with tag")}),e.createEl("p",{text:m("Replace the names of the two most frequently occurring speakers with tag format.")});for(let r of this.recommendTags)new zr.Setting(e).setName(r.original+` (${r.count})`).addText(n=>n.setPlaceholder(r.newTag).setValue(r.newTag).onChange(async s=>{r.newTag=s}));new zr.Setting(e).addButton(r=>r.setButtonText(m("Replace")).setCta().onClick(async()=>{this.close(),await this.onSubmit(this.recommendTags)}))}},Yx=t=>t.reduce((e,r)=>(e[r]=(e[r]||0)+1,e),{}),Qx=t=>{let r=t.split(`
`).map(a=>a.match(/^([\u4e00-\u9fa5a-zA-Z0-9# ]+)([:|:]) /g)).flatMap(a=>a||[]);console.debug("allMatches",r);let n=Yx(r),s=Object.entries(n).sort((a,c)=>c[1]-a[1]);console.debug("sortedMatchFrequencies",s);let[o,i]=s.slice(0,2);return!o||!i?[]:[{name:o[0],count:o[1]},{name:i[0],count:i[1]}]},Zx=(t,e)=>(e.forEach(({original:r,newTag:n})=>{t=t.replace(new RegExp(`^${r}`,"g"),`${n}`).replace(new RegExp(`
${r}`,"g"),`
${n}`)}),t);var Lm=require("obsidian");var Zu=(t,e)=>({id:"select-message-at-cursor",name:m("Select message at cursor"),editorCallback:async(r,n)=>{let s=await Xe(t,e),o=r.getCursor("to").line,[i,a]=Tm(s,o);if(i===-1||a===-1){new Lm.Notice(m("No message found at cursor"));return}r.setSelection(r.offsetToPos(i),r.offsetToPos(a))}});var Wo=require("obsidian");var ef=({id:t,name:e,tag:r},n,s)=>({id:t,name:e,editorCallback:async(o,i)=>{try{let a=gt(r),{range:c,role:l,tagContent:f,tagRange:u}=_s(n,o,s);if(console.debug("systemTagCmd",{range:c,role:l,tagContent:f,tagRange:u}),Ss(o,c))return xs(o,c.from,a);if(l===null)return Es(o,c,a);if(l==="system"){if(r!==f&&u)return Ga(o,c,u,r)}else o.setSelection(c.from,c.to),new Wo.Notice(`${m("Conversion failed. Selected sections is a")} ${m(l)} ${m("message")}`)}catch(a){console.error(a),new Wo.Notice(`\u{1F534} ${Wo.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${a}`,10*1e3)}}});var Ya=(t,e)=>`${t}#${e}`,eE=t=>{let[e,r]=t.split("#");return{type:e,tag:r}},tf=t=>{let e=t.newChatTags.map(o=>Ya("newChat",o)),r=t.systemTags.map(o=>Ya("system",o)),n=t.userTags.map(o=>Ya("user",o)),s=t.providers.map(o=>Ya("assistant",o.tag));return[...e,...r,...n,...s]},Xr=t=>{let{type:e,tag:r}=eE(t);return{id:t,name:tE(e,r),tag:r,role:e}},tE=(t,e)=>t==="newChat"?Uo(e):gt(e);var Vo=require("obsidian");var rf=({id:t,name:e,tag:r},n,s)=>({id:t,name:e,editorCallback:async(o,i)=>{try{let a=gt(r),{range:c,role:l,tagContent:f,tagRange:u}=_s(n,o,s);if(console.debug("userTagCmd",{range:c,role:l,tagContent:f,tagRange:u}),Ss(o,c))return xs(o,c.from,a);if(l===null)return Es(o,c,a);if(l==="user"){if(r!==f&&u)return Ga(o,c,u,r)}else o.setSelection(c.from,c.to),new Vo.Notice(`${m("Conversion failed. Selected sections is a")} ${m(l)} ${m("message")}`)}catch(a){console.error(a),new Vo.Notice(`\u{1F534} ${Vo.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${a}`,10*1e3)}}});var vy=My(_y()),je=require("obsidian");var Sy=require("obsidian");var kl=class extends Sy.Modal{constructor(e,r){super(e),this.reporter=r}onOpen(){let{contentEl:e}=this;e.createEl("h1",{text:m("Syntax Error Report")});let r=this.reporter.join(`
`);e.createEl("textarea",{text:r,cls:"syntax-error-textarea",attr:{readonly:!0,rows:5}})}onClose(){let{contentEl:e}=this;e.empty()}};var xy=async(t,e)=>{let r=t.vault.getFileByPath(e);if(!r)throw new Error("No prompt file found. "+e);let s=t.metadataCache.getFileCache(r);if(!s)throw new Error(m("Waiting for metadata to be ready. Please try again."));console.debug("sections",s.sections);let o=s.sections;if(!o)throw new Error("No sections found. "+e);let i=s.headings;if(!i)throw new Error("No headings found. "+e);let a=await t.vault.cachedRead(r),c=o.reduce((d,h)=>{if(h.type==="thematicBreak")return[...d,[]];let p=d.length-1;return d[p]=[...d[p],h],d},[[]]).filter(d=>d.length>0);console.debug("sectionGroups",c);let l=c.slice(1);console.debug("slides",l);let f=[],u=[];for(let d of l)try{let h=j0(d,i,a);if(f.some(p=>p.title===h.title))throw new Error(`${m("Duplicate title:")} ${h.title}`);f.push(h)}catch(h){u.push(h.message)}return console.debug("promptTemplates",f),console.debug("reporter",u),{promptTemplates:f,reporter:u}},j0=(t,e,r)=>{if(t.length<2)throw new Error(`Line ${t[0].position.start.line+1}, ${m("Expected at least 2 sections, heading and content")}`);if(t[0].type!=="heading")throw new Error(`Line ${t[0].position.start.line+1} - ${t[0].position.end.line+1}, ${m("Expected heading")}`);let n=e.find(l=>l.position.start.line===t[0].position.start.line);if(!n)throw new Error(`Line ${t[0].position.start.line+1}, ${m("Expected heading")}`);let s=n.heading.trim();if(!s)throw new Error(`Line ${n.position.start.line+1}, ${m("Expected heading")}`);let o=t[1].position.start.offset,i=t[t.length-1].position.end.offset,c=r.slice(o,i).trim();return{title:s,template:c}},Ey=(t,e)=>{let r=[],n=new Map;return t.forEach(s=>{n.set(s.title,s.template)}),e.forEach(s=>{let o=n.get(s.title);o!==void 0&&o!==s.template&&r.push(s)}),r};var oi=t=>`Prompt#${t.title}`,Xf=t=>t.slice(t.indexOf("#")+1),Yf=(t,e,r,n)=>({id:"LoadTemplateFile",name:m("Load template file: ")+`${qe}/${m("promptFileName")}.md`,callback:async()=>{try{let s=(0,je.normalizePath)(`${qe}/${m("promptFileName")}.md`);await W0(t)&&(await Ay(t,s),await new Promise(l=>setTimeout(l,2e3)));let{promptTemplates:i,reporter:a}=await xy(t,s),c=Ey(e.promptTemplates,i);c.length>0&&(console.debug("changed",c),new je.Notice(m("Templates have been updated: ")+c.map(l=>l.title).join(", "))),e.promptTemplates=i,await r(),n(),a&&a.length>0&&(await Ay(t,s),new kl(t,a).open())}catch(s){console.error(s),new je.Notice(`\u{1F534} ${je.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${s}`,10*1e3)}}}),W0=async t=>{let e=!1;await t.vault.adapter.exists((0,je.normalizePath)(qe))||await t.vault.createFolder(qe);let r=(0,je.normalizePath)(`${qe}/${m("promptFileName")}.md`);return await t.vault.adapter.exists(r)||(await t.vault.create(r,m("PRESET_PROMPT_TEMPLATES")),new je.Notice(m("Create prompt template file")+` ${qe}/${m("promptFileName")}.md`),e=!0),e},Ay=async(t,e)=>{var r;((r=t.workspace.getActiveFile())==null?void 0:r.path)!=e&&await t.workspace.openLinkText("",e,!0)},Qf=(t,e,r,n)=>({id:t,name:e,editorCallback:async(s,o)=>{try{let i=n.promptTemplates.find(f=>f.title===e);if(!i)throw new Error(`No template found. ${i}`);let a=Ju(r,s),{from:c,to:l}=a;s.setSelection(c,l),await new Promise(f=>setTimeout(f,500)),K0(s,i.template)}catch(i){console.error(i),new je.Notice(`\u{1F534} ${je.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${i}`,10*1e3)}}}),V0=t=>{let e=t.listSelections();if(e.length===0)throw new Error("No selection");if(e.length>1)throw new Error("Multiple selections");return e[0]},K0=(t,e)=>{let r=t.getSelection(),s=vy.default.compile(e,{strict:!1,noEscape:!0})({s:r}),o=s.includes(r)?s:r+s,{anchor:i,head:a}=V0(t);t.replaceRange(o,i,a)};var L=require("obsidian");var Zf=require("obsidian");var Ol=class extends Zf.FuzzySuggestModal{constructor(e,r,n){super(e),this.models=r,this.onChoose=n}getItems(){return this.models}getItemText(e){return e}renderSuggestion(e,r){let n=e.item,s=0,o=r.createEl("div");for(let i of e.match.matches){let a=n.slice(s,i[0]),c=n.slice(i[0],i[0]+i[1]);o.createEl("span",{text:a}),o.createEl("span",{text:c,cls:"fuzzy-match-highlight"}),s=i[0]+i[1]}o.createEl("span",{text:n.slice(s)})}onChooseItem(e,r){this.onChoose(e)}},Ml=class extends Zf.FuzzySuggestModal{constructor(e,r,n){super(e),this.vendors=r,this.onChoose=n}getItems(){return this.vendors}getItemText(e){return e.name}renderSuggestion(e,r){let n=e.item.name,s=0,o=r.createEl("div");for(let a of e.match.matches){let c=n.slice(s,a[0]),l=n.slice(a[0],a[0]+a[1]);o.createEl("span",{text:c}),o.createEl("span",{text:l,cls:"fuzzy-match-highlight"}),s=a[0]+a[1]}o.createEl("span",{text:n.slice(s)});let i=r.createEl("div",{cls:"capability-tags-container"});e.item.capabilities.forEach(a=>{i.createEl("span",{text:`${jn(a)} ${m(a)}`,cls:"capability-tag"})})}onChooseItem(e,r){this.onChoose(e)}};var Ll=class extends L.PluginSettingTab{constructor(r,n){super(r,n);this.createProviderSetting=(r,n,s=!1)=>{let o=qo.find(f=>f.name===n.vendor);if(!o)throw new Error("No vendor found "+n.vendor);let{containerEl:i}=this,a=i.createEl("details");a.createEl("summary",{text:Cy(n.tag,o.name),cls:"tars-setting-h4"}),a.open=s;let c=m("Supported features")+" : "+o.capabilities.map(f=>`${jn(f)} ${m(f)}`).join(" ");this.addTagSection(a,n,r,o.name);let l=z0[o.name];l?new L.Setting(a).setName(m("Model")).setDesc(c).addButton(f=>{f.setButtonText(n.options.model?n.options.model:m("Select the model to use")).onClick(async()=>{if(l.requiresApiKey&&!n.options.apiKey){new L.Notice(m("Please input API key first"));return}try{let u=await J0(l.url,l.requiresApiKey?n.options.apiKey:void 0),d=async h=>{n.options.model=h,await this.plugin.saveSettings(),f.setButtonText(h)};new Ol(this.app,u,d).open()}catch(u){if(u instanceof Error){let d=u.message.toLowerCase();d.includes("401")||d.includes("unauthorized")?new L.Notice("\u{1F511} "+m("API key may be incorrect. Please check your API key.")):d.includes("403")||d.includes("forbidden")?new L.Notice("\u{1F6AB} "+m("Access denied. Please check your API permissions.")):new L.Notice("\u{1F534} "+u.message)}else new L.Notice("\u{1F534} "+String(u))}})}):o.models.length>0?this.addModelDropDownSection(a,n.options,o.models,c):this.addModelTextSection(a,n.options,c),o.name!==La.name&&this.addAPIkeySection(a,n.options,o.websiteToObtainKey?m("Obtain key from ")+o.websiteToObtainKey:""),"apiSecret"in n.options&&this.addAPISecretOptional(a,n.options),o.capabilities.includes("Web Search")&&new L.Setting(a).setName(m("Web search")).setDesc(m("Enable web search for AI")).addToggle(f=>{var u;return f.setValue((u=n.options.enableWebSearch)!=null?u:!1).onChange(async d=>{n.options.enableWebSearch=d,await this.plugin.saveSettings()})}),o.name===la.name&&this.addClaudeSections(a,n.options),o.name===ma.name&&this.addGptImageSections(a,n.options),this.addBaseURLSection(a,n.options,o.defaultOptions.baseURL),"endpoint"in n.options&&this.addEndpointOptional(a,n.options),"apiVersion"in n.options&&this.addApiVersionOptional(a,n.options),this.addParametersSection(a,n.options),new L.Setting(a).setName(m("Remove")+" "+o.name).addButton(f=>{f.setWarning().setButtonText(m("Remove")).onClick(async()=>{this.plugin.settings.providers.splice(r,1),await this.plugin.saveSettings(),this.display()})})};this.addTagSection=(r,n,s,o)=>new L.Setting(r).setName("\u2728 "+m("Assistant message tag")).setDesc(m("Tag used to trigger AI text generation")).addText(i=>i.setPlaceholder(o).setValue(n.tag).onChange(async a=>{let c=a.trim();if(c.length===0||!Py(c))return;if(this.plugin.settings.providers.filter((u,d)=>d!==s).map(u=>u.tag.toLowerCase()).includes(c.toLowerCase())){new L.Notice(m("Keyword for tag must be unique"));return}n.tag=c;let f=r.querySelector("summary");f!=null&&(f.textContent=Cy(n.tag,o)),await this.plugin.saveSettings()}));this.addBaseURLSection=(r,n,s)=>{let o=null;new L.Setting(r).setName("baseURL").setDesc(m("Default:")+" "+s).addExtraButton(i=>{i.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{n.baseURL=s,await this.plugin.saveSettings(),o&&(o.value=s)})}).addText(i=>{o=i.inputEl,i.setValue(n.baseURL).onChange(async a=>{n.baseURL=a.trim(),await this.plugin.saveSettings()})})};this.addAPIkeySection=(r,n,s="")=>new L.Setting(r).setName("API key").setDesc(s).addText(o=>o.setPlaceholder(m("API key (required)")).setValue(n.apiKey).onChange(async i=>{n.apiKey=i.trim(),await this.plugin.saveSettings()}));this.addAPISecretOptional=(r,n,s="")=>new L.Setting(r).setName("API Secret").setDesc(s).addText(o=>o.setPlaceholder("").setValue(n.apiSecret).onChange(async i=>{n.apiSecret=i.trim(),await this.plugin.saveSettings()}));this.addModelDropDownSection=(r,n,s,o)=>new L.Setting(r).setName(m("Model")).setDesc(o).addDropdown(i=>i.addOptions(s.reduce((a,c)=>(a[c]=c,a),{})).setValue(n.model).onChange(async a=>{n.model=a,await this.plugin.saveSettings()}));this.addModelTextSection=(r,n,s)=>new L.Setting(r).setName(m("Model")).setDesc(s).addText(o=>o.setPlaceholder("").setValue(n.model).onChange(async i=>{n.model=i.trim(),await this.plugin.saveSettings()}));this.addClaudeSections=(r,n)=>{new L.Setting(r).setName(m("Thinking")).setDesc(m("When enabled, Claude will show its reasoning process before giving the final answer.")).addToggle(s=>{var o;return s.setValue((o=n.enableThinking)!=null?o:!1).onChange(async i=>{n.enableThinking=i,await this.plugin.saveSettings()})}),new L.Setting(r).setName(m("Budget tokens for thinking")).setDesc(m("Must be \u22651024 and less than max_tokens")).addText(s=>s.setPlaceholder("").setValue(n.budget_tokens?n.budget_tokens.toString():"1600").onChange(async o=>{let i=parseInt(o);if(isNaN(i)){new L.Notice(m("Please enter a number"));return}if(i<1024){new L.Notice(m("Minimum value is 1024"));return}n.budget_tokens=i,await this.plugin.saveSettings()})),new L.Setting(r).setName("Max tokens").setDesc(m("Refer to the technical documentation")).addText(s=>s.setPlaceholder("").setValue(n.max_tokens.toString()).onChange(async o=>{let i=parseInt(o);if(isNaN(i)){new L.Notice(m("Please enter a number"));return}if(i<256){new L.Notice(m("Minimum value is 256"));return}n.max_tokens=i,await this.plugin.saveSettings()}))};this.addEndpointOptional=(r,n)=>new L.Setting(r).setName(m("Endpoint")).setDesc("e.g. https://docs-test-001.openai.azure.com/").addText(s=>s.setPlaceholder("").setValue(n.endpoint).onChange(async o=>{let i=o.trim();if(i.length===0)n.endpoint="",await this.plugin.saveSettings();else if(G0(i))n.endpoint=i,await this.plugin.saveSettings();else{new L.Notice(m("Invalid URL"));return}}));this.addApiVersionOptional=(r,n)=>new L.Setting(r).setName(m("API version")).setDesc("e.g. 2024-xx-xx-preview").addText(s=>s.setPlaceholder("").setValue(n.apiVersion).onChange(async o=>{n.apiVersion=o.trim(),await this.plugin.saveSettings()}));this.addParametersSection=(r,n)=>new L.Setting(r).setName(m("Override input parameters")).setDesc(m(`Developer feature, in JSON format. For example, if the model list doesn't have the model you want, enter {"model": "your desired model"}`)).addTextArea(s=>s.setPlaceholder("{}").setValue(JSON.stringify(n.parameters)).onChange(async o=>{try{let i=o.trim();if(i===""){n.parameters={},await this.plugin.saveSettings();return}n.parameters=JSON.parse(i),await this.plugin.saveSettings()}catch(i){return}}));this.addGptImageSections=(r,n)=>{new L.Setting(r).setName(m("Image Display Width")).setDesc(m("Example: 400px width would output as ![[image.jpg|400]]")).addSlider(s=>s.setLimits(200,800,100).setValue(n.displayWidth).setDynamicTooltip().onChange(async o=>{n.displayWidth=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Number of images")).setDesc(m("Number of images to generate (1-5)")).addSlider(s=>s.setLimits(1,5,1).setValue(n.n).setDynamicTooltip().onChange(async o=>{n.n=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Image size")).addDropdown(s=>s.addOptions({auto:"Auto","1024x1024":"1024x1024","1536x1024":"1536x1024 "+m("landscape"),"1024x1536":"1024x1536 "+m("portrait")}).setValue(n.size).onChange(async o=>{n.size=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Output format")).addDropdown(s=>s.addOptions({png:"PNG",jpeg:"JPEG",webp:"WEBP"}).setValue(n.output_format).onChange(async o=>{n.output_format=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Quality")).setDesc(m("Quality level for generated images. default: Auto")).addDropdown(s=>s.addOptions({auto:m("Auto"),high:m("High"),medium:m("Medium"),low:m("Low")}).setValue(n.quality).onChange(async o=>{n.quality=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Background")).setDesc(m("Background of the generated image. default: Auto")).addDropdown(s=>s.addOptions({auto:m("Auto"),transparent:m("Transparent"),opaque:m("Opaque")}).setValue(n.background).onChange(async o=>{n.background=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Output compression")).setDesc(m("Compression level of the output image, 10% - 100%. Only for webp or jpeg output format")).addSlider(s=>s.setLimits(10,100,10).setValue(n.output_compression).setDynamicTooltip().onChange(async o=>{n.output_compression=o,await this.plugin.saveSettings()}))};this.plugin=n}hide(){this.plugin.buildTagCommands()}display(r=!1){let{containerEl:n}=this;n.empty(),new L.Setting(n).setName(m("AI assistants")).setHeading(),new L.Setting(n).setName(m("New AI assistant")).setDesc(m("For those compatible with the OpenAI protocol, you can select OpenAI.")).addButton(f=>{f.setButtonText(m("Add AI Provider")).onClick(async()=>{let u=async d=>{let h=d.name,y=this.plugin.settings.providers.map(S=>S.tag).includes(h)?"":h,g=JSON.parse(JSON.stringify(d.defaultOptions));this.plugin.settings.providers.push({tag:y,vendor:d.name,options:g}),await this.plugin.saveSettings(),this.display(!0)};new Ml(this.app,qo,u).open()})}),this.plugin.settings.providers.length||new L.Setting(n).setDesc(m("Please add at least one AI assistant to start using the plugin."));for(let[f,u]of this.plugin.settings.providers.entries()){let d=f===this.plugin.settings.providers.length-1;this.createProviderSetting(f,u,d&&r)}n.createEl("br"),new L.Setting(n).setName(m("Message tags")).setDesc(m("Keywords for tags in the text box are separated by spaces")).setHeading();let s=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.newChat+" "+m("New chat tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.newChatTags=mt.newChatTags,await this.plugin.saveSettings(),s&&(s.value=this.plugin.settings.newChatTags.join(" "))})}).addText(f=>{s=f.inputEl,f.setPlaceholder(mt.newChatTags.join(" ")).setValue(this.plugin.settings.newChatTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);ed(d)&&(this.plugin.settings.newChatTags=d,await this.plugin.saveSettings())})});let o=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.user+" "+m("User message tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.userTags=mt.userTags,await this.plugin.saveSettings(),o&&(o.value=this.plugin.settings.userTags.join(" "))})}).addText(f=>{o=f.inputEl,f.setPlaceholder(mt.userTags.join(" ")).setValue(this.plugin.settings.userTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);ed(d)&&(this.plugin.settings.userTags=d,await this.plugin.saveSettings())})});let i=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.system+" "+m("System message tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.systemTags=mt.systemTags,await this.plugin.saveSettings(),i&&(i.value=this.plugin.settings.systemTags.join(" "))})}).addText(f=>{i=f.inputEl,f.setPlaceholder(mt.systemTags.join(" ")).setValue(this.plugin.settings.systemTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);ed(d)&&(this.plugin.settings.systemTags=d,await this.plugin.saveSettings())})}),n.createEl("br"),new L.Setting(n).setName(m("System message")).setHeading();let a=null;new L.Setting(n).setName(m("Enable default system message")).setDesc(m("Automatically add a system message when none exists in the conversation")).addToggle(f=>f.setValue(this.plugin.settings.enableDefaultSystemMsg).onChange(async u=>{this.plugin.settings.enableDefaultSystemMsg=u,await this.plugin.saveSettings(),a&&(a.disabled=!u)})),new L.Setting(n).setName(m("Default system message")).addTextArea(f=>{a=f.inputEl,f.setDisabled(!this.plugin.settings.enableDefaultSystemMsg).setValue(this.plugin.settings.defaultSystemMsg).onChange(async u=>{this.plugin.settings.defaultSystemMsg=u.trim(),await this.plugin.saveSettings()})}),n.createEl("br"),new L.Setting(n).setName(m("Confirm before regeneration")).setDesc(m("Confirm before replacing existing assistant responses when using assistant commands")).addToggle(f=>f.setValue(this.plugin.settings.confirmRegenerate).onChange(async u=>{this.plugin.settings.confirmRegenerate=u,await this.plugin.saveSettings()})),new L.Setting(n).setName(m("Internal links")).setDesc(m("Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.")).addToggle(f=>f.setValue(this.plugin.settings.enableInternalLink).onChange(async u=>{this.plugin.settings.enableInternalLink=u,await this.plugin.saveSettings()})),n.createEl("br");let c=n.createEl("details");c.createEl("summary",{text:m("Advanced"),cls:"tars-setting-h4"}),new L.Setting(c).setName(m("Internal links for assistant messages")).setDesc(m("Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.")).addToggle(f=>{var u;return f.setValue((u=this.plugin.settings.enableInternalLinkForAssistantMsg)!=null?u:!1).onChange(async d=>{this.plugin.settings.enableInternalLinkForAssistantMsg=d,await this.plugin.saveSettings()})});let l=null;new L.Setting(c).setName(m("Delay before answer (Seconds)")).setDesc(m("If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.answerDelayInMilliseconds=mt.answerDelayInMilliseconds,await this.plugin.saveSettings(),l&&(l.value=(this.plugin.settings.answerDelayInMilliseconds/1e3).toString())})}).addSlider(f=>{l=f.sliderEl,f.setLimits(1.5,4,.5).setValue(this.plugin.settings.answerDelayInMilliseconds/1e3).setDynamicTooltip().onChange(async u=>{this.plugin.settings.answerDelayInMilliseconds=Math.round(u*1e3),await this.plugin.saveSettings()})}),new L.Setting(c).setName(m("Replace tag Command")).setDesc(m("Replace the names of the two most frequently occurring speakers with tag format.")).addToggle(f=>f.setValue(this.plugin.settings.enableReplaceTag).onChange(async u=>{this.plugin.settings.enableReplaceTag=u,await this.plugin.saveSettings(),u?this.plugin.addCommand(jo(this.app)):this.plugin.removeCommand(Xa)})),new L.Setting(c).setName(m("Export to JSONL Command")).setDesc(m("Export conversations to JSONL")).addToggle(f=>f.setValue(this.plugin.settings.enableExportToJSONL).onChange(async u=>{this.plugin.settings.enableExportToJSONL=u,await this.plugin.saveSettings(),u?this.plugin.addCommand(Ho(this.app,this.plugin.settings)):this.plugin.removeCommand(Ja)})),new L.Setting(c).setName(m("Tag suggest")).setDesc(m("If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.")).addToggle(f=>f.setValue(this.plugin.settings.enableTagSuggest).onChange(async u=>{this.plugin.settings.enableTagSuggest=u,await this.plugin.saveSettings()}))}},Cy=(t,e)=>t===e?e:t+" ("+e+")",Py=t=>t.includes("#")?(new L.Notice(m("Keyword for tag must not contain #")),!1):t.includes(" ")?(new L.Notice(m("Keyword for tag must not contain space")),!1):!0,ed=t=>{if(t.length===0)return new L.Notice(m("At least one tag is required")),!1;for(let e of t)if(!Py(e))return!1;return!0},G0=t=>{try{return new URL(t),!0}catch(e){return!1}},J0=async(t,e)=>(await(0,L.requestUrl)({url:t,headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/json"}})).json.data.map(s=>s.id),z0={[Da.name]:{url:"https://api.siliconflow.cn/v1/models?type=text&sub_type=chat",requiresApiKey:!0},[Na.name]:{url:"https://openrouter.ai/api/v1/models",requiresApiKey:!1},[Ma.name]:{url:"https://api.moonshot.cn/v1/models",requiresApiKey:!0},[Oa.name]:{url:"https://api.x.ai/v1/models",requiresApiKey:!0}};var nn=require("obsidian");var td=class extends nn.Modal{constructor(r,n){super(r);this.stats=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:m("AI Generation Details")});let n=r.createDiv({cls:"generation-stats"});n.createEl("p",{text:`${m("Round")}: ${this.stats.round}`}),n.createEl("p",{text:`${m("Model")}: ${this.stats.model}`}),n.createEl("p",{text:`${m("Vendor")}: ${this.stats.vendor}`}),n.createEl("p",{text:`${m("Characters")}: ${this.stats.characters}`}),n.createEl("p",{text:`${m("Duration")}: ${this.stats.duration}`}),n.createEl("p",{text:`${m("Start Time")}: ${this.stats.startTime.toLocaleTimeString()}`}),n.createEl("p",{text:`${m("End Time")}: ${this.stats.endTime.toLocaleTimeString()}`})}onClose(){let{contentEl:r}=this;r.empty()}},rd=class extends nn.Modal{constructor(r,n){super(r);this.error=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:m("Error Details")});let n=r.createDiv({cls:"error-details"});if(n.createEl("p",{text:`${m("Error Type")}: ${this.error.name||m("Unknown Error")}`}),n.createEl("p",{text:`${m("Error Message")}: ${this.error.message}`}),n.createEl("p",{text:`${m("Occurrence Time")}: ${this.error.timestamp.toLocaleString()}`}),this.error.stack){let s=n.createDiv({cls:"stack-trace"});s.createEl("h3",{text:m("Stack Trace")});let o=s.createEl("pre",{cls:"stack-trace-pre"});o.textContent=this.error.stack}if(nn.Platform.isDesktopApp){let o=r.createDiv({cls:"error-modal-buttons"}).createEl("button",{text:m("Copy Error Info")});o.onclick=()=>{navigator.clipboard.writeText(JSON.stringify(this.error,null,2)),new nn.Notice(m("Error info copied to clipboard"))}}}onClose(){let{contentEl:r}=this;r.empty()}},Nl=class{constructor(e,r){this.app=e;this.statusBarItem=r;this.autoHideTimer=null;this.state={type:"idle",content:{text:"Tars",tooltip:m("Tars AI assistant is ready")},timestamp:new Date},this.setupClickHandler(),this.refreshStatusBar()}setupClickHandler(){this.statusBarItem.addEventListener("click",()=>{this.state.data&&(this.state.type==="error"?new rd(this.app,this.state.data).open():this.state.type==="success"&&new td(this.app,this.state.data).open())}),this.statusBarItem.style.cursor="pointer",this.statusBarItem.style.transition="opacity 0.2s ease"}updateState(e){this.state={...this.state,...e,timestamp:new Date},this.refreshStatusBar()}refreshStatusBar(){let{content:e}=this.state;this.statusBarItem.setText(e.text),this.statusBarItem.setAttribute("title",e.tooltip)}setGeneratingStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"generating",content:{text:`Round ${e}...`,tooltip:`${m("Generating round")} ${e} ${m("answer...")}`},data:void 0})}updateGeneratingProgress(e){this.state.type==="generating"&&this.updateState({content:{text:`Tars: ${e}${m("characters")}`,tooltip:`${m("Generating...")} ${e} ${m("characters")}`}})}setSuccessStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"success",content:{text:`Tars: ${e.characters}${m("characters")} ${e.duration}`,tooltip:`${m("Round")} ${e.round} | ${e.characters}${m("characters")} | ${e.duration} | ${e.model}`},data:e})}setErrorStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null);let r={message:e.message,name:e.name,stack:e.stack,timestamp:new Date};this.updateState({type:"error",content:{text:`\u{1F534} Tars: ${m("Error")}`,tooltip:`${m("Error")}: ${e.message}`},data:r}),this.autoHideTimer=setTimeout(()=>this.clearStatus(),1e3*60*2)}setCancelledStatus(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"idle",content:{text:`\u26A0\uFE0F Tars: ${m("Generation cancelled")}`,tooltip:m("Generation cancelled")},data:void 0}),this.autoHideTimer=setTimeout(()=>this.clearStatus(),1e3*60*1)}clearStatus(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"idle",content:{text:"Tars",tooltip:m("Tars AI assistant is ready")},data:void 0})}getState(){return{...this.state}}dispose(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null)}};var Dl=class extends Ft.Plugin{constructor(){super(...arguments);this.tagCmdIds=[];this.promptCmdIds=[];this.tagLowerCaseMap=new Map;this.aborterInstance=null}async onload(){await this.loadSettings(),console.debug("loading Tars plugin...");let r=this.addStatusBarItem();this.statusBarManager=new Nl(this.app,r),this.buildTagCommands(!0),this.buildPromptCommands(!0),this.addCommand(Zu(this.app,this.settings)),this.addCommand(Yf(this.app,this.settings,()=>this.saveSettings(),()=>this.buildPromptCommands())),this.settings.editorStatus={isTextInserting:!1},this.settings.enableTagSuggest&&this.registerEditorSuggest(new Ka(this.app,this.settings,this.tagLowerCaseMap,this.statusBarManager,this.getRequestController())),this.addCommand({id:"cancelGeneration",name:m("Cancel generation"),callback:async()=>{if(this.settings.editorStatus.isTextInserting=!1,this.aborterInstance===null){new Ft.Notice(m("No active generation to cancel"));return}if(this.aborterInstance.signal.aborted){new Ft.Notice(m("Generation already cancelled"));return}this.aborterInstance.abort()}}),this.settings.enableReplaceTag&&this.addCommand(jo(this.app)),this.settings.enableExportToJSONL&&this.addCommand(Ho(this.app,this.settings)),this.addSettingTab(new Ll(this.app,this))}onunload(){var r;(r=this.statusBarManager)==null||r.dispose()}addTagCommand(r){let n=Xr(r);switch(n.role){case"newChat":this.addCommand(Yu(n));break;case"system":this.addCommand(ef(n,this.app,this.settings));break;case"user":this.addCommand(rf(n,this.app,this.settings));break;case"assistant":this.addCommand(Xu(n,this.app,this.settings,this.statusBarManager,this.getRequestController()));break;default:throw new Error("Unknown tag role")}}buildTagCommands(r=!1){this.settings.tagSuggestMaxLineLength=Im(this.settings);let n=tf(this.settings),s=this.tagCmdIds.filter(c=>!n.includes(c));s.forEach(c=>{this.removeCommand(c);let{tag:l}=Xr(c);this.tagLowerCaseMap.delete(l.toLowerCase())});let o=n.filter(c=>!this.tagCmdIds.includes(c));if(o.forEach(c=>{this.addTagCommand(c);let{role:l,tag:f}=Xr(c);this.tagLowerCaseMap.set(f.toLowerCase(),{role:l,tag:f})}),this.tagCmdIds=n,r)return;let i=s.map(c=>Xr(c).tag);i.length>0&&(console.debug("Removed commands",i),new Ft.Notice(`${m("Removed commands")}: ${i.join(", ")}`));let a=o.map(c=>Xr(c).tag);a.length>0&&(console.debug("Added commands",a),new Ft.Notice(`${m("Added commands")}: ${a.join(", ")}`))}buildPromptCommands(r=!1){let n=this.settings.promptTemplates.map(oi),s=this.promptCmdIds.filter(c=>!n.includes(c));s.forEach(c=>this.removeCommand(c));let o=this.settings.promptTemplates.filter(c=>!this.promptCmdIds.includes(oi(c)));if(o.forEach(c=>{this.addCommand(Qf(oi(c),c.title,this.app,this.settings))}),this.promptCmdIds=n,r)return;let i=s.map(c=>Xf(c));i.length>0&&(console.debug("Removed commands",i),new Ft.Notice(`${m("Removed commands")}: ${i.join(", ")}`));let a=o.map(c=>c.title);a.length>0&&(console.debug("Added commands",a),new Ft.Notice(`${m("Added commands")}: ${a.join(", ")}`))}getRequestController(){return{getController:()=>(this.aborterInstance||(this.aborterInstance=new AbortController),this.aborterInstance),cleanup:()=>{this.settings.editorStatus.isTextInserting=!1,this.aborterInstance=null}}}async loadSettings(){this.settings=Object.assign({},mt,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}};
/*! Bundled license information:
@google/generative-ai/dist/index.mjs:
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
*/
/* nosourcemap */