varzR=Object.create;varJc=Object.defineProperty;varxR=Object.getOwnPropertyDescriptor;varUR=Object.getOwnPropertyNames;varBR=Object.getPrototypeOf,rR=Object.prototype.hasOwnProperty;varOR=(l,I,G)=>Iinl?Jc(l,I,{enumerable:!0,configurable:!0,writable:!0,value:G}):l[I]=G;varEV=(l,I)=>()=>(I||l((I={exports:{}}).exports,I),I.exports),MR=(l,I)=>{for(varGinI)Jc(l,G,{get:I[G],enumerable:!0})},JV=(l,I,G,b)=>{if(I&&typeofI=="object"||typeofI=="function")for(letZofUR(I))!rR.call(l,Z)&&Z!==G&&Jc(l,Z,{get:()=>I[Z],enumerable:!(b=xR(I,Z))||b.enumerable});returnl};varMN=(l,I,G)=>(G=l!=null?zR(BR(l)):{},JV(I||!l||!l.__esModule?Jc(G,"default",{value:l,enumerable:!0}):G,l)),jR=l=>JV(Jc({},"__esModule",{value:!0}),l);varsI=(l,I,G)=>OR(l,typeofI!="symbol"?I+"":I,G);varca=EV(zd=>{"use strict";zd.byteLength=yH;zd.toByteArray=CH;zd.fromByteArray=LH;varEl=[],TG=[],sH=typeofUint8Array<"u"?Uint8Array:Array,VY="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(qb=0,ba=VY.length;qb<ba;++qb)El[qb]=VY[qb],TG[VY.charCodeAt(qb)]=qb;varqb,ba;TG[45]=62;TG[95]=63;functionZa(l){varI=l.length;if(I%4>0)thrownewError("Invalid string. Length must be a multiple of 4");varG=l.indexOf("=");G===-1&&(G=I);varb=G===I?0:4-G%4;return[G,b]}functionyH(l){varI=Za(l),G=I[0],b=I[1];return(G+b)*3/4-b}functioneH(l,I,G){return(I+G)*3/4-G}functionCH(l){varI,G=Za(l),b=G[0],Z=G[1],c=newsH(eH(l,b,Z)),W=0,d=Z>0?b-4:b,N;for(N=0;N<d;N+=4)I=TG[l.charCodeAt(N)]<<18|TG[l.charCodeAt(N+1)]<<12|TG[l.charCodeAt(N+2)]<<6|TG[l.charCodeAt(N+3)],c[W++]=I>>16&255,c[W++]=I>>8&255,c[W++]=I&255;returnZ===2&&(I=TG[l.charCodeAt(N)]<<2|TG[l.charCodeAt(N+1)]>>4,c[W++]=I&255),Z===1&&(I=TG[l.charCodeAt(N)]<<10|TG[l.charCodeAt(N+1)]<<4|TG[l.charCodeAt(N+2)]>>2,c[W++]=I>>8&255,c[W++]=I&255),c}functiongH(l){returnEl[l>>18&63]+El[l>>12&63]+El[l>>6&63]+El[l&63]}functionAH(l,I,G){for(varb,Z=[],c=I;c<G;c+=3)b=(l[c]<<16&16711680)+(l[c+1]<<8&65280)+(l[c+2]&255),Z.push(gH(b));returnZ.join("")}functionLH(l){for(varI,G=l.length,b=G%3,Z=[],c=16383,W=0,d=G-b;W<d;W+=c)Z.push(AH(l,W,W+c>d?d:W+c));returnb===1?(I=l[G-1],Z.push(El[I>>2]+El[I<<4&63]+"==")):b===2&&(I=(l[G-2]<<8)+l[G-1],Z.push(El[I>>10]+El[I>>4&63]+El[I<<2&63]+"=")),Z.join("")}});varIR=EV(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});require("obsidian");varql=classextendsError{},sY=classextendsql{constructor(I){super(`Invalid DateTime: ${I.toMessage()}`)}},yY=classextendsql{constructor(I){super(`Invalid Interval: ${I.toMessage()}`)}},eY=classextendsql{constructor(I){super(`Invalid Duration: ${I.toMessage()}`)}},$b=classextendsql{},IN=classextendsql{constructor(I){super(`Invalid unit ${I}`)}},JG=classextendsql{},Cl=classextendsql{constructor(){super("Zone is an abstract class")}},B="numeric",al="short",oG="long",GN={year:B,month:B,day:B},IF={year:B,month:al,day:B},bp={year:B,month:al,day:B,weekday:al},GF={year:B,month:oG,day:B},lF={year:B,month:oG,day:B,weekday:oG},bF={hour:B,minute:B},ZF={hour:B,minute:B,second:B},cF={hour:B,minute:B,second:B,timeZoneName:al},WF={hour:B,minute:B,second:B,timeZoneName:oG},dF={hour:B,minute:B,hourCycle:"h23"},NF={hour:B,minute:B,second:B,hourCycle:"h23"},mF={hour:B,minute:B,second:B,hourCycle:"h23",timeZoneName:al},YF={hour:B,minute:B,second:B,hourCycle:"h23",timeZoneName:oG},VF={year:B,month:B,day:B,hour:B,minute:B},hF={year:B,month:B,day:B,hour:B,minute:B,second:B},aF={year:B,month:al,day:B,hour:B,minute:B},FF={year:B,month:al,day:B,hour:B,minute:B,second:B},Zp={year:B,month:al,day:B,weekday:al,hour:B,minute:B},RF={year:B,month:oG,day:B,hour:B,minute:B,timeZoneName:al},XF={year:B,month:oG,day:B,hour:B,minute:B,second:B,timeZoneName:al},QF={year:B,month:oG,day:B,weekday:oG,hour:B,minute:B,timeZoneName:oG},HF={year:B,month:oG,day:B,weekday:oG,hour:B,minute:B,second:B,timeZoneName:oG},lZ=class{gettype(){thrownewCl}getname(){thrownewCl}getianaName(){returnthis.name}getisUniversal(){thrownewCl}offsetName(I,G){thrownewCl}formatOffset(I,G){thrownewCl}offset(I){thrownewCl}equals(I){thrownewCl}getisValid(){th
`||R.charAt(i)==="\r"&&R.charAt(i+1)!==`
`)&&(L++,k===0&&(k=i+1)),i--}var f=e+L,nI=p-k;return E[p]={line:f,lineStart:k},{offset:p,line:f+1,column:nI+1}}function x(R){if(!F(R))throw new Error("not a parser: "+R)}function GI(R,p){return typeof R=="string"?R.charAt(p):R[p]}function lI(R){if(typeof R!="number")throw new Error("not a number: "+R)}function aI(R){if(typeof R!="function")throw new Error("not a function: "+R)}function hI(R){if(typeof R!="string")throw new Error("not a string: "+R)}var vI=2,zG=3,kI=8,$G=5*kI,lG=4*kI,YG=" ";function Il(R,p){return new Array(p+1).join(R)}function o(R,p,E){var e=p-R.length;return e<=0?R:Il(E,e)+R}function NI(R,p,E,e){return{from:R-p>0?R-p:0,to:R+E>e?e:R+E}}function QI(R,p){var E,e,L,k,i,f=p.index,nI=f.offset,XG=1;if(nI===R.length)return"Got the end of the input";if(y(R)){var ZG=nI-nI%kI,il=nI-ZG,sG=NI(ZG,$G,lG+kI,R.length),zl=m(function(KI){return m(function(mZ){return o(mZ.toString(16),2,"0")},KI)},function(KI,mZ){var YZ=KI.length,nb=[],VZ=0;if(YZ<=mZ)return[KI.slice()];for(var hZ=0;hZ<YZ;hZ++)nb[VZ]||nb.push([]),nb[VZ].push(KI[hZ]),(hZ+1)%mZ==0&&VZ++;return nb}(R.slice(sG.from,sG.to).toJSON().data,kI));k=function(KI){return KI.from===0&&KI.to===1?{from:KI.from,to:KI.to}:{from:KI.from/kI,to:Math.floor(KI.to/kI)}}(sG),e=ZG/kI,E=3*il,il>=4&&(E+=1),XG=2,L=m(function(KI){return KI.length<=4?KI.join(" "):KI.slice(0,4).join(" ")+" "+KI.slice(4).join(" ")},zl),(i=(8*(k.to>0?k.to-1:k.to)).toString(16).length)<2&&(i=2)}else{var NZ=R.split(/\r\n|[\n\r\u2028\u2029]/);E=f.column-1,e=f.line-1,k=NI(e,vI,zG,NZ.length),L=NZ.slice(k.from,k.to),i=k.to.toString().length}var iR=e-k.from;return y(R)&&(i=(8*(k.to>0?k.to-1:k.to)).toString(16).length)<2&&(i=2),N(function(KI,mZ,YZ){var nb,VZ=YZ===iR,hZ=VZ?"> ":YG;return nb=y(R)?o((8*(k.from+YZ)).toString(16),i,"0"):o((k.from+YZ+1).toString(),i," "),[].concat(KI,[hZ+nb+" | "+mZ],VZ?[YG+Il(" ",i)+" | "+o("",E," ")+Il("^",XG)]:[])},[],L).join(`
`].join("");var E}function Xl(R){return R.flags!==void 0?R.flags:[R.global?"g":"",R.ignoreCase?"i":"",R.multiline?"m":"",R.unicode?"u":"",R.sticky?"y":""].join("")}function Ib(){for(var R=[].slice.call(arguments),p=R.length,E=0;E<p;E+=1)x(R[E]);return c(function(e,L){for(var k,i=new Array(p),f=0;f<p;f+=1){if(!(k=t(R[f]._(e,L),k)).status)return k;i[f]=k.value,L=k.index}return t(v(L,i),k)})}function kl(){var R=[].slice.call(arguments);if(R.length===0)throw new Error("seqMap needs at least one argument");var p=R.pop();return aI(p),Ib.apply(null,R).map(function(E){return p.apply(null,E)})}function Gb(){var R=[].slice.call(arguments),p=R.length;if(p===0)return pb("zero alternates");for(var E=0;E<p;E+=1)x(R[E]);return c(function(e,L){for(var k,i=0;i<R.length;i+=1)if((k=t(R[i]._(e,L),k)).status)return k;return k})}function CW(R,p){return ZZ(R,p).or(Ql([]))}function ZZ(R,p){return x(R),x(p),kl(R,p.then(R).many(),function(E,e){return[E].concat(e)})}function Hb(R){hI(R);var p="'"+R+"'";return c(function(E,e){var L=e+R.length,k=E.slice(e,L);return k===R?v(L,k):J(e,p)})}function Gl(R,p){(function(L){if(!(L instanceof RegExp))throw new Error("not a regexp: "+L);for(var k=Xl(L),i=0;i<k.length;i++){var f=k.charAt(i);if(f!=="i"&&f!=="m"&&f!=="u"&&f!=="s")throw new Error('unsupported regexp flag "'+f+'": '+L)}})(R),arguments.length>=2?lI(p):p=0;var E=function(L){return RegExp("^(?:"+L.source+")",Xl(L))}(R),e=""+R;return c(function(L,k){var i=E.exec(L.slice(k));if(i){if(0<=p&&p<=i.length){var f=i[0],nI=i[p];return v(k+f.length,nI)}return J(k,"valid match group (0 to "+i.length+") in "+e)}return J(k,e)})}function Ql(R){return c(function(p,E){return v(E,R)})}function pb(R){return c(function(p,E){return J(E,R)})}function cZ(R){if(F(R))return c(function(p,E){var e=R._(p,E);return e.index=E,e.value="",e});if(typeof R=="string")return cZ(Hb(R));if(R instanceof RegExp)return cZ(Gl(R));throw new Error("not a string, regexp, or parser: "+R)}function gW(R){return x(R),c(function(p,E){var e=R._(p,E),L=p.slice(E,e.index);return e.status?J(E,'not "'+L+'"'):v(E,null)})}function xG(R){return aI(R),c(function(p,E){var e=GI(p,E);return E<p.length&&R(e)?v(E+1,e):J(E,"a character/byte matching "+R)})}function ub(R,p){arguments.length<2&&(p=R,R=void 0);var E=c(function(e,L){return E._=p()._,E._(e,L)});return R?E.desc(R):E}function WZ(){return pb("fantasy-land/empty")}W.parse=function(R){if(typeof R!="string"&&!y(R))throw new Error(".parse must be called with a string or Buffer as its argument");var p,E=this.skip(dZ)._(R,0);return p=E.status?{status:!0,value:E.value}:{status:!1,index:S(R,E.furthest),expected:E.expected},delete O[R],p},W.tryParse=function(R){var p=this.parse(R);if(p.status)return p.value;var E=bG(R,p),e=new Error(E);throw e.type="ParsimmonError",e.result=p,e},W.assert=function(R,p){return this.chain(function(E){return R(E)?Ql(E):pb(p)})},W.or=function(R){return Gb(this,R)},W.trim=function(R){return this.wrap(R,R)},W.wrap=function(R,p){return kl(R,this,p,function(E,e){return e})},W.thru=function(R){return R(this)},W.then=function(R){return x(R),Ib(this,R).map(function(p){return p[1]})},W.many=function(){var R=this;return c(function(p,E){for(var e=[],L=void 0;;){if(!(L=t(R._(p,E),L)).status)return t(v(E,e),L);if(E===L.index)throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause");E=L.index,e.push(L.value)}})},W.tieWith=function(R){return hI(R),this.map(function(p){if(function(L){if(!n(L))throw new Error("not an array: "+L)}(p),p.length){hI(p[0]);for(var E=p[0],e=1;e<p.length;e++)hI(p[e]),E+=R+p[e];return E}return""})},W.tie=function(){return this.tieWith("")},W.times=function(R,p){var E=this;return arguments.length<2&&(p=R),lI(R),lI(p),c(function(e,L){for(var k=[],i=void 0,f=void 0,nI=0;nI<R;nI+=1){if(f=t(i=E._(e,L),f),!i.status)return f;L=i.index,k.push(i.value)}for(;nI<p&&(f=t(i=E._(e,L),f),i.status);nI+=1)L=i.index,k.push(i.value);return t(v(L,k),f)})},W.result=function(R){return this.map(function(){return R})},W.atMost=function(R){return this.times(0,R)
`),vV=Hb(`\r
`),tV=Gb(vV,wV,nV).desc("newline"),kR=Gb(tV,dZ);c.all=AW,c.alt=Gb,c.any=Ec,c.cr=nV,c.createLanguage=function(R){varp={};for(varEinR)({}).hasOwnProperty.call(R,E)&&function(e){p[e]=ub(function(){returnR[e](p)})}(E);returnp},c.crlf=vV,c.custom=function(R){returnc(R(v,J))},c.digit=LW,c.digits=oW,c.empty=WZ,c.end=kR,c.eof=dZ,c.fail=pb,c.formatError=bG,c.index=lb,c.isParser=F,c.lazy=ub,c.letter=gR,c.letters=AR,c.lf=wV,c.lookahead=cZ,c.makeFailure=J,c.makeSuccess=v,c.newline=tV,c.noneOf=function(R){returnxG(function(p){returnR.indexOf(p)<0}).desc("none of '"+R+"'")},c.notFollowedBy=gW,c.of=Ql,c.oneOf=function(R){for(varp=R.split(""),E=0;E<p.length;E++)p[E]="'"+p[E]+"'";returnxG(function(e){returnR.indexOf(e)>=0}).desc(p)},c.optWhitespace=LR,c.Parser=c,c.range=function(R,p){returnxG(function(E){returnR<=E&&E<=p}).desc(R+"-"+p)},c.regex=Gl,c.regexp=Gl,c.sepBy=CW,c.sepBy1=ZZ,c.seq=Ib,c.seqMap=kl,c.seqObj=function(){for(varR,p={},E=0,e=(R=arguments,Array.prototype.slice.call(R)),L=e.length,k=0;k<L;k+=1){vari=e[k];if(!F(i)){if(n(i)&&i.length===2&&typeofi[0]=="string"&&F(i[1])){varf=i[0];if(Object.prototype.hasOwnProperty.call(p,f))thrownewError("seqObj: duplicate key "+f);p[f]=!0,E++;continue}thrownewError("seqObj arguments must be parsers or [string, parser] array pairs.")}}if(E===0)thrownewError("seqObj expects at least one named parser, found zero");returnc(function(nI,XG){for(varZG,il={},sG=0;sG<L;sG+=1){varzl,NZ;if(n(e[sG])?(zl=e[sG][0],NZ=e[sG][1]):(zl=null,NZ=e[sG]),!(ZG=t(NZ._(nI,XG),ZG)).status)returnZG;zl&&(il[zl]=ZG.value),XG=ZG.index}returnt(v(XG,il),ZG)})},c.string=Hb,c.succeed=Ql,c.takeWhile=function(R){returnaI(R),c(function(p,E){for(vare=E;e<p.length&&R(GI(p,e));)e++;returnv(e,p.slice(E,e))})},c.test=xG,c.whitespace=oR,c["fantasy-land/empty"]=WZ,c["fantasy-land/of"]=Ql,c.Binary={bitSeq:a,bitSeqObj:function(R){h();varp={},E=0,e=m(function(k){if(n(k)){vari=k;if(i.length!==2)thrownewError("["+i.join(", ")+"] should be length 2, got length "+i.length);if(hI(i[0]),lI(i[1]),Object.prototype.hasOwnProperty.call(p,i[0]))thrownewError("duplicate key in bitSeqObj: "+i[0]);returnp[i[0]]=!0,E++,i}returnlI(k),[null,k]},R);if(E<1)thrownewError("bitSeqObj expects at least one named pair, got ["+R.join(", ")+"]");varL=m(function(k){returnk[0]},e);returna(m(function(k){returnk[1]},e)).map(function(k){returnN(function(i,f){returnf[0]!==null&&(i[f[0]]=f[1]),i},{},m(function(i,f){return[i,k[f]]},L))})},byte:function(R){if(h(),lI(R),R>255)thrownewError("Value specified to byte constructor ("+R+"=0x"+R.toString(16)+") is larger in value than a single byte.");varp=(R>15?"0x":"0x0")+R.toString(16);returnc(function(E,e){varL=GI(E,e);returnL===R?v(e+1,L):J(e,p)})},buffer:function(R){returnX("buffer",R).map(function(p){returnBuffer.from(p)})},encodedString:function(R,p){returnX("string",p).map(function(E){returnE.toString(R)})},uintBE:w,uint8BE:w(1),uint16BE:w(2),uint32BE:w(4),uintLE:u,uint8LE:u(1),uint16LE:u(2),uint32LE:u(4),intBE:s,int8BE:s(1),int16BE:s(2),int32BE:s(4),intLE:C,int8LE:C(1),int16LE:C(2),int32LE:C(4),floatBE:X("floatBE",4).map(function(R){returnR.readFloatBE(0)}),floatLE:X("floatLE",4).map(function(R){returnR.readFloatLE(0)}),doubleBE:X("doubleBE",8).map(function(R){returnR.readDoubleBE(0)}),doubleLE:X("doubleLE",8).map(function(R){returnR.readDoubleLE(0)})},G.exports=c}])})})(dN,dN.exports);varQ=dN.exports,IV=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u30
${I}`:""}`;function Ud(l){if(l){let I=new Va.Notice(Ya("starting",""),1e6);return{setMessage:(G,b)=>{I.setMessage(Ya(G,b))},hide:()=>I.hide()}}return{setMessage:(I,G)=>{U.logMessage(`(${I}) ${G}`)},hide:()=>{}}}var gG=(l,I)=>{let G=I.name==="gpt-3.5-turbo-16k"?"gpt-3.5-turbo":I.name;G=G==="gpt-4-1106-preview"?"gpt-4":G,G=G==="gpt-3.5-turbo-1106"?"gpt-3.5-turbo":G;try{return da(G).encode(l).length}catch{return FY("cl100k_base").encode(l).length}};async function fH(l,I,G){if(typeof l!="function")throw new TypeError("Callbackmustbeafunction.");if(!(I instanceof Promise))throw new TypeError("PromisemustbeaninstanceofPromise.");if(typeof G!="number"||G<=0)throw new TypeError("Intervalmustbeapositivenumber.");let b=!1;for(I.finally(()=>{b=!0});!b;)l(),await sleep(G)}async function PH(l,I,G){let b;if(I.enable)b=G.find(d=>d.path.endsWith(I.name));else{let d=G.map(N=>N.basename);b=await aG.Suggest(l,d,G)}CG(b,"Prompttemplatedoesnotexist");let Z=b.path,c=l.vault.getAbstractFileByPath(Z);CG(c instanceof ha.TFile,`${Z} is not a file`);let W=await l.vault.cachedRead(c);return[b.basename,W]}async function aa(l,I,G){if(M.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let b=Ud(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,promptTemplate:d,systemPrompt:N,promptTemplateFolder:m}=I,Y=KZ(l,m),[V,h]=await PH(l,d,Y);b.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let a=await G(h),X=["prompting",`Using prompt template "${V}".`];b.setMessage(X[0],X[1]);let w=xd(l,Z,c,N,I.modelOptions)(a),s=(await QY(w,100,n=>{b.setMessage(X[0],`${X[1]} (${(n/1e3).toFixed(2)}s)`)},n=>{b.setMessage("finished",`Took ${(n/1e3).toFixed(2)}s.`)})).content,C=(">"+s).replace(/\n/g,`
> `),F={[W]:s,[`${W}-quoted`]:C};return setTimeout(()=>b.hide(),5e3),F}catch(Z){b.setMessage("dead",Z.message),setTimeout(()=>b.hide(),5e3)}}async function QY(l,I,G,b){let Z=Date.now();return await fH(()=>G(Date.now()-Z),l,I),b(Date.now()-Z),await l}async function Fa(l,I,G){if(M.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let b=Ud(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,prompt:N,modelOptions:m}=I;b.setMessage("waiting","QuickAddisformattingtheprompttemplate.");let Y=await G(N),V=["prompting","Usingcustomprompt."];b.setMessage(V[0],V[1]);let a=xd(l,Z,c,d,m)(Y),H=(await QY(a,100,s=>{b.setMessage(V[0],`${V[1]} (${(s/1e3).toFixed(2)}s)`)},s=>{b.setMessage("finished",`Took ${(s/1e3).toFixed(2)}s.`)})).content,w=(">"+H).replace(/\n/g,`
> `),u={[W]:H,[`${W}-quoted`]:w};return setTimeout(()=>b.hide(),5e3),u}catch(Z){b.setMessage("dead",Z.message),setTimeout(()=>b.hide(),5e3)}}var XY=class{constructor(I,G){this.maxRequests=I;this.intervalMs=G;this.queue=[];this.pendingPromises=[]}add(I){return new Promise((G,b)=>{this.queue.push(async()=>{try{G(await I())}catch(Z){b(Z)}}),this.schedule()})}schedule(){if(this.queue.length===0||this.pendingPromises.length>=this.maxRequests)return;let I=this.queue.shift();if(!I)return;let G=I();this.pendingPromises.push(G),G.finally(()=>{this.pendingPromises=this.pendingPromises.filter(b=>b!==G),this.schedule()}),setTimeout(()=>this.schedule(),this.intervalMs)}};async function Ra(l,I,G){if(M.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let b=Ud(I.showAssistantMessages);try{let{apiKey:Z,model:c,outputVariableName:W,systemPrompt:d,promptTemplate:N,text:m,modelOptions:Y}=I;b.setMessage("chunking","Creatingpromptchunkswithtextandprompttemplate");let V=I.chunkSeparator||/\n/g,h=m.split(V),a=gG(d,c),X=await G(N,{chunk:""}),H=gG(X,c),w=ma(c.name)/2-a,u=I.shouldMerge??!0,s=[],C=w-H;if(u){let GI=[],lI="",aI=0;for(let hI of h){let vI=gG(hI,c)+1;if(vI>C)throw new Error(`The chunk "${hI.slice(0,25)}..." is too large to fit in a single prompt.`);aI+vI<C?(lI+=hI,aI+=vI):(GI.push(lI),lI=hI,aI=vI)}lI!==""&&GI.push(lI);for(let hI of GI){let vI=await G(N,{chunk:hI});s.push(vI)}}else for(let GI of h){let lI=gG(GI,c);if(lI>w)throw new Error(`Chunk size (${lI}) is larger than the maximum chunk size (${w}). Please check your chunk separator.`);let aI=await G(N,{chunk:GI});s.push(aI)}let F=xd(l,Z,c,d,Y),n=["prompting",`${s.length} prompts being sent.`];b.setMessage(n[0],n[1]);let y=new XY(5,1e3*30),v=Promise.all(s.map(GI=>y.add(()=>F(GI)))),O=(await QY(v,100,GI=>{b.setMessage(n[0],`${n[1]} (${(GI/1e3).toFixed(2)}s)`)},GI=>{b.setMessage("finished",`Took ${(GI/1e3).toFixed(2)}s.`)})).map(GI=>GI.content).join(I.resultJoiner),S=(">"+O).replace(/\n/g,`
> `),x={[W]:O,[`${W}-quoted`]:S};return setTimeout(()=>b.hide(),5e3),x}catch(Z){b.setMessage("dead",Z.message),setTimeout(()=>b.hide(),5e3)}}var Bd=class{static filterFiles(I,G,b){return Object.keys(G).length===0?I:I.filter(Z=>!(G.folder&&!this.matchesFolder(Z,G.folder)||G.tags&&G.tags.length>0&&!this.matchesTags(Z,G.tags,b)))}static matchesFolder(I,G){let b=this.normalizePath(G),Z=this.normalizePath(I.path);return Z.startsWith(b+"/")||Z.substring(0,Z.lastIndexOf("/"))===b}static matchesTags(I,G,b){let Z=b(I);if(!Z||!Z.tags)return!1;let c=Z.tags.map(W=>W.tag.startsWith("#")?W.tag.substring(1):W.tag);return G.every(W=>c.includes(W))}static normalizePath(I){return I.replace(/^\/+|\/+$/g,"")}};var cW=class cW{static parseInlineFields(I){let G=new Map,b=this.removeCodeBlocksAndFrontmatter(I),Z;for(;(Z=cW.INLINE_FIELD_REGEX.exec(b))!==null;){let c=Z[1].trim(),W=Z[2].trim();W&&(G.has(c)||G.set(c,new Set),W.includes(",")?W.split(",").map(N=>N.trim()).filter(N=>N.length>0).forEach(N=>G.get(c)?.add(N)):G.get(c)?.add(W))}return cW.INLINE_FIELD_REGEX.lastIndex=0,G}static removeCodeBlocksAndFrontmatter(I){let G=/^---\r?\n[\s\S]*?\r?\n---\r?\n/;I=I.replace(G,"");let b=/```[\s\S]*?```|`[^`]*`/g;return I=I.replace(b,""),I}static getFieldValues(I,G){return this.parseInlineFields(I).get(G)||new Set}};cW.INLINE_FIELD_REGEX=/(?:^|[\n\r])[ \t]*(?![-*+][ \t]+\[[ xX]\])([^:\n\r]+?)::[ \t]*(.*)$/gmu;var PZ=cW;var Dl=class l{constructor(){this.cache=new Map;this.TTL=5*60*1e3;this.MAX_CACHE_ENTRIES=100;this.MAX_VALUES_PER_ENTRY=1e3;this.cleanupInterval=null}static getInstance(){return l.instance||(l.instance=new l),l.instance}startAutomaticCleanup(I){if(this.cleanupInterval===null&&typeof window<"u"){let G=window.setInterval(()=>{this.cleanExpired()},6e4);this.cleanupInterval=I(G)}}get(I,G){let b=this.makeKey(I,G),Z=this.cache.get(b);return Z?Date.now()-Z.timestamp>this.TTL?(this.cache.delete(b),null):new Set(Z.values):null}set(I,G,b){let Z=this.makeKey(I,b),c=new Set,W=0;for(let d of G){if(W>=this.MAX_VALUES_PER_ENTRY)break;c.add(d),W++}this.cache.size>=this.MAX_CACHE_ENTRIES&&!this.cache.has(Z)&&this.evictOldestEntries(1),this.cache.set(Z,{values:c,timestamp:Date.now()})}evictOldestEntries(I){let G=Array.from(this.cache.entries()).sort(([,b],[,Z])=>b.timestamp-Z.timestamp).slice(0,I);for(let[b]of G)this.cache.delete(b)}clear(I){if(I){let G=[];for(let b of this.cache.keys())(b.startsWith(`${I}:`)||b===I)&&G.push(b);for(let b of G)this.cache.delete(b)}else this.cache.clear()}cleanExpired(){let I=Date.now(),G=[];for(let[b,Z]of this.cache.entries())I-Z.timestamp>this.TTL&&G.push(b);for(let b of G)this.cache.delete(b)}getStats(){return{size:this.cache.size,maxSize:this.MAX_CACHE_ENTRIES,cleanupInterval:this.cleanupInterval}}destroy(){this.cleanupInterval=null,this.cache.clear()}makeKey(I,G){return G?`${I}:${G}`:I}};var _Z=class{static GetApi(I,G,b){return{inputPrompt:(Z,c,W)=>this.inputPrompt(I,Z,c,W),wideInputPrompt:(Z,c,W)=>this.wideInputPrompt(I,Z,c,W),yesNoPrompt:(Z,c)=>this.yesNoPrompt(I,Z,c),infoDialog:(Z,c)=>this.infoDialog(I,Z,c),suggester:(Z,c)=>this.suggester(I,Z,c),checkboxPrompt:(Z,c)=>this.checkboxPrompt(I,Z,c),executeChoice:async(Z,c)=>{let W=G.getChoiceByName(Z);W||wI(new Error(`Choice named '${Z}' not found`),"APIexecuteChoiceerror"),c&&Object.keys(c).forEach(d=>{b.variables.set(d,c[d])}),await b.execute(W),b.variables.clear()},format:async(Z,c,W=!0)=>{c&&Object.keys(c).forEach(N=>{b.variables.set(N,c[N])});let d=await new sl(I,G,b).formatFileContent(Z);return W&&b.variables.clear(),d},ai:{prompt:async(Z,c,W)=>{let d=M.getState(),N=d.ai;if(d.disableOnlineFeatures)throw new Error("Rejectingrequestto`prompt`viaAPIAImodule.Onlinefeaturesaredisabledinsettings.");let m=this.GetApi(I,G,b).format,Y;if(typeof c=="string"){let a=ml(c);if(!a)throw new Error(`Model '${c}' not found.`);Y=a}else Y=c;let V=fb(Y.name);if(!V)throw new Error(`Model '${Y.name}' not found in any provider`);let h=await Fa(I,{model:Y,prompt:Z,apiKey:V.apiKey,modelOptions:W?.modelOptions??{},outputVariableName:W?.variableName??"output",showAssistantMessag
`)}function pa(l){return l.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}var yl=class extends $Z{constructor(I,G,b,Z,c,W){super(I),this.choice=b,this.plugin=G,this.macros=Z,this.choiceExecutor=c,this.params={app:this.app,quickAddApi:_Z.GetApi(I,G,c),variables:{},obsidian:_H},W?.forEach((d,N)=>{this.params.variables[N]=d})}async run(){let I=this.choice.macroId??this.choice?.macro?.id,G=this.macros.find(b=>b.id===I);if(!G||!G?.commands){U.logError(`No commands in the selected macro. Did you select a macro for '${this.choice.name}'?`);return}await this.executeCommands(G.commands)}async executeCommands(I){for(let G of I)G?.type==="Obsidian"&&this.executeObsidianCommand(G),G?.type==="UserScript"&&await this.executeUserScript(G),G?.type==="Choice"&&await this.executeChoice(G),G?.type==="Wait"&&await Ha(G.time),G?.type==="NestedChoice"&&await this.executeNestedChoice(G),G?.type==="EditorCommand"&&await this.executeEditorCommand(G),G?.type==="AIAssistant"&&await this.executeAIAssistant(G),Object.keys(this.params.variables).forEach(b=>{this.choiceExecutor.variables.set(b,this.params.variables[b])})}async executeUserScript(I){let G=await sd(I,this.app);if(!G){U.logError(`failed to load user script ${I.path}.`);return}G.settings&&(this.userScriptCommand=I);try{await this.userScriptDelegator(G)}catch(b){wI(b,`Failed to run user script ${I.name}`)}this.userScriptCommand&&(this.userScriptCommand=null)}async runScriptWithSettings(I,G){if(typeof I!="function"&&I.entry&&typeof I.entry=="function")return await this.onExportIsFunction(I.entry,G.settings);if(typeof I=="function")return await this.onExportIsFunction(I,G.settings)}async userScriptDelegator(I){switch(typeof I){case"function":this.userScriptCommand?await this.runScriptWithSettings(I,this.userScriptCommand):await this.onExportIsFunction(I);break;case"object":await this.onExportIsObject(I);break;case"bigint":case"boolean":case"number":case"string":this.output=I.toString();break;default:U.logError(`user script in macro for '${this.choice.name}' is invalid`)}}async onExportIsFunction(I,G){this.output=await I(this.params,G||{})}async onExportIsObject(I){if(Object.keys(I).length===0)throw new Error(`user script in macro for '${this.choice.name}' is an empty object`);if(this.userScriptCommand&&I.entry!==null){await this.runScriptWithSettings(I,this.userScriptCommand);return}try{let G=Object.keys(I),b=await aG.Suggest(this.app,G,G);await this.userScriptDelegator(I[b])}catch(G){wI(G,"Errorinscriptobjecthandling","LOG")}}executeObsidianCommand(I){this.app.commands.executeCommandById(I.commandId)}async executeChoice(I){let G=this.plugin.getChoiceById(I.choiceId);if(!G){U.logError("choicecouldnotbefound.");return}await this.choiceExecutor.execute(G)}async executeNestedChoice(I){let G=I.choice;if(!G){U.logError(`choice in ${I.name} is invalid`);return}await this.choiceExecutor.execute(G)}async executeEditorCommand(I){switch(I.editorCommandType){case"Cut":await Ic.run(this.app);break;case"Copy":await lc.run(this.app);break;case"Paste":await bc.run(this.app);break;case"Selectactiveline":Zc.run(this.app);break;case"Selectlinkonactiveline":cc.run(this.app);break}}async executeAIAssistant(I){if(M.getState().disableOnlineFeatures)throw new Error("BlockingrequesttoOpenAI:Onlinefeaturesaredisabledinsettings.");let G=M.getState().ai,b=Jl(),Z=I.model==="Askme"?await aG.Suggest(this.app,b,b):I.model,c=ml(Z);if(!c)throw new Error(`Model ${Z} not found with any provider.`);let W=new sl(this.app,XI.instance,this.choiceExecutor),d=fb(c.name);if(!d)throw new Error(`Model ${c.name} not found in the AI providers settings.`);let N=await aa(this.app,{apiKey:d.apiKey,model:c,outputVariableName:I.outputVariableName,promptTemplate:I.promptTemplate,promptTemplateFolder:G.promptTemplatesFolderPath,systemPrompt:I.systemPrompt,showAssistantMessages:G.showAssistant,modelOptions:I.modelParameters},async m=>W.formatFileContent(m));for(let m in N)this.choiceExecutor.variables.set(m,N[m])}};var rd=class extends yl{constructor(I,G,b,Z,c){super(I,G,null,b,Z,c)}async runAndGetOutput(I){let{basename:G,me
Suggested values for ${b}: ${V.slice(0,3).join(",")}`)}return await yI.Prompt(this.app,`Enter value for ${b}`,Y)}let m=`Enter value for ${b}`;return N.hasDefaultValue&&(m=`Enter value for ${b} (default: ${Z.defaultValue})`),await el.Suggest(this.app,N.values,N.values,{placeholder:m})}generateCacheKey(G){let b=[];return G.folder&&b.push(`folder:${G.folder}`),G.tags&&b.push(`tags:${G.tags.join(",")}`),G.inline&&b.push("inline:true"),G.caseSensitive&&b.push("case-sensitive:true"),G.excludeFolders&&b.push(`exclude-folders:${G.excludeFolders.join(",")}`),G.excludeTags&&b.push(`exclude-tags:${G.excludeTags.join(",")}`),G.excludeFiles&&b.push(`exclude-files:${G.excludeFiles.join(",")}`),G.defaultValue&&b.push(`default:${G.defaultValue}`),G.defaultEmpty&&b.push("default-empty:true"),G.defaultAlways&&b.push("default-always:true"),b.join("|")}async getMacroValue(G){let b=new rd(this.app,this.plugin,this.plugin.settings.macros,this.choiceExecutor,this.variables),Z=await b.runAndGetOutput(G)??"";return Object.keys(b.params.variables).forEach(c=>{this.variables.set(c,b.params.variables[c])}),Z}async getTemplateContent(G){return await new Xb(this.app,this.plugin,G,this.choiceExecutor).run()}async getSelectedText(){let G=this.app.workspace.getActiveViewOfType(GR.MarkdownView);return G?G.editor.getSelection():""}async replaceInlineJavascriptInString(G){let b=G;for(;qc.test(b);){let c=qc.exec(b)?.at(1)?.trim();if(c){let W=new Od(this.app,this.plugin,this.choiceExecutor,this.variables),d=await W.runAndGetOutput(c);for(let N in W.params.variables)this.variables.set(N,W.params.variables[N]);b=typeof d=="string"?this.replacer(b,qc,d):this.replacer(b,qc,"")}}return b}async collectValuesManually(G,b){let Z=new Set,c=this.app.vault.getMarkdownFiles();c=FN.filterFiles(c,b,d=>this.app.metadataCache.getFileCache(d));let W=50;for(let d=0;d<c.length;d+=W){let m=c.slice(d,d+W).map(async V=>{let h=new Set;try{let X=this.app.metadataCache.getFileCache(V)?.frontmatter?.[G];if(X!=null){if(Array.isArray(X))X.forEach(H=>{let w=String(H).trim();w&&h.add(w)});else if(typeof X!="object"){let H=String(X).trim();H&&h.add(H)}}if(b.inline)try{let H=await this.app.vault.read(V);PZ.getFieldValues(H,G).forEach(u=>h.add(u))}catch(H){console.warn(`Could not read file ${V.path} for inline field parsing:`,H)}}catch(a){console.warn(`Could not process metadata for file ${V.path}:`,a)}return h}),Y=await Promise.all(m);for(let V of Y)for(let h of V)Z.add(h)}return Z}};var lR=require("obsidian");var Hc=class extends SZ{constructor(G,b,Z){super(G);this.plugin=b;this.templater=vd(G),this.formatter=new sl(G,b,Z)}async getOrCreateFolder(G){let b;if(G.length>1){if(b=await aG.Suggest(this.app,G,G),!b)throw new Error("Nofolderselected.")}else b=G[0];return b?await this.createFolder(b):b="",b}async getFormattedFilePath(G,b,Z){let c=await this.formatter.formatFileName(b,Z);return this.normalizeMarkdownFilePath(G,c)}getTemplateExtension(G){return Sc.test(G)?".canvas":".md"}normalizeTemplateFilePath(G,b,Z){let c=G?`${G}/`:"",W=this.getTemplateExtension(Z),d=b.replace(Tc,"").replace(Sc,"");return`${c}${d}${W}`}async incrementFileName(G){let b=Yd.exec(G),Z=b&&typeof b.at=="function"?b?.at(1):void 0,c=await this.app.vault.adapter.exists(G),W=G,d=Sc.test(G)?".canvas":".md";if(c&&Z){let m=parseInt(Z);if(!m)throw new Error("detectednumbersbutcouldn't get them.");W=W.replace(Yd,`${m+1}${d}`)}else c&&(W=W.replace(Yd,`1${d}`));return await this.app.vault.adapter.exists(W)&&(W=await this.incrementFileName(W)),W}async createFileWithTemplate(G,b){try{let Z=await this.getTemplateContent(b),c=await this.formatter.formatFileContent(Z),W=await this.createFileWithInput(G,c);return await jZ(this.app,W),W}catch(Z){return wI(Z,"Could not create file with template"),null}}async overwriteFileWithTemplate(G,b){try{let Z=await this.getTemplateContent(b),c=await this.formatter.formatFileContent(Z);return await this.app.vault.modify(G,c),await jZ(this.app,G),G}catch(Z){return wI(Z,"Could not overwrite file with template"),null}}async appendToFileWithTemplate(G,b,Z){try{let c=await this.getTemplateContent
${d}`:`${d}
${W}`;return await this.app.vault.modify(G,N),await jZ(this.app,G),G}catch(c){return wI(c,"Could not append to file with template"),null}}async getTemplateContent(G){let b=G;!Tc.test(G)&&!Sc.test(G)&&(b+=".md");let Z=this.app.vault.getAbstractFileByPath(b);if(!(Z instanceof lR.TFile))throw new Error(`Template file not found at path "${b}".`);return await this.app.vault.cachedRead(Z)}};var Xb=class extends Hc{constructor(G,b,Z,c){super(G,b,c);this.templatePath=Z}async run(){let G=await this.getTemplateContent(this.templatePath);return G||U.logError(`Template ${this.templatePath} not found.`),G=await this.formatter.formatFileContent(G),G}};var kG=class extends Vb{constructor(G,b){super();this.app=G;this.plugin=b}async format(G){let b=G;try{b=this.replaceDateInString(b),b=this.replaceTimeInString(b),b=await this.replaceValueInString(b),b=await this.replaceDateVariableInString(b),b=await this.replaceVariableInString(b),b=await this.replaceLinkToCurrentFileInString(b),b=await this.replaceMacrosInString(b),b=await this.replaceTemplateInString(b),b=await this.replaceFieldVarInString(b),b=this.replaceLinebreakInString(b)}catch{return G}return b}promptForValue(G){return G||"user input"}getVariableValue(G){return yd(G)}getCurrentFileLink(){return Ad(this.app.workspace.getActiveFile())}getNaturalLanguageDates(){return vl(this.app)}suggestForValue(G){return gd(G)}getMacroValue(G){return ed(G)}promptForMathValue(){return Promise.resolve("calculation_result")}promptForVariable(G){return Promise.resolve(Cd(G))}async getTemplateContent(G){try{return await new Xb(this.app,this.plugin,G,void 0).run()}catch{return`Template (not found): ${G}`}}async getSelectedText(){return"selected_text"}async suggestForField(G){return Promise.resolve(`${G}_field_value`)}async replaceDateVariableInString(G){let b=G;return b=b.replace(new RegExp(Mb.source,"gi"),(Z,c,W)=>{let d=c?.trim(),N=W?.trim();if(!d||!N)return Z;let m=new Date,Y;try{Y=tl.generate(N,m)}catch{Y=`[${N} format]`}return Y}),b}};var pc=class extends Yb{constructor(G,b,Z){super(G);this.plugin=Z;this.choice=b,this.display()}display(){this.containerEl.addClass("captureChoiceBuilder"),this.contentEl.empty(),this.addCenteredChoiceNameHeader(this.choice),this.addCapturedToSetting(),this.choice?.captureToActiveFile||(this.addCreateIfNotExistsSetting(),this.choice?.createFileIfItDoesntExist?.enabled&&this.addCreateWithTemplateSetting()),this.addTaskSetting(),this.addPrependSetting(),this.addAppendLinkSetting(),this.addInsertAfterSetting(),this.choice.captureToActiveFile||(this.addOpenFileSetting(),this.choice.openFile&&this.addOpenFileInNewTabSetting()),this.addFormatSetting()}addCapturedToSetting(){let G;new eI.Setting(this.contentEl).setName("Capture To").setDesc("File to capture to. Supports some format syntax.");let b=this.contentEl.createDiv("captureToContainer"),Z=b.createDiv("captureToActiveFileContainer"),c=Z.createEl("span");c.textContent="Capture to active file";let W=new eI.ToggleComponent(Z);if(W.setValue(this.choice?.captureToActiveFile),W.onChange(d=>{this.choice.captureToActiveFile=d,this.reload()}),!this.choice?.captureToActiveFile){let d=b.createDiv("captureToFileContainer"),N=d.createEl("span"),m=new DZ(this.app);(async()=>N.textContent=await m.format(this.choice.captureTo))();let Y=new eI.TextComponent(d);Y.setPlaceholder("File name format"),G=Y,Y.inputEl.style.width="100%",Y.inputEl.style.marginBottom="8px",Y.setValue(this.choice.captureTo).setDisabled(this.choice?.captureToActiveFile).onChange(async h=>{this.choice.captureTo=h,N.textContent=await m.format(h)});let V=[...this.app.vault.getMarkdownFiles().map(h=>h.path),...F2];new mG(this.app,G.inputEl,V,50)}}addPrependSetting(){new eI.Setting(this.contentEl).setName("Write to bottom of file").setDesc(`Put value at the bottom of the file - otherwise at the ${this.choice?.captureToActiveFile?"active cursor location":"top"}.`).addToggle(b=>{b.setValue(this.choice.prepend),b.onChange(Z=>{this.choice.prepend=Z,this.choice.prepend&&this.choice.insertAfter.enabled&&(this.choice.insertAfter.enabled=!1,this.reload())})})}addTaskSetting()
${v?"Deleting this choice will delete all ("+n.choices.length+") choices inside it!":""}
${y?"Deleting this choice will delete the macro associated with it!":""}
`)&&(y&&(G(9,Z=Z.filter(t=>t.id!==n.macroId)),W(Z)),G(0,b=b.filter(t=>hR(n.id,t))),N.removeCommandForChoice(n),c(b))}async function V(F){let{choice:n}=F.detail,y;if(n.type==="Multi"){y=n;let v=await yI.Prompt(d,`Rename ${n.name}`,"",n.name);if(!v)return;y.name=v}else{let v=H(n);if(!v)throw new Error("Invalid choice type");y=await v.waitForClose}y&&(G(0,b=b.map(v=>mV(v,y))),N.removeCommandForChoice(n),N.addCommandForChoice(y),c(b))}async function h(F){let{choice:n}=F.detail,y={...n,command:!n.command};y.command?N.addCommandForChoice(y):N.removeCommandForChoice(y),G(0,b=b.map(v=>mV(v,y))),c(b)}async function a(F){let{choice:n}=F.detail,y=X(n);G(0,b=[...b,y]),c(b)}function X(F){if(!f2(F))throw new Error("Invalid choice type");let n;switch(F.type){case"Template":n=new gb(`${F.name} (copy)`);break;case"Capture":n=new Ab(`${F.name} (copy)`);break;case"Macro":n=new xc(`${F.name} (copy)`);break;case"Multi":n=new Lb(`${F.name} (copy)`);break}return F.type!=="Multi"?Object.assign(n,q2(F,["id","name"])):n.choices=F.choices.map(y=>X(y)),n}function H(F){switch(F.type){case"Template":return new TZ(d,F,N);case"Capture":return new pc(d,F,N);case"Macro":return new wN(d,F,Z,M.getState().choices);case"Multi":default:break}}async function w(){let F=await new vN(d,N,Z,b).waitForClose;F&&(W(F),G(9,Z=F))}async function u(){let F=await new EN(d,M.getState().ai).waitForClose;F&&M.setState(n=>({...n,ai:F}))}function s(F){b=F,G(0,b)}let C=F=>c(F.detail.choices);return l.$$set=F=>{"choices"in F&&G(0,b=F.choices),"macros"in F&&G(9,Z=F.macros),"saveChoices"in F&&G(1,c=F.saveChoices),"saveMacros"in F&&G(10,W=F.saveMacros),"app"in F&&G(11,d=F.app),"plugin"in F&&G(12,N=F.plugin)},[b,c,m,Y,V,h,a,w,u,Z,W,d,N,s,C]}var YV=class extends RI{constructor(I){super(),pI(this,I,eu,yu,HI,{choices:0,macros:9,saveChoices:1,saveMacros:10,app:11,plugin:12},Ju)}},aR=YV;var Cu={name:"OpenAI",endpoint:"https://api.openai.com/v1",apiKey:"",models:[{name:"text-davinci-003",maxTokens:4096},{name:"gpt-3.5-turbo",maxTokens:4096},{name:"gpt-3.5-turbo-16k",maxTokens:16384},{name:"gpt-3.5-turbo-1106",maxTokens:16385},{name:"gpt-4",maxTokens:8192},{name:"gpt-4-32k",maxTokens:32768},{name:"gpt-4-1106-preview",maxTokens:128e3},{name:"gpt-4-turbo",maxTokens:128e3},{name:"gpt-4o",maxTokens:128e3},{name:"gpt-4o-mini",maxTokens:128e3}]},JN=[Cu];var id={choices:[],macros:[],inputPrompt:"single-line",devMode:!1,templateFolderPath:"",announceUpdates:!0,version:"0.0.0",disableOnlineFeatures:!0,enableRibbonIcon:!1,ai:{defaultModel:"Ask me",defaultSystemPrompt:'AsanAIassistantwithinObsidian,yourprimarygoalistohelpusersmanagetheirideasandknowledgemoreeffectively.FormatyourresponsesusingMarkdownsyntax.Pleaseusethe[[Obsidian]]linkformat.Youcanwritealiasesforthelinksbywriting[[Obsidian|thealiasafterthepipesymbol]].Tousemathematicalnotation,useLaTeXsyntax.LaTeXsyntaxforlargerequationsshouldbeonseparatelines,surroundedwithdoubledollarsigns($$).Youcanalsoinlinemathexpressionsbywrappingitin$symbols.Forexample,use$$w_{ij}^{ext{new}}:=w_{ij}^{ext{current}}+etacdotdelta_jcdotx_{ij}$$onaseparateline,butyoucanwrite"($eta$ = learning rate, $delta_j$ = error term, $x_{ij}$ = input)"inline.',promptTemplatesFolderPath:"",showAssistant:!0,providers:JN},migrations:{migrateToMacroIDFromEmbeddedMacro:!1,useQuickAddTemplateFolder:!1,incrementFileNameSettingMoveToDefaultBehavior:!1,mutualExclusionInsertAfterAndWriteToBottomOfFile:!1,setVersionAfterUpdateModalRelease:!1,addDefaultAIProviders:!1}},sN=class extends Rl.PluginSettingTab{constructor(I,G){super(I,G),this.plugin=G}display(){let{containerEl:I}=this;I.empty(),I.createEl("h2",{text:"QuickAdd Settings"}),this.addChoicesSetting(),this.addUseMultiLineInputPromptSetting(),this.addTemplateFolderPathSetting(),this.addAnnounceUpdatesSetting(),this.addDisableOnlineFeaturesSetting(),this.addEnableRibbonIconSetting()}addAnnounceUpdatesSetting(){let I=new Rl.Setting(this.containerEl);I.setName("Announce Updates"),I.setDesc("Display release notes when a new vers
`:""}${Z}`}if(this.choice.insertAfter.enabled)return await this.insertAfterHandler(Z);let W=this.file?this.getFrontmatterEndPosition(this.file):null;return W?this.insertTextAfterPositionInBody(Z,this.fileContent,W):`${Z}${this.fileContent}`}async formatContentOnly(G){let b=await super.formatFileContent(G);return b=this.replaceLinebreakInString(b),b.trim()===""?this.fileContent:b}async insertAfterHandler(G){let b=await this.format(this.choice.insertAfter.after),Z=new RegExp(`\\s*${pa(b.replace("\\n",""))}\\s*`),c=HY(this.fileContent),W=c.findIndex(N=>Z.test(N));if(W===-1){if(this.choice.insertAfter?.createIfNotFound)return await this.createInsertAfterIfNotFound(G);wI(new Error("Unable to find insert after line in file"),"Insert After Error")}if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");W=gN(c,W,!!this.choice.insertAfter.considerSubsections)??c.length-1}return this.insertTextAfterPositionInBody(G,this.fileContent,W)}async createInsertAfterIfNotFound(G){let Z=`${this.replaceLinebreakInString(await this.format(this.choice.insertAfter.after))}
${Z}`;if(this.choice.insertAfter?.createIfNotFoundLocation===hd)try{let c=this.app.workspace.getActiveViewOfType(QR.MarkdownView);if(!c)throw new Error("No active view.");let d=c.editor.getCursor().line;if(this.choice.insertAfter?.insertAtEnd){if(!this.file)throw new Error("Tried to get sections without file.");let m=HY(this.fileContent);d=gN(m,d,!!this.choice.insertAfter.considerSubsections)??m.length-1}return this.insertTextAfterPositionInBody(Z,this.fileContent,d)}catch(c){wI(c,`Unable to insert line '${this.choice.insertAfter.after}' at cursor position`)}}getFrontmatterEndPosition(G){let b=this.app.metadataCache.getFileCache(G);return!b||!b.frontmatter?(U.logMessage("could not get frontmatter. Maybe there isn'tany."),-1):b.frontmatterPosition?b.frontmatterPosition.end.line:-1}insertTextAfterPositionInBody(G,b,Z){if(Z===-1){let N=!this.choice.task;return`${G}${N?`
`:""}${b}`}let c=b.split(`
`),W=c.slice(0,Z+1).join(`
`),d=c.slice(Z+1).join(`
`);return`${W}
${G}${d}`}};var LN=class{isResolved(){return!this.hasConflicts}isConflicted(){return this.hasConflicts}},JW=class l extends LN{constructor(I,G,b){super(),this.left=I,this.base=G,this.right=b,this.hasConflicts=!0}static create(I){return new l(I.left,I.base,I.right)}apply(I){return l.create({left:I(this.left),base:I(this.base),right:I(this.right)})}},_G=class l extends LN{constructor(I){super(),this.hasConflicts=!1,this.result=I}combine(I){this.result=this.result.concat(I.result)}apply(I){return new l(I(this.result))}};var Pl=class l{constructor(I,G){this.left=I,this.right=G}static executeDiff(I,G){if(!I.push)throw new Error("Argumentisnotanarray");let b=l.diff(I,G);return new aV(I,G,b).convertToTypedOutput()}static diff(I,G){return new l(I,G).performDiff()}performDiff(){let I=this.identifyUniquePositions();I.sort((c,W)=>W[0]-c[0]);let[G,b]=this.findNextChange(),Z=new oN(G,b,[]);return I.forEach(c=>{Z=this.getDifferences(Z,c)}),Z.changeRanges}getDifferences(I,G){let[b,Z]=[I.leftChangePos,I.rightChangePos],[c,W]=G;if(c<b||W<Z)return I;{let[d,N,m,Y]=this.findPrevChange(b,Z,c-1,W-1),[V,h]=this.findNextChange(c+1,W+1),a=this.appendChangeRange(I.changeRanges,d,N,m,Y);return new oN(V,h,a)}}findNextChange(I=0,G=0){let b=this.left.slice(I)||[],Z=this.right.slice(G)||[],c=this.mismatchOffset(b,Z);return[I+c,G+c]}findPrevChange(I,G,b,Z){if(I>b||G>Z)return[I,b,G,Z];{let c=this.left.slice(I,b+1).reverse()||[],W=this.right.slice(G,Z+1).reverse()||[],d=this.mismatchOffset(c,W);return[I,b-d,G,Z-d]}}mismatchOffset(I,G){let b=Math.max(I.length,G.length);for(let Z=0;Z<b;Z++)if(I[Z]!==G[Z])return Z;return Math.min(I.length,G.length)}identifyUniquePositions(){let I=this.findUnique(this.left),G=this.findUnique(this.right),b=new Set(...I.keys()),Z=new Set(...G.keys()),W=[...new Set([...b].filter(d=>Z.has(d)))].map(d=>[I.get(d),G.get(d)]);return W.unshift([this.left.length,this.right.length]),W}findUnique(I){let G=new Map;I.forEach((Z,c)=>{G.set(Z,new hV(c,!G.has(Z)))});let b=new Map;for(let[Z,c]of G.entries())c.unique&&b.set(Z,c.pos);return b}appendChangeRange(I,G,b,Z,c){return G<=b&&Z<=c?I.push(new sW(ol.change,G+1,b+1,Z+1,c+1)):G<=b?I.push(new sW(ol.remove,G+1,b+1,Z+1,Z)):Z<=c&&I.push(new sW(ol.add,G+1,G,Z+1,c+1)),I}},hV=class{constructor(I,G){this.pos=I,this.unique=G}},wc=class{constructor(I,G){this.text=I,this.low=G}},aV=class{constructor(I,G,b){this.oldTextArray=I,this.newTextArray=G,this.chunks=b,this.oldText=[],this.newText=[]}convertToTypedOutput(){let I=new FV(0,0);return this.chunks.forEach(G=>{let[b,Z]=this.setTextNodeIndexes(G,I.oldIndex,I.newIndex),[c,W]=this.appendChanges(G,I.oldIndex+b,I.newIndex+Z);I.oldIndex=c,I.newIndex=W}),this.setTheRemainingTextNodeIndexes(I.oldIndex,I.newIndex),{oldText:this.oldText,newText:this.newText}}setTextNodeIndexes(I,G,b){let Z=0;for(;G+Z<I.leftLo-1;)this.oldText.push(new wc(this.oldTextArray[G+Z],b+Z)),Z+=1;let c=0;for(;b+c<I.rightLo-1;)this.newText.push(new wc(this.newTextArray[b+c],G+c)),c+=1;return[Z,c]}appendChanges(I,G,b){for(;G<=I.leftHi-1;)this.oldText.push(this.oldTextArray[G]),G+=1;for(;b<=I.rightHi-1;)this.newText.push(this.newTextArray[b]),b+=1;return[G,b]}setTheRemainingTextNodeIndexes(I,G){let b=0;for(;I+b<this.oldTextArray.length;)this.oldText.push(new wc(this.oldTextArray[I+b],G+b)),b+=1;for(;G+b<this.newTextArray.length;)this.newText.push(new wc(this.newTextArray[G+b],I+b)),b+=1}},FV=class{constructor(I,G){this.oldIndex=I,this.newIndex=G}},ol;(function(l){l.change="change",l.add="add",l.remove="remove"})(ol||(ol={}));var sW=class{constructor(I,G,b,Z,c){this.action=I,this.leftLo=G,this.leftHi=b,this.rightLo=Z,this.rightHi=c}},oN=class{constructor(I,G,b){this.leftChangePos=I,this.rightChangePos=G,this.changeRanges=b}};var kN=class l{constructor(I,G,b,Z,c){this.code=I,this.baseLo=G,this.baseHi=b,this.sideLo=Z,this.sideHi=c}static fromChangeRange(I){return new l(I.action,I.leftLo,I.leftHi,I.rightLo,I.rightHi)}},vc=class l{constructor(I,G,b){this.left=I,this.base=G,this.right=b}static executeDiff(I,G,b){return new l(I,G,b).getDifferences()}getDifferences(){let I=Pl.diff(this.base,t
`),G}async getFormattedPathToCaptureTo(G){if(G){let m=this.app.workspace.getActiveFile();return CG(m,"Cannot capture to active file - no active file."),m.path}let b=this.choice.captureTo,Z=await this.formatFilePath(b),c=Z.replace(/^\/$|\/\.md$|^\.md$/,""),W=c==="",d=W||P2(this.app,c),N=Z.startsWith("#");if(d)return this.selectFileInFolder(c,W);if(N){let m=Z.replace(/\.md$/,"");return this.selectFileWithTag(m)}return Z}async selectFileInFolder(G,b){let Z=G.endsWith("/")||b?G:`${G}/`,c=KZ(this.app,Z);CG(c.length>0,`Folder ${Z} is empty.`);let W=c.map(m=>m.path),d=await el.Suggest(this.app,W.map(m=>m.replace(Z,"")),W);CG(!!d&&d.length>0,"No file selected for capture.");let N=d.startsWith(`${Z}`)?d:`${Z}/${d}`;return await this.formatFilePath(N)}async selectFileWithTag(G){let b=G.startsWith("#")?G:`#${G}`,Z=_2(this.app,b);CG(Z.length>0,`No files with tag ${G}.`);let c=Z.map(d=>d.path),W=await el.Suggest(this.app,c,c);return CG(!!W&&W.length>0,"No file selected for capture."),await this.formatFilePath(W)}async onFileExists(G,b){let Z=this.getFileByPath(G);if(!Z)throw new Error("File not found");let c=await this.formatter.formatContentOnly(b),W=await this.app.vault.read(Z),d=await this.formatter.formatContentWithFile(c,this.choice,W,Z),N=await this.app.vault.read(Z),m=d;if(N!==W){let Y=uR(N,W,d);CG(!Y.isSuccess,()=>`The file ${G} has been modified since the last read.
QuickAdd will now revert to backup.`),l.settings=b}}l.saveSettings()}var eR=Ku;var tc=require("obsidian");async function Du(l,I,G){let b=await fetch(`https://api.github.com/repos/${l}/${I}/releases`),Z=await b.json();if(!b.ok&&"message"in Z||!Array.isArray(Z))throw new Error(`Failed to fetch releases: ${Z.message??"Unknownerror"}`);let c=Z.findIndex(W=>W.tag_name===G);if(c===-1)throw new Error(`Could not find release with tag ${G}`);return Z.slice(0,c).filter(W=>!W.draft&&!W.prerelease)}function Tu(l,I=1){let G=l.split(`
`)}var rN=class extends tc.Modal{constructor(I,G){super(I),this.previousVersion=G,this.releaseNotesPromise=Du("chhoumann","quickadd",G),this.releaseNotesPromise.then(b=>{if(this.releases=b,this.releases.length===0){this.close();return}this.display()}).catch(b=>{U.logError(`Failed to fetch release notes: ${b}`)})}onOpen(){let{contentEl:I}=this;I.empty(),I.createEl("h1",{text:"Fetchingreleasenotes..."})}onClose(){let{contentEl:I}=this;I.empty()}display(){let{contentEl:I}=this;I.empty(),I.classList.add("quickadd-update-modal-container");let G=`### New in QuickAdd v${this.releases[0].tag_name}
`,b="ThankyouforusingQuickAdd!Ifyouliketheplugin,pleaseconsidersupportingmebybuyingmeacoffee.Withyoursponsorship,I'll be able to contribute more to my existing projects, start new ones, and be more responsive to issues & feature requests.",Z='<divclass="quickadd-bmac-container"><ahref="https://www.buymeacoffee.com/chhoumann"target="_blank"><imgsrc="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"alt="Buy Me A Coffee"style="height: 40px !important;width: 144px !important;"></a></div>',c=I.createDiv("quickadd-update-modal"),W=this.releases.map(Y=>Y.body).join(`
${Tu(W)}`;tc.MarkdownRenderer.renderMarkdown(m,c,this.app.vault.getRoot().path,new tc.Component)}};var qI=require("obsidian");var ON=class extends qI.Modal{constructor(G,b){super(G);this.showAdvancedSettings=!1;this.settings=b,this.waitForClose=new Promise((Z,c)=>{this.rejectPromise=c,this.resolvePromise=Z}),this.open(),this.display()}get systemPromptTokenLength(){let G=ml(this.settings.model);return G?gG(this.settings.systemPrompt,G):Number.POSITIVE_INFINITY}display(){this.contentEl.empty();let G=this.contentEl.createEl("h2",{text:`${this.settings.name}Settings`});G.style.textAlign="center",G.style.cursor="pointer",G.style.userSelect="none",G.addEventListener("click",async()=>{try{let b=await yI.Prompt(this.app,"New name",this.settings.name,this.settings.name);b&&b!==this.settings.name&&(this.settings.name=b,this.reload())}catch{}}),this.addResultJoinerSetting(this.contentEl),this.addChunkSeparatorSetting(this.contentEl),this.addMaxTokensSetting(this.contentEl),this.addMergeChunksSetting(this.contentEl),this.addModelSetting(this.contentEl),this.addOutputVariableNameSetting(this.contentEl),this.addShowAdvancedSettingsToggle(this.contentEl),this.showAdvancedSettings&&(this.settings.modelParameters||(this.settings.modelParameters={}),this.addTemperatureSetting(this.contentEl),this.addTopPSetting(this.contentEl),this.addFrequencyPenaltySetting(this.contentEl),this.addPresencePenaltySetting(this.contentEl)),this.addSystemPromptSetting(this.contentEl)}reload(){this.contentEl.empty(),this.display()}addModelSetting(G){new qI.Setting(G).setName("Model").setDesc("The model the AI Assistant will use").addDropdown(b=>{let Z=Jl();for(let c of Z)b.addOption(c,c);b.addOption("Ask me","Ask me"),b.setValue(this.settings.model),b.onChange(c=>{this.settings.model=c,this.reload()})})}addOutputVariableNameSetting(G){new qI.Setting(G).setName("Output variable name").setDesc("The name of the variable used to store the AI Assistant output, i.e. {{value:output}}.").addText(b=>{b.setValue(this.settings.outputVariableName).onChange(Z=>{this.settings.outputVariableName=Z})})}addSystemPromptSetting(G){new qI.Setting(G).setName("System Prompt").setDesc("The system prompt for the AI Assistant");let b=this.contentEl.createEl("div"),Z=b.createEl("span");Z.style.color="var(--text-muted-color)",b.appendChild(Z);let c=new qI.TextAreaComponent(G);c.setValue(this.settings.systemPrompt).onChange(async m=>{this.settings.systemPrompt=m,d.innerText=await W.format(m),N()}),new pG(this.app,c.inputEl,XI.instance);let W=new kG(this.app,XI.instance);c.inputEl.style.width="100%",c.inputEl.style.height="100px",c.inputEl.style.minHeight="100px",c.inputEl.style.marginBottom="1em";let d=this.contentEl.createEl("span"),N=(0,qI.debounce)(()=>{Z.innerText=`Tokencount:${this.systemPromptTokenLength}`},50);N(),(async()=>d.innerText=await W.format(this.settings.systemPrompt??""))()}addShowAdvancedSettingsToggle(G){new qI.Setting(G).setName("Show advanced settings").setDesc("Show advanced settings such as temperature, top p, and frequency penalty.").addToggle(b=>{b.setValue(this.showAdvancedSettings),b.onChange(Z=>{this.showAdvancedSettings=Z,this.reload()})})}addTemperatureSetting(G){new qI.Setting(G).setName("Temperature").setDesc("Sampling temperature. Higher values like 0.8 makes the output more random, whereas lower values like 0.2 will make it more focused and deterministic. The default is 1.").addSlider(b=>{b.setLimits(0,1,.1),b.setDynamicTooltip(),b.setValue(this.settings.modelParameters.temperature??1),b.onChange(Z=>{this.settings.modelParameters.temperature=Z})})}addTopPSetting(G){new qI.Setting(G).setName("Top P").setDesc("Nucleus sampling - consider this an alternative to temperature. The model considers the results of the tokens with top_p probability mass. 0.1 means only tokens compromising the top 10% probability mass are considered. The default is 1.").addSlider(b=>{b.setLimits(0,1,.1),b.setDynamicTooltip(),b.setValue(this.settings.modelParameters.top_p??1),b.onChange(Z=>{this.settings.modelParameters.top_p=Z})})}addFrequencyPenaltySetting(G){new qI.Setting(